@wcag-checkr/ci 1.0.22 → 1.0.24

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.
@@ -1,2101 +0,0 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/parallel-tab-flow-DN_z0IGA.js","assets/crash-reporter-DAZnNefT.js","assets/preload-helper-D7HrI6pR.js","assets/diff-CECbooHD.js","assets/ai-usage-log-HdIilbbf.js"])))=>i.map(i=>d[i]);
2
- var as=Object.defineProperty;var ns=(e,t,a)=>t in e?as(e,t,{enumerable:!0,configurable:!0,writable:!0,value:a}):e[t]=a;var Wt=(e,t,a)=>ns(e,typeof t!="symbol"?t+"":t,a);import{_ as kn}from"./preload-helper-D7HrI6pR.js";import{c as Z,e as he,o as $e,k as H,h as xe,f as $t,j as tr}from"./crash-reporter-DAZnNefT.js";import{b as pe,m as Xn,d as os,T as rs,e as Qn,c as xn,g as ga,i as Zn}from"./diff-CECbooHD.js";import{i as is,j as Pe,J as ss,T as In,x as Nt,v as ma,z as ke,D as cs,e as nn,K as ls,L as ds,M as us,N as hs,O as ps,P as fs,W as gs,b as ms,g as bs,u as ys,r as ws,f as vs}from"./ai-usage-log-HdIilbbf.js";const on=(e,t)=>t.some(a=>e instanceof a);let eo,to;function As(){return eo||(eo=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function ks(){return to||(to=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])}const rn=new WeakMap,Fa=new WeakMap,ba=new WeakMap;function xs(e){const t=new Promise((a,n)=>{const o=()=>{e.removeEventListener("success",r),e.removeEventListener("error",i)},r=()=>{a(Qe(e.result)),o()},i=()=>{n(e.error),o()};e.addEventListener("success",r),e.addEventListener("error",i)});return ba.set(t,e),t}function Is(e){if(rn.has(e))return;const t=new Promise((a,n)=>{const o=()=>{e.removeEventListener("complete",r),e.removeEventListener("error",i),e.removeEventListener("abort",i)},r=()=>{a(),o()},i=()=>{n(e.error||new DOMException("AbortError","AbortError")),o()};e.addEventListener("complete",r),e.addEventListener("error",i),e.addEventListener("abort",i)});rn.set(e,t)}let sn={get(e,t,a){if(e instanceof IDBTransaction){if(t==="done")return rn.get(e);if(t==="store")return a.objectStoreNames[1]?void 0:a.objectStore(a.objectStoreNames[0])}return Qe(e[t])},set(e,t,a){return e[t]=a,!0},has(e,t){return e instanceof IDBTransaction&&(t==="done"||t==="store")?!0:t in e}};function ar(e){sn=e(sn)}function Ss(e){return ks().includes(e)?function(...t){return e.apply(cn(this),t),Qe(this.request)}:function(...t){return Qe(e.apply(cn(this),t))}}function Cs(e){return typeof e=="function"?Ss(e):(e instanceof IDBTransaction&&Is(e),on(e,As())?new Proxy(e,sn):e)}function Qe(e){if(e instanceof IDBRequest)return xs(e);if(Fa.has(e))return Fa.get(e);const t=Cs(e);return t!==e&&(Fa.set(e,t),ba.set(t,e)),t}const cn=e=>ba.get(e);function Sn(e,t,{blocked:a,upgrade:n,blocking:o,terminated:r}={}){const i=indexedDB.open(e,t),c=Qe(i);return n&&i.addEventListener("upgradeneeded",d=>{n(Qe(i.result),d.oldVersion,d.newVersion,Qe(i.transaction),d)}),a&&i.addEventListener("blocked",d=>a(d.oldVersion,d.newVersion,d)),c.then(d=>{r&&d.addEventListener("close",()=>r()),o&&d.addEventListener("versionchange",l=>o(l.oldVersion,l.newVersion,l))}).catch(()=>{}),c}const $s=["get","getKey","getAll","getAllKeys","count"],Ts=["put","add","delete","clear"],_a=new Map;function ao(e,t){if(!(e instanceof IDBDatabase&&!(t in e)&&typeof t=="string"))return;if(_a.get(t))return _a.get(t);const a=t.replace(/FromIndex$/,""),n=t!==a,o=Ts.includes(a);if(!(a in(n?IDBIndex:IDBObjectStore).prototype)||!(o||$s.includes(a)))return;const r=async function(i,...c){const d=this.transaction(i,o?"readwrite":"readonly");let l=d.store;return n&&(l=l.index(c.shift())),(await Promise.all([l[a](...c),o&&d.done]))[0]};return _a.set(t,r),r}ar(e=>({...e,get:(t,a,n)=>ao(t,a)||e.get(t,a,n),has:(t,a)=>!!ao(t,a)||e.has(t,a)}));const Es=["continue","continuePrimaryKey","advance"],no={},ln=new WeakMap,nr=new WeakMap,Rs={get(e,t){if(!Es.includes(t))return e[t];let a=no[t];return a||(a=no[t]=function(...n){ln.set(this,nr.get(this)[t](...n))}),a}};async function*Os(...e){let t=this;if(t instanceof IDBCursor||(t=await t.openCursor(...e)),!t)return;t=t;const a=new Proxy(t,Rs);for(nr.set(a,t),ba.set(a,cn(t));t;)yield a,t=await(ln.get(a)||t.continue()),ln.delete(a)}function oo(e,t){return t===Symbol.asyncIterator&&on(e,[IDBIndex,IDBObjectStore,IDBCursor])||t==="iterate"&&on(e,[IDBIndex,IDBObjectStore])}ar(e=>({...e,get(t,a,n){return oo(t,a)?Os:e.get(t,a,n)},has(t,a){return oo(t,a)||e.has(t,a)}}));const Ms="wcag-component-auditor",Ds=3;let rt=null;function ce(){return rt||(rt=Sn(Ms,Ds,{upgrade(e,t){if(t<1){const a=e.createObjectStore("baselines",{keyPath:"componentId"});a.createIndex("byUrl","snapshotMeta.url"),a.createIndex("byDate","lastUpdated");const n=e.createObjectStore("audit-history",{keyPath:"auditId",autoIncrement:!0});n.createIndex("byComponentId","componentId"),n.createIndex("byDate","runDate")}if(t<2&&e.createObjectStore("site-crawl-per-url",{keyPath:"slot"}),t<3){e.createObjectStore("scheduled-audits",{keyPath:"id"});const a=e.createObjectStore("scheduled-audit-results",{keyPath:"resultId",autoIncrement:!0});a.createIndex("byScheduleId","scheduleId"),a.createIndex("byRanAt","ranAt")}}})),rt}async function Ns(){rt&&(await rt).close(),rt=null}async function ya(e){return(await ce()).get("baselines",e)}async function Cn(e){await(await ce()).put("baselines",e)}async function or(e){await(await ce()).delete("baselines",e)}async function rr(){return(await ce()).getAll("baselines")}async function Ls(e){return(await ce()).getAllFromIndex("baselines","byUrl",e)}async function Ps(e){return(await ce()).add("audit-history",e)}async function Fs(e){return(await ce()).getAllFromIndex("audit-history","byComponentId",e)}async function ir(){return(await ce()).get("site-crawl-per-url","current")}async function sr(e){await(await ce()).put("site-crawl-per-url",{...e,slot:"current"})}async function $n(){await(await ce()).delete("site-crawl-per-url","current")}async function cr(){return(await ce()).getAll("scheduled-audits")}async function lr(e){return(await ce()).get("scheduled-audits",e)}async function Tn(e){await(await ce()).put("scheduled-audits",e)}async function _s(e){await(await ce()).delete("scheduled-audits",e)}async function dr(e){return(await ce()).add("scheduled-audit-results",e)}async function Us(e){return(await ce()).getAllFromIndex("scheduled-audit-results","byScheduleId",e)}async function Ws(){return(await ce()).getAll("scheduled-audit-results")}async function ur(e,t=50){const a=await ce(),n=await a.getAllFromIndex("scheduled-audit-results","byScheduleId",e);if(n.length<=t)return;n.sort((i,c)=>c.ranAt.localeCompare(i.ranAt));const o=n.slice(t),r=a.transaction("scheduled-audit-results","readwrite");for(const i of o)i.resultId!==void 0&&await r.store.delete(i.resultId);await r.done}async function Gs(e){const a=(await ce()).transaction("scheduled-audit-results","readwrite");let o=await a.store.index("byScheduleId").openCursor(IDBKeyRange.only(e));for(;o;)await o.delete(),o=await o.continue();await a.done}const Vs=Object.freeze(Object.defineProperty({__proto__:null,_resetDbForTesting:Ns,appendAuditHistory:Ps,appendScheduledAuditResult:dr,deleteBaseline:or,deleteScheduledAudit:_s,deleteScheduledAuditResultsForScheduleId:Gs,deleteSiteCrawlPerUrl:$n,getBaseline:ya,getDb:ce,getScheduledAudit:lr,getSiteCrawlPerUrl:ir,listAllScheduledAuditResults:Ws,listAuditHistoryForComponent:Fs,listBaselines:rr,listBaselinesByUrl:Ls,listScheduledAuditResultsByScheduleId:Us,listScheduledAudits:cr,pruneScheduledAuditResults:ur,putScheduledAudit:Tn,setBaseline:Cn,setSiteCrawlPerUrl:sr},Symbol.toStringTag,{value:"Module"})),Qt="siteCrawlReport";async function En(){var a;if(typeof chrome>"u"||!((a=chrome.storage)!=null&&a.local))return null;const t=(await chrome.storage.local.get([Qt]))[Qt];return t&&typeof t=="object"?t:null}async function hr(e){var t;if(!(typeof chrome>"u"||!((t=chrome.storage)!=null&&t.local))){if(e===null){await chrome.storage.local.remove([Qt]),await $n().catch(()=>{});return}await chrome.storage.local.set({[Qt]:e})}}async function Zt(){try{const e=await ir();return(e==null?void 0:e.perUrl)??null}catch{return null}}async function pr(e,t){if(e===null){await $n();return}await sr({startUrl:(t==null?void 0:t.startUrl)??"",finishedAt:(t==null?void 0:t.finishedAt)??new Date().toISOString(),perUrl:e})}const wp=Object.freeze(Object.defineProperty({__proto__:null,loadSiteCrawlPerUrlResults:Zt,loadSiteCrawlReport:En,saveSiteCrawlPerUrlResults:pr,saveSiteCrawlReport:hr},Symbol.toStringTag,{value:"Module"}));async function He(){return!1}function vp(e){return!1}const Lt="HEADLESS_BUILD_LOCKOUT",Ze="wcagcheckr is in private build phase. A team license is required for access. If you believe you should have access, contact cliff@locustware.com.";async function fr(){const e=await chrome.tabs.query({currentWindow:!0}),t=e.find(n=>n.active);if(t!=null&&t.id&&ro(t.url))return t.id;const a=e.find(n=>n.id&&ro(n.url));return(a==null?void 0:a.id)??null}function ro(e){return typeof e=="string"&&/^https?:\/\//.test(e)}const dn="rubricConfigCache",js=7*24*60*60*1e3;function Ap(e){const t=Date.now()-e.fetchedAt;return t>=js?"expired":t>=60*60*1e3?"stale":"fresh"}async function kp(){var a;if(typeof chrome>"u"||!((a=chrome.storage)!=null&&a.local))return null;const t=(await chrome.storage.local.get(dn))[dn];return!t||typeof t!="object"?null:t}async function xp(e){var t;typeof chrome>"u"||!((t=chrome.storage)!=null&&t.local)||await chrome.storage.local.set({[dn]:e})}let gr=null;function Ip(e){gr=e}function mr(){return gr}const un="acknowledgedFindings";async function wa(){var a;if(typeof chrome>"u"||!((a=chrome.storage)!=null&&a.local))return[];const t=(await chrome.storage.local.get([un]))[un];return Array.isArray(t)?t:[]}async function va(e){const t=await wa();return new Set(t.filter(a=>a.componentId===e).map(a=>a.matchKey))}async function Bs(e){const a=(await wa()).filter(n=>!(n.componentId===e.componentId&&n.matchKey===e.matchKey));a.push({...e,acknowledgedAt:new Date().toISOString()}),await br(a)}async function Hs(e,t){const n=(await wa()).filter(o=>!(o.componentId===e&&o.matchKey===t));await br(n)}async function br(e){var t;typeof chrome>"u"||!((t=chrome.storage)!=null&&t.local)||await chrome.storage.local.set({[un]:e})}const Sp=Object.freeze(Object.defineProperty({__proto__:null,acknowledgeFinding:Bs,loadAcknowledged:wa,loadAcknowledgedKeysForComponent:va,unacknowledgeFinding:Hs},Symbol.toStringTag,{value:"Module"})),qs=/:nth-(?:last-)?(?:child|of-type)\([^)]+\)/g,zs=/\[id="[^"]*"\]/g,Ks=/\[data-testid="[^"]*"\]/g,Ys=/#[\w-]*\d[\w-]*/g,Js=/\[href(?:[\^$*~|]?=("|')[^"']*\1)?\]/g,Xs=/\[aria-label(?:[\^$*~|]?=("|')[^"']*\1)?\]/g,Qs=new Set(["region","landmark-one-main","page-has-heading-one","landmark-no-duplicate-banner","landmark-no-duplicate-contentinfo","landmark-no-duplicate-main","landmark-main-is-top-level","landmark-banner-is-top-level","landmark-contentinfo-is-top-level","landmark-complementary-is-top-level","landmark-unique","bypass","document-title","html-has-lang","meta-viewport"]);function Zs(e){return e&&e.replace(qs,"").replace(zs,"").replace(Ks,"").replace(Ys,"").replace(Js,"").replace(Xs,"").replace(/\s+/g," ").trim()}function Fe(e,t){return Qs.has(e)?`${e}::__structural__`:`${e}::${Zs(t)}`}const io={minor:0,moderate:1,serious:2,critical:3};function yr(e){const t=new Map;for(const a of e){const n=Fe(a.ruleId,a.target.selector),o=t.get(n);if(!o){t.set(n,a);continue}(io[a.impact]??0)>(io[o.impact]??0)&&t.set(n,a)}return Array.from(t.values())}const wr=[{id:"contrast",label:"Color & contrast",axeRules:["color-contrast","color-contrast-enhanced","link-in-text-block"],igtWorkflowIds:["visual-indicators"]},{id:"alt-text",label:"Alt text",axeRules:["image-alt","input-image-alt","object-alt","svg-img-alt","area-alt","role-img-alt"],igtWorkflowIds:[]},{id:"forms",label:"Forms",axeRules:["label","select-name","aria-input-field-name","aria-toggle-field-name","form-field-multiple-labels","label-content-name-mismatch","autocomplete-valid","label-title-only","wcc-onfocus-context-change","wcc-oninput-context-change","wcc-cognitive-auth-challenge"],igtWorkflowIds:["forms"]},{id:"keyboard",label:"Keyboard",axeRules:["nested-interactive","tabindex","frame-focusable-content","no-focusable-content","focus-order-semantics","wcc-gesture-no-alternative","wcc-drag-no-alternative"],igtWorkflowIds:["keyboard","focus-management"]},{id:"tab-order",label:"Tab order",axeRules:[],igtWorkflowIds:[],verifiedByWorkflowIds:["keyboard"],heuristic:"tab-order"},{id:"screen-reader",label:"Screen reader / ARIA",axeRules:["aria-allowed-attr","aria-required-attr","aria-required-children","aria-required-parent","aria-roles","aria-valid-attr-value","aria-valid-attr","aria-hidden-body","aria-hidden-focus","button-name","input-button-name","link-name","frame-title","presentation-role-conflict","aria-allowed-role","aria-prohibited-attr","aria-text","aria-deprecated-role","aria-conditional-attr","aria-braille-equivalent","empty-button","empty-heading","empty-link"],igtWorkflowIds:["screen-reader"]},{id:"reading-order",label:"Reading order",axeRules:[],igtWorkflowIds:[],verifiedByWorkflowIds:["page-structure"],heuristic:"reading-order"},{id:"page-structure",label:"Page structure",axeRules:["heading-order","page-has-heading-one","landmark-one-main","landmark-no-duplicate-banner","landmark-no-duplicate-contentinfo","landmark-no-duplicate-main","region","bypass","empty-table-header","landmark-banner-is-top-level","landmark-complementary-is-top-level","landmark-contentinfo-is-top-level","landmark-main-is-top-level","landmark-unique"],igtWorkflowIds:["page-structure"]}];function Cp(e,t){const a=new Set;for(const n of t)n.wcagCriterion===e&&a.add(n.ruleId);if(a.size===0)return null;for(const n of wr)for(const o of n.axeRules)if(a.has(o))return n.id;return null}function ec(e){const t=wr.map(o=>ac(o,e)),a=tc(t.map(o=>o.letter)),n=t.filter(o=>o.letter==="D"||o.letter==="F");return{overallLetter:a,subGrades:t,warningAreas:n,isLawsuitRisk:n.length>0}}function tc(e){const t=e.filter(i=>i==="A").length,a=e.filter(i=>i==="C").length,n=e.filter(i=>i==="D").length,o=e.filter(i=>i==="F").length,r=e.length-t;return t===0&&n+o>a?"F":r===0?"A":r<=3?"B":r<=6?"C":"D"}function ac(e,t){const a=new Set(e.axeRules),n=t.violations.filter(N=>a.has(N.ruleId)),o=t.manualRuns.filter(N=>e.igtWorkflowIds.includes(N.workflowId)),r=e.igtWorkflowIds.map(N=>t.workflows.find(O=>O.id===N)).filter(N=>N!=null);let i=r.length>0;for(const N of r){const O=o.find(P=>P.workflowId===N.id);if((O?Object.keys(O.steps).length:0)!==N.steps.length){i=!1;break}}const c=o.some(N=>Object.keys(N.steps).length>0),d=e.verifiedByWorkflowIds??[],l=t.manualRuns.filter(N=>d.includes(N.workflowId)),p=d.map(N=>t.workflows.find(O=>O.id===N)).filter(N=>N!=null);let m=d.length>0&&p.length===d.length;for(const N of p){const O=l.find(P=>P.workflowId===N.id);if((O?Object.keys(O.steps).length:0)!==N.steps.length){m=!1;break}}let u=null;if(m)for(const N of l)N.completedAt&&(u===null||N.completedAt>u)&&(u=N.completedAt);const g=e.heuristic==="tab-order"?t.heuristicCounts.tabOrder??0:e.heuristic==="reading-order"?t.heuristicCounts.readingOrder??0:0,h=d[0]??e.igtWorkflowIds[0]??null,f=t.interactiveAuditVerdicts,w=[];f&&(e.id==="tab-order"&&f.focusOrder&&w.push({verdict:f.focusOrder,criterionId:"2.4.3"}),e.id==="keyboard"&&(f.keyboardTrap&&w.push({verdict:f.keyboardTrap,criterionId:"2.1.2"}),f.focusVisible&&w.push({verdict:f.focusVisible,criterionId:"2.4.7"})),e.id==="reading-order"&&f.readingOrder&&w.push({verdict:f.readingOrder,criterionId:"1.3.2"}),e.id==="contrast"&&f.nonTextContrast&&w.push({verdict:f.nonTextContrast,criterionId:"1.4.11"}));const b=w.some(N=>N.verdict==="fail");if(w.length>0&&w.every(N=>N.verdict==="pass")&&d.length>0&&!m)return{id:e.id,label:e.label,letter:"A",untested:!1,needsIgt:!1,igtCompleted:!1,verifiedByIgt:!1,verifiedAt:w.length>0?new Date().toISOString():null,suppressedHeuristicCount:g,primaryVerifierWorkflowId:h,counts:{critical:0,serious:0,moderate:0,minor:0},caps:{cappedAtC:!1,cappedAtB:!1},aiVerifiedCriteria:w.map(N=>N.criterionId)};if(m&&d.length>0)return{id:e.id,label:e.label,letter:"A",untested:!1,needsIgt:!1,igtCompleted:!0,verifiedByIgt:!0,verifiedAt:u,suppressedHeuristicCount:g,primaryVerifierWorkflowId:h,counts:{critical:0,serious:0,moderate:0,minor:0},caps:{cappedAtC:!1,cappedAtB:!1}};const v=e.axeRules.length>0||e.heuristic!=null,s=e.igtWorkflowIds.length>0;if(v?!t.auditRan:!c)return{id:e.id,label:e.label,letter:"F",untested:!0,needsIgt:s||d.length>0,igtCompleted:!1,verifiedByIgt:!1,verifiedAt:null,suppressedHeuristicCount:0,primaryVerifierWorkflowId:h,counts:{critical:0,serious:0,moderate:0,minor:0},caps:{cappedAtC:!1,cappedAtB:!1}};const $={critical:0,serious:0,moderate:0,minor:0},A=yr(n);for(const N of A)$[N.impact]++;const C=(t.aiResolvedFails??[]).filter(N=>a.has(N.ruleId));if(C.length>0){const N=new Set(A.map(O=>`${O.ruleId}::${O.target.selector}`));for(const O of C){const W=`${O.ruleId}::${O.selector}`;N.has(W)||(N.add(W),$[O.impact]++)}}const F=w.length>0&&w.some(N=>N.verdict==="pass"||N.verdict==="fail"),T=F?g:0;F||($.serious+=g),b&&($.serious+=w.filter(N=>N.verdict==="fail").length);for(const N of o){const O=r.find(W=>W.id===N.workflowId);if(O)for(const W of O.steps){const P=N.steps[W.id];(P==null?void 0:P.status)==="fail"&&(W.severity==="required"?$.serious++:$.moderate++)}}const I=$.critical>0,D=$.serious>0;let S;$.critical>=5?S="F":$.critical>=1?S="D":$.serious>=1?S="C":$.moderate>=1?S="B":S="A";const _=S!=="A"&&(s&&!i||d.length>0&&!m);return{id:e.id,label:e.label,letter:S,untested:!1,needsIgt:_,igtCompleted:i,verifiedByIgt:!1,verifiedAt:null,suppressedHeuristicCount:T,primaryVerifierWorkflowId:h,counts:$,caps:{cappedAtC:I,cappedAtB:D}}}const it="incompleteResolutions",so=2e3,co=600;function Rn(e,t,a){return`${e}::${t}::${a}`}function vr(e){return e.reasoning&&e.reasoning.length>co?{...e,reasoning:e.reasoning.slice(0,co-1)+"…"}:e}function nc(e){const t=Object.entries(e);if(t.length<=so)return e;const a=t.sort(([,n],[,o])=>{const r=Date.parse(n.resolvedAt)||0;return(Date.parse(o.resolvedAt)||0)-r});return Object.fromEntries(a.slice(0,so))}async function Aa(){try{const t=(await chrome.storage.local.get(it))[it];return t&&typeof t=="object"?t:{}}catch{return{}}}async function On(e){const t=nc(e);try{await chrome.storage.local.set({[it]:t})}catch(a){const n=Object.entries(t).sort(([,r],[,i])=>{const c=Date.parse(r.resolvedAt)||0;return(Date.parse(i.resolvedAt)||0)-c}),o=Object.fromEntries(n.slice(0,Math.floor(n.length/2)));try{await chrome.storage.local.set({[it]:o}),console.warn("[incomplete-resolutions] storage quota hit; pruned to",Object.keys(o).length,"entries",a)}catch(r){await chrome.storage.local.remove(it).catch(()=>{}),console.warn("[incomplete-resolutions] storage quota still exceeded after prune; wiped key",r)}}}async function De(e){const t=await Aa();t[Rn(e.pageUrl,e.ruleId,e.selector)]=vr(e),await On(t)}async function oc(e){if(e.length===0)return;const t=await Aa();for(const a of e)t[Rn(a.pageUrl,a.ruleId,a.selector)]=vr(a);await On(t)}async function Ar(){const e=await Aa();return Object.values(e)}async function ka(e){return(await Ar()).filter(a=>a.pageUrl===e)}async function rc(e,t,a){const n=await Aa();delete n[Rn(e,t,a)],await On(n)}async function ic(){await chrome.storage.local.remove(it)}function kr(e){if(!e.reasoning)return e;const t=e.reasoning.toLowerCase(),a=Gt(t,/verdict\s+corrected\s+to\s+pass|verdict:\s*pass\s+\(corrected\)/gi),n=Gt(t,/verdict\s+corrected\s+to\s+fail|verdict:\s*fail\s+\(corrected\)/gi);if(a>n&&a>=0)return{...e,verdict:"pass"};if(n>a&&n>=0)return{...e,verdict:"fail"};const o=Gt(t,/actually\s+passes|in\s+fact\s+passes|passes\s+aa/gi),r=Gt(t,/actually\s+fails|in\s+fact\s+fails|fails\s+aa/gi);return o<0&&r<0?e:o>r&&o/t.length>=.5?{...e,verdict:"pass"}:r>o&&r/t.length>=.5?{...e,verdict:"fail"}:e}function Gt(e,t){let a=-1;const n=t.flags.includes("g")?t.flags:t.flags+"g",o=new RegExp(t.source,n);let r;for(;(r=o.exec(e))!==null;)a=r.index,r.index===o.lastIndex&&o.lastIndex++;return a}function xr(e){if(e.ruleId!=="color-contrast"&&e.ruleId!=="color-contrast-enhanced"||!e.reasoning||e.verdict!=="fail")return e;const t=sc(e.reasoning);if(t.length<2)return e;const a=t[0],n=t[1];if(n.a<.999)return e;const o=a.a<.999?{r:Math.round(a.r*a.a+n.r*(1-a.a)),g:Math.round(a.g*a.a+n.g*(1-a.a)),b:Math.round(a.b*a.a+n.b*(1-a.a))}:{r:a.r,g:a.g,b:a.b},r=lc(o,{r:n.r,g:n.g,b:n.b}),i=cc(e.reasoning)??4.5;return r<i+.05?e:{...e,verdict:"pass",reasoning:`${e.reasoning}
3
-
4
- (rc.299 math-salvage: re-computed from cited rgb(${a.r},${a.g},${a.b}) on rgb(${n.r},${n.g},${n.b}) → ${r.toFixed(2)}:1 against threshold ${i}:1 → PASS. Original AI verdict was FAIL but its arithmetic appears wrong on this element. One-way salvage: only flips fail→pass, never pass→fail.)`}}function Ir(e,t){var n;const a=new Set;for(const o of t)for(const r of((n=o.axeRulesEvaluated)==null?void 0:n.incomplete)??[])for(const i of r.elements??[])a.add(`${r.ruleId}::${i.selector}`);return e.map(kr).map(xr).filter(o=>o.verdict==="fail"&&a.has(`${o.ruleId}::${o.selector}`)&&!/aria-hidden=["']true["']/.test(o.selector))}function sc(e){const t=/rgba?\(\s*([0-9.]+)[,\s]+([0-9.]+)[,\s]+([0-9.]+)(?:[,/\s]+([0-9.]+))?\s*\)/gi,a=[];let n;for(;(n=t.exec(e))!==null&&(a.push({r:Math.round(parseFloat(n[1])),g:Math.round(parseFloat(n[2])),b:Math.round(parseFloat(n[3])),a:n[4]!==void 0?parseFloat(n[4]):1}),!(a.length>=4)););return a}function cc(e){const t=/([34](?:\.\d+)?|7(?:\.\d+)?)\s*:\s*1/g,a=[];let n;for(;(n=t.exec(e))!==null;){const o=parseFloat(n[1]);(o===3||o===4.5||o===7)&&a.push(o)}return a.length>0?a[a.length-1]:null}function lc(e,t){const a=d=>{const l=d/255;return l<=.03928?l/12.92:Math.pow((l+.055)/1.055,2.4)},n=d=>.2126*a(d.r)+.7152*a(d.g)+.0722*a(d.b),o=n(e),r=n(t),i=Math.max(o,r),c=Math.min(o,r);return(i+.05)/(c+.05)}const dc=Object.freeze(Object.defineProperty({__proto__:null,applyContrastMathSalvage:xr,applySelfCorrectionSalvage:kr,clearAllResolutions:ic,deleteResolution:rc,filterRelevant:Ir,getAllResolutions:Ar,getResolutionsForPage:ka,saveResolution:De,saveResolutions:oc},Symbol.toStringTag,{value:"Module"})),Rt="interactiveAuditResults";function Mn(e,t){return`${e}::${t}`}async function Pt(){try{const t=(await chrome.storage.local.get(Rt))[Rt];return t&&typeof t=="object"?t:{}}catch{return{}}}async function Dn(e){await chrome.storage.local.set({[Rt]:e})}async function te(e){const t=await Pt(),a={componentId:e.componentId,criterionId:e.criterionId,verdict:e.verdict,reasoning:e.reasoning,confidence:e.confidence,pageUrl:e.pageUrl,finishedAt:e.finishedAt,costUsd:e.costUsd,model:e.model,inputHash:e.inputHash};t[Mn(e.componentId,e.criterionId)]=a,await Dn(t)}async function Ge(e,t){return(await Pt())[Mn(e,t)]??null}async function Sr(){const e=await Pt();return Object.values(e)}async function ea(e){return(await Sr()).filter(a=>a.componentId===e)}async function uc(e,t){const a=await Pt();delete a[Mn(e,t)],await Dn(a)}async function hc(){await chrome.storage.local.remove(Rt)}async function xa(e){const t=new Set;for(const n of e)n&&t.add(n);if(t.size===0)return[];const a=[];for(const n of t)try{const o=await ea(n);for(const r of o)a.push({criterionId:r.criterionId,ruleId:`ai-interactive::${r.criterionId}`,pageUrl:r.pageUrl,verdict:r.verdict,reasoning:r.reasoning})}catch{}return a}async function pc(){try{const e=await Pt();let t=!1;for(const a of Object.keys(e)){const n=e[a];if(n.steps&&n.steps.length>0){const o={componentId:n.componentId,criterionId:n.criterionId,verdict:n.verdict,reasoning:n.reasoning,confidence:n.confidence,pageUrl:n.pageUrl,finishedAt:n.finishedAt,costUsd:n.costUsd,model:n.model};e[a]=o,t=!0}}t&&await Dn(e)}catch{try{await chrome.storage.local.remove(Rt)}catch{}}}const $p=Object.freeze(Object.defineProperty({__proto__:null,clearAllInteractiveAuditResults:hc,getAllInteractiveAuditResults:Sr,getInteractiveAuditResult:Ge,getInteractiveAuditResultsForComponent:ea,loadInteractiveResultsForScoring:xa,migrateStrippedShape:pc,removeInteractiveAuditResult:uc,saveInteractiveAuditResult:te},Symbol.toStringTag,{value:"Module"})),fc=Z("walkthrough-acks"),hn="walkthroughAcks";function Nn(e,t,a){return`${e}::${t}::${a}`}async function Ia(){try{const t=(await chrome.storage.local.get(hn))[hn];return t&&typeof t=="object"?t:{}}catch{return{}}}async function Cr(e){await chrome.storage.local.set({[hn]:e})}async function Tp(e){if(!e.note||!e.note.trim())throw new Error("Acknowledgement requires a non-empty note explaining manual verification.");const t=await Ia();t[Nn(e.componentId,e.criterionId,e.pageUrl)]={...e,note:e.note.trim()},await Cr(t),fc.info(`acknowledged ${e.criterionId} on ${e.pageUrl}`)}async function Ep(e,t,a){const n=await Ia();delete n[Nn(e,t,a)],await Cr(n)}async function gc(e,t,a){return(await Ia())[Nn(e,t,a)]??null}async function mc(){const e=await Ia();return Object.values(e)}async function $r(e){const t=new Set;for(const n of e)n&&t.add(n);return t.size===0?[]:(await mc()).filter(n=>t.has(n.componentId))}const ta={A:4,B:3,C:2,D:1,F:0},bc=["F","D","C","B","A"];function yc(e,t){const a=(ta[e]+ta[t])/2,n=Math.ceil(a-.5);return bc[n]}function wc(e,t){return ta[e]<=ta[t]?e:t}const Ua=[{id:"contrast",label:"Color contrast",rules:["color-contrast","color-contrast-enhanced","link-in-text-block"],needsManualCheck:!1},{id:"alt",label:"Image alt text",rules:["image-alt","input-image-alt","area-alt","svg-img-alt","object-alt","role-img-alt"],needsManualCheck:!1},{id:"labels",label:"Form labels",rules:["label","select-name","aria-input-field-name","aria-toggle-field-name","form-field-multiple-labels","label-content-name-mismatch","autocomplete-valid"],needsManualCheck:!1},{id:"names",label:"Buttons / links named",rules:["button-name","input-button-name","link-name","empty-button","empty-heading","empty-link"],needsManualCheck:!1},{id:"keyboard",label:"Keyboard operability",rules:["nested-interactive","tabindex","frame-focusable-content","no-focusable-content"],needsManualCheck:!0},{id:"structure",label:"Landmarks + heading structure",rules:["heading-order","page-has-heading-one","landmark-one-main","landmark-no-duplicate-banner","landmark-no-duplicate-contentinfo","landmark-no-duplicate-main","region","bypass"],needsManualCheck:!1}];function vc(e){const t=new Map;for(const a of e){const n=`${a.ruleId}::${a.target.selector}`;t.has(n)||t.set(n,a)}return Array.from(t.values())}function Ac(e,t,a="2.1",n="AA",o,r,i,c,d){const l=is({audits:e??[],igtRuns:(t==null?void 0:t.runs)??[],workflows:(t==null?void 0:t.workflows)??Pe,acknowledgedMatchKeys:o??new Set,incompleteResolutions:r,interactiveAuditResults:i,auditScope:c,humanCriterionVerdicts:d}),p={},m={},u=[],g=[],h=[];let f=0;for(const b of l.values()){if(b.state==="not-evaluated"){u.push(b.criterionId);continue}if(f++,b.state==="fail"){h.push(b.criterionId);const k=[];for(const v of b.evidence)v.outcome==="fail"&&k.push({source:v.source,ruleOrStepId:v.ruleOrStepId,selector:v.selector,notes:v.notes,pageUrl:v.pageUrl});k.length>0&&(m[b.criterionId]=k)}if(b.state==="inconclusive"){g.push(b.criterionId);const k=[];for(const v of b.evidence)if(v.outcome==="incomplete"){const s=v.source==="ai"?"ai-uncertain":"axe-incomplete";k.push({source:s,ruleOrStepId:v.ruleOrStepId,resolutionHint:v.resolutionHint,elements:v.elements??(v.selector?[{selector:v.selector,failureSummary:v.resolutionHint}]:void 0),pageUrl:v.pageUrl})}else v.outcome==="skip"&&k.push({source:"igt-skip",ruleOrStepId:v.ruleOrStepId,resolutionHint:v.resolutionHint});k.length>0&&(p[b.criterionId]=k)}}const w=ss(l);return{targetVersion:Nt,targetLevel:In,totalApplicable:l.size,evaluated:f,untestedCriteria:u,inconclusiveCriteria:g,failingCriteria:h,inconclusiveReasons:p,failingReasons:m,canClaimConformance:w.canClaimConformance}}function Sa(e,t,a,n,o,r,i,c,d){const l=n??new Set,p=vc(e).filter(D=>!l.has(D.matchKey)),m=p.filter(D=>D.needsReview),u=p.filter(D=>!D.needsReview),g={critical:0,serious:0,moderate:0,minor:0,unique:u.length};for(const D of u)g[D.impact]++;let h;t&&(h=kc(t.runs,t.workflows),g.serious+=h.failedRequired,g.moderate+=h.failedAdvisory,g.unique+=h.failedRequired+h.failedAdvisory);const f=[],w=[];if(o&&o.length>0){const D=new Set;if(r)for(const _ of r)D.add(`${_.criterionId}::${_.pageUrl}`);const S=new Set;for(const _ of o){if(_.verdict==="pass")continue;const N=`${_.criterionId}::${_.pageUrl}`;if(S.has(N))continue;S.add(N);const O=_.verdict==="fail"?"serious":"moderate",W={criterionId:_.criterionId,pageUrl:_.pageUrl,verdict:_.verdict,impact:O,reasoning:_.reasoning};if(D.has(N)){w.push(W);continue}f.push(W),g[O]++,g.unique++}}const b=new Map;for(const D of Ua)for(const S of D.rules)b.set(S,D);const k=new Map;for(const D of Ua)k.set(D.id,{count:0,rules:new Set});for(const D of yr(u)){const S=b.get(D.ruleId);if(!S)continue;const _=k.get(S.id);_.count++,_.rules.add(D.ruleId)}const v=Ua.map(D=>{const S=k.get(D.id);let _="pass";return S.count>0?_="fail":D.needsManualCheck&&(_="unchecked"),{id:D.id,label:D.label,status:_,violationCount:S.count,rules:Array.from(S.rules),needsManualCheck:D.needsManualCheck}}),s=g.critical>0,x=g.serious>0,$=(()=>{if(!o||o.length===0||!r||r.length===0)return o;const D=new Set;for(const S of r)D.add(`${S.criterionId}::${S.pageUrl}`);return o.map(S=>D.has(`${S.criterionId}::${S.pageUrl}`)?{...S,verdict:"pass",reasoning:`Human verified: ${S.reasoning}`}:S)})(),A=a?Ac(a,t,"2.1","AA",n,d,$,c,i):void 0,C=A?!A.canClaimConformance:!1;let F;g.critical>=5?F="F":g.critical>=1?F="D":g.serious>=5||g.serious>=1?F="C":g.moderate>=3||g.moderate>=1?F="B":(g.minor>=1,F="A"),C&&F==="A"&&(F="B");const T=v.filter(D=>D.status==="fail").length;let I;return g.critical>0||T>=4?I="critical":g.serious>=3||T>=2?I="high":g.serious>=1||g.moderate>=3?I="moderate":I="low",{letter:F,risk:I,caps:{cappedAtC:s,cappedAtB:x,cappedAtBByCoverage:C},totals:g,categories:v,coverage:A,manual:h,reviewQueue:{count:m.length,rules:Array.from(new Set(m.map(D=>D.ruleId)))},walkthroughFindings:f,walkthroughAcknowledgements:w}}function kc(e,t){new Map(t.map(c=>[c.id,c]));const a=new Map(e.map(c=>[c.workflowId,c]));let n=0,o=0,r=0;const i=t.map(c=>{const d=a.get(c.id);let l=0,p=0,m=0,u=0,g=0;for(const h of c.steps){const f=d==null?void 0:d.steps[h.id];f&&(g++,f.status==="pass"?l++:f.status==="skip"?u++:f.status==="fail"&&(h.severity==="required"?p++:m++))}return g===c.steps.length&&r++,n+=p,o+=m,{workflowId:c.id,name:c.name,passed:l,failedRequired:p,failedAdvisory:m,skipped:u,answered:g,total:c.steps.length}});return{workflowsCompleted:r,workflowsTotal:t.length,failedRequired:n,failedAdvisory:o,perWorkflow:i}}const xc={low:"Low exposure — no critical or serious violations across the three layers (axe-core, wcagcheckr DOM analyzers, AI walkthroughs). All 50 WCAG 2.1 AA criteria have an evaluation path; spot-check content-meaning criteria (caption accuracy, alt-text correctness) before any formal conformance claim.",moderate:"Moderate exposure — some serious or multiple moderate violations. Should be addressed but not lawsuit-emergency level.",high:"High exposure — multiple serious violations OR multiple lawsuit-magnet categories failing. ADA Title III suits target sites at this level.",critical:"Critical exposure — at least one critical-impact violation OR most lawsuit-magnet categories failing. Sites in this state are demand-letter targets."},Tr={low:"✓ Off the radar",moderate:"⚡ Some lawsuit exposure",high:"⚠️ High target risk",critical:"🚨 Lawsuit magnet"},Er={low:"Your site clears the automated checks ADA-targeting tools use to identify lawsuit victims. wcagcheckr runs three layers (axe-core, our DOM analyzers, AI walkthroughs) covering all 50 WCAG 2.1 AA criteria — most demand-letter mills only run axe.",moderate:"Some failures. Not the easiest target, but the issues here are exactly what automated targeting tools look for. Switch to Developer mode for the issue list and fix-it walkthroughs.",high:"Multiple serious failures. Automated lawsuit-screening tools will flag this site. Real risk of being targeted with a demand letter — Developer mode has the full issue list and fix-it walkthroughs.",critical:"Your site fails the automated WCAG checks demand-letter mills run on thousands of sites to identify lawsuit targets. Without remediation, expect to be flagged. Developer mode has the full issue list plus fix-it guidance for each."},lo={A:"No critical, serious, or moderate violations across the three layers (axe-core, wcagcheckr DOM analyzers, AI walkthroughs). All 50 WCAG 2.1 AA criteria evaluated; content-meaning checks (caption accuracy, alt-text correctness, sensory cues) benefit from a human spot-check before formal conformance claims.",B:"Only moderate-impact violations detected. No serious or critical findings.",C:"Has at least one serious-impact violation. Automatically capped here regardless of how few.",D:"Has at least one critical-impact violation. Automatically capped here regardless of how few.",F:"Multiple critical-impact violations detected. Lawsuit-magnet profile."};function Rp(e,t){if(e!=="B")return lo[e];const{moderateCount:a,blockingCriteriaCount:n}=t;return n>0&&a===0?`No critical, serious, or moderate violations detected — but ${n} WCAG 2.1 AA criteri${n===1?"on has":"a have"} not yet been affirmatively evaluated (untested or inconclusive). The grade is capped at B until coverage is complete. Open the side panel's "Coverage gaps" panel under the grade and record a verdict for each.`:n>0&&a>0?`${a} moderate WCAG finding${a===1?"":"s"} detected, AND ${n} criteri${n===1?"on has":"a have"} not yet been affirmatively evaluated. Address both before any formal conformance claim.`:lo.B}const lt={"ai-alt-misleading":{summary:`The AI vision model judged this image's alt text is empty, misleading, or generic when the image is actually informative or functional. Use the AI assessment (shown above this recipe) to understand what the image depicts, then write descriptive alt text conveying its meaning to a screen-reader user. Use alt="" only when the image is genuinely decorative (a divider, a flourish, an icon next to text that already labels the action). Decorative is rare — when in doubt, describe.`,snippetLang:"html",snippet:`<!-- Failing — empty alt on an informational logo -->
5
- <img src="/assets/logo.png" alt="">
6
-
7
- <!-- Passing — descriptive alt -->
8
- <img src="/assets/logo.png" alt="Acme Corp logo">
9
-
10
- <!-- Decorative (rare) — empty alt + aria-hidden -->
11
- <img src="/divider.svg" alt="" aria-hidden="true">`},"ai-alt-uncertain":{summary:"The AI could not verify whether the existing alt text accurately matches the image (typically: a person's name on a portrait, a product SKU on a packshot — plausible but not provable from pixels). Surface this finding to a human content owner who knows the actual subject. Confirm or correct the alt. No code change needed if the alt is already accurate.",snippetLang:"html",snippet:`<!-- Example: AI sees a person, can't confirm identity -->
12
- <img src="/team/cliff.jpg" alt="Cliff C. - Founder of Locustware">
13
- <!-- Action: verify the named person matches the image. If yes, leave it. -->`},"ai-heading-not-descriptive":{summary:'WCAG 2.4.6 — Headings and labels must describe the topic or purpose of the section they introduce. The AI judged this heading is too generic ("More info", "Section 1", "Welcome") to convey what its section actually covers. Rewrite the heading to summarise the section content in a handful of words. Screen-reader users navigate by heading; vague headings make the page unscannable.',snippetLang:"html",snippet:`<!-- Failing -->
14
- <h2>More info</h2>
15
- <p>Our 2024 financial results show ...</p>
16
-
17
- <!-- Passing -->
18
- <h2>2024 financial results</h2>
19
- <p>Our 2024 financial results show ...</p>`},"ai-sensory-instruction":{summary:'WCAG 1.3.3 — Instructions must not rely solely on sensory characteristics (shape, size, colour, position, sound). "Click the round green button" excludes users who cannot perceive colour or shape. Add a programmatic identifier — visible text label, accessible name, or labelled reference — that does not depend on visual or auditory perception.',snippetLang:"html",snippet:`<!-- Failing -->
20
- <p>Click the green button on the right to proceed.</p>
21
-
22
- <!-- Passing -->
23
- <p>Click the <strong>"Proceed"</strong> button to continue.</p>`},"ai-aria-misuse":{summary:`WCAG 4.1.2 — ARIA role must match the element's actual behaviour. The AI judged this element uses an ARIA role that does not fit its DOM structure or behaviour. First rule of ARIA: don't use ARIA when a native element works. Prefer <button> over <div role="button">, <nav> over <div role="navigation">, etc. If the role IS appropriate, verify all required ARIA attributes (aria-expanded, aria-controls, aria-label, aria-selected, etc.) are present and accurate.`,snippetLang:"html",snippet:`<!-- Failing — div claims to be a button -->
24
- <div role="button" onclick="...">Submit</div>
25
-
26
- <!-- Passing — use the native element -->
27
- <button type="button" onclick="...">Submit</button>`},"ai-image-of-text":{summary:"WCAG 1.4.5 — Text rendered into a raster image (banner copy, infographic labels, social-share text, quote graphics) does not scale, does not respect user font preferences, can't reflow, and is only reachable via alt text. Replace with real HTML text styled to match the previous design. Exceptions: logos, brand wordmarks, and product photography where text is incidental.",snippetLang:"html",snippet:`<!-- Failing — text baked into image -->
28
- <img src="/banners/big-quote.png" alt="Customer testimonial: 'Best service ever.'">
29
-
30
- <!-- Passing — real text -->
31
- <figure class="testimonial">
32
- <blockquote>Best service ever.</blockquote>
33
- <figcaption>— a happy customer</figcaption>
34
- </figure>`},"ai-color-only-meaning":{summary:"WCAG 1.4.1 — Information conveyed by colour alone is invisible to users with colour-vision deficiency, monochrome displays, or low-contrast environments. Pair every colour signal with a redundant text label, icon, shape, or pattern. Status indicators, form validation, chart series, table-row highlights — wherever colour carries meaning, add a secondary cue.",snippetLang:"html",snippet:`<!-- Failing — status conveyed only by background colour -->
35
- <tr style="background:#fee">Failed run</tr>
36
- <tr style="background:#efe">Passed run</tr>
37
-
38
- <!-- Passing — colour + icon + text -->
39
- <tr><td>FAIL</td>...</tr>
40
- <tr><td>PASS</td>...</tr>`},"ai-generic-link-text":{summary:'WCAG 2.4.4 — Link purpose must be clear from the link text alone OR the link text plus its immediate surrounding context. "Click here", "Learn more", "Read this", and similarly vague text fail when a screen-reader user navigates a list of links out of context. Rewrite the link to describe its destination, ensure the surrounding sentence makes the destination unambiguous, or use aria-label / aria-labelledby to attach a descriptive name.',snippetLang:"html",snippet:`<!-- Failing — link text alone is meaningless -->
41
- <p>Our pricing has changed. <a href="/pricing">Click here</a>.</p>
42
-
43
- <!-- Passing — link text is self-describing -->
44
- <p>Our pricing has changed. <a href="/pricing">See our 2025 pricing tiers</a>.</p>`},"ai-wall-of-text":{summary:"WCAG 3.1.5 — Long unbroken prose with no scannable structure is exhausting to read and inaccessible to users with cognitive disabilities. Break the block into shorter paragraphs (aim for 50-150 words each), add a subheading every 2-4 paragraphs, convert lists-in-prose into actual <ul> / <ol>, and use plain language where possible.",snippetLang:"html",snippet:`<!-- Failing — one giant paragraph -->
45
- <p>Our process is straightforward we start by gathering requirements then we design the solution then we implement it then we test it then we deploy it then we support it ongoing ...</p>
46
-
47
- <!-- Passing — chunked with subheadings -->
48
- <h3>1. Requirements</h3>
49
- <p>We start by gathering your specifics.</p>
50
- <h3>2. Design</h3>
51
- <p>We map out the solution before writing code.</p>`},"ai-language-mismatch":{summary:`WCAG 3.1.1 / 3.1.2 — The page or passage's declared language attribute does not match the actual content language. Screen readers use the lang attribute to choose pronunciation rules; mismatch produces unintelligible speech. Either correct the <html lang=""> declaration to match the content, or add lang="" to any sub-passage that is in a different language than the page default.`,snippetLang:"html",snippet:`<!-- Failing — content is English but lang says French -->
52
- <html lang="fr"><body>...English content...</body></html>
53
-
54
- <!-- Passing — correct page-level declaration -->
55
- <html lang="en"><body>...English content...</body></html>
56
-
57
- <!-- Passing — passage-level override for non-default language -->
58
- <p>The German term is <span lang="de">Schadenfreude</span>.</p>`},"wcagcheckr-reflow":{summary:"WCAG 1.4.10 Reflow requires content to be presentable at 320 CSS pixels wide without requiring horizontal scrolling, except for data tables, code blocks, maps, and other intrinsically wide content. The usual culprits: fixed widths in px, hard-coded layout containers, white-space: nowrap on long text, large images without max-width, and horizontal scroll containers that exceed the viewport.",snippetLang:"css",snippet:`/* Failing: fixed-width container forces horizontal scroll at 320px */
59
- .container { width: 1024px; }
60
-
61
- /* Passing: use max-width and let content reflow */
62
- .container { max-width: 1024px; width: 100%; }
63
-
64
- /* Prevent images / media from forcing overflow */
65
- img, video, iframe { max-width: 100%; height: auto; }
66
-
67
- /* Avoid hard nowrap on long inline content */
68
- .long-string { overflow-wrap: anywhere; }`},"color-contrast":{summary:"Ensure foreground and background colors meet WCAG 2 AA contrast ratios: 4.5:1 for normal text, 3:1 for large text (18pt+ regular or 14pt+ bold). Check both default and interactive states (:hover, :focus) — a hover-only contrast failure is the most common regression.",snippetLang:"css",snippet:`/* Failing: light gray on white = 1.85:1 */
69
- .muted { color: #d3d3d3; }
70
-
71
- /* Passing: dark slate on white = 12.6:1 */
72
- .muted { color: #475569; }`},"image-alt":{summary:'Every <img> must have an alt attribute. Use empty alt="" for decorative images (the browser then announces nothing); use descriptive text for informative images.',snippetLang:"html",snippet:`<!-- Decorative -->
73
- <img src="divider.svg" alt="" />
74
-
75
- <!-- Informative -->
76
- <img src="chart.png" alt="Q3 revenue rose 42%" />`},"button-name":{summary:"Every <button> needs an accessible name. Provide visible text, an aria-label, or aria-labelledby. Icon-only buttons especially need aria-label so screen reader users hear what the button does.",snippetLang:"html",snippet:`<!-- GOOD: Visible text -->
77
- <button>Save changes</button>
78
-
79
- <!-- GOOD: Icon-only with aria-label -->
80
- <button aria-label="Close dialog">
81
- <svg aria-hidden="true">...</svg>
82
- </button>`},"link-name":{summary:'Links must have discernible text. Avoid empty <a> tags or links containing only an icon without an aria-label. "Read more" links should reference what they read more about via aria-label or surrounding context.',snippetLang:"html",snippet:`<!-- BAD: Generic -->
83
- <a href="/post/42">Read more</a>
84
-
85
- <!-- GOOD: Specific -->
86
- <a href="/post/42">Read more about Q3 revenue</a>
87
-
88
- <!-- GOOD: Or with aria-label -->
89
- <a href="/post/42" aria-label="Read more about Q3 revenue">Read more</a>`},"heading-order":{summary:"Don't skip heading levels. After an <h2>, the next heading should be <h2> or <h3> — never <h4>. Screen reader users navigate by heading level, and skipped levels imply missing structure.",snippetLang:"html",snippet:`<!-- BAD -->
90
- <h1>Page title</h1>
91
- <h3>Section</h3>
92
-
93
- <!-- GOOD -->
94
- <h1>Page title</h1>
95
- <h2>Section</h2>`},"landmark-one-main":{summary:`Every page should have exactly one <main> element (or one element with role="main"). It marks the start of the page's primary content for screen reader users.`,snippetLang:"html",snippet:`<body>
96
- <header>...</header>
97
- <main>
98
- <!-- primary content -->
99
- </main>
100
- <footer>...</footer>
101
- </body>`},"landmark-no-duplicate-banner":{summary:'A page should have at most one <header> at the top level (or one [role="banner"]). Multiple top-level banners confuse landmark navigation.'},"landmark-no-duplicate-contentinfo":{summary:'A page should have at most one <footer> at the top level (or one [role="contentinfo"]). Multiple top-level footers confuse landmark navigation.'},"aria-required-attr":{summary:'When using an ARIA role, you must include all required attributes for that role. For example, role="checkbox" requires aria-checked; role="combobox" requires aria-expanded.',snippetLang:"html",snippet:`<!-- BAD: Missing aria-checked -->
102
- <div role="checkbox">Subscribe</div>
103
-
104
- <!-- GOOD -->
105
- <div role="checkbox" aria-checked="false" tabindex="0">Subscribe</div>`},"aria-allowed-attr":{summary:"Some ARIA attributes only apply to specific roles. For example, aria-required is only valid on form widgets; putting it on a <div> with no role is wrong. Either remove the attribute or add the appropriate role."},"aria-roles":{summary:'The role attribute value must be a valid ARIA role from the WAI-ARIA spec. Common typos: "buton", "tab-list", "menuitem-radio". Check the WAI-ARIA spec for the exact role name.'},"aria-valid-attr":{summary:"Use ARIA attribute names exactly as specified in WAI-ARIA. Common typos: aria-labeledby (should be aria-labelledby with two L's), aria-describeby (should be aria-describedby)."},"duplicate-id":{summary:"IDs must be unique within a document. Duplicate IDs break label association, fragment navigation, and aria-labelledby/aria-describedby references."},"duplicate-id-aria":{summary:"IDs referenced by ARIA attributes (aria-labelledby, aria-describedby, aria-controls) must be unique. Duplicate IDs cause assistive tech to associate the wrong element."},"empty-button":{summary:"A button with no text and no aria-label has no name for screen readers. Add visible text or an aria-label describing what the button does."},"empty-heading":{summary:"Heading elements should contain text. An empty heading provides no information and confuses screen reader heading navigation. Either add text or remove the heading."},"empty-link":{summary:'A link with no text and no aria-label has no name. Screen reader users hear "link" with no destination cue. Add link text or aria-label.'},"form-field-multiple-labels":{summary:'A form field should have one label, not multiple. Multiple labels (e.g., wrapping <label> + separate <label for="">) confuse assistive tech about which is the canonical name.'},"html-has-lang":{summary:"The root <html> element needs a lang attribute so screen readers use the correct pronunciation rules.",snippetLang:"html",snippet:'<html lang="en">'},"html-lang-valid":{summary:`The lang attribute value must be a valid IANA language tag. Use "en" for English, "es" for Spanish, "fr-CA" for Canadian French, etc. Don't invent codes.`},"input-button-name":{summary:'Input elements with type="button", type="submit", or type="reset" must have an accessible name via the value attribute or aria-label.',snippetLang:"html",snippet:'<input type="submit" value="Save changes" />'},"input-image-alt":{summary:"Image-type inputs must have alt text describing the button's action.",snippetLang:"html",snippet:'<input type="image" src="search.png" alt="Search" />'},"meta-viewport":{summary:"Don't set user-scalable=no or maximum-scale less than 5.0 on the viewport meta. That blocks low-vision users from zooming.",snippetLang:"html",snippet:`<!-- GOOD: Allows zoom -->
106
- <meta name="viewport" content="width=device-width, initial-scale=1" />
107
-
108
- <!-- BAD: Blocks zoom -->
109
- <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no" />`},"nested-interactive":{summary:"Don't put interactive elements inside other interactive elements. A button inside a link, or a link inside a button, breaks keyboard activation and screen reader announcements."},"presentation-role-conflict":{summary:`role="presentation" or role="none" removes an element's semantics. Don't apply it to elements that have important interactive properties (focusable, named) — those will conflict and be ignored.`},"select-name":{summary:'Every <select> needs a programmatic label, just like <input> elements. Use <label for=""> or aria-label.'},"target-size":{summary:"Interactive targets must be at least 24×24 CSS px (WCAG 2.5.8 AA) or 44×44 (2.5.5 AAA). Small touch targets are hard to hit accurately, especially on mobile and for users with motor impairments. If the target itself can't be larger, ensure 24px of clear spacing between adjacent targets.",snippetLang:"css",snippet:`/* Pad the hit area without changing visual size */
110
- .icon-button {
111
- width: 24px;
112
- height: 24px;
113
- /* Ensures clickable area is 44×44 */
114
- padding: 10px;
115
- background-clip: content-box;
116
- }`},"valid-lang":{summary:'lang attribute values on individual elements (e.g., <span lang="es">) must be valid IANA language tags, just like the root html lang.'},"autocomplete-valid":{summary:'autocomplete attribute values must come from the WHATWG list. Common valid values: "name", "email", "tel", "current-password", "new-password", "street-address", "postal-code". Browsers and password managers rely on these to suggest the right values.'},"wcc-consistency-needs-site-crawl":{summary:`WCAG 3.2.3 Consistent Navigation + 3.2.4 Consistent Identification + 3.2.6 Consistent Help require that navigation, brand link, search, and help affordances appear in the SAME ORDER and with the SAME ACCESSIBLE NAME across every page where they appear. A single-page audit can't verify this — it only sees one page. To remediate:
117
-
118
- 1. Run the Site Crawl flow against a representative sample (≥ 5 pages covering the major templates: home, an interior page, a content page, a transactional page, a settings page). The crawler emits per-divergence findings naming exactly which element diverges and which pages disagree.
119
-
120
- 2. If divergences come back, fix them in the SHARED LAYOUT components (header, footer, navigation menu) — not page-by-page. Same JSX or partial = same DOM order across every page = the criterion clears for the whole site in one change.
121
-
122
- 3. If your site has truly different navigation per page-type (e.g., logged-in dashboard vs marketing site), document the role/template each nav serves and ensure WITHIN each role the nav is consistent. Per-template consistency satisfies 3.2.3 — the criterion isn't "every page identical," it's "every page where this set of items appears, they appear in the same order."
123
-
124
- False-positive cases (the ONLY legitimate reasons to skip): genuinely-different page types (login form vs main app), conditional nav based on auth/feature-flag (still consistent within each branch — verify both states), responsive mobile-vs-desktop nav variants (must be consistent within each breakpoint).`,snippetLang:"html",snippet:`<!-- Anti-pattern — same nav re-written per page, divergence likely -->
125
- <!-- pages/home.html -->
126
- <nav><a href="/">Home</a><a href="/about">About</a><a href="/contact">Contact</a></nav>
127
- <!-- pages/about.html -->
128
- <nav><a href="/">Home</a><a href="/contact">Contact</a><a href="/about">About</a></nav>
129
- <!-- ^^^ order changed -->
130
-
131
- <!-- Pattern — shared layout component, one source of truth -->
132
- <!-- components/SiteHeader.jsx -->
133
- export function SiteHeader() {
134
- return (
135
- <nav aria-label="Primary">
136
- <a href="/">Home</a>
137
- <a href="/about">About</a>
138
- <a href="/contact">Contact</a>
139
- </nav>
140
- );
141
- }
142
- <!-- Used on every page → DOM order is identical → 3.2.3 clears site-wide. -->`},"wcc-redundant-entry-needs-site-crawl":{summary:`WCAG 3.3.7 Redundant Entry (Level A, WCAG 2.2) requires that information the user has already provided in a multi-step process not be requested again — unless it's essential (re-entering a password for confirmation is allowed). A single-page audit can't verify this because the redundancy is across pages/steps. To remediate:
143
-
144
- 1. Identify every multi-step flow on the site (registration, checkout, multi-page forms, application wizards). For each: list the form fields requested on each step.
145
-
146
- 2. Look for fields that appear on Step N AND Step M (N ≠ M) with the same semantic meaning (email address, name, phone, address, etc.).
147
-
148
- 3. Fix by pre-filling the second occurrence from the first OR by making it auto-fill-friendly (correct autocomplete attributes + name attributes so the browser fills it).
149
-
150
- Allowed redundancy: password confirmation (essential), security challenges (essential), inputs where the user is correcting their own previously-entered value (the user is the cause, not the system). NOT allowed: re-typing the same email on a confirmation step, re-entering a shipping address that was already collected, re-typing a phone number from one step to the next.`,snippetLang:"html",snippet:`<!-- Step 1: collect contact info -->
151
- <input type="email" name="email" autocomplete="email" required>
152
- <input type="tel" name="phone" autocomplete="tel" required>
153
-
154
- <!-- Step 2 — REDUNDANT: asks for the same email again -->
155
- <!-- Anti-pattern -->
156
- <label>Confirm your email address</label>
157
- <input type="email" name="email_step2" required>
158
-
159
- <!-- Pattern — pre-fill from step 1, let user edit if needed -->
160
- <label>Email address (from previous step — edit if needed)</label>
161
- <input type="email" name="email" value="\${user.email}" autocomplete="email" required>`},"wcc-title-tooltip-no-persistence":{summary:"WCAG 1.4.13 Content on Hover or Focus requires that hover-revealed content be DISMISSIBLE (Esc closes it), HOVERABLE (the user can move the pointer over it without it disappearing), and PERSISTENT (it doesn't auto-hide after a timeout unless the user dismisses it). The native HTML `title` attribute fails all three on most browsers — the tooltip vanishes the moment the pointer moves. Replace `title` with a proper tooltip component (Radix UI, ARIA Authoring Practices popover pattern, or a `<details>` summary with visible label) that satisfies all three behaviors.",snippetLang:"html",snippet:`<!-- Failing — native title attribute -->
162
- <button title="Saves your work and exits the editor">Save & exit</button>
163
- <!-- The tooltip flashes briefly and disappears on pointer move. -->
164
-
165
- <!-- Passing — visible label as the primary affordance -->
166
- <button>
167
- Save & exit
168
- <span class="hint">Saves your work and exits the editor</span>
169
- </button>
170
-
171
- <!-- Passing — Radix tooltip (or any APG popover pattern) -->
172
- <Tooltip.Root>
173
- <Tooltip.Trigger asChild>
174
- <button aria-describedby="save-hint">Save & exit</button>
175
- </Tooltip.Trigger>
176
- <Tooltip.Content id="save-hint">
177
- Saves your work and exits the editor
178
- </Tooltip.Content>
179
- </Tooltip.Root>`},"wcc-reflow-horizontal-scroll":{summary:"WCAG 1.4.10 — Page produced horizontal scroll at narrow viewport (≤360 CSS pixels). The spec requires content to fit within 320px without two-dimensional scrolling. Common causes: fixed-width container exceeding viewport, images without max-width:100%, long unbroken strings (URLs, code identifiers), wide tables without overflow wrappers, third-party widgets ignoring container constraints. Fix: identify the offending element (DevTools at 320px viewport, find widest descendant), then apply max-width:100% (images/iframes), overflow-x:auto wrapper (tables/code blocks), overflow-wrap:anywhere (long strings), or responsive width (fixed-width containers). WCAG allows individual widgets that REQUIRE two-dimensional layout (maps, data viz, gantt charts) to scroll inside their own wrapper — the page itself must not.",snippet:`/* Common fixes */
180
- img, video, iframe { max-width: 100%; height: auto; }
181
- .wide-table-wrapper { overflow-x: auto; max-width: 100%; }
182
- pre { overflow-x: auto; }
183
- .long-url { overflow-wrap: anywhere; word-break: break-word; }
184
- .container { max-width: 1200px; width: 100%; margin: 0 auto; }`,snippetLang:"css"},label:{summary:'WCAG 1.3.1, 3.3.2 — Form control has no programmatically-determined label. Screen-reader users hear "edit, blank" instead of what to type. Fix: associate a `<label>` with the input via `for=` attribute pointing at the input\'s `id`, OR wrap the input inside the `<label>`, OR add `aria-label` / `aria-labelledby` when the label is visually elsewhere (modal title, table header). Avoid `placeholder=` as the only label — placeholders disappear on focus.',snippet:`<!-- Best: explicit label/for -->
185
- <label for="email">Email address</label>
186
- <input id="email" type="email">
187
-
188
- <!-- Acceptable: implicit (wrapped) label -->
189
- <label>
190
- Phone
191
- <input type="tel">
192
- </label>
193
-
194
- <!-- Acceptable when label is elsewhere -->
195
- <input type="search" aria-label="Search the catalog">`,snippetLang:"html"},"label-content-name-mismatch":{summary:`WCAG 2.5.3 — The control's accessible name (aria-label) does NOT contain its visible text. Speech-recognition users saying "click [visible text]" can't activate the control. Fix: ensure the accessible name STARTS WITH the visible text. If a longer description is needed, use aria-describedby for the additional info, OR set aria-label to "[visible-text] — [extra context]".`,snippet:`<!-- Failing -->
196
- <button aria-label="Close form">Cancel</button>
197
-
198
- <!-- Passing — visible text is contained in accessible name -->
199
- <button aria-label="Cancel — close the form">Cancel</button>
200
-
201
- <!-- Better: just remove the aria-label; visible text IS the name -->
202
- <button>Cancel</button>`,snippetLang:"html"},"label-title-only":{summary:"WCAG 1.3.1, 3.3.2 — Form control uses `title=` as its only label. Tooltips are inconsistent across browsers + screen readers + touch (no hover on mobile). Fix: replace with a visible `<label>` or, if no visible label is feasible, `aria-label`.",snippet:`<!-- Failing -->
203
- <input type="search" title="Search the catalog">
204
-
205
- <!-- Passing -->
206
- <label for="q">Search</label>
207
- <input id="q" type="search">`,snippetLang:"html"},"aria-required-children":{summary:'WCAG 1.3.1 — An ARIA role REQUIRES specific child roles, and one or more are missing. E.g., `role="list"` requires `role="listitem"` children; `role="tablist"` requires `role="tab"` children; `role="menu"` requires `role="menuitem"`. Fix: add the required child elements OR change the parent role to one that doesn\'t require those children OR remove the parent role entirely if native semantics (`<ul>`, `<select>`) already produce the right tree.',snippet:`<!-- Failing — role="list" without listitems -->
208
- <div role="list">
209
- <p>Item</p>
210
- </div>
211
-
212
- <!-- Passing — explicit listitem children -->
213
- <div role="list">
214
- <div role="listitem">Item</div>
215
- </div>
216
-
217
- <!-- Better: native -->
218
- <ul>
219
- <li>Item</li>
220
- </ul>`,snippetLang:"html"},"aria-required-parent":{summary:'WCAG 1.3.1 — Element with an ARIA role REQUIRES a specific parent role. E.g., `role="tab"` requires parent `role="tablist"`; `role="treeitem"` requires `role="tree"`; `role="menuitem"` requires `role="menu"` or `role="menubar"`. Fix: wrap the element in the correct parent role, OR remove the role from this element and use a different pattern.',snippet:`<!-- Failing — orphan tab -->
221
- <div role="tab">Tab 1</div>
222
-
223
- <!-- Passing — wrapped in tablist -->
224
- <div role="tablist">
225
- <div role="tab" aria-controls="panel-1">Tab 1</div>
226
- </div>`,snippetLang:"html"},"aria-valid-attr-value":{summary:'WCAG 4.1.2 — An ARIA attribute has an invalid value. Common: `aria-labelledby="non-existent-id"`, `aria-controls="missing"`, `aria-pressed="yes"` (must be true/false), `aria-expanded="undefined"`. Fix: ensure the value matches the spec for that attribute. Boolean attrs take `true`/`false`; ID-reference attrs require an element with that id to exist in the DOM.',snippet:`<!-- Failing -->
227
- <button aria-pressed="yes">Toggle</button>
228
- <button aria-labelledby="missing-id">Open</button>
229
-
230
- <!-- Passing -->
231
- <button aria-pressed="true">Toggle</button>
232
- <button aria-labelledby="dialog-title">Open</button>
233
- <h2 id="dialog-title">Settings</h2>`,snippetLang:"html"},"aria-hidden-focus":{summary:'WCAG 4.1.2 — Element with `aria-hidden="true"` contains focusable content. Screen-reader users can\'t see the element, but Tab still lands on its children — confusing + unusable. Fix: either remove the `aria-hidden`, OR add `tabindex="-1"` + `inert` to all focusable descendants, OR restructure so the hidden region has no focusable children.',snippet:`<!-- Failing -->
234
- <div aria-hidden="true">
235
- <button>Hidden button (Tab still lands here)</button>
236
- </div>
237
-
238
- <!-- Passing — inert blocks focus + click -->
239
- <div aria-hidden="true" inert>
240
- <button>Not reachable</button>
241
- </div>`,snippetLang:"html"},"aria-hidden-body":{summary:'WCAG 4.1.2 — The `<body>` element has `aria-hidden="true"`, hiding the entire page from assistive tech. Almost always a bug (often left over from modal-management code that forgot to restore). Fix: remove `aria-hidden` from `<body>`. If you need to hide page content behind a modal, use `inert` on the background or `aria-hidden="true"` only on the modal\'s sibling containers.',snippet:`<!-- Failing -->
242
- <body aria-hidden="true">...</body>
243
-
244
- <!-- Passing — modal pattern -->
245
- <body>
246
- <main inert>...</main>
247
- <div role="dialog" aria-modal="true">...</div>
248
- </body>`,snippetLang:"html"},"aria-allowed-role":{summary:'WCAG 4.1.2 — An element has a `role=` attribute that conflicts with its native semantics. E.g., `<button role="link">` (use `<a>` instead), `<h1 role="paragraph">` (semantic loss). Fix: remove the `role` attribute if the native semantics are correct, OR change the element type to match the desired role.',snippet:`<!-- Failing -->
249
- <button role="link">Go to home</button>
250
-
251
- <!-- Passing -->
252
- <a href="/">Go to home</a>
253
-
254
- <!-- Or: button styled to look like a link -->
255
- <button class="link-style" onclick="...">Action</button>`,snippetLang:"html"},"aria-prohibited-attr":{summary:'WCAG 4.1.2 — An ARIA attribute is used on an element that doesn\'t support it. E.g., `aria-label` on a `<span>` with no role, `aria-haspopup` on `<input type="text">`. Fix: either remove the prohibited attribute, OR add a role that allows it, OR change to an element that supports the attribute natively.',snippet:`<!-- Failing -->
256
- <span aria-label="Logo">XYZ</span>
257
-
258
- <!-- Passing -->
259
- <img src="logo.svg" alt="XYZ logo">
260
- <!-- or -->
261
- <div role="img" aria-label="XYZ logo">XYZ</div>`,snippetLang:"html"},region:{summary:'WCAG 1.3.1 — Content sits outside any landmark region. Screen-reader users can\'t skip to "main content" because no `<main>` (or `role="main"`) wraps it. Fix: wrap top-level page sections in landmark elements — `<header>`, `<nav>`, `<main>`, `<aside>`, `<footer>` — or their ARIA equivalents.',snippet:`<!-- Failing -->
262
- <body>
263
- <div class="header">...</div>
264
- <div class="content">...</div>
265
- </body>
266
-
267
- <!-- Passing -->
268
- <body>
269
- <header>...</header>
270
- <main>...</main>
271
- <footer>...</footer>
272
- </body>`,snippetLang:"html"},bypass:{summary:'WCAG 2.4.1 — Page lacks a "skip to main content" mechanism for keyboard users. Without it, every keyboard user re-tabs through the entire nav on every page. Fix: add a skip-link as the first focusable element. Use CSS to visually hide it until focused.',snippet:`<!-- HTML -->
273
- <a href="#main-content" class="skip-link">Skip to main content</a>
274
- <header>...</header>
275
- <main id="main-content">...</main>
276
-
277
- <!-- CSS -->
278
- .skip-link {
279
- position: absolute;
280
- left: -9999px;
281
- }
282
- .skip-link:focus {
283
- left: 0;
284
- top: 0;
285
- z-index: 999;
286
- padding: 0.5em 1em;
287
- background: #000;
288
- color: #fff;
289
- }`,snippetLang:"html"},"page-has-heading-one":{summary:"WCAG 1.3.1 — Page has no `<h1>`. Screen-reader users use the H1 to identify the page's primary topic + as a navigation anchor. Fix: add exactly ONE `<h1>` to the page describing its primary content (typically near the top of `<main>`). Don't use `<h1>` for the site name on every page — that belongs in `<header>` as a `<p>` or styled span.",snippet:`<!-- Failing — site name is the only H1 -->
290
- <header><h1>Acme Corp</h1></header>
291
- <main>
292
- <h2>Product details</h2>
293
- </main>
294
-
295
- <!-- Passing -->
296
- <header><a href="/"><img src="logo.svg" alt="Acme Corp"></a></header>
297
- <main>
298
- <h1>iPhone 15 Pro Max — 256GB</h1>
299
- </main>`,snippetLang:"html"},"landmark-unique":{summary:'WCAG 1.3.1 — Multiple landmarks of the same type with no distinguishing accessible name. Screen-reader users hear "navigation, navigation, navigation" with no way to tell them apart. Fix: add `aria-label` (or `aria-labelledby`) to each landmark with the same role, describing its purpose.',snippet:`<!-- Failing -->
300
- <nav>Primary nav</nav>
301
- <nav>Footer nav</nav>
302
-
303
- <!-- Passing -->
304
- <nav aria-label="Primary">...</nav>
305
- <nav aria-label="Footer">...</nav>`,snippetLang:"html"},tabindex:{summary:'WCAG 2.4.3 — Element has a positive `tabindex` value (e.g., `tabindex="1"`), creating a parallel focus order that\'s a maintenance nightmare + confuses users. Fix: use only `tabindex="0"` (to add to natural order) or `tabindex="-1"` (to make programmatically focusable but skipped by Tab). NEVER use positive values.',snippet:`<!-- Failing -->
306
- <button tabindex="1">First</button>
307
- <button tabindex="2">Second</button>
308
-
309
- <!-- Passing — natural DOM order -->
310
- <button>First</button>
311
- <button>Second</button>`,snippetLang:"html"},"focus-order-semantics":{summary:'WCAG 1.3.1, 2.4.3 — Element has `tabindex` making it focusable but has no role, so screen readers announce just "focusable, blank." Fix: either add a proper role (`role="button"`, `role="link"`, etc.) + Enter/Space handler, OR use the correct native element (`<button>`, `<a>`), OR remove the `tabindex` if the element shouldn\'t be focusable.',snippet:`<!-- Failing -->
312
- <div tabindex="0" onclick="open()">Open</div>
313
-
314
- <!-- Passing -->
315
- <button type="button" onclick="open()">Open</button>`,snippetLang:"html"},"no-focusable-content":{summary:'WCAG 2.1.1 — Element has an interactive ARIA role (`role="button"`, `role="link"`) but isn\'t focusable. Keyboard users can\'t reach it. Fix: add `tabindex="0"` AND a keyboard handler (Enter/Space → activate). Better: replace with a native interactive element.',snippet:`<!-- Failing -->
316
- <div role="button" onclick="run()">Run</div>
317
-
318
- <!-- Passing — tabindex + keyboard handler -->
319
- <div role="button" tabindex="0" onclick="run()" onkeydown="if(event.key==='Enter'||event.key===' '){event.preventDefault();run();}">Run</div>
320
-
321
- <!-- Best -->
322
- <button type="button" onclick="run()">Run</button>`,snippetLang:"html"},"frame-title":{summary:"WCAG 4.1.2, 2.4.1 — `<iframe>` or `<frame>` has no `title` attribute. Screen-reader users hear \"frame\" with no idea what's inside. Fix: add a descriptive `title` attribute summarizing the iframe's purpose.",snippet:`<!-- Failing -->
323
- <iframe src="https://maps.example.com/embed?location=hq"></iframe>
324
-
325
- <!-- Passing -->
326
- <iframe src="..." title="Map showing our headquarters location"></iframe>`,snippetLang:"html"},"area-alt":{summary:'WCAG 1.1.1 — Image map `<area>` element has no alt text. Screen-reader users hear "link" with no destination context. Fix: add an `alt=` attribute describing where the link goes / what region it represents.',snippet:`<!-- Failing -->
327
- <img src="map.png" usemap="#regions">
328
- <map name="regions">
329
- <area shape="rect" coords="0,0,100,100" href="/north">
330
- </map>
331
-
332
- <!-- Passing -->
333
- <map name="regions">
334
- <area shape="rect" coords="0,0,100,100" href="/north" alt="North region">
335
- </map>`,snippetLang:"html"},"object-alt":{summary:"WCAG 1.1.1 — `<object>` element has no fallback text. Screen readers (and browsers that can't render the object) have nothing to convey. Fix: include text content INSIDE the `<object>` describing what it represents — that text serves as the alt + the fallback.",snippet:`<!-- Failing -->
336
- <object data="chart.svg" type="image/svg+xml"></object>
337
-
338
- <!-- Passing -->
339
- <object data="chart.svg" type="image/svg+xml">
340
- Q4 revenue chart: $4.2M, up 18% YoY.
341
- </object>`,snippetLang:"html"},"svg-img-alt":{summary:'WCAG 1.1.1 — `<svg>` element with `role="img"` lacks an accessible name. Fix: add `<title>` as the FIRST child of the SVG (screen readers read it as the name), OR use `aria-label` / `aria-labelledby`.',snippet:`<!-- Failing -->
342
- <svg role="img"><path d="..."/></svg>
343
-
344
- <!-- Passing -->
345
- <svg role="img"><title>Search</title><path d="..."/></svg>
346
-
347
- <!-- Or -->
348
- <svg role="img" aria-label="Search"><path d="..."/></svg>
349
-
350
- <!-- Decorative SVG -->
351
- <svg aria-hidden="true"><path d="..."/></svg>`,snippetLang:"html"},"role-img-alt":{summary:'WCAG 1.1.1 — Element with `role="img"` lacks an accessible name. Without it, SR users hear "image, blank." Fix: add `aria-label` or `aria-labelledby` describing the image\'s content / function.',snippet:`<!-- Failing -->
352
- <div role="img">★★★★☆</div>
353
-
354
- <!-- Passing -->
355
- <div role="img" aria-label="Rated 4 out of 5 stars">★★★★☆</div>`,snippetLang:"html"},"color-contrast-enhanced":{summary:'WCAG 1.4.6 (AAA) — Text contrast is below the AAA threshold (7:1 for normal text, 4.5:1 for large text). AAA is the "enhanced" tier — fix by raising contrast to AAA OR explicitly declaring AA-only conformance (drop this rule from the audit). Same fix mechanics as `color-contrast` but with higher contrast thresholds.',snippet:`/* Same approach as color-contrast — raise foreground darkness or
356
- background lightness until the computed ratio meets 7:1 (or 4.5:1
357
- for text >=24px / 19px bold). */`,snippetLang:"css"},"link-in-text-block":{summary:"WCAG 1.4.1 — Inline link inside a paragraph is distinguished from surrounding text by color alone. Color-blind users can't see the difference. Fix: add a non-color affordance — underline (most common), bold weight, icon, or background color. Underline is the conventional choice and what browsers do by default.",snippet:`/* Failing — same family + color only */
358
- p { color: #333; }
359
- p a { color: #06f; text-decoration: none; }
360
-
361
- /* Passing — underline added */
362
- p a { color: #06f; text-decoration: underline; }`,snippetLang:"css"},"document-title":{summary:'WCAG 2.4.2 — The page has no non-empty <title>. Every page needs a unique, descriptive title that names the page first and the site second, e.g. "Checkout — Acme". It is the first thing a screen reader announces and what labels the browser tab/history.',snippetLang:"html",snippet:`<head>
363
- <title>Checkout — Acme</title>
364
- </head>`},list:{summary:`WCAG 1.3.1 — A <ul>/<ol> contains direct children that are not <li> (or wrapping elements that break the list semantics). Screen readers stop announcing "list, N items". Fix: make <li> the only direct child of the list; move other content inside an <li>, and ensure any wrappers (e.g. from a component library) use role="list"/role="listitem" if the tags can't change.`},listitem:{summary:'WCAG 1.3.1 — An <li> is not contained by a <ul>/<ol> (or a role="list" ancestor), so it loses its list semantics. Wrap the items in a proper list container, or add role="list" to the existing parent and role="listitem" to the items if the markup is fixed.'},"definition-list":{summary:"WCAG 1.3.1 — A <dl> is structured incorrectly: its direct children must be <dt>/<dd> (optionally grouped in <div>), in the right order. Remove stray elements and ensure every <dt> term is followed by one or more <dd> descriptions."},dlitem:{summary:"WCAG 1.3.1 — A <dt> or <dd> is not inside a <dl>. Wrap the term/description pairs in a <dl> so the definition-list relationship is exposed."},"th-has-data-cells":{summary:`WCAG 1.3.1 — A <th> header cell has no data cells associated with it, so the table's header/data relationship is broken. Ensure the table is a real data table with <td> cells under each header, give headers scope="col"/scope="row", and remove header cells used purely for layout.`,snippetLang:"html",snippet:`<table>
365
- <tr><th scope="col">Name</th><th scope="col">Email</th></tr>
366
- <tr><td>Ada</td><td>ada@x.com</td></tr>
367
- </table>`},"td-headers-attr":{summary:`WCAG 1.3.1 — A cell's headers="" attribute references ids that don't exist (or aren't header cells) in the same table. Fix the ids so each headers value points at the id of a real <th> in the same table, or switch to scope="col"/scope="row" for simple tables.`},"scope-attr-valid":{summary:"WCAG 1.3.1 — A scope attribute has an invalid value or is on a non-header element. scope is only valid on <th> and must be one of col, row, colgroup, or rowgroup."},"empty-table-header":{summary:"WCAG 1.3.1 — A table header cell is empty. Either give the <th> a meaningful label, or if the corner cell is intentionally blank, leave it as <td></td> rather than <th>."},"aria-command-name":{summary:'WCAG 4.1.2 — An element with role="button"/"link"/"menuitem" has no accessible name. Give it visible text content, or aria-label / aria-labelledby pointing at visible text. Native <button>/<a> with text is preferable to ARIA roles.'},"aria-input-field-name":{summary:'WCAG 4.1.2 — An ARIA input field (role="textbox", "combobox", "listbox", "searchbox", "slider", "spinbutton") has no accessible name. Associate a visible <label>, or use aria-label / aria-labelledby. A native <input> with a <label> is the robust choice.'},"aria-toggle-field-name":{summary:'WCAG 4.1.2 — An ARIA toggle field (role="checkbox", "radio", "switch", "menuitemcheckbox", "menuitemradio") has no accessible name. Label it with visible text via aria-labelledby, or aria-label when no visible text exists.'},"aria-dialog-name":{summary:`WCAG 4.1.2 — A role="dialog"/"alertdialog" has no accessible name, so screen-reader users don't hear what the dialog is for. Add aria-labelledby pointing at the dialog's heading element, or aria-label.`},"aria-meter-name":{summary:'WCAG 1.1.1 — A role="meter" has no accessible name. Add aria-label or aria-labelledby describing what the meter measures (e.g. "Disk usage").'},"aria-progressbar-name":{summary:'WCAG 1.1.1 — A role="progressbar" has no accessible name. Add aria-label or aria-labelledby describing what is in progress (e.g. "Upload progress").'},"aria-tooltip-name":{summary:'WCAG 4.1.2 — A role="tooltip" has no accessible name. Give the tooltip text content or aria-label so it is announced.'},"aria-treeitem-name":{summary:'WCAG 4.1.2 — A role="treeitem" has no accessible name. Provide visible text content, or aria-label / aria-labelledby.'},"aria-deprecated-role":{summary:'An ARIA role that has been deprecated is in use. Replace it with the current equivalent (e.g. role="directory" → role="list"). Prefer the native HTML element that conveys the same semantics.'},"aria-text":{summary:'WCAG 1.3.1 — role="text" is on an element that has focusable descendants, which is not allowed (role="text" flattens its subtree). Remove role="text", or remove the interactive/focusable children from inside it.'},"aria-roledescription":{summary:"WCAG 4.1.2 — aria-roledescription is used on an element whose role doesn't support it (it requires a non-abstract role with semantics). Put it on an element with a supporting role, and keep the custom description short and meaningful."},"meta-refresh":{summary:'WCAG 2.2.1 / 2.2.4 — <meta http-equiv="refresh"> auto-refreshes or redirects the page on a timer, which can trap or disorient users. Remove it; do redirects server-side (3xx) and let users control any timed updates.'},marquee:{summary:"WCAG 2.2.2 — The deprecated <marquee> element auto-scrolls content with no way to pause it. Remove <marquee>; if motion is truly needed, use CSS animation that respects prefers-reduced-motion and provide a pause control."},blink:{summary:"WCAG 2.2.2 — The deprecated <blink> element makes content blink with no stop control. Remove it entirely; blinking text is a usability and seizure concern."},"video-caption":{summary:'WCAG 1.2.2 — A <video> has no captions track. Add a <track kind="captions"> (or "subtitles") with synchronized caption text for all meaningful audio so deaf/hard-of-hearing users get the dialogue and important sounds.',snippetLang:"html",snippet:`<video controls>
368
- <source src="talk.mp4" type="video/mp4">
369
- <track kind="captions" src="talk.en.vtt" srclang="en" label="English">
370
- </video>`},"no-autoplay-audio":{summary:"WCAG 1.4.2 — Audio (or video with audio) plays automatically for more than 3 seconds with no built-in control to pause/stop or mute it. Remove autoplay, or provide an obvious, keyboard-operable pause/mute control near the start of the page."},"scrollable-region-focusable":{summary:`WCAG 2.1.1 — A scrollable region (overflow content) can't be reached or scrolled by keyboard. Make the container focusable with tabindex="0" (and an accessible name) so keyboard users can scroll it, or ensure a focusable child sits inside it.`},"server-side-image-map":{summary:"WCAG 2.1.1 — A server-side image map (<img ismap>) can only be used with a pointer. Replace it with a client-side image map (<map>/<area> with alt text) or, better, real <a> links so keyboard users can operate it."},accesskeys:{summary:"WCAG 4.1.1 — Two elements share the same accesskey value, so the shortcut is ambiguous. Make every accesskey unique, or remove them — accesskeys frequently collide with browser/AT shortcuts and are rarely worth keeping."},"css-orientation-lock":{summary:"WCAG 1.3.4 — CSS (a transform/orientation media query) locks content to a single orientation. Remove the lock so the page works in both portrait and landscape; users with fixed-mount devices depend on this."},"avoid-inline-spacing":{summary:'WCAG 1.4.12 — Inline style="" forces line-height, letter-spacing, or word-spacing with !important, preventing users from overriding text spacing. Move spacing to a stylesheet without !important so the text-spacing bookmarklet/user styles can adjust it.'},"summary-name":{summary:"WCAG 4.1.2 — A <summary> (disclosure control) has no accessible name. Give it visible text describing what it expands."},"frame-title-unique":{summary:"WCAG 4.1.2 — Multiple frames share the same title, so users can't tell them apart. Give each <iframe>/<frame> a unique, descriptive title naming its specific content."},"frame-focusable-content":{summary:'WCAG 2.1.1 — An <iframe> with tabindex="-1" contains focusable elements, creating a keyboard trap / unreachable content. Remove tabindex="-1" from the frame, or make the embedded content non-focusable.'}};function Op(e){return lt[e]??null}const Ic=new Set(["region","landmark-complementary-is-top-level","landmark-banner-is-top-level","landmark-contentinfo-is-top-level","landmark-main-is-top-level","link-in-text-block","scrollable-region-focusable","label-content-name-mismatch","identical-links-same-purpose"]);function Sc(e){if(e.needsReview)return{level:"needs-review",label:"Needs human confirmation",rationale:"Automation could not decide this either way — confirm against the live page before treating it as a defect."};if(e.ai){const t=Math.round((e.ai.confidence??0)*100);return{level:"ai-verified",label:`AI-verified (${t}%)`,rationale:t>=80?"A vision/text model judged this with high confidence (reasoning shown above).":"A model flagged this with moderate confidence — sanity-check its reasoning above before applying."}}return e.flakyAcrossRuns?{level:"medium",label:"Medium",rationale:"This did not reproduce in every audit run — it may be a transient (animation, lazy load, third-party script). Confirm it on a stable render before fixing."}:e.target.opacityContext&&(e.target.opacityContext.self<1||e.target.opacityContext.ancestor<1)?{level:"medium",label:"Medium",rationale:"The element (or an ancestor) was partially transparent at audit time — likely a mid-animation opacity, not a real color choice. Verify it is still low-contrast once fully rendered before changing colors."}:Ic.has(e.ruleId)?{level:"medium",label:"Medium",rationale:"This is a context-dependent best-practice check that can over-flag legitimate patterns. Apply the fix, but first confirm the flagged element genuinely fits the rule."}:{level:"high",label:"High",rationale:""}}function Rr(e){const t=Sc(e);return t.rationale?`**Confidence:** ${t.label} — ${t.rationale}`:`**Confidence:** ${t.label}`}const pn="aiColorSuggestions";async function Ca(){try{const t=(await chrome.storage.local.get(pn))[pn];return t&&typeof t=="object"?t:{}}catch{return{}}}async function Or(e){await chrome.storage.local.set({[pn]:e})}async function Mp(e){const t=await Ca();t[e.matchKey]=e,await Or(t)}async function Dp(e){if(e.length===0)return;const t=await Ca();for(const a of e)t[a.matchKey]=a;await Or(t)}async function Np(e){return(await Ca())[e]??null}async function Cc(){return await Ca()}const Mr={AT:{name:"Austria — Beschwerdestelle Bundessozialamt",url:"https://www.sozialministeriumservice.at/"},BE:{name:"Belgium — Unia / Bosa",url:"https://accessibility.belgium.be/"},BG:{name:"Bulgaria — State e-Government Agency",url:"https://e-gov.bg/"},CY:{name:"Cyprus — Department of Electronic Communications",url:"https://www.mtcw.gov.cy/"},CZ:{name:"Czechia — Ministry of the Interior",url:"https://www.mvcr.cz/"},DE:{name:"Germany — Bundesfachstelle Barrierefreiheit",url:"https://www.bundesfachstelle-barrierefreiheit.de/"},DK:{name:"Denmark — Digitaliseringsstyrelsen",url:"https://www.digst.dk/"},EE:{name:"Estonia — Ministry of Economic Affairs and Communications",url:"https://mkm.ee/"},ES:{name:"Spain — Observatorio de Accesibilidad Web",url:"https://administracionelectronica.gob.es/"},FI:{name:"Finland — Etelä-Suomen aluehallintovirasto",url:"https://www.saavutettavuusvaatimukset.fi/"},FR:{name:"France — Défenseur des droits",url:"https://www.defenseurdesdroits.fr/"},GR:{name:"Greece — Ministry of Digital Governance",url:"https://mindigital.gr/"},HR:{name:"Croatia — Information Commissioner",url:"https://www.pristupinfo.hr/"},HU:{name:"Hungary — Information Society Authority",url:"https://nmhh.hu/"},IE:{name:"Ireland — National Disability Authority",url:"https://nda.ie/"},IT:{name:"Italy — Agenzia per l'Italia Digitale",url:"https://www.agid.gov.it/"},LT:{name:"Lithuania — Information Society Development Committee",url:"https://ivpk.lrv.lt/"},LU:{name:"Luxembourg — Service Information et Presse",url:"https://accessibilite.public.lu/"},LV:{name:"Latvia — VARAM",url:"https://www.varam.gov.lv/"},MT:{name:"Malta — MITA",url:"https://www.mita.gov.mt/"},NL:{name:"Netherlands — Logius",url:"https://www.digitoegankelijk.nl/"},PL:{name:"Poland — Ministry of Digital Affairs",url:"https://www.gov.pl/web/dostepnosc-cyfrowa/"},PT:{name:"Portugal — AMA",url:"https://accessmonitor.acessibilidade.gov.pt/"},RO:{name:"Romania — ANCOM",url:"https://www.ancom.ro/"},SE:{name:"Sweden — DIGG",url:"https://www.digg.se/"},SI:{name:"Slovenia — Ministry of Public Administration",url:"https://www.gov.si/"},SK:{name:"Slovakia — Ministry of Investments",url:"https://www.mirri.gov.sk/"}},Dr=(e,t)=>`${e} is committed to making its website accessible, in accordance with national legislation transposing Directive (EU) 2016/2102 of the European Parliament and of the Council. This accessibility statement applies to ${t}.`,Nr=(e,t)=>`${e} is committed to making its products and services accessible to all users, in accordance with the European Accessibility Act (Directive (EU) 2019/882) and its national transpositions, enforceable from 28 June 2025. This accessibility statement applies to ${t}.`,Lr=(e,t,a,n="EN 301 549 v3.2.1")=>{const o=`Web Content Accessibility Guidelines (WCAG) ${t} level ${a}`;switch(e){case"full":return`This website is fully conformant with ${o} and the corresponding ${n} clauses.`;case"partial":return`This website is partially conformant with ${o} and the corresponding ${n} clauses. "Partially conformant" means that some parts of the content do not fully conform to the accessibility standard. The non-accessible content is listed below.`;case"non-conformant":return`This website is currently NOT conformant with ${o}. The non-accessible content is listed below, along with our plan to address it.`}},Pr=(e,t)=>`The accessibility of this website was last evaluated on ${t}. The evaluation was conducted by ${e} using automated testing (wcagcheckr — multi-state matrix audit across 144 keyboard / focus / theme / breakpoint / direction combinations, AI-augmented walkthroughs for 5 criteria axe-core cannot evaluate, plus DOM-criterion analyzers for 16 additional criteria). The audit is conformant with the EN 301 549 evaluation methodology.`;function $c(e,t){const a=e.language||"English",n=e.auditedBy||"wcagcheckr (self-evaluation)",o=e.wcagVersion||"2.1",r=e.wcagLevel||"AA",i=[];if(i.push(`# Accessibility Statement — ${e.organizationName}`),i.push(""),i.push(`*Statement prepared on ${e.preparedAt}. Language: ${a}.*`),i.push(""),i.push(e.framing==="wad"?Dr(e.organizationName,e.siteUrl):Nr(e.organizationName,e.siteUrl)),i.push(""),i.push("## Conformance status"),i.push(""),i.push(Lr(e.conformanceStatus,o,r)),i.push(""),t.length>0){i.push("## Non-accessible content"),i.push(""),i.push("The following content is not yet accessible:"),i.push("");for(const c of t){const d=c.exemption?c.exemption==="disproportionate-burden"?" *(claimed under disproportionate burden — Article 5 WAD / Article 14 EAA)*":" *(not subject to applicable legislation)*":"";i.push(`- **WCAG ${c.criterion}** — ${c.description}${d}`)}i.push("")}else e.conformanceStatus==="full"&&(i.push("## Non-accessible content"),i.push(""),i.push("No non-accessible content is currently known. If you encounter any accessibility barriers, please contact us using the feedback details below."),i.push(""));if(i.push("## Preparation of this accessibility statement"),i.push(""),i.push(Pr(n,e.evaluatedAt)),i.push(""),i.push("## Feedback and contact information"),i.push(""),i.push(`If you experience accessibility barriers on ${e.siteUrl}, please contact us so we can address them:`),i.push(""),e.contact.email&&i.push(`- **Email:** ${e.contact.email}`),e.contact.phone&&i.push(`- **Phone:** ${e.contact.phone}`),e.contact.formUrl&&i.push(`- **Web form:** ${e.contact.formUrl}`),i.push(""),e.framing==="wad"&&e.countryCode){const c=Mr[e.countryCode];c&&(i.push("## Enforcement procedure"),i.push(""),i.push(`If you are not satisfied with the response to your accessibility complaint, you may contact the national enforcement body for ${c.name}:`),i.push(""),i.push(`${c.url}`),i.push(""))}return e.framing==="eaa"&&(i.push("## Enforcement"),i.push(""),i.push("Enforcement of the European Accessibility Act is carried out by national market-surveillance authorities in each EU member state. If your accessibility complaint is not addressed satisfactorily, you may contact the market-surveillance authority of the EU member state in which you are located."),i.push("")),i.push("---"),i.push(""),i.push(`_Statement generated by wcagcheckr. Audit methodology details + cryptographic anchoring of the audit results are available on request from ${e.contact.email??"the contact above"}._`),i.join(`
371
- `)}function Tc(e,t){const a=l=>l==null?"":String(l).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;"),n=e.language||"English",o=e.languageCode||"en",r=e.auditedBy||"wcagcheckr (self-evaluation)",i=e.wcagVersion||"2.1",c=e.wcagLevel||"AA",d=[];if(d.push(`<article lang="${a(o)}">`),d.push(`<h1>Accessibility Statement — ${a(e.organizationName)}</h1>`),d.push(`<p><em>Statement prepared on ${a(e.preparedAt)}. Language: ${a(n)}.</em></p>`),d.push(`<p>${a(e.framing==="wad"?Dr(e.organizationName,e.siteUrl):Nr(e.organizationName,e.siteUrl))}</p>`),d.push("<h2>Conformance status</h2>"),d.push(`<p>${a(Lr(e.conformanceStatus,i,c))}</p>`),t.length>0){d.push("<h2>Non-accessible content</h2>"),d.push("<p>The following content is not yet accessible:</p>"),d.push("<ul>");for(const l of t){const p=l.exemption?l.exemption==="disproportionate-burden"?" <em>(claimed under disproportionate burden — Article 5 WAD / Article 14 EAA)</em>":" <em>(not subject to applicable legislation)</em>":"";d.push(`<li><strong>WCAG ${a(l.criterion)}</strong> — ${a(l.description)}${p}</li>`)}d.push("</ul>")}else e.conformanceStatus==="full"&&(d.push("<h2>Non-accessible content</h2>"),d.push("<p>No non-accessible content is currently known. If you encounter any accessibility barriers, please contact us using the feedback details below.</p>"));if(d.push("<h2>Preparation of this accessibility statement</h2>"),d.push(`<p>${a(Pr(r,e.evaluatedAt))}</p>`),d.push("<h2>Feedback and contact information</h2>"),d.push(`<p>If you experience accessibility barriers on ${a(e.siteUrl)}, please contact us so we can address them:</p>`),d.push("<ul>"),e.contact.email&&d.push(`<li><strong>Email:</strong> <a href="mailto:${a(e.contact.email)}">${a(e.contact.email)}</a></li>`),e.contact.phone&&d.push(`<li><strong>Phone:</strong> ${a(e.contact.phone)}</li>`),e.contact.formUrl&&d.push(`<li><strong>Web form:</strong> <a href="${a(e.contact.formUrl)}">${a(e.contact.formUrl)}</a></li>`),d.push("</ul>"),e.framing==="wad"&&e.countryCode){const l=Mr[e.countryCode];l&&(d.push("<h2>Enforcement procedure</h2>"),d.push(`<p>If you are not satisfied with the response to your accessibility complaint, you may contact the national enforcement body for ${a(l.name)}: <a href="${a(l.url)}">${a(l.url)}</a></p>`))}return e.framing==="eaa"&&(d.push("<h2>Enforcement</h2>"),d.push("<p>Enforcement of the European Accessibility Act is carried out by national market-surveillance authorities in each EU member state. If your accessibility complaint is not addressed satisfactorily, you may contact the market-surveillance authority of the EU member state in which you are located.</p>")),d.push("<hr>"),d.push(`<p><small>Statement generated by wcagcheckr. Audit methodology details + cryptographic anchoring of the audit results are available on request from ${a(e.contact.email??"the contact above")}.</small></p>`),d.push("</article>"),d.join(`
372
- `)}function Ec(e,t={},a=new Set){var c;const n=e.flatMap(d=>d.violations),o=new Map;for(const d of n){const l=Fe(d.ruleId,d.target.selector);o.has(l)||o.set(l,d)}const r=new Map;for(const d of o.values()){const l=d.wcagCriterion;if(!l||a.has(l))continue;const p=r.get(l)??[];p.push(d),r.set(l,p)}const i=[];for(const[d,l]of r.entries()){const p=l[0];let m=t[d];if(!m){const u=lt[p.ruleId];u!=null&&u.summary?m=((c=u.summary.split(/[.!?]\s+/)[0])==null?void 0:c.trim())??p.description:m=p.description}m=m.replace(new RegExp("^\\s*WCAG\\s+"+d.replace(/\./g,"\\.")+"\\b[\\s:.\\u2014-]*","i"),"").trim(),l.length>1&&(m+=` (affects ${l.length} components on the audited page${e.length>1?"s":""})`),i.push({criterion:d,description:m})}return i.sort((d,l)=>{const p=g=>g.split(".").map(h=>parseInt(h,10)),m=p(d.criterion),u=p(l.criterion);for(let g=0;g<Math.max(m.length,u.length);g++){const h=(m[g]??0)-(u[g]??0);if(h!==0)return h}return 0}),i}function Rc(e){const t=Ec(e.results,e.customDescriptions,e.dismissedCriteria);return e.outputFormat==="html"?Tc(e.inputs,t):$c(e.inputs,t)}function Lp(e){if(e.reduce((n,o)=>n+o.violations.length,0)===0)return"full";const a=new Set;for(const n of e)for(const o of n.violations)o.wcagCriterion&&a.add(o.wcagCriterion);return a.size>=10?"non-conformant":"partial"}function et(e,t,a,n,o,r,i,c,d){var k,v,s,x;const l=Sa(e,t,a,n,o,r,i,c,d),p=a??[],m=new Set((r??[]).map($=>$.criterionId)),u={};for(const $ of o??[]){const A=m.has($.criterionId)?"pass":$.verdict;$.criterionId==="2.4.3"?u.focusOrder=A:$.criterionId==="2.1.2"?u.keyboardTrap=A:$.criterionId==="2.4.7"?u.focusVisible=A:$.criterionId==="1.3.2"?u.readingOrder=A:$.criterionId==="1.4.11"&&(u.nonTextContrast=A)}const g=Ir(d??[],p).map($=>({ruleId:$.ruleId,impact:"serious",selector:$.selector})),h=ec({violations:e,auditRan:p.length>0,manualRuns:(t==null?void 0:t.runs)??[],workflows:(t==null?void 0:t.workflows)??[],heuristicCounts:{tabOrder:((v=(k=p[0])==null?void 0:k.tabOrderIssues)==null?void 0:v.length)??0,readingOrder:((x=(s=p[0])==null?void 0:s.readingOrderIssues)==null?void 0:x.length)??0},interactiveAuditVerdicts:u,aiResolvedFails:g}),f=yc(l.letter,h.overallLetter);return{combined:l.totals.critical>0||l.totals.serious>0?wc(f,l.letter):f,severity:l.letter,breadth:h.overallLetter,score:l,subScore:h}}const fn="humanCriterionVerdicts";async function Ln(){var a;if(typeof chrome>"u"||!((a=chrome.storage)!=null&&a.local))return[];const t=(await chrome.storage.local.get(fn))[fn];return Array.isArray(t)?t:[]}async function Fr(e){const t=new Set;for(const n of e)n&&t.add(n);return t.size===0?[]:(await Ln()).filter(n=>t.has(n.componentId))}async function Pp(e){if(!e.note||!e.note.trim())throw new Error("Human criterion verdict requires a non-empty note explaining the determination.");const a=(await Ln()).filter(n=>!(n.componentId===e.componentId&&n.criterionId===e.criterionId));a.push({...e,note:e.note.trim()}),await _r(a)}async function Fp(e,t){const n=(await Ln()).filter(o=>!(o.componentId===e&&o.criterionId===t));await _r(n)}async function _r(e){var t;typeof chrome>"u"||!((t=chrome.storage)!=null&&t.local)||await chrome.storage.local.set({[fn]:e})}function Kt(e){return/\[Cascade resolution — rc\.\d+ escalation\]/.test(e)}function _p(e){return/\[Manual verification — rc\.\d+\]/.test(e)}function Up(e){const t=e.match(/\[Cascade resolution — rc\.\d+ (fallback-\d|escalation)\]/);if(!t)return null;const a=t[1];return a==="fallback-1"||a==="fallback-2"||a==="escalation"?a:null}const Ur={ruleIds:["image-alt","label","button-name","link-name","color-contrast","document-title","html-has-lang"],thresholds:{moderate:1,high:2,critical:4},headlines:{low:"Low risk. Your site passes the checks common automated lawsuit-targeting scanners run today — not likely automated lawfare target. This isn't a guarantee: scanners add checks over time, so re-audit as your site changes.",moderate:"Moderate risk. A demand-letter scanner could flag at least one issue. Fix to drop off the easy-target list.",high:"High risk. Multiple findings here are common patterns demand-letter mills target.",critical:"Critical risk. Your site has many high-frequency patterns ADA-targeting firms scan for."},version:0};Ur.ruleIds;function Wr(){var e;return((e=mr())==null?void 0:e.lawfare)??Ur}function Gr(e,t=Wr()){return t.ruleIds.includes(e)}function uo(e,t=Wr()){const a=new Set(t.ruleIds),n=new Map;for(const l of e)a.has(l.ruleId)&&n.set(l.ruleId,(n.get(l.ruleId)??0)+1);const o=Array.from(n.entries()).map(([l,p])=>({ruleId:l,instanceCount:p})).sort((l,p)=>p.instanceCount-l.instanceCount),r=o.length,i=Array.from(n.values()).reduce((l,p)=>l+p,0);let c;return r<t.thresholds.moderate?c="low":r<t.thresholds.high?c="moderate":r<t.thresholds.critical?c="high":c="critical",{tier:c,letter:c==="low"?"A":c==="moderate"?"C":c==="high"?"D":"F",flaggedRuleCount:r,flaggedInstanceCount:i,flaggedRules:o,headline:t.headlines[c],rubricVersion:t.version}}function Oc(e,t){return e.flatMap(a=>a.violations).filter(a=>!a.needsReview&&!t.has(a.matchKey))}function Mc(e,t){const a=[],n={};for(const o of e){const r=Oc(o.results,t);a.push(...r),n[o.url]=uo(r).letter}return{site:uo(a),perUrlLetter:n}}function Wp(e){return e.filter(t=>!t.needsReview&&Gr(t.ruleId))}const gn="manualCriterionAttestations";function Gp(e,t,a){const n=a==="attested-conforms"?"conforms":"does not apply",o=t.slice(0,10);return`I, the operator, manually evaluated ${e} on ${o} and, to the best of my knowledge, it ${n}. This is my own assessment; wcagcheckr did not verify it.`}const Vr=`About this grade — basis and limits. This grade reflects (1) what wcagcheckr verified programmatically and by AI evaluation ("proven in code") and (2) the operator's own attestations on the content-meaning criteria the tool cannot verify ("claimed by the operator"). An "A" is issued only after the operator has affirmatively confirmed every such criterion as conforming or not-applicable; any criterion the operator leaves "not addressed" holds the grade below A. This grade is NOT a certification, warranty, or guarantee of conformance with WCAG, the ADA, or any law, and must not be relied upon as proof of legal compliance. The operator is solely responsible for the accuracy of their attestations and for any criteria outside wcagcheckr's automated scope.`,$a=[{id:"1.1.1",reason:"alt text exists, but only a human can confirm it conveys the image's meaning/purpose"},{id:"1.2.1",reason:"a transcript/alternative exists and is accurate for audio-only / video-only media"},{id:"1.2.2",reason:"captions are present AND accurate/synced for prerecorded audio"},{id:"1.2.3",reason:"audio description or a full text alternative covers the prerecorded video"},{id:"1.2.4",reason:"captions are present AND accurate for LIVE audio"},{id:"1.2.5",reason:"audio description quality is sufficient for prerecorded video"},{id:"1.3.3",reason:"instructions do not rely on sensory characteristics (shape/size/position/sound) alone"},{id:"1.4.1",reason:"information is not conveyed by color alone in content the tool could not classify"}],Vp={"1.1.1":{what:"Every meaningful image needs alt text that conveys what the image shows or does — not just that an image is there.",applies:"Applies if your pages have images that carry meaning — photos, logos, icons used as buttons, charts, infographics. Purely decorative images (background flourishes) don't count and the tool already handles those.",confirm:`Pick a handful of important images (your hero image, product photos, any icon you click, any chart). Read each one's alt text and ask: "If I couldn't see this image, would this text tell me what I need?" Conforms if yes. If an icon-button just says "icon" or a chart's alt is "chart", that's a fail.`},"1.2.1":{what:"Audio with no video (a podcast) needs a written transcript; video with no sound (a silent animation) needs a text or audio description of what happens.",applies:"Only if you host audio-only or silent-video media. No podcasts, voice clips, or silent video on your site? → N/A (very common).",confirm:"Find each such file. Audio-only → is there a readable transcript nearby? Silent video → is there text (or narration) describing what it shows? Conforms if the alternative exists and matches."},"1.2.2":{what:"Recorded videos that have sound need captions that match the spoken words and are timed correctly.",applies:"Only if you have videos with audio — tutorials, promos, an embedded YouTube clip. No videos with sound anywhere? → N/A.",confirm:"Open each video, turn captions on, watch ~15 seconds. Do the captions match what's actually said and stay in sync? Auto-generated captions are often wrong — read them, don't assume. Conforms only if they're accurate."},"1.2.3":{what:"For a recorded video, anything shown but not spoken (on-screen text, a chart, an action) must also reach someone who can't see it — via an audio-description track OR a full text version.",applies:"Only if you have videos where important information appears visually without being said out loud. No such videos? → N/A.",confirm:"Watch a video with your eyes closed. Did you miss anything important (on-screen text, who did what)? If yes, check there's an audio description or a transcript that fills the gap. Conforms if a blind viewer would still get everything."},"1.2.4":{what:"A LIVE broadcast with sound (a webinar, a live event stream) needs captions appearing in real time as people speak.",applies:"Only if your site streams LIVE audio or video. Almost no sites do — pre-recorded videos are NOT live. No live streaming? → N/A (this is the usual answer).",confirm:'During an actual live broadcast, are captions shown as it happens and roughly accurate? Conforms if yes. If you never stream live, mark N/A and note "no live media."'},"1.2.5":{what:"A stronger version of 1.2.3: recorded videos should have an audio-description track that narrates the important visual-only details for someone who can't see the screen.",applies:"Only if you have videos with meaningful visuals that aren't spoken aloud. No such videos? → N/A.",confirm:"Play the audio-description track (if there is one) and confirm it explains the key visuals a blind viewer would otherwise miss. Conforms if the description is adequate; if there's no described track and the video needs one, that's a fail."},"1.3.3":{what:'Instructions must not rely ONLY on shape, size, position, or sound — e.g. "click the round green button on the right" or "the field marked with the symbol."',applies:"Applies if any of your pages give instructions that point at things by how they look or where they are — common on forms, checkouts, and help text.",confirm:'Scan your instructional text. Does any of it say "the button on the left," "the green one," "the round icon," or "when you hear the beep" WITHOUT also naming the thing (its label or text)? If every instruction also names what it points to, Conforms.'},"1.4.1":{what:`Color can't be the ONLY way you signal something — e.g. required fields shown only in red, links that look identical to text except they're blue, or "items in green are in stock."`,applies:"Applies to nearly every site — anywhere forms, links, or status indicators use color to mean something.",confirm:`Find places where color carries meaning (form errors, links in body text, status badges, chart series). Is there ALSO a non-color cue — text, an icon, an underline, a label? If yes everywhere, Conforms. If something is "red = error" with no other signal, that's a fail.`}};async function Pn(){var a;if(typeof chrome>"u"||!((a=chrome.storage)!=null&&a.local))return[];const t=(await chrome.storage.local.get(gn))[gn];return Array.isArray(t)?t:[]}async function jr(e){const t=new Set;for(const n of e)n&&t.add(n);return t.size===0?[]:(await Pn()).filter(n=>t.has(n.componentId))}async function jp(e){if(e.kind!=="not-addressed"&&(!e.note||!e.note.trim()))throw new Error("An attestation of conformance / N-A requires a note describing what you checked.");const a=(await Pn()).filter(n=>!(n.componentId===e.componentId&&n.criterionId===e.criterionId));a.push({...e,note:e.note.trim()}),await Br(a)}async function Bp(e,t){const n=(await Pn()).filter(o=>!(o.componentId===e&&o.criterionId===t));await Br(n)}async function Br(e){var t;typeof chrome>"u"||!((t=chrome.storage)!=null&&t.local)||await chrome.storage.local.set({[gn]:e})}function ft(e){return new Set(e.map(a=>a.pageUrl??a.scope??"").filter(Boolean)).size>1?"site-crawl":"single-page"}function Dc(e){const t=new Set;for(const a of e)a.componentId&&t.add(a.componentId);return Array.from(t)}async function Le(e,t=[]){const a=Dc(e),n=new Set(t.filter(w=>!!w)),o=Array.from(new Set([...a,...n]));if(o.length===0)return{walkthroughs:[],walkthroughAcks:[],acknowledgedMatchKeys:new Set,humanCriterionVerdicts:[],incompleteResolutions:[],attestations:[],walkthroughsByComponent:new Map,walkthroughAcksByComponent:new Map,ackedKeysByComponent:new Map,humanVerdictsByComponent:new Map,incompleteResolutionsByComponent:new Map};const[r,i,c,d,l,p]=await Promise.all([Nc(o),Lc(o),Pc(o),Fc(o),_c(e,o),jr(o)]);if(n.size>0&&a.length>0){const w=new Map;for(const b of n){const k=d.get(b)??[];for(const v of k)w.has(v.criterionId)||w.set(v.criterionId,v)}if(w.size>0)for(const b of a){const k=d.get(b)??[],v=new Set(k.map(x=>x.criterionId)),s=[...k];for(const x of w.values())v.has(x.criterionId)||s.push({...x,componentId:b});d.set(b,s)}}const m=[];for(const w of r.values())m.push(...w);const u=[];for(const w of i.values())u.push(...w);const g=new Set;for(const w of c.values())for(const b of w)g.add(b);const h=[];for(const w of d.values())h.push(...w);const f=[];for(const w of l.values())f.push(...w);return{walkthroughs:m,walkthroughAcks:u,acknowledgedMatchKeys:g,humanCriterionVerdicts:h,incompleteResolutions:f,attestations:p,walkthroughsByComponent:r,walkthroughAcksByComponent:i,ackedKeysByComponent:c,humanVerdictsByComponent:d,incompleteResolutionsByComponent:l}}async function Nc(e){const t=new Map;return await Promise.all(e.map(async a=>{const n=await xa([a]);t.set(a,n)})),t}async function Lc(e){const t=new Map,a=await $r(e);for(const n of e)t.set(n,[]);for(const n of a){const o=t.get(n.componentId);o&&o.push(n)}return t}async function Pc(e){const t=new Map;return await Promise.all(e.map(async a=>{const n=await va(a);t.set(a,n)})),t}async function Fc(e){const t=new Map,a=await Fr(e);for(const n of e)t.set(n,[]);for(const n of a){const o=t.get(n.componentId);o&&o.push(n)}return t}async function _c(e,t){const a=new Map;for(const o of e)if(o.componentId&&!a.has(o.componentId)){const r=o.pageUrl??o.scope;r&&a.set(o.componentId,r)}const n=new Map;return await Promise.all(t.map(async o=>{const r=a.get(o);n.set(o,r?await ka(r):[])})),n}function Uc(e){return e.length<2?[]:[...Gc(e),...jc(e),...Bc(e),...Hc(e)]}function Wc(e){const t=new Set;if(e.length<2)return t;for(const o of["primary","footer","utility"]){const r=e.map(i=>i.navLinks.filter(c=>c.region===o&&c.href).map(c=>c.href)).filter(i=>i.length>0);for(let i=0;i<r.length-1;i++)if(r[i].filter(d=>r[i+1].includes(d)).length>=2){t.add("3.2.3");break}if(t.has("3.2.3"))break}const a=new Map;e.forEach((o,r)=>{for(const i of o.sharedComponents)a.has(i.fingerprint)||a.set(i.fingerprint,new Set),a.get(i.fingerprint).add(r)}),[...a.values()].some(o=>o.size>=2)&&t.add("3.2.4");const n=new Map;return e.forEach((o,r)=>{for(const i of o.helpMechanisms){const c=Ta(i.label);c&&(n.has(c)||n.set(c,new Set),n.get(c).add(r))}}),[...n.values()].some(o=>o.size>=2)&&t.add("3.2.6"),t}function Gc(e){const t=[];for(const a of["primary","footer","utility"]){const n=e.map(o=>({snapshot:o,hrefs:o.navLinks.filter(r=>r.region===a&&r.href).map(r=>r.href)})).filter(o=>o.hrefs.length>0);if(!(n.length<2))for(let o=0;o<n.length-1;o++){const r=n[o],i=n[o+1],c=r.hrefs.filter(h=>i.hrefs.includes(h));if(c.length<2)continue;const d=c.map(h=>r.hrefs.indexOf(h)),l=c.map(h=>i.hrefs.indexOf(h)),p=[...d].sort((h,f)=>h-f),m=[...l].sort((h,f)=>h-f),u=p.map(h=>c[d.indexOf(h)]),g=m.map(h=>c[l.indexOf(h)]);Vc(u,g)||t.push({ruleId:"wcc-consistent-navigation",wcagCriterion:"3.2.3",wcagLevel:"AA",impact:"moderate",description:`${a}-region nav links appear in a different order on these pages.`,details:[`Page A: ${r.snapshot.url}`,` order: [${u.join(", ")}]`,`Page B: ${i.snapshot.url}`,` order: [${g.join(", ")}]`,"WCAG 3.2.3 requires that components that appear on multiple pages occur in the same relative order. Additions are fine; reorders are not."].join(`
373
- `),pages:[{url:r.snapshot.url,evidence:u.join(" → ")},{url:i.snapshot.url,evidence:g.join(" → ")}]})}}return t}function Vc(e,t){if(e.length!==t.length)return!1;for(let a=0;a<e.length;a++)if(e[a]!==t[a])return!1;return!0}function jc(e){const t=[],a=new Map;for(const n of e)for(const o of n.sharedComponents)a.has(o.fingerprint)||a.set(o.fingerprint,[]),a.get(o.fingerprint).push({url:n.url,accessibleName:o.accessibleName,role:o.role});for(const[n,o]of a.entries()){if(o.length<2)continue;const r=new Set(o.map(i=>Ta(i.accessibleName)));r.size<=1||t.push({ruleId:"wcc-consistent-identification",wcagCriterion:"3.2.4",wcagLevel:"AA",impact:"moderate",description:`Same component (${n}) has different accessible names across pages.`,details:[`Fingerprint: ${n}`,`Role: ${o[0].role}`,`Distinct names observed: ${[...r].map(i=>`"${i}"`).join(", ")}`,...o.map(i=>` ${i.url} → "${i.accessibleName}"`),"WCAG 3.2.4 requires components with identical functionality to have identical accessible names across pages."].join(`
374
- `),pages:o.map(i=>({url:i.url,evidence:i.accessibleName}))})}return t}function Ta(e){return e.toLowerCase().replace(/\s+/g," ").trim()}function Bc(e){const t=[],a=new Map;for(const n of e)for(const o of n.helpMechanisms){const r=Ta(o.label);r&&(a.has(r)||a.set(r,[]),a.get(r).push({url:n.url,landmark:o.landmark,rawLabel:o.label}))}for(const[n,o]of a.entries()){if(o.length<2)continue;const r=new Set(o.map(i=>i.landmark));r.size<=1||t.push({ruleId:"wcc-consistent-help",wcagCriterion:"3.2.6",wcagLevel:"A",impact:"minor",description:`Help mechanism "${n}" appears in different landmarks across pages.`,details:[`Help label: "${n}"`,`Distinct landmarks observed: ${[...r].join(", ")}`,...o.map(i=>` ${i.url} → ${i.landmark}`),"WCAG 3.2.6 (AA, WCAG 2.2): when a help mechanism exists on multiple pages, it must appear in the same relative order. Same-label help that moves between header/footer/nav is a divergence."].join(`
375
- `),pages:o.map(i=>({url:i.url,evidence:`${i.rawLabel} in ${i.landmark}`}))})}return t}function Hc(e){const t=[],a=e.filter(o=>o.isMultiStep);if(a.length<2)return t;const n=new Map;for(const o of a)for(const r of o.formFields){const i=Ta(r.name);i&&(n.has(i)||n.set(i,[]),n.get(i).push({url:o.url,label:r.label,type:r.type,isSecurityEssential:r.isSecurityEssential}))}for(const[o,r]of n.entries())r.length<2||r.some(i=>i.isSecurityEssential)||t.push({ruleId:"wcc-redundant-entry",wcagCriterion:"3.3.7",wcagLevel:"A",impact:"minor",description:`Field "${o}" is requested on multiple steps of a multi-step flow.`,details:[`Field name: "${o}"`,"Occurrences:",...r.map(i=>` ${i.url} → label "${i.label}", type ${i.type}`),"WCAG 3.3.7 (A, WCAG 2.2): information previously entered in a multi-step process must be auto-populated or selectable, unless re-entry is essential (e.g., password confirmation, security questions)."].join(`
376
- `),pages:r.map(i=>({url:i.url,evidence:`${i.label} (${i.type})`}))});return t}const qc=$a.length;function zc(e,t){const a=$a.map(c=>c.id),n=a.length,o=a.filter(c=>!t.has(c)),r=n-o.length;return e!=="A"?{status:"none",displayGrade:e,automationGrade:e,answered:r,total:n,unanswered:o,reason:null}:o.length>0?{status:"pending",displayGrade:"pending",automationGrade:e,answered:r,total:n,unanswered:o,reason:null}:a.some(c=>t.get(c)==="not-addressed")?{status:"resolved",displayGrade:"B",automationGrade:e,answered:r,total:n,unanswered:o,reason:"spot-checks-not-addressed"}:{status:"resolved",displayGrade:"A",automationGrade:e,answered:r,total:n,unanswered:o,reason:null}}function Kc(e){const t=new Set($a.map(n=>n.id)),a=new Map;for(const n of e)t.has(n.criterionId)&&a.set(n.criterionId,n.kind);return a}function Hr(e,t){if(e==="pending"){const a=(t==null?void 0:t.answered)??0,n=(t==null?void 0:t.total)??qc;return`Pending — ${a} of ${n} content-meaning spot-checks answered; no letter grade is issued until all are`}return e}const aa={A:0,B:1,C:2,D:3,F:4},ho={low:0,moderate:1,high:2,critical:3};function Yc(e,t){return aa[e]>aa[t]?e:t}function Jc(e,t){return ho[e]>ho[t]?e:t}function Xc(e){const t=[];for(const a of e)for(const n of a.results)for(const o of n.violations)o.needsReview||t.push({url:a.url,componentId:a.componentId,v:o});return t}function Qc(e,t){const a=[];for(const n of e){const o=t==null?void 0:t.get(n.componentId);for(const r of n.results)for(const i of r.violations)i.needsReview&&(o!=null&&o.has(i.matchKey)||a.push({url:n.url,v:i}))}return a}function qr(e,t,a,n,o,r,i,c,d,l,p){const m=t.filter(y=>!y.error).length,u=t.filter(y=>!!y.error&&!y.skipped).length,g=t.filter(y=>!!y.skipped).length,h=t.length<=1?"single-page":"site-crawl",f=t.map(y=>y.snapshot).filter(y=>!!y),w=Uc(f),b=new Set(w.map(y=>y.wcagCriterion)),k=[...Wc(f)].filter(y=>!b.has(y)),v=()=>k.map(y=>({criterionId:y,verdict:"pass",note:`[auto] cross-page consistency comparator found no divergence across ${f.length} crawled pages`,verifiedAt:n})),s=t.filter(y=>!y.skipped).map(y=>{if(y.error)return{url:y.url,grade:"F",risk:"critical",uniqueViolations:0,totals:{critical:0,serious:0,moderate:0,minor:0},durationMs:y.durationMs,error:y.error,walkthroughFindings:[],walkthroughAcknowledgements:[]};const L=y.results.flatMap(Me=>Me.violations),R=r==null?void 0:r.get(y.componentId),G=i==null?void 0:i.get(y.componentId),Y=c==null?void 0:c.get(y.componentId),B=[...(d==null?void 0:d.get(y.componentId))??[],...v()],K=l==null?void 0:l.get(y.componentId),Q=et(L,{runs:[],workflows:Pe},y.results,Y?new Set(Y):void 0,R?[...R]:void 0,G?[...G]:void 0,B?[...B]:void 0,h,K?[...K]:void 0),ae=Q.score;return{url:y.url,grade:Q.combined,risk:ae.risk,uniqueViolations:ae.totals.unique,totals:{critical:ae.totals.critical,serious:ae.totals.serious,moderate:ae.totals.moderate,minor:ae.totals.minor},durationMs:y.durationMs,walkthroughFindings:ae.walkthroughFindings,walkthroughAcknowledgements:ae.walkthroughAcknowledgements}});s.sort((y,L)=>{const R=aa[L.grade]-aa[y.grade];return R!==0?R:L.uniqueViolations-y.uniqueViolations});let x="A",$="low";for(const y of s)x=Yc(x,y.grade),$=Jc($,y.risk);const A=s.length>0?zc(x,Kc(p??[])):void 0,C=(A==null?void 0:A.displayGrade)??x,F=Xc(t).filter(({v:y,componentId:L})=>{const R=c==null?void 0:c.get(L);return!(R!=null&&R.has(y.matchKey))}),T=y=>`${y.ruleId}::${y.target.selector}`,I=new Map;for(const{v:y}of F){const L=T(y);I.has(L)||I.set(L,y)}const D=I.size,S={critical:0,serious:0,moderate:0,minor:0};for(const y of I.values())S[y.impact]++;const _=new Map;for(const{url:y,v:L}of F){let R=_.get(L.ruleId);R||(R={ruleId:L.ruleId,description:L.description,impact:L.impact,urls:new Set,totalOccurrences:0},_.set(L.ruleId,R)),R.urls.add(y),R.totalOccurrences++}const N=Array.from(_.values()).map(y=>({ruleId:y.ruleId,description:y.description,impact:y.impact,urlsAffected:y.urls.size,totalOccurrences:y.totalOccurrences,sampleUrls:Array.from(y.urls).slice(0,5)})).sort((y,L)=>L.urlsAffected!==y.urlsAffected?L.urlsAffected-y.urlsAffected:L.totalOccurrences-y.totalOccurrences),O=Qc(t,c),W=new Map,P=new Set;for(const{url:y,v:L}of O){P.add(`${L.ruleId}::${L.target.selector}`);let R=W.get(L.ruleId);R||(R={ruleId:L.ruleId,description:L.description,impact:L.impact,urls:new Set,totalOccurrences:0},W.set(L.ruleId,R)),R.urls.add(y),R.totalOccurrences++}const V=Array.from(W.values()).map(y=>({ruleId:y.ruleId,description:y.description,impact:y.impact,urlsAffected:y.urls.size,totalOccurrences:y.totalOccurrences,sampleUrls:Array.from(y.urls).slice(0,5)})).sort((y,L)=>L.urlsAffected!==y.urlsAffected?L.urlsAffected-y.urlsAffected:L.totalOccurrences-y.totalOccurrences),M=P.size,j={minor:0,moderate:1,serious:2,critical:3},q=new Map;for(const y of t){if(y.error)continue;const L=c==null?void 0:c.get(y.componentId);for(const R of y.results)for(const G of R.violations){if(L!=null&&L.has(G.matchKey))continue;const Y=`${Fe(G.ruleId,G.target.selector)}::${G.needsReview?"NR":"ACT"}`;let B=q.get(Y);B||(B={ruleId:G.ruleId,representativeSelector:G.target.selector,representativeOuterHTML:G.target.outerHTML??"",impact:G.impact,wcagCriterion:G.wcagCriterion??null,axeDescription:G.description??"",pages:new Map,totalOccurrences:0,needsReview:G.needsReview??!1,failureSummary:G.target.failureSummary??null},q.set(Y,B)),j[G.impact]>j[B.impact]&&(B.impact=G.impact),B.totalOccurrences++,B.pages.has(y.url)||B.pages.set(y.url,{selector:G.target.selector,outerHTML:G.target.outerHTML??""}),!B.failureSummary&&G.target.failureSummary&&(B.failureSummary=G.target.failureSummary)}}const z=Array.from(q.values()).map(y=>({ruleId:y.ruleId,representativeSelector:y.representativeSelector,representativeOuterHTML:y.representativeOuterHTML,impact:y.impact,wcagCriterion:y.wcagCriterion,axeDescription:y.axeDescription,pages:Array.from(y.pages.entries()).map(([L,R])=>({url:L,selector:R.selector,outerHTML:R.outerHTML})),totalOccurrences:y.totalOccurrences,isShared:y.pages.size>=2,needsReview:y.needsReview,failureSummary:y.failureSummary})).sort((y,L)=>j[L.impact]!==j[y.impact]?j[L.impact]-j[y.impact]:L.pages.length-y.pages.length),X={A:0,B:0,C:0,D:0,F:0};for(const y of s)X[y.grade]++;const re=new Set,oe=[],le=[];for(const y of s){for(const L of y.walkthroughFindings){const R=`${L.criterionId}::${L.pageUrl}`;re.has(R)||(re.add(R),oe.push(L))}for(const L of y.walkthroughAcknowledgements){const R=`${L.criterionId}::${L.pageUrl}::ack`;re.has(R)||(re.add(R),le.push(L))}}const ie=new Map,ge={untested:0,inconclusive:1,failing:2},Re=new Map;for(const y of ma("2.1","AA"))Re.set(y.id,y.title);const Oe=new Map;function ve(y,L){const R=`${L.pageUrl}::${L.selector??""}::${L.source}::${L.ruleOrStepId}`;let G=Oe.get(y);if(G||(G=new Set,Oe.set(y,G)),G.has(R))return;G.add(R);const Y=ie.get(y);Y&&(Y.evidence.length>=6||Y.evidence.push(L))}for(const y of t){if(y.error)continue;const L=y.results.flatMap(Ae=>Ae.violations),R=r==null?void 0:r.get(y.componentId),G=i==null?void 0:i.get(y.componentId),Y=c==null?void 0:c.get(y.componentId),B=[...(d==null?void 0:d.get(y.componentId))??[],...v()],K=l==null?void 0:l.get(y.componentId),Q=Sa(L,void 0,y.results,Y?new Set(Y):void 0,R?[...R]:void 0,G?[...G]:void 0,B?[...B]:void 0,h,K?[...K]:void 0);if(!Q.coverage)continue;const ae=(Ae,Ce)=>{for(const ne of Ae){const Ue=Re.get(ne)??ne,We=ie.get(ne);We?ge[Ce]>ge[We.state]&&ie.set(ne,{state:Ce,title:Ue,evidence:We.evidence}):ie.set(ne,{state:Ce,title:Ue,evidence:[]})}};ae(Q.coverage.untestedCriteria,"untested"),ae(Q.coverage.inconclusiveCriteria,"inconclusive"),ae(Q.coverage.failingCriteria,"failing");const Me=Q.coverage.inconclusiveReasons??{};for(const[Ae,Ce]of Object.entries(Me))for(const ne of Ce)if(ne.elements&&ne.elements.length>0)for(const Ue of ne.elements)ve(Ae,{pageUrl:ne.pageUrl??y.url,selector:Ue.selector,ruleOrStepId:ne.ruleOrStepId,source:ne.source,notes:Ue.failureSummary});else ve(Ae,{pageUrl:ne.pageUrl??y.url,ruleOrStepId:ne.ruleOrStepId,source:ne.source,notes:ne.resolutionHint});const ee=Q.coverage.failingReasons??{};for(const[Ae,Ce]of Object.entries(ee))for(const ne of Ce)ve(Ae,{pageUrl:ne.pageUrl??y.url,selector:ne.selector,ruleOrStepId:ne.ruleOrStepId,source:ne.source,notes:ne.notes})}const de=Array.from(ie.entries()).map(([y,L])=>({criterionId:y,title:L.title,state:L.state,evidence:L.evidence})).sort((y,L)=>y.criterionId.localeCompare(L.criterionId,void 0,{numeric:!0}));return{startedAt:a,finishedAt:n,startUrl:e,pagesAudited:m,pagesFailed:u,pagesSkipped:g,totalDurationMs:o,siteGrade:C,spotCheckGate:A,siteRisk:$,totalUniqueViolations:D,totals:S,topViolations:N,needsReviewItems:V,totalNeedsReview:M,findingGroups:z,pages:s,pagesByGrade:X,consistencyFindings:w,walkthroughFindings:oe,walkthroughAcknowledgements:le,totalWalkthroughFindings:oe.length,blockingCriteria:de}}function tt(e){return/<main[\s>]/i.test(e)?e:e.replace(/(<body[^>]*>)/i,`$1
377
- <main>`).replace(/(<\/body>)/i,`</main>
378
- $1`)}function na(e){return e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?"["+e.map(n=>na(n)).join(",")+"]":"{"+Object.keys(e).sort().map(n=>{const o=e[n];return JSON.stringify(n)+":"+na(o)}).join(",")+"}"}const Zc="wcag-forensic-log",el=1,Be="audits";let Wa=null;function Ea(){return Wa||(Wa=Sn(Zc,el,{upgrade(e){if(!e.objectStoreNames.contains(Be)){const t=e.createObjectStore(Be,{keyPath:["componentId","capturedAt"]});t.createIndex("byCapturedAt","capturedAt"),t.createIndex("byComponentId","componentId")}}})),Wa}async function tl(e){const t=na(e),a=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",a);return Array.from(new Uint8Array(n)).map(o=>o.toString(16).padStart(2,"0")).join("")}async function zr(e,t,a){if(e.length===0)return null;const n=e[0],o=n.componentId,r=n.pageUrl??n.scope,i=n.startedAt,c={componentId:o,pageUrl:r,scope:n.scope,grade:t.letter,totals:{critical:t.totals.critical,serious:t.totals.serious,moderate:t.totals.moderate,minor:t.totals.minor,unique:t.totals.unique},axeVersion:n.axeVersion,capturedAt:i,statesAudited:e.length},l={hash:await tl(c),componentId:o,pageUrl:r,scope:n.scope,grade:t.letter,totals:c.totals,axeVersion:n.axeVersion,capturedAt:i,statesAudited:e.length,durationMs:a};try{await(await Ea()).put(Be,l)}catch(p){return console.warn("[forensic-log] failed to record audit",p),l}return l}async function Kr(e,t,a){try{const n=await Ea(),o=await n.get(Be,[e,t]);if(!o){console.warn("[forensic-log] no entry to attach receipt to",{componentId:e,capturedAt:t});return}o.receipt=a,await n.put(Be,o)}catch(n){console.warn("[forensic-log] failed to attach receipt",n)}}async function Tt(){try{return(await(await Ea()).getAll(Be)).sort((a,n)=>a.capturedAt<n.capturedAt?1:-1)}catch(e){return console.warn("[forensic-log] listAudits failed",e),[]}}async function al(e){try{return(await(await Ea()).transaction(Be).objectStore(Be).index("byComponentId").getAll(IDBKeyRange.only(e))).sort((o,r)=>o.capturedAt<r.capturedAt?1:-1)}catch(t){return console.warn("[forensic-log] listAuditsForComponent failed",t),[]}}const nl={"color-contrast":{whatsWrong:"Some text on this page is too light to read against its background.",whyItMatters:"People with low vision, older eyes, or anyone reading on a sunny phone screen can't make out faint text. Color blindness affects about 1 in 12 men and 1 in 200 women. Insufficient contrast is the #1 most-common cause of accessibility lawsuits — every Domino's-style ADA suit cites it.",howToFix:"If you use a website builder (Squarespace, Wix, Shopify, WordPress with a theme), open your site styles or theme color settings and pick darker text colors or lighter backgrounds. Aim for very dark text on white, or very light text on dark. Free check at webaim.org/resources/contrastchecker. If you have a developer, ask them to ensure all text meets WCAG AA contrast (4.5:1 for normal text, 3:1 for large text)."},"color-contrast-enhanced":{whatsWrong:"Text on this page doesn't meet the higher (AAA) contrast level — important for people with significant low vision.",whyItMatters:"AAA is a stricter standard than the legal-minimum AA. If your audience includes older adults, people with cataracts or macular degeneration, or government-related contracts that require AAA conformance, this matters.",howToFix:"Same as basic contrast — go darker on text or lighter on backgrounds. AAA requires 7:1 for normal text and 4.5:1 for large text."},"link-in-text-block":{whatsWrong:"Links inside paragraphs are distinguishable from the surrounding text by color alone.",whyItMatters:"If a user is colorblind or sees in grayscale, they can't tell which words are clickable. WCAG requires another visual cue (underline, bold, icon) in addition to color.",howToFix:"Add an underline to links inside paragraphs. In most theme editors there's a 'link style' setting — turn underlines back on. The underline is the standard convention; it's also more discoverable for everyone."},"image-alt":{whatsWrong:"Some images on this page have no description for screen readers.",whyItMatters:"Blind and low-vision users rely on screen readers to read pages aloud. When an image has no description, the screen reader either skips it entirely or reads out the file name — useless. Missing alt text is the #2 lawsuit-magnet category.",howToFix:"In your site editor, click each image and look for an 'Alt text' or 'Image description' field. Write a short sentence describing what the image shows or what it links to. For purely decorative images (dividers, background flourishes), enter empty alt text or check a 'decorative' box if the platform offers one."},"input-image-alt":{whatsWrong:"Image-based form buttons (submit buttons that are images) have no description.",whyItMatters:"Without a description, screen-reader users can't tell what the button does — they hear 'button, submit.png' or just 'graphic'.",howToFix:"Replace image submit buttons with regular text buttons (most platforms let you do this in form settings), OR if you must use an image, ensure it has alt text describing the action ('Subscribe', 'Send message', 'Submit form')."},"area-alt":{whatsWrong:"An image map (clickable regions inside a single image) has unlabeled regions.",whyItMatters:"Each clickable area is a link — without a description, screen-reader users don't know what it points to.",howToFix:"Image maps are uncommon today. If you need one, your developer should add an alt attribute to each clickable area. The simpler modern approach: use multiple separate linked images or buttons instead."},"svg-img-alt":{whatsWrong:"Some SVG icons that act as images don't have a description.",whyItMatters:"SVG icons used decoratively are fine to leave silent, but icons that convey meaning (status indicators, social-media icons that link out) need a description so screen readers know what they represent.",howToFix:"In most platforms this requires a developer. Tell them: 'meaningful SVG icons need a title or aria-label; decorative SVGs need aria-hidden=true'. Examples: an envelope icon linking to 'Contact us' should be labeled 'Contact us', not silent."},"object-alt":{whatsWrong:"Embedded content (PDFs, videos, embedded apps) has no fallback description.",whyItMatters:"If the embed fails to load — or the user's screen reader can't navigate it — they need a text description of what the embed is.",howToFix:"Replace embedded objects with native modern alternatives where possible (HTML5 video instead of Flash, linked PDF with a description). If you must use an <object> embed, ask your developer to add fallback content describing what it is."},"role-img-alt":{whatsWrong:"An element marked as an image is missing its description.",whyItMatters:"Same as missing image alt — screen-reader users get nothing where they should hear a description.",howToFix:"Ask your developer: 'elements with role=img need aria-label or aria-labelledby'."},"image-redundant-alt":{whatsWrong:"Some images have alt text that duplicates nearby visible text.",whyItMatters:"Screen-reader users hear the same content twice — the surrounding text and then the alt text. Annoying, not blocking. Lower-priority fix.",howToFix:"Find images where the caption or nearby paragraph already says what the image shows, and either change the alt text to add new info or set the alt to empty (so the screen reader skips it as decorative)."},label:{whatsWrong:"Some form fields have no label that screen readers can announce.",whyItMatters:"Visually you can see what each field is for (next to a 'Name:' or 'Email:' text), but screen-reader users hear only 'edit text' if there's no programmatic label connecting the text to the field. The result: blind users can't tell what to type where.",howToFix:"In a website builder, every form field has a 'Label' field or similar. Make sure every input has one filled in. Placeholder text (the gray hint inside the field) does NOT count as a label — it has to be a real label."},"select-name":{whatsWrong:"A dropdown menu has no description.",whyItMatters:"Screen-reader users hear 'combo box, has popup' but not what the dropdown is for. They can't fill out forms reliably.",howToFix:"In your form editor, check that each dropdown has a visible label above or beside it. If your platform has separate label/field settings, both must be filled."},"aria-input-field-name":{whatsWrong:"A custom input control (search box, range slider, custom date picker) has no name.",whyItMatters:"Custom controls are common in modern site builders — they look fancy but break for screen-reader users when not labeled.",howToFix:"This is a developer fix. Ask: 'custom inputs with role=textbox / searchbox / slider / spinbutton need an aria-label or aria-labelledby'."},"aria-toggle-field-name":{whatsWrong:"A toggle switch (on/off control) has no description.",whyItMatters:"User can see the switch but can't tell what it controls without a label.",howToFix:"Developer fix: 'switches and checkboxes with role=switch need an accessible name'."},"form-field-multiple-labels":{whatsWrong:"A form field has multiple labels, which confuses screen readers.",whyItMatters:"Screen readers will read all labels — sometimes saying conflicting things — leaving users unsure what to enter.",howToFix:"Developer fix: 'this field has multiple <label> associations; pick one and remove the others'."},"label-content-name-mismatch":{whatsWrong:"A button's visible text doesn't match the description it announces to screen readers.",whyItMatters:"A user dictating 'click Submit' to voice-control software may see 'Submit' on screen but the announce-name is something else, so the voice command fails.",howToFix:"Developer fix: 'aria-label should start with or fully contain the visible button text'."},"autocomplete-valid":{whatsWrong:"A field that should auto-fill (name, email, phone, address) is missing the right autocomplete hint.",whyItMatters:"Browsers use these hints to auto-fill personal info, helping users with motor disabilities and saving everyone time. Older adults appreciate this most.",howToFix:"In your form builder, look for an 'Autocomplete' or 'Field type' setting per field. Set them to 'email', 'name', 'tel', 'street-address' etc. as appropriate."},"button-name":{whatsWrong:"Some buttons have no description that screen readers can announce.",whyItMatters:"Visual users see an icon (a heart, a trash can, an X), but screen-reader users hear only 'button' — they don't know if it'll favorite a post, delete it, or close a dialog. This is a critical accessibility blocker and a top lawsuit driver.",howToFix:"Every button needs a text label. If you can't put text inside the button (icon-only design), in your platform's button settings look for an 'Aria label' or 'Screen reader text' field — fill it with what the button does ('Close', 'Add to cart', 'Open menu')."},"input-button-name":{whatsWrong:"An <input type=submit> or similar button has no description.",whyItMatters:"Same as button-name — screen-reader users don't know what the button does.",howToFix:"Set the button's 'value' or 'label' to text describing the action ('Submit', 'Subscribe', 'Send')."},"link-name":{whatsWrong:"Some links have no readable text — usually icon-only links.",whyItMatters:"Screen-reader users hear 'link' but not where the link goes. Users navigate by listening to a list of links — useless if every entry is just 'link, link, link'.",howToFix:"In your site editor, for icon-only links (social-media icons, navigation arrows), set an 'Aria label' or 'Title' field describing where it goes ('Follow us on Twitter', 'Next page')."},"empty-button":{whatsWrong:"A button is completely empty — no text, no icon, no description.",whyItMatters:"Both visual and screen-reader users can't tell what an empty button does.",howToFix:"Find empty buttons in your editor (often a leftover from a deleted icon) and either delete them or add text/an icon + description."},"empty-link":{whatsWrong:"A link has no readable text or description.",whyItMatters:"Screen-reader users hear nothing useful; visual users see an empty space they can't tell is clickable.",howToFix:"Same as link-name — add link text or an aria-label describing the destination."},"empty-heading":{whatsWrong:"A heading on this page has no text.",whyItMatters:"Screen-reader users navigate pages by jumping between headings. An empty heading is dead air — they don't know what the section is about.",howToFix:"Find the empty heading in your editor (often a section title that was deleted but the heading element remained) and either delete it or add real heading text."},"document-title":{whatsWrong:"This page's title (in the browser tab) is missing or generic.",whyItMatters:"Tab titles help users who have many tabs open know which one is which. Screen readers also announce the page title when the page loads.",howToFix:"In your platform's page settings or SEO panel, find the 'Page title' field and set it to something descriptive ('Contact Us — YourBusiness', not 'Untitled' or just your business name)."},"html-has-lang":{whatsWrong:"The page doesn't declare what language it's in.",whyItMatters:"Screen readers use this to pick the right voice and pronunciation rules. Without it, English content might be read with a French accent (or vice versa).",howToFix:"In your platform's site settings, find a 'Site language' option and set it (English = en, Spanish = es, etc.). Most modern platforms do this automatically — if it's missing, ask your developer to add lang='en' to the html element."},"html-lang-valid":{whatsWrong:"The page declares a language code that isn't valid.",whyItMatters:"Same as missing language — screen readers can't pick the right voice.",howToFix:"Use a standard ISO language code: en, es, fr, de, ja, zh, pt, etc. Avoid full strings like 'english' — use the two-letter code."},"valid-lang":{whatsWrong:"Text marked as a different language uses an invalid code.",whyItMatters:"Same as above — screen readers can't switch voices for the foreign-language passage.",howToFix:"Use ISO codes (en, fr, es) for the lang attribute on individual elements. This typically requires a developer."},"page-has-heading-one":{whatsWrong:"This page is missing a main heading (H1).",whyItMatters:"Screen-reader users use the H1 to confirm they landed on the right page. The H1 is also a strong SEO signal — Google uses it to understand what the page is about.",howToFix:"Add a clear, descriptive H1 to the top of the page. In website builders, this is usually the 'Title' or 'Page heading' setting. Each page should have exactly one H1."},"heading-order":{whatsWrong:"Heading levels skip — for example, an H2 jumps directly to an H4 with no H3 between them.",whyItMatters:"Screen-reader users navigate by heading levels. Skipped levels suggest missing content and break the page's outline. Confusing for everyone.",howToFix:"In your editor, find the headings that skip levels and either bump them up to the right level (H4 → H3 if no H2 exists between) or insert the missing level. Headings should follow a logical outline like a document outline."},"landmark-one-main":{whatsWrong:"This page has no 'main content' region marked.",whyItMatters:"Screen-reader users press a single shortcut to jump to the main content, skipping menus and headers. Without a marked main region, they have to tab through everything.",howToFix:"Most modern platforms add this automatically. If yours doesn't, ask your developer to wrap the main content in a <main> element."},"landmark-no-duplicate-banner":{whatsWrong:"There are multiple top banners (headers) on the page when there should be one.",whyItMatters:"Screen-reader users get confused by duplicate landmarks — they don't know which is the 'real' header.",howToFix:"Developer fix: 'only one element should have role=banner or be a top-level <header>; remove duplicates'."},"landmark-no-duplicate-contentinfo":{whatsWrong:"There are multiple footer regions on the page when there should be one.",whyItMatters:"Same as duplicate banner — confusing landmark navigation.",howToFix:"Developer fix: 'only one element should have role=contentinfo or be a top-level <footer>; remove duplicates'."},region:{whatsWrong:"Some content on the page isn't inside a recognized region (header, nav, main, footer, aside).",whyItMatters:"Screen-reader users navigate by these regions. Content outside any region can be missed when skimming.",howToFix:"Developer fix: 'wrap orphaned page content in semantic landmark elements (<main>, <aside>, <nav>) so it's reachable via landmark nav'."},bypass:{whatsWrong:"There's no 'skip to main content' link at the top of the page.",whyItMatters:"Keyboard-only users (and some screen-reader users) have to tab through every menu item on every page before reaching the main content. A skip link gives them a single keystroke to jump past the menu.",howToFix:"Most modern themes include a skip link automatically — it's only visible when keyboard-focused. If yours doesn't, ask your developer to add one as the first focusable element on every page."},"aria-required-attr":{whatsWrong:"An element uses a screen-reader role but is missing required information for that role.",whyItMatters:"Custom controls (sliders, tabs, dialogs) need specific extra info to work properly with screen readers. Missing pieces = broken behavior.",howToFix:"Developer fix: 'this role requires additional aria-* attributes; check axe-core docs for the specific role'."},"aria-allowed-attr":{whatsWrong:"An element has a screen-reader hint that doesn't apply to its role.",whyItMatters:"Inappropriate hints can confuse or break screen-reader announcements.",howToFix:"Developer fix: 'this aria-* attribute isn't allowed on this role; remove it or change the role'."},"aria-roles":{whatsWrong:"An element claims to be a type that isn't valid (typo or misuse of a role).",whyItMatters:"Screen readers ignore invalid roles, leaving the element unannounced.",howToFix:"Developer fix: 'this role value isn't recognized; check spelling or use a valid role'."},"aria-valid-attr":{whatsWrong:"An element uses a screen-reader hint that doesn't exist (typo).",whyItMatters:"Same as invalid roles — typos are silently ignored.",howToFix:"Developer fix: 'this aria-* attribute name isn't recognized; check spelling'."},"presentation-role-conflict":{whatsWrong:"An element is marked as decorative but is also focusable or has a description — contradictory.",whyItMatters:"Screen readers handle this inconsistently; some announce it anyway, some don't, leaving users with mixed experiences.",howToFix:"Developer fix: 'role=presentation/none cannot coexist with focusability or aria-label'."},"duplicate-id":{whatsWrong:"Two or more elements on the page share the same internal ID.",whyItMatters:"Some screen reader and skip-link behaviors rely on unique IDs. Duplicates can break label associations and skip-link targets.",howToFix:"Developer fix: 'rename duplicate IDs so each is unique'. Often arises when copying components."},"duplicate-id-aria":{whatsWrong:"An ID referenced by a screen-reader hint exists multiple times.",whyItMatters:"Screen readers may pick the wrong one and announce wrong information.",howToFix:"Developer fix: 'IDs used in aria-labelledby / aria-describedby must be unique'."},"meta-viewport":{whatsWrong:"The page tells mobile browsers users can't zoom in.",whyItMatters:"People with low vision rely on pinch-zoom to read small text. Disabling zoom is a real WCAG failure and a common lawsuit target.",howToFix:"In platform site settings, look for a 'Mobile zoom' or 'Pinch zoom' option and enable it. If your developer added user-scalable=no in a viewport meta tag, ask them to remove it."},"nested-interactive":{whatsWrong:"An interactive element (link, button) is inside another interactive element.",whyItMatters:"Keyboard and screen-reader users can't reliably reach the inner element. Common in 'card-as-link' designs where a button sits inside a clickable card.",howToFix:"Developer fix: 'avoid putting buttons inside links or links inside buttons; use a single interactive element with internal helpers'."},tabindex:{whatsWrong:"Some elements have positive tabindex values, forcing a custom focus order.",whyItMatters:"Custom focus orders are nearly always confusing — focus jumps around unexpectedly. Best practice is to never use positive tabindex.",howToFix:"Developer fix: 'replace tabindex=1/2/3... with tabindex=0 (or remove entirely); use DOM order to control focus order'."},"frame-focusable-content":{whatsWrong:"A frame on the page can't be navigated by keyboard.",whyItMatters:"Keyboard users get stuck — they can't reach interactive content inside the frame.",howToFix:"Developer fix: 'iframes containing interactive content shouldn't have tabindex=-1 on their parent or content'."},"no-focusable-content":{whatsWrong:"An element looks interactive but can't actually receive keyboard focus.",whyItMatters:"Keyboard-only users can't activate the element.",howToFix:"Developer fix: 'replace divs/spans-with-onClick with a real <button>, or add tabindex=0'."},"target-size":{whatsWrong:"Some buttons or links are too small to tap reliably on touch screens.",whyItMatters:"WCAG 2.2 requires touch targets to be at least 24×24 pixels. Small targets are a problem for users with hand tremors, large fingers, or motor disabilities. They're also frustrating for everyone.",howToFix:"In your editor, increase padding around small icon buttons. If your developer is involved, ask them to ensure all interactive elements have minimum 24×24 CSS pixels of clickable area."},"frame-title":{whatsWrong:"An iframe (embedded content) has no title.",whyItMatters:"Screen readers announce frame titles when entering them. Without one, users hear 'frame' with no context.",howToFix:"If using a third-party embed (YouTube, Vimeo, Stripe), most platforms set the title automatically. If yours doesn't, look for a 'Title' or 'Description' field on the embed block."}};function ol(e){const t=nl[e];return t||{whatsWrong:"An accessibility rule failed on this page.",whyItMatters:"Some users — particularly those using screen readers, keyboard-only navigation, or who have low vision or motor disabilities — may have trouble using this part of the page.",howToFix:"Share the technical rule ID with your developer. They can look up the full fix at https://dequeuniversity.com/rules/axe."}}const rl={whatsWrong:"This element appears to have a contrast issue, but it's actually transparent — its parent (or itself) has an opacity below 100%.",whyItMatters:"When something is partially transparent, the colors blend with whatever's behind it, which automated tools see as poor contrast. Most often this happens because the element is part of an entry animation (fade-in on scroll) that hasn't completed when the audit ran. The element will likely look correct once the animation finishes.",howToFix:"Check whether this element is inside a scroll-reveal animation (common patterns: classes like .fade-in, .reveal, .animate-on-scroll; or JavaScript using IntersectionObserver to add a .visible class). If so, this is NOT a real contrast problem — the element will become opaque once the user scrolls past it. If you want the audit to skip these false positives, ensure your site honors prefers-reduced-motion (which serves the final state immediately) or remove the opacity:0 default."};function Fn(e,t){return e==="color-contrast"&&t&&(t.self<.99||t.ancestor<.99)?rl:ol(e)}const oa="inflight:audit";async function Ra(){return(await chrome.storage.local.get(oa))[oa]??null}async function at(e){await chrome.storage.local.set({[oa]:e})}async function dt(){await chrome.storage.local.remove(oa)}async function Hp(){const e=await Ra();e&&e.state==="running"&&await at({...e,state:"interrupted",lastProgressAt:new Date().toISOString()})}async function Ft(e){const t=await Ra();t&&await at({...t,...e,lastProgressAt:new Date().toISOString()})}function _t(){return crypto.randomUUID()}const Yr="https://api.wcagcheckr.com/verify";function Jr(e){return`${Yr}?hash=${encodeURIComponent(e)}`}function qp(e){return`${Yr}#entry=${encodeURIComponent(JSON.stringify(e))}`}const il="offscreen/offscreen.html";let Vt=null;async function sl(){return Vt||(Vt=(async()=>{if(!chrome.offscreen)throw new Error("chrome.offscreen API is unavailable. Update Chrome to 109+.");await chrome.offscreen.hasDocument()||await chrome.offscreen.createDocument({url:il,reasons:[chrome.offscreen.Reason.DOM_PARSER],justification:"Parse PDF accessibility structure tree with pdf.js (no DOM access available in service worker)."})})().catch(e=>{throw Vt=null,e})),Vt}async function cl(e,t){try{await sl()}catch(o){return{ok:!1,source:e,findings:[],pageCount:null,fatalError:`Could not create offscreen document for PDF audit: ${o instanceof Error?o.message:String(o)}`}}const a={type:"OFFSCREEN_PDF_AUDIT_REQUEST",url:e,...(t==null?void 0:t.maxBytes)!==void 0?{maxBytes:t.maxBytes}:{}};let n;try{n=await chrome.runtime.sendMessage(a)}catch(o){return{ok:!1,source:e,findings:[],pageCount:null,fatalError:`Offscreen audit messaging failed: ${o instanceof Error?o.message:String(o)}`}}return!n||n.type!=="OFFSCREEN_PDF_AUDIT_RESPONSE"?{ok:!1,source:e,findings:[],pageCount:null,fatalError:"Offscreen audit returned an unexpected response shape."}:{ok:n.ok,source:n.source,findings:[...n.findings],pageCount:n.pageCount,...n.fatalError?{fatalError:n.fatalError}:{},...n._perPageContrast?{_perPageContrast:n._perPageContrast}:{},...n.aiCandidates?{aiCandidates:n.aiCandidates}:{}}}async function ll(e,t){var a;try{return((a=(await chrome.scripting.executeScript({target:{tabId:e},func:dl,args:[t]}))[0])==null?void 0:a.result)??null}catch{return null}}function dl(e){var k;function t(v){var C,F;const s=v.getAttribute("aria-label");if(s&&s.trim())return s.trim();const x=v.getAttribute("aria-labelledby");if(x){const T=x.split(/\s+/).map(I=>{var D,S;return((S=(D=document.getElementById(I))==null?void 0:D.textContent)==null?void 0:S.trim())??""}).filter(Boolean);if(T.length)return T.join(" ")}if(v instanceof HTMLInputElement||v instanceof HTMLTextAreaElement||v instanceof HTMLSelectElement){if(v.id){const I=document.querySelector(`label[for="${CSS.escape(v.id)}"]`);if((C=I==null?void 0:I.textContent)!=null&&C.trim())return I.textContent.trim()}const T=v.closest("label");if((F=T==null?void 0:T.textContent)!=null&&F.trim())return T.textContent.trim();if(v instanceof HTMLInputElement&&v.placeholder)return v.placeholder}const $=(v.textContent??"").replace(/\s+/g," ").trim();if($)return $.slice(0,120);const A=v.getAttribute("title");return A?A.trim():""}function a(v){if(!v||v.startsWith("javascript:")||v.startsWith("#"))return null;try{return new URL(v,document.baseURI).href}catch{return v}}function n(v){let s=v;for(;s&&s!==document.body;){if(s.tagName==="HEADER")return"header";if(s.tagName==="FOOTER")return"footer";if(s.tagName==="NAV")return"nav";if(s.tagName==="MAIN"||s.getAttribute("role")==="main")return"main";if(s.tagName==="ASIDE"||s.getAttribute("role")==="complementary")return"aside";const x=s.getAttribute("role");if(x==="banner")return"header";if(x==="contentinfo")return"footer";if(x==="navigation")return"nav";s=s.parentElement}return"none"}function o(v){let s=v;for(;s&&s!==document.body;){if(s.tagName==="FOOTER"||s.getAttribute("role")==="contentinfo")return"footer";if(s.tagName==="HEADER"||s.getAttribute("role")==="banner")return"primary";s=s.parentElement}return"utility"}const r=[],i=document.querySelectorAll('nav, [role="navigation"]');for(const v of Array.from(i)){const s=o(v),x=v.querySelectorAll("a[href]");let $=0;for(const A of Array.from(x)){const C=a(A.getAttribute("href")),F=t(A);!F&&!C||r.push({href:C,accessibleName:F,index:$++,region:s})}}const c=[],d=new Set;for(const v of r)v.href&&(d.has(v.href)||(d.add(v.href),c.push({fingerprint:`href:${v.href}`,accessibleName:v.accessibleName,role:"link"})));const l=[{sel:'[data-test-id="logo"]',alias:"logo",role:"link"},{sel:".logo",alias:"logo",role:"link"},{sel:'[aria-label*="menu" i]',alias:"menu-toggle",role:"button"},{sel:'[data-test-id="menu-toggle"]',alias:"menu-toggle",role:"button"},{sel:'[aria-label*="search" i]',alias:"search-toggle",role:"button"},{sel:'[data-test-id="search"]',alias:"search-toggle",role:"button"}];for(const{sel:v,alias:s,role:x}of l){const $=document.querySelector(v);if(!$)continue;const A=`alias:${s}`;d.has(A)||(d.add(A),c.push({fingerprint:A,accessibleName:t($),role:x}))}const p=[],m=/(help|support|contact|faq|chat|live\s*chat)\b/i,u=document.querySelectorAll('a, button, [role="button"], [role="link"]'),g=new Set;for(const v of Array.from(u)){const s=t(v),x=v.getAttribute("aria-label")??"",$=s||x;if(!m.test($))continue;const A=`${$.toLowerCase().slice(0,32)}::${v.tagName}`;g.has(A)||(g.add(A),p.push({label:$.slice(0,80),href:v instanceof HTMLAnchorElement?a(v.getAttribute("href")):null,landmark:n(v)}))}const h=[],f=/(password|cvc|cvv|otp|one[-_\s]?time|security[-_\s]?answer|secret|2fa|mfa)/i,w=document.querySelectorAll("input, textarea, select");for(const v of Array.from(w)){if(v instanceof HTMLInputElement){const C=(v.type||"text").toLowerCase();if(C==="hidden"||C==="submit"||C==="button"||C==="image"||C==="reset")continue}const s=v.getAttribute("name")||v.id||"";if(!s)continue;const x=v instanceof HTMLInputElement?v.type||"text":v instanceof HTMLTextAreaElement?"textarea":"select",$=t(v),A=f.test(s)||f.test($)||x==="password";h.push({name:s,type:x,label:$,isSecurityEssential:A})}let b=!1;if(document.querySelector('[role="progressbar"]')&&(b=!0),!b){const v=document.querySelectorAll('button, a, [role="button"]');let s=0,x=0;for(const $ of Array.from(v)){const A=($.textContent??"").trim();if(/step\s*\d+\s*of\s*\d+/i.test(A)){b=!0;break}/^(next|continue)$/i.test(A)&&s++,/^(previous|prev|back)$/i.test(A)&&x++}s>0&&x>0&&(b=!0)}return{url:e,title:(document.title||(((k=document.querySelector("h1"))==null?void 0:k.textContent)??"")).trim(),navLinks:r,sharedComponents:c,helpMechanisms:p,formFields:h,isMultiStep:b}}const ul=`Respond ONLY with a JSON object — no markdown, no preamble:
379
- {
380
- "verdict": "pass" | "fail" | "uncertain",
381
- "reasoning": "one-sentence explanation",
382
- "confidence": 0.0 to 1.0
383
- }`,jt=`
384
-
385
- Previous verdict on this page: {{verdict}} ({{confidence}}% confidence). Reasoning: "{{reasoning}}". Keep the same verdict unless concrete new evidence has changed.
386
- `,hl={version:0,jsonOutputInstructions:ul,altText:{template:`You are an accessibility auditor. Judge whether the alt text describes the image.
387
-
388
- Alt: {{alt}}
389
- {{surroundingContextLine}}
390
-
391
- Pass if descriptive; fail if missing, generic, or filename-style; uncertain if you cannot tell.
392
-
393
- {{jsonOutputInstructions}}`,maxTokens:300},heading:{template:`You are an accessibility auditor. Judge whether the heading describes its section.
394
-
395
- Heading: {{headingText}}
396
- Section content: {{sectionContent}}
397
-
398
- Pass if the heading describes what follows; fail if generic or unrelated; uncertain if too short to judge.
399
-
400
- {{jsonOutputInstructions}}`,maxTokens:250},sensoryLanguage:{template:`You are an accessibility auditor. Judge whether the instruction relies only on sensory cues (shape, color, position).
401
-
402
- Instruction: {{instructionText}}
403
-
404
- Pass if a programmatic identifier accompanies sensory cues; fail if only sensory; uncertain if ambiguous.
405
-
406
- {{jsonOutputInstructions}}`,maxTokens:250},ariaSemantics:{template:`You are an accessibility auditor. Judge whether the ARIA role matches the element's apparent purpose.
407
-
408
- Element: {{elementHtml}}
409
- Computed role: {{computedRole}}
410
- Surrounding: {{surroundingHtml}}
411
-
412
- Pass if role matches behavior; fail if mismatched; uncertain if behavior unclear from static markup.
413
-
414
- {{jsonOutputInstructions}}`,maxTokens:350},imageOfText:{template:`You are an accessibility auditor. Judge whether the image contains substantial baked-in text that should be HTML text.
415
-
416
- {{accessibleNameLine}}
417
-
418
- Pass if no substantial text (or logo / unavoidable artifact); fail if body text / headings / labels are baked in; uncertain if low-res or ambiguous.
419
-
420
- {{jsonOutputInstructions}}`,maxTokens:300},colorOnlyMeaning:{template:`You are an accessibility auditor. Judge whether the element conveys meaning only through color.
421
-
422
- Element: {{elementHtml}}
423
- Context: {{contextDescription}}
424
-
425
- Pass if a non-color cue (label / icon / text / aria-label) exists; fail if color is the only signal; uncertain if ambiguous.
426
-
427
- {{jsonOutputInstructions}}`,maxTokens:250},genericLinkText:{template:`You are an accessibility auditor. Judge whether the link purpose is clear from its text or context.
428
-
429
- Link text: {{linkText}}
430
- Surrounding: {{surroundingText}}
431
-
432
- Pass if link text alone OR with context clarifies the destination; fail if generic AND context does not clarify; uncertain if borderline.
433
-
434
- {{jsonOutputInstructions}}`,maxTokens:250},wallOfText:{template:`You are an accessibility auditor. Judge whether this block is an unreadable wall of text.
435
-
436
- Block (first 1200 chars): {{blockText}}
437
- Structural children: {{structuralChildrenCount}}
438
-
439
- Pass if short OR adequately structured; fail if long prose with no breaks; uncertain if borderline.
440
-
441
- {{jsonOutputInstructions}}`,maxTokens:250},languageMismatch:{template:`You are an accessibility auditor. Judge whether the declared language matches the page content.
442
-
443
- Declared: {{declaredLang}}
444
- Content sample: {{bodyTextSample}}
445
-
446
- Pass if declared matches content; fail if mismatched OR no declaration with non-trivial content; uncertain if too short / multilingual.
447
-
448
- {{jsonOutputInstructions}}`,maxTokens:250},focusVisible:{template:`You are an accessibility auditor evaluating focus-visibility (WCAG 2.4.7).
449
-
450
- Page: {{pageUrl}}
451
- {{sampleCount}} screenshot(s) above; each shows a focused element with a metadata line (selector, role, name, rect, computed outline / box-shadow styles).
452
-
453
- Per image, decide whether the focused element shows a visible focus indicator (outline, box-shadow, border / background change relative to baseline).
454
- - "pass" = every sample shows a clearly visible indicator.
455
- - "fail" = one or more samples have no visible indicator (typically outline:none with no compensating treatment).
456
- - "uncertain" = images are unreadable or rects do not match visible elements.
457
-
458
- {{jsonOutputInstructions}}`,maxTokens:600},keyboardTrap:{template:`You are an accessibility auditor evaluating keyboard-trap risk (WCAG 2.1.2 — No Keyboard Trap).{{anchor}}
459
-
460
- Page: {{pageUrl}}
461
-
462
- A robot walked the page with Tab, then Shift-Tab. Findings below.
463
-
464
- Forward walk (Tab, in order):
465
- {{forwardSequence}}
466
-
467
- Reverse walk (Shift+Tab, in order — should walk back through the forward sequence):
468
- {{reverseSequence}}
469
-
470
- Stuck-run detection (selector appearing 3+ times in a row in the forward walk):
471
- {{stuckRuns}}
472
-
473
- Reverse mismatches (expected vs. actual reverse-walk positions):
474
- {{reverseMismatches}}
475
-
476
- Verdict:
477
- - "pass" = focus moves freely forward and backward. No stuck runs. Reverse walk mirrors forward order.
478
- - "fail" = clear trap evidence: stuck runs, Shift-Tab can't escape a region, or reverse walk diverges significantly.
479
- - "uncertain" = too few tabbable elements (<3) to judge OR data is inconsistent.
480
-
481
- {{jsonOutputInstructions}}`,maxTokens:400,anchorTemplate:jt},nonTextContrast:{template:`You are an accessibility auditor evaluating non-text contrast (WCAG 1.4.11 — Non-text Contrast, Level AA).
482
-
483
- A screenshot of {{pageUrl}} is attached.{{anchor}}
484
-
485
- WCAG 1.4.11 requires ≥3:1 contrast against adjacent colors for: UI components (button borders/backgrounds, form input borders, focus indicators, checkbox/radio borders, state changes) and graphical objects (icons that convey meaning, status indicators).
486
-
487
- Exempt — do NOT flag: pure decoration (thin dividers, gradient fades, ornamental flourishes), logos / brand wordmarks, icons with redundant adjacent text labels, disabled / inactive controls, hero / banner imagery, well-known affordance icons (hamburger / kebab / overflow).
488
-
489
- Verdict:
490
- - "pass" = every visible UI component / meaningful icon has distinguishable contrast against its surroundings.
491
- - "fail" = ≥2 visible UI components in the "DOES cover" list are below 3:1 against their adjacent surroundings. Name each specifically.
492
- - "uncertain" = screenshot is unreadable OR one borderline case that can't be confirmed.
493
-
494
- When in doubt, prefer pass or uncertain over fail. Decoration misclassification is the #1 false-positive trap.
495
-
496
- {{jsonOutputInstructions}}`,maxTokens:1500,anchorTemplate:jt},readingOrder:{template:`You are an accessibility auditor evaluating reading-order quality (WCAG 1.3.2 — Meaningful Sequence).{{anchor}}
497
-
498
- A screenshot of {{pageUrl}} is attached. A heuristic compared DOM source order to visual position and flagged {{flaggedCount}} element(s) whose DOM index diverges from visual index:
499
- {{issuesList}}
500
-
501
- Evaluate whether the flagged divergences represent REAL reading-order breaks or normal multi-column / banked layout patterns. Multi-column / newspaper layouts, skip-links, caption-before-image, modal portals, and grouped card layouts are legitimate divergences.
502
-
503
- Verdict:
504
- - "pass" = every flagged divergence fits a legitimate pattern. Multi-column / banked layouts default to PASS.
505
- - "fail" = ≥1 flagged divergence is a real reading-order break (out-of-order paragraphs, captions DOM-far from referenced content, form labels DOM-after inputs).
506
- - "uncertain" = screenshot missing OR layout too ambiguous to judge.
507
-
508
- When in doubt, prefer "uncertain" over "fail". Multi-column false positives are the most common trap.
509
-
510
- {{jsonOutputInstructions}}`,maxTokens:1500,anchorTemplate:jt},focusOrder:{template:`You are an accessibility auditor evaluating tab-order quality (WCAG 2.4.3 — Focus Order).{{anchor}}
511
-
512
- A screenshot of {{pageUrl}} is attached. The page's keyboard-tabbable elements were walked in order; the sequence below groups items by visual row ({{rowBucketPx}}px buckets) so sub-pixel y-noise can't cause a fail.
513
-
514
- Tab sequence (grouped by visual row):
515
- {{seq}}
516
-
517
- Evaluate whether the focus order preserves the meaning + operability of the page. Within a row, x-order is what matters; across rows, top-to-bottom is expected but multi-column, banked, sticky-header, and footer-jump-back patterns are common and legitimate.
518
-
519
- Strict-fail signals (require multiple):
520
- - A region's INTERNAL items are scrambled (card title last, action button first within the same row group).
521
- - A SINGLE element is skipped (interactive but never receives focus).
522
- - Focus enters a region, leaves, then re-enters non-contiguously.
523
- - Positive tabindex values producing observably out-of-source-order focus.
524
-
525
- Verdict:
526
- - "pass" = order is logical within regions. Multi-region pages PASS by default unless internal scrambling is obvious.
527
- - "fail" = ≥2 strict-fail signals. Cite specific items by ordinal.
528
- - "uncertain" = screenshot missing, sequence too short (<5 items), or layout is ambiguous.
529
-
530
- When in doubt, prefer "uncertain" over "fail". Multi-column / banked layouts are the most common false-fail trap.
531
-
532
- {{jsonOutputInstructions}}`,maxTokens:1500,anchorTemplate:jt},labelInName:{template:`You are an accessibility auditor evaluating WCAG 2.5.3 (Label in Name) for {{pageUrl}}.
533
-
534
- WCAG 2.5.3 says: when an interactive control has BOTH visible text AND a programmatic accessible name, the accessible name must contain the visible text (case-insensitive, leading non-text characters ignored). Required for speech-recognition users.
535
-
536
- A screenshot is attached for visual context.
537
-
538
- The candidates below failed a strict substring match. Classify each as a genuine 2.5.3 failure OR an acceptable variation (icon-prefix, smart-quote / hyphen variation, number formatting, truncation, plural/singular variations are common edge cases):
539
- {{candidatesList}}
540
-
541
- Verdict over the whole page:
542
- - "pass" = every candidate is an acceptable variation.
543
- - "fail" = at least one candidate is a genuine 2.5.3 failure that would break speech recognition.
544
- - "uncertain" = screenshot unreadable OR ambiguity cannot be resolved without page interaction.
545
-
546
- Cite candidates by ordinal in the reasoning, especially when calling fail.
547
-
548
- {{jsonOutputInstructions}}`,maxTokens:1500},focusOrderFallback:{template:`You are an accessibility auditor making a cascade-fallback judgment on tab-order quality (WCAG 2.4.3 — Focus Order).
549
-
550
- Context: primary AI judgment was UNCERTAIN ("{{primaryUncertainReason}}"). WCAG 2.1.2 No Keyboard Trap PASSED on the same DOM. A programmatic multi-column-layout detector found NO conventional layout pattern.
551
-
552
- Your narrower job: decide whether the tab sequence is a known false-positive pattern from the LONG TAIL (custom JS focus management, roving tabindex composite widgets, sticky sidebars, skip-links, modal traps, table-based layouts, absolute-positioned columns, header navigation wrap, carousels) OR a real fail (positive tabindex, scrambled region, skipped interactive element, non-contiguous region re-entry).
553
-
554
- Tab sequence (grouped by visual row, {{rowBucketPx}}px buckets):
555
- {{seq}}
556
-
557
- Screenshot of {{pageUrl}} attached.
558
-
559
- DECISIVENESS BIAS: the primary already returned uncertain. If you also return uncertain, the system escalates to FAIL + human verification. Only return uncertain when the screenshot is unreadable, sequence is empty / too short (<3 items), or you genuinely cannot tell.
560
-
561
- {{jsonOutputInstructions}}`,maxTokens:1500}};function Xr(e,t){return e.replace(/\{\{(\w+)\}\}/g,(a,n)=>{const o=t[n];return o??""})}function Qr(){var e;return((e=mr())==null?void 0:e.aiPrompts)??hl}function ye(e,t){const a=Qr(),n=e(a),o={...t,jsonOutputInstructions:a.jsonOutputInstructions};return{text:Xr(n.template,o),maxTokens:n.maxTokens}}function Bt(e,t){if(!t)return"";const a=e(Qr());return a.anchorTemplate?Xr(a.anchorTemplate,{verdict:t.verdict.toUpperCase(),confidence:(t.confidence*100).toFixed(0),reasoning:t.reasoning.slice(0,400).replace(/"/g,"'")}):""}const pl={input:3/1e6,output:15/1e6},fl={input:1/1e6,output:5/1e6},gl="claude-sonnet-4-6",ml="https://api.anthropic.com/v1/messages",bl="2023-06-01";function yl(e){const t=e.model||gl,a=t.includes("haiku")?fl:pl;return{providerId:"anthropic",async judgeAltText({imageUrl:n,alt:o,surroundingContext:r,signal:i}){const c=await go(n,i);if(!c)return mo("Could not fetch image to verify alt text",0,t);const{text:d,maxTokens:l}=ye(m=>m.altText,{alt:o?`"${o}"`:"(empty / missing)",surroundingContextLine:r?`
562
- Nearby page context: ${r.slice(0,500)}`:""}),p=await se({apiKey:e.apiKey,model:t,maxTokens:l,signal:i,messages:[{role:"user",content:[{type:"image",source:{type:"base64",media_type:c.mediaType,data:c.data}},{type:"text",text:d}]}]});return me(p,a)},async judgeHeading({headingText:n,sectionContent:o,signal:r}){const{text:i,maxTokens:c}=ye(l=>l.heading,{headingText:n,sectionContent:o.slice(0,800)}),d=await se({apiKey:e.apiKey,model:t,maxTokens:c,signal:r,messages:[{role:"user",content:[{type:"text",text:i}]}]});return me(d,a)},async judgeSensoryLanguage({instructionText:n,signal:o}){const{text:r,maxTokens:i}=ye(d=>d.sensoryLanguage,{instructionText:n.slice(0,800)}),c=await se({apiKey:e.apiKey,model:t,maxTokens:i,signal:o,messages:[{role:"user",content:[{type:"text",text:r}]}]});return me(c,a)},async judgeAriaSemantics({elementHtml:n,computedRole:o,surroundingHtml:r,signal:i}){const{text:c,maxTokens:d}=ye(p=>p.ariaSemantics,{elementHtml:n.slice(0,600),computedRole:o,surroundingHtml:r.slice(0,500)}),l=await se({apiKey:e.apiKey,model:t,maxTokens:d,signal:i,messages:[{role:"user",content:[{type:"text",text:c}]}]});return me(l,a)},async judgeImageOfText({imageUrl:n,accessibleName:o,signal:r}){const i=await go(n,r);if(!i)return mo("Could not fetch image to inspect for embedded text",0,t);const{text:c,maxTokens:d}=ye(p=>p.imageOfText,{accessibleNameLine:o?`
563
- Accessible name (alt / aria-label) of this image: "${o.slice(0,200)}"`:""}),l=await se({apiKey:e.apiKey,model:t,maxTokens:d,signal:r,messages:[{role:"user",content:[{type:"image",source:{type:"base64",media_type:i.mediaType,data:i.data}},{type:"text",text:c}]}]});return me(l,a)},async judgeColorOnlyMeaning({elementHtml:n,contextDescription:o,signal:r}){const{text:i,maxTokens:c}=ye(l=>l.colorOnlyMeaning,{elementHtml:n.slice(0,800),contextDescription:o.slice(0,400)}),d=await se({apiKey:e.apiKey,model:t,maxTokens:c,signal:r,messages:[{role:"user",content:[{type:"text",text:i}]}]});return me(d,a)},async judgeGenericLinkText({linkText:n,surroundingText:o,signal:r}){const{text:i,maxTokens:c}=ye(l=>l.genericLinkText,{linkText:n.slice(0,200),surroundingText:o.slice(0,800)}),d=await se({apiKey:e.apiKey,model:t,maxTokens:c,signal:r,messages:[{role:"user",content:[{type:"text",text:i}]}]});return me(d,a)},async judgeWallOfText({blockText:n,structuralChildrenCount:o,signal:r}){const{text:i,maxTokens:c}=ye(l=>l.wallOfText,{blockText:n.slice(0,1200),structuralChildrenCount:String(o)}),d=await se({apiKey:e.apiKey,model:t,maxTokens:c,signal:r,messages:[{role:"user",content:[{type:"text",text:i}]}]});return me(d,a)},async judgeLanguageMismatch({declaredLang:n,bodyTextSample:o,signal:r}){const{text:i,maxTokens:c}=ye(l=>l.languageMismatch,{declaredLang:n||"(none / empty)",bodyTextSample:o.slice(0,1200)}),d=await se({apiKey:e.apiKey,model:t,maxTokens:c,signal:r,messages:[{role:"user",content:[{type:"text",text:i}]}]});return me(d,a)},async suggestColorFix(n){const o=await se({apiKey:e.apiKey,model:t,maxTokens:600,messages:[{role:"user",content:[{type:"text",text:El(n)}]}]});return Ol(o,a)},async generateExecutiveSummary(n){const o=await se({apiKey:e.apiKey,model:t,maxTokens:800,messages:[{role:"user",content:[{type:"text",text:Rl(n)}]}]});return Nl(o,a)},async resolveAxeIncomplete(n){const o=await se({apiKey:e.apiKey,model:t,maxTokens:400,signal:n.signal,messages:[{role:"user",content:[{type:"text",text:Ml(n)}]}]});return Dl(o,a,t)},async judgeFocusVisible({pageUrl:n,samples:o,signal:r}){const i=[];for(const p of o){const m=/^data:(image\/[a-z]+);base64,(.+)$/i.exec(p.screenshot);m&&(i.push({type:"image",source:{type:"base64",media_type:m[1],data:m[2]}}),i.push({type:"text",text:`Image #${p.ordinal} — selector: ${p.selector} — role: ${p.role||"(none)"} — name: "${p.name||"(no name)"}" — rect: x=${Math.round(p.rect.x)} y=${Math.round(p.rect.y)} w=${Math.round(p.rect.width)} h=${Math.round(p.rect.height)} — outline: ${p.focusStyle.outlineStyle} ${p.focusStyle.outlineWidth} ${p.focusStyle.outlineColor} (offset ${p.focusStyle.outlineOffset}) — box-shadow: ${p.focusStyle.boxShadow||"none"}`}))}const{text:c,maxTokens:d}=ye(p=>p.focusVisible,{pageUrl:n,sampleCount:String(o.length)});i.push({type:"text",text:c});const l=await se({apiKey:e.apiKey,model:t,maxTokens:d,signal:r,messages:[{role:"user",content:i}]});return me(l,a)},async judgeConsistencyDivergence({wcagCriterion:n,ruleId:o,description:r,details:i,pages:c,signal:d}){const l=$l(n,o,r,i,c),p=await se({apiKey:e.apiKey,model:t,maxTokens:500,signal:d,messages:[{role:"user",content:[{type:"text",text:l}]}]});return me(p,a)},async judgeKeyboardTrap({pageUrl:n,forwardSequence:o,reverseSequence:r,stuckRuns:i,reverseMismatches:c,previousVerdict:d,signal:l}){const p=o.map((b,k)=>` ${k+1}. ${b}`).join(`
564
- `)||" (no tabbable elements found)",m=r.map((b,k)=>` ${k+1}. ${b}`).join(`
565
- `)||" (Shift-Tab moved to body / no reverse path)",u=i.length===0?" (none detected)":i.map(b=>` - ${b}`).join(`
566
- `),g=c.length===0?" (none — Shift-Tab cleanly reversed the forward order)":c.map(b=>` - position ${b.index}: expected ${b.expected}, got ${b.actual}`).join(`
567
- `),{text:h,maxTokens:f}=ye(b=>b.keyboardTrap,{pageUrl:n,anchor:Bt(b=>b.keyboardTrap,d),forwardSequence:p,reverseSequence:m,stuckRuns:u,reverseMismatches:g}),w=await se({apiKey:e.apiKey,model:t,maxTokens:f,signal:l,messages:[{role:"user",content:[{type:"text",text:h}]}]});return me(w,a)},async judgeNonTextContrast({pageUrl:n,pageScreenshot:o,previousVerdict:r,signal:i}){const{text:c,maxTokens:d}=ye(u=>u.nonTextContrast,{pageUrl:n,anchor:Bt(u=>u.nonTextContrast,r)}),l=[],p=/^data:(image\/[a-z]+);base64,(.+)$/i.exec(o);p&&l.push({type:"image",source:{type:"base64",media_type:p[1],data:p[2]}}),l.push({type:"text",text:c});const m=await se({apiKey:e.apiKey,model:t,maxTokens:d,signal:i,messages:[{role:"user",content:l}]});return me(m,a)},async judgeReadingOrder({pageUrl:n,pageScreenshot:o,flaggedIssues:r,previousVerdict:i,signal:c}){const d=r.map(g=>` - DOM #${g.domIndex} → Visual #${g.visualIndex} | selector ${g.selector} | at (x=${Math.round(g.rect.x)}, y=${Math.round(g.rect.y)}, w=${Math.round(g.rect.w)}, h=${Math.round(g.rect.h)}) | text: "${g.textSnippet.slice(0,80).replace(/"/g,"'")}"`).join(`
568
- `),{text:l,maxTokens:p}=ye(g=>g.readingOrder,{pageUrl:n,anchor:Bt(g=>g.readingOrder,i),flaggedCount:String(r.length),issuesList:d}),m=[];if(o){const g=/^data:(image\/[a-z]+);base64,(.+)$/i.exec(o);g&&m.push({type:"image",source:{type:"base64",media_type:g[1],data:g[2]}})}m.push({type:"text",text:l});const u=await se({apiKey:e.apiKey,model:t,maxTokens:p,signal:c,messages:[{role:"user",content:m}]});return me(u,a)},async judgeFocusOrder({pageUrl:n,pageScreenshot:o,tabSequence:r,previousVerdict:i,signal:c}){const{text:d,maxTokens:l}=ye(u=>u.focusOrder,{pageUrl:n,anchor:Bt(u=>u.focusOrder,i),rowBucketPx:String(ra),seq:po(r)}),p=[];if(o){const u=/^data:(image\/[a-z]+);base64,(.+)$/i.exec(o);u&&p.push({type:"image",source:{type:"base64",media_type:u[1],data:u[2]}})}p.push({type:"text",text:d});const m=await se({apiKey:e.apiKey,model:t,maxTokens:l,signal:c,messages:[{role:"user",content:p}]});return me(m,a)},async judgeLabelInName({pageUrl:n,pageScreenshot:o,candidates:r,signal:i}){const c=r.map((u,g)=>`${g+1}. [${u.role}] selector=${u.selector}
569
- visibleText: "${u.visibleText}"
570
- accessibleName: "${u.accessibleName}"`).join(`
571
- `),{text:d,maxTokens:l}=ye(u=>u.labelInName,{pageUrl:n,candidatesList:c}),p=[];if(o){const u=/^data:(image\/[a-z]+);base64,(.+)$/i.exec(o);u&&p.push({type:"image",source:{type:"base64",media_type:u[1],data:u[2]}})}p.push({type:"text",text:d});const m=await se({apiKey:e.apiKey,model:t,maxTokens:l,signal:i,messages:[{role:"user",content:p}]});return me(m,a)},async judgeFocusOrderFallback({pageUrl:n,pageScreenshot:o,tabSequence:r,primaryUncertainReason:i,signal:c}){const{text:d,maxTokens:l}=ye(u=>u.focusOrderFallback,{pageUrl:n,primaryUncertainReason:i.replace(/"/g,"'").slice(0,600),rowBucketPx:String(ra),seq:po(r)}),p=[];if(o){const u=/^data:(image\/[a-z]+);base64,(.+)$/i.exec(o);u&&p.push({type:"image",source:{type:"base64",media_type:u[1],data:u[2]}})}p.push({type:"text",text:d});const m=await se({apiKey:e.apiKey,model:t,maxTokens:l,signal:c,messages:[{role:"user",content:p}]});return me(m,a)}}}function po(e){return Tl(e).map(a=>{const n=a.items.map(o=>` ${o.ordinal}. [${o.role||o.selector.split(" ").pop()||"?"}] "${o.name||"(no name)"}" — selector ${o.selector} — x=${Math.round(o.rect.x)}, w=${Math.round(o.rect.width)}`).join(`
572
- `);return` Row ~y=${a.row*ra} (${a.items.length} item${a.items.length===1?"":"s"}):
573
- ${n}`}).join(`
574
- `)}class Ot extends Error{constructor(){super("Anthropic API: canceled by caller"),this.name="ExternalAbortError"}}const Zr=3e4,fo=3,wl=1e4;function vl(e){return e===429||e>=500}function Al(e){return e instanceof Error?e.name==="TimeoutError"||e.name==="AbortError"||e instanceof TypeError:!1}function kl(e,t){if(!t)return e;if(typeof AbortSignal.any=="function")return AbortSignal.any([e,t]);const a=new AbortController,n=()=>a.abort();return e.aborted?a.abort():e.addEventListener("abort",n,{once:!0}),t.aborted?a.abort():t.addEventListener("abort",n,{once:!0}),a.signal}async function xl(e){var o,r;const t=AbortSignal.timeout(Zr),a=kl(t,e.signal);let n;try{n=await fetch(ml,{method:"POST",headers:{"x-api-key":e.apiKey,"anthropic-version":bl,"content-type":"application/json","anthropic-dangerous-direct-browser-access":"true"},body:JSON.stringify({model:e.model,max_tokens:e.maxTokens,messages:e.messages,temperature:e.temperature??0}),signal:a})}catch(i){throw(o=e.signal)!=null&&o.aborted?new Ot:i}if(!n.ok){const c=((r=(await n.json().catch(()=>({}))).error)==null?void 0:r.message)??`${n.status} ${n.statusText}`,d=new Error(`Anthropic API: ${c}`);throw d.status=n.status,d}return await n.json()}async function se(e){var a;let t=null;for(let n=1;n<=fo;n++){if((a=e.signal)!=null&&a.aborted)throw new Ot;try{return await xl(e)}catch(o){if(o instanceof Ot)throw o;const r=o.status;if(!(Al(o)||typeof r=="number"&&vl(r))||n===fo)throw o instanceof Error&&(o.name==="TimeoutError"||o.name==="AbortError")?new Error(`Anthropic API: timed out after ${Zr/1e3}s on each of ${n} attempt${n===1?"":"s"}`):o;t=o instanceof Error?o:new Error(String(o)),await Il(n*1e3,e.signal)}}throw t??new Error("Anthropic API: all retries failed")}function Il(e,t){return new Promise((a,n)=>{if(t!=null&&t.aborted){n(new Ot);return}const o=setTimeout(()=>{t==null||t.removeEventListener("abort",r),a()},e),r=()=>{clearTimeout(o),n(new Ot)};t==null||t.addEventListener("abort",r,{once:!0})})}async function go(e,t){var r,i;const a=new AbortController,n=setTimeout(()=>a.abort(),wl),o=()=>a.abort();t&&(t.aborted?a.abort():t.addEventListener("abort",o,{once:!0}));try{const c=await fetch(e,{signal:a.signal});if(!c.ok)return null;const d=((i=(r=c.headers.get("content-type"))==null?void 0:r.split(";")[0])==null?void 0:i.trim())??"image/png";if(!d.startsWith("image/")||d!=="image/jpeg"&&d!=="image/png"&&d!=="image/gif"&&d!=="image/webp")return null;const l=await c.arrayBuffer();let p="";const m=new Uint8Array(l),u=32768;for(let g=0;g<m.length;g+=u)p+=String.fromCharCode(...m.slice(g,g+u));return{data:btoa(p),mediaType:d}}catch{return null}finally{clearTimeout(n),t&&t.removeEventListener("abort",o)}}function me(e,t){var r;const a=((r=e.content.find(i=>i.type==="text"))==null?void 0:r.text)??"",n=Sl(a),o=e.usage.input_tokens*t.input+e.usage.output_tokens*t.output;return{verdict:n.verdict,reasoning:n.reasoning,confidence:n.confidence,costUsd:o,model:e.model}}function Sl(e){const a=e.replace(/```(?:json)?/g,"").trim().match(/\{[\s\S]*\}/);if(!a)return{verdict:"uncertain",reasoning:"Model returned no parseable JSON",confidence:0};try{const n=JSON.parse(a[0]),o=n.verdict==="pass"||n.verdict==="fail"?n.verdict:"uncertain",r=(n.reasoning??"").trim().slice(0,600),i=typeof n.confidence=="number"?n.confidence:.5,c=Math.max(0,Math.min(1,i));return{verdict:o,reasoning:r,confidence:c}}catch{return{verdict:"uncertain",reasoning:"Model returned invalid JSON",confidence:0}}}function mo(e,t,a){return{verdict:"uncertain",reasoning:e,confidence:0,costUsd:t,model:a,unverifiable:!0}}const Cl=`
575
- Respond ONLY with a single JSON object — no preamble, no markdown:
576
- { "verdict": "pass" | "fail" | "uncertain", "reasoning": "1-3 sentences", "confidence": 0.0-1.0 }
577
- `.trim();function $l(e,t,a,n,o){const r=o.map((c,d)=>` ${d+1}. ${c.url}
578
- ${c.evidence}`).join(`
579
- `);return`You are an accessibility auditor evaluating whether a heuristic finding is a real WCAG violation or a false positive.
580
-
581
- A site-crawl heuristic flagged this divergence:
582
-
583
- Criterion: ${e}
584
- Rule: ${t}
585
- Summary: ${a}
586
-
587
- Diagnostic details:
588
- ${n}
589
-
590
- Pages involved:
591
- ${r}
592
-
593
- WCAG context for this criterion:
594
- ${{"3.2.3":"WCAG 3.2.3 Consistent Navigation (AA) — navigational mechanisms repeated on multiple pages occur in the same relative order each time they are repeated. Allowed exceptions: locale-driven reorders (RTL vs LTR), additions (one page has extra links), legitimate dynamic personalization where ALL users see the same order on the same page state.","3.2.4":"WCAG 3.2.4 Consistent Identification (AA) — components with the same functionality within a set of pages are identified consistently (same accessible name). Allowed exceptions: language differences in localized sites, intentional brand variation per page-section.","3.2.6":"WCAG 3.2.6 Consistent Help (A, WCAG 2.2) — when a help mechanism is present on multiple pages, it occurs in the same relative order to other page content. Allowed exceptions: pages where help is genuinely contextual to a different function.","3.3.7":"WCAG 3.3.7 Redundant Entry (A, WCAG 2.2) — information previously entered by the user in a multi-step process is auto-populated OR available for the user to select, unless re-entry is essential (security verification, password confirmation, intentional change confirmation)."}[e]}
595
-
596
- Your job: decide whether this is a real WCAG ${e} divergence that the developer needs to fix, or a false positive the heuristic shouldn't have flagged.
597
-
598
- Common false-positive patterns to be aware of:
599
- - Language switchers reordering nav per locale (legitimate)
600
- - Logged-in vs logged-out menus (different functionality, not a divergence)
601
- - A/B test variants (intentional)
602
- - Multi-tenant pages where each tenant has its own brand naming (legitimate)
603
- - Dynamic personalization where the order varies per-user but is consistent for THAT user (debatable but generally not a fail)
604
- - Contextual help that legitimately belongs in a different position (e.g., inline help in a multi-step form vs. global help in the footer)
605
-
606
- Verdict mapping:
607
- - "pass" = false positive. The flagged pattern is intentional, expected, or otherwise not a WCAG violation. Suppress this finding.
608
- - "fail" = real divergence. This IS a WCAG ${e} violation and should be reported to the user.
609
- - "uncertain" = the evidence is genuinely ambiguous; surface the finding so a human can decide.
610
-
611
- ${Cl}`}const ra=32;function Tl(e){const t=[];let a=null;for(const n of e){const o=Math.round(n.rect.y/ra);a===null||a.row!==o?(a={row:o,items:[n]},t.push(a)):a.items.push(n)}return t}function El(e){const t=e.targetLevel==="AAA"?e.fontSize>=18.66||e.fontSize>=14&&e.fontWeight>=700?"4.5":"7.0":e.fontSize>=18.66||e.fontSize>=14&&e.fontWeight>=700?"3.0":"4.5";return`You are a color accessibility expert. Suggest replacement colors that fix a contrast failure while preserving design intent.
612
-
613
- Current pair (FAILING):
614
- - Foreground: ${e.foreground}
615
- - Background: ${e.background}
616
- - Font size: ${e.fontSize}px, weight: ${e.fontWeight}
617
- - Required contrast for WCAG ${e.targetLevel}: ${t}:1
618
-
619
- ${e.paletteHints&&e.paletteHints.length>0?`Available palette tokens (prefer these to keep brand cohesion):
620
- ${e.paletteHints.slice(0,30).map(a=>` - ${a}`).join(`
621
- `)}`:"No palette tokens discovered. Stay close in hue + saturation to the original colors."}
622
-
623
- ${e.brandIntent?`Brand intent: ${e.brandIntent}`:""}
624
-
625
- Suggest up to 3 candidate replacement pairs. Each candidate should:
626
- 1. Pass the required ${t}:1 contrast (verify your math).
627
- 2. Stay close in hue to the original (don't swap a warm palette for a cool one).
628
- 3. Prefer modifying ONE color (foreground OR background) over both, unless the original is severely off.
629
- 4. If palette tokens are available, prefer in-palette colors.
630
-
631
- Respond ONLY with a JSON object — no preamble, no markdown:
632
- {
633
- "verdict": "suggested" | "no-suggestion",
634
- "candidates": [
635
- { "foreground": "#hexHEX", "background": "#hexHEX", "contrast": 4.6, "rationale": "1 sentence" }
636
- ],
637
- "reasoning": "1-3 sentences explaining your overall approach or why no suggestions are possible"
638
- }`}function Rl(e){return`You are an accessibility auditor writing the executive summary for an automated audit report.
639
-
640
- Audience: ${e.framing==="defense"?"an internal stakeholder team (engineering + legal + risk-management)":e.framing==="evidence"?"an attorney or accessibility advocate considering a notice-and-cure step":"a non-technical site owner who needs to understand their accessibility status"}.
641
- Framing: ${e.framing} report.
642
-
643
- Audit data:
644
- - Page audited: ${e.pageUrl}
645
- - Audit date: ${e.auditDate}
646
- - Compliance grade: ${e.grade}
647
- - Risk tier: ${e.riskTier}
648
- - Severity totals: ${e.totals.critical} critical, ${e.totals.serious} serious, ${e.totals.moderate} moderate, ${e.totals.minor} minor (unique: ${e.totals.unique})
649
- - Top categories driving risk: ${e.riskDrivers.length>0?e.riskDrivers.join(", "):"none flagged"}
650
- ${e.priorAuditCount!==void 0&&e.priorAuditCount>0?`- Prior audit count in record: ${e.priorAuditCount} (ongoing-diligence context)`:""}
651
-
652
- Tone:
653
- - Plain-spoken. No legalese, no marketing hype.
654
- - Direct about risk without alarmism.
655
- - "Defense" framing: emphasize good-faith remediation effort + that this audit ran three evaluation layers (axe-core rule-based, wcagcheckr DOM analyzers, AI walkthroughs) covering all 50 WCAG 2.1 AA criteria structurally; human spot-checks remain advisable for content-meaning criteria (caption accuracy, alt-text correctness, sensory cues).
656
- - "Evidence" framing: present findings objectively + suggest notice-and-cure procedures over immediate litigation.
657
- - "Owner-report" framing: explain what the findings mean for the site owner in everyday terms, no code talk.
658
-
659
- Constraints:
660
- - Do NOT suggest specific dollar amounts, settlement figures, or legal predictions.
661
- - Do NOT claim the audit proves compliance OR non-compliance — it documents detected violations.
662
- - Do NOT use "ADA-compliant" or "WCAG-compliant" as adjectives — say "documented violations of [specific WCAG SCs]" instead.
663
-
664
- Respond ONLY with a JSON object — no preamble, no markdown:
665
- {
666
- "lead": "2-3 sentence headline framing",
667
- "body": "2-3 paragraphs of risk explanation + audit-date framing + ongoing-diligence context if applicable. ~150-300 words total.",
668
- "closer": "1-2 sentence closing line"
669
- }`}function Ol(e,t){var i;const o=(((i=e.content.find(c=>c.type==="text"))==null?void 0:i.text)??"").replace(/```(?:json)?/g,"").trim().match(/\{[\s\S]*\}/),r=e.usage.input_tokens*t.input+e.usage.output_tokens*t.output;if(!o)return{verdict:"error",candidates:[],reasoning:"Model returned no parseable JSON",costUsd:r,model:e.model};try{const c=JSON.parse(o[0]),d=(c.candidates??[]).slice(0,3).map(l=>({foreground:typeof l.foreground=="string"?l.foreground:"",background:typeof l.background=="string"?l.background:"",contrast:typeof l.contrast=="number"?l.contrast:0,rationale:typeof l.rationale=="string"?l.rationale:""})).filter(l=>l.foreground&&l.background);return{verdict:c.verdict==="suggested"&&d.length>0?"suggested":"no-suggestion",candidates:d,reasoning:typeof c.reasoning=="string"?c.reasoning:"",costUsd:r,model:e.model}}catch{return{verdict:"error",candidates:[],reasoning:"Could not parse color suggestions",costUsd:r,model:e.model}}}function Ml(e){var n,o,r,i,c,d;const t=(n=e.element.styles)==null?void 0:n.effectiveBackground,a=e.ruleId==="color-contrast"||e.ruleId==="color-contrast-enhanced"?`
670
- This is a COLOR-CONTRAST evaluation. axe-core couldn't determine the
671
- contrast ratio (commonly because the element's own background-color
672
- is transparent and axe didn't walk the DOM cascade to find the
673
- effective rendered backdrop). The audit pipeline has already done
674
- that walk for you — use the effectiveBackground below, NOT the
675
- element's own background-color, when computing contrast.
676
-
677
- Computed styles axe captured at audit time:
678
- - Foreground (color): ${((o=e.element.styles)==null?void 0:o.foreground)??"unknown"}
679
- - Element's OWN background-color: ${((r=e.element.styles)==null?void 0:r.background)??"unknown"} (often transparent; ignore unless solid)
680
- - Font size: ${((i=e.element.styles)==null?void 0:i.fontSize)??"unknown"} px
681
- - Font weight: ${((c=e.element.styles)==null?void 0:c.fontWeight)??"unknown"}
682
- - Text sample: ${JSON.stringify(((d=e.element.styles)==null?void 0:d.textSample)??"")}
683
-
684
- EFFECTIVE BACKGROUND (the actual color rendered beneath this text,
685
- captured by walking up the DOM cascade until we hit an opaque
686
- ancestor background-color):
687
- - Effective background color: ${(t==null?void 0:t.color)??"unknown"}
688
- - Came from ancestor: ${(t==null?void 0:t.fromAncestor)??"(the element itself)"}
689
- - Background-image present in cascade: ${t!=null&&t.hasBackgroundImageInChain?`YES (on ${t.imageAncestor??"an ancestor"})`:"no"}
690
-
691
- WCAG ${e.targetLevel} contrast thresholds:
692
- - Normal text (< 18pt, or < 14pt and not bold): 4.5:1 for AA, 7:1 for AAA
693
- - Large text (≥ 18pt OR ≥ 14pt bold): 3:1 for AA, 4.5:1 for AAA
694
-
695
- Reasoning approach:
696
- 1. Bold = font-weight >= 700. Large text threshold uses size + weight.
697
- 2. If 'Background-image present in cascade' is **no** → compute the
698
- contrast ratio between foreground and effectiveBackground.color.
699
- This is what the browser is actually rendering. Return 'pass' or
700
- 'fail' against the appropriate threshold. Cite the computed ratio.
701
- 3. If 'Background-image present in cascade' is **YES** → the
702
- effectiveBackground.color is what shows through the image's
703
- transparent regions, but the image itself may dominate visually.
704
- Reason about it:
705
- - If the image is likely dark and text is light (or vice versa),
706
- contrast is typically OK — lean 'pass' if foreground +
707
- effectiveBackground also pass, and call out the assumption.
708
- - If you genuinely can't tell whether the image dominates with a
709
- color that breaks contrast (text-over-photo scenarios), return
710
- 'uncertain' and explain that vision capability is needed.
711
- 4. NEVER return 'uncertain' just because the element's own background
712
- is transparent — that's expected and the effectiveBackground
713
- handles it.
714
-
715
- Return one of:
716
- - 'pass' if contrast comfortably meets the threshold (give the computed ratio).
717
- - 'fail' if contrast is below the threshold.
718
- - 'uncertain' ONLY when a background-image likely dominates visually
719
- and you cannot reasonably infer its tone.
720
- `:`
721
- This is a general WCAG conformance evaluation for rule '${e.ruleId}'.
722
- axe-core ran but couldn't conclude pass/fail for this element.
723
- Use the failureSummary + outerHTML to determine if the rule is
724
- satisfied. If the evidence is insufficient, return 'uncertain'.
725
- `;return`You are a WCAG accessibility auditor resolving an axe-core "incomplete"
726
- result. axe ran the rule successfully but couldn't fully determine
727
- the outcome on this specific element.
728
-
729
- Rule: ${e.ruleId}
730
- Page: ${e.pageUrl}
731
- Selector: ${e.element.selector}
732
- axe-core diagnostic: ${e.element.failureSummary??"(no detail provided)"}
733
-
734
- outerHTML snippet:
735
- ${e.element.outerHTMLSnippet??"(not captured)"}
736
- ${a}
737
-
738
- Respond with strict JSON (no markdown fences):
739
- {
740
- "verdict": "pass" | "fail" | "uncertain",
741
- "reasoning": "one or two sentences explaining the determination, citing the contrast ratio for color-contrast"
742
- }`}function Dl(e,t,a){var c;const n=((c=e.content.find(d=>d.type==="text"))==null?void 0:c.text)??"",r=n.replace(/```(?:json)?/g,"").trim().match(/\{[\s\S]*\}/),i=e.usage.input_tokens*t.input+e.usage.output_tokens*t.output;if(!r)return{verdict:"uncertain",reasoning:n||"AI returned no parseable response.",costUsd:i,model:e.model||a};try{const d=JSON.parse(r[0]);return{verdict:d.verdict==="pass"||d.verdict==="fail"?d.verdict:"uncertain",reasoning:typeof d.reasoning=="string"&&d.reasoning?d.reasoning:"AI returned no rationale.",costUsd:i,model:e.model||a}}catch{return{verdict:"uncertain",reasoning:n,costUsd:i,model:e.model||a}}}function Nl(e,t){var i;const a=((i=e.content.find(c=>c.type==="text"))==null?void 0:i.text)??"",o=a.replace(/```(?:json)?/g,"").trim().match(/\{[\s\S]*\}/),r=e.usage.input_tokens*t.input+e.usage.output_tokens*t.output;if(!o)return{lead:"",body:a||"Summary generation failed.",closer:"",costUsd:r,model:e.model};try{const c=JSON.parse(o[0]);return{lead:typeof c.lead=="string"?c.lead:"",body:typeof c.body=="string"?c.body:"",closer:typeof c.closer=="string"?c.closer:"",costUsd:r,model:e.model}}catch{return{lead:"",body:a,closer:"",costUsd:r,model:e.model}}}function fe(e){if(!e.enabled)return{ok:!1,reason:"AI augmentation is disabled in settings"};if(!e.apiKey)return{ok:!1,reason:"No API key configured"};switch(e.provider){case"anthropic":return{ok:!0,client:yl({apiKey:e.apiKey,model:e.model})};case"openai":return{ok:!1,reason:"OpenAI provider not yet implemented"};case"gemini":return{ok:!1,reason:"Gemini provider not yet implemented"};default:return{ok:!1,reason:`Unknown provider: ${e.provider}`}}}const At=Z("consistency-ai-suppression");async function Ll(e,t={}){var p;if(e.length===0)return{emitted:[],suppressed:0,uncertain:0,apiCalls:0};const a=await pe();if(!he(a,"aiConsistencySuppression"))return{emitted:e,suppressed:0,uncertain:0,apiCalls:0};let n;try{const m=await chrome.storage.local.get("aiConfig");n=ke(m.aiConfig)}catch{return At.debug("aiConfig load failed; emitting heuristic findings unchanged"),{emitted:e,suppressed:0,uncertain:0,apiCalls:0}}const o=fe(n);if(!o.ok)return At.info(`AI client unavailable (${o.reason}); emitting heuristic findings unchanged`),{emitted:e,suppressed:0,uncertain:0,apiCalls:0};const r=o.client;if(typeof r.judgeConsistencyDivergence!="function")return At.info("AI client does not support judgeConsistencyDivergence; emitting heuristic findings unchanged"),{emitted:e,suppressed:0,uncertain:0,apiCalls:0};const i=[];let c=0,d=0,l=0;for(const m of e){if((p=t.signal)!=null&&p.aborted){i.push(m);continue}try{const u=await r.judgeConsistencyDivergence({wcagCriterion:m.wcagCriterion,ruleId:m.ruleId,description:m.description,details:m.details,pages:m.pages,signal:t.signal});if(l++,u.verdict==="pass"){c++;continue}if(u.verdict==="fail"){i.push({...m,aiVerdict:{verdict:"real-divergence",confidence:u.confidence??0,reasoning:u.reasoning??""}});continue}d++,i.push({...m,aiVerdict:{verdict:"uncertain",confidence:u.confidence??0,reasoning:u.reasoning??""}})}catch(u){At.warn(`AI suppression failed for ${m.ruleId} ${m.wcagCriterion}: ${u instanceof Error?u.message:String(u)}`),i.push(m)}}return At.info(`consistency AI suppression: ${l} API calls, ${c} false-positives suppressed, ${d} uncertain, ${i.length} emitted`),{emitted:i,suppressed:c,uncertain:d,apiCalls:l}}const zp=3,ei=["default","hover","focus","focus-visible","active","disabled"],ti=["light","dark","forced-colors-active","forced-colors-none"],ai=["desktop","mobile","tablet"],ni="ltr",Kp={pseudoStates:[...ei],ariaVariations:[],themes:[...ti],directions:[ni],breakpoints:[...ai],breakpointPresets:cs};function Pl(e){const t=[],a=e.stateMatrix??{},n=(c,d)=>d.filter(l=>!(Array.isArray(c)&&c.includes(l))),o=n(a.pseudoStates,ei);o.length&&t.push(`missing pseudo-states: ${o.join(", ")}`);const r=n(a.themes,ti);r.length&&t.push(`missing themes: ${r.join(", ")}`);const i=n(a.breakpoints,ai);return i.length&&t.push(`missing breakpoints: ${i.join(", ")}`),Array.isArray(a.directions)&&a.directions.includes(ni)||t.push("LTR direction not enabled"),e.aiEnabled||t.push("AI checks off (an AI key is required for the criteria axe-core cannot cover)"),t}async function _n(e){var w;let t={},a=1,n={};try{if(typeof chrome<"u"&&((w=chrome.storage)!=null&&w.local)){const b=await chrome.storage.local.get(["stateMatrix","runsPerState","aiConfig"]);t=b.stateMatrix??{},a=b.runsPerState,n=b.aiConfig??{}}}catch{}const o=(b,k)=>Array.isArray(b)&&b.length>0?b:k,r=o(t.pseudoStates,["default"]),i=o(t.themes,["light"]),c=o(t.directions,["ltr"]),d=o(t.breakpoints,["desktop"]),l=Array.isArray(t.ariaVariations)?t.ariaVariations.length:0,p=r.length*i.length*c.length*d.length*Math.max(l,1),m=typeof a=="number"&&a>0?a:1,u=!!n.enabled&&!!n.apiKey,g=n.enabledChecks,h=u&&g?Object.values(g).filter(Boolean).length:0,f=Pl({stateMatrix:{pseudoStates:r,themes:i,directions:c,breakpoints:d,ariaVariations:[]},aiEnabled:u});return{stateCount:p,pseudoStates:r,themes:i,directions:c,breakpoints:d,ariaVariations:l,runsPerState:m,aiEnabled:u,aiCheckCount:h,wcagTarget:"WCAG 2.1 AA",isConformance:f.length===0,conformanceGaps:f,capturedAt:e}}function oi(e){return e?`${((a,n)=>`${a} ${n}${a===1?"":"s"}`)(e.stateCount,"UI state")} (${e.pseudoStates.length} pseudo × ${e.themes.length} theme${e.themes.length===1?"":"s"} × ${e.directions.length} dir × ${e.breakpoints.length} breakpoint${e.breakpoints.length===1?"":"s"}${e.ariaVariations?` × ${e.ariaVariations} ARIA`:""}) · each screen re-checked until results stabilized · AI ${e.aiEnabled?`ON (${e.aiCheckCount} checks)`:"OFF"} · ${e.wcagTarget}`:"Audit settings: not recorded."}function ri(e){return e?e.isConformance?null:`Quick check — NOT a Full 2.1 AA audit${e.conformanceGaps.length?` (${e.conformanceGaps.join("; ")})`:""}. This grade reflects a LIMITED run and is not a conformance result; run the Full 2.1 AA audit before relying on it.`:"Audit settings were not recorded — treat this grade as unverified."}function Fl(e){const t=new Map(e.breakpointPresets.map(n=>[n.id,n])),a=[];for(const n of e.breakpoints){const o=t.get(n);if(o)for(const r of e.directions)for(const i of e.themes){const c=e.ariaVariations.length===0?[null]:e.ariaVariations;for(const d of c)for(const l of e.pseudoStates)a.push({pseudoState:l,ariaVariation:d,theme:i,direction:r,breakpoint:o})}}return a}const ii=["color-contrast","color-contrast-enhanced","link-in-text-block"],_l=["image-alt","input-image-alt","area-alt","svg-img-alt","object-alt","role-img-alt","label","select-name","aria-input-field-name","aria-toggle-field-name","form-field-multiple-labels","autocomplete-valid","label-content-name-mismatch","label-title-only","button-name","input-button-name","link-name","empty-button","empty-heading","empty-link","frame-title","heading-order","page-has-heading-one","landmark-one-main","landmark-no-duplicate-banner","landmark-no-duplicate-contentinfo","landmark-no-duplicate-main","landmark-unique","landmark-banner-is-top-level","landmark-complementary-is-top-level","landmark-contentinfo-is-top-level","landmark-main-is-top-level","region","bypass","empty-table-header","aria-allowed-attr","aria-required-attr","aria-required-children","aria-required-parent","aria-roles","aria-valid-attr-value","aria-valid-attr","aria-hidden-body","aria-hidden-focus","aria-allowed-role","aria-prohibited-attr","presentation-role-conflict","aria-text","aria-deprecated-role","aria-conditional-attr","aria-braille-equivalent","html-has-lang","html-lang-valid","html-xml-lang-mismatch","valid-lang","nested-interactive","tabindex","frame-focusable-content","no-focusable-content","focus-order-semantics","meta-viewport","meta-refresh","duplicate-id","duplicate-id-active","duplicate-id-aria","video-caption","audio-caption","table-fake-caption","scope-attr-valid","th-has-data-cells","td-headers-attr"];{const e=new Set(ii),t=_l.filter(a=>e.has(a));t.length>0&&console.error("axe-rule-classification: rule(s) classified as BOTH state-dependent and markup-eligible:",t)}const Ul=Z("chrome-api"),Wl="1.3",bo=3e4;class Gl extends Error{constructor(t,a){super(`CDP ${t} timed out after ${a}ms`),this.method=t,this.timeoutMs=a,this.name="CdpTimeoutError"}}class si{constructor(t){this.target=t}async attach(){await chrome.debugger.attach(this.target,Wl)}async detach(){try{await chrome.debugger.detach(this.target)}catch(t){Ul.debug("detach soft-failure",t)}}async send(t,a){const n=chrome.debugger.sendCommand(this.target,t,a);let o;const r=new Promise((i,c)=>{o=setTimeout(()=>c(new Gl(t,bo)),bo)});try{return await Promise.race([n,r])}finally{o!==void 0&&clearTimeout(o)}}}function Vl(e){const t=e instanceof Error?e.message:String(e);return/Another debugger is already attached|Cannot attach to/i.test(t)}function ci(e){const t=e instanceof Error?e.message:String(e);return Vl(e)?Xn("DEBUGGER_BUSY","DevTools is open on this tab. Close it to run the audit.",!0,{raw:t}):Xn("STATE_DRIVE_FAILED",t,!1)}function jl(e){const t=(a,n)=>e(a,n);return chrome.debugger.onDetach.addListener(t),()=>chrome.debugger.onDetach.removeListener(t)}const we=Z("state-driver"),Bl=60*1e3,Ve=new Map,ia=new Map,gt=new Map,ut=new Map,Hl='button, a[href], input, textarea, select, summary, [tabindex]:not([tabindex="-1"]), [role="button"], [role="link"], [role="checkbox"], [role="radio"], [role="tab"], [role="menuitem"], [role="switch"], [role="combobox"], [role="option"]',Mt=new Map,ql={default:[],hover:["hover"],focus:["focus"],"focus-visible":["focus","focus-visible"],active:["active"],disabled:[]};async function li(e){let t=Ve.get(e);if(!t){t=new si({tabId:e});try{await t.attach(),await t.send("Runtime.enable"),await t.send("Page.enable"),await t.send("DOM.enable"),await t.send("DOM.getDocument",{depth:-1,pierce:!0}),await t.send("CSS.enable")}catch(a){try{await t.detach()}catch{}throw a}Ve.set(e,t),gt.set(e,new Map),zl(e),we.info("attached",{tabId:e})}return Yl(e),t}function zl(e){const t=(a,n,o)=>{var i,c;if(a.tabId!==e)return;const r=gt.get(e);if(r)if(n==="Runtime.executionContextCreated"){const d=o,l=d==null?void 0:d.context;l&&((i=l.auxData)!=null&&i.isDefault)&&((c=l.auxData)!=null&&c.frameId)&&r.set(l.auxData.frameId,l.id)}else if(n==="Runtime.executionContextDestroyed"){const d=o,l=d==null?void 0:d.executionContextId;if(l!==void 0)for(const[p,m]of r.entries())m===l&&r.delete(p)}else n==="Runtime.executionContextsCleared"&&r.clear()};chrome.debugger.onEvent.addListener(t)}async function Kl(e){const t=Ve.get(e);if(Ve.delete(e),gt.delete(e),ut.delete(e),Mt.delete(e),t)try{await t.detach()}catch{}}function Yl(e){const t=ia.get(e);t&&clearTimeout(t),ia.set(e,setTimeout(()=>{Oa(e).catch(a=>we.warn("idle detach failed",a))},Bl))}async function Oa(e){const t=Ve.get(e);t&&(await t.detach(),Ve.delete(e)),gt.delete(e),ut.delete(e),Mt.delete(e);const a=ia.get(e);a&&(clearTimeout(a),ia.delete(e))}function di(e){const t=[{id:e.frame.id,url:e.frame.url}];for(const a of e.childFrames??[])t.push(...di(a));return t}async function Jl(e,t,a){var r;if(!a||a===0)return;const n=gt.get(t);if(!n)return;let o;try{o=(r=(await chrome.scripting.executeScript({target:{tabId:t,frameIds:[a]},func:()=>location.href}))[0])==null?void 0:r.result}catch(i){we.debug("frame URL lookup failed",i)}try{const i=await e.send("Page.getFrameTree"),c=di(i.frameTree);if(o){const p=c.find(m=>m.url===o);if(p){const m=n.get(p.id);if(m!==void 0)return m}}const d=i.frameTree.frame.id,l=c.find(p=>p.id!==d);return l?n.get(l.id):void 0}catch(i){we.warn("Page.getFrameTree failed",i);return}}async function Xl(e,t,a){var i;const n={expression:`document.querySelector(${JSON.stringify(t)})`,objectGroup:"wcag-auditor",returnByValue:!1};a!==void 0&&(n.contextId=a);const r=(i=(await e.send("Runtime.evaluate",n)).result)==null?void 0:i.objectId;if(!r)return null;try{return(await e.send("DOM.requestNode",{objectId:r})).nodeId??null}finally{e.send("Runtime.releaseObject",{objectId:r}).catch(()=>{})}}async function ui(e){const t=ut.get(e);if(!t||t.length===0)return;const a=Ve.get(e);if(a){for(const n of t)try{await a.send("CSS.forcePseudoState",{nodeId:n,forcedPseudoClasses:[]})}catch(o){we.debug("forcePseudoState clear failed (node may be gone)",o)}ut.delete(e)}}async function Ql(e,t){try{return(await e.send("DOM.querySelectorAll",{nodeId:t,selector:Hl})).nodeIds??[]}catch(a){return we.debug("querySelectorAll for interactive descendants failed",a),[]}}async function mn(e,t,a,n){await chrome.scripting.executeScript({target:Un(e,t),func:(o,r)=>{const i=document.querySelector(o);i&&(r?i.setAttribute("disabled",""):i.removeAttribute("disabled"))},args:[a,n]})}async function hi(e,t){await chrome.scripting.executeScript({target:Un(e,t),func:()=>{const a=document.activeElement;a&&typeof a.blur=="function"&&a.blur()}})}async function pi(e,t){await chrome.scripting.executeScript({target:{tabId:e,frameIds:[0]},func:a=>{document.documentElement.setAttribute("dir",a)},args:[t]})}async function Zl(e,t,a,n){await chrome.scripting.executeScript({target:Un(e,t),func:(o,r)=>{const i=document.querySelector(o);if(i)for(const[c,d]of Object.entries(r))i.setAttribute(c,d)},args:[a,n]})}function Un(e,t){return t!==void 0&&t!==0?{tabId:e,frameIds:[t]}:{tabId:e}}async function ed(e,t,a,n){const o=await li(e),r=Mt.get(e),i=(r==null?void 0:r.scope)===a&&(r==null?void 0:r.frameId)===n,c=t.ariaVariation?JSON.stringify(t.ariaVariation.attributes):"",d=!i||(r==null?void 0:r.pseudoState)!==t.pseudoState,l=!r||r.theme!==t.theme,p=!r||r.direction!==t.direction,m=!r||r.breakpointId!==t.breakpoint.id,u=!i||(r==null?void 0:r.ariaVariationKey)!==c;if(d&&(await ui(e),a)){t.pseudoState==="disabled"?await mn(e,n,a,!0):(await mn(e,n,a,!1),await hi(e,n));const g=ql[t.pseudoState];if(g.length>0){const h=await Jl(o,e,n),f=await Xl(o,a,h);if(f!==null){const w=await Ql(o,f),b=[f,...w];for(const k of b)try{await o.send("CSS.forcePseudoState",{nodeId:k,forcedPseudoClasses:g})}catch(v){we.debug(`CSS.forcePseudoState failed for nodeId=${k}`,v)}ut.set(e,b),we.debug(`forced :${t.pseudoState} on ${b.length} node(s)`)}else we.debug(`could not resolve nodeId for ${a} (frameId=${n})`)}}if(l){const g=[{name:"prefers-reduced-motion",value:"reduce"}];t.theme==="dark"?(g.push({name:"prefers-color-scheme",value:"dark"}),g.push({name:"forced-colors",value:"none"})):t.theme==="light"?(g.push({name:"prefers-color-scheme",value:"light"}),g.push({name:"forced-colors",value:"none"})):t.theme==="forced-colors-active"?g.push({name:"forced-colors",value:"active"}):t.theme==="forced-colors-none"&&g.push({name:"forced-colors",value:"none"}),await o.send("Emulation.setEmulatedMedia",{features:g}),await new Promise(h=>setTimeout(h,50))}p&&await pi(e,t.direction),m&&await o.send("Emulation.setDeviceMetricsOverride",{width:t.breakpoint.width,height:t.breakpoint.height,deviceScaleFactor:t.breakpoint.deviceScaleFactor,mobile:t.breakpoint.mobile}),u&&t.ariaVariation&&a&&await Zl(e,n,a,t.ariaVariation.attributes),Mt.set(e,{scope:a,frameId:n,pseudoState:t.pseudoState,theme:t.theme,direction:t.direction,breakpointId:t.breakpoint.id,ariaVariationKey:c})}async function td(e,t,a){const n=Ve.get(e);if(n){if(await ui(e),Mt.delete(e),t)try{await mn(e,a,t,!1),await hi(e,a),await pi(e,"ltr")}catch(o){we.warn("element-level reset partial failure",o)}try{await n.send("Emulation.setEmulatedMedia",{features:[]}),await n.send("Emulation.clearDeviceMetricsOverride")}catch(o){we.warn("reset partial failure",o)}await Oa(e)}}async function bn(e,t,a,n){try{return await ed(e,t,a,n),H({type:"STATE_CHANGED_EVENT",tabId:e,currentState:t}),{type:"STATE_DRIVE_RESPONSE",success:!0,appliedState:t}}catch(o){return we.error("state drive failed",o),await Kl(e),{type:"STATE_DRIVE_RESPONSE",success:!1,error:ci(o)}}}async function Yt(e,t,a){await td(e,t,a)}async function Yp(e){await Oa(e);try{await chrome.debugger.detach({tabId:e})}catch{}}async function ad(e,t={}){try{const a=await li(e),n={format:"jpeg",quality:t.quality??75};t.fullPage&&(n.captureBeyondViewport=!0);const o=await a.send("Page.captureScreenshot",n);return o!=null&&o.data?`data:image/jpeg;base64,${o.data}`:null}catch(a){return we.debug("Page.captureScreenshot failed",a),null}}function Jp(){var a;const e=[];if(e.push($e("STATE_DRIVE_REQUEST",n=>bn(n.tabId,n.state,n.scope,n.frameId))),e.push($e("STATE_RESET_REQUEST",n=>Yt(n.tabId))),(a=chrome.tabs)!=null&&a.onRemoved){const n=o=>{Oa(o).catch(()=>{})};chrome.tabs.onRemoved.addListener(n),e.push(()=>chrome.tabs.onRemoved.removeListener(n))}const t=jl((n,o)=>{n.tabId!==void 0&&(Ve.delete(n.tabId),gt.delete(n.tabId),ut.delete(n.tabId),we.warn("unexpected detach",{tabId:n.tabId,reason:o}))});return e.push(t),we.info("handlers registered"),()=>e.forEach(n=>n())}const st=Z("cloud-sync"),yo="cloudSyncEnabled",Ga="cloudSyncEndpoint",Va="licenseToken",yn="cloudSyncVersionCache";async function Wn(){try{const e=await pe();if(!he(e,"cloudSync"))return null;const t=await chrome.storage.local.get([yo,Ga,Va]),a=t[yo]===!0,n=typeof t[Ga]=="string"?t[Ga]:"",o=typeof t[Va]=="string"?t[Va]:"";return!a||!n||!o?null:{endpoint:n.replace(/\/$/,""),token:o,enabled:a}}catch{return null}}async function fi(){try{const t=(await chrome.storage.local.get(yn))[yn];return t&&typeof t=="object"?t:{}}catch{return{}}}async function sa(e){try{await chrome.storage.local.set({[yn]:e})}catch{}}async function nd(e,t,a){const n=await Wn();if(!n)return!1;const o=await fi(),r=o[e];try{const i=`${n.endpoint}/v1/products/wcagcheckr/baselines/${encodeURIComponent(e)}`,c=await fetch(i,{method:"PUT",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n.token}`},body:JSON.stringify({snapshot:t,axeVersion:a,expectedVersion:r})});if(c.status===409)return st.warn(`baseline ${e} version conflict on push`,{expectedVersion:r}),delete o[e],await sa(o),!1;if(!c.ok)return st.warn("baseline push failed",{status:c.status}),!1;const d=await c.json();return typeof d.version=="number"&&(o[e]=d.version,await sa(o)),!0}catch(i){return st.debug("push network failure (offline?)",i),!1}}async function od(e){const t=await Wn();if(!t)return!1;try{const a=`${t.endpoint}/v1/products/wcagcheckr/baselines/${encodeURIComponent(e)}`,n=await fetch(a,{method:"DELETE",headers:{Authorization:`Bearer ${t.token}`}});if(n.ok){const o=await fi();delete o[e],await sa(o)}return n.ok}catch(a){return st.debug("delete network failure",a),!1}}async function rd(){const e=await Wn();if(!e)return[];try{const t=await fetch(`${e.endpoint}/v1/products/wcagcheckr/baselines`,{headers:{Authorization:`Bearer ${e.token}`}});if(!t.ok)return st.warn("pull failed",{status:t.status}),[];const n=(await t.json()).items??[],o={};for(const r of n)o[r.componentId]=r.version;return await sa(o),n}catch(t){return st.debug("pull network failure",t),[]}}const gi=Z("baseline-store"),wo="componentIdAliases";async function ht(e,t){try{return await t()}catch(a){const n=a instanceof Error?a.message:String(a);throw gi.error(`baseline IDB ${e} failed: ${n}`),new rs({code:"BASELINE_DB_ERROR",message:`Baseline storage is unavailable (${e}: ${n}).`,recoverable:!1,details:n})}}async function Ma(e){return((await chrome.storage.local.get(wo))[wo]??{})[e]??e}async function id(e){const t=await Ma(e),a=await ht("get",()=>ya(t));return a?{violations:a.violations,snapshotMeta:a.snapshotMeta}:null}async function sd(e,t,a,n){const o=await Ma(e),r=await ht("get-for-set",()=>ya(o)),i=(r==null?void 0:r.seenOnUrls)??[],c=i.includes(a.url)?i:[...i,a.url];await ht("set",()=>Cn({componentId:o,violations:t,snapshotMeta:a,lastUpdated:new Date().toISOString(),axeVersion:a.axeVersion,announcements:n==null?void 0:n.announcements,focusEvents:n==null?void 0:n.focusEvents,seenOnUrls:c})),nd(o,{violations:t,snapshotMeta:a},a.axeVersion).catch(()=>{})}function cd(e,t){if(!e||!t||Qn(e)===Qn(t))return;const a=r=>{var i,c,d,l,p;return(((i=r.pseudoStates)==null?void 0:i.length)??0)*Math.max(1,((c=r.ariaVariations)==null?void 0:c.length)??0)*(((d=r.themes)==null?void 0:d.length)??0)*(((l=r.directions)==null?void 0:l.length)??0)*(((p=r.breakpoints)==null?void 0:p.length)??0)},n=a(e),o=a(t);return`Baseline was captured under a different state-matrix configuration (${n} states) than this run (${o} states). Per-state-instance deltas inflate when the matrix changes — the unique-violation deltas above are still reliable.`}async function Gn(e,t,a,n){var l;const o=await Ma(e),r=await va(o),i=await ht("compare",()=>ya(o));if(!i){const p=t.filter(u=>r.has(u.matchKey)),m=t.filter(u=>!r.has(u.matchKey));return{new:m,persistent:[],fixed:[],newCount:m.length,persistentCount:0,fixedCount:0,baselineSnapshotMeta:null,comparedAt:new Date().toISOString(),newAnnouncements:a==null?void 0:a.announcements,newFocusEvents:a==null?void 0:a.focusEvents,acknowledged:p,acknowledgedCount:p.length}}const c=os(i.violations,t,i.snapshotMeta,{baselineAnnouncements:i.announcements,currentAnnouncements:a==null?void 0:a.announcements,baselineFocusEvents:i.focusEvents,currentFocusEvents:a==null?void 0:a.focusEvents},r),d=cd((l=i.snapshotMeta)==null?void 0:l.matrixConfig,n);return d&&(c.matrixMismatchWarning=d),c}async function ld(e){const t=await Ma(e);await ht("delete",()=>or(t)),od(t).catch(()=>{})}async function Xp(){const e=await rd();for(const t of e)await Cn({componentId:t.componentId,violations:t.snapshot.violations,snapshotMeta:t.snapshot.snapshotMeta,lastUpdated:t.updatedAt,axeVersion:t.axeVersion});return e.length>0&&H({type:"SCORECARD_UPDATED_EVENT"}),e.length}async function dd(e){let t=await ht("list",()=>rr());return e!=null&&e.url&&(t=t.filter(a=>a.snapshotMeta.url===e.url)),t.map(a=>{const n=(a.focusEvents??[]).filter(l=>l.isFocusReset).length,o=(a.announcements??[]).length,r=a.violations.filter(l=>l.ruleId==="target-size").length,i=a.violations.some(l=>l.ruleId==="color-contrast"&&l.currentState.pseudoState==="hover"),c=a.violations.filter(l=>l.impact==="critical").length,d=a.violations.filter(l=>l.impact==="serious").length;return{componentId:a.componentId,violationCount:a.violations.length,lastUpdated:a.lastUpdated,seenOnUrlsCount:(a.seenOnUrls??[]).length,metrics:{criticalCount:c,seriousCount:d,focusResetCount:n,announcementCount:o,targetSizeFailCount:r,hoverContrastFail:i}}})}function Qp(){const e=[];return e.push($e("BASELINE_GET",async t=>({type:"BASELINE_GET_RESPONSE",baseline:await id(t.componentId)}))),e.push($e("BASELINE_SET",async t=>{await sd(t.componentId,t.violations,t.snapshotMeta,{announcements:t.announcements,focusEvents:t.focusEvents}),H({type:"SCORECARD_UPDATED_EVENT"})})),e.push($e("BASELINE_COMPARE",async t=>({type:"BASELINE_COMPARE_RESPONSE",delta:await Gn(t.componentId,t.currentViolations,{announcements:t.announcements,focusEvents:t.focusEvents},t.currentMatrix)}))),e.push($e("BASELINE_DELETE",async t=>{await ld(t.componentId),H({type:"SCORECARD_UPDATED_EVENT"})})),e.push($e("BASELINE_LIST",async t=>({type:"BASELINE_LIST_RESPONSE",items:await dd(t.filter)}))),gi.info("handlers registered"),()=>e.forEach(t=>t())}const ud=Z("settings-store"),vo=1,ja="__schemaVersion",ca={stateMatrix:nn,componentIdAliases:{},ignorePatterns:[]},hd=["stateMatrix","componentIdAliases","ignorePatterns","activePresetId","matrixPresets","userMode","crawlMaxPages","crawlIncludeRegex","crawlExcludeRegex","crawlRememberSettings","crawlReviewEnabled","githubRepoUrl","jiraInstanceUrl","azureDevOpsProjectUrl","gitlabProjectUrl"];async function Ye(e,t){return(await chrome.storage.local.get(e))[e]??t}async function Zp(){const e=await chrome.storage.local.get([ja,...Object.keys(ca)]);if(e[ja]===vo)return;const t={[ja]:vo};for(const[a,n]of Object.entries(ca))a in e||(t[a]=n);await chrome.storage.local.set(t),ud.info("defaults ensured")}function ef(){const e=[];return e.push($e("SETTINGS_GET",async t=>({type:"SETTINGS_RESPONSE",data:(await chrome.storage.local.get(t.key))[t.key]??ca[t.key]}))),e.push($e("SETTINGS_SET",async t=>{await chrome.storage.local.set({[t.key]:t.value})})),e.push($e("SETTINGS_GET_ALL",async()=>{const t=await chrome.storage.local.get([...hd]);return{type:"SETTINGS_RESPONSE",data:{...ca,...t}}})),()=>e.forEach(t=>t())}function _e(e){const t={capUsd:Math.max(0,e),spentUsd:0,exceeded:!1};return{state:t,canCharge(){return!t.exceeded&&t.spentUsd<t.capUsd},recordCharge(a){t.spentUsd+=Math.max(0,a),t.spentUsd>=t.capUsd&&(t.exceeded=!0)}}}const pd=Z("ai-alt-text");async function fd(e,t,a={}){var m,u;if(!t.enabled||!t.enabledChecks.altText)return{findings:[],totalCostUsd:0,capExceeded:!1,errors:[]};const n=fe(t);if(!n.ok)return{findings:[],totalCostUsd:0,capExceeded:!1,errors:[`AI client unavailable: ${n.reason}`]};const o=n.client,r=_e(t.costCapUsd),i=[],c=[],d=Math.max(1,t.maxCandidatesPerCheck??10),l=e.slice(0,d),p=l.length;for(let g=0;g<l.length;g++){const h=l[g];if(!r.canCharge())break;try{if((m=a.signal)!=null&&m.aborted){c.push(`canceled after ${g}/${p} candidates`);break}const f=await o.judgeAltText({imageUrl:h.imageUrl,alt:h.alt,surroundingContext:h.surroundingContext,signal:a.signal});r.recordCharge(f.costUsd),(f.verdict==="fail"||f.verdict==="uncertain"&&f.confidence<.6)&&i.push(await gd(h,f))}catch(f){if(f instanceof Error&&(f.name==="AbortError"||f.name==="ExternalAbortError")){c.push(`canceled after ${g}/${p} candidates`);break}const b=f instanceof Error?f.message:String(f);c.push(`${h.selector}: ${b}`),pd.warn("alt-text judgment failed",f)}(u=a.onProgress)==null||u.call(a,g+1,p)}return{findings:i,totalCostUsd:r.state.spentUsd,capExceeded:r.state.exceeded,errors:c}}async function gd(e,t){const a=t.verdict==="uncertain"?"ai-alt-uncertain":"ai-alt-misleading",n=e.alt?`“${e.alt}”`:"(empty / missing alt)",o=t.unverifiable?`This image is a format automated tools can't read (e.g. SVG). Nothing is wrong that we can see — a human just has to confirm the alt text is right. Its alt text is: ${n}. Verify that accurately describes what the image shows or does.`:`AI assessment: ${t.reasoning}`,r={selector:e.selector,outerHTML:e.outerHTML.slice(0,500),failureSummary:o,tagName:"IMG",role:null,accessibleName:e.alt,textSnippet:null,attrId:null,attrTestid:null},i=await xn({ruleId:a,componentId:e.componentId,currentState:e.currentState,target:r}),c=t.verdict==="uncertain";return{ruleId:a,wcagCriterion:"1.1.1",wcagLevel:"A",impact:c?"minor":"serious",description:t.unverifiable?"Automated tools can't read this image's format (e.g. SVG) — a human needs to confirm its alt text is appropriate.":c?"AI couldn't verify whether this alt text is appropriate — flag for human review.":"AI judged the alt text to be misleading, generic, or otherwise inappropriate.",helpUrl:"https://www.w3.org/WAI/WCAG21/Understanding/non-text-content.html",target:r,componentId:e.componentId,currentState:e.currentState,axeVersion:e.axeVersion,detectedAt:new Date().toISOString(),matchKey:i,ai:{reasoning:t.reasoning,confidence:t.confidence,model:t.model,costUsd:t.costUsd},...c?{needsReview:!0}:{}}}const kt=Z("interactive-audit"),md="1.3",bd={Tab:{key:"Tab",code:"Tab",windowsVirtualKeyCode:9},Enter:{key:"Enter",code:"Enter",windowsVirtualKeyCode:13},Escape:{key:"Escape",code:"Escape",windowsVirtualKeyCode:27},Space:{key:" ",code:"Space",windowsVirtualKeyCode:32},ArrowLeft:{key:"ArrowLeft",code:"ArrowLeft",windowsVirtualKeyCode:37},ArrowUp:{key:"ArrowUp",code:"ArrowUp",windowsVirtualKeyCode:38},ArrowRight:{key:"ArrowRight",code:"ArrowRight",windowsVirtualKeyCode:39},ArrowDown:{key:"ArrowDown",code:"ArrowDown",windowsVirtualKeyCode:40},Home:{key:"Home",code:"Home",windowsVirtualKeyCode:36},End:{key:"End",code:"End",windowsVirtualKeyCode:35}};class Vn{constructor(t){Wt(this,"session");Wt(this,"attached",!1);Wt(this,"steps",[]);this.tabId=t,this.session=new si({tabId:t})}async attach(){if(!this.attached)try{await chrome.debugger.attach({tabId:this.tabId},md),await this.session.send("Runtime.enable"),await this.session.send("Page.enable"),await this.session.send("DOM.enable"),await this.session.send("DOM.getDocument",{depth:-1,pierce:!0}),await this.session.send("Accessibility.enable"),this.attached=!0}catch(t){throw kt.error("attach failed",t),ci(t)}}async dispose(){if(this.attached){try{await chrome.debugger.detach({tabId:this.tabId})}catch(t){kt.debug("detach soft-failure",t)}this.attached=!1}}async pressKey(t,a){const n=bd[t];if(!n)throw new Error(`Unknown key: ${String(t)}`);const o=a!=null&&a.shift?8:0;await this.session.send("Input.dispatchKeyEvent",{type:"rawKeyDown",key:n.key,code:n.code,windowsVirtualKeyCode:n.windowsVirtualKeyCode,modifiers:o}),await this.session.send("Input.dispatchKeyEvent",{type:"keyUp",key:n.key,code:n.code,windowsVirtualKeyCode:n.windowsVirtualKeyCode,modifiers:o}),await Ao(50)}async pressKeyN(t,a,n){for(let o=0;o<a;o++)await this.pressKey(t,n)}async typeText(t){await this.session.send("Input.insertText",{text:t}),await Ao(50)}async countFocusables(){var a;const t=`(() => {
743
- const sel = [
744
- 'a[href]', 'button', 'input', 'select', 'textarea',
745
- '[tabindex]', 'audio[controls]', 'video[controls]', '[contenteditable]'
746
- ].join(',');
747
- const all = Array.from(document.querySelectorAll(sel));
748
- const visible = (el) => {
749
- if (el.hasAttribute && el.hasAttribute('disabled')) return false;
750
- const ti = el.getAttribute && el.getAttribute('tabindex');
751
- if (ti != null && parseInt(ti, 10) < 0) return false;
752
- if (el.getAttribute && el.getAttribute('aria-hidden') === 'true') return false;
753
- if (el.tagName === 'INPUT' && el.type === 'hidden') return false;
754
- if (el.getClientRects && el.getClientRects().length === 0) return false;
755
- const cs = getComputedStyle ? getComputedStyle(el) : null;
756
- if (cs && (cs.display === 'none' || cs.visibility === 'hidden')) return false;
757
- if (cs && parseFloat(cs.opacity || '1') === 0) return false;
758
- return true;
759
- };
760
- return all.filter(visible).length;
761
- })()`;try{const n=await this.session.send("Runtime.evaluate",{expression:t,returnByValue:!0}),o=(a=n==null?void 0:n.result)==null?void 0:a.value;return typeof o=="number"&&Number.isFinite(o)?o:0}catch{return 0}}async getFocusedElement(){var a;const t=await this.session.send("Runtime.evaluate",{expression:wd,returnByValue:!0});try{const n=(a=t.result)==null?void 0:a.value;return typeof n=="string"?JSON.parse(n):n}catch(n){return kt.error("getFocusedElement: probe returned non-JSON",n),yd}}async captureScreenshot(){try{const t=await this.session.send("Page.captureScreenshot",{format:"jpeg",quality:75});return t!=null&&t.data?`data:image/jpeg;base64,${t.data}`:null}catch(t){return kt.debug("captureScreenshot failed",t),null}}async getAxContext(){try{return((await this.session.send("Accessibility.getFullAXTree")).nodes??[]).filter(a=>!a.ignored).map(a=>{var n,o,r;return{nodeId:a.nodeId,role:(n=a.role)==null?void 0:n.value,name:(o=a.name)==null?void 0:o.value,description:(r=a.description)==null?void 0:r.value,childIds:a.childIds}})}catch(t){return kt.debug("getAxContext failed",t),[]}}async recordStep(t,a){const n=await this.getFocusedElement(),o=(a==null?void 0:a.screenshot)!==!1?await this.captureScreenshot():null,r=a!=null&&a.ax?await this.getAxContext():void 0,i={ordinal:this.steps.length,at:new Date().toISOString(),action:t,focused:n,screenshot:o??void 0,axContext:r};return this.steps.push(i),i}}function Ao(e){return new Promise(t=>setTimeout(t,e))}const yd={selector:"body",tag:"body",role:"",name:"",outerHtml:"",rect:{x:0,y:0,width:0,height:0},isBody:!0},wd=`(() => {
762
- const el = document.activeElement;
763
- if (!el || el === document.body) {
764
- return JSON.stringify({
765
- selector: 'body',
766
- tag: 'body',
767
- role: '',
768
- name: '',
769
- outerHtml: '',
770
- rect: { x: 0, y: 0, width: 0, height: 0 },
771
- isBody: true,
772
- });
773
- }
774
- function selectorFor(node) {
775
- if (node.id) return '#' + CSS.escape(node.id);
776
- const parts = [];
777
- let cur = node;
778
- while (cur && cur.nodeType === 1 && cur !== document.body) {
779
- let part = cur.tagName.toLowerCase();
780
- if (cur.classList.length > 0) {
781
- part += '.' + Array.from(cur.classList).slice(0, 2).map(c => CSS.escape(c)).join('.');
782
- }
783
- const parent = cur.parentElement;
784
- if (parent) {
785
- const siblings = Array.from(parent.children).filter(s => s.tagName === cur.tagName);
786
- if (siblings.length > 1) {
787
- part += ':nth-of-type(' + (siblings.indexOf(cur) + 1) + ')';
788
- }
789
- }
790
- parts.unshift(part);
791
- cur = parent;
792
- if (cur && cur.id) { parts.unshift('#' + CSS.escape(cur.id)); break; }
793
- }
794
- return parts.join(' > ');
795
- }
796
- function accName(node) {
797
- return (
798
- node.getAttribute('aria-label') ||
799
- (node.getAttribute('aria-labelledby') && (() => {
800
- const ids = node.getAttribute('aria-labelledby').split(/\\s+/);
801
- return ids.map(id => { const r = document.getElementById(id); return r ? r.textContent : ''; }).join(' ').trim();
802
- })()) ||
803
- node.getAttribute('alt') ||
804
- (node.tagName === 'INPUT' && node.labels && node.labels[0] ? node.labels[0].textContent : '') ||
805
- (node.textContent || '').trim().slice(0, 200)
806
- );
807
- }
808
- const rect = el.getBoundingClientRect();
809
- // rc.120 — Document-relative coordinates. Pre-rc.120 we captured
810
- // viewport-relative rect.top, which silently lied as the walker
811
- // progressed: when a Tab scrolls a later element into view, EARLIER
812
- // elements that were at top:100 in their initial snapshot now have
813
- // top:-3500 (scrolled off the top). Sort the rec by y and the
814
- // sequence looks "descending from y=4260 to y=1240" — geometrically
815
- // nonsense for a top-to-bottom Tab walk. Document-relative position
816
- // is invariant under scroll, so the comparator + LLM see the real
817
- // visual order regardless of how far the walker scrolled.
818
- return JSON.stringify({
819
- selector: selectorFor(el),
820
- tag: el.tagName.toLowerCase(),
821
- role: el.getAttribute('role') || '',
822
- name: (accName(el) || '').toString().slice(0, 200),
823
- outerHtml: (el.outerHTML || '').slice(0, 2000),
824
- rect: {
825
- x: rect.left + window.scrollX,
826
- y: rect.top + window.scrollY,
827
- width: rect.width,
828
- height: rect.height,
829
- },
830
- isBody: false,
831
- });
832
- })()`,vd=[/no parseable JSON/i,/invalid JSON/i];function ko(e){if(e.verdict!=="uncertain"||e.confidence!==0)return!1;const t=e.reasoning??"";return vd.some(a=>a.test(t))}async function nt(e){const t=await e();if(!ko(t))return t;try{const a=await e();if(!ko(a))return a}catch{}return t}async function Ad(e,t){if(t.length===0||typeof OffscreenCanvas>"u"||typeof createImageBitmap>"u")return e;try{const n=await(await fetch(e)).blob(),o=await createImageBitmap(n),r=new OffscreenCanvas(o.width,o.height),i=r.getContext("2d");if(!i)return e;i.drawImage(o,0,0);const c=Math.max(...t.map(h=>h.rect.x+h.rect.width),0),d=c>0&&o.width/c>1.5?o.width/Math.max(1280,c):1;for(const h of t){const f=(h.rect.x+h.rect.width/2)*d,w=(h.rect.y+h.rect.height/2)*d,b=16*d;i.fillStyle="rgba(220, 38, 38, 0.92)",i.strokeStyle="rgba(255, 255, 255, 0.95)",i.lineWidth=2*d,i.beginPath(),i.arc(f,w,b,0,2*Math.PI),i.fill(),i.stroke(),i.fillStyle="white",i.font=`bold ${Math.round(18*d)}px sans-serif`,i.textAlign="center",i.textBaseline="middle",i.fillText(String(h.ordinal),f,w)}const p=await(await r.convertToBlob({type:"image/jpeg",quality:.85})).arrayBuffer(),m=new Uint8Array(p);let u="";const g=8192;for(let h=0;h<m.byteLength;h+=g){const f=m.subarray(h,Math.min(h+g,m.byteLength));u+=String.fromCharCode(...f)}return`data:image/jpeg;base64,${btoa(u)}`}catch{return e}}async function la(e,t={}){var i;const a=Date.now(),n=5e3,o=200,r=e;for(;Date.now()-a<n;){const d=(i=(await r.session.send("Runtime.evaluate",{expression:`(() => ({ ready: document.readyState === "complete", focusables: document.querySelectorAll('a[href], button:not([disabled]), input:not([disabled]):not([type="hidden"]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"]):not([disabled]), [contenteditable="true"]').length }))()`,returnByValue:!0})).result)==null?void 0:i.value;if(d&&d.ready&&(d.focusables??0)>0)break;await new Promise(l=>setTimeout(l,o))}t.extraDelayMs&&t.extraDelayMs>0&&await new Promise(c=>setTimeout(c,t.extraDelayMs))}function jn(e){const t=(e.name??"").trim().slice(0,60),a=Math.round(e.rect.x),n=Math.round(e.rect.y),o=Math.round(e.rect.width),r=Math.round(e.rect.height);return`${e.selector}|${e.tag}|${t}|${a},${n},${o},${r}`}async function kd(e,t){const a=JSON.stringify({criterionId:e,sequence:t.map(i=>({o:i.ordinal,s:i.selector,r:i.role,x:Math.round(i.rect.x),y:Math.round(i.rect.y),w:Math.round(i.rect.width),h:Math.round(i.rect.height)}))}),n=new TextEncoder().encode(a),o=await crypto.subtle.digest("SHA-256",n);return Array.from(new Uint8Array(o)).map(i=>i.toString(16).padStart(2,"0")).join("")}const Ba=Z("focus-order-audit"),Ha="2.4.3",xo=50;async function xd(e){var i,c,d;const t=await chrome.storage.local.get("aiConfig"),a=ke(t.aiConfig),n=fe(a);if(!n.ok)return{ok:!1,error:n.reason};const o=n.client;if(typeof o.judgeFocusOrder!="function")return{ok:!1,error:"AI client does not support judgeFocusOrder yet."};const r=new Vn(e.tabId);try{await r.attach(),await la(r),await Id(r),await r.recordStep("initial",{screenshot:!0});const l=await r.countFocusables(),p=l>0?Math.min(xo,l):xo,m=new Set;for(let s=0;s<p;s++){if((i=e.signal)!=null&&i.aborted)return{ok:!1,error:"Audit cancelled."};await r.pressKey("Tab");const x=await r.recordStep(`Tab #${s+1}`,{screenshot:!1});if(x.focused.isBody)break;const $=jn(x.focused);if(m.has($))break;m.add($),(c=e.onStep)==null||c.call(e,{ordinal:x.ordinal,selector:x.focused.selector,role:x.focused.role,name:x.focused.name})}const u=r.steps.filter(s=>s.action!=="initial"&&!s.focused.isBody).map(s=>({ordinal:s.ordinal,selector:s.focused.selector,role:s.focused.role,name:s.focused.name,rect:s.focused.rect})),g=(d=r.steps[0])==null?void 0:d.screenshot,h=g?await Ad(g,u):void 0,f=await kd(Ha,u);let w,b=null;try{b=await Ge(e.componentId,Ha),b&&!Kt(b.reasoning)?w={verdict:b.verdict,reasoning:b.reasoning,confidence:b.confidence}:b&&Kt(b.reasoning)&&Ba.info("Skipping anchor — previous 2.4.3 verdict was cascade-escalated (system-imposed); letting primary judge fresh")}catch{}if(b&&b.inputHash===f&&!Kt(b.reasoning)){Ba.info(`2.4.3 inputs unchanged (hash match: ${f.slice(0,8)}…); reusing previous verdict=${b.verdict} without AI call`);const s={...b,finishedAt:new Date().toISOString(),costUsd:0,model:`${b.model} (cached, hash-match)`,inputHash:f};return await te(s),{ok:!0,result:s}}const k=await nt(()=>o.judgeFocusOrder({pageUrl:e.pageUrl,pageScreenshot:h,tabSequence:u,previousVerdict:w,signal:e.signal})),v={componentId:e.componentId,criterionId:Ha,verdict:k.verdict==="pass"?"pass":k.verdict==="fail"?"fail":"uncertain",reasoning:k.reasoning,confidence:k.confidence,steps:r.steps,pageUrl:e.pageUrl,finishedAt:new Date().toISOString(),costUsd:k.costUsd,model:k.model,inputHash:f};return await te(v),{ok:!0,result:v}}catch(l){return Ba.error("focus-order audit failed",l),{ok:!1,error:l instanceof Error?l.message:String(l)}}finally{await r.dispose()}}async function Id(e){await e.session.send("Runtime.evaluate",{expression:"(() => { if (document.activeElement && document.activeElement !== document.body) document.activeElement.blur(); window.scrollTo(0, 0); })()"})}async function Da(e,t){const a=JSON.stringify({criterionId:e,input:t}),n=new TextEncoder().encode(a),o=await crypto.subtle.digest("SHA-256",n);return Array.from(new Uint8Array(o)).map(i=>i.toString(16).padStart(2,"0")).join("")}async function Na(e,t,a){const n=await Ge(e,t);return n?n.inputHash!==a?{hit:!1,previous:n}:n.verdict==="uncertain"?{hit:!1,previous:n}:Kt(n.reasoning)?{hit:!1,previous:n}:{hit:!0,previous:n}:{hit:!1,previous:null}}function La(e,t){return{...e,finishedAt:new Date().toISOString(),costUsd:0,model:`${e.model} (cached, hash-match)`,inputHash:t}}const qa=Z("keyboard-trap-audit"),xt="2.1.2",Io=50;async function Sd(e){const t=await chrome.storage.local.get("aiConfig"),a=ke(t.aiConfig),n=fe(a);if(!n.ok)return{ok:!1,error:n.reason};const o=n.client;if(typeof o.judgeKeyboardTrap!="function")return{ok:!1,error:"AI client does not support judgeKeyboardTrap yet."};const r=new Vn(e.tabId);try{await r.attach(),await la(r),await So(r),await r.recordStep("initial",{screenshot:!0});const i=await r.countFocusables(),c=i>0?Math.min(Io,i):Io;let d=await Co(r,c,e.signal);if(d.forwardSelectors.length===0&&d.reverseSelectors.length>0&&(qa.info("2.1.2 detected degenerate 0/N walk — retrying after extra hydration wait"),await la(r,{extraDelayMs:1500}),await So(r),d=await Co(r,c,e.signal)),d.forwardSelectors.length===0){const s=Cd(i),x={componentId:e.componentId,criterionId:xt,verdict:s,reasoning:s==="pass"?`The page has ${i} focusable element${i===1?"":"s"} (confirmed by a direct focusable-element count), but the automated forward Tab walk could not traverse them in this session — focus did not enter the page document. This is a known timing/session artifact (most common when this check runs after another keyboard walkthrough during a crawl), not evidence of a problem. No keyboard trap was observed and interactive content is present, so this passes. If you suspect a trap, open the page directly and Tab through it manually.`:`Could not run a meaningful keyboard-trap evaluation: the forward Tab walk found no focusable elements and the page reports none (forward: 0, reverse: ${d.reverseSelectors.length}). Likely a page with no interactive content, or one that is auth-gated / blocks automation. If the page genuinely has no interactive content, mark this criterion as Not Applicable.`,confidence:s==="pass"?.6:.9,steps:r.steps,pageUrl:e.pageUrl,finishedAt:new Date().toISOString(),costUsd:0,model:s==="pass"?"heuristic-reconciled":"heuristic-degenerate-walk"};return await te(x),{ok:!0,result:x}}const{forwardSelectors:l,reverseSelectors:p,stuckRuns:m}=d,u=l.slice(0,-1).reverse(),g=[];for(let s=0;s<Math.min(u.length,p.length);s++){const x=u[s],$=p[s];x!==$&&g.push({index:s,expected:x,actual:$})}const h=$d(u,p,g,m);if(h.detected){const s={componentId:e.componentId,criterionId:xt,verdict:"pass",reasoning:h.reasoning,confidence:.95,steps:r.steps,pageUrl:e.pageUrl,finishedAt:new Date().toISOString(),costUsd:0,model:"heuristic-only"};return await te(s),{ok:!0,result:s}}const f=await Da(xt,{forwardSequence:l,reverseSequence:p,stuckRuns:m,reverseMismatches:g.slice(0,10)}),w=await Na(e.componentId,xt,f);if(w.hit){qa.info(`2.1.2 inputs unchanged (hash match); reusing verdict=${w.previous.verdict}`);const s=La(w.previous,f);return await te(s),{ok:!0,result:s}}const b=w.previous?{verdict:w.previous.verdict,reasoning:w.previous.reasoning,confidence:w.previous.confidence}:void 0,k=await nt(()=>o.judgeKeyboardTrap({pageUrl:e.pageUrl,forwardSequence:l,reverseSequence:p,stuckRuns:m,reverseMismatches:g.slice(0,10),previousVerdict:b,signal:e.signal})),v={componentId:e.componentId,criterionId:xt,verdict:k.verdict==="pass"?"pass":k.verdict==="fail"?"fail":"uncertain",reasoning:k.reasoning,confidence:k.confidence,steps:r.steps,pageUrl:e.pageUrl,finishedAt:new Date().toISOString(),costUsd:k.costUsd,model:k.model,inputHash:f};return await te(v),{ok:!0,result:v}}catch(i){return qa.error("keyboard-trap audit failed",i),{ok:!1,error:i instanceof Error?i.message:String(i)}}finally{await r.dispose()}}async function So(e){await e.session.send("Runtime.evaluate",{expression:"(() => { if (document.activeElement && document.activeElement !== document.body) document.activeElement.blur(); window.scrollTo(0, 0); })()"})}async function Co(e,t,a){const o=[],r=[];for(let m=0;m<t&&!(a!=null&&a.aborted);m++){await e.pressKey("Tab");const u=await e.recordStep(`Tab #${m+1}`,{screenshot:!1});if(u.focused.isBody){if(o.length===0)continue;break}o.push(u.focused.selector);const g=jn(u.focused);if(r.length>2&&g===r[0])break;r.push(g)}const i=[];let c=0;for(let m=1;m<=r.length;m++)if(m===r.length||r[m]!==r[m-1]){const u=m-c;u>=3&&i.push(`${o[c]} (×${u} consecutive)`),c=m}const d=[],p=Math.min(50,t);for(let m=0;m<p&&!(a!=null&&a.aborted);m++){await e.pressKey("Tab",{shift:!0});const u=await e.recordStep(`Shift+Tab #${m+1}`,{screenshot:!1});if(u.focused.isBody||(d.push(u.focused.selector),d.length>=o.length))break}return{forwardSelectors:o,reverseSelectors:d,stuckRuns:i}}function Cd(e){return e>0?"pass":"uncertain"}function $d(e,t,a,n){if(e.length<3||t.length<3)return{detected:!1};if(n.length>0)return{detected:!1};const o=Math.min(e.length,t.length);if(a.length<o-1)return{detected:!1};const r=b=>{let k=0;for(let v=0;v<e.length;v++){const s=t[v+b];s!==void 0&&s===e[v]&&k++}return k},i=r(0),c=r(1),d=r(-1),l=Math.floor(e.length*.7),p=Math.max(c,d);if(p<l||p<=i)return{detected:!1};const m=new Set(e),u=new Set(t),g=[...m].filter(b=>u.has(b)),h=new Set([...m,...u]);return h.size-g.length>2?{detected:!1}:{detected:!0,reasoning:`Comparator artifact detected: every reverse-walk position mismatched by the same ${c>=d?"+1":"-1"} offset, but the SET of focused elements matches the forward walk (${g.length}/${h.size} elements common) and no stuck runs occurred. This is the comparator's index math being off-by-one against actual Shift-Tab semantics, not a real keyboard trap. Pass.`}}const $o=Z("focus-visible-audit"),za="2.4.7",To=30,Td=10;async function Ed(e){var i;const t=await chrome.storage.local.get("aiConfig"),a=ke(t.aiConfig),n=fe(a);if(!n.ok)return{ok:!1,error:n.reason};const o=n.client;if(typeof o.judgeFocusVisible!="function")return{ok:!1,error:"AI client does not support judgeFocusVisible yet."};const r=new Vn(e.tabId);try{await r.attach(),await la(r),await Rd(r);const c=[],d=await r.countFocusables(),l=d>0?Math.min(To,d):To,p=new Set;for(let f=0;f<l&&c.length<Td;f++){if((i=e.signal)!=null&&i.aborted)return{ok:!1,error:"Audit cancelled."};await r.pressKey("Tab");const w=await r.recordStep(`Tab #${f+1}`,{screenshot:!0});if(w.focused.isBody)break;const b=jn(w.focused);if(p.has(b))break;p.add(b);const k=await Od(r);w.screenshot&&c.push({ordinal:c.length+1,selector:w.focused.selector,role:w.focused.role,name:w.focused.name,rect:w.focused.rect,screenshot:w.screenshot,focusStyle:k})}if(c.length===0)return{ok:!1,error:"No focusable elements found on the page; cannot evaluate 2.4.7."};const m=await Da(za,{samples:c.map(f=>({ordinal:f.ordinal,selector:f.selector,role:f.role,focusStyle:f.focusStyle,rect:{x:Math.round(f.rect.x),y:Math.round(f.rect.y),w:Math.round(f.rect.width),h:Math.round(f.rect.height)}}))}),u=await Na(e.componentId,za,m);if(u.hit){$o.info(`2.4.7 inputs unchanged (hash match); reusing verdict=${u.previous.verdict}`);const f=La(u.previous,m);return await te(f),{ok:!0,result:f}}const g=await nt(()=>o.judgeFocusVisible({pageUrl:e.pageUrl,samples:c,signal:e.signal})),h={componentId:e.componentId,criterionId:za,verdict:g.verdict==="pass"?"pass":g.verdict==="fail"?"fail":"uncertain",reasoning:g.reasoning,confidence:g.confidence,steps:r.steps,pageUrl:e.pageUrl,finishedAt:new Date().toISOString(),costUsd:g.costUsd,model:g.model,inputHash:m};return await te(h),{ok:!0,result:h}}catch(c){return $o.error("focus-visible audit failed",c),{ok:!1,error:c instanceof Error?c.message:String(c)}}finally{await r.dispose()}}async function Rd(e){await e.session.send("Runtime.evaluate",{expression:"(() => { if (document.activeElement && document.activeElement !== document.body) document.activeElement.blur(); window.scrollTo(0, 0); })()"})}async function Od(e){const t=`(() => {
833
- const el = document.activeElement;
834
- if (!el || el === document.body) return JSON.stringify({
835
- outlineStyle: '', outlineWidth: '', outlineColor: '', outlineOffset: '',
836
- boxShadow: '', border: '', backgroundColor: '',
837
- });
838
- const cs = getComputedStyle(el);
839
- return JSON.stringify({
840
- outlineStyle: cs.outlineStyle,
841
- outlineWidth: cs.outlineWidth,
842
- outlineColor: cs.outlineColor,
843
- outlineOffset: cs.outlineOffset,
844
- boxShadow: cs.boxShadow,
845
- border: cs.border,
846
- backgroundColor: cs.backgroundColor,
847
- });
848
- })()`;try{const a=await e.session.send("Runtime.evaluate",{expression:t,returnByValue:!0});return JSON.parse(a.result.value)}catch{return{outlineStyle:"",outlineWidth:"",outlineColor:"",outlineOffset:"",boxShadow:"",border:"",backgroundColor:""}}}const Eo=Z("reading-order-audit"),Ht="1.3.2";async function Md(e){var p,m,u;const t=await chrome.storage.local.get("aiConfig"),a=ke(t.aiConfig),n=fe(a);if(!n.ok)return{ok:!1,error:n.reason};const o=n.client;if(typeof o.judgeReadingOrder!="function")return{ok:!1,error:"AI client does not support judgeReadingOrder yet."};const r=((p=e.results[0])==null?void 0:p.readingOrderIssues)??[],i=(m=e.results[0])==null?void 0:m.screenshotDataUrl;if(r.length===0){const g={componentId:e.componentId,criterionId:Ht,verdict:"pass",reasoning:"The reading-order heuristic flagged zero divergences between DOM source order and visual position order. No AI judgment required.",confidence:1,steps:[],pageUrl:e.pageUrl,finishedAt:new Date().toISOString(),costUsd:0,model:"heuristic-only"};return await te(g),{ok:!0,result:g}}if((u=e.signal)!=null&&u.aborted)return{ok:!1,error:"Audit cancelled."};const c=await Da(Ht,{flaggedIssues:r.map(g=>({selector:g.selector,textSnippet:g.textSnippet,domIndex:g.domIndex,visualIndex:g.visualIndex}))}),d=await Na(e.componentId,Ht,c);if(d.hit){Eo.info(`1.3.2 inputs unchanged (hash match); reusing verdict=${d.previous.verdict}`);const g=La(d.previous,c);return await te(g),{ok:!0,result:g}}const l=d.previous?{verdict:d.previous.verdict,reasoning:d.previous.reasoning,confidence:d.previous.confidence}:void 0;try{const g=await nt(()=>o.judgeReadingOrder({pageUrl:e.pageUrl,pageScreenshot:i,flaggedIssues:r.map(f=>({selector:f.selector,textSnippet:f.textSnippet,domIndex:f.domIndex,visualIndex:f.visualIndex,rect:f.boundingRect})),previousVerdict:l,signal:e.signal})),h={componentId:e.componentId,criterionId:Ht,verdict:g.verdict==="pass"?"pass":g.verdict==="fail"?"fail":"uncertain",reasoning:g.reasoning,confidence:g.confidence,steps:[],pageUrl:e.pageUrl,finishedAt:new Date().toISOString(),costUsd:g.costUsd,model:g.model,inputHash:c};return await te(h),{ok:!0,result:h}}catch(g){return Eo.error("reading-order audit failed",g),{ok:!1,error:g instanceof Error?g.message:String(g)}}}const Ro=Z("non-text-contrast-audit"),qt="1.4.11";async function Dd(e){var d,l,p,m;const t=await chrome.storage.local.get("aiConfig"),a=ke(t.aiConfig),n=fe(a);if(!n.ok)return{ok:!1,error:n.reason};const o=n.client;if(typeof o.judgeNonTextContrast!="function")return{ok:!1,error:"AI client does not support judgeNonTextContrast yet."};const r=(d=e.results[0])==null?void 0:d.screenshotDataUrl;if(!r)return{ok:!1,error:"No page screenshot available — re-run the audit so a screenshot is captured."};if((l=e.signal)!=null&&l.aborted)return{ok:!1,error:"Audit cancelled."};let i=null;if(e.tabId!==void 0)try{const u=await chrome.scripting.executeScript({target:{tabId:e.tabId},func:Nd});i=((p=u==null?void 0:u[0])==null?void 0:p.result)??null}catch(u){Ro.warn("component contrast measurement failed; falling back to AI",u)}if(i&&i.measured.length>=1){const u=i.measured.filter(f=>f.ratio<3&&f.confident),g=i.measured.filter(f=>f.ratio>=3),h=i.measured.filter(f=>!f.confident);if(u.length>0){const f={componentId:e.componentId,criterionId:qt,verdict:"fail",reasoning:`Programmatic measurement: ${u.length} of ${i.measured.length} measured components fail WCAG 1.4.11 (< 3:1 contrast against adjacent background). `+u.slice(0,6).map(w=>`${w.selector} — ${w.ratio.toFixed(2)}:1 (${w.borderColor} on ${w.backgroundColor})`).join("; ")+(g.length>0?` · ${g.length} other components pass.`:""),confidence:.98,steps:[],pageUrl:e.pageUrl,finishedAt:new Date().toISOString(),costUsd:0,model:"programmatic-contrast-measurement"};return await te(f),{ok:!0,result:f}}if(h.length===0&&g.length===i.measured.length){const f={componentId:e.componentId,criterionId:qt,verdict:"pass",reasoning:`Programmatic measurement: ${g.length===1?"the":"all"} ${g.length} measured component${g.length===1?"":"s"} pass${g.length===1?"es":""} WCAG 1.4.11 (≥ 3:1 contrast against adjacent background). Lowest measured: ${(m=g.map(w=>w.ratio).sort((w,b)=>w-b)[0])==null?void 0:m.toFixed(2)}:1. Decorative-only graphics and components with transparent borders over images / gradients (which programmatic measurement cannot resolve) are not in scope of this measurement; if such components exist on the page they should be inspected separately.`,confidence:.95,steps:[],pageUrl:e.pageUrl,finishedAt:new Date().toISOString(),costUsd:0,model:"programmatic-contrast-measurement"};return await te(f),{ok:!0,result:f}}}let c;try{const u=await Ge(e.componentId,qt);u&&(c={verdict:u.verdict,reasoning:u.reasoning,confidence:u.confidence})}catch{}try{const u=await nt(()=>o.judgeNonTextContrast({pageUrl:e.pageUrl,pageScreenshot:r,previousVerdict:c,signal:e.signal})),g={componentId:e.componentId,criterionId:qt,verdict:u.verdict==="pass"?"pass":u.verdict==="fail"?"fail":"uncertain",reasoning:u.reasoning,confidence:u.confidence,steps:[],pageUrl:e.pageUrl,finishedAt:new Date().toISOString(),costUsd:u.costUsd,model:u.model};return await te(g),{ok:!0,result:g}}catch(u){return Ro.error("non-text-contrast audit failed",u),{ok:!1,error:u instanceof Error?u.message:String(u)}}}function Nd(){function e(h){const f=h.match(/rgba?\(\s*([0-9.]+)\s*,?\s*([0-9.]+)\s*,?\s*([0-9.]+)(?:\s*[,/]\s*([0-9.]+))?\s*\)/i);if(!f)return null;const w=Math.round(parseFloat(f[1])),b=Math.round(parseFloat(f[2])),k=Math.round(parseFloat(f[3])),v=f[4]!==void 0?parseFloat(f[4]):1;return{r:w,g:b,b:k,a:v}}function t(h){const f=w=>{const b=w/255;return b<=.03928?b/12.92:Math.pow((b+.055)/1.055,2.4)};return .2126*f(h.r)+.7152*f(h.g)+.0722*f(h.b)}function a(h,f){const w=t(h),b=t(f),k=Math.max(w,b),v=Math.min(w,b);return(k+.05)/(v+.05)}function n(h,f){const w=Math.max(0,Math.min(1,h.a));return{r:Math.round(h.r*w+f.r*(1-w)),g:Math.round(h.g*w+f.g*(1-w)),b:Math.round(h.b*w+f.b*(1-w))}}function o(h){let f=h.parentElement;for(;f&&f!==document.documentElement;){const w=getComputedStyle(f);if(w.backgroundImage&&w.backgroundImage!=="none")return{color:w.backgroundColor,hasImage:!0};const k=e(w.backgroundColor);if(k&&k.a>.5)return{color:w.backgroundColor,hasImage:!1};f=f.parentElement}return{color:"rgb(255, 255, 255)",hasImage:!1}}function r(h){if(h.id)return`#${h.id}`;const f=h.tagName.toLowerCase(),w=h.className&&typeof h.className=="string"?h.className.split(/\s+/).filter(Boolean).slice(0,2).join("."):"";return w?`${f}.${w}`:f}function i(h,f){const w=getComputedStyle(h),b=e(w.backgroundColor);return b?b.a>=.999?b:b.a<=.001?f:n(b,f):f}function c(h,f){if((h.textContent??"").trim().length===0)return!1;const w=document.createTreeWalker(h,NodeFilter.SHOW_TEXT);let b;for(;b=w.nextNode();){if((b.textContent??"").trim().length===0)continue;const v=b.parentElement;if(!v)continue;const s=getComputedStyle(v);if(s.visibility==="hidden"||s.display==="none")continue;if(s.position==="absolute"){const D=parseFloat(s.width),S=parseFloat(s.height);if(D>0&&D<=1||S>0&&S<=1||s.clip==="rect(0px, 0px, 0px, 0px)"||s.clipPath==="inset(50%)")continue}const x=e(s.color);if(!x)continue;const $=x.a<1?n(x,f):x,A=a($,f),C=parseFloat(s.fontSize)||16,F=parseInt(s.fontWeight,10)||400,I=C>=24||C>=18.5&&F>=700?3:4.5;if(A>=I)return!0}return!1}function d(h){const f=h.tagName.toLowerCase();if(f==="textarea"||f==="select")return!0;if(f==="input"){const w=(h.getAttribute("type")??"text").toLowerCase();return w!=="hidden"&&w!=="checkbox"&&w!=="radio"&&w!=="submit"&&w!=="button"&&w!=="reset"&&w!=="image"}return!1}function l(h,f){const w=document.activeElement;try{h.focus({preventScroll:!0})}catch{return null}if(document.activeElement!==h){if(w)try{w.focus({preventScroll:!0})}catch{}return null}const b=getComputedStyle(h);let k=0,v="";const s=b.outlineStyle,x=parseFloat(b.outlineWidth)||0;if(s!=="none"&&x>0){const A=e(b.outlineColor);if(A){const C=A.a<1?n(A,f):A,F=a(C,f);F>k&&(k=F,v=`outline ${x}px ${b.outlineColor}`)}}const $=b.boxShadow;if($&&$!=="none"){const A=e($);if(A){const C=A.a<1?n(A,f):A,F=a(C,f);F>k&&(k=F,v=`box-shadow ${$.slice(0,60)}`)}}try{h.blur()}catch{}if(w)try{w.focus({preventScroll:!0})}catch{}return k===0?null:{ratio:k,indicator:v}}function p(h){const f=[{attr:"aria-current",activeVal:"page"},{attr:"aria-pressed",activeVal:"true"},{attr:"aria-selected",activeVal:"true"},{attr:"aria-checked",activeVal:"true"}];let w=null;for(const T of f){const I=h.getAttribute(T.attr);if(I&&(T.attr==="aria-current"?I!=="false"&&I!=="":I===T.activeVal)){w=T;break}}if(!w)return null;const b=h.parentElement;if(!b)return null;const k=h.tagName.toLowerCase(),v=Array.from(b.children).filter(T=>{if(!(T instanceof HTMLElement)||T===h||T.tagName.toLowerCase()!==k)return!1;const I=T.getAttribute(w.attr);return I?w.attr==="aria-current"?I==="false"||I==="":I!==w.activeVal:!0});if(v.length===0)return null;const s=v[0],x=getComputedStyle(h),$=getComputedStyle(s),A=[["backgroundColor","background"],["color","text color"],["borderTopColor","border"]],C=o(h),F=e(C.color);if(!F)return null;for(const[T,I]of A){const D=e(x[T]),S=e($[T]);if(!D||!S||D.r===S.r&&D.g===S.g&&D.b===S.b&&D.a===S.a)continue;const _=D.a<1?n(D,F):D,N=S.a<1?n(S,F):S,O=a(_,N);return{activeColor:_,inactiveColor:N,ratio:O,ariaMarker:`${w.attr}="${h.getAttribute(w.attr)}" vs ${I}`}}return null}const u=Array.from(document.querySelectorAll('input:not([type="hidden"]):not([type="checkbox"]):not([type="radio"]), button, select, textarea, a[href][aria-current], a[href][role="tab"], [role="tab"], [role="button"][aria-pressed], [role="checkbox"][aria-checked]')).filter(h=>{const f=h.getBoundingClientRect();if(f.width<8||f.height<8)return!1;const w=getComputedStyle(h);return!(w.visibility==="hidden"||w.display==="none")}),g=[];for(const h of u){const f=getComputedStyle(h),w=o(h),b=w.hasImage?null:e(w.color),k=b?i(h,b):null;if(b&&k){const A=p(h);A&&A.ratio<3&&g.push({selector:r(h),role:h.getAttribute("role")??h.tagName.toLowerCase(),borderColor:`state: ${A.ariaMarker}`,backgroundColor:`active rgb(${A.activeColor.r},${A.activeColor.g},${A.activeColor.b}) vs inactive rgb(${A.inactiveColor.r},${A.inactiveColor.g},${A.inactiveColor.b})`,ratio:A.ratio,confident:!0})}if(b){const A=l(h,b);A!==null&&A.ratio<3&&g.push({selector:r(h),role:h.getAttribute("role")??h.tagName.toLowerCase(),borderColor:`focus: ${A.indicator}`,backgroundColor:w.color,ratio:A.ratio,confident:!0})}if(parseFloat(f.borderTopWidth)+parseFloat(f.borderRightWidth)+parseFloat(f.borderBottomWidth)+parseFloat(f.borderLeftWidth)===0)continue;const s=e(f.borderTopColor);if(!s)continue;if(w.hasImage){g.push({selector:r(h),role:h.getAttribute("role")??h.tagName.toLowerCase(),borderColor:f.borderTopColor,backgroundColor:w.color,ratio:0,confident:!1});continue}if(!b||!k||!d(h)&&c(h,k))continue;const x=s.a<1?n(s,b):s,$=a(x,b);if(g.push({selector:r(h),role:h.getAttribute("role")??h.tagName.toLowerCase(),borderColor:f.borderTopColor,backgroundColor:w.color,ratio:$,confident:!0}),g.length>=20)break}return{measured:g}}const It=Z("label-in-name-audit"),ot="2.5.3";function Ld(){function e(c){return c.replace(/\s+/g," ").trim().toLowerCase()}function t(c){const d=c.cloneNode(!0);return d.querySelectorAll('[aria-hidden="true"]').forEach(l=>l.remove()),d.querySelectorAll(".sr-only, .visually-hidden, .screen-reader-text, .visuallyhidden").forEach(l=>l.remove()),(d.textContent??"").replace(/\s+/g," ").trim()}function a(c){var m,u,g,h;const d=c.getAttribute("aria-label");if(d&&d.trim())return d.trim();const l=c.getAttribute("aria-labelledby");if(l){const f=l.split(/\s+/).map(w=>document.getElementById(w)).filter(w=>w!==null).map(w=>{var b;return((b=w.textContent)==null?void 0:b.trim())??""}).filter(Boolean);if(f.length>0)return f.join(" ")}if(c.tagName==="INPUT"||c.tagName==="SELECT"||c.tagName==="TEXTAREA"){const f=c.getAttribute("id");if(f){const k=document.querySelector(`label[for="${f}"]`);if(k)return((m=k.textContent)==null?void 0:m.trim())??""}const w=c.closest("label");if(w)return((u=w.textContent)==null?void 0:u.trim())??"";const b=c.getAttribute("placeholder");if(b)return b.trim()}if(c.tagName==="BUTTON"||c.tagName==="A")return((g=c.textContent)==null?void 0:g.trim())??"";const p=c.getAttribute("value");return p&&c.type==="submit"?p.trim():((h=c.textContent)==null?void 0:h.trim())??""}function n(c){if(c.id)return`#${c.id}`;const d=c.tagName.toLowerCase(),l=c.className&&typeof c.className=="string"?"."+c.className.split(/\s+/).filter(Boolean).slice(0,2).join("."):"";return d+l}const o=["a[href]","button","input:not([type=hidden]):not([type=submit])[aria-label], input[aria-labelledby]","input[type=submit]","input[type=button]",'[role="button"]','[role="link"]','[role="checkbox"]','[role="radio"]','[role="switch"]','[role="tab"]','[role="menuitem"]'],r=Array.from(new Set(o.flatMap(c=>Array.from(document.querySelectorAll(c))))).filter(c=>{if(c.hasAttribute("disabled"))return!1;const d=c.getBoundingClientRect();if(d.width===0||d.height===0)return!1;const l=getComputedStyle(c);return!(l.visibility==="hidden"||l.display==="none")}),i=[];for(const c of r){const d=t(c),l=a(c);if(!d||!l)continue;const p=e(d),m=e(l);let u;m.includes(p)?u="pass":m.length===0||p.length===0?u="fail":u="ambiguous";const g=c.getAttribute("role")??c.tagName.toLowerCase();i.push({selector:n(c),role:g,visibleText:d.slice(0,200),accessibleName:l.slice(0,200),programmaticMatch:u})}return i}async function Pd(e){var g,h,f,w;if((g=e.signal)!=null&&g.aborted)return{ok:!1,error:"Audit cancelled."};let t;try{const k=(await chrome.scripting.executeScript({target:{tabId:e.tabId},world:"MAIN",func:Ld}))[0];if(!k||!k.result)return{ok:!1,error:"DOM walker returned no result."};t=k.result}catch(b){return It.warn("DOM walker injection failed",b),{ok:!1,error:`DOM walker failed: ${b instanceof Error?b.message:String(b)}`}}const a=t.filter(b=>b.programmaticMatch==="fail"),n=t.filter(b=>b.programmaticMatch==="ambiguous"),o=t.length;if(o===0){const b={componentId:e.componentId,criterionId:ot,verdict:"pass",reasoning:"No interactive elements with both visible text AND a separate accessible name were found on the page. WCAG 2.5.3 has no applicable controls — counts as pass / not applicable.",confidence:.95,pageUrl:e.pageUrl,finishedAt:new Date().toISOString(),costUsd:0,model:"programmatic-only"};return await te(b),{ok:!0,result:b}}if(a.length===0&&n.length===0){const b={componentId:e.componentId,criterionId:ot,verdict:"pass",reasoning:`${o} interactive controls audited; all visible labels are contained in their accessible names (case-insensitive substring match). WCAG 2.5.3 passes.`,confidence:.95,pageUrl:e.pageUrl,finishedAt:new Date().toISOString(),costUsd:0,model:"programmatic-only"};return await te(b),It.info(`2.5.3 passed programmatically (${o} candidates, all substring-matched)`),{ok:!0,result:b}}const r=await chrome.storage.local.get("aiConfig"),i=ke(r.aiConfig),c=fe(i);if(!c.ok){const b=`Programmatic-only verdict (no AI key configured): ${a.length} candidates with visible text NOT contained in their accessible name. Each of these is likely a WCAG 2.5.3 failure: ${a.slice(0,5).map(v=>`${v.role}/${v.selector} (visible="${v.visibleText.slice(0,50)}", accessible="${v.accessibleName.slice(0,50)}")`).join("; ")}${a.length>5?"; ...":""}. ${n.length} additional candidates are AMBIGUOUS (icon-prefix, plurals, smart-quotes) — configure an AI key to disambiguate.`,k={componentId:e.componentId,criterionId:ot,verdict:a.length>0?"fail":"uncertain",reasoning:b,confidence:.6,pageUrl:e.pageUrl,finishedAt:new Date().toISOString(),costUsd:0,model:"programmatic-only"};return await te(k),{ok:!0,result:k}}const d=c.client;if(typeof d.judgeLabelInName!="function")return{ok:!1,error:"AI client does not support judgeLabelInName."};if((h=e.signal)!=null&&h.aborted)return{ok:!1,error:"Audit cancelled."};const l=(w=(f=e.results)==null?void 0:f[0])==null?void 0:w.screenshotDataUrl,p=[...a,...n],m=await Da(ot,{candidates:p.map(b=>({selector:b.selector,role:b.role,visibleText:b.visibleText,accessibleName:b.accessibleName,programmaticMatch:b.programmaticMatch}))}),u=await Na(e.componentId,ot,m);if(u.hit){It.info(`2.5.3 inputs unchanged (hash match); reusing verdict=${u.previous.verdict}`);const b=La(u.previous,m);return await te(b),{ok:!0,result:b}}try{const b=await nt(()=>d.judgeLabelInName({pageUrl:e.pageUrl,pageScreenshot:l,candidates:p,signal:e.signal})),k=b.verdict==="pass"?"pass":b.verdict==="fail"?"fail":"uncertain",v={componentId:e.componentId,criterionId:ot,verdict:k,reasoning:`${o} interactive controls audited. ${t.length-p.length} passed the strict substring match; ${p.length} (${a.length} strict fails + ${n.length} ambiguous) sent to AI judgment. AI verdict: ${k}. `+b.reasoning,confidence:b.confidence,pageUrl:e.pageUrl,finishedAt:new Date().toISOString(),costUsd:b.costUsd,model:b.model,inputHash:m};return await te(v),It.info(`2.5.3 resolved to ${k} (${p.length} ambiguous cases AI-judged)`),{ok:!0,result:v}}catch(b){return It.error("label-in-name AI judgment failed",b),{ok:!1,error:b instanceof Error?b.message:String(b)}}}const Je=Z("focus-order-cascade");function Fd(){const e=Array.from(document.querySelectorAll('a[href], button, input:not([type=hidden]), select, textarea, [tabindex]:not([tabindex="-1"])')).filter(r=>{if(r.hasAttribute("disabled"))return!1;const i=r.getBoundingClientRect();if(i.width===0||i.height===0)return!1;const c=getComputedStyle(r);return!(c.visibility==="hidden"||c.display==="none")});if(e.length<4)return{matches:!1,pattern:"none",evidence:`only ${e.length} focusable element(s) on page — cascade does not apply`,totalFocusables:e.length,largestCluster:0};const t=new Map;for(const r of e){let i=r.parentElement;for(;i&&i!==document.body&&i!==document.documentElement;){const c=getComputedStyle(i);let d="";if(c.display==="grid"||c.display==="inline-grid"){const l=c.gridTemplateColumns.trim().split(/\s+/).filter(Boolean);l.length>=2&&c.gridTemplateColumns!=="none"&&(d=`grid-${l.length}-cols`)}else if(c.display==="flex"||c.display==="inline-flex")c.flexDirection.startsWith("row")&&(c.flexWrap==="wrap"||c.flexWrap==="wrap-reverse"?d="flex-row-wrap":i.children.length>=2&&(d="flex-row"));else{const l=c.columnCount;l&&l!=="auto"&&parseInt(l,10)>=2&&(d=`css-columns-${l}`)}if(d){const l=t.get(i);l?l.count++:t.set(i,{count:1,pattern:d});break}i=i.parentElement}}let a={count:0,pattern:"none"};for(const r of t.values())r.count>a.count&&(a={count:r.count,pattern:r.pattern});const n=Math.max(2,Math.ceil(e.length*.3)),o=a.count>=n;return{matches:o,pattern:o?a.pattern:"none",evidence:o?`${a.count} of ${e.length} focusable elements share a ${a.pattern} container (threshold ${n})`:`largest multi-column cluster was ${a.count} of ${e.length} focusables; threshold was ${n} — no dominant banked layout`,totalFocusables:e.length,largestCluster:a.count}}function _d(){const e='a[href], button:not([disabled]), input:not([disabled]):not([type="hidden"]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"]):not([disabled])',t=Array.from(document.querySelectorAll('nav, [role="navigation"], [role="group"], section[aria-labelledby], section[aria-label], aside[aria-labelledby], aside[aria-label], header[aria-labelledby], footer[aria-labelledby]')),a=t.filter(r=>t.some(i=>i!==r&&i.contains(r))?!1:!t.some(i=>i!==r&&r.contains(i)));let n=0;for(const r of a)r.querySelector(e)&&n++;const o=n>=2;return{matches:o,evidence:o?`${n} distinct labeled navigation regions found on page (e.g., multiple <nav> blocks in a footer). Column-first focus traversal across these groups is a valid pattern — screen readers announce each group's label before its contents.`:`${n} labeled navigation region(s) found — need ≥2 with focusable content to trigger multi-region override`,groupCount:a.length,groupsWithFocusables:n}}async function Ud(e){if(e.focusOrderVerdict!=="uncertain")return{ran:!1,reason:`2.4.3 verdict was ${e.focusOrderVerdict}, not uncertain — cascade does not apply`};if(e.keyboardTrapVerdict!=="pass")return{ran:!1,reason:`2.1.2 verdict was ${e.keyboardTrapVerdict??"absent"}, not pass — cascade does not apply (need empirical focus-path functionality)`};const t=await Ge(e.componentId,"2.4.3");if(!t)return{ran:!1,reason:"2.4.3 record not found in storage — cannot apply cascade"};let a=null;try{const i=(await chrome.scripting.executeScript({target:{tabId:e.tabId},world:"MAIN",func:Fd}))[0];i&&i.result&&(a=i.result)}catch(r){Je.warn("focus-order cascade detector failed",r)}if(a&&a.matches){const r={...t,verdict:"pass",reasoning:t.reasoning+`
849
-
850
- [Cascade resolution — rc.167 fallback-1]
851
- Primary AI verdict was uncertain. WCAG 2.1.2 No Keyboard Trap PASSED on the same DOM (Tab walks forward AND Shift+Tab walks back through every focusable). The programmatic multi-column layout detector confirmed: `+a.evidence+`. The heuristic's "reverse y-coordinate" complaint is a known false-positive pattern for banked layouts — combined with the empirical 2.1.2 PASS, this resolves to PASS. If the visual reading order is intentionally column-first (typical for footers, sidebars, card grids), this is correct behavior.`};return await te(r),Je.info(`2.4.3 cascade resolved uncertain → pass via fallback-1 (${a.pattern}, ${a.largestCluster}/${a.totalFocusables} focusables clustered)`),{ran:!0,resolved:"pass",via:"fallback-1",pattern:a.pattern,evidence:a.evidence}}const n=await Wd(e,t);if(n.ran&&n.resolved==="pass"||n.ran&&n.resolved==="fail")return n;const o={...t,verdict:"fail",reasoning:t.reasoning+`
852
-
853
- [Cascade resolution — rc.169 escalation]
854
- All cascade fallbacks returned uncertain. Primary AI judgment: uncertain. Programmatic multi-column-layout detector: `+(a?a.evidence:"did not run (script injection failed)")+". Focused AI re-call (fallback 2): "+(n.ran?n.evidence??"returned uncertain":n.reason)+". Marked as FAIL with required manual verification — the user can override this verdict via the human-review UI in the side panel."};return await te(o),Je.info("2.4.3 cascade escalated to FAIL — all fallbacks returned uncertain; manual verification required"),{ran:!0,resolved:"fail",via:"escalation",evidence:"all fallbacks returned uncertain; verdict escalated to fail pending manual verification"}}async function Wd(e,t){if(!e.tabSequence||e.tabSequence.length===0)return{ran:!0,resolved:"uncertain",via:"none",evidence:"fallback-2 skipped — no tab sequence provided (primary walkthrough did not capture steps)"};let a;try{const r=await chrome.storage.local.get("aiConfig");a=ke(r.aiConfig)}catch(r){return Je.warn("fallback-2: failed to read aiConfig",r),{ran:!0,resolved:"uncertain",via:"none",evidence:"fallback-2 skipped — could not load aiConfig"}}const n=fe(a);if(!n.ok)return{ran:!0,resolved:"uncertain",via:"none",evidence:`fallback-2 skipped — ${n.reason}`};const o=n.client;if(typeof o.judgeFocusOrderFallback!="function")return{ran:!0,resolved:"uncertain",via:"none",evidence:"fallback-2 skipped — AI client does not support judgeFocusOrderFallback (older provider)"};try{const r=await nt(()=>o.judgeFocusOrderFallback({pageUrl:e.pageUrl,pageScreenshot:e.pageScreenshot,tabSequence:e.tabSequence,primaryUncertainReason:t.reasoning,signal:e.signal}));if(r.verdict==="pass"){const i={...t,verdict:"pass",reasoning:t.reasoning+`
855
-
856
- [Cascade resolution — rc.169 fallback-2]
857
- Primary AI verdict was uncertain. Programmatic multi-column detector found no matching pattern (long-tail case). Focused AI re-call resolved to PASS with reasoning: `+r.reasoning+`
858
-
859
- The focused prompt explicitly enumerates long-tail false-positive patterns (custom JS focus management, roving tabindex composite widgets, sticky sidebars, skip-link patterns, modal traps, table layouts, absolute positioning) — when the AI identifies one of these AND the tab sequence is consistent with the pattern, the cascade resolves to PASS.`,costUsd:t.costUsd+r.costUsd};return await te(i),Je.info("2.4.3 cascade resolved uncertain → pass via fallback-2 (focused AI re-call)"),{ran:!0,resolved:"pass",via:"fallback-2",evidence:`focused AI re-call returned pass with confidence ${r.confidence.toFixed(2)}`}}if(r.verdict==="fail"){const i={...t,verdict:"fail",reasoning:t.reasoning+`
860
-
861
- [Cascade resolution — rc.169 fallback-2]
862
- Primary AI verdict was uncertain. Programmatic multi-column detector found no matching pattern. Focused AI re-call resolved to FAIL with reasoning: `+r.reasoning,costUsd:t.costUsd+r.costUsd};return await te(i),Je.info("2.4.3 cascade resolved uncertain → fail via fallback-2 (focused AI re-call detected a real failure)"),{ran:!0,resolved:"fail",via:"fallback-2",evidence:`focused AI re-call returned fail with confidence ${r.confidence.toFixed(2)}`}}return{ran:!0,resolved:"uncertain",via:"fallback-2",evidence:`focused AI re-call also returned uncertain — ${r.reasoning.slice(0,200)}`}}catch(r){return Je.warn("fallback-2 AI re-call threw",r),{ran:!0,resolved:"uncertain",via:"none",evidence:`fallback-2 AI re-call threw: ${r instanceof Error?r.message:String(r)}`}}}async function Pa(){const e=await pe();return he(e,"aiWalkthroughs")}const be=Z("interactive-walkthroughs");async function ct(e,t){if(!e.verifyFixesOnly)return null;const a=await Ge(e.componentId,t);return a?await gc(e.componentId,t,e.pageUrl)?(be.info(`${t} skipped (verify-fixes): ack present`),a):a.verdict==="pass"?(be.info(`${t} skipped (verify-fixes): previously passed`),a):null:null}async function Gd(e){var a,n,o,r,i,c,d;if(!await Pa())return[{criterionId:"2.4.3",ran:!1,ok:!0,error:"AI walkthroughs not available on current plan"},{criterionId:"2.1.2",ran:!1,ok:!0,error:"AI walkthroughs not available on current plan"},{criterionId:"2.4.7",ran:!1,ok:!0,error:"AI walkthroughs not available on current plan"}];const t=[];try{if((a=e.signal)!=null&&a.aborted)t.push({criterionId:"2.4.3",ran:!1,ok:!1,error:"cancelled"});else{const l=await ct(e,"2.4.3");if(l)t.push({criterionId:"2.4.3",ran:!1,ok:!0,verdict:l.verdict,skippedForVerifyFixes:!0});else{const p=await xd({tabId:e.tabId,componentId:e.componentId,pageUrl:e.pageUrl,signal:e.signal});t.push({criterionId:"2.4.3",ran:!0,ok:p.ok,verdict:p.ok?p.result.verdict:void 0,error:p.ok?void 0:p.error})}}}catch(l){be.warn("2.4.3 walkthrough threw",l),t.push({criterionId:"2.4.3",ran:!0,ok:!1,error:l instanceof Error?l.message:String(l)})}try{if((n=e.signal)!=null&&n.aborted)t.push({criterionId:"2.1.2",ran:!1,ok:!1,error:"cancelled"});else{const l=await ct(e,"2.1.2");if(l)t.push({criterionId:"2.1.2",ran:!1,ok:!0,verdict:l.verdict,skippedForVerifyFixes:!0});else{const p=await Sd({tabId:e.tabId,componentId:e.componentId,pageUrl:e.pageUrl,signal:e.signal});t.push({criterionId:"2.1.2",ran:!0,ok:p.ok,verdict:p.ok?p.result.verdict:void 0,error:p.ok?void 0:p.error})}}}catch(l){be.warn("2.1.2 walkthrough threw",l),t.push({criterionId:"2.1.2",ran:!0,ok:!1,error:l instanceof Error?l.message:String(l)})}try{if((o=e.signal)!=null&&o.aborted)t.push({criterionId:"2.4.7",ran:!1,ok:!1,error:"cancelled"});else{const l=await ct(e,"2.4.7");if(l)t.push({criterionId:"2.4.7",ran:!1,ok:!0,verdict:l.verdict,skippedForVerifyFixes:!0});else{const p=await Ed({tabId:e.tabId,componentId:e.componentId,pageUrl:e.pageUrl,signal:e.signal});t.push({criterionId:"2.4.7",ran:!0,ok:p.ok,verdict:p.ok?p.result.verdict:void 0,error:p.ok?void 0:p.error})}}}catch(l){be.warn("2.4.7 walkthrough threw",l),t.push({criterionId:"2.4.7",ran:!0,ok:!1,error:l instanceof Error?l.message:String(l)})}try{const l=t.find(p=>p.criterionId==="2.4.3");if(l!=null&&l.ok&&l.verdict==="fail"){const p=await chrome.scripting.executeScript({target:{tabId:e.tabId},func:_d}),m=(r=p==null?void 0:p[0])==null?void 0:r.result;if(m!=null&&m.matches){const u=await Ge(e.componentId,"2.4.3");if(u&&u.verdict==="fail"){const g={...u,verdict:"pass",reasoning:u.reasoning+`
863
-
864
- [Labeled-group nav override — rc.270] Programmatic detector found ${m.groupsWithFocusables} distinct labeled navigation regions on this page. ${m.evidence} Per WCAG 2.4.3, column-first traversal ACROSS distinct labeled regions is a valid focus order — the user can locate themselves via each region's label (announced by screen readers) before traversing within the region. Overriding fail → pass.`};await te(g),l.verdict="pass",be.info(`2.4.3 fail overridden → pass (rc.270 labeled-group nav: ${m.groupsWithFocusables} regions)`)}}}}catch(l){be.warn("2.4.3 labeled-group nav override step failed",l)}try{const l=t.find(m=>m.criterionId==="2.4.3"),p=t.find(m=>m.criterionId==="2.1.2");if(l!=null&&l.ok&&l.verdict==="fail"&&(p!=null&&p.ok)&&p.verdict==="pass"){const m=await Ge(e.componentId,"2.4.3");if(m&&m.verdict==="fail"){const u={...m,verdict:"uncertain",reasoning:m.reasoning+`
865
-
866
- [Cross-corroboration override] WCAG 2.1.2 No Keyboard Trap PASSED on this same DOM. Tab walks forward AND Shift+Tab walks back. The "reverse y-coordinate" pattern this rule flagged is consistent with a multi-column or banked layout (header → main → sidebar → footer), not an actual focus-order break. Downgraded fail → uncertain. Verify manually if the visual reading order is ambiguous.`};await te(u),l.verdict="uncertain",be.info("2.4.3 fail downgraded to uncertain — 2.1.2 PASSed (multi-column layout corroboration)")}}}catch(l){be.warn("2.4.3 ↔ 2.1.2 cross-corroboration step failed",l)}try{const l=t.find(m=>m.criterionId==="2.4.3"),p=t.find(m=>m.criterionId==="2.1.2");if(l&&l.verdict==="uncertain"&&(p==null?void 0:p.verdict)==="pass"){const m=await Ge(e.componentId,"2.4.3"),u=await Ud({tabId:e.tabId,componentId:e.componentId,pageUrl:e.pageUrl,focusOrderVerdict:l.verdict,keyboardTrapVerdict:p.verdict,tabSequence:(i=m==null?void 0:m.steps)==null?void 0:i.filter(g=>g.action!=="initial").map(g=>({ordinal:g.ordinal,selector:g.focused.selector,role:g.focused.role,name:g.focused.name,rect:g.focused.rect??{x:0,y:0,width:0,height:0}})),pageScreenshot:(d=(c=m==null?void 0:m.steps)==null?void 0:c[0])==null?void 0:d.screenshot,signal:e.signal});u.ran&&u.resolved==="pass"?(l.verdict="pass",be.info(`2.4.3 uncertain resolved to PASS via cascade ${u.via} (${u.pattern??u.evidence.slice(0,80)})`)):u.ran&&u.resolved==="fail"?(l.verdict="fail",be.info(`2.4.3 resolved to FAIL via cascade ${u.via}: ${u.evidence.slice(0,80)}`)):u.ran&&u.resolved==="uncertain"?be.info("2.4.3 cascade exhausted all paths — uncertain stays. (this shouldn't happen post-rc.169; escalation should have fired)"):u.ran||be.info(`2.4.3 cascade did not run: ${u.reason}`)}}catch(l){be.warn("2.4.3 cascade step failed",l)}return t}async function Vd(e){var t;try{if(!await Pa())return{criterionId:"1.3.2",ran:!1,ok:!0,error:"AI walkthroughs not available on current plan"};if((t=e.signal)!=null&&t.aborted)return{criterionId:"1.3.2",ran:!1,ok:!1,error:"cancelled"};const a=await ct(e,"1.3.2");if(a)return{criterionId:"1.3.2",ran:!1,ok:!0,verdict:a.verdict,skippedForVerifyFixes:!0};if(!e.results||e.results.length===0)return{criterionId:"1.3.2",ran:!1,ok:!1,error:"no audit results available"};const n=await Md({componentId:e.componentId,pageUrl:e.pageUrl,results:e.results,signal:e.signal});return{criterionId:"1.3.2",ran:!0,ok:n.ok,verdict:n.ok?n.result.verdict:void 0,error:n.ok?void 0:n.error}}catch(a){return be.warn("1.3.2 walkthrough threw",a),{criterionId:"1.3.2",ran:!0,ok:!1,error:a instanceof Error?a.message:String(a)}}}async function jd(e){var t;try{if(!await Pa())return{criterionId:"1.4.11",ran:!1,ok:!0,error:"AI walkthroughs not available on current plan"};if((t=e.signal)!=null&&t.aborted)return{criterionId:"1.4.11",ran:!1,ok:!1,error:"cancelled"};const a=await ct(e,"1.4.11");if(a)return{criterionId:"1.4.11",ran:!1,ok:!0,verdict:a.verdict,skippedForVerifyFixes:!0};if(!e.results||e.results.length===0)return{criterionId:"1.4.11",ran:!1,ok:!1,error:"no audit results available"};const n=await Dd({componentId:e.componentId,pageUrl:e.pageUrl,results:e.results,signal:e.signal,tabId:e.tabId});return{criterionId:"1.4.11",ran:!0,ok:n.ok,verdict:n.ok?n.result.verdict:void 0,error:n.ok?void 0:n.error}}catch(a){return be.warn("1.4.11 walkthrough threw",a),{criterionId:"1.4.11",ran:!0,ok:!1,error:a instanceof Error?a.message:String(a)}}}async function Bd(e){var t;try{if(!await Pa())return{criterionId:"2.5.3",ran:!1,ok:!0,error:"AI walkthroughs not available on current plan"};if((t=e.signal)!=null&&t.aborted)return{criterionId:"2.5.3",ran:!1,ok:!1,error:"cancelled"};const a=await ct(e,"2.5.3");if(a)return{criterionId:"2.5.3",ran:!1,ok:!0,verdict:a.verdict,skippedForVerifyFixes:!0};const n=await Pd({tabId:e.tabId,componentId:e.componentId,pageUrl:e.pageUrl,results:e.results,signal:e.signal});return{criterionId:"2.5.3",ran:!0,ok:n.ok,verdict:n.ok?n.result.verdict:void 0,error:n.ok?void 0:n.error}}catch(a){return be.warn("2.5.3 walkthrough threw",a),{criterionId:"2.5.3",ran:!0,ok:!1,error:a instanceof Error?a.message:String(a)}}}async function Oo(e){const t=JSON.stringify({algo:"css-crosscheck-bgfp4-gradient",ruleId:e.ruleId,selector:e.selector,fg:e.foreground??null,fs:e.fontSize??null,fw:e.fontWeight??null,summary:e.failureSummary??null,bgfp:e.bgFingerprint??null}),a=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",a);return Array.from(new Uint8Array(n)).map(o=>o.toString(16).padStart(2,"0")).join("")}const Xe=Z("pixel-contrast-sampler"),Hd="1.3",Ka=4.5,Ya=3;function Ja(e,t){return e?e>=24||e>=18.66&&(t??400)>=700:!1}function qd(e){if(!e)return null;const t=/^rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/.exec(e);if(t)return{r:Number(t[1]),g:Number(t[2]),b:Number(t[3])};const a=/^#([0-9a-f])([0-9a-f])([0-9a-f])$/i.exec(e);if(a)return{r:parseInt(a[1]+a[1],16),g:parseInt(a[2]+a[2],16),b:parseInt(a[3]+a[3],16)};const n=/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i.exec(e);return n?{r:parseInt(n[1],16),g:parseInt(n[2],16),b:parseInt(n[3],16)}:null}function Mo({r:e,g:t,b:a}){const n=o=>{const r=o/255;return r<=.03928?r/12.92:Math.pow((r+.055)/1.055,2.4)};return .2126*n(e)+.7152*n(t)+.0722*n(a)}function Et(e,t){const a=Mo(e),n=Mo(t),o=Math.max(a,n),r=Math.min(a,n);return(o+.05)/(r+.05)}function zd(e,t,a,n){return e>=n||!a?!1:Et(t,a)>=n}async function Kd(e,t){var n;const a=`(() => {
867
- const dpr = window.devicePixelRatio || 1;
868
- const sx = window.scrollX || 0;
869
- const sy = window.scrollY || 0;
870
- const sels = ${JSON.stringify(t)};
871
- const out = {};
872
- // rc.225 — Filter visually-hidden elements BEFORE the sampler runs.
873
- // ada.gov's .usa-sr-only is the smoking gun: position:absolute +
874
- // clip:rect(0,0,0,0) + width:1px means it's intentionally invisible
875
- // to sighted users. axe-core's incomplete logic doesn't always know
876
- // this, and the sampler then produces a meaningless 1:1 ratio. The
877
- // checks below are the same patterns CSS authors use for "visually
878
- // hidden, still in a11y tree" — collectively they cover every
879
- // mainstream framework's sr-only utility (USWDS, Bootstrap,
880
- // Tailwind's .sr-only, Material's .mat-sr-only, etc.).
881
- function isVisuallyHidden(el, r) {
882
- const cs = getComputedStyle(el);
883
- if (cs.display === 'none') return true;
884
- // rc.407 — Skip aria-hidden decorative subtrees. They are removed from the
885
- // accessibility tree and are not "text" for WCAG 1.4.3 — a visible
886
- // decorative glyph (e.g. an aria-hidden SVG arrow whose stroke is
887
- // currentColor) must NOT be measured as failing text contrast. This was a
888
- // real false positive: a decorative gold arrow got reported as
889
- // black 1.17:1 and dropped a clean site to a "C".
890
- if (el.closest && el.closest('[aria-hidden="true"]')) return true;
891
- if (cs.visibility === 'hidden' || cs.visibility === 'collapse') return true;
892
- if (parseFloat(cs.opacity || '1') === 0) return true;
893
- // Sub-pixel sizing pattern (sr-only): width 1px, height 1px.
894
- if (r.width <= 1 && r.height <= 1) return true;
895
- // Classic clip: rect(0,0,0,0) — older sr-only pattern.
896
- const clip = cs.clip || '';
897
- if (/rect\\(0\\w*,?\\s*0\\w*,?\\s*0\\w*,?\\s*0\\w*\\)/i.test(clip)) return true;
898
- // Modern clip-path: inset(50%) or inset(100%) — current sr-only.
899
- const clipPath = cs.clipPath || cs.webkitClipPath || '';
900
- if (/inset\\(50%|inset\\(100%/i.test(clipPath)) return true;
901
- // Off-screen positioning: top/left far enough out that no real
902
- // user can see them. Heuristic — only fires when the absolute
903
- // offset is wildly large.
904
- if (cs.position === 'absolute' || cs.position === 'fixed') {
905
- const top = parseFloat(cs.top || '0');
906
- const left = parseFloat(cs.left || '0');
907
- if (top <= -9999 || left <= -9999) return true;
908
- }
909
- return false;
910
- }
911
- // rc.356 — Resolve the element's effective background to a solid color
912
- // by walking ancestors. Returns null (= "let the pixel sampler decide")
913
- // when any ancestor in the stack has a background image/gradient or a
914
- // semi-transparent background layer — those genuinely can't be reduced
915
- // to one flat color. All-transparent up to the root → the canvas
916
- // default (white). This is the truth the sampler's pixel-derived
917
- // "dominant background" sometimes gets wrong (anti-aliased blends).
918
- function resolveBg(el) {
919
- let node = el;
920
- while (node && node.nodeType === 1) {
921
- const cs = getComputedStyle(node);
922
- if (cs.backgroundImage && cs.backgroundImage !== 'none') return null;
923
- const m = /^rgba?\\(\\s*(\\d+)\\s*,\\s*(\\d+)\\s*,\\s*(\\d+)\\s*(?:,\\s*([\\d.]+))?\\)/.exec(cs.backgroundColor || '');
924
- if (m) {
925
- const a = m[4] === undefined ? 1 : parseFloat(m[4]);
926
- if (a >= 0.999) return { r: +m[1], g: +m[2], b: +m[3] };
927
- if (a > 0) return null; // semi-transparent → compositing ambiguous
928
- // a === 0 fully transparent → keep walking up
929
- }
930
- node = node.parentElement;
931
- }
932
- return { r: 255, g: 255, b: 255 }; // reached root, all transparent, no image → browser default
933
- }
934
- // rc.413 — When the effective background is a simple linear-gradient of SOLID
935
- // rgb stops, resolveBg returns null (can't reduce a gradient to one flat
936
- // color) — but contrast is still decidable: return the gradient's stop colors
937
- // so the sampler computes the WORST-CASE ratio (fg vs the least-contrasting
938
- // stop). Mirrors resolveBg's ancestor walk. Returns null for solid bg
939
- // (resolveBg handles it), images (url(...)), or a gradient with any
940
- // translucent/non-rgb stop.
941
- function resolveBgGradient(el) {
942
- let node = el;
943
- while (node && node.nodeType === 1) {
944
- const cs = getComputedStyle(node);
945
- const img = cs.backgroundImage;
946
- if (img && img !== 'none') {
947
- if (/linear-gradient\\(/i.test(img) && !/url\\(/i.test(img)) {
948
- const stops = [];
949
- const re = /rgba?\\(\\s*(\\d+)\\s*,\\s*(\\d+)\\s*,\\s*(\\d+)\\s*(?:,\\s*([\\d.]+))?\\)/g;
950
- let m;
951
- while ((m = re.exec(img)) !== null) {
952
- const a = m[4] === undefined ? 1 : parseFloat(m[4]);
953
- if (a < 0.999) return null; // a translucent stop → compositing ambiguous
954
- stops.push({ r: +m[1], g: +m[2], b: +m[3] });
955
- }
956
- return stops.length >= 2 ? stops : null;
957
- }
958
- return null; // image or unparseable gradient
959
- }
960
- const m = /^rgba?\\(\\s*(\\d+)\\s*,\\s*(\\d+)\\s*,\\s*(\\d+)\\s*(?:,\\s*([\\d.]+))?\\)/.exec(cs.backgroundColor || '');
961
- if (m) {
962
- const a = m[4] === undefined ? 1 : parseFloat(m[4]);
963
- if (a >= 0.999) return null; // solid bg — resolveBg handles it
964
- }
965
- node = node.parentElement;
966
- }
967
- return null;
968
- }
969
- // Background fingerprint: computed background-color + background-image of
970
- // the element and every ancestor up to the root. Unlike resolveBg (which
971
- // collapses to null on gradients/images), this changes on ANY background
972
- // change, so it can key the sampler cache and force a re-measure after a
973
- // re-theme (the dark→light staleness bug).
974
- function bgFingerprint(el) {
975
- const parts = [];
976
- let node = el;
977
- while (node && node.nodeType === 1) {
978
- const cs = getComputedStyle(node);
979
- parts.push((cs.backgroundColor || '') + ';' + (cs.backgroundImage || 'none'));
980
- node = node.parentElement;
981
- }
982
- return parts.join('|');
983
- }
984
- for (const sel of sels) {
985
- try {
986
- const el = document.querySelector(sel);
987
- if (!el) { out[sel] = null; continue; }
988
- const r = el.getBoundingClientRect();
989
- if (r.width === 0 || r.height === 0) { out[sel] = null; continue; }
990
- // rc.409 — Decorative / visually-hidden (incl. aria-hidden subtrees):
991
- // mark distinctly so the caller resolves it as a not-applicable 'pass',
992
- // rather than measuring it and emitting a misleading 'fail'/'uncertain'.
993
- if (isVisuallyHidden(el, r)) { out[sel] = { decorative: true }; continue; }
994
- out[sel] = {
995
- x: r.left + sx,
996
- y: r.top + sy,
997
- width: r.width,
998
- height: r.height,
999
- devicePixelRatio: dpr,
1000
- selector: sel,
1001
- resolvedBg: resolveBg(el),
1002
- resolvedBgGradient: resolveBgGradient(el),
1003
- bgFingerprint: bgFingerprint(el),
1004
- };
1005
- } catch { out[sel] = null; }
1006
- }
1007
- return JSON.stringify(out);
1008
- })()`;try{const o=await chrome.debugger.sendCommand({tabId:e},"Runtime.evaluate",{expression:a,returnByValue:!0}),r=(n=o==null?void 0:o.result)==null?void 0:n.value;if(!r||typeof r!="string")return new Map;const i=JSON.parse(r);return new Map(Object.entries(i))}catch(o){return Xe.debug("getAllRectsAtOnce failed",o),new Map}}const Bn="__wcagcheckr_hidetext";async function Yd(e){const t=`
1009
- (async () => {
1010
- // Wait for fonts so hide/restore screenshots show identical glyph metrics.
1011
- try { await document.fonts.ready; } catch {}
1012
- const s = document.createElement('style');
1013
- s.id = ${JSON.stringify(Bn)};
1014
- s.textContent = '*, *::before, *::after { color: transparent !important; text-shadow: none !important; -webkit-text-fill-color: transparent !important; caret-color: transparent !important; }';
1015
- document.documentElement.appendChild(s);
1016
- // Force a reflow + paint so the next screenshot captures the new state.
1017
- document.body.offsetHeight;
1018
- return true;
1019
- })()
1020
- `;await chrome.debugger.sendCommand({tabId:e},"Runtime.evaluate",{expression:t,awaitPromise:!0})}async function Jd(e){const t=`
1021
- (() => {
1022
- const el = document.getElementById(${JSON.stringify(Bn)});
1023
- if (el) el.remove();
1024
- document.body.offsetHeight;
1025
- return true;
1026
- })()
1027
- `;await chrome.debugger.sendCommand({tabId:e},"Runtime.evaluate",{expression:t})}async function Do(e,t){let a;try{a=await chrome.debugger.sendCommand({tabId:e},"Page.captureScreenshot",{format:"png",captureBeyondViewport:!0,clip:{x:t.x,y:t.y,width:t.width,height:t.height,scale:1}})}catch(n){return Xe.warn(`captureElementClip failed: ${n instanceof Error?n.message:String(n)}`),null}if(!(a!=null&&a.data))return null;try{const n=`data:image/png;base64,${a.data}`,o=await fetch(n).then(d=>d.blob()),r=await createImageBitmap(o),c=new OffscreenCanvas(r.width,r.height).getContext("2d");return c?(c.drawImage(r,0,0),c.getImageData(0,0,r.width,r.height)):null}catch(n){return Xe.warn(`clip decode failed: ${n instanceof Error?n.message:String(n)}`),null}}const Xd=25,Jt=8,Qd=150,Zd=.95,eu=4,tu=400;function au(e,t,a){if(e.width!==t.width||e.height!==t.height)return null;const n=e.width,o=e.height;let r=0,i=0;for(let v=0;v<o;v++)for(let s=0;s<n;s++){const x=(v*n+s)*4,$=t.data[x],A=t.data[x+1],C=t.data[x+2],F=e.data[x],T=e.data[x+1],I=e.data[x+2],D=Math.abs(F-$)+Math.abs(T-A)+Math.abs(I-C);D>i&&(i=D),D>=Xd&&r++}if(r<Jt)return null;const c=i*Zd;let d=0,l=0,p=0,m=0;if(i>=tu)for(let v=0;v<o;v++)for(let s=0;s<n;s++){const x=(v*n+s)*4,$=t.data[x],A=t.data[x+1],C=t.data[x+2],F=e.data[x],T=e.data[x+1],I=e.data[x+2];Math.abs(F-$)+Math.abs(T-A)+Math.abs(I-C)>=c&&(d+=$,l+=A,p+=C,m++)}const u=m>=eu?{r:Math.round(d/m),g:Math.round(l/m),b:Math.round(p/m)}:a,g=new Map;let h=0;for(let v=0;v<o;v++)for(let s=0;s<n;s++){const x=(v*n+s)*4,$=t.data[x],A=t.data[x+1],C=t.data[x+2];if(Math.abs($-u.r)+Math.abs(A-u.g)+Math.abs(C-u.b)>=Qd){h++;const T=$>>4<<8|A>>4<<4|C>>4,I=g.get(T);I?(I.r+=$,I.g+=A,I.b+=C,I.count++):g.set(T,{r:$,g:A,b:C,count:1})}}const f=n*o;if(h<f*.2){g.clear();for(let v=0;v<o;v++)for(let s=0;s<n;s++){const x=(v*n+s)*4,$=e.data[x],A=e.data[x+1],C=e.data[x+2],F=$>>4<<8|A>>4<<4|C>>4,T=g.get(F);T?(T.r+=$,T.g+=A,T.b+=C,T.count++):g.set(F,{r:$,g:A,b:C,count:1})}}let w={r:0,g:0,b:0,count:0};for(const v of g.values())v.count>w.count&&(w=v);const b={r:Math.round(w.r/w.count),g:Math.round(w.g/w.count),b:Math.round(w.b/w.count)},k=Et(u,b);return{textPixelCount:r,worstRatio:k,worstBackground:b,worstForeground:u}}async function nu(e,t,a){var d,l,p,m,u,g;const n=new Map;for(const h of t){const f=h.pageUrl??h.scope??"";for(const w of((d=h.axeRulesEvaluated)==null?void 0:d.incomplete)??[])if(w.ruleId==="color-contrast")for(const b of w.elements??[]){const k=`${f}::${w.ruleId}::${b.selector}`;n.has(k)||n.set(k,{pageUrl:f,ruleId:w.ruleId,selector:b.selector,wcagCriterion:w.wcagCriterion??"1.4.3",foreground:(l=b.styles)==null?void 0:l.foreground,fontSize:(p=b.styles)==null?void 0:p.fontSize,fontWeight:(m=b.styles)==null?void 0:m.fontWeight,failureSummary:b.failureSummary})}}if(n.size===0)return{resolved:0,skipped:0};let o=!1,r=null;for(let h=1;h<=6;h++)try{await chrome.debugger.attach({tabId:e},Hd),o=!0;break}catch(f){r=f;const w=f instanceof Error?f.message:String(f);if(/already attached/i.test(w)){await new Promise(b=>setTimeout(b,500));continue}break}if(!o)return Xe.warn("debugger attach failed after retries; skipping pixel sampling",r),{resolved:0,skipped:n.size};let i=0,c=0;try{const h=Array.from(n.values()),f=h.map(I=>I.selector),w=await Kd(e,f);if(a!=null&&a.aborted)return{resolved:0,skipped:n.size};const b=I=>{const D=w.get(I);return D&&!("decorative"in D)?D:null},k=new Set;for(const[I,D]of w)D&&"decorative"in D&&k.add(I);for(const I of h){if(!k.has(I.selector))continue;const D={pageUrl:I.pageUrl,ruleId:I.ruleId,selector:I.selector,verdict:"pass",reasoning:'Not applicable to WCAG 1.4.3 (contrast minimum): this element is decorative / removed from the accessibility tree — it sits inside an aria-hidden="true" subtree, or is visually hidden (display:none, sr-only clip, off-screen, or zero opacity). Decorative and incidental content is exempt from the contrast-minimum requirement, so it is recorded as not-applicable and does not count as a violation.',resolvedAt:new Date().toISOString(),costUsd:0,wcagCriterion:I.wcagCriterion,inputHash:await Oo({...I,bgFingerprint:null})};await De(D),i++}const v=h.filter(I=>!k.has(I.selector));if(v.length===0)return Xe.info(`pixel-contrast sampler: all ${h.length} targets decorative/not-applicable (1.4.3)`),{resolved:i,skipped:c};const s=((u=h[0])==null?void 0:u.pageUrl)??"",x=s?await ka(s):[],$=new Map;for(const I of x)$.set(`${I.ruleId}::${I.selector}`,I);const A=new Map,C=[];for(const I of v){const D=await Oo({...I,bgFingerprint:((g=b(I.selector))==null?void 0:g.bgFingerprint)??null});A.set(I.selector,D);const S=$.get(`${I.ruleId}::${I.selector}`);if(S&&S.inputHash===D&&S.verdict!=="uncertain"){const _={...S,resolvedAt:new Date().toISOString(),reasoning:S.reasoning.includes("(cached, hash-match)")?S.reasoning:`${S.reasoning} (cached, hash-match)`};await De(_),i++;continue}C.push(I)}if(C.length===0)return Xe.info(`pixel-contrast sampler: all ${h.length} targets reused from hash-cache`),{resolved:i,skipped:c};await Yd(e);const F=new Map;for(const I of C){if(a!=null&&a.aborted)break;const D=b(I.selector);if(!D)continue;const S=await Do(e,D);S&&F.set(I.selector,S)}if(await Jd(e),a!=null&&a.aborted)return{resolved:0,skipped:n.size};const T=new Map;for(const I of C){if(a!=null&&a.aborted)break;const D=b(I.selector);if(!D)continue;const S=await Do(e,D);S&&T.set(I.selector,S)}for(const I of C){if(a!=null&&a.aborted)break;const D=A.get(I.selector),S=b(I.selector);if(!S){c++;const X={pageUrl:I.pageUrl,ruleId:I.ruleId,selector:I.selector,verdict:"uncertain",reasoning:"Hide-text observation: element's bounding rect could not be resolved at audit time (element may be display:none, detached from DOM, or zero-size). Cannot sample contrast empirically. Manual verification required if you believe this element is visible.",resolvedAt:new Date().toISOString(),costUsd:0,wcagCriterion:I.wcagCriterion,inputHash:D};await De(X);continue}const _=F.get(I.selector),N=T.get(I.selector);if(!_||!N){c++;const X={pageUrl:I.pageUrl,ruleId:I.ruleId,selector:I.selector,verdict:"uncertain",reasoning:"Hide-text observation: per-element clip capture failed via chrome.debugger Page.captureScreenshot. Manual verification required.",resolvedAt:new Date().toISOString(),costUsd:0,wcagCriterion:I.wcagCriterion,inputHash:D};await De(X);continue}const O=qd(I.foreground);if(!O){c++;const X={pageUrl:I.pageUrl,ruleId:I.ruleId,selector:I.selector,verdict:"uncertain",reasoning:`Hide-text observation: element's computed CSS foreground color could not be parsed (got ${JSON.stringify(I.foreground)}). Cannot compute contrast against rendered background without an intended foreground color. Manual verification required.`,resolvedAt:new Date().toISOString(),costUsd:0,wcagCriterion:I.wcagCriterion,inputHash:D};await De(X);continue}const W=au(_,N,O);if(!W){if(S.resolvedBg){const re=Ja(I.fontSize,I.fontWeight),oe=re?Ya:Ka,le=Et(O,S.resolvedBg),ie=le>=oe;i++,await De({pageUrl:I.pageUrl,ruleId:I.ruleId,selector:I.selector,verdict:ie?"pass":"fail",reasoning:`Too few text pixels for an empirical screenshot reading (under ${Jt} after diffing hidden vs visible). Resolved DETERMINISTICALLY from CSS: foreground rgb(${O.r},${O.g},${O.b}) on resolved background rgb(${S.resolvedBg.r},${S.resolvedBg.g},${S.resolvedBg.b}) = ${le.toFixed(2)}:1 vs AA ${oe}:1 (${re?"large":"normal"} text) → ${ie?"PASS":"FAIL"}. (rc.413 — known-fg/known-bg text isn't left 'uncertain' when the pixel diff is sparse; that caused A↔B grade flip-flop.)`,resolvedAt:new Date().toISOString(),costUsd:0,wcagCriterion:I.wcagCriterion,inputHash:D});continue}if(S.resolvedBgGradient&&S.resolvedBgGradient.length>=2){const re=Ja(I.fontSize,I.fontWeight),oe=re?Ya:Ka,le=S.resolvedBgGradient;let ie=1/0,ge=le[0];for(const Oe of le){const ve=Et(O,Oe);ve<ie&&(ie=ve,ge=Oe)}const Re=ie>=oe;i++,await De({pageUrl:I.pageUrl,ruleId:I.ruleId,selector:I.selector,verdict:Re?"pass":"fail",reasoning:`Too few text pixels for an empirical screenshot reading (under ${Jt}). Background is a linear-gradient; resolved DETERMINISTICALLY from CSS worst-case stop: foreground rgb(${O.r},${O.g},${O.b}) on least-contrasting stop rgb(${ge.r},${ge.g},${ge.b}) = ${ie.toFixed(2)}:1 vs AA ${oe}:1 (${re?"large":"normal"} text) → ${Re?"PASS":"FAIL"}. (rc.413 — small text on a gradient isn't left 'uncertain'; that caused the A↔B grade flip-flop.)`,resolvedAt:new Date().toISOString(),costUsd:0,wcagCriterion:I.wcagCriterion,inputHash:D});continue}c++;const X={pageUrl:I.pageUrl,ruleId:I.ruleId,selector:I.selector,verdict:"uncertain",reasoning:`Hide-text observation: too few text pixels detected (under ${Jt} after diffing hidden vs visible captures) AND the background is a raster image / otherwise unresolvable, so neither an empirical nor a CSS contrast reading is possible. Element may be canvas-rendered or SVG. Manual verification required.`,resolvedAt:new Date().toISOString(),costUsd:0,wcagCriterion:I.wcagCriterion,inputHash:D};await De(X);continue}const P=Ja(I.fontSize,I.fontWeight),V=P?Ya:Ka,M=X=>`rgb(${X.r},${X.g},${X.b})`;let j=W.worstRatio>=V,q="";if(zd(W.worstRatio,O,S.resolvedBg,V)){const X=Et(O,S.resolvedBg);j=!0,q=` Cross-check (rc.356): computed CSS contrast ${M(O)} on resolved background ${M(S.resolvedBg)} = ${X.toFixed(2)}:1, which PASSES ${V}:1 — the sub-threshold pixel reading is an anti-aliasing/sampling artifact, not a real failure. Suppressed.`}const z={pageUrl:I.pageUrl,ruleId:I.ruleId,selector:I.selector,verdict:j?"pass":"fail",reasoning:`Hide-text observation: ${W.textPixelCount} text-core pixels detected by diffing hidden-vs-visible viewport screenshots. Worst per-pixel contrast: ${W.worstRatio.toFixed(2)}:1 against AA threshold ${V}:1 (${P?"large text":"normal text"}). At worst pixel: rendered foreground ${M(W.worstForeground)} on rendered background ${M(W.worstBackground)}. ${j&&q?"Passes (computed cross-check).":j?"Passes threshold.":"Falls below threshold — at least one text pixel reads against a background that fails contrast."}`+q,resolvedAt:new Date().toISOString(),costUsd:0,wcagCriterion:I.wcagCriterion,inputHash:D};await De(z),i++}}finally{try{await chrome.debugger.sendCommand({tabId:e},"Runtime.evaluate",{expression:`(() => { const el = document.getElementById(${JSON.stringify(Bn)}); if (el) el.remove(); return true; })()`})}catch{}try{await chrome.debugger.detach({tabId:e})}catch{}}return Xe.info(`pixel-contrast sampler: resolved ${i}, skipped ${c}/${n.size}`),{resolved:i,skipped:c}}const mt=Z("ai-text");function bt(e){if(e!=null&&e.aborted){const t=new Error("aborted");throw t.name="AbortError",t}}function yt(e){return e instanceof Error&&(e.name==="AbortError"||e.name==="ExternalAbortError"||e.message==="aborted")}async function ou(e,t,a,n={}){var u;if(!a.enabled||!a.enabledChecks.headings)return{findings:[],totalCostUsd:0,capExceeded:!1,errors:[]};const o=fe(a);if(!o.ok)return{findings:[],totalCostUsd:0,capExceeded:!1,errors:[`AI client unavailable: ${o.reason}`]};const r=o.client,i=_e(a.costCapUsd),c=[],d=[],l=Math.max(1,a.maxCandidatesPerCheck??10),p=e.slice(0,l),m=p.length;for(let g=0;g<p.length;g++){const h=p[g];if(!i.canCharge())break;try{bt(n.signal);const f=await r.judgeHeading({headingText:h.text,sectionContent:h.sectionContent,signal:n.signal});i.recordCharge(f.costUsd),f.verdict==="fail"&&f.confidence>=.6&&c.push(await wt("ai-heading-not-descriptive","2.4.6","AA","moderate","AI judged this heading does not describe its section content.",h.selector,h.outerHTML,h.text,f,t))}catch(f){if(yt(f)){d.push(`canceled after ${g}/${m} candidates`);break}const w=f instanceof Error?f.message:String(f);d.push(`${h.selector}: ${w}`),mt.warn("heading judgment failed",f)}(u=n.onProgress)==null||u.call(n,g+1,m)}return{findings:c,totalCostUsd:i.state.spentUsd,capExceeded:i.state.exceeded,errors:d}}async function ru(e,t,a,n={}){var u;if(!a.enabled||!a.enabledChecks.sensory)return{findings:[],totalCostUsd:0,capExceeded:!1,errors:[]};const o=fe(a);if(!o.ok)return{findings:[],totalCostUsd:0,capExceeded:!1,errors:[`AI client unavailable: ${o.reason}`]};const r=o.client,i=_e(a.costCapUsd),c=[],d=[],l=Math.max(1,a.maxCandidatesPerCheck??10),p=e.slice(0,l),m=p.length;for(let g=0;g<p.length;g++){const h=p[g];if(!i.canCharge())break;try{bt(n.signal);const f=await r.judgeSensoryLanguage({instructionText:h.text,signal:n.signal});i.recordCharge(f.costUsd),f.verdict==="fail"&&f.confidence>=.6&&c.push(await wt("ai-sensory-instruction","1.3.3","A","serious","AI flagged this instruction as relying on sensory characteristics (shape, color, location) without a programmatic identifier.",h.selector,h.outerHTML,h.text.slice(0,100),f,t))}catch(f){if(yt(f)){d.push(`canceled after ${g}/${m} candidates`);break}const w=f instanceof Error?f.message:String(f);d.push(`${h.selector}: ${w}`),mt.warn("sensory judgment failed",f)}(u=n.onProgress)==null||u.call(n,g+1,m)}return{findings:c,totalCostUsd:i.state.spentUsd,capExceeded:i.state.exceeded,errors:d}}async function iu(e,t,a,n={}){var u;if(!a.enabled||!a.enabledChecks.aria)return{findings:[],totalCostUsd:0,capExceeded:!1,errors:[]};const o=fe(a);if(!o.ok)return{findings:[],totalCostUsd:0,capExceeded:!1,errors:[`AI client unavailable: ${o.reason}`]};const r=o.client,i=_e(a.costCapUsd),c=[],d=[],l=Math.max(1,a.maxCandidatesPerCheck??10),p=e.slice(0,l),m=p.length;for(let g=0;g<p.length;g++){const h=p[g];if(!i.canCharge())break;try{bt(n.signal);const f=await r.judgeAriaSemantics({elementHtml:h.outerHTML,computedRole:h.role,surroundingHtml:h.surroundingHtml,signal:n.signal});i.recordCharge(f.costUsd),f.verdict==="fail"&&f.confidence>=.65&&c.push(await wt("ai-aria-misuse","4.1.2","A","serious",`AI judged role="${h.role}" is being used inappropriately on this element.`,h.selector,h.outerHTML,h.role,f,t))}catch(f){if(yt(f)){d.push(`canceled after ${g}/${m} candidates`);break}const w=f instanceof Error?f.message:String(f);d.push(`${h.selector}: ${w}`),mt.warn("aria judgment failed",f)}(u=n.onProgress)==null||u.call(n,g+1,m)}return{findings:c,totalCostUsd:i.state.spentUsd,capExceeded:i.state.exceeded,errors:d}}async function su(e,t,a,n={}){var u;if(!a.enabled||!a.enabledChecks.genericLinkText)return{findings:[],totalCostUsd:0,capExceeded:!1,errors:[]};const o=fe(a);if(!o.ok)return{findings:[],totalCostUsd:0,capExceeded:!1,errors:[`AI client unavailable: ${o.reason}`]};const r=o.client,i=_e(a.costCapUsd),c=[],d=[],l=Math.max(1,a.maxCandidatesPerCheck??10),p=e.slice(0,l),m=p.length;for(let g=0;g<p.length;g++){const h=p[g];if(!i.canCharge())break;try{bt(n.signal);const f=await r.judgeGenericLinkText({linkText:h.linkText,surroundingText:h.surroundingText,signal:n.signal});i.recordCharge(f.costUsd),f.verdict==="fail"&&f.confidence>=.6&&c.push(await wt("ai-generic-link-text","2.4.4","A","serious","AI judged this link's purpose is not clear from its text or surrounding context.",h.selector,h.outerHTML,h.linkText,f,t))}catch(f){if(yt(f)){d.push(`canceled after ${g}/${m} candidates`);break}const w=f instanceof Error?f.message:String(f);d.push(`${h.selector}: ${w}`),mt.warn("generic-link judgment failed",f)}(u=n.onProgress)==null||u.call(n,g+1,m)}return{findings:c,totalCostUsd:i.state.spentUsd,capExceeded:i.state.exceeded,errors:d}}async function cu(e,t,a,n={}){var u;if(!a.enabled||!a.enabledChecks.wallOfText)return{findings:[],totalCostUsd:0,capExceeded:!1,errors:[]};const o=fe(a);if(!o.ok)return{findings:[],totalCostUsd:0,capExceeded:!1,errors:[`AI client unavailable: ${o.reason}`]};const r=o.client,i=_e(a.costCapUsd),c=[],d=[],l=Math.max(1,a.maxCandidatesPerCheck??10),p=e.slice(0,l),m=p.length;for(let g=0;g<p.length;g++){const h=p[g];if(!i.canCharge())break;try{bt(n.signal);const f=await r.judgeWallOfText({blockText:h.blockText,structuralChildrenCount:h.structuralChildrenCount,signal:n.signal});i.recordCharge(f.costUsd),f.verdict==="fail"&&f.confidence>=.6&&c.push(await wt("ai-wall-of-text","3.1.5","AAA","moderate","AI flagged this block as a wall of text with insufficient structural breaks (subheadings, lists, paragraphs).",h.selector,h.outerHTML,h.blockText.slice(0,80),f,t))}catch(f){if(yt(f)){d.push(`canceled after ${g}/${m} candidates`);break}const w=f instanceof Error?f.message:String(f);d.push(`${h.selector}: ${w}`),mt.warn("wall-of-text judgment failed",f)}(u=n.onProgress)==null||u.call(n,g+1,m)}return{findings:c,totalCostUsd:i.state.spentUsd,capExceeded:i.state.exceeded,errors:d}}async function lu(e,t,a,n={}){var u;if(!a.enabled||!a.enabledChecks.languageMismatch)return{findings:[],totalCostUsd:0,capExceeded:!1,errors:[]};const o=fe(a);if(!o.ok)return{findings:[],totalCostUsd:0,capExceeded:!1,errors:[`AI client unavailable: ${o.reason}`]};const r=o.client,i=_e(a.costCapUsd),c=[],d=[],l=Math.max(1,a.maxCandidatesPerCheck??10),p=e.slice(0,l),m=p.length;for(let g=0;g<p.length;g++){const h=p[g];if(!i.canCharge())break;try{bt(n.signal);const f=await r.judgeLanguageMismatch({declaredLang:h.declaredLang,bodyTextSample:h.bodyTextSample,signal:n.signal});i.recordCharge(f.costUsd),f.verdict==="fail"&&f.confidence>=.7&&c.push(await wt("ai-language-mismatch","3.1.1","A","serious",`AI judged the page's content does not match the declared lang="${h.declaredLang||"(none)"}".`,h.selector,h.outerHTML,h.bodyTextSample.slice(0,80),f,t))}catch(f){if(yt(f)){d.push(`canceled after ${g}/${m} candidates`);break}const w=f instanceof Error?f.message:String(f);d.push(`${h.selector}: ${w}`),mt.warn("language-mismatch judgment failed",f)}(u=n.onProgress)==null||u.call(n,g+1,m)}return{findings:c,totalCostUsd:i.state.spentUsd,capExceeded:i.state.exceeded,errors:d}}async function wt(e,t,a,n,o,r,i,c,d,l){const p={selector:r,outerHTML:i.slice(0,500),failureSummary:`AI assessment: ${d.reasoning}`,tagName:"AI",role:null,accessibleName:null,textSnippet:c.slice(0,100)||null,attrId:null,attrTestid:null},m=await xn({ruleId:e,componentId:l.componentId,currentState:l.currentState,target:p});return{ruleId:e,wcagCriterion:t,wcagLevel:a,impact:n,description:o,helpUrl:"https://www.w3.org/WAI/WCAG21/Understanding/",target:p,componentId:l.componentId,currentState:l.currentState,axeVersion:l.axeVersion,detectedAt:new Date().toISOString(),matchKey:m,ai:{reasoning:d.reasoning,confidence:d.confidence,model:d.model,costUsd:d.costUsd}}}const mi=Z("ai-vision");function bi(e){if(e!=null&&e.aborted){const t=new Error("aborted");throw t.name="AbortError",t}}function yi(e){return e instanceof Error&&(e.name==="AbortError"||e.name==="ExternalAbortError"||e.message==="aborted")}async function du(e,t,a,n={}){var u;if(!a.enabled||!a.enabledChecks.imageOfText)return{findings:[],totalCostUsd:0,capExceeded:!1,errors:[]};const o=fe(a);if(!o.ok)return{findings:[],totalCostUsd:0,capExceeded:!1,errors:[`AI client unavailable: ${o.reason}`]};const r=o.client,i=_e(a.costCapUsd),c=Math.max(1,a.imageOfTextMaxImages??5),d=[...e].sort((g,h)=>h.pixelArea-g.pixelArea).slice(0,c),l=d.length,p=[],m=[];for(let g=0;g<d.length;g++){const h=d[g];if(!i.canCharge())break;try{bi(n.signal);const f=await r.judgeImageOfText({imageUrl:h.imageUrl,accessibleName:h.accessibleName,signal:n.signal});i.recordCharge(f.costUsd),f.verdict==="fail"&&f.confidence>=.65&&p.push(await wi("ai-image-of-text","1.4.5","AA","moderate","AI judged this image bakes substantial text into the raster — should be presented as actual HTML text instead.",h.selector,h.outerHTML,h.accessibleName??"",f,t))}catch(f){if(yi(f)){m.push(`canceled after ${g}/${l} candidates`);break}const w=f instanceof Error?f.message:String(f);m.push(`${h.selector}: ${w}`),mi.warn("image-of-text judgment failed",f)}(u=n.onProgress)==null||u.call(n,g+1,l)}return{findings:p,totalCostUsd:i.state.spentUsd,capExceeded:i.state.exceeded,errors:m}}async function uu(e,t,a,n={}){var u;if(!a.enabled||!a.enabledChecks.colorOnlyMeaning)return{findings:[],totalCostUsd:0,capExceeded:!1,errors:[]};const o=fe(a);if(!o.ok)return{findings:[],totalCostUsd:0,capExceeded:!1,errors:[o.reason]};const r=o.client,i=_e(a.costCapUsd),c=[],d=[],l=Math.max(1,a.maxCandidatesPerCheck??10),p=e.slice(0,l),m=p.length;for(let g=0;g<p.length;g++){const h=p[g];if(!i.canCharge())break;try{bi(n.signal);const f=await r.judgeColorOnlyMeaning({elementHtml:h.elementHtml,contextDescription:h.contextDescription,signal:n.signal});i.recordCharge(f.costUsd),f.verdict==="fail"&&f.confidence>=.65&&c.push(await wi("ai-color-only-meaning","1.4.1","A","serious","AI judged this region conveys information only through color (no text label, icon glyph, or shape difference).",h.selector,h.outerHTML,h.contextDescription,f,t))}catch(f){if(yi(f)){d.push(`canceled after ${g}/${m} candidates`);break}const w=f instanceof Error?f.message:String(f);d.push(w),mi.warn("color-only judgment failed",f)}(u=n.onProgress)==null||u.call(n,g+1,m)}return{findings:c,totalCostUsd:i.state.spentUsd,capExceeded:i.state.exceeded,errors:d}}async function wi(e,t,a,n,o,r,i,c,d,l){const p={selector:r,outerHTML:i.slice(0,500),failureSummary:`AI assessment: ${d.reasoning}`,tagName:"AI",role:null,accessibleName:null,textSnippet:c.slice(0,100)||null,attrId:null,attrTestid:null},m=await xn({ruleId:e,componentId:l.componentId,currentState:l.currentState,target:p});return{ruleId:e,wcagCriterion:t,wcagLevel:a,impact:n,description:o,helpUrl:"https://www.w3.org/WAI/WCAG21/Understanding/",target:p,componentId:l.componentId,currentState:l.currentState,axeVersion:l.axeVersion,detectedAt:new Date().toISOString(),matchKey:m,ai:{reasoning:d.reasoning,confidence:d.confidence,model:d.model,costUsd:d.costUsd}}}const wn=Z("ensure-content-script"),hu=1500,pu=300;async function Hn(e,t){if(await No(e,t))return{ok:!0};const a=chrome.runtime.getManifest(),n=[];for(const o of a.content_scripts??[])Array.isArray(o.js)&&n.push(...o.js);if(n.length===0)return wn.error("manifest declares no content_scripts"),{ok:!1,reason:"inject-failed",detail:"no content_scripts declared in manifest"};try{const o=t!==void 0?{tabId:e,frameIds:[t]}:{tabId:e,allFrames:!0};await chrome.scripting.executeScript({target:o,files:n})}catch(o){return fu(o)}return await gu(pu),await No(e,t)?(wn.info("content script injected on demand",{tabId:e,frameId:t}),{ok:!0}):{ok:!1,reason:"unresponsive-after-inject",detail:"content script injected but did not register handlers — likely Content Security Policy on this page is blocking it"}}async function No(e,t){try{const a=t!==void 0?{frameId:t}:void 0,n=await Promise.race([chrome.tabs.sendMessage(e,{type:"PING_REQUEST"},a),new Promise((o,r)=>setTimeout(()=>r(new Error("ping timeout")),hu))]);return(n==null?void 0:n.type)==="PING_RESPONSE"}catch{return!1}}function fu(e){const t=e instanceof Error?e.message:String(e);return/cannot access contents of (?:the page|url)/i.test(t)||/chrome:\/\//i.test(t)||/chrome-extension:\/\//i.test(t)||/devtools:\/\//i.test(t)||/chrome\.google\.com\/webstore/i.test(t)||/the extensions gallery/i.test(t)?{ok:!1,reason:"restricted-url",detail:t}:/no tab with id/i.test(t)||/tab .* was closed/i.test(t)?{ok:!1,reason:"tab-gone",detail:t}:(wn.warn("content-script injection failed",e),{ok:!1,reason:"inject-failed",detail:t})}function gu(e){return new Promise(t=>setTimeout(t,e))}function vn(e){switch(e.reason){case"restricted-url":return"Chrome blocks extensions on this page (chrome:// pages, the Chrome Web Store, view-source: pages, and a few others). Open a regular https:// page and try again.";case"tab-gone":return"The tab was closed or navigated away while the audit was starting. Click into the tab you want audited and click Scan again.";case"unresponsive-after-inject":return"We loaded our auditor onto the page, but the page's Content Security Policy appears to be blocking it. Some sites (banks, gov, strict CSPs) prevent extensions from running. Try a different page on the same site, or open DevTools → Console to confirm a CSP error.";case"inject-failed":return`Could not load our auditor onto the page. Try a hard refresh (Ctrl+Shift+R) on the page and click Scan again. If it persists, the page may be using an unusual document type or origin restriction.${e.detail?` (Detail: ${e.detail})`:""}`;case"unknown":default:return"Could not establish connection with the page. Hard-refresh (Ctrl+Shift+R) the tab you want audited and try again."}}const Xa=Z("forensic-anchor-client"),mu="https://api.wcagcheckr.com",bu="wcagcheckr",yu=15e3;function wu(e){if(typeof e!="object"||e===null)return!1;const t=e;return t.schemaVersion!==1&&t.schemaVersion!==2||!(typeof t.anchoredAt=="string"&&typeof t.tsaName=="string"&&typeof t.rfc3161TokenBase64=="string"&&t.rfc3161TokenBase64.length>0&&typeof t.serverSignatureBase64=="string"&&t.serverSignatureBase64.length>0&&typeof t.serverKeyFingerprint=="string"&&t.serverKeyFingerprint.length>0)?!1:t.schemaVersion===2?typeof t.prevAuditHash=="string"&&/^[0-9a-f]{64}$/.test(t.prevAuditHash):!0}async function vi(e,t){return Ai(e.hash,e.pageUrl,e.capturedAt,t)}async function Ai(e,t,a,n){const o={auditHash:e,pageUrl:t,capturedAt:a,...n?{licenseId:n}:{}},r=`${mu}/v1/products/${bu}/forensic/anchor`;try{const i=await fetch(r,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(o),signal:AbortSignal.timeout(yu)});if(!i.ok)return Xa.warn(`anchor HTTP ${i.status}; entry stays local-only`),null;const c=await i.json();return wu(c)?c:(Xa.warn("anchor returned malformed receipt; entry stays local-only",c),null)}catch(i){return Xa.warn("anchor request failed; entry stays local-only",i),null}}async function vu(e){const t=na(e),a=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",a);return Array.from(new Uint8Array(n)).map(o=>o.toString(16).padStart(2,"0")).join("")}function Au(e){try{return new URL(e).hostname}catch{return e}}const ku="wcag-site-claims",xu=1,Dt="claims";let Qa=null;function qn(){return Qa||(Qa=Sn(ku,xu,{upgrade(e){e.objectStoreNames.contains(Dt)||e.createObjectStore(Dt,{keyPath:"domain"})}})),Qa}async function Iu(e){await(await qn()).put(Dt,e)}async function tf(e){return await(await qn()).get(Dt,e)??null}async function af(){return(await qn()).getAll(Dt)}const Lo="4.11.4";async function Su(e){try{return(await chrome.tabs.get(e)).url??""}catch{return""}}const U=Z("flows");async function vt(){const e=await fr();if(!e)throw new Error("no audit target tab found");return e}async function zn(){var a,n,o,r,i;const e=await Ye("stateMatrix",nn);return((a=e.pseudoStates)==null?void 0:a.length)>0&&((n=e.themes)==null?void 0:n.length)>0&&((o=e.directions)==null?void 0:o.length)>0&&((r=e.breakpoints)==null?void 0:r.length)>0&&((i=e.breakpointPresets)==null?void 0:i.length)>0?e:(U.warn("stored stateMatrix is invalid; using defaults"),nn)}async function Cu(e,t,a){const n=t.themes.includes("light"),o=t.themes.includes("dark");if(!n||!o)return t;let r=null;try{r=await xe(e,{type:"THEME_AWARENESS_REQUEST"},a)}catch{return t}return!r||r.hasUnreadableSheets?t:r.hasDarkModeCss&&!r.hasLightModeCss?(U.info("theme-axis prune: site is dark-only, skipping light pass"),{...t,themes:t.themes.filter(i=>i!=="light")}):r.hasLightModeCss&&!r.hasDarkModeCss?(U.info("theme-axis prune: site is light-only, skipping dark pass"),{...t,themes:t.themes.filter(i=>i!=="dark")}):t}const $u=200,Za=3,Po=8;async function Tu(e,t){const a=[];let n=null,o=null;for(let i=0;i<Po&&!t();i++){const c=await e();if(c.error&&(o=c.error),!c.result)break;if(n=c.result,a.push(c.violations),i===1&&a[0].length===0&&a[1].length===0)return{violations:[],lastResult:n,sampleCount:2,stabilized:!0,lastError:o};if(a.length>=Za){const d=a.slice(-Za);if(Eu(d))return{violations:d[d.length-1],lastResult:n,sampleCount:a.length,stabilized:!0,lastError:o}}i<Po-1&&await new Promise(d=>setTimeout(d,$u))}const r=a.slice(-Za);return{violations:Ru(r),lastResult:n,sampleCount:a.length,stabilized:!1,lastError:o}}function Eu(e){if(e.length<2)return!0;const t=Fo(e[0]);for(let a=1;a<e.length;a++){const n=Fo(e[a]);if(n.size!==t.size)return!1;for(const o of t)if(!n.has(o))return!1}return!0}function Fo(e){return new Set(e.map(t=>`${t.ruleId}::${t.target.selector}::${t.matchKey}`))}function Ru(e){const t=new Map,a="Audit detected this finding intermittently across multiple samples — likely an animation or transitional state was in progress. Verify manually.";for(const n of e)for(const o of n){const r=`${o.ruleId}::${o.target.selector}::${o.matchKey}`;t.has(r)||t.set(r,{...o,needsReview:!0,flakyAcrossRuns:!0,target:{...o.target,failureSummary:o.target.failureSummary?`${o.target.failureSummary} ${a}`:a}})}return Array.from(t.values())}async function _o(e,t,a,n,o){await Promise.all([(async()=>{var r;try{const i=await xe(e,{type:"READING_ORDER_REQUEST",selector:t},a);n[0]&&(i.issues.length>0?(n[0].readingOrderIssues=i.issues,n[0].positionAnalysisCapturedAt=o):(r=n[0].axeRulesEvaluated)==null||r.passed.push({ruleId:"wcc-reading-order-clean",wcagCriterion:"1.3.2"}))}catch(i){U.debug("reading-order analysis skipped",i)}})(),(async()=>{var r;try{const i=await xe(e,{type:"TAB_ORDER_ANALYZE_REQUEST"},a);n[0]&&(i.issues.length>0?(n[0].tabOrderIssues=i.issues,n[0].positionAnalysisCapturedAt=o):(r=n[0].axeRulesEvaluated)==null||r.passed.push({ruleId:"wcc-tab-order-clean",wcagCriterion:"2.4.3"}))}catch(i){U.debug("tab-order analysis skipped",i)}})(),(async()=>{var r;try{const i=await xe(e,{type:"TYPOGRAPHY_ANALYZE_REQUEST",selector:t},a);i.issues.length>0&&n[0]?n[0].typographyIssues=i.issues:n[0]&&((r=n[0].axeRulesEvaluated)==null||r.passed.push({ruleId:"wcc-typography-clean",wcagCriterion:"1.4.12"}))}catch(i){U.debug("typography analysis skipped",i)}})(),(async()=>{try{const r=await xe(e,{type:"CUSTOM_PROPERTY_REQUEST"},a);r.undefined.length>0&&n[0]&&(n[0].undefinedCustomProperties=r.undefined)}catch(r){U.debug("custom-property analysis skipped",r)}})()])}async function pt(e,t,a,n,o={}){var I,D,S,_,N;const r=o.asSubroutine===!0;if(await He())return r||H({type:"AUDIT_FAILED_EVENT",error:{code:Lt,message:Ze,recoverable:!1}}),{ok:!1,results:[],error:Ze};const i=o.tabIdOverride??await vt(),c=await Hn(i,a);if(!c.ok)return r||H({type:"AUDIT_FAILED_EVENT",error:{code:c.reason==="restricted-url"?"RESTRICTED_URL":"CONTENT_SCRIPT_UNREACHABLE",message:vn(c),recoverable:c.reason!=="restricted-url"}}),{ok:!1,results:[],error:vn(c)};try{const[O]=await chrome.scripting.executeScript({target:{tabId:i,frameIds:a!==void 0?[a]:void 0},func:()=>document.contentType}),W=String((O==null?void 0:O.result)??"").toLowerCase();if(!(W===""||W==="text/html"||W==="application/xhtml+xml")){const V=`This page is not an HTML document (Content-Type: ${W||"unknown"}). WCAG HTML checks don't apply to XML sitemaps, RSS/Atom feeds, JSON, or plain text — skipped.`;return r||H({type:"AUDIT_FAILED_EVENT",error:{code:"NOT_HTML_DOCUMENT",message:V,recoverable:!1}}),{ok:!1,results:[],error:V,skipped:!0}}}catch(O){U.debug("content-type probe failed (non-fatal); proceeding with audit",O)}try{await chrome.scripting.executeScript({target:{tabId:i,frameIds:a!==void 0?[a]:void 0},world:"MAIN",func:()=>{try{let O=document.getElementById("__wcagcheckr_audit_freeze");O||(O=document.createElement("style"),O.id="__wcagcheckr_audit_freeze",O.textContent="*, *::before, *::after { animation-duration: 0s !important; animation-delay: 0s !important; transition-duration: 0s !important; transition-delay: 0s !important; } html, body { scroll-behavior: auto !important; }",document.documentElement.appendChild(O)),window.scrollTo(0,0);const W=document.activeElement;W&&W instanceof HTMLElement&&W!==document.body&&W.blur()}catch{}}}),await chrome.scripting.executeScript({target:{tabId:i,frameIds:a!==void 0?[a]:void 0},world:"MAIN",func:async()=>{try{await document.fonts.ready}catch{}}})}catch(O){U.debug("audit-start state stabilization failed (non-fatal)",O)}const d=n??await zn(),l=await Cu(i,d,a),p=Fl(l),m=await ls(`${await Su(i)}|${e}|${a??0}`),u=await ds(l),g=await Ye("axeDisabledRules",[]),h=await us(g);let f=null;try{f=(await xe(i,{type:"SCOPE_FINGERPRINT_REQUEST",selector:e},a)).fingerprint}catch(O){U.debug("scope fingerprint failed; skipping cache fast-path",O)}if(f){const O=await hs(m);if(O&&O.fingerprint===f&&O.axeVersion===Lo&&O.matrixConfigHash===u&&O.disabledRulesHash===h)return U.info(`audit-cache HIT for ${O.componentId} — skipping matrix iteration`),r||(H({type:"AUDIT_COMPLETE_EVENT",componentId:O.componentId,results:O.results,delta:O.delta}),H({type:"SCORECARD_UPDATED_EVENT"})),{ok:!0,results:O.results}}r||await at({sessionId:_t(),mode:"single-element",scope:e,startedAt:new Date().toISOString(),lastProgressAt:new Date().toISOString(),state:"running"}),await $t(i,{type:"LIVE_REGIONS_ARM_REQUEST"},a).catch(()=>{}),await $t(i,{type:"FOCUS_TRACE_ARM_REQUEST"},a).catch(()=>{}),await xe(i,{type:"WARMUP_REQUEST"},a).catch(()=>{});const w=[],b=[];let k="",v,s=!1,x=null,$=null,A=null,C=null,F=!1,T=null;try{for(let O=0;O<p.length;O++){if(t.isCanceled()){U.info("single audit canceled by user");break}const W=p[O];try{const P=await bn(i,W,e,a);if(!P.success){v=(I=P.error)==null?void 0:I.message,U.warn(`state ${O+1}/${p.length} drive failed`,v);continue}W.breakpoint.id!==x&&(await xe(i,{type:"WARMUP_REQUEST"},a).catch(()=>{}),x=W.breakpoint.id);const V=O===0?void 0:[...ii],M=await Tu(async()=>{var z;const q=await xe(i,{type:"AUDIT_REQUEST",selector:e,currentState:W,rulesToRun:V},a);return q.success&&q.result?{result:q.result,violations:q.result.violations,error:null}:{result:null,violations:[],error:((z=q.error)==null?void 0:z.message)??null}},()=>t.isCanceled());M.lastError&&(v=M.lastError,U.warn(`state ${O+1}/${p.length} sampling: ${M.lastError}`));const j=M.lastResult;if(!M.stabilized&&M.sampleCount>0&&U.info(`state ${O+1}/${p.length} did not stabilize after ${M.sampleCount} samples — ${M.violations.length} finding(s) routed to needs-review as flickering`),j){s=!0;const q=M.violations;U.info(`[adaptive-sample] state ${O+1}/${p.length} ${W.pseudoState}·${W.theme}·${W.direction}·${W.breakpoint.id}: ${M.sampleCount} sample(s), ${M.stabilized?"stabilized":"flickering"}, ${q.length} finding(s)`);const z=await ad(i,{quality:75})??void 0;let X,re;try{X=(await xe(i,{type:"LIVE_REGIONS_DRAIN_REQUEST"},a)).announcements}catch{}try{re=(await xe(i,{type:"FOCUS_TRACE_DRAIN_REQUEST"},a)).focusEvents}catch{}if(b.push({...j,violations:q,frameId:a,announcements:X,focusEvents:re,screenshotDataUrl:z}),w.push(...q),k=j.componentId,O===0&&$===null)try{const oe=await Ye("aiConfig",{}),le=ke(oe);if(le.enabled&&le.apiKey&&k){$=pa(i,e,a,le,b,k,t).catch(ge=>{U.warn("ai augmentation (parallel) failed",ge)});const ie=((D=b[0])==null?void 0:D.pageUrl)??((S=b[0])==null?void 0:S.scope)??"";A=jd({tabId:i,componentId:k,pageUrl:ie,results:b,verifyFixesOnly:o.verifyFixesOnly}).catch(ge=>(U.warn("1.4.11 walkthrough (parallel) failed",ge),{criterionId:"1.4.11",ran:!0,ok:!1,error:String(ge)}))}}catch(oe){U.debug("ai augmentation (parallel) gate-read failed",oe)}!F&&W.pseudoState==="default"&&W.theme==="light"&&W.direction==="ltr"&&W.breakpoint.id==="desktop"&&b[0]&&(F=!0,T=_o(i,e,a,b,W).catch(le=>{U.debug("lightweight deep analyzers (parallel) failed",le)}))}}catch(P){v=P instanceof Error?P.message:String(P),U.warn(`state ${O+1}/${p.length} threw`,P)}H({type:"AUDIT_PROGRESS_EVENT",current:O+1,total:p.length,currentState:W,componentId:k||void 0}),r||await Ft({})}if(s&&k){const O={pseudoState:"default",ariaVariation:null,theme:"light",direction:"ltr",breakpoint:{id:"desktop",label:"Desktop",width:1280,height:800,deviceScaleFactor:1,mobile:!1}};if(F){if(T)try{await T}catch{}}else{try{await bn(i,O,e,a),await new Promise(M=>setTimeout(M,200))}catch(M){U.debug("reference-state drive failed; analyzers will use last matrix state",M)}await _o(i,e,a,b,O).catch(M=>{U.debug("lightweight deep analyzers (post-matrix fallback) failed",M)})}try{const M=await Ye("aiConfig",{}),j=ke(M);if(j.enabled&&j.apiKey&&k&&b[0]){const q=b[0].pageUrl??b[0].scope??"";C=Vd({tabId:i,componentId:k,pageUrl:q,results:b,verifyFixesOnly:o.verifyFixesOnly}).catch(z=>(U.warn("1.3.2 walkthrough (parallel) failed",z),{criterionId:"1.3.2",ran:!0,ok:!1,error:String(z)}))}}catch(M){U.debug("1.3.2 walkthrough (parallel) gate-read failed",M)}try{if($)await $;else{const M=await Ye("aiConfig",{}),j=ke(M);j.enabled&&j.apiKey&&await pa(i,e,a,j,b,k,t)}}catch(M){U.warn("ai augmentation skipped",M)}try{const M=await Ye("aiConfig",{}),j=ke(M);if(j.enabled&&j.apiKey&&k&&b[0]){await Yt(i,e,a).catch(oe=>U.warn("pre-walkthrough resetState failed",oe));const q=b[0].pageUrl??b[0].scope??"",z=new AbortController,X=setInterval(()=>{t.isCanceled()&&z.abort()},250),re=await Gd({tabId:i,componentId:k,pageUrl:q,results:b,signal:z.signal,verifyFixesOnly:o.verifyFixesOnly}).finally(()=>clearInterval(X));U.info("keyboard walkthroughs complete",re)}}catch(M){U.warn("keyboard walkthroughs failed",M)}try{const M=[];A&&M.push(await A),C&&M.push(await C),M.length>0&&U.info("parallel AI walkthroughs joined",M)}catch(M){U.warn("parallel AI walkthrough join failed",M)}try{if(k&&b[0]){const M=b[0].pageUrl??b[0].scope??"",j=new AbortController,q=setInterval(()=>{t.isCanceled()&&j.abort()},250),z=await Bd({tabId:i,componentId:k,pageUrl:M,results:b,signal:j.signal,verifyFixesOnly:o.verifyFixesOnly}).finally(()=>clearInterval(q));U.info("2.5.3 label-in-name walkthrough complete",z)}}catch(M){U.warn("2.5.3 walkthrough failed",M)}try{if(k&&b[0]){await Yt(i,e,a).catch(X=>U.warn("pre-sampler resetState failed",X));const M=new AbortController,j=setInterval(()=>{t.isCanceled()&&M.abort()},250),{resolved:q,skipped:z}=await nu(i,b,M.signal).finally(()=>clearInterval(j));U.info(`pixel contrast sampler: resolved=${q} skipped=${z}`)}}catch(M){U.warn("pixel contrast sampler failed",M)}const W=b.flatMap(M=>M.announcements??[]),P=b.flatMap(M=>M.focusEvents??[]),V=await Gn(k,w,{announcements:W,focusEvents:P},d);try{const M=await xa(b.map(de=>de.componentId)),j=await $r(b.map(de=>de.componentId)),q=new Set;for(const de of new Set(b.map(y=>y.componentId))){const y=await va(de);for(const L of y)q.add(L)}const z=[...new Set(b.map(de=>de.componentId))],X=await Fr(z),re=((_=b[0])==null?void 0:_.pageUrl)??((N=b[0])==null?void 0:N.scope)??"",oe=re?await ka(re):[],le=new Set(b.map(de=>de.pageUrl??de.scope??"").filter(Boolean)).size>1?"site-crawl":"single-page",ie=et(w,{runs:[],workflows:Pe},b,q,M,j,X,le,oe),ge={...ie.score,letter:ie.combined},Re=b.reduce((de,y)=>de+y.durationMs,0),Oe=await pe(),ve=o.recordForensic!==!1&&he(Oe,"forensicLog")?await zr(b,ge,Re):null;if(ve){const de=await pe();if(he(de,"forensicAnchoring"))try{const y=await ga(),L=await vi(ve,y??void 0);L&&await Kr(ve.componentId,ve.capturedAt,L)}catch(y){U.warn("forensic anchoring failed (entry stays local-only)",y)}}}catch(M){U.warn("forensic log recording failed",M)}if(f)try{await ps({lookupKey:m,fingerprint:f,axeVersion:Lo,matrixConfigHash:u,disabledRulesHash:h,results:b,delta:V,componentId:k,cachedAt:Date.now()})}catch(M){U.warn("audit-cache write failed",M)}try{await chrome.scripting.executeScript({target:{tabId:i,frameIds:a!==void 0?[a]:void 0},world:"MAIN",func:()=>{const M=document.getElementById("__wcagcheckr_audit_freeze");M&&M.remove()}})}catch(M){U.debug("audit-end state-freeze cleanup failed",M)}r||H({type:"AUDIT_COMPLETE_EVENT",componentId:k,results:b,delta:V})}else r||H({type:"AUDIT_FAILED_EVENT",error:{code:"AXE_FAILED",message:v?`All audits failed. Last error: ${v}`:"No state produced results. Selector may not exist in the audit target frame.",recoverable:!0}});r||await dt()}catch(O){U.error("single audit failed",O),r||H({type:"AUDIT_FAILED_EVENT",componentId:k||void 0,error:Zn(O)?O.payload:{code:"UNKNOWN",message:String(O),recoverable:!1}}),v=Zn(O)?O.payload.message:String(O)}finally{await $t(i,{type:"LIVE_REGIONS_DISARM_REQUEST"},a).catch(()=>{}),await $t(i,{type:"FOCUS_TRACE_DISARM_REQUEST"},a).catch(()=>{}),await Yt(i,e,a)}return{ok:s,results:b,error:s?void 0:v}}async function ki(e){var t;try{const n=(await chrome.scripting.executeScript({target:{tabId:e,allFrames:!0},world:"MAIN",func:()=>{var r;const o=window;return{detected:typeof o.__STORYBOOK_PREVIEW__=="object",version:(r=o.__STORYBOOK_PREVIEW__)==null?void 0:r.version}}})).find(o=>{var r;return(r=o.result)==null?void 0:r.detected});if(n)return{detected:!0,version:(t=n.result)==null?void 0:t.version,frameId:n.frameId}}catch(a){U.warn("storybook detection scripting failed",a)}return{detected:!1}}async function Ou(e){if(await He()){H({type:"AUDIT_FAILED_EVENT",error:{code:Lt,message:Ze,recoverable:!1}});return}const t=await vt(),a=await Si(t);if(await chrome.storage.local.set({"storybook:lastDetected":{detected:a.kind==="storybook"&&a.detected,version:a.version,detectedAt:new Date().toISOString()},"playground:lastDetected":{kind:a.kind,detected:a.detected,version:a.version,detectedAt:new Date().toISOString()}}),!a.detected){H({type:"AUDIT_FAILED_EVENT",error:{code:"STORYBOOK_NOT_DETECTED",message:"No supported component playground detected on this tab. Open a Storybook (iframe.html / storybook-static), Ladle, or Bit page and try again.",recoverable:!0}});return}if(a.kind==="bit"){H({type:"AUDIT_FAILED_EVENT",error:{code:"STORYBOOK_NOT_DETECTED",message:"Bit detected. Auto-iterate is not yet supported for Bit (compositions are iframe-per-component without a unified listing API). Use the element picker to audit individual compositions one at a time.",recoverable:!0}});return}const n=a.frameId??0,o=a.kind==="storybook"?await Nu(t,n):await Pu(t,n);if(!o.length){U.warn(`${a.kind} detected but no stories returned`),H({type:"AUDIT_FAILED_EVENT",error:{code:"STORYBOOK_NOT_DETECTED",message:`${a.kind==="ladle"?"Ladle":"Storybook"} detected but no stories were returned. Try reloading the page.`,recoverable:!0}});return}await at({sessionId:_t(),mode:"storybook-all",totalStories:o.length,completedStories:[],startedAt:new Date().toISOString(),lastProgressAt:new Date().toISOString(),state:"running"});for(const r of o){if(e.isCanceled()){U.info(`${a.kind} iteration canceled by user`);break}try{if(a.kind==="storybook"){await Lu(t,n,r.id);const c=await $t(t,{type:"STORYBOOK_GET_STORY_TARGET_REQUEST",tabId:t},n);await pt(c.selector,e,n)}else await Fu(t,n,r.id),await pt("#ladle-root",e,n)}catch(c){U.warn(`story ${r.id} failed; continuing with next`,c)}const i=await Ra();if((i==null?void 0:i.state)==="interrupted"){U.info("storybook iteration interrupted");break}await Ft({completedStories:[...(i==null?void 0:i.completedStories)??[],r.id]})}H({type:"SCORECARD_UPDATED_EVENT"}),await dt()}async function Mu(e){if(await He()){H({type:"AUDIT_FAILED_EVENT",error:{code:Lt,message:Ze,recoverable:!1}});return}const t=await pe();if(!he(t,"allFramesAudit")){H({type:"AUDIT_FAILED_EVENT",error:{code:"FEATURE_NOT_AVAILABLE",message:"All-frames audit is not available on your current plan.",recoverable:!1}});return}const a=await vt();let n=[];try{n=(await chrome.scripting.executeScript({target:{tabId:a,allFrames:!0},func:()=>({url:window.location.href})})).map(r=>{var i;return{frameId:r.frameId,url:((i=r.result)==null?void 0:i.url)??""}}).filter(r=>/^https?:/i.test(r.url))}catch(o){U.warn("multi-frame discovery failed",o)}if(n.length===0){H({type:"AUDIT_FAILED_EVENT",error:{code:"CONTENT_SCRIPT_UNREACHABLE",message:"No auditable frames found on this tab. The page may use only chrome-extension:// or data: frames.",recoverable:!0}});return}await at({sessionId:_t(),mode:"all-frames",totalFrames:n.length,completedFrames:[],startedAt:new Date().toISOString(),lastProgressAt:new Date().toISOString(),state:"running"});for(const o of n){if(e.isCanceled()){U.info("all-frames iteration canceled");break}try{await pt("html",e,o.frameId)}catch(i){U.warn(`frame ${o.frameId} (${o.url.slice(0,80)}) audit failed; continuing`,i)}const r=await Ra();if((r==null?void 0:r.state)==="interrupted"){U.info("all-frames iteration interrupted");break}await Ft({completedFrames:[...(r==null?void 0:r.completedFrames)??[],o.frameId]})}H({type:"SCORECARD_UPDATED_EVENT"}),await dt()}async function Du(e){var o;const t=await pe();if(!he(t,"parallelScan")){H({type:"AUDIT_FAILED_EVENT",error:{code:"FEATURE_NOT_AVAILABLE",message:"Parallel scan is not available on your current plan.",recoverable:!1}});return}const a=await fr();let n;if(a!==null)try{n=(await chrome.tabs.get(a)).url}catch(r){U.warn("failed to get target tab url",r)}if(!n){H({type:"AUDIT_FAILED_EVENT",error:{code:"NETWORK",message:"Could not determine target URL for parallel scan.",recoverable:!1}});return}await at({sessionId:_t(),mode:"single-element",scope:"html",startedAt:new Date().toISOString(),lastProgressAt:new Date().toISOString(),state:"running"});try{const r=await zn(),{runParallelTabAudit:i}=await kn(async()=>{const{runParallelTabAudit:m}=await import("./parallel-tab-flow-DN_z0IGA.js");return{runParallelTabAudit:m}},__vite__mapDeps([0,1,2,3,4])),c=await i({targetUrl:n,scope:"html",matrix:r,parallelism:4,cancel:e});if(U.info(`parallel scan complete: ${c.results.length} results across ${c.tabsCompleted} tabs (${c.tabsFailed} failed) in ${Math.round(c.parallelDurationMs)}ms`),c.results.length===0){H({type:"AUDIT_FAILED_EVENT",error:{code:"NETWORK",message:`All ${c.tabsFailed} worker tabs failed. Falling back to Full Page scan is recommended.`,recoverable:!0}});return}const d=((o=c.results[0])==null?void 0:o.componentId)??"parallel-scan";if(a!==null)try{const m=await Ye("aiConfig",{}),u=ke(m);u.enabled&&u.apiKey&&await pa(a,"html",void 0,u,c.results,d,e)}catch(m){U.warn("parallel scan: ai augmentation skipped",m)}const l=c.results.flatMap(m=>m.violations);let p;try{p=await Gn(d,l)}catch(m){U.warn("parallel scan: baseline compare failed",m),p={new:[],persistent:[],fixed:[],newCount:0,persistentCount:0,fixedCount:0,baselineSnapshotMeta:null,comparedAt:new Date().toISOString()}}H({type:"AUDIT_COMPLETE_EVENT",componentId:d,results:c.results,delta:p}),H({type:"SCORECARD_UPDATED_EVENT"})}catch(r){U.warn("parallel scan failed",r),H({type:"AUDIT_FAILED_EVENT",error:{code:"UNKNOWN",message:r instanceof Error?r.message:String(r),recoverable:!0}})}finally{await dt()}}async function Nu(e,t){var a;try{return((a=(await chrome.scripting.executeScript({target:{tabId:e,frameIds:[t]},world:"MAIN",func:async()=>{var d,l;const o=window.__STORYBOOK_PREVIEW__;if(!o)return[];const r=o.storyStoreValue??o.storyStore;if(!r)return[];typeof r.cacheAllCSFFiles=="function"&&await r.cacheAllCSFFiles();const i=((d=r.extract)==null?void 0:d.call(r))??((l=r.cachedCSFFiles)==null?void 0:l.call(r));if(!i)return[];const c=[];if(i instanceof Map)for(const[p,m]of i){const u=m;c.push({id:String(p),name:u.name??String(p),kind:u.title??u.kind??""})}else if(typeof i=="object"&&i!==null)for(const[p,m]of Object.entries(i)){const u=m;c.push({id:p,name:u.name??p,kind:u.title??u.kind??""})}return c}}))[0])==null?void 0:a.result)??[]}catch(n){return U.warn("listStoriesViaMainWorld failed",n),[]}}async function Lu(e,t,a){try{await chrome.scripting.executeScript({target:{tabId:e,frameIds:[t]},world:"MAIN",args:[a,3e3],func:async(n,o)=>{const r=new URL(window.location.href);r.searchParams.set("id",n),r.searchParams.set("viewMode","story"),window.location.href!==r.href&&(window.history.pushState({},"",r.href),window.dispatchEvent(new PopStateEvent("popstate"))),await new Promise(i=>{const c=setTimeout(()=>i(),o),d=()=>{clearTimeout(c),i()};window.addEventListener("storyrendered",d,{once:!0})})}})}catch(n){U.warn(`navigateToStoryViaMainWorld(${a}) failed`,n)}}async function xi(e){var t;try{const n=(await chrome.scripting.executeScript({target:{tabId:e,allFrames:!0},world:"MAIN",func:()=>{const o=document.getElementById("ladle-root")!==null,r=document.title==="Ladle",i=!!document.querySelector('link[href*="ladle.css"]');return{detected:o&&(r||i),version:void 0}}})).find(o=>{var r;return(r=o.result)==null?void 0:r.detected});if(n)return{detected:!0,version:(t=n.result)==null?void 0:t.version,frameId:n.frameId}}catch(a){U.warn("ladle detection scripting failed",a)}return{detected:!1}}async function Pu(e,t){var a;try{return((a=(await chrome.scripting.executeScript({target:{tabId:e,frameIds:[t]},world:"MAIN",func:async()=>{try{const o=await fetch(new URL("/meta.json",window.location.href).href,{credentials:"same-origin"});if(!o.ok)return[];const i=(await o.json()).stories??{};return Object.entries(i).map(([c,d])=>({id:c,name:d.name??c,kind:(d.levels??[]).join(" / ")}))}catch{return[]}}}))[0])==null?void 0:a.result)??[]}catch(n){return U.warn("listLadleStoriesViaMainWorld failed",n),[]}}async function Fu(e,t,a){try{await chrome.scripting.executeScript({target:{tabId:e,frameIds:[t]},world:"MAIN",args:[a,3e3],func:async(n,o)=>{const r=new URL(window.location.href);r.searchParams.set("story",n),window.location.href!==r.href&&(window.history.pushState({},"",r.href),window.dispatchEvent(new PopStateEvent("popstate"))),await new Promise(i=>setTimeout(i,Math.min(o,500)))}})}catch(n){U.warn(`navigateToLadleStoryViaMainWorld(${a}) failed`,n)}}async function Ii(e){try{return(await chrome.scripting.executeScript({target:{tabId:e,allFrames:!0},world:"MAIN",func:()=>{const a=window.location.href;return/bit\.dev|bit-dev|bitsrc|\/~aspect|\/composition/i.test(a)}})).some(a=>a.result===!0)}catch{return!1}}async function Si(e){const t=await ki(e);if(t.detected)return{kind:"storybook",...t};const a=await xi(e);return a.detected?{kind:"ladle",...a}:await Ii(e)?{kind:"bit",detected:!0}:{kind:null,detected:!1}}const da=200,Ci=6e4;function ua(e,t){try{return new URL(e).origin===new URL(t).origin}catch{return!1}}function $i(e,t){try{const a=new URL(e,t);return a.hash="",a.toString()}catch{return null}}function Ti(e){try{return/\.(xml|rss|atom|json|txt|csv|ics|rdf|xsl|xslt)$/i.test(new URL(e).pathname)}catch{return!1}}async function Ei(e,t,a){await chrome.tabs.update(e,{url:t}),await new Promise((n,o)=>{const r=setTimeout(()=>{chrome.tabs.onUpdated.removeListener(i),o(new Error(`navigation timeout (${a}ms): ${t}`))},a);function i(c,d){c===e&&d.status==="complete"&&(clearTimeout(r),chrome.tabs.onUpdated.removeListener(i),n())}chrome.tabs.onUpdated.addListener(i)}),await new Promise(n=>setTimeout(n,400))}async function Ri(e){var t;try{return((t=(await chrome.scripting.executeScript({target:{tabId:e},func:()=>Array.from(document.querySelectorAll("a[href]")).map(n=>n.getAttribute("href")).filter(n=>typeof n=="string"&&!n.startsWith("javascript:"))}))[0])==null?void 0:t.result)??[]}catch(a){return U.debug("link discovery failed",a),[]}}async function Oi(e,t){var a,n;try{const r=new URL(t).pathname.toLowerCase().replace(/\/+$/,"");if(/(?:^|\/)(?:404|not-found|page-not-found|error|server-error)$/.test(r))return`URL path "${r||"/"}" matches a common error-route pattern.`}catch{}try{const o=await chrome.scripting.executeScript({target:{tabId:e},func:()=>document.title||""}),r=((n=(a=o==null?void 0:o[0])==null?void 0:a.result)==null?void 0:n.trim())??"";if(!r)return null;const i=[[/^4(?:0[0-46-9]|[1-9]\d)\b/,"title starts with a 4xx error code"],[/^5\d{2}\b/,"title starts with a 5xx error code"],[/^(?:page\s+)?not\s+found\b/i,'title starts with "Not Found"'],[/^error\s*[-:]?\s*\d{3}\b/i,'title starts with "Error" + status code'],[/^(?:oops|whoops)[\s,!:.-]/i,'title leads with "Oops" — common error-template pattern']];for(const[c,d]of i)if(c.test(r))return`${d} (title: "${r.slice(0,80)}").`;return null}catch(o){return U.debug("error-page detection failed; proceeding with audit",o),null}}const Uo=/Linked PDF at (\S+)\./;async function Mi(e,t){if(!he(t,"pdfAudit")){U.info("PDF audit disabled for tier; skipping crawl PDF pass",{tier:t});return}const a=new Map;for(const n of e)if(!n.error)for(const o of n.results)for(const r of o.violations){if(r.ruleId!=="pdf-needs-cli-audit")continue;const i=Uo.exec(r.description);if(!i)continue;const c=i[1];let d;try{d=new URL(c,n.url).href}catch{continue}if(!/^https?:\/\//i.test(d))continue;let l=a.get(d);l||(l=new Set,a.set(d,l)),l.add(n)}if(a.size!==0){U.info(`PDF audit pass: ${a.size} unique PDF(s) across the crawl`);for(const[n,o]of a){let r;try{r=await cl(n)}catch(i){U.warn(`PDF audit threw for ${n}`,i);continue}for(const i of o){const c=i.results[0];if(!c)continue;const d=c.componentId,l=c.state,p=r.findings.map(m=>Wo(m,n,d,l));c.violations=c.violations.filter(m=>{if(m.ruleId!=="pdf-needs-cli-audit")return!0;const u=Uo.exec(m.description);if(!u)return!0;try{return new URL(u[1],i.url).href!==n}catch{return!0}}),c.violations.push(...p),r.fatalError&&c.violations.push(Wo({ruleId:"pdf-audit-skipped",impact:"minor",wcagCriterion:"1.1.1",description:`PDF audit skipped: ${r.fatalError}`,failureSummary:"The PDF could not be audited automatically. Run `wcagcheckr-ci pdf <url>` against this PDF on the command line for a manual audit."},n,d,l))}}}}function Wo(e,t,a,n){return{ruleId:e.ruleId,wcagCriterion:e.wcagCriterion,wcagLevel:"AA",impact:e.impact,description:e.description,helpUrl:"https://www.w3.org/WAI/standards-guidelines/wcag/",target:{selector:t,outerHTML:`<a href="${t}">[PDF]</a>`,failureSummary:e.failureSummary,tagName:"PDF",role:null,accessibleName:null,textSnippet:null,attrId:null,attrTestid:null},componentId:a,currentState:n,axeVersion:"pdf-audit",detectedAt:new Date().toISOString(),matchKey:`pdf::${e.ruleId}::${t}`}}async function _u(e,t,a){if(await He())return H({type:"CRAWL_DISCOVERY_FAILED_EVENT",error:{code:Lt,message:Ze,recoverable:!1}}),[];const n=await pe();if(!he(n,"siteCrawl"))return H({type:"CRAWL_DISCOVERY_FAILED_EVENT",error:{code:"FEATURE_NOT_AVAILABLE",message:"Site crawl is not available on your current plan.",recoverable:!1}}),[];const o=await vt(),r=tr(n).siteCrawlMaxPages,i=Number.isFinite(r)?Math.min(r,da):da,c=Math.min(t.maxPages??25,i),d=t.includeRegex?ha(t.includeRegex):null,l=t.excludeRegex?ha(t.excludeRegex):null,p=[e],m=new Set,u=[];try{for(;p.length>0&&u.length<c;){if(a.isCanceled()){U.info("crawl discovery canceled by user");break}const g=p.shift();if(!(!g||m.has(g))&&ua(g,e)&&!(d&&!d.test(g))&&!(l&&l.test(g))){m.add(g);try{if(await Ei(o,g,Ci),!(await Hn(o,0)).ok||await Oi(o,g))continue;u.push(g),H({type:"CRAWL_DISCOVERY_PROGRESS_EVENT",found:u.length,url:g});const w=await Ri(o);for(const b of w){const k=$i(b,g);k&&ua(k,e)&&!Ti(k)&&!m.has(k)&&!p.includes(k)&&p.push(k)}}catch(h){U.debug("discovery: page navigation/link-read failed; skipping",h);continue}await Ft({})}}return H({type:"CRAWL_DISCOVERY_COMPLETE_EVENT",urls:u}),u}catch(g){return U.error("crawl discovery failed",g),H({type:"CRAWL_DISCOVERY_FAILED_EVENT",error:{code:"CRAWL_DISCOVERY_FAILED",message:String(g),recoverable:!0}}),[]}}async function Uu(e,t,a){if(await He()){H({type:"SITE_CRAWL_FAILED_EVENT",error:{code:Lt,message:Ze,recoverable:!1}});return}const n=await pe();if(!he(n,"siteCrawl")){H({type:"SITE_CRAWL_FAILED_EVENT",error:{code:"FEATURE_NOT_AVAILABLE",message:"Site crawl is not available on your current plan.",recoverable:!1}});return}const o=await vt(),r=tr(n).siteCrawlMaxPages,i=Number.isFinite(r)?Math.min(r,da):da,c=Array.isArray(t.urls)&&t.urls.length>0,d=Math.min(c?t.urls.length:t.maxPages??25,i),l=t.includeRegex?ha(t.includeRegex):null,p=t.excludeRegex?ha(t.excludeRegex):null,m=new Date().toISOString(),u=Date.now(),g=c?[...t.urls]:[e],h=new Set,f=[];await at({sessionId:_t(),mode:"storybook-all",scope:e,startedAt:m,lastProgressAt:new Date().toISOString(),state:"running"});try{for(;g.length>0&&h.size<d;){if(a.isCanceled()){U.info("site crawl canceled by user");break}const x=g.shift();if(!x||h.has(x)||!ua(x,e)||l&&!l.test(x)||p&&p.test(x))continue;h.add(x);const $=h.size,A=Date.now();H({type:"SITE_CRAWL_PROGRESS_EVENT",current:$,total:Math.min(d,h.size+g.length),url:x,status:"auditing"});try{await Ei(o,x,Ci);const C=await Hn(o,0);if(!C.ok)throw new Error(vn(C));const F=await Oi(o,x);if(F){const _=`Skipped — page appears to be an error response. ${F}`;f.push({url:x,results:[],delta:null,componentId:x,durationMs:Date.now()-A,error:_}),H({type:"SITE_CRAWL_PROGRESS_EVENT",current:$,total:Math.min(d,h.size+g.length),url:x,status:"failed",error:_});continue}await xe(o,{type:"WARMUP_REQUEST"},0).catch(()=>{});const T=await pt("html",a,0,void 0,{asSubroutine:!0,tabIdOverride:o,verifyFixesOnly:t.verifyFixesOnly,recordForensic:t.recordForensic}),I=T.results,D=T.ok?void 0:T.error,S=Date.now()-A;if(!T.ok&&T.skipped)f.push({url:x,results:[],delta:null,componentId:x,durationMs:S,error:T.error,skipped:!0}),H({type:"SITE_CRAWL_PROGRESS_EVENT",current:$,total:Math.min(d,h.size+g.length),url:x,status:"skipped",error:T.error});else if(I.length>0){const _=await ll(o,x).catch(()=>null),N=I.reduce((O,W)=>O+W.violations.length,0);f.push({url:x,results:I,delta:null,componentId:I[0].componentId,durationMs:S,snapshot:_??void 0}),H({type:"SITE_CRAWL_PROGRESS_EVENT",current:$,total:Math.min(d,h.size+g.length),url:x,status:"completed",violations:N})}else{const _=D??"audit returned no result";f.push({url:x,results:[],delta:null,componentId:x,durationMs:S,error:_}),H({type:"SITE_CRAWL_PROGRESS_EVENT",current:$,total:Math.min(d,h.size+g.length),url:x,status:"failed",error:_})}if(!c){const _=await Ri(o);for(const N of _){const O=$i(N,x);O&&ua(O,e)&&!Ti(O)&&!h.has(O)&&!g.includes(O)&&g.push(O)}}}catch(C){const F=Date.now()-A,T=C instanceof Error?C.message:String(C);f.push({url:x,results:[],delta:null,componentId:x,durationMs:F,error:T}),H({type:"SITE_CRAWL_PROGRESS_EVENT",current:$,total:Math.min(d,h.size+g.length),url:x,status:"failed",error:T})}await Ft({})}try{const x=await pe();await Mi(f,x)}catch(x){U.warn("PDF audit pass failed",x)}const w=new Date().toISOString(),b=Date.now()-u,k=f.flatMap(x=>x.results),v=await Le(k,[e]),s=qr(e,f,m,w,b,v.walkthroughsByComponent,v.walkthroughAcksByComponent,v.ackedKeysByComponent,v.humanVerdictsByComponent,v.incompleteResolutionsByComponent,v.attestations);try{s.auditSettings=await _n(w)}catch(x){U.warn("audit-settings capture failed",x)}if(s.consistencyFindings.length>0)try{const x=await Ll(s.consistencyFindings);s.consistencyFindings=x.emitted}catch(x){U.warn("consistency AI suppression failed; emitting heuristic findings",x)}try{const x=f.map($=>({...$,results:$.results.map(({screenshotDataUrl:A,...C})=>C)}));await pr(x,{startUrl:e,finishedAt:w})}catch(x){const $=x instanceof Error?x.message:String(x);U.error("persisting siteCrawlPerUrlResults failed",x),H({type:"SITE_CRAWL_FAILED_EVENT",error:{code:"CRAWL_PERSIST_FAILED",message:`Crawl finished but persistence failed (${$}). The AI fix prompt export won't have per-page data.`,recoverable:!1}})}H({type:"SITE_CRAWL_COMPLETE_EVENT",report:s}),await Di(s),await dt()}catch(w){U.error("site crawl failed",w),H({type:"SITE_CRAWL_FAILED_EVENT",error:{code:"UNKNOWN",message:String(w),recoverable:!1}}),await dt()}}function ha(e){try{return new RegExp(e)}catch{return null}}async function Wu(){const[e,t]=await Promise.all([En(),Zt()]);if(!e)return{ok:!1,reason:"No crawl report cached. Run a site crawl first."};if(!t||t.length===0)return{ok:!1,reason:"Crawl report exists but per-URL audit data was not retained. Re-run the crawl once; future regrades will work."};const a=t.flatMap(i=>i.results),n=await Le(a,[e.startUrl]),o=new Date().toISOString(),r=qr(e.startUrl,t,e.startedAt,o,e.totalDurationMs,n.walkthroughsByComponent,n.walkthroughAcksByComponent,n.ackedKeysByComponent,n.humanVerdictsByComponent,n.incompleteResolutionsByComponent,n.attestations);return r.auditSettings=e.auditSettings??await _n(o),await hr(r),H({type:"SITE_CRAWL_COMPLETE_EVENT",report:r}),await Di(r),{ok:!0}}async function Di(e){try{if(e.siteGrade==="pending")return;const t=await pe();if(!he(t,"forensicAnchoring"))return;const a={domain:Au(e.startUrl),grade:e.siteGrade,scope:"site",pageCount:e.pagesAudited,wcagLevel:`${Nt} ${In}`,auditedAt:e.finishedAt,productSlug:"wcagcheckr"},n=await vu(a),o=await ga(),r=await Ai(n,e.startUrl,e.finishedAt,o??void 0);await Iu({domain:a.domain,claim:a,hash:n,receipt:r}),H({type:"SITE_CLAIM_SEALED_EVENT",domain:a.domain})}catch(t){U.warn("site-claim seal/anchor failed (badge unavailable for this crawl)",t)}}const en=5*6e4,Go=9e4,Vo={altText:"Verifying alt text…",headings:"Judging heading quality…",sensory:"Scanning for sensory-only instructions…",aria:"Reviewing ARIA semantics…",imageOfText:"Detecting baked-in text in images…",colorOnlyMeaning:"Checking for color-only meaning…",genericLinkText:"Reviewing link clarity…",wallOfText:"Detecting walls of text…",languageMismatch:"Verifying page language…"},Gu={altText:["1.1.1"],headings:["2.4.6"],sensory:["1.3.3"],aria:["4.1.2"],imageOfText:["1.4.5"],colorOnlyMeaning:["1.4.1"],genericLinkText:["2.4.4"],wallOfText:[],languageMismatch:["3.1.1","3.1.2"]};async function pa(e,t,a,n,o,r,i){const c=await pe();if(!he(c,"aiJudgment")){U.debug("aiJudgment not allowed on current tier — skipping AI augmentation");return}let d;try{d=await xe(e,{type:"AI_CANDIDATES_REQUEST",selector:t},a)}catch(S){U.debug("ai candidates fetch failed",S);return}const l=o[0];if(!l)return;const p={componentId:r,currentState:l.state,axeVersion:l.axeVersion},m={at:new Date().toISOString(),componentId:r,pageUrl:l.pageUrl??t,enabledChecks:n.enabledChecks,candidateCounts:{images:d.images.length,headings:d.headings.length,instructions:d.instructions.length,ariaElements:d.ariaElements.length,links:d.links.length,longTextBlocks:d.longTextBlocks.length,colorOnlyRegions:d.colorOnlyRegions.length,languageInfo:d.languageInfo?"present":"null"}};U.info("ai augmentation gate snapshot",JSON.stringify(m));try{await chrome.storage.local.set({aiDiagnosticLatest:m})}catch(S){U.warn("failed to persist ai diagnostic to storage.local",S)}const u=[];if(n.enabledChecks.altText&&u.push({key:"altText",run:S=>{const _=d.images.map(N=>({imageUrl:N.imageUrl,alt:N.alt,selector:N.selector,outerHTML:N.outerHTML,surroundingContext:N.surroundingContext,...p}));return fd(_,n,S)}}),n.enabledChecks.headings&&u.push({key:"headings",run:S=>ou(d.headings,p,n,S)}),n.enabledChecks.sensory&&u.push({key:"sensory",run:S=>ru(d.instructions,p,n,S)}),n.enabledChecks.aria&&u.push({key:"aria",run:S=>iu(d.ariaElements,p,n,S)}),n.enabledChecks.imageOfText&&u.push({key:"imageOfText",run:S=>{const _=d.images.map(N=>({imageUrl:N.imageUrl,accessibleName:N.alt||void 0,selector:N.selector,outerHTML:N.outerHTML,pixelArea:N.pixelArea}));return du(_,p,n,S)}}),n.enabledChecks.colorOnlyMeaning&&u.push({key:"colorOnlyMeaning",run:S=>uu(d.colorOnlyRegions,p,n,S)}),n.enabledChecks.genericLinkText&&u.push({key:"genericLinkText",run:S=>su(d.links,p,n,S)}),n.enabledChecks.wallOfText&&u.push({key:"wallOfText",run:S=>cu(d.longTextBlocks,p,n,S)}),n.enabledChecks.languageMismatch){const S=d.languageInfo;u.push({key:"languageMismatch",run:_=>lu(S?[S]:[],p,n,_)})}if(u.length===0)return;let g=0,h=0,f=!1;const w={};let b=0,k=0,v=0;const s=[];let x=!1,$=!1;function A(S,_){if(w[S]=(w[S]??0)+_.totalCostUsd,g+=_.totalCostUsd,h+=_.findings.length,f=f||_.capExceeded,b++,_.errors.length>0){v++;for(const N of _.errors)s.includes(N)||s.push(N)}else k++;U.info(`ai ${S}: ${_.findings.length} findings, $${_.totalCostUsd.toFixed(4)}, errs=${_.errors.length}`),_.capExceeded&&U.warn(`ai cost cap exceeded after $${_.totalCostUsd.toFixed(4)} during ${S}`)}const C=(async()=>{for(let S=0;S<u.length;S++){if(i!=null&&i.isCanceled()){$=!0;break}const _=u[S];H({type:"AI_AUGMENTATION_PROGRESS_EVENT",componentId:r,currentCheck:_.key,currentCheckLabel:Vo[_.key],current:S+1,total:u.length});const N=new AbortController,O=setTimeout(()=>N.abort(),Go),W=i?setInterval(()=>{i.isCanceled()&&N.abort()},500):null;let P;try{P=await _.run({signal:N.signal,onProgress:(V,M)=>{M>0&&H({type:"AI_AUGMENTATION_PROGRESS_EVENT",componentId:r,currentCheck:_.key,currentCheckLabel:Vo[_.key],current:S+1,total:u.length,candidatesDone:V,candidatesTotal:M})}}),N.signal.aborted&&(i!=null&&i.isCanceled())?P.errors=[...P.errors,`${_.key} canceled by user`]:N.signal.aborted}catch(V){const M=V instanceof Error?V.message:String(V),j=N.signal.aborted,q=j&&(i!=null&&i.isCanceled())?`${_.key} canceled by user`:j?`${_.key} hit per-check ${Go/1e3}s cap — analyzer aborted`:`${_.key} threw: ${M}`;P={findings:[],totalCostUsd:0,capExceeded:!1,errors:[q]}}finally{clearTimeout(O),W&&clearInterval(W)}if(P.findings.length>0&&(l.violations=[...l.violations,...P.findings]),P.errors.length===0){const V=Gu[_.key];if(V&&V.length>0&&l.axeRulesEvaluated)for(const M of V)l.axeRulesEvaluated.passed.push({ruleId:`ai-${_.key}-coverage`,wcagCriterion:M})}A(_.key,P)}})(),F=new Promise(S=>{setTimeout(()=>S("timeout"),en)});await Promise.race([C.then(()=>"done"),F])==="timeout"&&(x=!0,U.warn(`ai augmentation hit global ${en/1e3}s timeout after ${b}/${u.length} checks`));let I;if(v>0||x||$){x?I=`AI augmentation timed out after ${en/1e3}s`:$?I="AI augmentation canceled":I=s[0]??"AI analyzer error";const S=k===0?"total":"partial";H({type:"AI_AUGMENTATION_FAILED_EVENT",componentId:r,severity:S,reason:I,checksAttempted:b,checksSucceeded:k,checksErrored:v,errorDetails:x||$?[I,...s.slice(0,4)]:s.slice(0,5)}),U.warn(`ai augmentation ${S} failure: ${v}/${b} checks errored — ${I}`)}(g>0||h>0||I)&&await fs({at:new Date().toISOString(),pageUrl:l.pageUrl??t,componentId:r,totalCostUsd:g,byCheck:w,findingsCount:h,capExceeded:f,failureReason:I})}const nf=Object.freeze(Object.defineProperty({__proto__:null,auditCrawlPdfs:Mi,detectBit:Ii,detectLadleAcrossFrames:xi,detectPlayground:Si,detectStorybookAcrossFrames:ki,discoverCrawlUrls:_u,getActiveTabId:vt,getMatrixSettings:zn,regradeSiteCrawl:Wu,runAiAugmentation:pa,runAllFramesAudit:Mu,runParallelScan:Du,runSingleElementAudit:pt,runSiteCrawl:Uu,runStorybookAllAudit:Ou},Symbol.toStringTag,{value:"Module"})),St=Z("alert-sender"),Vu="wcagcheckr",ju="https://api.wcagcheckr.com",Bu=`${ju}/v1/products/${Vu}/alerts/send`,Hu=1e4,An="alertConfig:v1",qu={emailEnabled:!1,webhookEnabled:!1,webhookUrl:"",minImpact:"serious"},zt={minor:1,moderate:2,serious:3,critical:4};async function zu(){const t=(await chrome.storage.local.get(An))[An];return{...qu,...t??{}}}async function of(e){await chrome.storage.local.set({[An]:e})}async function Ku(e){let t;try{t=await zu()}catch(h){return St.warn("failed to read alert config",h),{fired:!1,reason:"config_read_failed"}}if(!t.emailEnabled&&!t.webhookEnabled)return{fired:!1,reason:"no_channel_enabled"};const a=await pe(),n=he(a,"emailAlerts"),o=he(a,"webhookAlerts"),r=t.emailEnabled&&n,i=t.webhookEnabled&&o;if(!r&&!i)return{fired:!1,reason:"no_channel_enabled"};const c=[];for(const h of e.results){const f=h.delta;f!=null&&f.new&&c.push(...f.new)}const d=zt[t.minImpact],l=c.filter(h=>zt[h.impact]>=d);if(l.length===0)return{fired:!1,reason:"below_impact_threshold"};const p=await ga();if(!p)return St.debug("no license token; alert skipped"),{fired:!1,reason:"no_license_token"};l.sort((h,f)=>zt[f.impact]-zt[h.impact]);const m=l.slice(0,10).map(h=>({wcag:h.wcagCriterion,impact:h.impact,selector:h.target.selector,help:h.description.slice(0,480),helpUrl:h.helpUrl})),u=e.results.reduce((h,f)=>h+f.violations.length,0),g={token:p,scheduleId:e.scheduleId,auditedUrl:e.auditedUrl,totalViolations:u,newViolationCount:l.length,topViolations:m,webhookUrl:i&&t.webhookUrl?t.webhookUrl:void 0,emailEnabled:r,ranAt:e.ranAt};try{const h=await fetch(Bu,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(g),signal:AbortSignal.timeout(Hu)}),f=await h.json().catch(()=>null);return h.ok?(St.info("alert delivered",{emailSent:f==null?void 0:f.emailSent,webhookSent:f==null?void 0:f.webhookSent}),{fired:!0,emailSent:(f==null?void 0:f.emailSent)??!1,webhookSent:(f==null?void 0:f.webhookSent)??!1,serverStatus:h.status}):(St.warn(`alert server returned ${h.status}`,f),{fired:!1,reason:`server_${h.status}`,serverStatus:h.status})}catch(h){return St.warn("alert send failed",h),{fired:!1,reason:h instanceof Error?h.message:"unknown_error"}}}const Yu="#dc2626",Ju="#f59e0b",Xu="#059669",Qu="#94a3b8";function Zu(e){const t=e.filter(c=>c.enabled);let a=0,n=0,o=0,r=0;for(const c of t){const d=c.lastNewViolationCount??0;c.lastResult==="failed"?n++:c.lastResult==="ok"?d>0?a+=d:o++:r++}let i;return t.length===0?i="no-schedules":a>0?i="new-violations":n>0?i="failed":o>0?i="all-clear":i="pending-first-run",{state:i,newViolationsTotal:a,failingCount:n,okCount:o,pendingCount:r,totalEnabled:t.length}}async function eh(e){switch(e.state){case"new-violations":{const t=e.newViolationsTotal>99?"99+":String(e.newViolationsTotal);await chrome.action.setBadgeText({text:t}),await chrome.action.setBadgeBackgroundColor({color:Yu}),await chrome.action.setTitle({title:`wcagcheckr — ${e.newViolationsTotal} new WCAG violation${e.newViolationsTotal===1?"":"s"} vs baseline across ${e.totalEnabled} scheduled audit${e.totalEnabled===1?"":"s"}`});break}case"failed":{await chrome.action.setBadgeText({text:"!"}),await chrome.action.setBadgeBackgroundColor({color:Ju}),await chrome.action.setTitle({title:`wcagcheckr — ${e.failingCount} scheduled audit${e.failingCount===1?"":"s"} failed to run`});break}case"all-clear":{await chrome.action.setBadgeText({text:"✓"}),await chrome.action.setBadgeBackgroundColor({color:Xu}),await chrome.action.setTitle({title:`wcagcheckr — all ${e.okCount} scheduled audit${e.okCount===1?"":"s"} passing`});break}case"pending-first-run":{await chrome.action.setBadgeText({text:""}),await chrome.action.setBadgeBackgroundColor({color:Qu}),await chrome.action.setTitle({title:`wcagcheckr — ${e.pendingCount} scheduled audit${e.pendingCount===1?"":"s"} awaiting first run`});break}case"no-schedules":default:{await chrome.action.setBadgeText({text:""}),await chrome.action.setTitle({title:"wcagcheckr"});break}}}async function th(){const e=await pe();if(!he(e,"statusBadge")){try{await chrome.action.setBadgeText({text:""})}catch{}return{state:"no-schedules",newViolationsTotal:0,failingCount:0,okCount:0,pendingCount:0,totalEnabled:0}}const t=await cr(),a=Zu(t);try{await eh(a)}catch(n){console.warn("[status-badge] failed to apply",n)}return a}const jo=Z("deposition-packet");function J(e){return e.replace(/[&<>"']/g,t=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[t])}function ah(e,t,a){if(!e)return`<section class="dp-cover dp-cover-error">
1028
- <h2 style="margin:0 0 8pt 0; color:#b91c1c">⚠ Chain-of-Custody: UNAVAILABLE</h2>
1029
- <p>This packet could not be sealed because the underlying audit record was empty. Provenance cannot be verified.</p>
1030
- </section>`;const n=Jr(e.hash);return t?`<section class="dp-cover dp-cover-sealed" style="border:2pt solid #059669; background:#ecfdf5; padding:14pt; border-radius:4pt; margin:0 0 14pt 0">
1031
- <h2 style="margin:0 0 8pt 0; color:#064e3b">🔒 Chain-of-Custody: SEALED (RFC 3161 + ed25519)</h2>
1032
- <p style="margin:0 0 10pt 0">This audit's content hash was independently witnessed by a public RFC 3161 timestamp authority and counter-signed by the wcagcheckr server. The seal can be verified offline using only published keys.</p>
1033
- <dl style="margin:0; font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size:9pt">
1034
- <dt style="font-weight:600">Audit hash (SHA-256)</dt>
1035
- <dd style="margin:0 0 6pt 16pt; word-break:break-all">${J(e.hash)}</dd>
1036
- <dt style="font-weight:600">Captured at (extension)</dt>
1037
- <dd style="margin:0 0 6pt 16pt">${J(e.capturedAt)}</dd>
1038
- <dt style="font-weight:600">Anchored at (server)</dt>
1039
- <dd style="margin:0 0 6pt 16pt">${J(t.anchoredAt)}</dd>
1040
- <dt style="font-weight:600">RFC 3161 timestamp authority</dt>
1041
- <dd style="margin:0 0 6pt 16pt">${J(t.tsaName)}</dd>
1042
- <dt style="font-weight:600">Server key fingerprint</dt>
1043
- <dd style="margin:0 0 6pt 16pt; word-break:break-all">${J(t.serverKeyFingerprint)}</dd>
1044
- <dt style="font-weight:600">RFC 3161 token (base64)</dt>
1045
- <dd style="margin:0 0 6pt 16pt; word-break:break-all; max-height:60pt; overflow:auto; background:#f1f5f9; padding:4pt; border-radius:2pt" tabindex="0">${J(t.rfc3161TokenBase64)}</dd>
1046
- <dt style="font-weight:600">Server signature (base64, ed25519)</dt>
1047
- <dd style="margin:0 0 6pt 16pt; word-break:break-all; max-height:60pt; overflow:auto; background:#f1f5f9; padding:4pt; border-radius:2pt" tabindex="0">${J(t.serverSignatureBase64)}</dd>
1048
- </dl>
1049
- <p style="margin:10pt 0 0 0">
1050
- <strong>Verify online:</strong>
1051
- <a href="${J(n)}" style="color:#1e40af">${J(n)}</a>
1052
- </p>
1053
- </section>`:`<section class="dp-cover dp-cover-warning" style="border:2pt solid #f59e0b; background:#fef3c7; padding:14pt; border-radius:4pt; margin:0 0 14pt 0">
1054
- <h2 style="margin:0 0 8pt 0; color:#92400e">⚠ Chain-of-Custody: LOCAL-ONLY (Not Third-Party Anchored)</h2>
1055
- <p style="margin:0 0 8pt 0">This audit has a SHA-256 integrity hash but was <strong>not anchored</strong> to the wcagcheckr trusted-timestamp service when this packet was generated${a?` (${J(a)})`:""}. The seal is self-attested rather than independently witnessed by an RFC 3161 timestamp authority.</p>
1056
- <dl style="margin:8pt 0 0 0; font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size:9pt">
1057
- <dt style="font-weight:600">Audit hash (SHA-256)</dt>
1058
- <dd style="margin:0 0 6pt 16pt; word-break:break-all">${J(e.hash)}</dd>
1059
- <dt style="font-weight:600">Captured at</dt>
1060
- <dd style="margin:0 0 6pt 16pt">${J(e.capturedAt)}</dd>
1061
- <dt style="font-weight:600">Page URL</dt>
1062
- <dd style="margin:0 0 6pt 16pt">${J(e.pageUrl)}</dd>
1063
- <dt style="font-weight:600">Grade</dt>
1064
- <dd style="margin:0 0 6pt 16pt">${J(e.grade)}</dd>
1065
- </dl>
1066
- <p style="margin:8pt 0 0 0; font-size:10pt"><strong>To convert to anchored status:</strong> re-run this export with an online connection to api.wcagcheckr.com.</p>
1067
- </section>`}function nh(e,t){var n;if(!e)return"";const a=Jr(e.hash);return`<section class="dp-verification" style="border:1pt solid #cbd5e1; padding:14pt; margin:24pt 0; border-radius:4pt; background:#f8fafc">
1068
- <h2 style="margin:0 0 8pt 0">How to verify this audit's integrity</h2>
1069
- <p style="margin:0 0 8pt 0">This packet is the output of an automated WCAG accessibility audit conducted by the wcagcheckr Chrome extension. The audit's content has been cryptographically sealed so any modification to this document — including changes to the violation list, the screenshots, or the grade — would invalidate the seal.</p>
1070
-
1071
- <h3 style="margin:14pt 0 6pt 0">Quick verification (recommended)</h3>
1072
- <ol style="margin:0 0 8pt 20pt; padding:0">
1073
- <li style="margin-bottom:4pt">Visit <a href="${J(a)}">${J(a)}</a></li>
1074
- <li style="margin-bottom:4pt">The page will look up the audit hash <code>${J(e.hash.slice(0,16))}…</code> against the wcagcheckr trusted-anchor log.</li>
1075
- <li style="margin-bottom:4pt">If the page reports "VERIFIED", the seal is intact: the audit's content matches what was witnessed by the timestamp authority at <strong>${J((t==null?void 0:t.anchoredAt)??"(not anchored)")}</strong>.</li>
1076
- <li style="margin-bottom:4pt">If the page reports "NOT FOUND" or "INVALID", the document has been modified or the audit was never anchored.</li>
1077
- </ol>
1078
-
1079
- <h3 style="margin:14pt 0 6pt 0">Offline verification</h3>
1080
- <p style="margin:0 0 6pt 0">The seal can be verified without contacting wcagcheckr's servers using only the published RFC 3161 timestamp-authority certificate and the wcagcheckr public ed25519 key. The procedure:</p>
1081
- <ol style="margin:0 0 8pt 20pt; padding:0">
1082
- <li style="margin-bottom:4pt">Compute SHA-256 over the canonical-JSON of the audit identity block (hash inputs are documented at <a href="https://api.wcagcheckr.com/verify-format">api.wcagcheckr.com/verify-format</a>).</li>
1083
- <li style="margin-bottom:4pt">Verify the RFC 3161 token (above) against the published TSA certificate from <strong>${J((t==null?void 0:t.tsaName)??"(not anchored)")}</strong>.</li>
1084
- <li style="margin-bottom:4pt">Verify the server ed25519 signature (above) using the wcagcheckr public key with fingerprint <code>${J(((n=t==null?void 0:t.serverKeyFingerprint)==null?void 0:n.slice(0,16))??"(not anchored)")}…</code> (full key downloadable at <a href="https://api.wcagcheckr.com/v1/products/wcagcheckr/forensic/public-key">api.wcagcheckr.com/v1/products/wcagcheckr/forensic/public-key</a>).</li>
1085
- </ol>
1086
-
1087
- <h3 style="margin:14pt 0 6pt 0">What the seal proves</h3>
1088
- <ul style="margin:0 0 8pt 20pt; padding:0">
1089
- <li style="margin-bottom:4pt"><strong>Existence at a point in time:</strong> the RFC 3161 timestamp witnesses that this content existed at the anchored timestamp. (An independent third party — the TSA — bound the hash to that moment.)</li>
1090
- <li style="margin-bottom:4pt"><strong>Integrity:</strong> the SHA-256 hash means any subsequent edit to the audit content (violations, screenshots, grade, etc.) produces a different hash, breaking the seal.</li>
1091
- <li style="margin-bottom:4pt"><strong>Provenance:</strong> the ed25519 signature is over (audit hash + anchored-at + TSA name + product slug + previous-anchor hash), proving wcagcheckr's server is the source.</li>
1092
- </ul>
1093
-
1094
- <h3 style="margin:14pt 0 6pt 0">What the seal does NOT prove</h3>
1095
- <ul style="margin:0 0 8pt 20pt; padding:0">
1096
- <li style="margin-bottom:4pt">It does not prove the audit conclusions are correct — only that the audit's content is unchanged since sealing.</li>
1097
- <li style="margin-bottom:4pt">It does not authenticate the auditor (a human operator may have run the extension; the seal only attests to the audit content).</li>
1098
- <li style="margin-bottom:4pt">It does not warrant against future protocol breaks (cryptography evolves; a seal valid today may need re-anchoring decades later).</li>
1099
- </ul>
1100
- </section>`}function oh(e){return e?`<section class="dp-declaration" style="border:1pt solid #cbd5e1; padding:14pt; margin:24pt 0; border-radius:4pt; page-break-before:always">
1101
- <h2 style="margin:0 0 8pt 0">Declaration under penalty of perjury (template)</h2>
1102
- <p style="margin:0 0 8pt 0; font-size:10pt; color:#475569">The template below is provided for the convenience of the auditor and should be reviewed by competent counsel before execution. wcagcheckr makes no representation that this template is sufficient for any particular jurisdiction's requirements.</p>
1103
- <div style="border:1pt dashed #94a3b8; padding:12pt; background:#ffffff">
1104
- <p style="margin:0 0 10pt 0">I, <strong>[Name of declarant]</strong>, of <strong>[City, State / Province]</strong>, hereby declare under penalty of perjury under the laws of <strong>[jurisdiction]</strong> that the following is true and correct:</p>
1105
- <ol style="margin:0 0 10pt 20pt">
1106
- <li style="margin-bottom:6pt">I conducted an automated accessibility audit of <strong>${J(e.pageUrl)}</strong> on <strong>${J(e.capturedAt)}</strong> using the wcagcheckr Chrome extension, version <strong>${J(Ee())}</strong>, running axe-core <strong>${J(e.axeVersion)}</strong>.</li>
1107
- <li style="margin-bottom:6pt">The audit produced a SHA-256 content hash of <code style="word-break:break-all">${J(e.hash)}</code>, which was sealed via RFC 3161 trusted timestamp and the wcagcheckr server's ed25519 signature.</li>
1108
- <li style="margin-bottom:6pt">The contents of this packet (the chain-of-custody cover, the findings, the per-state screenshots, and the verification instructions) are an accurate and complete representation of the sealed audit. No findings were added, removed, or altered after sealing.</li>
1109
- <li style="margin-bottom:6pt">[Optional: I am personally familiar with the page audited, and to the best of my knowledge it was in its [production / staging / pre-deployment] state on the audit date.]</li>
1110
- </ol>
1111
- <p style="margin:14pt 0 6pt 0">Executed on <strong>[Date]</strong> at <strong>[Location]</strong>.</p>
1112
- <p style="margin:24pt 0 6pt 0; border-top:1pt solid #0f172a; padding-top:6pt; max-width:300pt"><strong>[Signature]</strong></p>
1113
- <p style="margin:0; font-size:10pt"><strong>[Printed name]</strong></p>
1114
- </div>
1115
- </section>`:""}function rh(e){const t=e.map(a=>({...a,screenshotDataUrl:void 0,states:void 0}));return`<section class="dp-raw-json" style="display:none" aria-hidden="true">
1116
- <h2>Raw axe-core JSON (machine-readable)</h2>
1117
- <p>The block below is the unfiltered axe-core output included for machine re-verification. View HTML source to extract.</p>
1118
- <pre id="wcagcheckr-axe-raw-json" data-product="wcagcheckr" data-format="deposition-packet-v1">${J(JSON.stringify(t,null,2))}</pre>
1119
- </section>`}async function ih(e,t,a,n,o,r){if(e.length===0)return null;const i=e[0],d=(await al(i.componentId)).find(u=>u.capturedAt===i.startedAt);if(d)return d;const l=e.flatMap(u=>u.violations),p=et(l,{runs:[],workflows:Pe},e,n,t,a,o,ft(e),r),m=e.reduce((u,g)=>u+g.durationMs,0);return zr(e,{...p.score,letter:p.combined},m)}async function Ni(e){let t;try{t=await ih(e.results,e.interactiveAuditResults,e.walkthroughAcks,e.acknowledgedMatchKeys,e.humanCriterionVerdicts,e.incompleteResolutions)}catch(f){jo.warn("ensureForensicEntry failed",f),t=null}let a;if(t&&!t.receipt)try{const f=await vi(t,e.licenseId);f?(await Kr(t.componentId,t.capturedAt,f),t={...t,receipt:f}):a="server returned null or malformed receipt"}catch(f){a=f instanceof Error?f.message:String(f),jo.warn("anchor failed",f)}const n=await Tt().catch(()=>[]),o=Ut(e.results,e.delta,"defense",e.manualRuns,n,e.aiSummary??void 0,e.wallClockMs,e.interactiveAuditResults,e.walkthroughAcks,e.acknowledgedMatchKeys,e.humanCriterionVerdicts,e.incompleteResolutions),r=await _n(new Date().toISOString()).catch(()=>{}),i=ah(t,(t==null?void 0:t.receipt)??null,a)+`<section class="dp-grade-scope" style="border:1pt solid #cbd5e1; background:#f8fafc; padding:12pt; border-radius:4pt; margin:0 0 14pt 0"><h3 style="margin:0 0 6pt 0; font-size:11pt;">About this grade — basis and limits</h3><p style="margin:0 0 6pt 0; font-size:9.5pt; line-height:1.5; color:#334155">${J(Vr)}</p><p style="margin:0; font-size:9.5pt; line-height:1.5; color:#334155"><strong>Audit rigor:</strong> ${J(oi(r))}`+(()=>{const f=ri(r);return f?` <strong style="color:#b45309">[${J(f)}]</strong>`:' <strong style="color:#047857">[Full 2.1 AA audit — settings cleared the conformance bar.]</strong>'})()+"</p></section>",c=nh(t,(t==null?void 0:t.receipt)??null),d=oh(t),l=rh(e.results);let p=o;const m=p.indexOf("<h1");m>-1?p=p.slice(0,m)+i+p.slice(m):p=i+p;const u=p.lastIndexOf("</main>"),g=u>-1?u:p.lastIndexOf("</body>"),h=c+d+l;return p=g>-1?p.slice(0,g)+h+p.slice(g):p+h,{html:p,entry:t,anchored:!!(t!=null&&t.receipt),anchorError:a}}function Se(e){return e.replace(/[&<>"']/g,t=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[t])}function sh(e){const t=new Set;for(const a of e){const n=a.axeRulesEvaluated;if(n){for(const o of n.passed??[])t.add(o.ruleId);for(const o of n.inapplicable??[])t.add(o.ruleId);for(const o of n.incomplete??[])t.add(o.ruleId);for(const o of a.violations)t.add(o.ruleId)}}return t}const ch=new Set(["1.1.1","1.2.2","1.3.1","1.3.4","1.3.5","1.4.1","1.4.2","1.4.3","1.4.4","2.1.1","2.2.2","2.4.1","2.4.2","2.4.4","2.4.6","2.5.3","3.1.1","3.1.2","3.2.2","3.3.1","3.3.2","4.1.1","4.1.2","4.1.3"]);function lh(e,t,a,n){return`<section>
1120
- <h2>1. Tool identification</h2>
1121
- <table style="border-collapse:collapse; margin-top:8pt; font-size:10pt">
1122
- <tr><td style="padding:2pt 12pt 2pt 0; color:#475569">Tool</td><td><strong>wcagcheckr</strong> — Chrome MV3 accessibility audit extension</td></tr>
1123
- <tr><td style="padding:2pt 12pt 2pt 0; color:#475569">Extension version</td><td><code>${Se(t)}</code></td></tr>
1124
- <tr><td style="padding:2pt 12pt 2pt 0; color:#475569">Audit engine</td><td><code>axe-core ${Se(a)}</code> (pinned; not auto-updated)</td></tr>
1125
- <tr><td style="padding:2pt 12pt 2pt 0; color:#475569">WCAG target</td><td>WCAG ${Se(e)} Level AA</td></tr>
1126
- <tr><td style="padding:2pt 12pt 2pt 0; color:#475569">Conformance frame</td><td>EN 301 549 v3.2.1 (EU); Section 508 / ADA (US); EAA Directive 2019/882 (EU, enforceable 2025-06-28)</td></tr>
1127
- ${n?`<tr><td style="padding:2pt 12pt 2pt 0; color:#475569">Audit captured at</td><td><code>${Se(n)}</code></td></tr>`:""}
1128
- </table>
1129
- </section>`}function dh(){return`<section>
1130
- <h2>2. Methodology overview</h2>
1131
- <p>The wcagcheckr audit framework rests on three layers that complement (rather than overlap) one another:</p>
1132
- <ol>
1133
- <li><strong>Multi-state matrix audit.</strong> Most accessibility scanners check a page in its default rendered state — i.e. <em>after</em> a CSS theme loads but <em>before</em> a user has interacted with it. Real users hover, focus, click, type, and toggle disabled/expanded states; the page transitions through dozens of distinct rendering states that a stateless scanner cannot observe. wcagcheckr drives each interactive element through a configurable matrix of pseudo-states (<code>:hover</code>, <code>:focus</code>, <code>:focus-visible</code>, <code>:active</code>, <code>:disabled</code>), ARIA states (<code>aria-expanded</code>, <code>aria-pressed</code>, <code>aria-selected</code>, <code>aria-invalid</code>), themes (light, dark, forced-colors), text direction (LTR, RTL), and viewport breakpoints, running axe-core <em>at every state</em>.</li>
1134
- <li><strong>Delta-only reporting.</strong> Findings are diffed against a stored baseline. The audit surfaces only <em>new</em> violations relative to the last accepted state — preventing the regression-vs-inherited-debt confusion that floods stateless-scanner reports.</li>
1135
- <li><strong>Per-component scorecards.</strong> Findings are attributed to a stable component identity (URL + ARIA test-id + structural fingerprint) rather than to a one-off page snapshot, so re-audits over time produce a coherent history per design-system component.</li>
1136
- </ol>
1137
- <p>The audit pipeline is fail-safe: each state is captured + scored independently, so a transient layout glitch or third-party script load failure in one state does not invalidate findings from the other states.</p>
1138
- </section>`}function uh(){return`<section>
1139
- <h2>3. State matrix specification</h2>
1140
- <p>For each in-scope interactive element, the audit drives the following dimensions and records the rendered DOM + computed styles at each combination:</p>
1141
- <table style="border-collapse:collapse; font-size:10pt; margin-top:8pt">
1142
- <tr style="border-bottom:1px solid #cbd5e1">
1143
- <th style="text-align:left; padding:4pt 12pt 4pt 0">Dimension</th>
1144
- <th style="text-align:left; padding:4pt 12pt 4pt 0">States driven</th>
1145
- <th style="text-align:left; padding:4pt">Mechanism</th>
1146
- </tr>
1147
- <tr><td style="padding:4pt 12pt 4pt 0">Pseudo-states</td><td style="padding:4pt 12pt 4pt 0">default, :hover, :focus, :focus-visible, :active, :disabled</td><td style="padding:4pt; color:#475569">CSS.forcePseudoState via chrome.debugger</td></tr>
1148
- <tr><td style="padding:4pt 12pt 4pt 0">ARIA states</td><td style="padding:4pt 12pt 4pt 0">aria-expanded, aria-pressed, aria-selected, aria-invalid, aria-busy</td><td style="padding:4pt; color:#475569">Direct attribute mutation + axe re-evaluation</td></tr>
1149
- <tr><td style="padding:4pt 12pt 4pt 0">Theme</td><td style="padding:4pt 12pt 4pt 0">light, dark, forced-colors (Windows High Contrast)</td><td style="padding:4pt; color:#475569">Emulation.setEmulatedMedia (prefers-color-scheme, forced-colors)</td></tr>
1150
- <tr><td style="padding:4pt 12pt 4pt 0">Direction</td><td style="padding:4pt 12pt 4pt 0">LTR, RTL</td><td style="padding:4pt; color:#475569">document.dir mutation</td></tr>
1151
- <tr><td style="padding:4pt 12pt 4pt 0">Viewport</td><td style="padding:4pt 12pt 4pt 0">320px, 768px, 1280px (configurable)</td><td style="padding:4pt; color:#475569">Emulation.setDeviceMetricsOverride</td></tr>
1152
- <tr><td style="padding:4pt 12pt 4pt 0">Motion preference</td><td style="padding:4pt 12pt 4pt 0">prefers-reduced-motion: reduce</td><td style="padding:4pt; color:#475569">Emulation.setEmulatedMedia</td></tr>
1153
- </table>
1154
- <p style="margin-top:10pt">At each combination, a viewport screenshot is captured, the computed-style snapshot is recorded, and axe-core is invoked against the live DOM (not a serialized copy). Findings are tagged with the originating state so reports show which state produced each violation.</p>
1155
- </section>`}function hh(e,t){const a=new Set;for(const r of Bo)for(const i of r.rules)a.add(i);const o=Array.from(a).sort().map(r=>{const i=t.has(r),d=Bo.filter(l=>l.rules.includes(r)).map(l=>`${l.ref} ${l.title}`).join(", ")||"(unmapped)";return`<tr>
1156
- <td style="padding:3pt; font-family:monospace; font-size:9pt"><code>${Se(r)}</code></td>
1157
- <td style="padding:3pt; font-size:9pt">${Se(d)}</td>
1158
- <td style="padding:3pt; font-size:9pt; ${i?"color:#065f46;font-weight:600":"color:#475569"}">${i?"✓ ran":"— not in this run"}</td>
1159
- </tr>`}).join("");return`<section>
1160
- <h2>4. Automated rule coverage (axe-core)</h2>
1161
- <p>${e?'The audit referenced by this methodology document evaluated the following axe-core rules. Rules marked <span style="color:#065f46;font-weight:600">✓ ran</span> were exercised; rules marked otherwise were not in scope for this particular audit (either not triggered by any element on the audited page, or filtered out by the user-configured rule list).':"The wcagcheckr audit framework draws from the axe-core rule set, mapped to WCAG success criteria as follows."}</p>
1162
- <table style="border-collapse:collapse; font-size:10pt; margin-top:8pt; width:100%">
1163
- <tr style="border-bottom:1px solid #cbd5e1">
1164
- <th style="text-align:left; padding:4pt 8pt 4pt 4pt">axe-core rule</th>
1165
- <th style="text-align:left; padding:4pt 8pt 4pt 4pt">WCAG criterion</th>
1166
- <th style="text-align:left; padding:4pt">Status${e?" (this audit)":""}</th>
1167
- </tr>
1168
- ${o}
1169
- </table>
1170
- </section>`}function ph(e){const t=new Set((e??[]).map(n=>n.workflowId));return`<section>
1171
- <h2>5. Manual workflow framework (Intelligent Guided Tests)</h2>
1172
- <p>WCAG includes criteria that cannot be reduced to a single automated heuristic — keyboard reachability, focus management, screen-reader announcement quality, cognitive task complexity. wcagcheckr provides curated step-by-step workflows that surface the right specific checks at the right time, recorded for inclusion in the audit record:</p>
1173
- <table style="border-collapse:collapse; font-size:10pt; margin-top:8pt; width:100%">
1174
- <tr style="border-bottom:1px solid #cbd5e1">
1175
- <th style="text-align:left; padding:4pt">Workflow</th>
1176
- <th style="text-align:left; padding:4pt">Coverage</th>
1177
- <th style="text-align:right; padding:4pt">Length</th>
1178
- <th style="text-align:left; padding:4pt">Status</th>
1179
- </tr>
1180
- ${Pe.map(n=>{const o=t.has(n.id),r=n.steps.length;return`<tr>
1181
- <td style="padding:4pt; font-weight:600">${Se(n.name)}</td>
1182
- <td style="padding:4pt; color:#475569; max-width:380pt">${Se(n.blurb)}</td>
1183
- <td style="padding:4pt; font-size:9pt; text-align:right">${r} step${r===1?"":"s"}</td>
1184
- <td style="padding:4pt; font-size:9pt; ${o?"color:#065f46;font-weight:600":"color:#475569"}">${o?"✓ executed":"— not in this run"}</td>
1185
- </tr>`}).join("")}
1186
- </table>
1187
- <p style="margin-top:10pt; font-size:10pt; color:#475569">Each step records a pass/fail/skip + free-form notes + a screenshot of the state being evaluated. Workflow run-records are included in the per-component baseline so subsequent audits can compare keyboard/SR behavior over time.</p>
1188
- </section>`}function fh(e){const a=ma(e,"AA").filter(o=>!ch.has(o.id)),n=a.map(o=>`<tr>
1189
- <td style="padding:3pt; font-family:monospace; font-size:9pt"><code>${Se(o.id)}</code></td>
1190
- <td style="padding:3pt"><strong>${Se(o.title)}</strong> <span style="color:#475569">(${Se(o.level)})</span></td>
1191
- <td style="padding:3pt; color:#475569; font-size:10pt">${Se(o.shortDescription)}</td>
1192
- </tr>`).join("");return`<section>
1193
- <h2>6. WCAG criteria requiring manual review</h2>
1194
- <p>The following ${a.length} WCAG ${e} Level AA criteria have <strong>no automated heuristic</strong> that can produce a defensible pass/fail signal alone. wcagcheckr surfaces these criteria with manual-review prompts via the IGT workflows (Section 5) or via the side-panel "Manual checks needed" list. This list is published verbatim so a reviewer can confirm completeness:</p>
1195
- <table style="border-collapse:collapse; font-size:10pt; margin-top:8pt; width:100%">
1196
- <tr style="border-bottom:1px solid #cbd5e1">
1197
- <th style="text-align:left; padding:4pt">SC</th>
1198
- <th style="text-align:left; padding:4pt">Criterion</th>
1199
- <th style="text-align:left; padding:4pt">Short description</th>
1200
- </tr>
1201
- ${n}
1202
- </table>
1203
- </section>`}function gh(){return`<section>
1204
- <h2>7. Limitations of automated detection</h2>
1205
- <p>wcagcheckr provides high-precision automated coverage where automation can be trusted, and explicit manual prompts where it cannot. The audit framework does <strong>not</strong> claim to detect:</p>
1206
- <ul>
1207
- <li>Cognitive accessibility concerns (plain-language quality, readability, comprehension).</li>
1208
- <li>Sensory accessibility beyond color contrast (icon-only labeling intent, ambient color signaling).</li>
1209
- <li>Time-based media content (caption accuracy, audio-description completeness).</li>
1210
- <li>Content-correctness errors (alt-text accuracy, heading-text relevance) — only structural-presence errors (alt-text missing, heading-order wrong).</li>
1211
- <li>Whole-task accessibility — completion of multi-step user journeys with assistive technology (covered by the IGT keyboard + screen-reader workflows when executed).</li>
1212
- <li>Dynamic content that requires authentication or sequential user input to reach the audit target — the audit applies to the page as rendered at the time of capture.</li>
1213
- </ul>
1214
- <p>Findings produced by this tool support but do not substitute for an expert review.</p>
1215
- </section>`}function mh(){return`<section>
1216
- <h2>8. Audit process (technical specification)</h2>
1217
- <ol>
1218
- <li><strong>Tab attach.</strong> The extension's service worker attaches via <code>chrome.debugger</code> (CDP version 1.3) to the audited tab. The user is shown the standard Chrome "developer is debugging this browser" banner — wcagcheckr does not attempt to hide or work around this banner.</li>
1219
- <li><strong>Page warmup.</strong> The audit waits for <code>document.readyState === 'complete'</code> plus a 500ms post-load buffer to allow late-mounted React/Vue/etc. trees to finish initial render.</li>
1220
- <li><strong>State driving.</strong> For each combination in the state matrix (Section 3), the audit applies the state via CDP (<code>CSS.forcePseudoState</code>, <code>Emulation.setEmulatedMedia</code>, <code>Emulation.setDeviceMetricsOverride</code>, or direct attribute mutation), then waits for layout to settle.</li>
1221
- <li><strong>Screenshot capture.</strong> A viewport screenshot is captured via <code>Page.captureScreenshot</code> at each state for inclusion in evidence bundles.</li>
1222
- <li><strong>axe-core invocation.</strong> The pinned axe-core build is injected via CDP <code>Runtime.evaluate</code> and run against the live DOM. Findings are returned with element selectors, computed accessible names, ARIA contexts, and the state under which they were detected.</li>
1223
- <li><strong>Result aggregation.</strong> Per-state findings are merged. Each unique violation is keyed by (axe ruleId, logical-group selector). Violations appearing in only some states are flagged as state-dependent; violations stable across states are flagged as persistent.</li>
1224
- <li><strong>Baseline diff.</strong> The merged result is diffed against the saved baseline for this component. New violations, persistent violations, and fixed violations are categorized separately.</li>
1225
- <li><strong>Forensic record.</strong> A SHA-256 hash of the canonical audit identity block (componentId, pageUrl, grade, totals, axeVersion, capturedAt, statesAudited) is computed and stored in the local forensic log.</li>
1226
- </ol>
1227
- </section>`}function bh(){return`<section>
1228
- <h2>9. Forensic anchoring (RFC 3161 + ed25519)</h2>
1229
- <p>Audit records can be sealed against a trusted third-party timestamp authority and counter-signed by the wcagcheckr server. When sealed:</p>
1230
- <ul>
1231
- <li>The SHA-256 hash of the audit identity block is submitted to a public RFC 3161 timestamp authority. The TSA returns a signed timestamp token witnessing that the hash existed at the recorded time.</li>
1232
- <li>The wcagcheckr server counter-signs (audit hash + anchored-at + TSA name + product slug + previous-anchor hash) using its ed25519 private key. The corresponding public key is published at <code>api.wcagcheckr.com/v1/products/wcagcheckr/forensic/public-key</code>.</li>
1233
- <li>The seal can be verified offline using only the published TSA certificate and the wcagcheckr public key. No server contact is required at verification time.</li>
1234
- <li>Each new anchor incorporates the hash of the previous anchor in the chain, so removing or backdating an entry would invalidate every later seal.</li>
1235
- </ul>
1236
- <p>Sealed audits are surfaced in the deposition packet (G18) with the full receipt + verification instructions. Public verification page: <a href="https://api.wcagcheckr.com/verify">api.wcagcheckr.com/verify</a>.</p>
1237
- </section>`}function yh(){return`<section>
1238
- <h2>10. References</h2>
1239
- <ul style="font-size:10pt; line-height:1.6">
1240
- <li>W3C, <a href="https://www.w3.org/TR/WCAG21/">Web Content Accessibility Guidelines (WCAG) 2.1</a>, W3C Recommendation 2018-06-05 (updated 2023-09-21).</li>
1241
- <li>W3C, <a href="https://www.w3.org/TR/WCAG22/">Web Content Accessibility Guidelines (WCAG) 2.2</a>, W3C Recommendation 2023-10-05.</li>
1242
- <li>European Telecommunications Standards Institute, <a href="https://www.etsi.org/deliver/etsi_en/301500_301599/301549/03.02.01_60/en_301549v030201p.pdf">EN 301 549 v3.2.1</a>, Accessibility requirements suitable for public procurement of ICT products and services.</li>
1243
- <li>European Union, Directive (EU) <a href="https://eur-lex.europa.eu/eli/dir/2019/882/oj">2019/882</a>, European Accessibility Act, enforceable 2025-06-28.</li>
1244
- <li>Deque Systems, <a href="https://github.com/dequelabs/axe-core/blob/master/doc/API.md">axe-core API documentation</a>, MPL 2.0.</li>
1245
- <li>IETF RFC 3161, <a href="https://datatracker.ietf.org/doc/html/rfc3161">Internet X.509 Public Key Infrastructure Time-Stamp Protocol (TSP)</a>.</li>
1246
- <li>IETF RFC 8032, <a href="https://datatracker.ietf.org/doc/html/rfc8032">Edwards-Curve Digital Signature Algorithm (EdDSA)</a>.</li>
1247
- </ul>
1248
- </section>`}const Bo=[{ref:"1.1.1",title:"Non-text Content",rules:["image-alt","input-image-alt","area-alt","object-alt","svg-img-alt"]},{ref:"1.2.2",title:"Captions (Prerecorded)",rules:["video-caption"]},{ref:"1.3.1",title:"Info and Relationships",rules:["heading-order","list","listitem","definition-list","dlitem","th-has-data-cells","td-headers-attr","aria-required-children","aria-required-parent","label"]},{ref:"1.3.4",title:"Orientation",rules:["css-orientation-lock"]},{ref:"1.3.5",title:"Identify Input Purpose",rules:["autocomplete-valid"]},{ref:"1.4.1",title:"Use of Color",rules:["link-in-text-block"]},{ref:"1.4.2",title:"Audio Control",rules:["no-autoplay-audio"]},{ref:"1.4.3",title:"Contrast (Minimum)",rules:["color-contrast"]},{ref:"1.4.4",title:"Resize Text",rules:["meta-viewport"]},{ref:"2.1.1",title:"Keyboard",rules:["accesskeys"]},{ref:"2.2.2",title:"Pause, Stop, Hide",rules:["blink","marquee","meta-refresh"]},{ref:"2.4.1",title:"Bypass Blocks",rules:["bypass","skip-link"]},{ref:"2.4.2",title:"Page Titled",rules:["document-title"]},{ref:"2.4.4",title:"Link Purpose (In Context)",rules:["link-name"]},{ref:"2.4.6",title:"Headings and Labels",rules:["empty-heading"]},{ref:"3.1.1",title:"Language of Page",rules:["html-has-lang","html-lang-valid"]},{ref:"3.1.2",title:"Language of Parts",rules:["valid-lang"]},{ref:"3.3.1",title:"Error Identification",rules:["aria-input-field-name"]},{ref:"3.3.2",title:"Labels or Instructions",rules:["label-title-only","form-field-multiple-labels"]},{ref:"4.1.1",title:"Parsing",rules:["duplicate-id","duplicate-id-active","duplicate-id-aria"]},{ref:"4.1.2",title:"Name, Role, Value",rules:["aria-allowed-attr","aria-required-attr","aria-roles","aria-valid-attr-value","aria-valid-attr","button-name","select-name","role-img-alt","aria-hidden-body","aria-hidden-focus"]},{ref:"4.1.3",title:"Status Messages",rules:["aria-toggle-field-name"]}];function wh(e={}){var l,p,m,u,g;const t=e.results??[],a=e.manualRuns,n=e.wcagTargetOverride??Nt,o=typeof chrome<"u"&&((m=(p=(l=chrome.runtime)==null?void 0:l.getManifest)==null?void 0:p.call(l))==null?void 0:m.version)||"unknown",r=((u=t[0])==null?void 0:u.axeVersion)??"4.11.4",i=((g=t[0])==null?void 0:g.startedAt)??null,c=sh(t),d=c.size>0;return tt(`<!doctype html>
1249
- <html lang="en">
1250
- <head>
1251
- <meta charset="utf-8" />
1252
- <title>wcagcheckr — Audit Methodology (WCAG ${Se(n)} AA)</title>
1253
- <style>
1254
- *, *::before, *::after { box-sizing: border-box; }
1255
- body { font: 11pt/1.55 -apple-system, system-ui, "Segoe UI", sans-serif; color: #0f172a; max-width: 8in; margin: 0.5in auto; padding: 0 0.25in; }
1256
- h1 { font-size: 22pt; margin: 0 0 4pt; }
1257
- h2 { font-size: 14pt; margin: 24pt 0 8pt; padding-bottom: 4pt; border-bottom: 1px solid #cbd5e1; page-break-after: avoid; }
1258
- .doc-meta { font-size: 10pt; color: #475569; margin-bottom: 12pt; }
1259
- section { page-break-inside: avoid; }
1260
- table { width: 100%; }
1261
- code { background: #f1f5f9; padding: 1pt 4pt; border-radius: 2pt; }
1262
- ul, ol { padding-left: 20pt; }
1263
- ul li, ol li { margin-bottom: 4pt; }
1264
- @media print {
1265
- body { margin: 0; padding: 0.25in; max-width: none; }
1266
- }
1267
- </style>
1268
- </head>
1269
- <body>
1270
- <h1>Audit Methodology — wcagcheckr</h1>
1271
- <p class="doc-meta">Standalone methodology document. Pair with a specific audit's deposition packet (separate file) to demonstrate both how the audit was conducted and what it found.</p>
1272
-
1273
- ${lh(n,o,r,i)}
1274
- ${dh()}
1275
- ${uh()}
1276
- ${hh(d,c)}
1277
- ${ph(a)}
1278
- ${fh(n)}
1279
- ${gh()}
1280
- ${mh()}
1281
- ${bh()}
1282
- ${yh()}
1283
-
1284
- </body>
1285
- </html>`)}const Ho=[{wcagId:"1.1.1",title:"Non-text Content",level:"A",addedIn:"2.0",en301549Clause:"9.1.1.1",section508:"in-scope",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"in-scope"},{wcagId:"1.2.1",title:"Audio-only and Video-only (Prerecorded)",level:"A",addedIn:"2.0",en301549Clause:"9.1.2.1",section508:"in-scope",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"in-scope"},{wcagId:"1.2.2",title:"Captions (Prerecorded)",level:"A",addedIn:"2.0",en301549Clause:"9.1.2.2",section508:"in-scope",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"in-scope"},{wcagId:"1.2.3",title:"Audio Description or Media Alternative (Prerecorded)",level:"A",addedIn:"2.0",en301549Clause:"9.1.2.3",section508:"in-scope",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"in-scope"},{wcagId:"1.2.4",title:"Captions (Live)",level:"AA",addedIn:"2.0",en301549Clause:"9.1.2.4",section508:"in-scope",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"in-scope"},{wcagId:"1.2.5",title:"Audio Description (Prerecorded)",level:"AA",addedIn:"2.0",en301549Clause:"9.1.2.5",section508:"in-scope",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"in-scope"},{wcagId:"1.3.1",title:"Info and Relationships",level:"A",addedIn:"2.0",en301549Clause:"9.1.3.1",section508:"in-scope",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"in-scope"},{wcagId:"1.3.2",title:"Meaningful Sequence",level:"A",addedIn:"2.0",en301549Clause:"9.1.3.2",section508:"in-scope",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"in-scope"},{wcagId:"1.3.3",title:"Sensory Characteristics",level:"A",addedIn:"2.0",en301549Clause:"9.1.3.3",section508:"in-scope",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"in-scope"},{wcagId:"1.3.4",title:"Orientation",level:"AA",addedIn:"2.1",en301549Clause:"9.1.3.4",section508:"not-in-scope-2.1",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"not-in-scope-2.1",notes:"WCAG 2.1 addition. Section 508 Refresh is bound to WCAG 2.0."},{wcagId:"1.3.5",title:"Identify Input Purpose",level:"AA",addedIn:"2.1",en301549Clause:"9.1.3.5",section508:"not-in-scope-2.1",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"not-in-scope-2.1"},{wcagId:"1.4.1",title:"Use of Color",level:"A",addedIn:"2.0",en301549Clause:"9.1.4.1",section508:"in-scope",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"in-scope"},{wcagId:"1.4.2",title:"Audio Control",level:"A",addedIn:"2.0",en301549Clause:"9.1.4.2",section508:"in-scope",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"in-scope"},{wcagId:"1.4.3",title:"Contrast (Minimum)",level:"AA",addedIn:"2.0",en301549Clause:"9.1.4.3",section508:"in-scope",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"in-scope",notes:"The single most-cited criterion in US Title III website complaints."},{wcagId:"1.4.4",title:"Resize Text",level:"AA",addedIn:"2.0",en301549Clause:"9.1.4.4",section508:"in-scope",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"in-scope"},{wcagId:"1.4.5",title:"Images of Text",level:"AA",addedIn:"2.0",en301549Clause:"9.1.4.5",section508:"in-scope",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"in-scope"},{wcagId:"1.4.10",title:"Reflow",level:"AA",addedIn:"2.1",en301549Clause:"9.1.4.10",section508:"not-in-scope-2.1",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"not-in-scope-2.1"},{wcagId:"1.4.11",title:"Non-text Contrast",level:"AA",addedIn:"2.1",en301549Clause:"9.1.4.11",section508:"not-in-scope-2.1",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"not-in-scope-2.1"},{wcagId:"1.4.12",title:"Text Spacing",level:"AA",addedIn:"2.1",en301549Clause:"9.1.4.12",section508:"not-in-scope-2.1",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"not-in-scope-2.1"},{wcagId:"1.4.13",title:"Content on Hover or Focus",level:"AA",addedIn:"2.1",en301549Clause:"9.1.4.13",section508:"not-in-scope-2.1",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"not-in-scope-2.1",notes:"Cited in tooltip + dropdown-related complaints."},{wcagId:"2.1.1",title:"Keyboard",level:"A",addedIn:"2.0",en301549Clause:"9.2.1.1",section508:"in-scope",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"in-scope"},{wcagId:"2.1.2",title:"No Keyboard Trap",level:"A",addedIn:"2.0",en301549Clause:"9.2.1.2",section508:"in-scope",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"in-scope"},{wcagId:"2.1.4",title:"Character Key Shortcuts",level:"A",addedIn:"2.1",en301549Clause:"9.2.1.4",section508:"not-in-scope-2.1",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"not-in-scope-2.1"},{wcagId:"2.2.1",title:"Timing Adjustable",level:"A",addedIn:"2.0",en301549Clause:"9.2.2.1",section508:"in-scope",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"in-scope"},{wcagId:"2.2.2",title:"Pause, Stop, Hide",level:"A",addedIn:"2.0",en301549Clause:"9.2.2.2",section508:"in-scope",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"in-scope"},{wcagId:"2.3.1",title:"Three Flashes or Below Threshold",level:"A",addedIn:"2.0",en301549Clause:"9.2.3.1",section508:"in-scope",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"in-scope"},{wcagId:"2.4.1",title:"Bypass Blocks",level:"A",addedIn:"2.0",en301549Clause:"9.2.4.1",section508:"in-scope",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"in-scope"},{wcagId:"2.4.2",title:"Page Titled",level:"A",addedIn:"2.0",en301549Clause:"9.2.4.2",section508:"in-scope",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"in-scope"},{wcagId:"2.4.3",title:"Focus Order",level:"A",addedIn:"2.0",en301549Clause:"9.2.4.3",section508:"in-scope",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"in-scope"},{wcagId:"2.4.4",title:"Link Purpose (In Context)",level:"A",addedIn:"2.0",en301549Clause:"9.2.4.4",section508:"in-scope",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"in-scope"},{wcagId:"2.4.5",title:"Multiple Ways",level:"AA",addedIn:"2.0",en301549Clause:"9.2.4.5",section508:"in-scope",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"in-scope"},{wcagId:"2.4.6",title:"Headings and Labels",level:"AA",addedIn:"2.0",en301549Clause:"9.2.4.6",section508:"in-scope",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"in-scope"},{wcagId:"2.4.7",title:"Focus Visible",level:"AA",addedIn:"2.0",en301549Clause:"9.2.4.7",section508:"in-scope",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"in-scope"},{wcagId:"2.4.11",title:"Focus Not Obscured (Minimum)",level:"AA",addedIn:"2.2",en301549Clause:"9.2.4.11",section508:"not-in-scope-2.2",adaTitleIII:"gray-area",eaa:"gray-area",aoda:"not-in-scope-2.2",notes:"WCAG 2.2 addition. EN 301 549 may not yet reference; case law not yet settled."},{wcagId:"2.5.1",title:"Pointer Gestures",level:"A",addedIn:"2.1",en301549Clause:"9.2.5.1",section508:"not-in-scope-2.1",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"not-in-scope-2.1"},{wcagId:"2.5.2",title:"Pointer Cancellation",level:"A",addedIn:"2.1",en301549Clause:"9.2.5.2",section508:"not-in-scope-2.1",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"not-in-scope-2.1"},{wcagId:"2.5.3",title:"Label in Name",level:"A",addedIn:"2.1",en301549Clause:"9.2.5.3",section508:"not-in-scope-2.1",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"not-in-scope-2.1"},{wcagId:"2.5.4",title:"Motion Actuation",level:"A",addedIn:"2.1",en301549Clause:"9.2.5.4",section508:"not-in-scope-2.1",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"not-in-scope-2.1"},{wcagId:"2.5.7",title:"Dragging Movements",level:"AA",addedIn:"2.2",en301549Clause:"9.2.5.7",section508:"not-in-scope-2.2",adaTitleIII:"gray-area",eaa:"gray-area",aoda:"not-in-scope-2.2"},{wcagId:"2.5.8",title:"Target Size (Minimum)",level:"AA",addedIn:"2.2",en301549Clause:"9.2.5.8",section508:"not-in-scope-2.2",adaTitleIII:"gray-area",eaa:"gray-area",aoda:"not-in-scope-2.2"},{wcagId:"3.1.1",title:"Language of Page",level:"A",addedIn:"2.0",en301549Clause:"9.3.1.1",section508:"in-scope",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"in-scope"},{wcagId:"3.1.2",title:"Language of Parts",level:"AA",addedIn:"2.0",en301549Clause:"9.3.1.2",section508:"in-scope",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"in-scope"},{wcagId:"3.2.1",title:"On Focus",level:"A",addedIn:"2.0",en301549Clause:"9.3.2.1",section508:"in-scope",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"in-scope"},{wcagId:"3.2.2",title:"On Input",level:"A",addedIn:"2.0",en301549Clause:"9.3.2.2",section508:"in-scope",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"in-scope"},{wcagId:"3.2.3",title:"Consistent Navigation",level:"AA",addedIn:"2.0",en301549Clause:"9.3.2.3",section508:"in-scope",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"in-scope"},{wcagId:"3.2.4",title:"Consistent Identification",level:"AA",addedIn:"2.0",en301549Clause:"9.3.2.4",section508:"in-scope",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"in-scope"},{wcagId:"3.2.6",title:"Consistent Help",level:"A",addedIn:"2.2",en301549Clause:"9.3.2.6",section508:"not-in-scope-2.2",adaTitleIII:"gray-area",eaa:"gray-area",aoda:"not-in-scope-2.2"},{wcagId:"3.3.1",title:"Error Identification",level:"A",addedIn:"2.0",en301549Clause:"9.3.3.1",section508:"in-scope",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"in-scope"},{wcagId:"3.3.2",title:"Labels or Instructions",level:"A",addedIn:"2.0",en301549Clause:"9.3.3.2",section508:"in-scope",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"in-scope"},{wcagId:"3.3.3",title:"Error Suggestion",level:"AA",addedIn:"2.0",en301549Clause:"9.3.3.3",section508:"in-scope",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"in-scope"},{wcagId:"3.3.4",title:"Error Prevention (Legal, Financial, Data)",level:"AA",addedIn:"2.0",en301549Clause:"9.3.3.4",section508:"in-scope",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"in-scope"},{wcagId:"3.3.7",title:"Redundant Entry",level:"A",addedIn:"2.2",en301549Clause:"9.3.3.7",section508:"not-in-scope-2.2",adaTitleIII:"gray-area",eaa:"gray-area",aoda:"not-in-scope-2.2"},{wcagId:"3.3.8",title:"Accessible Authentication (Minimum)",level:"AA",addedIn:"2.2",en301549Clause:"9.3.3.8",section508:"not-in-scope-2.2",adaTitleIII:"gray-area",eaa:"gray-area",aoda:"not-in-scope-2.2"},{wcagId:"4.1.1",title:"Parsing",level:"A",addedIn:"2.0",en301549Clause:"9.4.1.1",section508:"in-scope",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"in-scope",notes:"OBSOLETE in WCAG 2.2 — modern HTML5 parsing handles legacy use cases."},{wcagId:"4.1.2",title:"Name, Role, Value",level:"A",addedIn:"2.0",en301549Clause:"9.4.1.2",section508:"in-scope",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"in-scope",notes:"Second most-cited after 1.4.3 in US Title III complaints."},{wcagId:"4.1.3",title:"Status Messages",level:"AA",addedIn:"2.1",en301549Clause:"9.4.1.3",section508:"not-in-scope-2.1",adaTitleIII:"de-facto-standard",eaa:"in-scope",aoda:"not-in-scope-2.1"}];function Ne(e){return e.replace(/[&<>"']/g,t=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[t])}function vh(e){const t=new Set;for(const a of e)for(const n of a.violations)t.add(n.wcagCriterion);return t}function Te(e,t){return`<span style="display:inline-block; padding:1pt 6pt; border-radius:3pt; font-size:9pt; background:${t}20; border-left:3px solid ${t}; color:#1e293b; font-weight:600">${Ne(e)}</span>`}function Ah(e){switch(e){case"in-scope":return Te("§E207.2 → WCAG 2.0","#059669");case"not-in-scope-2.1":return Te("Not in scope (WCAG 2.1+)","#94a3b8");case"not-in-scope-2.2":return Te("Not in scope (WCAG 2.2)","#94a3b8")}}function kh(e){switch(e){case"de-facto-standard":return Te("De facto via WCAG AA","#059669");case"gray-area":return Te("Gray area (new SC)","#f59e0b")}}function xh(e){switch(e){case"in-scope":return Te("In scope","#059669");case"product-related":return Te("Product-related","#0ea5e9");case"gray-area":return Te("Gray area","#f59e0b")}}function Ih(e){switch(e){case"in-scope":return Te("In scope (WCAG 2.0)","#059669");case"not-in-scope-2.1":return Te("Not in scope (2.1+)","#94a3b8");case"not-in-scope-2.2":return Te("Not in scope (2.2)","#94a3b8")}}function Sh(e={}){var d;const t=e.wcagTargetOverride??Nt,a=e.results?vh(e.results):new Set,n=(((d=e.results)==null?void 0:d.length)??0)>0,o=new Set(ma(t,"AA").map(l=>l.id)),r=Ho.map(l=>{const p=a.has(l.wcagId),m=o.has(l.wcagId),u=p?"background:#fee2e2;":m?"":"background:#f8fafc;",g=p?'<div style="font-size:9pt; color:#b91c1c; font-weight:700; margin-top:2pt">⚠ Violated in this audit</div>':"";return`<tr style="${u}">
1286
- <td style="padding:5pt 6pt; vertical-align:top; border-bottom:1px solid #e2e8f0">
1287
- <div style="font-family:monospace; font-weight:600">${Ne(l.wcagId)}</div>
1288
- <div style="font-size:9pt; color:#475569">${Ne(l.level)} · added ${Ne(l.addedIn)}</div>
1289
- </td>
1290
- <td style="padding:5pt 6pt; vertical-align:top; border-bottom:1px solid #e2e8f0">
1291
- <div style="font-weight:600">${Ne(l.title)}</div>
1292
- ${g}
1293
- ${l.notes?`<div style="font-size:9pt; color:#475569; margin-top:3pt; font-style:italic">${Ne(l.notes)}</div>`:""}
1294
- </td>
1295
- <td style="padding:5pt 6pt; vertical-align:top; border-bottom:1px solid #e2e8f0; font-family:monospace; font-size:9pt">
1296
- ${l.en301549Clause?`§${Ne(l.en301549Clause)}`:'<span style="color:#475569">—</span>'}
1297
- </td>
1298
- <td style="padding:5pt 6pt; vertical-align:top; border-bottom:1px solid #e2e8f0">${Ah(l.section508)}</td>
1299
- <td style="padding:5pt 6pt; vertical-align:top; border-bottom:1px solid #e2e8f0">${kh(l.adaTitleIII)}</td>
1300
- <td style="padding:5pt 6pt; vertical-align:top; border-bottom:1px solid #e2e8f0">${xh(l.eaa)}</td>
1301
- <td style="padding:5pt 6pt; vertical-align:top; border-bottom:1px solid #e2e8f0">${Ih(l.aoda)}</td>
1302
- </tr>`}).join(""),i=Ho.filter(l=>a.has(l.wcagId)).length,c=n?`<p class="doc-meta">Annotated with ${i} ${i===1?"criterion":"criteria"} violated in the underlying audit (rows highlighted red).</p>`:'<p class="doc-meta">Standalone reference. Pair with a deposition packet to annotate which criteria were violated in a specific audit.</p>';return tt(`<!doctype html>
1303
- <html lang="en">
1304
- <head>
1305
- <meta charset="utf-8" />
1306
- <title>wcagcheckr — Conformance Crosswalk (WCAG ${Ne(t)} AA → EN / 508 / ADA / EAA / AODA)</title>
1307
- <style>
1308
- *, *::before, *::after { box-sizing: border-box; }
1309
- body { font: 10pt/1.5 -apple-system, system-ui, "Segoe UI", sans-serif; color: #0f172a; max-width: 11in; margin: 0.4in auto; padding: 0 0.25in; }
1310
- h1 { font-size: 20pt; margin: 0 0 4pt; }
1311
- h2 { font-size: 13pt; margin: 18pt 0 8pt; padding-bottom: 4pt; border-bottom: 1px solid #cbd5e1; page-break-after: avoid; }
1312
- .doc-meta { font-size: 10pt; color: #475569; margin: 0 0 14pt; }
1313
- table { border-collapse: collapse; width: 100%; font-size: 10pt; margin-top: 10pt; }
1314
- th { text-align: left; padding: 6pt; background: #f1f5f9; border-bottom: 2px solid #cbd5e1; font-weight: 600; }
1315
- thead { display: table-header-group; }
1316
- tr { page-break-inside: avoid; }
1317
- code { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 9pt; }
1318
- .legend { background: #f8fafc; border: 1px solid #e2e8f0; padding: 10pt 14pt; border-radius: 4pt; margin: 14pt 0; }
1319
- .legend dt { font-weight: 600; margin-top: 6pt; }
1320
- .legend dd { margin: 2pt 0 0 0; font-size: 9pt; color: #475569; }
1321
- @media print {
1322
- body { margin: 0; padding: 0.25in; max-width: none; }
1323
- }
1324
- </style>
1325
- </head>
1326
- <body>
1327
- <h1>Conformance Crosswalk</h1>
1328
- ${c}
1329
-
1330
- <section class="legend">
1331
- <h2 style="margin-top:0; border:none; padding:0">How to read this document</h2>
1332
- <p style="margin:0 0 8pt 0">Each row is a single WCAG success criterion. The columns show how that criterion maps onto five other accessibility frameworks. The same finding cited as a WCAG violation in one jurisdiction may need to be re-cited under a different framework's clause in another.</p>
1333
- <dl style="margin:0">
1334
- <dt>WCAG ${Ne(t)} AA</dt>
1335
- <dd>The dotted SC number (e.g. <code>1.4.3</code>), level, and the WCAG version that introduced it. Criteria de-emphasized when out of scope for the audit's target version (${Ne(t)}).</dd>
1336
- <dt>EN 301 549 v3.2.1</dt>
1337
- <dd>European procurement standard. The <code>§9.x.y.z</code> clause is the direct cross-reference. Cited in EAA-related disputes and EU public-procurement complaints.</dd>
1338
- <dt>Section 508 (36 CFR 1194)</dt>
1339
- <dd>US federal standard, post-2017 Refresh. Incorporates WCAG 2.0 A + AA by reference (E207.2). Criteria added in WCAG 2.1+ are not currently in scope.</dd>
1340
- <dt>ADA Title III</dt>
1341
- <dd>US private-sector. DOJ has not adopted formal technical standards; courts and consent decrees have converged on WCAG AA as the de facto standard. 2.2 criteria are "gray area" — too recent for settled case law.</dd>
1342
- <dt>EAA (Directive 2019/882)</dt>
1343
- <dd>EU. Enforceable since 28 June 2025 for private-sector websites + apps + e-commerce in EU markets. References WCAG via EN 301 549.</dd>
1344
- <dt>AODA (Ontario, Canada)</dt>
1345
- <dd>Integrated Accessibility Standards Regulation (O. Reg. 191/11) Part II. Adopts WCAG 2.0 AA for public-sector + designated private-sector organizations with > 50 employees.</dd>
1346
- </dl>
1347
- </section>
1348
-
1349
- <table>
1350
- <thead>
1351
- <tr>
1352
- <th>WCAG SC</th>
1353
- <th>Criterion</th>
1354
- <th>EN 301 549</th>
1355
- <th>Section 508</th>
1356
- <th>ADA Title III</th>
1357
- <th>EAA</th>
1358
- <th>AODA</th>
1359
- </tr>
1360
- </thead>
1361
- <tbody>
1362
- ${r}
1363
- </tbody>
1364
- </table>
1365
-
1366
- <section style="margin-top:24pt; font-size:9pt; color:#475569; border-top:1px solid #e2e8f0; padding-top:10pt">
1367
- <p><strong>Note on mappings.</strong> Cross-framework mappings shown here are based on published cross-references (ETSI EN 301 549 v3.2.1 Annex A; US Access Board Section 508 Refresh 2017 §E207.2; AODA IASR O. Reg. 191/11 Part II Information &amp; Communications) and on DOJ Title III consent decrees and settlements citing WCAG AA. Mappings are not legal advice. Edge cases (WCAG 2.2 criteria, motion + pointer criteria, accessible-authentication) reflect current case-law uncertainty and may shift as courts and standards bodies update their references.</p>
1368
- <p><strong>References:</strong> <a href="https://www.w3.org/TR/WCAG21/">WCAG 2.1</a> · <a href="https://www.w3.org/TR/WCAG22/">WCAG 2.2</a> · <a href="https://www.etsi.org/deliver/etsi_en/301500_301599/301549/03.02.01_60/en_301549v030201p.pdf">EN 301 549 v3.2.1</a> · <a href="https://www.access-board.gov/ict/">US Access Board ICT Refresh</a> · <a href="https://eur-lex.europa.eu/eli/dir/2019/882/oj">EU Directive 2019/882 (EAA)</a> · <a href="https://www.ontario.ca/laws/regulation/110191">O. Reg. 191/11 IASR</a>.</p>
1369
- </section>
1370
-
1371
- </body>
1372
- </html>`)}const qo={critical:4,serious:3,moderate:2,minor:1},Li={critical:"🔴",serious:"🟠",moderate:"🟡",minor:"⚪"};function Ch(e,t){return e.length>t?e.slice(0,t-1)+"…":e}function $h(e){const t=e.split(" > ");return t[t.length-1]??e}function Th(e,t,a){const n=lt[t.ruleId],o=[];return o.push(`## Ticket ${e} — ${Li[t.impact]} [${t.impact}] ${t.ruleId}`),o.push(""),o.push(`**WCAG:** ${t.wcagCriterion} ${t.wcagLevel}`),o.push(`**Impact:** ${t.impact}`),o.push(`**Selector:** \`${t.target.selector}\``),o.push(`**Page:** ${a}`),t._instances>1&&o.push(`**Instances:** ${t._instances} (this rule fires on ${t._instances} elements; fixing the root cause will resolve all)`),o.push(""),o.push("### What failed"),o.push(""),o.push(t.description),o.push(""),t.target.accessibleName&&(o.push(`Element's current accessible name: \`${t.target.accessibleName}\``),o.push("")),o.push("### Element"),o.push(""),o.push("```html"),o.push(t.target.outerHTML),o.push("```"),o.push(""),t.target.failureSummary&&t.target.failureSummary.trim().length>0&&(o.push("### What axe-core checked"),o.push(""),o.push("```"),o.push(t.target.failureSummary.trim()),o.push("```"),o.push("")),n&&(o.push("### How to fix"),o.push(""),o.push(n.summary),o.push(""),n.snippet&&(o.push("```"+(n.snippetLang??"")),o.push(n.snippet),o.push("```"),o.push(""))),o.push("### Reference"),o.push(""),o.push(`- WCAG ${t.wcagCriterion}: https://www.w3.org/WAI/WCAG21/Understanding/`),o.push(`- axe-core rule: ${t.helpUrl}`),o.push(""),o.join(`
1373
- `)}function Eh(e){var d;const t=e.results.flatMap(l=>l.violations),a=new Map;for(const l of t){const p=Fe(l.ruleId,l.target.selector),m=a.get(p);m?m._instances+=1:a.set(p,{...l,_instances:1})}const n=Array.from(a.values()).sort((l,p)=>{const m=qo[p.impact]-qo[l.impact];return m!==0?m:l.ruleId.localeCompare(p.ruleId)}),o=e.pageUrlOverride??((d=e.results[0])==null?void 0:d.pageUrl)??"(unknown)",r=new Date().toISOString(),i=[];i.push("# Accessibility Remediation Tickets"),i.push(""),i.push(`**Generated:** ${r}`),i.push(`**Source URL:** ${o}`),i.push(`**Total tickets:** ${n.length}`),i.push(`**Total violations (with duplicates):** ${t.length}`),i.push(""),i.push("Each ticket below is a self-contained, copy-pasteable section suitable for "),i.push("filing into Linear, Jira, Asana, Trello, GitHub Issues, or any tool that "),i.push("accepts markdown. Tickets are de-duped by logical group, so a list-grid "),i.push("with 50 instances of the same issue produces one ticket noting the count."),i.push(""),i.push("## Index"),i.push(""),i.push("| # | Impact | Rule | WCAG | Element |"),i.push("|---|--------|------|------|---------|"),n.forEach((l,p)=>{const m=Ch($h(l.target.selector),32).replace(/\|/g,"\\|");i.push(`| ${p+1} | ${Li[l.impact]} ${l.impact} | \`${l.ruleId}\` | ${l.wcagCriterion} ${l.wcagLevel} | \`${m}\` |`)}),i.push(""),i.push("---"),i.push("");const c=n.map((l,p)=>Th(p+1,l,o)).join(`
1374
- ---
1375
-
1376
- `);return n.length===0?[i.join(`
1377
- `),"_No violations to file. Run an audit first._"].join(`
1378
- `):i.join(`
1379
- `)+c}const zo={critical:4,serious:3,moderate:2,minor:1};function ue(e){return e.replace(/[&<>"']/g,t=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[t])}function Rh(e,t,a){const n=a??new Set,o=e.flatMap(i=>i.violations).filter(i=>!n.has(i.matchKey)),r=new Map;for(const i of o){const c=`${i.ruleId}::${i.target.selector}::${i.wcagCriterion}`,d=r.get(c);if(d){d._instances+=1;continue}r.set(c,{...i,_instances:1})}return Array.from(r.values()).sort((i,c)=>{const d=zo[c.impact]-zo[i.impact];return d!==0?d:i.ruleId.localeCompare(c.ruleId)}).slice(0,t)}function Oh(e,t){switch(e){case"A":return"No critical or serious WCAG violations detected. The audited page is in good shape; manual review still recommended for criteria automation cannot fully evaluate.";case"B":{const a=(t==null?void 0:t.moderate)??0;return t!=null&&t.cappedByCoverage&&a===0?'No critical, serious, or moderate violations detected — but not every applicable WCAG 2.1 AA criterion has been affirmatively evaluated yet. The exact criteria still needing your judgment are listed in the "Criteria still needing your judgment" section below. Each can be marked pass / N/A / fail in the Coverage gaps panel under the grade in the side panel; once every blocker has a verdict, the grade lifts to A.':t!=null&&t.cappedByCoverage&&a>0?`${a} moderate WCAG finding${a===1?"":"s"} detected, AND the audit hasn't yet affirmatively evaluated every applicable AA criterion. The "Top risks" section lists the moderate finding${a===1?"":"s"}; the "Criteria still needing your judgment" section lists the coverage gaps. Both must close before any public conformance claim.`:`${a||"Several"} moderate WCAG finding${a===1?"":"s"} — no critical or serious violations, but areas worth attention before public claims of full conformance.`}case"C":return"At least one serious WCAG violation detected. These typically affect users of assistive technology and should be addressed before the next public release.";case"D":return"Multiple serious WCAG violations detected. The page in its current state is likely to fail real-world testing by users with disabilities and creates measurable legal exposure.";case"F":return"At least one critical WCAG violation detected. Critical-impact issues block users of assistive technology from core functionality and require immediate remediation."}}function Mh(e,t,a=0,n=[]){const o=[];if(e.length===0){if(a>0){const i=n.slice(0,3).join(", "),c=a>3?` (+${a-3} more listed below)`:"";return o.push(`Open the side panel, expand the "${a} criteri${a===1?"on":"a"} need your judgment to lift this to A" panel under the grade, and mark each one pass / N/A / fail with a note. Start with: WCAG ${i}${c}.`),o.push("Schedule a recurring audit (Schedules tab) so any regression is caught within a single cadence window."),o.push("Publish an EAA / WAD accessibility statement (Delta tab → export menu) once coverage is complete."),o}return o.push("Run an IGT manual workflow (keyboard, screen reader) to cover criteria automation cannot fully evaluate."),o.push("Schedule a recurring audit (Schedules tab) so any regression is caught within a single cadence window."),o.push("Publish an EAA / WAD accessibility statement (Delta tab → export menu)."),o}const r=e[0];return o.push(`Resolve the ${r.impact}-impact ${r.ruleId} violation (WCAG ${r.wcagCriterion}). ${r._instances} instance${r._instances===1?"":"s"} on the page; the developer's full findings document has the exact selectors + recommended fixes.`),o.push(t==="F"||t==="D"?"File the top 3 findings into your issue tracker (Delta tab supports GitHub, Jira, GitLab, and Azure DevOps with one click). Block release until critical/serious findings are remediated.":"Add the surfaced findings to the next sprint as accessibility-debt tickets."),o.push("Schedule the page for recurring audit (Schedules tab) so any new violation is caught at the next cadence and surfaces via email or webhook alert."),o}function Dh(e,t={}){const a=e.flatMap(T=>T.violations),n=et(a,t.manualRuns,e,t.acknowledgedMatchKeys,t.interactiveAuditResults,t.walkthroughAcks,t.humanCriterionVerdicts,ft(e),t.incompleteResolutions),o=n.score,r=n.combined,i={critical:o.totals.critical,serious:o.totals.serious,moderate:o.totals.moderate,minor:o.totals.minor},c=Rh(e,3,t.acknowledgedMatchKeys),d=new Map(ma("2.1","AA").map(T=>[T.id,T.title])),l=new Map,p={untested:0,inconclusive:1,failing:2};function m(T,I){for(const D of T){const S=l.get(D);(!S||p[I]>p[S.state])&&l.set(D,{id:D,title:d.get(D)??"(criterion title unavailable)",state:I})}}o.coverage&&(m(o.coverage.untestedCriteria,"untested"),m(o.coverage.inconclusiveCriteria,"inconclusive"),m(o.coverage.failingCriteria,"failing"));const u=Array.from(l.values()).sort((T,I)=>T.id.localeCompare(I.id,void 0,{numeric:!0})),g=Mh(c,r,u.length,u.map(T=>T.id)),h=e[0],f=(h==null?void 0:h.pageUrl)??"(unknown)",w=(h==null?void 0:h.axeVersion)??"4.11.4",b=e.length,k=t.asOfDateOverride??(h==null?void 0:h.startedAt)??new Date().toISOString(),v={A:"#059669",B:"#16a34a",C:"#f59e0b",D:"#ea580c",F:"#dc2626"},s=t.orgName?`<p class="org">Prepared for <strong>${ue(t.orgName)}</strong></p>`:"",x=t.logoUrl?`<img src="${ue(t.logoUrl)}" alt="${ue(t.orgName??"Logo")}" class="logo" />`:"",$=c.length===0?'<p class="empty">No findings surfaced. Manual review still recommended for criteria automation cannot evaluate.</p>':`<ol class="risks">${c.map(T=>`<li>
1380
- <div class="risk-head">
1381
- <span class="risk-impact risk-${ue(T.impact)}">${ue(T.impact)}</span>
1382
- <code>${ue(T.ruleId)}</code>
1383
- <span class="risk-wcag">WCAG ${ue(T.wcagCriterion)} (${ue(T.wcagLevel)})</span>
1384
- </div>
1385
- <p class="risk-desc">${ue(T.description)}</p>
1386
- <p class="risk-meta">${T._instances} instance${T._instances===1?"":"s"} · selector <code>${ue(T.target.selector)}</code></p>
1387
- </li>`).join("")}</ol>`,A=`<ol class="steps">${g.map(T=>`<li>${ue(T)}</li>`).join("")}</ol>`,C={untested:{label:"no evidence",bg:"#64748b"},inconclusive:{label:"inconclusive",bg:"#a16207"},failing:{label:"failing",bg:"#dc2626"}},F=u.length===0?"":`<section>
1388
- <h2>Criteria still needing your judgment <span style="color:#64748b;font-weight:400;font-size:11pt">(${u.length})</span></h2>
1389
- <p class="risk-meta" style="margin:0 0 8pt">These WCAG 2.1 AA criteria are blocking an A grade — each is currently failing, inconclusive, or not yet affirmatively evaluated (see the status on each below). Open the side panel, expand the "${u.length} criteri${u.length===1?"on":"a"} need your judgment to lift this to A" panel under the grade, and resolve each: fix the failing ones, and record a pass / N/A verdict for the rest.</p>
1390
- <ol class="risks">${u.map(T=>{const I=C[T.state];return`<li>
1391
- <div class="risk-head">
1392
- <span class="risk-impact" style="background:${I.bg}">${ue(I.label)}</span>
1393
- <code>WCAG ${ue(T.id)}</code>
1394
- <span class="risk-wcag">${ue(T.title)}</span>
1395
- </div>
1396
- </li>`}).join("")}</ol>
1397
- </section>`;return tt(`<!doctype html>
1398
- <html lang="en">
1399
- <head>
1400
- <meta charset="utf-8" />
1401
- <title>Accessibility Executive Report${t.orgName?" — "+ue(t.orgName):""}</title>
1402
- <style>
1403
- *, *::before, *::after { box-sizing: border-box; }
1404
- body { font: 11pt/1.55 -apple-system, system-ui, "Segoe UI", Roboto, sans-serif; color: #0f172a; max-width: 7.5in; margin: 0.5in auto; padding: 0 0.25in; }
1405
- header { display: flex; align-items: flex-start; justify-content: space-between; gap: 16pt; padding-bottom: 14pt; border-bottom: 2px solid #0f172a; margin-bottom: 18pt; }
1406
- header h1 { font-size: 22pt; margin: 0; }
1407
- header .meta { color: #475569; font-size: 10pt; margin: 4pt 0 0; }
1408
- header .org { color: #475569; font-size: 10pt; margin: 8pt 0 0; }
1409
- .logo { max-height: 60pt; max-width: 200pt; object-fit: contain; }
1410
- .hero { display: flex; align-items: center; gap: 18pt; background: #f8fafc; border: 1px solid #cbd5e1; border-radius: 6pt; padding: 16pt; margin-bottom: 18pt; }
1411
- .grade { font-size: 48pt; font-weight: 800; color: white; width: 72pt; height: 72pt; border-radius: 8pt; display: flex; align-items: center; justify-content: center; flex-shrink: 0; }
1412
- .hero-text { font-size: 11pt; line-height: 1.55; }
1413
- .hero-text strong { display: block; font-size: 13pt; margin-bottom: 4pt; }
1414
- h2 { font-size: 13pt; margin: 18pt 0 8pt; padding-bottom: 4pt; border-bottom: 1px solid #cbd5e1; page-break-after: avoid; }
1415
- section { page-break-inside: avoid; margin-bottom: 14pt; }
1416
- .tested-grid { display: grid; grid-template-columns: repeat(2, 1fr); gap: 6pt 16pt; font-size: 10pt; }
1417
- .tested-grid dt { font-weight: 600; color: #475569; }
1418
- .tested-grid dd { margin: 0; }
1419
- .tested-grid code { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 9pt; background: #f1f5f9; padding: 1pt 4pt; border-radius: 2pt; }
1420
- ol.risks { list-style: none; padding: 0; margin: 0; }
1421
- ol.risks li { padding: 8pt 0; border-bottom: 1px solid #e2e8f0; }
1422
- ol.risks li:last-child { border-bottom: none; }
1423
- .risk-head { display: flex; align-items: center; gap: 8pt; flex-wrap: wrap; margin-bottom: 4pt; }
1424
- .risk-impact { display: inline-block; padding: 1pt 6pt; border-radius: 3pt; font-size: 9pt; font-weight: 600; text-transform: lowercase; color: white; }
1425
- .risk-critical { background: #dc2626; }
1426
- .risk-serious { background: #c2410c; }
1427
- .risk-moderate { background: #b45309; }
1428
- .risk-minor { background: #94a3b8; }
1429
- .risk-wcag { color: #475569; font-size: 9pt; }
1430
- .risk-desc { margin: 0 0 4pt; }
1431
- .risk-meta { margin: 0; font-size: 9pt; color: #475569; }
1432
- .risk-meta code { font-family: ui-monospace, monospace; font-size: 8pt; background: #f1f5f9; padding: 0 4pt; }
1433
- ol.steps { padding-left: 18pt; margin: 0; }
1434
- ol.steps li { margin: 6pt 0; }
1435
- .empty { color: #475569; font-style: italic; }
1436
- footer { margin-top: 24pt; padding-top: 10pt; border-top: 1px solid #cbd5e1; font-size: 9pt; color: #64748b; }
1437
- @media print {
1438
- body { margin: 0; padding: 0.4in; max-width: none; }
1439
- .hero { box-shadow: none; }
1440
- }
1441
- </style>
1442
- </head>
1443
- <body>
1444
- <header>
1445
- <div>
1446
- <h1>Accessibility Executive Report</h1>
1447
- <p class="meta">As of ${ue(k)}</p>
1448
- ${s}
1449
- </div>
1450
- ${x}
1451
- </header>
1452
-
1453
- <section class="hero" aria-label="Audit summary">
1454
- <div class="grade" style="background:${v[r]}">${r}</div>
1455
- <div class="hero-text">
1456
- <strong>${i.critical} critical · ${i.serious} serious · ${i.moderate} moderate · ${i.minor} minor</strong>
1457
- ${ue(Oh(r,{moderate:i.moderate,cappedByCoverage:o.caps.cappedAtBByCoverage}))}
1458
- </div>
1459
- </section>
1460
-
1461
- <section>
1462
- <h2>What was tested</h2>
1463
- <dl class="tested-grid">
1464
- <dt>Page URL</dt><dd><code>${ue(f)}</code></dd>
1465
- <dt>Audit engine</dt><dd>axe-core <code>${ue(w)}</code> + wcagcheckr DOM analyzers</dd>
1466
- <dt>States audited</dt><dd>${b} (pseudo-states × themes × directions × breakpoints)</dd>
1467
- <dt>WCAG target</dt><dd>WCAG 2.1 Level AA (configurable; see methodology document)</dd>
1468
- </dl>
1469
- </section>
1470
-
1471
- <section>
1472
- <h2>Top risks</h2>
1473
- ${$}
1474
- </section>
1475
-
1476
- ${F}
1477
-
1478
- <section>
1479
- <h2>Recommended next steps</h2>
1480
- ${A}
1481
- </section>
1482
-
1483
- <footer>
1484
- This is a one-page executive summary. The developer's full findings document, the deposition packet (forensic-anchored), the audit methodology document, and the cross-jurisdiction conformance crosswalk are available as separate exports.
1485
- </footer>
1486
- </body>
1487
- </html>`)}function Nh(e){var t;return((t=gs.find(a=>a.id===e))==null?void 0:t.title)??e}const Pi={"attested-conforms":"Conforms (operator-attested)","attested-na":"N/A (operator-attested)","not-addressed":"Not addressed"};function Fi(e){const t=new Map(e.map(a=>[a.criterionId,a]));return $a.map(a=>{const n=t.get(a.id);return{id:a.id,title:Nh(a.id),kind:(n==null?void 0:n.kind)??"not-addressed",note:(n==null?void 0:n.note)??"",operator:(n==null?void 0:n.operator)??"",date:n!=null&&n.timestamp?n.timestamp.slice(0,10):""}})}function Lh(e){const t=Fi(e),a=[];a.push("## Operator spot-check attestations (self-attested — NOT tool-verified · an A requires all confirmed)"),a.push(""),a.push(`These content-meaning criteria cannot be verified by automation (caption accuracy, audio-description quality, alt-text meaning, sensory cues). Each row below is the operator's OWN statement on what they manually checked; wcagcheckr did not verify it. "Not addressed" means the operator did not record a manual check — it is shown honestly, not as a pass.`),a.push(""),a.push("| WCAG | Criterion | Operator attestation | What they checked | Operator · Date |"),a.push("|---|---|---|---|---|");for(const n of t){const o=n.note?n.note.replace(/\|/g,"\\|"):"—",r=n.operator?`${n.operator} · ${n.date}`:"—";a.push(`| ${n.id} | ${n.title} | ${Pi[n.kind]} | ${o} | ${r} |`)}return a.push(""),a.join(`
1488
- `)}function rf(e,t){return`<section style="margin:18px 0;"><h2 style="font-size:16px;margin:0 0 6px;">Operator spot-check attestations</h2><p style="margin:0 0 10px;font-size:12px;color:#475569;line-height:1.5;">Self-attested by the operator — <strong>NOT verified by wcagcheckr</strong>. These content-meaning criteria can't be verified by automation, so an <strong>A</strong> is issued only once the operator has confirmed every one as conforming or not-applicable; any <strong>"Not addressed"</strong> holds the grade at B and is shown honestly, not as a pass.</p><table style="border-collapse:collapse;width:100%;font-size:12px;"><thead><tr style="text-align:left;background:#f1f5f9;"><th style="padding:6px 8px;">WCAG</th><th style="padding:6px 8px;">Criterion</th><th style="padding:6px 8px;">Operator attestation</th><th style="padding:6px 8px;">What they checked</th><th style="padding:6px 8px;">Operator · Date</th></tr></thead><tbody>${Fi(e).map(o=>{const r=o.note?t(o.note):'<span style="color:#94a3b8">—</span>',i=o.operator?`${t(o.operator)} · ${t(o.date)}`:'<span style="color:#94a3b8">—</span>',c=o.kind==="attested-conforms"?"#059669":o.kind==="attested-na"?"#64748b":"#b45309";return`<tr><td style="padding:6px 8px;border-bottom:1px solid #e2e8f0;font-family:ui-monospace,monospace;">${t(o.id)}</td><td style="padding:6px 8px;border-bottom:1px solid #e2e8f0;">${t(o.title)}</td><td style="padding:6px 8px;border-bottom:1px solid #e2e8f0;color:${c};font-weight:600;">${t(Pi[o.kind])}</td><td style="padding:6px 8px;border-bottom:1px solid #e2e8f0;">${r}</td><td style="padding:6px 8px;border-bottom:1px solid #e2e8f0;white-space:nowrap;">${i}</td></tr>`}).join("")}</tbody></table></section>`}const Ph=["image-alt","input-image-alt","area-alt","object-alt","role-img-alt","svg-img-alt","alt-text","1.1.1","1.2.1","1.2.2","1.2.3","1.2.4","1.2.5","caption","transcript","audio-desc","1.3.2","meaningful-sequence","reading-order","2.4.6","2.4.4","2.4.9","heading-not-descriptive","generic-link-text","link-in-text-block","identical-links-same-purpose","sensory","color-only","wall-of-text","language-mismatch","uncertain"];function Ko(e){if(!e)return"ai-fixable";const t=e.toLowerCase();return Ph.some(a=>t.includes(a))?"human-verify":"ai-fixable"}const Fh=["## How to act on this report","","Each finding is tagged **[AI-fixable]** or **[Human-verify]**:","","- **[AI-fixable]** — the fix is mechanical/code-level (accessible names, label association, ARIA roles/states, contrast, lang, titles, landmarks, heading ORDER). Fix these directly in the code.",`- **[Human-verify]** — the fix needs judgment of content or meaning you cannot confirm from markup (alt-text accuracy, caption/transcript correctness, meaningful reading sequence, whether heading/link wording is genuinely descriptive). You MAY draft a suggestion, but hand it back as a short, plain-language "check this, and here's why" — never jargon homework, and never silently mark it done.`,"",'If a finding lacks the detail needed to act (no selector / no element / no colors), say so explicitly as **"blocked: detail missing from this report"** — that is a report gap to flag, not a failure on your part. Do not guess or hallucinate the missing detail.',""].join(`
1489
- `);function _h(e){if(!e)return null;const t=e.match(/<[a-zA-Z][^>]*>/);return t?t[0]:null}function Yo(e,t){return new RegExp(`\\s${t}(\\s|=|>|/)`,"i").test(e)}function ze(e,t){return e.endsWith("/>")?`${e.slice(0,-2).trimEnd()} ${t} />`:`${e.slice(0,-1).trimEnd()} ${t}>`}function Uh(e){return(e.target.tagName||"").toLowerCase()}const Wh=new Set(["image-alt","role-img-alt","svg-img-alt","area-alt","input-image-alt","object-alt"]),Gh=new Set(["html-has-lang","html-lang-valid","html-xml-lang-mismatch","valid-lang"]);function _i(e,t={}){var o,r,i,c,d,l,p,m,u,g;const a=e.ruleId,n=_h(e.target.outerHTML);if(a==="color-contrast"||a==="color-contrast-enhanced"){const h=e.target.cascadeChain;if(!(!!(h!=null&&h.color||h!=null&&h.backgroundColor)||!!t.suggestedColors))return null;const w=((o=h==null?void 0:h.color)==null?void 0:o.ruleSelector)||((r=h==null?void 0:h.backgroundColor)==null?void 0:r.ruleSelector)||e.target.selector,b=((i=h==null?void 0:h.color)==null?void 0:i.authored)??((c=h==null?void 0:h.color)==null?void 0:c.rendered)??"currentColor",k=((d=h==null?void 0:h.backgroundColor)==null?void 0:d.authored)??((l=h==null?void 0:h.backgroundColor)==null?void 0:l.rendered)??"transparent",v=(p=h==null?void 0:h.color)!=null&&p.authored&&h.color.rendered&&h.color.authored!==h.color.rendered?` /* renders ${h.color.rendered} */`:"",s=a==="color-contrast-enhanced"?"7:1 (normal) / 4.5:1 (large)":"4.5:1 (normal) / 3:1 (large)",x=((m=t.suggestedColors)==null?void 0:m.foreground)??`{{a foreground that reaches ${s} on ${k}}}`,$=((u=t.suggestedColors)==null?void 0:u.background)??k,A=`${w} {
1490
- color: ${b};${v}
1491
- background-color: ${k};
1492
- }`,C=`${w} {
1493
- color: ${x};
1494
- background-color: ${$};
1495
- }`,F=(g=t.suggestedColors)!=null&&g.foreground?"Colors above already pass WCAG AA for this pair — verify they fit the design.":`Pick a color that reaches ${s} contrast; check :hover / :focus too.`;return{current:A,suggested:C,note:F,lang:"css"}}if(!n)return null;if(Wh.has(a))return Yo(n,"alt")&&a==="image-alt"?null:{current:n,suggested:ze(n,a==="svg-img-alt"?'role="img" aria-label="{{what the graphic conveys}}"':'alt="{{what the image conveys; use alt=\\"\\" if purely decorative}}"'),note:`Describe the image's MEANING in context, not its appearance. Decorative images take an empty alt="".`,lang:"html"};if(a==="button-name"||a==="input-button-name")return{current:n,suggested:ze(n,'aria-label="{{the action this control performs}}"'),note:"Prefer visible button text; use aria-label only when the control is icon-only.",lang:"html"};if(a==="link-name")return{current:n,suggested:ze(n,'aria-label="{{where this link goes}}"'),note:"Prefer descriptive visible link text; aria-label is the fallback for icon/image links.",lang:"html"};if(a==="aria-command-name"||a==="aria-input-field-name"||a==="aria-toggle-field-name")return{current:n,suggested:ze(n,'aria-label="{{accessible name for this control}}"'),note:"An aria-labelledby pointing at visible text is preferable when such text exists.",lang:"html"};if(a==="label"||a==="select-name"){const h=e.target.attrId,f=n,w=h?`<label for="${h}">{{visible field label}}</label>
1496
- ${n}`:ze(n,'aria-label="{{visible field label}}"');return{current:f,suggested:w,note:h?"A programmatically-associated <label for> is preferred over aria-label.":"Add an id to the field and a <label for>, or use aria-label as shown.",lang:"html"}}if(a==="frame-title")return{current:n,suggested:ze(n,'title="{{purpose of this frame}}"'),lang:"html"};if(Gh.has(a)&&Uh(e)==="html"){const h=Yo(n,"lang")?n.replace(/lang="[^"]*"/i,'lang="en"'):ze(n,'lang="en"');return{current:n,suggested:h,note:`Set lang to the page's actual primary language (BCP-47), e.g. "en", "es", "fr".`,lang:"html"}}if(a==="meta-viewport"){const h=n.replace(/\s*,?\s*user-scalable\s*=\s*(no|0)/i,"").replace(/\s*,?\s*maximum-scale\s*=\s*(1(\.0)?|0?\.\d+)/i,"");return{current:n,suggested:h,note:"Remove user-scalable=no and any maximum-scale < 2 so users can zoom (WCAG 1.4.4).",lang:"html"}}return a==="tabindex"?{current:n,suggested:n.replace(/tabindex="[1-9]\d*"/i,'tabindex="0"'),note:"Positive tabindex hijacks the tab sequence; use 0 (or restructure the DOM order).",lang:"html"}:null}const tn=Z("ai-compliance-summarizer");async function Ui(e,t){if(!t.enabled)return null;const a=fe(t);if(!a.ok)return tn.debug(`AI client unavailable: ${a.reason}`),null;const n=_e(t.costCapUsd);if(!n.canCharge())return null;try{const o=await a.client.generateExecutiveSummary(e);return n.recordCharge(o.costUsd),!o.lead&&!o.body?(tn.debug("AI summary returned empty"),null):o}catch(o){return tn.warn("compliance-summary generation failed",o),null}}async function Vh(){const e=await chrome.storage.local.get("aiConfig");return ke(e.aiConfig)}function sf(){return $e("AI_COMPLIANCE_SUMMARY_REQUEST",async e=>{const t=await pe();if(!he(t,"aiComplianceSummary"))return{type:"AI_COMPLIANCE_SUMMARY_RESPONSE",summary:null,unavailableReason:"AI compliance summary is not available on your current plan."};const a=await Vh();if(!a.enabled)return{type:"AI_COMPLIANCE_SUMMARY_RESPONSE",summary:null,unavailableReason:"AI augmentation is disabled in Settings → AI augmentation."};if(!a.apiKey)return{type:"AI_COMPLIANCE_SUMMARY_RESPONSE",summary:null,unavailableReason:"No AI API key configured."};const n=await Ui(e.input,a);return{type:"AI_COMPLIANCE_SUMMARY_RESPONSE",summary:n,unavailableReason:n?void 0:"AI summary generation returned no result."}})}const Ie="wcagcheckr";function Ee(){try{return chrome.runtime.getManifest().version}catch{return"0.0.0"}}function qe(e){const t=e[0];return t?t.pageUrl?t.pageUrl:t.scope&&/^https?:\/\//.test(t.scope)?t.scope:t.scope?`(selector: ${t.scope})`:"unknown":"unknown"}function Wi(e,t){return{schemaVersion:1,generatedAt:new Date().toISOString(),tool:{name:Ie,version:Ee()},results:e,delta:t}}function Jo(e){return e==="critical"||e==="serious"?"error":e==="moderate"?"warning":"note"}function Gi(e,t){const a=(t?t.new:e.flatMap(c=>c.violations)).filter(c=>!c.needsReview),n=new Set,o=[];for(const c of a)n.has(c.ruleId)||(n.add(c.ruleId),o.push({id:c.ruleId,shortDescription:{text:c.description||c.ruleId},helpUri:c.helpUrl||void 0,defaultConfiguration:{level:Jo(c.impact)},properties:{tags:[c.wcagCriterion,`wcag-${c.wcagLevel}`]}}));const r=qe(e),i=a.map(c=>({ruleId:c.ruleId,level:Jo(c.impact),message:{text:`${c.description}`+(c.target.failureSummary?`
1497
-
1498
- ${c.target.failureSummary}`:"")},locations:[{physicalLocation:{artifactLocation:{uri:r&&/^https?:\/\//.test(r)?`${r}#${c.target.selector}`:c.target.selector?`selector://${c.target.selector}`:"unknown"},region:{snippet:{text:c.target.outerHTML}}},logicalLocations:[{name:c.componentId,kind:"module"}]}],properties:{componentId:c.componentId,wcagCriterion:c.wcagCriterion,wcagLevel:c.wcagLevel,pseudoState:c.currentState.pseudoState,theme:c.currentState.theme,direction:c.currentState.direction,breakpoint:c.currentState.breakpoint.id,detectedAt:c.detectedAt}}));return{$schema:"https://json.schemastore.org/sarif-2.1.0.json",version:"2.1.0",runs:[{tool:{driver:{name:Ie,version:Ee(),informationUri:"https://wcagcheckr.com",rules:o}},results:i}]}}function Vi(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}function Ke(e){return Vi(e).replace(/\n/g,"&#10;").replace(/\r/g,"&#13;")}function ji(e,t){const a=!!t,n=l=>(a?l.violations.filter(p=>t.new.some(m=>m.matchKey===p.matchKey)):l.violations).filter(p=>!p.needsReview),o=e.reduce((l,p)=>l+Math.max(1,p.violations.length),0),r=e.reduce((l,p)=>l+n(p).length,0),i=e.reduce((l,p)=>l+p.durationMs,0)/1e3,c=[];c.push('<?xml version="1.0" encoding="UTF-8"?>');const d=`${Ie} — ${qe(e)}`;c.push(`<testsuites name="${Ke(d)}" tests="${o}" failures="${r}" time="${i.toFixed(3)}">`);for(const l of e){const p=`${l.state.pseudoState}_${l.state.theme}_${l.state.direction}_${l.state.breakpoint.id}`,m=`${l.componentId}::${p}`,u=n(l),g=Math.max(1,l.violations.length);if(c.push(` <testsuite name="${Ke(m)}" tests="${g}" failures="${u.length}" time="${(l.durationMs/1e3).toFixed(3)}">`),l.violations.length===0)c.push(` <testcase classname="${Ke(m)}" name="no-violations" time="${(l.durationMs/1e3).toFixed(3)}" />`);else for(const h of l.violations){const f=u.some(v=>v.matchKey===h.matchKey),w=`classname="${Ke(m)}" name="${Ke(h.ruleId)}" time="0"`;if(!f){c.push(` <testcase ${w} />`);continue}const b=`${h.impact} - ${h.description}`,k=`Selector: ${h.target.selector}
1499
- WCAG: ${h.wcagCriterion} (${h.wcagLevel})
1500
- State: ${p}
1501
- `+(h.helpUrl?`Help: ${h.helpUrl}
1502
- `:"")+(h.target.failureSummary?`
1503
- ${h.target.failureSummary}`:"");c.push(` <testcase ${w}>`),c.push(` <failure message="${Ke(b)}" type="${Ke(h.ruleId)}">${Vi(k)}</failure>`),c.push(" </testcase>")}c.push(" </testsuite>")}return c.push("</testsuites>"),c.join(`
1504
- `)}function E(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function jh(e,t,a){if(e.length===0&&t.length===0)return"";const n=new Map;for(const i of a)n.set(`${i.criterionId}::${i.pageUrl}`,i);const o=e.map((i,c)=>`
1505
- <tr>
1506
- <td>${c+1}</td>
1507
- <td><span class="impact impact-${E(i.impact)}">${E(i.impact)}</span></td>
1508
- <td><code>${E(i.criterionId)}</code></td>
1509
- <td>${E(i.verdict.toUpperCase())}</td>
1510
- <td>${E(i.reasoning)}</td>
1511
- <td><code class="sel">${E(i.pageUrl)}</code></td>
1512
- </tr>`).join(""),r=t.map((i,c)=>{const d=n.get(`${i.criterionId}::${i.pageUrl}`),l=(d==null?void 0:d.note)??"(note missing)",p=d!=null&&d.acknowledgedAt?new Date(d.acknowledgedAt).toLocaleString():"(timestamp missing)";return`
1513
- <tr>
1514
- <td>${c+1}</td>
1515
- <td><code>${E(i.criterionId)}</code></td>
1516
- <td>AI: ${E(i.verdict.toUpperCase())} → ✓ Human verified</td>
1517
- <td>${E(l)}</td>
1518
- <td>${E(p)}</td>
1519
- <td><code class="sel">${E(i.pageUrl)}</code></td>
1520
- </tr>`}).join("");return`
1521
- <h2 id="walkthroughs">3a. AI walkthrough findings</h2>
1522
- <p>The wcagcheckr extension runs interactive AI walkthroughs for criteria that aren't fully decidable from static DOM (Focus Order 2.4.3, No Keyboard Trap 2.1.2, Focus Visible 2.4.7, Meaningful Sequence 1.3.2, Non-text Contrast 1.4.11, Label in Name 2.5.3). FAIL and UNCERTAIN verdicts are listed below, separated into "still open" (blocking grade) and "human verified" (the auditor manually confirmed the criterion passes, with the note logged inline for chain-of-custody).</p>
1523
- ${e.length===0?"<p><em>No open walkthrough findings — every AI walkthrough verdict is either PASS or has been human-acknowledged.</em></p>":`<h3 style="margin-top:12pt">Still open (${e.length})</h3>
1524
- <table>
1525
- <thead>
1526
- <tr><th>#</th><th>Impact</th><th>Criterion</th><th>AI verdict</th><th>AI reasoning</th><th>Page</th></tr>
1527
- </thead>
1528
- <tbody>${o}</tbody>
1529
- </table>`}
1530
- ${t.length===0?"":`<h3 style="margin-top:12pt">Human verified (${t.length})</h3>
1531
- <p style="font-size:10pt; color:#475569">Each row records an AI walkthrough that flagged a potential issue, followed by the human auditor's manual verification. The note is the verifier's explanation of how they confirmed the criterion passes; the timestamp is when the verification was recorded.</p>
1532
- <table>
1533
- <thead>
1534
- <tr><th>#</th><th>Criterion</th><th>Chain</th><th>Verification note</th><th>Recorded at</th><th>Page</th></tr>
1535
- </thead>
1536
- <tbody>${r}</tbody>
1537
- </table>`}`}function Kn(e,t,a){var k,v,s,x,$;const n=((k=e[0])==null?void 0:k.componentId)??"unknown",o=qe(e),r=a??e.reduce((A,C)=>A+C.durationMs,0),i=e.flatMap(A=>A.violations),c=new Map;for(const A of i){const C=`${A.ruleId}::${A.target.selector}`,F=`:${A.currentState.pseudoState} · ${A.currentState.theme} · ${A.currentState.direction}`,T=c.get(C);if(T){T._states.includes(F)||T._states.push(F);continue}c.set(C,{...A,_states:[F]})}const d=Array.from(c.values()),l={critical:[],serious:[],moderate:[],minor:[]};for(const A of d)(l[A.impact]??l.moderate).push(A);const p=new Set(((v=t==null?void 0:t.new)==null?void 0:v.map(A=>`${A.ruleId}::${A.target.selector}`))??[]),m=new Set(((s=t==null?void 0:t.persistent)==null?void 0:s.map(A=>`${A.ruleId}::${A.target.selector}`))??[]),u=new Set(((x=t==null?void 0:t.fixed)==null?void 0:x.map(A=>`${A.ruleId}::${A.target.selector}`))??[]);let g=0,h=0;for(const A of d){const C=`${A.ruleId}::${A.target.selector}`;m.has(C)?h++:p.has(C)&&g++}let f=0;for(const A of u)!m.has(A)&&!p.has(A)&&f++;const w=A=>{const C=p.has(`${A.ruleId}::${A.target.selector}`);return`
1538
- <article class="violation impact-${E(A.impact)}${C?" is-new":""}">
1539
- <header>
1540
- <span class="rule">${E(A.ruleId)}</span>
1541
- <span class="impact">${E(A.impact)}</span>
1542
- <span class="wcag">${E(A.wcagCriterion)} ${E(A.wcagLevel)}</span>
1543
- ${C?'<span class="new-badge">NEW vs baseline</span>':""}
1544
- </header>
1545
- <p class="desc">${E(A.description)}</p>
1546
- <p class="meta"><strong>Selector:</strong> <code>${E(A.target.selector)}</code></p>
1547
- <p class="meta"><strong>Found in state(s):</strong> ${E(A._states.join(", "))}</p>
1548
- <pre class="snippet"><code>${E(A.target.outerHTML)}</code></pre>
1549
- ${A.helpUrl?`<p class="help"><a href="${E(A.helpUrl)}">Reference: ${E(A.helpUrl)}</a></p>`:""}
1550
- </article>`},b=(A,C)=>C.length===0?"":`
1551
- <section class="impact-section impact-${E(A)}">
1552
- <h2>${E(A[0].toUpperCase()+A.slice(1))} (${C.length})</h2>
1553
- ${C.map(w).join("")}
1554
- </section>`;return tt(`<!doctype html>
1555
- <html lang="en">
1556
- <head>
1557
- <meta charset="utf-8" />
1558
- <title>Accessibility audit — ${E(n)}</title>
1559
- <style>
1560
- *, *::before, *::after { box-sizing: border-box; }
1561
- body {
1562
- font: 12pt/1.5 -apple-system, system-ui, "Segoe UI", sans-serif;
1563
- color: #0f172a;
1564
- max-width: 7.5in;
1565
- margin: 0.5in auto;
1566
- padding: 0 0.25in;
1567
- }
1568
- h1 { font-size: 22pt; margin: 0 0 6pt; }
1569
- h2 { font-size: 14pt; margin: 18pt 0 8pt; padding-bottom: 4pt; border-bottom: 1px solid #cbd5e1; }
1570
- header.report-header { margin-bottom: 18pt; }
1571
- .summary { font-size: 11pt; color: #475569; margin-bottom: 12pt; }
1572
- .summary span { margin-right: 12pt; }
1573
- .violation {
1574
- border-left: 4px solid #cbd5e1;
1575
- background: #f8fafc;
1576
- padding: 10pt 12pt;
1577
- margin: 8pt 0;
1578
- page-break-inside: avoid;
1579
- }
1580
- .violation.impact-critical { border-left-color: #dc2626; }
1581
- .violation.impact-serious { border-left-color: #ea580c; }
1582
- .violation.impact-moderate { border-left-color: #ca8a04; }
1583
- .violation.impact-minor { border-left-color: #2563eb; }
1584
- .violation.is-new { background: #fef2f2; }
1585
- .violation .new-badge { font-size: 9pt; padding: 1pt 6pt; border-radius: 3pt; background: #dc2626; color: white; text-transform: uppercase; letter-spacing: 0.04em; }
1586
- .violation header { display: flex; gap: 8pt; align-items: baseline; margin-bottom: 4pt; }
1587
- .violation .rule { font-family: "SF Mono", Menlo, monospace; font-weight: 600; font-size: 11pt; }
1588
- .violation .impact { font-size: 9pt; padding: 1pt 6pt; border-radius: 3pt; background: #e2e8f0; text-transform: uppercase; letter-spacing: 0.04em; }
1589
- .violation .wcag { font-size: 10pt; color: #475569; }
1590
- .violation .desc { margin: 0 0 4pt; }
1591
- .violation .meta { font-size: 10pt; color: #475569; margin: 2pt 0; }
1592
- .violation code { font-family: "SF Mono", Menlo, monospace; font-size: 10pt; }
1593
- .violation .snippet {
1594
- background: #fff; border: 1px solid #cbd5e1; border-radius: 3pt;
1595
- padding: 6pt 8pt; overflow-x: auto;
1596
- font-family: "SF Mono", Menlo, monospace; font-size: 10pt; white-space: pre-wrap;
1597
- }
1598
- .violation .help { font-size: 10pt; }
1599
- footer { margin-top: 24pt; padding-top: 8pt; border-top: 1px solid #cbd5e1; font-size: 9pt; color: #64748b; }
1600
- @media print {
1601
- body { margin: 0; max-width: none; }
1602
- h2 { page-break-after: avoid; }
1603
- .violation { break-inside: avoid; }
1604
- }
1605
- </style>
1606
- </head>
1607
- <body>
1608
- <header class="report-header">
1609
- <h1>Accessibility audit report</h1>
1610
- <p class="summary" style="font-size: 11pt; word-break: break-all;">
1611
- <strong>URL audited:</strong> <code>${E(o)}</code>
1612
- </p>
1613
- <p class="summary">
1614
- <span><strong>Component:</strong> <code>${E(n)}</code></span>
1615
- <span><strong>Date:</strong> ${E(new Date().toLocaleString())}</span>
1616
- <span><strong>axe-core:</strong> ${E((($=e[0])==null?void 0:$.axeVersion)??"n/a")}</span>
1617
- </p>
1618
- <p class="summary">
1619
- <span><strong>States audited:</strong> ${e.length}</span>
1620
- <span><strong>Unique violations:</strong> ${d.length}</span>
1621
- <span><strong>Total violation instances:</strong> ${i.length}</span>
1622
- <span><strong>Audit duration:</strong> ${(r/1e3).toFixed(1)}s</span>
1623
- </p>
1624
- ${t!=null&&t.matrixMismatchWarning?`
1625
- <p class="summary" style="background: #fef3c7; border: 1px solid #f59e0b; padding: 8pt 10pt; border-radius: 3pt;">
1626
- ⚠ ${E(t.matrixMismatchWarning)}
1627
- </p>
1628
- `:""}
1629
- ${t&&t.baselineSnapshotMeta?`
1630
- <p class="summary"><strong>Unique-violation deltas (rule + selector pairs):</strong></p>
1631
- <p class="summary">
1632
- <span style="color: #dc2626;"><strong>NEW:</strong> ${g}</span>
1633
- <span><strong>Persistent:</strong> ${h}</span>
1634
- <span style="color: #15803d;"><strong>Fixed since baseline:</strong> ${f}</span>
1635
- </p>
1636
- <p class="summary" style="font-size: 9pt; color: #64748b;">
1637
- Per-state-instance deltas (each state×rule×selector combination): ${t.newCount} new instances · ${t.persistentCount} persistent · ${t.fixedCount} fixed. The unique-violation counts above are usually what you want to track; instance counts inflate when the matrix size changes.
1638
- </p>
1639
- `:t?'<p class="summary"><span style="color: #64748b;">No baseline accepted yet — every violation is unrated.</span></p>':""}
1640
- <p style="font-size: 10pt; color: #64748b;">
1641
- Tip: use your browser's print dialog (Ctrl+P / Cmd+P) → "Save as PDF" to produce a PDF file.
1642
- </p>
1643
- </header>
1644
- ${b("critical",l.critical)}
1645
- ${b("serious",l.serious)}
1646
- ${b("moderate",l.moderate)}
1647
- ${b("minor",l.minor)}
1648
- <footer>
1649
- Generated by ${Ie} v${Ee()}. Full audit — all detected violations included, deduped across states. Items flagged "NEW vs baseline" were not present in the most-recent accepted baseline.
1650
- </footer>
1651
- </body>
1652
- </html>`)}const Bi=[{ref:"1.1.1",title:"Non-text Content",level:"A",rules:["image-alt","input-image-alt","area-alt","object-alt","svg-img-alt"]},{ref:"1.2.1",title:"Audio-only and Video-only (Prerecorded)",level:"A",rules:["wcc-audio-needs-transcript","wcc-clean::1.2.1"]},{ref:"1.2.2",title:"Captions (Prerecorded)",level:"A",rules:["video-caption","wcc-video-no-captions","wcc-clean::1.2.2"]},{ref:"1.2.3",title:"Audio Description or Media Alternative (Prerecorded)",level:"A",rules:["wcc-video-no-audio-desc-or-alt","wcc-clean::1.2.3"]},{ref:"1.2.4",title:"Captions (Live)",level:"AA",rules:["wcc-clean::1.2.4"]},{ref:"1.2.5",title:"Audio Description (Prerecorded)",level:"AA",rules:["wcc-video-no-descriptions","wcc-clean::1.2.5"]},{ref:"1.3.1",title:"Info and Relationships",level:"A",rules:["heading-order","list","listitem","definition-list","dlitem","th-has-data-cells","td-headers-attr","aria-required-children","aria-required-parent","label","aria-pattern-tablist-no-tabs","aria-pattern-tab-no-controls","aria-pattern-tab-broken-controls","aria-pattern-tab-wrong-target-role","aria-pattern-combobox-no-popup","aria-pattern-combobox-broken-popup","aria-pattern-combobox-wrong-popup-role"]},{ref:"1.3.2",title:"Meaningful Sequence",level:"A",rules:[]},{ref:"1.3.3",title:"Sensory Characteristics",level:"A",rules:["wcc-sensory-only-directive","wcc-clean::1.3.3"]},{ref:"1.3.4",title:"Orientation",level:"AA",rules:["css-orientation-lock","wcc-orientation-locked-content","wcc-clean::1.3.4"]},{ref:"1.3.5",title:"Identify Input Purpose",level:"AA",rules:["autocomplete-valid"]},{ref:"1.4.1",title:"Use of Color",level:"A",rules:["link-in-text-block"]},{ref:"1.4.2",title:"Audio Control",level:"A",rules:["no-autoplay-audio","wcc-autoplay-no-controls","wcc-clean::1.4.2"]},{ref:"1.4.3",title:"Contrast (Minimum)",level:"AA",rules:["color-contrast"]},{ref:"1.4.4",title:"Resize Text",level:"AA",rules:["meta-viewport","wcc-viewport-locks-zoom","wcc-clean::1.4.4"]},{ref:"1.4.5",title:"Images of Text",level:"AA",rules:["wcc-image-of-text-candidate","wcc-svg-text-as-content","wcc-clean::1.4.5"]},{ref:"1.4.10",title:"Reflow",level:"AA",rules:["wcc-reflow-horizontal-scroll","wcc-reflow-clean"]},{ref:"1.4.11",title:"Non-text Contrast",level:"AA",rules:[]},{ref:"1.4.12",title:"Text Spacing",level:"AA",rules:["wcc-text-spacing-clip-risk","wcc-clean::1.4.12"]},{ref:"1.4.13",title:"Content on Hover or Focus",level:"AA",rules:["wcc-title-tooltip-no-persistence","wcc-clean::1.4.13"]},{ref:"2.1.1",title:"Keyboard",level:"A",rules:["nested-interactive","frame-focusable-content"]},{ref:"2.1.2",title:"No Keyboard Trap",level:"A",rules:[]},{ref:"2.1.4",title:"Character Key Shortcuts",level:"A",rules:["wcc-inline-key-handler","wcc-clean::2.1.4"]},{ref:"2.2.1",title:"Timing Adjustable",level:"A",rules:["meta-refresh","wcc-meta-refresh","wcc-timer-mutates-content","wcc-clean::2.2.1"]},{ref:"2.2.2",title:"Pause, Stop, Hide",level:"A",rules:["blink","marquee","wcc-marquee-blink","wcc-autoplay-no-controls","wcc-long-infinite-animation","wcc-clean::2.2.2"]},{ref:"2.3.1",title:"Three Flashes or Below Threshold",level:"A",rules:["wcc-flash-risk","wcc-clean::2.3.1"]},{ref:"2.4.1",title:"Bypass Blocks",level:"A",rules:["bypass"]},{ref:"2.4.2",title:"Page Titled",level:"A",rules:["document-title"]},{ref:"2.4.3",title:"Focus Order",level:"A",rules:["tabindex"]},{ref:"2.4.4",title:"Link Purpose (In Context)",level:"A",rules:["link-name"]},{ref:"2.4.5",title:"Multiple Ways",level:"AA",rules:["wcc-only-one-way-to-find","wcc-clean::2.4.5"]},{ref:"2.4.6",title:"Headings and Labels",level:"AA",rules:["empty-heading","empty-table-header"]},{ref:"2.4.7",title:"Focus Visible",level:"AA",rules:[]},{ref:"2.4.11",title:"Focus Not Obscured (Minimum)",level:"AA",rules:["wcc-sticky-may-obscure-focus","wcc-clean::2.4.11"]},{ref:"2.5.1",title:"Pointer Gestures",level:"A",rules:["wcc-gesture-no-alternative","wcc-clean::2.5.1"]},{ref:"2.5.2",title:"Pointer Cancellation",level:"A",rules:["wcc-down-event-fires-action","wcc-clean::2.5.2"]},{ref:"2.5.3",title:"Label in Name",level:"A",rules:["label-content-name-mismatch"]},{ref:"2.5.4",title:"Motion Actuation",level:"A",rules:["wcc-motion-actuation-no-alt","wcc-clean::2.5.4"]},{ref:"2.5.7",title:"Dragging Movements",level:"AA",rules:["wcc-drag-no-alternative","wcc-clean::2.5.7"]},{ref:"2.5.8",title:"Target Size (Minimum)",level:"AA",rules:["target-size"]},{ref:"3.1.1",title:"Language of Page",level:"A",rules:["html-has-lang","html-lang-valid"]},{ref:"3.1.2",title:"Language of Parts",level:"AA",rules:["valid-lang"]},{ref:"3.2.1",title:"On Focus",level:"A",rules:["wcc-onfocus-context-change","wcc-clean::3.2.1"]},{ref:"3.2.2",title:"On Input",level:"A",rules:["wcc-oninput-context-change","wcc-clean::3.2.2"]},{ref:"3.2.3",title:"Consistent Navigation",level:"AA",rules:["wcc-consistent-navigation"]},{ref:"3.2.4",title:"Consistent Identification",level:"AA",rules:["wcc-consistent-identification"]},{ref:"3.2.6",title:"Consistent Help",level:"A",rules:["wcc-consistent-help"]},{ref:"3.3.1",title:"Error Identification",level:"A",rules:["wcc-form-no-aria-error-pattern","wcc-clean::3.3.1"]},{ref:"3.3.2",title:"Labels or Instructions",level:"A",rules:["label","form-field-multiple-labels","select-name"]},{ref:"3.3.3",title:"Error Suggestion",level:"AA",rules:["wcc-form-no-error-suggestion","wcc-clean::3.3.3"]},{ref:"3.3.4",title:"Error Prevention (Legal, Financial, Data)",level:"AA",rules:["wcc-commit-form-no-review-step","wcc-clean::3.3.4"]},{ref:"3.3.7",title:"Redundant Entry",level:"A",rules:["wcc-redundant-entry","wcc-clean::3.3.7"]},{ref:"3.3.8",title:"Accessible Authentication (Minimum)",level:"AA",rules:["wcc-cognitive-auth-challenge","wcc-clean::3.3.8"]},{ref:"4.1.1",title:"Parsing",level:"A",rules:["duplicate-id","duplicate-id-aria","duplicate-id-active","wcc-clean::4.1.1"]},{ref:"4.1.2",title:"Name, Role, Value",level:"A",rules:["button-name","aria-required-attr","aria-allowed-attr","aria-roles","aria-valid-attr","aria-valid-attr-value","aria-input-field-name","aria-toggle-field-name","select-name","input-button-name","aria-pattern-dialog-no-name","aria-pattern-dialog-no-modal-attr","aria-pattern-tabs-no-selected","aria-pattern-tabs-multiple-selected","aria-pattern-combobox-no-expanded","aria-pattern-combobox-invalid-expanded","aria-pattern-combobox-broken-activedescendant"]},{ref:"4.1.3",title:"Status Messages",level:"AA",rules:["wcc-no-live-regions","wcc-clean::4.1.3"]}];function Hi(e,t,a,n,o,r){if(o==="pass")return{conformance:"Supports",hits:["Human verified: pass"]};if(o==="na")return{conformance:"Not Applicable",hits:["Human verified: not applicable"]};if(o==="fail")return{conformance:"Partially Supports",hits:["Human verified: fail"]};if((r??[]).some(m=>m.verdict==="fail"&&(m.wcagCriterion===e.ref||e.rules.includes(m.ruleId))))return{conformance:"Partially Supports",hits:["Pixel-contrast sampler determined a contrast failure"]};const c=n==null?void 0:n.find(m=>m.criterionId===e.ref);if(e.rules.length===0)return c?c.verdict==="pass"?{conformance:"Supports",hits:[]}:c.verdict==="fail"?{conformance:"Partially Supports",hits:["AI walkthrough verdict: fail"]}:{conformance:"Not Evaluated",hits:[]}:{conformance:"Not Applicable",hits:[]};const d=e.rules.filter(m=>t.has(m));if(d.length>0)return{conformance:"Partially Supports",hits:d};if((c==null?void 0:c.verdict)==="fail")return{conformance:"Partially Supports",hits:["AI walkthrough verdict: fail"]};const l=e.rules.some(m=>a.has(m)),p=(c==null?void 0:c.verdict)==="pass";return l||p?{conformance:"Supports",hits:[]}:{conformance:"Not Evaluated",hits:[]}}function qi(e,t,a,n,o,r){var w,b;const i=((w=e[0])==null?void 0:w.componentId)??"unknown",c=qe(e);let d;try{d=new URL(c).host||i}catch{d=i}const l=n??new Set,p=e.flatMap(k=>k.violations).filter(k=>!l.has(k.matchKey)),m=new Set(p.map(k=>k.ruleId)),u=new Map;for(const k of o??[])u.set(k.criterionId,k.verdict);const g=new Set(m);for(const k of e){const v=k.axeRulesEvaluated;if(v){for(const s of v.passed)g.add(s.ruleId);for(const s of v.inapplicable)g.add(s.ruleId);for(const s of v.incomplete)g.add(s.ruleId)}}const h=k=>{const{conformance:v,hits:s}=Hi(k,m,g,a,u.get(k.ref),r);return`
1653
- <tr class="${v==="Supports"?"supports":v==="Partially Supports"?"partial":v==="Not Evaluated"?"not-evaluated":"na"}">
1654
- <td class="ref">${E(k.ref)}</td>
1655
- <td class="title">${E(k.title)} <span class="level">(${k.level})</span></td>
1656
- <td class="conf">${v}</td>
1657
- <td class="notes">${s.length>0?`Auto-detected violations of: ${s.map($=>`<code>${E($)}</code>`).join(", ")}. Manual review recommended.`:v==="Not Applicable"?"No automated rule maps to this criterion. Manual evaluation required.":"No automated violations detected. Manual confirmation recommended for full claim."}</td>
1658
- </tr>`},f=k=>{const v=Bi.filter(s=>s.level===k).map(h).join("");return`
1659
- <h2>WCAG 2.1 Level ${k}</h2>
1660
- <table>
1661
- <thead>
1662
- <tr><th>Criterion</th><th>Title</th><th>Conformance</th><th>Notes</th></tr>
1663
- </thead>
1664
- <tbody>${v}</tbody>
1665
- </table>`};return tt(`<!doctype html>
1666
- <html lang="en">
1667
- <head>
1668
- <meta charset="utf-8" />
1669
- <title>VPAT — ${E(d)}</title>
1670
- <style>
1671
- body { font: 11pt/1.5 -apple-system, system-ui, sans-serif; color: #0f172a; max-width: 8in; margin: 0.5in auto; padding: 0 0.25in; }
1672
- h1 { font-size: 18pt; }
1673
- h2 { font-size: 13pt; margin-top: 20pt; padding-bottom: 4pt; border-bottom: 1px solid #cbd5e1; }
1674
- .meta { font-size: 10pt; color: #475569; }
1675
- .preamble { background: #fef3c7; border: 1px solid #f59e0b; padding: 8pt 10pt; border-radius: 3pt; font-size: 10pt; margin: 12pt 0; }
1676
- table { width: 100%; border-collapse: collapse; margin: 6pt 0 12pt; font-size: 10pt; }
1677
- th, td { border: 1px solid #cbd5e1; padding: 5pt 7pt; text-align: left; vertical-align: top; }
1678
- th { background: #f1f5f9; }
1679
- td.ref { font-family: "SF Mono", Menlo, monospace; white-space: nowrap; }
1680
- td.conf { font-weight: 600; }
1681
- tr.supports td.conf { color: #15803d; }
1682
- tr.partial td.conf { color: #b45309; }
1683
- tr.na td.conf { color: #64748b; }
1684
- tr.not-evaluated td.conf { color: #b45309; background: #fef3c7; }
1685
- .level { color: #475569; font-weight: 400; }
1686
- code { font-family: "SF Mono", Menlo, monospace; font-size: 9pt; background: #f1f5f9; padding: 0 3pt; }
1687
- @media print { body { margin: 0; } table, tr { page-break-inside: avoid; } }
1688
- </style>
1689
- </head>
1690
- <body>
1691
- <h1>Voluntary Product Accessibility Template (VPAT 2.5)</h1>
1692
- <p class="meta"><strong>Product:</strong> ${E(d)}</p>
1693
- <p class="meta" style="word-break: break-all;"><strong>URL evaluated:</strong> <code>${E(c)}</code></p>
1694
- <p class="meta"><strong>Date:</strong> ${E(new Date().toLocaleString())}</p>
1695
- <p class="meta"><strong>Evaluation method:</strong> Automated audit via wcagcheckr (axe-core ${E(((b=e[0])==null?void 0:b.axeVersion)??"n/a")}) across ${e.length} configured states.</p>
1696
- <div class="preamble">
1697
- <strong>Auto-generated draft.</strong> This VPAT was produced automatically from automated test
1698
- results. Conformance values reflect what automated testing can detect — they are not a complete
1699
- accessibility claim. Manual review by qualified accessibility evaluators is required before
1700
- using this document for procurement, contracting, or legal purposes. Criteria with no
1701
- automated rule are marked "Not Applicable" until manually evaluated.
1702
- </div>
1703
- ${f("A")}
1704
- ${f("AA")}
1705
- <footer style="margin-top: 24pt; padding-top: 8pt; border-top: 1px solid #cbd5e1; font-size: 9pt; color: #64748b;">
1706
- Generated by ${Ie} v${Ee()}. Conformance assessed against all violations detected during the audit (not delta-filtered).
1707
- </footer>
1708
- </body>
1709
- </html>`)}function Bh(e){const t=[],a=e.target.outerHTML;if(e.ruleId==="image-alt"||e.ruleId==="input-image-alt"||e.ruleId==="area-alt"||e.ruleId==="svg-img-alt"||e.ruleId==="object-alt"){const n=/\bsrc\s*=\s*"([^"]+)"|\bsrc\s*=\s*'([^']+)'/i.exec(a);n&&t.push({label:"Image source",value:`\`${n[1]??n[2]}\` — if you have vision capability, view this image and propose alt text. Use \`alt=""\` if it's decorative.`});const o=/<title>([^<]+)<\/title>/i.exec(a);o&&t.push({label:"Inline SVG <title>",value:o[1]})}if(e.ruleId==="button-name"||e.ruleId==="empty-button"||e.ruleId==="input-button-name"){const n=/\baria-label\s*=\s*"([^"]+)"/i.exec(a);n&&t.push({label:"Existing aria-label",value:n[1]});const o=/<svg[^>]*>[\s\S]*?<title>([^<]+)<\/title>/i.exec(a);o&&t.push({label:"SVG <title> inside",value:o[1]});const r=/<(?:i|svg|span)[^>]*class\s*=\s*"([^"]*(?:icon|fa-|material-icon)[^"]*)"/i.exec(a);r&&t.push({label:"Icon class hint",value:`\`${r[1]}\` — name suggests intent`})}if(e.ruleId==="link-name"||e.ruleId==="empty-link"){const n=/\bhref\s*=\s*"([^"]+)"|\bhref\s*=\s*'([^']+)'/i.exec(a);n&&t.push({label:"Link href",value:`\`${n[1]??n[2]}\` — destination may suggest the right link text`});const o=/\baria-label\s*=\s*"([^"]+)"/i.exec(a);o&&t.push({label:"Existing aria-label",value:o[1]})}if(e.ruleId==="label"||e.ruleId==="select-name"||e.ruleId==="aria-input-field-name"){const n=/\bname\s*=\s*"([^"]+)"|\bname\s*=\s*'([^']+)'/i.exec(a);n&&t.push({label:"Field name attribute",value:`\`${n[1]??n[2]}\` — often hints at the intended label`});const o=/\bplaceholder\s*=\s*"([^"]+)"|\bplaceholder\s*=\s*'([^']+)'/i.exec(a);o&&t.push({label:"Placeholder text (visible)",value:o[1]??o[2]});const r=/\btype\s*=\s*"([^"]+)"|\btype\s*=\s*'([^']+)'/i.exec(a);r&&t.push({label:"Input type",value:`\`${r[1]??r[2]}\``});const i=/\bautocomplete\s*=\s*"([^"]+)"|\bautocomplete\s*=\s*'([^']+)'/i.exec(a);i&&t.push({label:"Autocomplete",value:i[1]??i[2]})}return t}function Hh(e,t){var i;const a=new Set((t??[]).filter(c=>c.verdict==="pass"||c.verdict==="fail").map(c=>`${c.pageUrl}::${c.ruleId}::${c.selector}`)),n=new Map;for(const c of t??[])c.verdict==="uncertain"&&n.set(`${c.pageUrl}::${c.ruleId}::${c.selector}`,c.reasoning);const o=new Set,r=[];for(const c of e){const d=c.pageUrl??c.scope,l=((i=c.axeRulesEvaluated)==null?void 0:i.incomplete)??[];for(const p of l)for(const m of p.elements??[]){const u=`${d}::${p.ruleId}::${m.selector}`;o.has(u)||a.has(u)||(o.add(u),r.push({pageUrl:d,ruleId:p.ruleId,wcagCriterion:p.wcagCriterion,selector:m.selector,failureSummary:m.failureSummary,styles:m.styles,aiAttemptReasoning:n.get(u)}))}}return r}function zi(e,t,a,n,o,r,i,c,d){var z,X,re,oe,le,ie,ge,Re,Oe,ve,de;const l=new Set(o??[]),p=new Set(d??[]),m=((z=e[0])==null?void 0:z.componentId)??"unknown",u=qe(e),g=!!(t&&t.baselineSnapshotMeta),h=e.flatMap(y=>y.violations),f=p.size>0?h.filter(y=>p.has(y.matchKey)):[],w=y=>l.has(`violation::${y}`),b=h.filter(y=>!p.has(y.matchKey)&&!w(y.matchKey)),k=new Map;for(const y of b){const L=y.ruleId.startsWith("ai-")?`${y.ruleId}::${y.target.selector}::${(y.target.outerHTML??"").slice(0,200)}`:Fe(y.ruleId,y.target.selector),R=`${y.currentState.pseudoState} · ${y.currentState.theme} · ${y.currentState.direction} · ${y.currentState.breakpoint.id}`,G=k.get(L);if(G){G._states.includes(R)||G._states.push(R),G._instanceSelectors.includes(y.target.selector)||G._instanceSelectors.push(y.target.selector);continue}k.set(L,{...y,_states:[R],_instanceSelectors:[y.target.selector]})}const v=Array.from(k.values()).sort((y,L)=>{const R={critical:0,serious:1,moderate:2,minor:3};return(R[y.impact]??99)-(R[L.impact]??99)}),s=[];s.push("# Accessibility Fix Request"),s.push(""),s.push("> **Your job is to APPLY the fixes in this report — not to evaluate, second-guess, or re-litigate whether the findings are correct.** This report is the output of a real automated audit (axe-core run in a live browser across many UI states) plus AI verification; the triage already happened upstream. Do not debate severity or skip items you personally doubt. Read each finding, apply the canonical fix, and report the outcome per the Work contract below. A genuine blocker or a real user-decision is the only acceptable non-fix — and those are reported explicitly per the contract, never silently dropped."),s.push(""),s.push(`You are a senior accessibility engineer pairing with the user on their codebase. The component below has ${v.length} unique WCAG violation${v.length===1?"":"s"} detected by an automated audit running axe-core ${((X=e[0])==null?void 0:X.axeVersion)??"4.x"} across ${e.length} state combinations (hover, focus, focus-visible, active, disabled × dark / forced-colors / RTL / breakpoints). Your task: locate each violation in the codebase and apply the canonical fix — carefully, atomically, and asking before guessing.`),s.push(""),s.push("## [!] Work contract — read before doing anything else"),s.push(""),s.push(`**You will receive ${v.length} numbered finding${v.length===1?"":"s"} below.** Each one needs an outcome BEFORE you report completion. Do not stop early. Do not batch by impact level. Do not declare done without addressing every numbered item.`),s.push(""),s.push("**For each numbered finding (1 through "+v.length+"), produce one of:**"),s.push(""),s.push("- [DONE] **Applied** — the canonical fix from this prompt was applied to the source. Cite the file + line."),s.push("- [BLOCKED] **Blocked** — explicitly state WHY you cannot apply the fix (missing info, ambiguous user content, dependency change required, etc.). One sentence per blocked finding."),s.push("- [NEEDS-DECISION] **Needs user decision** — you found options but need the user to pick. List the options inline."),s.push(""),s.push(`**The single answer you cannot use: "skipped" or "didn't get to it."** If you ran out of context or time, stop and tell the user — do not silently omit items.`),s.push(""),s.push("**Required final response format** — at the end of your work, produce a completion table:"),s.push(""),s.push("```"),s.push("| # | Rule ID | Status | Notes |"),s.push("|---|---------|--------|-------|"),s.push("| 1 | <rule> | DONE / BLOCKED / NEEDS-DECISION | <file:line OR reason> |"),s.push("| 2 | ... | ... | ... |"),s.push(`| ${v.length} | ... | ... | ... |`),s.push("```"),s.push(""),s.push("**Every row must be present.** If status is BLOCKED or NEEDS-DECISION, the Notes column explains specifically what the blocker is so the user can address it on the next pass. The point is that ONE pass through this prompt should produce either a fix or a clear next action for every finding — not a partial sweep that leaves the user re-running the loop."),s.push(""),s.push("---"),s.push("");const x=a&&a.length>0?{runs:a,workflows:Pe}:void 0,$=c==null?void 0:c.map(y=>({criterionId:y.criterionId,ruleId:`ai-interactive::${y.criterionId}`,pageUrl:y.pageUrl,verdict:y.verdict,reasoning:y.reasoning})),A=et(h,x,e,p,$,void 0,void 0,ft(e),r),C=A.score;if(s.push("## Context"),s.push(""),s.push(`- **Component / scope:** \`${m}\``),s.push(`- **Audited URL:** ${u}`),s.push(`- **WCAG target:** WCAG ${Nt} ${In} (this audit's goal; the receiving fix should bring the page into compliance with this level)`),s.push("- **Source filter:** Full audit — every detected violation"),s.push(`- **Compliance posture:** Grade **${A.combined}** · **${C.risk.toUpperCase()} risk** (${C.totals.critical} critical · ${C.totals.serious} serious · ${C.totals.moderate} moderate · ${C.totals.minor} minor). ${C.risk==="critical"||C.risk==="high"?"Treat as triage priority — these violations represent meaningful lawsuit exposure under ADA Title III, EAA, and EN 301 549.":C.risk==="moderate"?"Should be addressed in the current sprint cycle; not lawsuit-emergency but real exposure.":"Lower exposure; still worth fixing but not blocking other work."}`),C.coverage){const y=C.coverage.untestedCriteria.length;y>0?s.push(`- **WCAG ${C.coverage.targetVersion} ${C.coverage.targetLevel} coverage:** ${C.coverage.evaluated} of ${C.coverage.totalApplicable} criteria evaluated. **Cannot claim ${C.coverage.targetLevel} conformance** until ${y} untested criteria are evaluated via Guided Tests (Pass / Fail / N/A). Untested: ${C.coverage.untestedCriteria.join(", ")}.`):s.push(`- **WCAG ${C.coverage.targetVersion} ${C.coverage.targetLevel} coverage:** ${C.coverage.evaluated} of ${C.coverage.totalApplicable} criteria evaluated. Full coverage — defensible conformance claim possible once all violations below are fixed.`)}g&&t&&s.push(`- **Trend vs your saved baseline:** ${t.newCount} new · ${t.persistentCount} carried over · ${t.fixedCount} resolved. The fix list below is the FULL current violation set, not just the delta.`),s.push(""),s.push("## Before you start (safety)"),s.push(""),s.push("Do these in order before making any code changes:"),s.push(""),s.push("1. **Verify a clean git working tree** (`git status`). If there are uncommitted changes, ask the user whether to commit, stash, or proceed."),s.push("2. **Switch to a feature branch** dedicated to this work — e.g., `a11y/fix-component-name`. Don't commit directly to `main` / `master` / `develop`."),s.push("3. **Plan one commit per fix.** Each violation gets its own atomic commit so any individual change can be reverted without untangling the rest. Commit messages should follow the pattern: `a11y: fix <ruleId> on <selector or component>`."),s.push("4. **Show diffs before applying** when your tooling supports it (Cursor / Copilot Chat agents). Never silently overwrite files."),s.push("5. **Do not bump dependencies** to resolve accessibility issues — fixes should be code changes, not package upgrades."),s.push(""),s.push("## Ask me these questions first"),s.push(""),s.push("Before applying any fix, ask the user the questions below. Don't proceed until you have answers — guessing here produces fixes that don't match the codebase's conventions and will be rejected on review."),s.push(""),s.push("1. **Framework + style approach?** React / Vue / Svelte / Angular / Solid / vanilla — and CSS Modules / Tailwind / styled-components / Emotion / scoped `<style>` / global CSS / design-tokens system. This determines *how* every fix is written."),s.push("2. **Existing design tokens or raw values?** If the codebase uses `var(--color-text-on-surface)` or a `tokens.ts` / `theme.json`, fixes must use tokens — never introduce new hex codes. Where can you read the available tokens?"),s.push('3. **Existing utility classes or component library?** e.g., does `.text-slate-700` or `<Button variant="primary">` already exist? Use what\'s there before inventing new selectors or components.'),s.push("4. **Files or directories that are off-limits?** Generated code, vendored libraries, third-party widgets, lockfiles — confirm what you must NOT touch."),s.push("5. **For color-contrast fixes: prefer adjusting foreground or background?** Brand color preservation is usually a stakeholder call, not a developer call."),s.push("6. **How should I verify fixes are done?** Re-run this auditor (preferred), run the existing test suite, manual screen-reader pass, or all three?"),s.push(""),s.push("## Decision rules (when ambiguity surfaces during fixes)"),s.push(""),s.push('- **Native HTML beats ARIA.** First rule of ARIA: don\'t use ARIA when a native element works. Prefer `<button>` over `<div role="button">`, `<nav>` over `<div role="navigation">`, etc.'),s.push("- **State-specific failures get state-specific fixes.** A `:hover`-only contrast failure goes in the `:hover` rule, not the default selector."),s.push("- **Where multiple valid fixes exist, surface options — don't pick silently.** E.g., adding an accessible name can be done via visible text, `aria-label`, or `aria-labelledby` referencing existing copy. Present the options with tradeoffs and let the user choose."),s.push("- **When the fix would alter visible design** (color shifts, layout changes, content additions), pause and confirm with the user before applying."),s.push(""),s.push("## [STOP] Do not dismiss findings without empirical verification"),s.push(""),s.push('**Default stance: every finding in this report is real and needs a fix.** Your job is to apply fixes, not to triage which ones "probably aren\'t real." That triage already happened — the auditor ran on a real browser, captured real DOM, real `getBoundingClientRect()` coordinates, real WCAG rule failures from axe-core. You are downstream of all that.'),s.push(""),s.push('Some categories (reading-order, tab-order) are explicitly heuristic and DO have legitimate false-positive cases. Those cases are listed inline in each section. **But "this looks like it might be a false positive based on the pattern" is not verification.** Pattern-matching from the report alone is inference, not evidence.'),s.push(""),s.push("**To dismiss any finding as a false positive, you must do all of the following:**"),s.push(""),s.push("1. **Load the deployed page in a real browser** at the viewport listed in the finding's capture-state header (e.g., 1280×800 LTR for the position-based analyses)."),s.push("2. **Inspect the flagged elements directly** — DevTools, real `getBoundingClientRect()` coordinates, real DOM source order."),s.push("3. **Compare your empirical observation to the auditor's claim.** Does the visual layout actually contradict the DOM order, or not?"),s.push("4. **If you conclude false positive, document why** — include the empirical evidence (coordinates, screenshots, DOM excerpt) so the user can audit your reasoning."),s.push(`5. **Even after empirical verification, ASK THE USER before dismissing.** They have context you don't (e.g., "yes that's an intentional skip-link / multi-column layout / RTL-only behavior").`),s.push(""),s.push("**What does NOT count as verification:**"),s.push(""),s.push("- Looking at the CSS file and not seeing `flex-direction: row-reverse` (the layout could be from `order:`, `grid-area`, absolute positioning, or RTL emulation)"),s.push('- Pattern-matching the finding shape ("this looks like a perfect arithmetic flip therefore it must be an RTL artifact")'),s.push(`- Reading the auditor's false-positive list and concluding your case "looks like one of those"`),s.push(`- Deciding it's "probably fine" because the structure looks reasonable on a quick read`),s.push(""),s.push("**If you cannot run a real browser** (e.g., environment doesn't allow headless Chromium), then you cannot verify, which means you cannot dismiss. In that case: surface the finding to the user, propose the fix, and let them decide."),s.push(""),s.push("**Skipping a finding without verification is worse than fixing one that turns out to be a false positive.** Over-fix is reversible (delete the commit). Under-fix is silent — the user thinks they're compliant when they aren't."),s.push(""),s.push("**When you DO verify a finding is a false positive** (per the empirical rules above), the right action is to recommend the user click **dismiss** on that finding in the auditor's Activity tab. The auditor records the dismissal with your reason, suppresses the finding from displayed counts, the Matrix banner, and future AI prompts. **Don't modify code to silence a verified false positive** — that produces brittle workarounds and pollutes the codebase with comments explaining heuristic quirks. Dismissals persist per-URL and survive re-audits cleanly."),s.push(""),s.push("## Content-decision rules (alt text, button labels, link text)"),s.push(""),s.push("Some violations require copy that the audit can't generate. Don't invent copy out of nowhere, but DON'T just punt to the user either — use the capabilities you have:"),s.push(""),s.push('1. **For images missing alt text** (`image-alt`, `input-image-alt`, `area-alt`, `svg-img-alt`): if you have vision capability, **fetch or view the image** at the `src` URL listed in the violation and PROPOSE descriptive alt text based on what the image actually contains. Mark obviously-decorative images (icons inside buttons that already have text labels, dividers, background flourishes) for `alt=""`.'),s.push('2. **For unlabeled buttons / links** (`button-name`, `link-name`, `empty-button`, `empty-link`): look at the surrounding code context — nearby text, the button\'s icon (often a known SVG name like "close" / "search" / "menu"), the route the link points at — and PROPOSE an accessible name. Show your inference reasoning.'),s.push("3. **For unlabeled form fields** (`label`, `select-name`, `aria-input-field-name`): inspect the field's `name`, `placeholder`, `id`, and any nearby visible text in the parent container. PROPOSE a label."),s.push("4. **For ambiguous content** (alt text where you genuinely can't tell what an image shows; labels where there's no surrounding context), ask the user — don't guess."),s.push("5. **Always show your proposed copy before applying** — let the user approve, edit, or reject."),s.push(""),s.push("## [VERIFY] Verify with Playwright before asking the user"),s.push(""),s.push(`Many WCAG criteria that look like "needs human verification" are actually scriptable — you can write a short Playwright test, run it, observe the result, and resolve the question without bothering the user. **Default to this path.** Only ask the user when Playwright can't reach the answer (subjective copy decisions, content judgment, business-context questions).`),s.push(""),s.push("### Step 1: Check if Playwright is available"),s.push(""),s.push('Look in the project root for `playwright.config.ts` / `playwright.config.js` / a `tests/` or `e2e/` directory using `@playwright/test`. If yes — use it directly. If no — ask the user once: "Want me to add Playwright (`npm install -D @playwright/test && npx playwright install`) so I can verify a few WCAG criteria automatically?" If they decline, fall back to asking per-item.'),s.push(""),s.push("### Step 2: Run targeted smoke tests instead of asking"),s.push(""),s.push("Here are the manual-checklist items below that Playwright CAN verify on the CURRENT PAGE (no multi-page setup needed). For each, write the test, run it, and only escalate to the user if the test result is ambiguous:"),s.push(""),s.push("**Scope disambiguation:** the criteria below are all **single-page** — they describe behavior of the current page. They are NOT multi-page concerns. Cross-page criteria (3.2.3 Consistent Navigation, 3.2.4 Consistent Identification, 3.2.6 Consistent Help) require comparing multiple pages and are handled by wcagcheckr's Site Crawl flow, NOT by Playwright tests here. Don't skip 3.2.1 / 3.2.2 thinking they're multi-page — they're single-page and Playwright-testable."),s.push(""),s.push("| Criterion | Scope | Playwright test |"),s.push("|---|---|---|"),s.push('| **1.4.4 Resize Text (AA)** | single-page | `await page.evaluate(() => document.body.style.zoom = "200%"); await page.screenshot(...); assert no horizontal scroll on critical content blocks` |'),s.push("| **1.4.10 Reflow (AA)** | single-page | `await page.setViewportSize({ width: 320, height: 800 }); await expect(page).toHaveScreenshot(...); assert documentElement.scrollWidth ≤ clientWidth + 10` |"),s.push("| **1.4.12 Text Spacing (AA)** | single-page | inject `* { line-height: 1.5 !important; letter-spacing: 0.12em !important; word-spacing: 0.16em !important; }` via `addStyleTag`, screenshot, check no clipping/overlap |"),s.push('| **1.4.13 Content on Hover or Focus (AA)** | single-page | hover each tooltip-bearing element, then `await page.keyboard.press("Escape")` — verify tooltip closes (dismissible); move mouse INTO tooltip, verify it stays (hoverable); wait 5s without interaction, verify it stays (persistent) |'),s.push("| **2.1.4 Character Key Shortcuts (A)** | single-page | enumerate document keydown handlers; press each single-key shortcut + verify it only fires when expected (focus-dependent or toggleable) |"),s.push("| **2.2.1 Timing Adjustable (A)** | single-page | scan code for setTimeout/setInterval with user-facing impact; assert each has a pause/extend/disable affordance |"),s.push("| **2.2.2 Pause, Stop, Hide (A)** | single-page | find elements with CSS animation / transition / autoplay video; assert each has a visible pause/stop control |"),s.push('| **2.4.5 Multiple Ways (AA)** | single-page | `await page.locator("nav").count() + page.locator("[role=search]").count() + page.locator("a[href*=sitemap]").count() ≥ 2` — checks the current page exposes at least two ways to reach other pages (nav + search, or nav + sitemap link, etc.). |'),s.push("| **2.5.2 Pointer Cancellation (A)** | single-page | for each `<button>` / `[role=button]`: `page.mouse.down()` on it, `page.mouse.move(elsewhere)`, `page.mouse.up()` — assert no action fired (no URL change, no submitted form, no state mutation) |"),s.push("| **3.2.1 On Focus (A)** | **single-page (per-page test, NOT multi-page)** | iterate every focusable on the current page; `.focus()` on each; assert URL unchanged + no modal opened + no form submitted + no scroll jump. This is about each FOCUS event on this page, not about page-to-page navigation. |"),s.push('| **3.2.2 On Input (A)** | **single-page (per-page test, NOT multi-page)** | for each `<select>` / `<input>` / `<textarea>` / `[contenteditable]` on the current page: change value via `.fill()` or `.selectOption()`; assert no URL change, no auto-submit, no scroll jump UNLESS the form clearly warns ("submits on change" UI affordance). |'),s.push('| **4.1.3 Status Messages (AA)** | single-page | trigger a form-validation error or async update; assert the live region announces (`role="status"` or `role="alert"` exists + has text content) |'),s.push(""),s.push("### Step 3: Vision-capable items"),s.push(""),s.push('For items where the test result is "a screenshot to evaluate":'),s.push("- **Color contrast on a gradient/image background:** Playwright screenshot of the element + 50px context, sample foreground + background pixels at the text's bounding box, compute WCAG contrast ratio, compare to 4.5:1 (normal) or 3:1 (large)."),s.push('- **Alt text accuracy:** fetch the `src=` URL, view the image, propose alt text. If the image is a logo/wordmark/decorative, recommend `alt=""`.'),s.push("- **1.4.5 Images of Text:** screenshot the hero / heading / banner; check whether typography is rendered as text (selectable + DOM-visible) or as a raster image."),s.push(""),s.push("### Step 4: When to fall back to asking the user"),s.push(""),s.push("Ask only when:"),s.push(`1. The verification requires subjective judgment Playwright can't make (e.g., "is this alt text accurate to the brand's voice?")`),s.push('2. The criterion needs production-data context (e.g., "do users hit this timeout in practice?")'),s.push("3. The Playwright test itself is ambiguous and the user has context that resolves it"),s.push(""),s.push('**Report Playwright results inline with your fix proposals.** "I ran a smoke test for 1.4.10 at 320px — no horizontal scroll detected; checking this off" beats "Could you verify 1.4.10 manually?" every time.'),s.push(""),s.push("## Determinism + reproducibility"),s.push(""),s.push("**AI judgments are not reproducible by default.** Anthropic, OpenAI, and most LLM APIs run at non-zero sampling temperature unless you explicitly request otherwise — meaning the same prompt + same context can produce different answers on different runs. wcagcheckr learned this the hard way (rc.190 → rc.192): consecutive audits on an unchanged page produced different verdicts because the audit's own AI calls ran at default temperature. The fix was `temperature: 0` on every judgment call."),s.push(""),s.push("You face the same risk for any decision you make based on AI judgment rather than empirical observation. Mitigate by:"),s.push(""),s.push('1. **Prefer empirical verification over AI judgment.** If a question can be answered by running Playwright, running axe-core, sampling pixel values, or grepping the codebase — do that, not "I think the screenshot shows…". The Playwright section above lists 11 criteria that can be verified deterministically.'),s.push("2. **For any auxiliary AI calls you make** (vision tasks, classification, summarization), pass `temperature: 0` (Anthropic / OpenAI) or `top_p: 0.01` (other providers). Same screenshot + same prompt should produce the same answer twice in a row — verify before trusting the answer."),s.push('3. **Document AI-judgment decisions in commit messages.** When you DO rely on AI for a subjective call ("I chose `aria-label=\\"Search the catalog\\"` over `\\"Search\\"` because…"), record the reasoning in the commit so the next session — yours or a human\'s — can audit the call.'),s.push("4. **Treat any single AI verdict as one data point, not gospel.** If you ask AI the same question twice and get different answers, that's the variance showing. Stick with the FIRST answer you committed to OR cross-check with Playwright; don't flip-flop based on subsequent re-rolls."),s.push("5. **Re-run the auditor (`wcagcheckr`) after every commit** rather than asking AI \"is this fixed?\" — the auditor's output is the source of truth for whether a fix landed, not the fixer AI's self-assessment."),s.push(""),s.push("Sampling variance is the silent enemy of compliance automation. Treat it as a constraint to design around, not noise to ignore."),s.push(""),s.push("## Constraints"),s.push(""),s.push("- Don't fix violations that aren't in this list (no scope creep)."),s.push(`- Don't reformat or reorder unrelated code. No "while I'm here" cleanup.`),s.push(`- Match existing code style. Don't invoke Prettier / ESLint to "fix everything" — focus your diff strictly on the violation's element + relevant style rule.`),s.push("- Don't add new dependencies, configs, or build steps."),s.push("- Add inline comments only where the fix's rationale is non-obvious; otherwise skip comments."),s.push("- Preserve existing functionality and visual design wherever possible."),s.push(""),s.push("## How to use this prompt"),s.push(""),s.push("Paste this into Claude / Cursor / Copilot Chat with your codebase open. The AI should:"),s.push('1. **First**: walk through the "Before you start" + "Ask me these questions" sections with the user.'),s.push("2. **Then**: identify the source files containing each violating element (use the selectors + outerHTML below)."),s.push("3. **Then**: for each violation, propose the fix using the recipe + answers gathered, surface ambiguity per the decision rules, and apply only after the user confirms."),s.push("4. **Finally**: produce one atomic commit per fix, with a clear message."),s.push(""),s.push("## Locating findings in source"),s.push(""),s.push("For each finding below, the most reliable search strategies (try in this order):"),s.push(""),s.push('1. **The accessible name / text content** — works for JSX, Vue templates, Svelte, server-rendered HTML. Search for the visible text in `"quotes"` or as a string literal in component files.'),s.push("2. **A distinctive class name** — e.g., `.cta-primary` → grep `cta-primary` in CSS + component files. BEM-style and Tailwind utility classes are the most stable identifiers."),s.push('3. **A unique data attribute** — `data-testid="checkout-button"`, `data-qa=`, `data-cy=` — these are usually authored deliberately and survive minification.'),s.push("4. **A stable ID** — `#hero-search` → grep `hero-search`. Watch out for IDs that look generated (`#field_3f8a92`)."),s.push('5. **The outerHTML pattern** — fall back when class/id/testid don\'t help. Search for distinctive attribute combinations (e.g., `aria-label="…"` + `class="…"`).'),s.push(""),s.push("**Do not search on these — they're runtime artifacts:**"),s.push("- `:nth-child(N)`, `:nth-of-type(N)` — these are positional, never appear in source"),s.push("- Numeric suffixes that look generated (`-1234`, `__abc123`) — usually from CSS Modules / styled-components hashing"),s.push("- Selector paths with `>` chains — describes a DOM structure, not a source location"),s.push(""),s.push("**For pages built with a framework**, also check:"),s.push("- Storybook stories (`*.stories.tsx`, `*.stories.mdx`) — often the canonical component definition"),s.push("- Shared layout components (`Header.tsx`, `Footer.tsx`, `Layout.tsx`) — most page-level violations live here"),s.push("- Theme / token files (`theme.ts`, `tokens.json`) — color-contrast fixes often patch tokens, not consumers"),s.push(""),s.push("---"),s.push("");const F=(((re=e[0])==null?void 0:re.readingOrderIssues)??[]).filter(y=>!l.has(`reading-order::${y.selector}`)),T=(oe=e[0])==null?void 0:oe.positionAnalysisCapturedAt,I=T?`${T.breakpoint.width}×${T.breakpoint.height} (${T.breakpoint.label}), ${T.direction.toUpperCase()}, ${T.theme} theme, ${T.pseudoState} pseudo-state`:"(reference state unavailable — findings reflect last matrix state)",D=c==null?void 0:c.some(y=>y.criterionId==="1.3.2");if(F.length>0&&!D){s.push("## Reading-order concerns (DOM ≠ visual order)"),s.push(""),s.push(`_Positions captured at: **${I}**. Multi-column layouts, RTL pages, and mobile-stacked sections may have legitimately different reading orders at other viewports — verify each finding against the layout the user actually sees._`),s.push(""),s.push(`Screen readers read the DOM in source order. CSS that visually rearranges things (\`flex-direction: row-reverse\`, \`order:\`, \`grid-area\`, absolute positioning) does NOT reorder what the SR sees. ${F.length} element${F.length===1?" has":"s have"} a notable gap between their DOM position and their visual position:`),s.push(""),s.push("| DOM index | Visual index | Selector | Text |"),s.push("|---|---|---|---|");for(const y of F){const L=y.textSnippet.replace(/\|/g,"\\|").replace(/\n/g," ");s.push(`| ${y.domIndex} | ${y.visualIndex} | \`${y.selector}\` | ${L} |`)}s.push(""),s.push("**How to fix:** match DOM order to intended reading order — reorder the JSX/HTML, NOT the CSS. CSS visual rearrangement is a code smell only because it diverges from DOM order; if the DOM order is what the user should hear, no fix is needed."),s.push(""),s.push("**False-positive cases — these are the ONLY legitimate reasons to skip a flagged element:**"),s.push(""),s.push('1. **Multi-column / newspaper layouts** — DOM order is "column 1 top to bottom, then column 2", which is correct for SR but reads as "out of order" to this analyzer.'),s.push('2. **Skip-links** ("Skip to main content") — visually positioned late but DOM-early on purpose.'),s.push("3. **Caption-first patterns** — captions placed before their image in DOM so SR users get context before the alt text."),s.push("4. **Modal / popover triggers** — the trigger button is DOM-near the modal's portal mount point, which is often `<body>` end."),s.push(""),s.push('**Per the verification rules above (§ "Do not dismiss findings without empirical verification"): even when a finding looks like one of these false-positive cases, you must verify in a real browser before skipping. "Looks like a multi-column layout" is inference, not proof.** Read the DOM. Get real coordinates. Then ask the user. Then skip if confirmed.'),s.push(""),s.push("Surface the candidates above to the user, ask which (if any) are intended, and only reorder the rest. **If in doubt, fix it.** Reordering JSX is reversible; failing a Level A criterion is not."),s.push(""),s.push("---"),s.push("")}const S=(((le=e[0])==null?void 0:le.tabOrderIssues)??[]).filter(y=>!l.has(`tab-order::${y.selector}`)),_=c==null?void 0:c.some(y=>y.criterionId==="2.1.2"&&y.verdict==="pass");if(S.length>0&&!_){const y=S.filter(R=>R.flag==="visual"||R.flag==="both").length,L=S.filter(R=>R.flag==="tabindex"||R.flag==="both").length;s.push("## Tab-order concerns (keyboard focus sequence ≠ visual order) — WCAG 2.4.3 Focus Order (A)"),s.push(""),s.push(`_Positions captured at: **${I}**. Tab-position-vs-visual-position divergence is direction- and breakpoint-sensitive — what looks wrong here may be correct on RTL or mobile (and vice versa). Verify each finding against the layout the user actually sees._`),s.push(""),s.push(`Keyboard users tab through the page in one order; sighted users scan in another. axe-core does not detect this. ${S.length} focusable element${S.length===1?" has":"s have"} a notable divergence. Of these: ${y} ${y===1?"has":"have"} a visual-vs-tab mismatch (focus jumps around the page); ${L} ${L===1?"is":"are"} caused by positive \`tabindex\` reordering DOM source.`),s.push(""),s.push("| Tab pos | Visual pos | DOM pos | Flag | Selector | Text |"),s.push("|---|---|---|---|---|---|");for(const R of S){const G=R.textSnippet.replace(/\|/g,"\\|").replace(/\n/g," ");s.push(`| ${R.tabPosition} | ${R.visualPosition} | ${R.domPosition} | ${R.flag} | \`${R.selector}\` | ${G} |`)}s.push(""),s.push("**How to fix:**"),s.push(""),s.push("- **`flag: visual`** — tab order doesn't match visual layout. Reorder the JSX/HTML so the DOM source order matches the layout order users see. Don't use `tabindex` to \"patch\" this — that creates the next class of bug."),s.push('- **`flag: tabindex`** — a positive `tabindex` value (`tabindex="3"`) is reordering DOM. Remove the positive `tabindex` and rely on DOM source order. Use `tabindex="0"` only to make a non-focusable element focusable; use `tabindex="-1"` only to remove from the tab order.'),s.push("- **`flag: both`** — both conditions present. Fix the DOM order first, then remove the positive `tabindex`."),s.push(""),s.push("**False-positive cases — these are the ONLY legitimate reasons to skip a flagged element:**"),s.push(""),s.push('1. **Skip-links** ("Skip to main content") — visually-late, DOM-early on purpose. Their tab position should be near 1; their visual position is wherever their `:focus` styling places them.'),s.push("2. **Modal triggers + portal-rendered modals** — the trigger button is DOM-near the modal's portal mount point (often `<body>` end), so tab/visual positions can legitimately diverge."),s.push("3. **Dropdown menus / popovers** — a button DOM-far from its portal-rendered menu may produce false positives when the menu is open."),s.push(""),s.push(`**Per the verification rules above (§ "Do not dismiss findings without empirical verification"): even when a finding looks like one of these cases, you must verify in a real browser before skipping. Tabbing through the actual deployed page is empirical evidence; reading the auditor's table and pattern-matching is not.** If in doubt, fix it. Reordering JSX is reversible; failing a Level A criterion is not.`),s.push(""),s.push("Surface candidates to the user; ask which are intended; only fix the rest."),s.push(""),s.push("---"),s.push("")}const N=e.flatMap(y=>y.announcements??[]),W=e.flatMap(y=>y.focusEvents??[]).filter(y=>y.isFocusReset);if(N.length>0||W.length>0){if(s.push("## Runtime behavioral observations"),s.push(""),N.length>0){const y=N.filter(R=>R.politeness==="assertive").length;s.push(`**Live-region announcements** (${N.length} total, ${y} assertive): screen-reader announcements captured during state-driving. WCAG 4.1.3 Status Messages (AA) requires that non-essential changes use polite announcements; only blocking errors warrant assertive. Review:`),s.push("");const L=N.slice(0,8);for(const R of L){const G=R.text.replace(/\|/g,"\\|").replace(/\n/g," ").slice(0,120);s.push(`- \`[${R.politeness}${R.role?`/${R.role}`:""}]\` ${G}`)}N.length>8&&s.push(`- (and ${N.length-8} more)`),s.push(""),s.push("Verify each is appropriate. Common bug: error messages firing as `polite` (SR may not interrupt), or status updates firing as `assertive` (interrupts user mid-sentence)."),s.push("")}if(W.length>0){s.push(`**Focus resets to body** (${W.length} occurrence${W.length===1?"":"s"}): during the audit, focus jumped to \`<body>\` or \`<html>\` unexpectedly. This is almost always a bug — focus should move to a logical landing place (modal, alert, next field), never disappear.`),s.push("");for(const y of W.slice(0,5))s.push(`- \`${y.fromSelector??"(none)"}\` → \`${y.toSelector}\``);W.length>5&&s.push(`- (and ${W.length-5} more)`),s.push(""),s.push("Common cause: an element is removed from the DOM (e.g., modal closes) without `.focus()` being called on a sensible destination."),s.push("")}s.push("---"),s.push("")}const P=((ie=e[0])==null?void 0:ie.undefinedCustomProperties)??[];if(P.length>0){s.push("## Undefined CSS custom properties (cascade root cause)"),s.push(""),s.push(`${P.length} CSS custom propert${P.length===1?"y is":"ies are"} referenced via \`var(--name)\` but never declared. When a custom property is missing, the browser falls back to the property's initial value (often \`Canvas\` for color slots → resolves to white), which can produce a wave of false contrast failures. **Fix these missing tokens FIRST** — many of the contrast violations below may disappear once the cascade resolves correctly.`),s.push(""),s.push("| Custom property | References | First sample sites |"),s.push("|---|---|---|");for(const y of P){const L=y.sampleSites.map(R=>`\`${R.selector} { ${R.property} }\``).join("; ");s.push(`| \`${y.name}\` | ${y.referenceCount} | ${L} |`)}s.push(""),s.push("Each entry needs a definition in `:root` (or wherever the design-token layer lives). Surface to the user before applying contrast fixes — the missing token may be the root cause."),s.push(""),s.push("---"),s.push("")}if(a&&a.length>0){s.push("## Manual checks already completed (Guided Tests)"),s.push(""),s.push(`The consultant has run ${a.length} Intelligent Guided Test workflow${a.length===1?"":"s"} against this component covering the WCAG criteria automation cannot verify (keyboard navigation, screen-reader experience, focus management, forms, error prevention, etc.). Treat the verdicts below as ground truth — these came from a human running the actual flow.`),s.push(""),s.push("**Manual passes outrank heuristic findings.** When an IGT workflow has passed (e.g. Keyboard 7/7) and the heuristic analyzers below (Tab-order concerns, Reading-order concerns) flag findings on the same WCAG dimension, the manual pass is ground truth. A human ran real keyboard/SR navigation against the deployed page; the heuristic computes visual position from `getBoundingClientRect()` and can produce false positives on sticky / multi-column / grid layouts. **When the IGT and the heuristic disagree on the same WCAG criterion, treat the heuristic findings as suspect first**, run the empirical verification described above, and (if confirmed false positive) recommend dismissal via the Activity tab."),s.push("");const y=Pe;s.push("| Workflow | Status | Notes |"),s.push("|---|---|---|");for(const Y of a){const B=y.find(Ue=>Ue.id===Y.workflowId);if(!B)continue;let K=0,Q=0,ae=0,Me=0,ee=0;for(const Ue of B.steps){const We=Y.steps[Ue.id];if(!We){ee++;continue}We.status==="pass"?K++:We.status==="fail"?Q++:We.status==="skip"?ae++:We.status==="not-applicable"?Me++:ee++}const Ae=Q>0?`[FAIL] ${Q} failed`:ee>0?`[WARN] ${ee} unanswered`:`[PASS] all ${B.steps.length} answered`,Ce=[`${K}p`,`${Q}f`];Me>0&&Ce.push(`${Me} N/A`),ae>0&&Ce.push(`${ae} skip`),ee>0&&Ce.push(`${ee} unanswered`);const ne=`${Ce.join(" · ")} of ${B.steps.length} steps`;s.push(`| ${B.name} | ${Ae} | ${ne} |`)}s.push("");const L=[];for(const Y of a){const B=y.find(K=>K.id===Y.workflowId);if(B)for(const K of B.steps){const Q=Y.steps[K.id];(Q==null?void 0:Q.status)==="fail"&&L.push({workflow:B.name,stepTitle:K.question,notes:Q.notes})}}if(L.length>0){s.push("**Failed manual checks** (these are real WCAG failures the consultant verified by hand):"),s.push("");for(const Y of L)s.push(`- **${Y.workflow} → ${Y.stepTitle}**${Y.notes?`: ${Y.notes}`:""}`);s.push(""),s.push("**Address these alongside the automated violations below.** They will not appear in the violations list because no automated rule catches them — but they are still real WCAG failures and must be fixed for compliance."),s.push("")}const R=new Set(a.map(Y=>Y.workflowId)),G=y.filter(Y=>!R.has(Y.id));G.length>0&&(s.push(`**Not yet manually verified** (${G.length} workflow${G.length===1?"":"s"}): `+G.map(Y=>Y.name).join(", ")+". These cover WCAG criteria automation cannot detect; ask the consultant whether to run them before declaring the audit complete."),s.push("")),s.push("---"),s.push("")}if(n&&n.pagesAudited>1){const y=(()=>{try{return new URL(u).origin}catch{return null}})(),L=(()=>{try{return new URL(n.startUrl).origin}catch{return null}})();if(y&&L&&y===L){const R=n.finishedAt,G=R?Date.now()-new Date(R).getTime():0,Y=G<6e4?"just now":G<36e5?`${Math.round(G/6e4)} minute${Math.round(G/6e4)===1?"":"s"} ago`:G<864e5?`${Math.round(G/36e5)} hour${Math.round(G/36e5)===1?"":"s"} ago`:`${Math.round(G/864e5)} day${Math.round(G/864e5)===1?"":"s"} ago`;if(s.push("## Site-wide context (from a recent site crawl)"),s.push(""),s.push(`A crawl ${R?`(${Y})`:""} of ${n.pagesAudited} page${n.pagesAudited===1?"":"s"} on this origin produced grade **${Hr(n.siteGrade,n.spotCheckGate)}** site-wide with **${n.totalUniqueViolations}** unique violations. Use this context for WCAG 3.2.3 (Consistent Navigation) and 3.2.4 (Consistent Identification) which require cross-page comparison.`),s.push(""),n.topViolations.length>0){s.push("**Most-frequent violations across the site** (rules to prioritize because they affect multiple pages):"),s.push("");for(const K of n.topViolations.slice(0,6))s.push(`- \`${K.ruleId}\` — ${K.impact} — found on ${K.urlsAffected} page${K.urlsAffected===1?"":"s"} (${K.totalOccurrences} total instances)`);s.push(""),s.push("Fixing one of these rules in shared components / layouts is leverage — one fix resolves N pages."),s.push("")}const B=n.consistencyFindings??[];if(B.length===0&&n.topViolations.some(Q=>Q.ruleId==="wcc-consistency-needs-site-crawl"||Q.ruleId==="wcc-redundant-entry-needs-site-crawl")&&(s.push("**Cross-page consistency status:** the comparators ran across the crawled pages and detected **no real divergences** — primary navigation, brand link, footer help mechanism, and multi-step form fields are all consistent across the sample. The `wcc-consistency-needs-site-crawl` and `wcc-redundant-entry-needs-site-crawl` rule IDs in the violations list are placeholder findings emitted per-page by the single-page analyzer (which can't see other pages); the cross-page comparators downgrade them when the crawl confirms consistency. **Do not chase these on a per-page basis** — they're already cleared at the site level."),s.push("")),B.length>0){s.push("**Cross-page consistency divergences detected:**"),s.push("");for(const K of B){const Q=K.aiVerdict?K.aiVerdict.verdict==="uncertain"?" (AI: uncertain — human verify)":` (AI: confirmed real, confidence ${(K.aiVerdict.confidence*100).toFixed(0)}%)`:"";s.push(`- **${K.wcagCriterion} ${K.impact}**${Q} — ${K.description}`);for(const ae of K.details.split(`
1710
- `))s.push(` ${ae}`);(ge=K.aiVerdict)!=null&&ge.reasoning&&s.push(` AI reasoning: ${K.aiVerdict.reasoning}`),s.push("")}}s.push("**Manual cross-page checks the AI should still verify** (the heuristic comparators above can miss edge cases):"),s.push(""),s.push("- **3.2.3 Consistent Navigation** — primary nav DOM order across pages."),s.push("- **3.2.4 Consistent Identification** — same logo / menu / search / nav-link accessible names across pages."),s.push("- **3.2.6 Consistent Help (WCAG 2.2 A)** — help mechanism position consistency."),s.push("- **3.3.7 Redundant Entry (WCAG 2.2 A)** — multi-step forms re-asking for already-entered information."),s.push(""),s.push("---"),s.push("")}}if(f.length>0){const y=new Map;for(const R of f)y.has(R.matchKey)||y.set(R.matchKey,R);const L=Array.from(y.values());s.push("## Previously verified by human — DO NOT re-flag or attempt to fix"),s.push(""),s.push(`The user manually verified each of the following ${L.length} finding${L.length===1?"":"s"} in the wcagcheckr side panel. They WILL appear in raw axe output on every subsequent audit (axe re-detects them because the underlying DOM hasn't changed), but the user has dispositioned each one as acceptable — typically because an automated rule fired on a legitimate edge case (decorative image with empty alt, contrast that passes APCA but not WCAG 2.0 ratio, etc.). **Do not attempt to "fix" any item in this list.** Treat them as resolved. If you genuinely believe one is misjudged, note your reasoning in a comment for the user to review on their next audit — do NOT modify the markup.`),s.push(""),L.forEach((R,G)=>{s.push(`${G+1}. \`${R.ruleId}\` on \`${R.target.selector}\``),R.target.accessibleName&&s.push(` - Accessible name: "${R.target.accessibleName}"`),R.target.textSnippet&&s.push(` - Text: "${R.target.textSnippet.slice(0,120)}"`),s.push(` - WCAG ${R.wcagCriterion} ${R.wcagLevel} · ${R.impact}`)}),s.push(""),s.push("---"),s.push("")}const V=(r??[]).filter(y=>y.verdict==="fail").filter(y=>!p.has(`${y.ruleId}::${y.selector}`));if(V.length>0){const y=new Map;for(const R of V){const G=`${R.ruleId}::${R.selector}`;y.has(G)||y.set(G,R)}const L=Array.from(y.values());s.push("## AI-evaluated fails (axe couldn't determine — AI vision determined FAIL)"),s.push(""),s.push(`axe-core flagged each of the following ${L.length} element${L.length===1?"":"s"} as INCOMPLETE — its automated heuristics couldn't reach a verdict (typically because the background is a gradient, image, or semi-transparent overlay that axe can't pixel-sample). wcagcheckr's AI resolver then evaluated each element via vision + computed-style sampling and determined it is a real **FAIL**. Treat these the same as axe violations: locate the element in source, apply the canonical fix for the rule, and re-audit. The AI's reasoning is included per finding so you don't have to re-derive what was wrong.`),s.push(""),L.forEach((R,G)=>{const Y=R.wcagCriterion?` — WCAG ${R.wcagCriterion}`:"";s.push(`### ${G+1}. \`${R.ruleId}\`${Y}`),s.push(""),s.push(`**Selector:** \`${R.selector}\``),s.push(""),s.push(`**AI verdict (FAIL):** ${R.reasoning}`),s.push("");const B=lt[R.ruleId];B&&(s.push(`**Recipe:** ${B.summary}`),s.push(""),B.snippet&&(s.push("```"+(B.snippetLang??"")),s.push(B.snippet),s.push("```"),s.push("")))}),s.push("---"),s.push("")}s.push("## Violations to fix"),s.push(""),v.forEach((y,L)=>{var Me;const R=lt[y.ruleId],G=y._instanceSelectors.length;if(s.push(`### ${L+1}. \`${y.ruleId}\` — ${y.impact} — WCAG ${y.wcagCriterion} ${y.wcagLevel}${G>1?` (${G} instances)`:""}`),s.push(""),s.push(`**Description:** ${y.description}`),s.push(""),G>1){s.push(`**Affects ${G} spots — fix at the SOURCE (one CSS rule, one component, one shared class) — DO NOT patch each instance separately:**`);for(const ee of y._instanceSelectors.slice(0,8))s.push(`- \`${ee}\``);y._instanceSelectors.length>8&&s.push(`- (and ${y._instanceSelectors.length-8} more)`),s.push(""),s.push(`> **Find the common source.** ${G} matches means there's a single component / class / CSS rule producing all of them. Search the codebase for the shared class name OR the JSX/template that renders this element, then patch ONCE there. If you can't find a shared source (the elements are genuinely independent), apply the same fix to each — but flag that to the user as "code smell: this pattern is repeated."`)}else s.push(`**Selector:** \`${y.target.selector}\``);s.push(""),s.push(`**Found in state(s):** ${y._states.join(" / ")}`),s.push(""),s.push(Rr(y)),s.push("");const Y=Bh(y);if(Y.length>0){for(const ee of Y)s.push(`**${ee.label}:** ${ee.value}`);s.push("")}y.target.failureSummary&&(s.push(`**Diagnostic:** ${y.target.failureSummary.replace(/\n+/g," ")}`),s.push("")),y.ai&&(s.push(`**[AI] AI-verified finding** (model: ${y.ai.model}, confidence: ${(y.ai.confidence*100).toFixed(0)}%)`),s.push(`> ${y.ai.reasoning}`),s.push(""));const B=y.target.cascadeChain;if(B&&(B.color||B.backgroundColor)){if(s.push("**CSS cascade chain (authored → rendered):**"),B.color){const ee=B.color.vars.length>0?` (vars: ${B.color.vars.map(Ae=>`\`${Ae}\``).join(", ")})`:"";s.push(`- \`color\`: \`${B.color.authored}\` → \`${B.color.rendered}\`${ee}${B.color.ruleSelector?` — set in rule \`${B.color.ruleSelector}\``:""}`)}if(B.backgroundColor){const ee=B.backgroundColor.vars.length>0?` (vars: ${B.backgroundColor.vars.map(Ae=>`\`${Ae}\``).join(", ")})`:"";s.push(`- \`background-color\`: \`${B.backgroundColor.authored}\` → \`${B.backgroundColor.rendered}\`${ee}${B.backgroundColor.ruleSelector?` — set in rule \`${B.backgroundColor.ruleSelector}\``:""}`)}s.push("")}const K=i==null?void 0:i[y.matchKey];if(K&&K.suggestions.length>0){s.push(`**AI color suggestions** (cached from in-UI tooling — ${K.suggestions.length} candidates passing WCAG):`);for(const ee of K.suggestions)s.push(`- foreground \`${ee.foreground}\` on background \`${ee.background}\` → ${ee.contrast.toFixed(2)}:1 — ${ee.rationale}`);s.push(`> AI reasoning: ${K.reasoning}`),s.push("")}s.push("**Element HTML:**"),s.push("```html"),s.push(y.target.outerHTML),s.push("```"),s.push("");const Q=(Me=K==null?void 0:K.suggestions)==null?void 0:Me[0],ae=_i(y,{suggestedColors:Q?{foreground:Q.foreground,background:Q.background}:void 0});if(ae){s.push("**Suggested fix for this element** (apply to the source, not the rendered DOM):"),s.push("```diff");for(const ee of ae.current.split(`
1711
- `))s.push(`- ${ee}`);for(const ee of ae.suggested.split(`
1712
- `))s.push(`+ ${ee}`);s.push("```"),ae.note&&s.push(`> ${ae.note}`),s.push("")}R?(s.push(`**Recipe:** ${R.summary}`),R.snippet&&(s.push(""),s.push("```"+(R.snippetLang??"")),s.push(R.snippet),s.push("```"))):s.push(`**Recipe:** No curated recipe for this rule — apply the standard WCAG ${y.wcagCriterion} guidance.`),y.helpUrl&&(s.push(""),s.push(`**More info:** ${y.helpUrl}`)),s.push(""),s.push("---"),s.push("")});const M=Hh(e,r);if(M.length>0){s.push("## Items axe couldn't determine — needs human review"),s.push(""),s.push("axe-core ran these rules but couldn't conclude pass/fail (the most common cause is color-contrast on a gradient / image / semi-transparent background). For each element below: if you have vision capability, sample the rendered background and compute the contrast ratio; otherwise ask the user to verify visually."),s.push("");for(const y of M)s.push(`### \`${y.ruleId}\` on \`${y.selector}\``),s.push(""),s.push(`- **WCAG criterion:** ${y.wcagCriterion}`),s.push(`- **Page URL:** ${y.pageUrl}`),y.failureSummary&&s.push(`- **axe diagnostic:** ${y.failureSummary}`),(Re=y.styles)!=null&&Re.foreground&&s.push(`- **Foreground:** \`${y.styles.foreground}\``),(Oe=y.styles)!=null&&Oe.background&&s.push(`- **Background:** \`${y.styles.background}\``),(ve=y.styles)!=null&&ve.fontSize&&s.push(`- **Font size:** ${y.styles.fontSize}px, weight ${y.styles.fontWeight??"unknown"}`),(de=y.styles)!=null&&de.textSample&&s.push(`- **Text sample:** ${JSON.stringify(y.styles.textSample)}`),y.aiAttemptReasoning&&(s.push(""),s.push("**Our AI resolver already attempted this element and returned uncertain.** Its reasoning:"),s.push(""),s.push(`> ${y.aiAttemptReasoning.replace(/\n/g,`
1713
- > `)}`),s.push(""),s.push("**Suggested next step:** if you have stronger vision capability than our resolver, re-evaluate with a fresh screenshot. Otherwise the user must verify this one manually.")),s.push(""),s.push("---"),s.push("")}s.push("## Manual verification checklist — content-meaning criteria"),s.push(""),s.push(`wcagcheckr's three layers (axe-core, DOM analyzers, AI walkthroughs) cover every WCAG 2.1 AA criterion structurally. What automation CANNOT verify is content meaning: whether your caption text actually matches the audio, whether alt text accurately describes the image, whether sensory cues ("click the red button") have an alternative non-visual phrasing. **After applying the fixes above, walk the user through each item below before declaring the audit complete.** Mark each one passed, failed (and add to the fix queue), or N/A (with reasoning).`),s.push(""),s.push('Items the auditor has already flagged in earlier sections (reading-order, tab-order, behavioral observations, IGT manual checks) are listed below as "ALREADY FLAGGED" — confirm those fixes are in place.'),s.push("");const j=new Map;if(c)for(const y of c)j.set(y.criterionId,y.verdict);function q(y,L){const R=j.get(y);return R==="pass"?`- [x] **${y}** — [PASS] AI walkthrough verified pass during audit (see "AI keyboard walkthroughs" section). No manual verification needed.`:R==="fail"?`- [x] **${y}** — [FAIL] AI walkthrough FAILED during audit (see "AI keyboard walkthroughs" section for the fix). Confirm the code fix is applied and re-audit.`:R==="uncertain"?`- [ ] **${y}** — AI walkthrough was uncertain. ${L}`:`- [ ] **${y}** — ${L}`}return s.push("### Perceivable (audit-already-verified items pre-checked)"),s.push(""),s.push(q("1.3.2 Meaningful Sequence (A)","verify DOM source order matches the visual / reading order. Screen readers read the DOM; CSS reordering does NOT affect what the SR hears.")),s.push("- [ ] **1.2.1 Audio-only / Video-only Prerecorded (A)** — every audio-only file has a text transcript; every silent-video file has a text alternative or audio description. Ask the user: does the page have media? If yes, list each `<audio>` / `<video>` and verify the alternative."),s.push('- [ ] **1.2.2 Captions Prerecorded (A)** — every prerecorded video with audio has synchronized captions. If `<video>` elements exist without `<track kind="captions">`, ask the user about caption files.'),s.push("- [ ] **1.2.3 Audio Description / Media Alternative Prerecorded (A)** — prerecorded video has either audio description or a full text alternative."),s.push("- [ ] **1.2.4 Captions Live (AA)** — live audio content (livestream, real-time meeting) has captions. Usually N/A for static sites."),s.push("- [ ] **1.2.5 Audio Description Prerecorded (AA)** — prerecorded video has audio description for visual-only information."),s.push("- [ ] **1.4.2 Audio Control (A)** — if any audio plays automatically for >3 seconds, there is a mechanism to pause / stop / control volume. Test by loading the page; if anything autoplays audibly, fail."),s.push("- [ ] **1.4.4 Resize Text (AA)** — zoom the browser to 200%. All text remains readable; nothing is cut off. No horizontal scrolling within content blocks."),s.push("- [ ] **1.4.5 Images of Text (AA)** — confirm text is rendered as actual text, not as images. Exceptions: logos, brand wordmarks. Walk the user through their hero / heading sections."),s.push("- [ ] **1.4.10 Reflow (AA)** — resize browser to 320px wide × 256px tall. Page is usable; no horizontal scrollbar appears (except for data tables / maps / code)."),s.push(q("1.4.11 Non-text Contrast (AA)","every UI component (button border, form input border, icon, focus indicator) and graphical object has at least 3:1 contrast against adjacent colors. Inspect every interactive control + state indicator visually.")),s.push("- [ ] **1.4.12 Text Spacing (AA)** — apply user-stylesheet overrides: line-height ≥1.5×; paragraph spacing ≥2×; letter-spacing ≥0.12×; word-spacing ≥0.16×. Layout doesn't break, no clipped/overlapping text."),s.push("- [ ] **1.4.13 Content on Hover or Focus (AA)** — for any tooltip / popover / hover-revealed content: verify it is *dismissible* (Esc closes), *hoverable* (mouse can move into it without it disappearing), and *persistent* (doesn't auto-disappear unless user dismisses)."),s.push(""),s.push("### Operable (audit-already-verified items pre-checked)"),s.push(""),s.push(q("2.1.2 No Keyboard Trap (A)","Tab through the entire page from start to finish; verify focus never gets stuck in a region you can't leave with Tab/Shift+Tab/Esc. Common offenders: video players, custom widgets, modals without proper Esc handling.")),s.push('- [ ] **2.1.4 Character Key Shortcuts (A)** — if the site implements single-key shortcuts (pressing "j" advances feed, etc.), they must be either turn-off-able OR only active when focus is on a specific control. Ask the user about implemented shortcuts.'),s.push('- [ ] **2.2.1 Timing Adjustable (A)** — if any timeout exists (auto-logout, session expiry, "complete this in X seconds"), user can turn it off, adjust it, or extend it (≥10× the default). Exception: real-time events. Ask the user.'),s.push("- [ ] **2.2.2 Pause, Stop, Hide (A)** — for moving / blinking / scrolling / auto-updating content lasting >5s: there is a mechanism to pause/stop/hide it. Carousels, tickers, animations, autoplaying video — all need controls."),s.push("- [ ] **2.3.1 Three Flashes or Below Threshold (A)** — no content flashes more than 3× per second. Test with anything that pulses, blinks, or has rapid color changes (loading animations, alert flashing). Use https://trace.umd.edu/peat/ for borderline cases."),s.push(q("2.4.3 Focus Order (A)","spot-check by tabbing through the page: focus visits elements in a logical order (matches visual / semantic flow).")),s.push("- [ ] **2.4.5 Multiple Ways (AA)** — at least two ways to find any page within a set: site search + nav menu, OR menu + sitemap, OR menu + table of contents, etc. Single-page apps may exempt; ask user."),s.push(q("2.4.7 Focus Visible (AA)","every focusable element shows a visible focus indicator. Tab through the page and verify focus is always visually obvious.")),s.push("- [ ] **2.5.1 Pointer Gestures (A)** — any multi-point gesture (pinch-zoom, two-finger swipe) or path-based gesture (signature, drag-along-curve) has a single-pointer alternative. Common offender: maps, signatures, drawing canvases."),s.push("- [ ] **2.5.2 Pointer Cancellation (A)** — actions trigger on the up-event (mouseup / pointerup), NOT the down-event. Pressing then dragging-away cancels. Test by mouse-down on a button → drag off → release: action should not fire."),s.push(q("2.5.3 Label in Name (A)",`every interactive control's accessible name contains its visible text. Test with speech recognition: "click [visible text]" should activate the correct control.`)),s.push("- [ ] **2.5.4 Motion Actuation (A)** — features triggered by device motion (shake-to-undo, tilt-to-scroll) can be disabled AND have UI-button alternatives. Usually N/A for desktop sites."),s.push("- [ ] **2.5.7 Dragging Movements (AA, WCAG 2.2)** — any drag-only operation (kanban board, slider) has a non-drag alternative (buttons, click-to-place). Test sliders, drag-and-drop, sortable lists."),s.push(""),s.push("### Understandable"),s.push(""),s.push("- [ ] **3.2.1 On Focus (A)** — focusing any element does NOT trigger a context change (URL change, viewport scroll, modal open, form submit). Tab through every focusable element; verify none cause unexpected behavior."),s.push("- [ ] **3.2.2 On Input (A)** — changing the value of any form control does NOT trigger context change unless the user was warned. Common offender: `<select onChange={navigate}>` — must include adjacent submit button or warn the user."),n&&n.pagesAudited>1?(s.push("- [x] **3.2.3 Consistent Navigation (AA)** — site-crawl context provided above. Walk the user through verifying nav appears in the same order across pages."),s.push("- [x] **3.2.4 Consistent Identification (AA)** — verify components with the same function have the same accessible name across pages (logo home link, search button, menu toggle).")):(s.push("- [ ] **3.2.3 Consistent Navigation (AA)** — REQUIRES MULTI-PAGE COMPARISON. Ask the user for 2-3 representative pages; verify primary nav, footer, and search appear in the same DOM order on each."),s.push('- [ ] **3.2.4 Consistent Identification (AA)** — REQUIRES MULTI-PAGE COMPARISON. Components with identical functionality must have identical accessible names. Compare logo "home" link, search button, menu toggle across pages.')),s.push("- [ ] **3.2.6 Consistent Help (A, WCAG 2.2)** — REQUIRES MULTI-PAGE COMPARISON. If a help mechanism exists (chat, contact link, FAQ), it appears in the same relative order on every page where it appears."),s.push("- [ ] **3.3.4 Error Prevention — Legal, Financial, Data (AA)** — for any form that submits legal commitments (contracts, agreement), financial transactions (payments), or modifies/deletes user data: there is at least ONE of (a) reversibility, (b) error-checking with confirmation, (c) review-and-confirm step before final submit."),s.push("- [ ] **3.3.7 Redundant Entry (A, WCAG 2.2)** — forms in a multi-step process do NOT ask for the same information twice unless essential (re-entering password for confirmation is allowed). Auto-fill or pre-fill where possible."),s.push("- [ ] **3.3.8 Accessible Authentication — Minimum (AA, WCAG 2.2)** — login does not require a cognitive function test (puzzle, riddle, character-recognition) unless an alternative is provided (object recognition + autofill support are allowed; CAPTCHAs that require pattern recognition typically fail)."),s.push(""),s.push("### Robust"),s.push(""),N.length>0||W.length>0?s.push("- [x] **4.1.3 Status Messages (AA)** — runtime observations provided above (`Runtime behavioral observations` section). Confirm announcements use appropriate `aria-live` politeness and focus management is correct."):s.push('- [ ] **4.1.3 Status Messages (AA)** — status updates that don\'t cause a focus change (form-validation errors, "saved" confirmations, search-result counts) must use `role="status"` (polite) or `role="alert"` (assertive). Ask the user to demo their form-error and async-update flows; verify SR announces them.'),s.push(""),s.push("### Manual checks STILL TO DO"),s.push(""),s.push(`Walk the user through each unchecked box above (or batch them by criterion type — "let's test all the keyboard ones together"). For each: either mark passed (and move on), failed (add to the fix queue and resolve), or N/A (briefly justify why this site doesn't require this criterion).`),s.push(""),s.push('**Do not declare the audit complete until every box above is checked.** A site that passes only the automated portion is "axe-clean," not WCAG-compliant.'),s.push(""),s.push("---"),s.push(""),s.push("## When you're done — verification"),s.push(""),s.push("Before reporting completion, do all of the following:"),s.push(""),s.push(`1. **Confirm all ${v.length} violation${v.length===1?"":"s"} above are addressed.** Walk back through the list with the user, ticking each one off.`),s.push("2. **Re-run the auditor** (or whatever method we agreed in question 6 above). Verify zero NEW violations were introduced by the fixes."),s.push(`3. **Walk through the Manual verification checklist above** — every item should be marked passed, failed-and-fixed, or N/A. This is the half of WCAG that automation can't reach; skipping it means "axe-clean," not "compliant."`),s.push("4. **Visual diff** — for design-affecting fixes (color, spacing, layout), confirm the change with the user against the original. Storybook stories and visual regression suites are good checkpoints if the codebase has them."),s.push("5. **Commit log review** — surface the list of commits you produced. Each should be atomic and revertable."),s.push("6. **Report what you couldn't do** explicitly. If any violation required information we don't have (e.g., correct alt text), surface a TODO list for the user rather than guessing."),s.push(""),s.push("## Success criteria"),s.push(""),s.push("- All "+v.length+" violation"+(v.length===1?"":"s")+" above are resolved or explicitly deferred with reason."),s.push('- **Every reading-order and tab-order finding** is either fixed OR documented as a verified false positive (per § "Do not dismiss findings without empirical verification" above). Pattern-matching dismissals do not count.'),s.push('- **Every item in the manual verification checklist** above is marked passed, failed-and-fixed, or N/A-with-reason. (This is what separates "axe-clean" from "WCAG-compliant" — do not skip.)'),s.push("- No new violations introduced."),s.push("- State-specific behavior preserved (`:hover`, `:focus`, dark-mode, RTL, breakpoints)."),s.push("- One atomic commit per fix; clean revertable history."),s.push("- No unrelated code reformatted, no dependencies bumped."),s.push("- Diff is reviewable in under 10 minutes per fix."),s.push(""),s.push(`_Generated by ${Ie} v${Ee()}._`),s.join(`
1714
- `)}const qh=5;function zh(e){const t=new Map;let a=0;for(const n of e){if(!n.screenshotDataUrl||n.violations.length===0)continue;const o=`${n.state.pseudoState} · ${n.state.theme} · ${n.state.direction} · ${n.state.breakpoint.id}`,r=o;t.has(r)||t.set(r,{stateLabel:o,screenshotDataUrl:n.screenshotDataUrl,violations:[]});const i=t.get(r);for(const c of n.violations)a++,i.violations.push({...c,_idx:a})}return Array.from(t.values()).sort((n,o)=>o.violations.length-n.violations.length).slice(0,qh)}const Xo=1280,Qo=800,Kh={low:"Low risk",moderate:"Moderate risk",high:"High risk",critical:"Critical risk"},Yh={low:"#d1fae5",moderate:"#fef3c7",high:"#fed7aa",critical:"#fecaca"},Jh={low:"#065f46",moderate:"#92400e",high:"#9a3412",critical:"#991b1b"},Xh={A:"#10b981",B:"#84cc16",C:"#eab308",D:"#f97316",F:"#dc2626"},Qh={defense:{title:"Accessibility Defense Bundle",documentLabel:"engineering, design, and risk-management",disclaimerHeading:"This document is not a compliance certification.",disclaimerBody:"Automated accessibility audits, including this one, detect a subset (typically 30–50%) of WCAG success criteria. Conformance with the full WCAG specification requires manual evaluation by qualified accessibility professionals, including (but not limited to): keyboard-only operability testing, screen-reader compatibility testing across NVDA / JAWS / VoiceOver, manual review of dynamic content and live regions, and content-quality review for alt text, link text, and labels."},evidence:{title:"Accessibility Compliance Evidence",documentLabel:"documentation and review",disclaimerHeading:"This document is automated audit evidence — not a determination of liability or conformance.",disclaimerBody:"This report documents detected accessibility defects in the audited resource at the date and time of capture. The audit was conducted using axe-core, an industry-standard automated accessibility-rule engine maintained by Deque Systems and used by Microsoft (Accessibility Insights), Google (Lighthouse), IBM, and others. The findings represent objective rule-engine output, not subjective evaluation. Automated audits surface a subset (typically 30–50%) of WCAG success criteria; the absence of a violation in this report is not evidence of conformance, and the presence of a violation is not, by itself, a determination of legal liability."}};function Ki(e,t,a,n,o,r,i){return Ut(e,t,"evidence",a,n,o,r,i)}function Yi(e,t,a,n,o,r){return Qi(e,"letter",t,a,n,o,r)}function Ji(e,t,a,n,o,r){return Qi(e,"report",t,a,n,o,r)}function Xi(e,t,a,n,o,r){var h;const i=e.flatMap(f=>f.violations),c=Sa(i,void 0,e,a,t,n,o,ft(e),r),d=qe(e),l=new Map;for(const f of i){const w=Fe(f.ruleId,f.target.selector);l.has(w)||l.set(w,f)}const p=Array.from(l.values()).sort((f,w)=>{const b={critical:0,serious:1,moderate:2,minor:3};return(b[f.impact]??99)-(b[w.impact]??99)}),m=new Map;for(const f of p){const w=m.get(f.ruleId)??[];w.push(f),m.set(f.ruleId,w)}const u=[];if(u.push("# Help me fix accessibility issues on my website"),u.push(""),u.push("You are an accessibility advisor helping me — a non-technical site owner — understand and fix accessibility issues on my website. I ran an automated audit and got the issues below. I may not have technical knowledge, so please explain things in plain English."),u.push(""),u.push("## What I need from you"),u.push(""),u.push("1. **First, ask me what I use to manage my website.** Common platforms: Squarespace, Wix, Shopify, WordPress (with theme name), Webflow, Framer, custom-built. Your advice will be different for each."),u.push("2. **Then, for each issue below, tell me clearly:**"),u.push(" - Whether **I can fix it myself** in my site editor (changing colors, adding alt text, editing button labels, etc.) — and if so, walk me through where to look in my platform"),u.push(" - Or whether **my developer needs to do this** (code-level fix) — and what to ask them to do"),u.push("3. **Prioritize ruthlessly.** I want to start with the issues that:"),u.push(" - Are most likely to come up in an ADA-related lawsuit (critical-impact items)"),u.push(" - Are easiest for me to fix without involving a developer"),u.push("4. **Don't bury me in jargon.** If you have to use a technical term, explain it in plain English first."),u.push("5. **If something is genuinely beyond a non-technical fix, say so.** Tell me what to ask my developer or website-builder support team."),u.push(""),u.push("## Audit summary"),u.push(""),u.push(`- **Page audited:** ${d}`),u.push(`- **Lawsuit-target risk:** ${Tr[c.risk]} — ${Er[c.risk]}`),u.push(`- **Issues found:** ${c.totals.unique} unique problems (${c.totals.critical} critical · ${c.totals.serious} serious · ${c.totals.moderate} moderate · ${c.totals.minor} minor)`),c.coverage&&c.coverage.untestedCriteria.length>0?u.push(`- **WCAG conformance progress:** ${c.coverage.evaluated} of ${c.coverage.totalApplicable} criteria evaluated. Fixing the issues below will clear me of automated lawsuit-targeting tools. To make a formal claim that the site meets WCAG ${c.coverage.targetVersion} ${c.coverage.targetLevel}, ${c.coverage.untestedCriteria.length} more criteria need human review — see the "Guided Tests" workflows in the auditor side panel for these.`):c.coverage&&c.coverage.untestedCriteria.length===0&&u.push(`- **WCAG conformance:** All ${c.coverage.totalApplicable} applicable WCAG ${c.coverage.targetVersion} ${c.coverage.targetLevel} criteria have been evaluated. Fixing the issues below will produce a defensible conformance claim.`),u.push(""),u.push("## The issues, in plain language"),u.push(""),m.size===0)return u.push("No issues were detected across our three evaluation layers (axe-core rule-based checks, our DOM analyzers covering criteria axe doesn't reach, and AI walkthroughs that drive real keyboard input and judge screenshots). For a formal conformance claim, spot-check the content-meaning criteria — automation can detect missing captions, not whether your caption text accurately matches the audio."),u.join(`
1715
- `);let g=1;for(const[f,w]of m.entries()){const b=(h=w.find(s=>s.target.opacityContext))==null?void 0:h.target.opacityContext,k=Fn(f,b),v=w[0].impact;u.push(`### ${g}. [${v.toUpperCase()}] ${k.whatsWrong}`),u.push(""),u.push(`**Why this matters.** ${k.whyItMatters}`),u.push(""),u.push(`**Plain-language fix guidance.** ${k.howToFix}`),u.push(""),u.push(`**Where on the page (${w.length} ${w.length===1?"spot":"spots"}):**`);for(const s of w.slice(0,8))u.push(`- \`${s.target.selector}\``);w.length>8&&u.push(`- (and ${w.length-8} more spots)`),u.push(""),u.push(`*Technical reference for your developer:* axe-core rule \`${f}\` — full docs at https://dequeuniversity.com/rules/axe/4.11/${f}`),u.push(""),g++}return u.push("---"),u.push(""),u.push("## How to use this output"),u.push(""),u.push("Walk through this list with me one issue at a time. For each:"),u.push("1. Help me understand the issue with a real example of who it affects."),u.push("2. Tell me clearly if I can fix it myself, and if so, walk me through it for my platform."),u.push("3. If I need a developer, give me a short paragraph I can paste into an email or message to them."),u.push("4. Help me prioritize — I have limited time and want to fix the riskiest things first."),u.push(""),u.push("Start by asking me which platform I use."),u.join(`
1716
- `)}function Qi(e,t,a,n,o,r,i){const c=e.flatMap(b=>b.violations),d=Sa(c,void 0,e,n,a,o,r,ft(e),i),l=qe(e),p=new Date,m=new Map;for(const b of c){const k=Fe(b.ruleId,b.target.selector);m.has(k)||m.set(k,b)}const u=Array.from(m.values()).sort((b,k)=>{const v={critical:0,serious:1,moderate:2,minor:3};return(v[b.impact]??99)-(v[k.impact]??99)}),g=new Map;for(const b of u){const k=g.get(b.ruleId)??[];k.push(b),g.set(b.ruleId,k)}const h=Array.from(g.entries()).map(([b,k])=>{var C;const v=(C=k.find(F=>F.target.opacityContext))==null?void 0:C.target.opacityContext,s=Fn(b,v),x=k[0].impact,$=k.slice(0,8).map(F=>`<code>${E(F.target.selector)}</code>`).join(", "),A=k.length>8?` <em>(and ${k.length-8} more)</em>`:"";return`
1717
- <section class="rule">
1718
- <div class="rule-header">
1719
- <span class="impact impact-${E(x)}">${E(x)}</span>
1720
- <h3>${E(s.whatsWrong)}</h3>
1721
- </div>
1722
- <p class="why"><strong>Why this matters.</strong> ${E(s.whyItMatters)}</p>
1723
- <p class="how"><strong>How to fix.</strong> ${E(s.howToFix)}</p>
1724
- <p class="where">
1725
- <strong>Where on the page (${k.length} ${k.length===1?"spot":"spots"}):</strong> ${$}${A}
1726
- </p>
1727
- <details class="techy">
1728
- <summary>Technical reference for the developer</summary>
1729
- <p>axe-core rule ID: <code>${E(b)}</code>. Full rule documentation:
1730
- <a href="https://dequeuniversity.com/rules/axe/4.11/${E(b)}">dequeuniversity.com/rules/axe/4.11/${E(b)}</a>.</p>
1731
- </details>
1732
- </section>`}).join(""),f=t==="letter"?d.totals.critical>0?"Hi! I ran an automated accessibility check on our site and found some things I think we should fix. A few are flagged as <strong>critical</strong> — those tend to be the ones that come up in ADA-related lawsuits, so they're worth prioritizing.":d.totals.serious>0?"Hi! I ran an automated accessibility check on our site. We have some serious issues to fix — nothing immediately critical, but real problems that affect real users.":"Hi! I ran an automated accessibility check on our site. The issues found are mostly minor or moderate — worth tidying up but not urgent.":d.totals.critical>0?"This report summarizes the accessibility findings for the page below. <strong>Critical-impact issues</strong> were detected — these are the categories that most commonly drive ADA-related lawsuits and should be prioritized.":d.totals.serious>0?"This report summarizes the accessibility findings for the page below. Serious issues were detected — real problems for real users, though none rise to the critical level.":"This report summarizes the accessibility findings for the page below. Findings are mostly minor or moderate — worth addressing during normal site maintenance.",w=t==="letter"?"Accessibility check":"Accessibility report";return tt(`<!doctype html>
1733
- <html lang="en">
1734
- <head>
1735
- <meta charset="utf-8" />
1736
- <title>${E(w)} — ${E(l)}</title>
1737
- <style>
1738
- body { font: 15px/1.6 -apple-system, system-ui, "Segoe UI", sans-serif; color: #0f172a; max-width: 720px; margin: 24px auto; padding: 0 24px 60px; }
1739
- h1 { font-size: 22px; margin: 0 0 4px; }
1740
- h2 { font-size: 16px; margin-top: 28px; }
1741
- h3 { font-size: 15px; margin: 0; flex: 1; }
1742
- .meta { color: #64748b; font-size: 13px; margin-bottom: 18px; }
1743
- .summary { background: #f8fafc; border: 1px solid #e2e8f0; border-radius: 8px; padding: 14px 18px; margin: 18px 0; }
1744
- .summary .totals { display: flex; gap: 14px; flex-wrap: wrap; margin-top: 8px; font-size: 13px; }
1745
- .summary .totals span { color: #64748b; }
1746
- .summary .totals strong { color: #0f172a; }
1747
- .rule { border: 1px solid #e2e8f0; border-radius: 6px; padding: 14px 18px; margin: 14px 0; background: white; }
1748
- .rule-header { display: flex; align-items: center; gap: 10px; margin-bottom: 10px; }
1749
- .impact { font-size: 11px; padding: 2px 8px; border-radius: 4px; font-weight: 600; text-transform: uppercase; letter-spacing: 0.04em; }
1750
- .impact-critical { background: #fee2e2; color: #991b1b; }
1751
- .impact-serious { background: #ffedd5; color: #9a3412; }
1752
- .impact-moderate { background: #fef9c3; color: #854d0e; }
1753
- .impact-minor { background: #dbeafe; color: #1e40af; }
1754
- .rule p { margin: 8px 0; }
1755
- .where { font-size: 13px; color: #475569; }
1756
- .where code { background: #f1f5f9; padding: 1px 4px; border-radius: 3px; font-size: 12px; }
1757
- details.techy { margin-top: 10px; font-size: 12px; color: #64748b; }
1758
- details.techy summary { cursor: pointer; color: #475569; }
1759
- footer { margin-top: 40px; padding-top: 16px; border-top: 1px solid #e2e8f0; font-size: 12px; color: #475569; }
1760
- @media print { body { max-width: none; margin: 0; padding: 0.5in; } }
1761
- </style>
1762
- </head>
1763
- <body>
1764
- <h1>${E(w)} for ${E(l)}</h1>
1765
- <p class="meta">${t==="letter"?"Ran":"Audit run"} ${E(p.toLocaleString())} · ${u.length} issue${u.length===1?"":"s"} grouped into ${g.size} ${g.size===1?"category":"categories"}</p>
1766
-
1767
- <p>${f}</p>
1768
-
1769
- <div class="summary">
1770
- <p style="margin: 0;"><strong>${E(Tr[d.risk])}.</strong> ${E(Er[d.risk])}</p>
1771
- <div class="totals">
1772
- ${d.totals.critical>0?`<span><strong>${d.totals.critical}</strong> critical</span>`:""}
1773
- ${d.totals.serious>0?`<span><strong>${d.totals.serious}</strong> serious</span>`:""}
1774
- ${d.totals.moderate>0?`<span><strong>${d.totals.moderate}</strong> moderate</span>`:""}
1775
- ${d.totals.minor>0?`<span><strong>${d.totals.minor}</strong> minor</span>`:""}
1776
- ${d.totals.unique===0?"<span>No automated issues detected — manual review still recommended.</span>":""}
1777
- </div>
1778
- </div>
1779
-
1780
- <h2>${t==="letter"?"What I found":"Detailed findings"}</h2>
1781
- ${h.length>0?h:"<p>No automated issues detected on this page.</p>"}
1782
-
1783
- ${t==="letter"?`
1784
- <h2>What I&apos;d like you to do</h2>
1785
- <ol>
1786
- <li>Take a look at the items above and let me know which ones you can address.</li>
1787
- <li>For the ones marked <strong>critical</strong> — those tend to be the issues that show up in ADA-related lawsuit complaints, so I&apos;d prioritize those if you can.</li>
1788
- <li>If anything is unclear or you need more detail, the technical references inside each section link to the full rule documentation. The whole audit was generated by an automated tool that runs the same checks Deque, IBM, and Microsoft all use.</li>
1789
- </ol>
1790
-
1791
- <p>Thanks for taking a look!</p>
1792
- `:`
1793
- <h2>Recommended next steps</h2>
1794
- <ol>
1795
- <li>Address <strong>critical</strong> findings first — these are the categories most commonly cited in ADA-related accessibility lawsuits.</li>
1796
- <li>Address <strong>serious</strong> findings during the next site update cycle.</li>
1797
- <li>Save or print this report for your records. It documents an automated audit was performed on ${E(p.toLocaleDateString())}.</li>
1798
- <li>Re-run the audit after fixes to verify resolution and catch any regressions.</li>
1799
- </ol>
1800
- `}
1801
-
1802
- <footer>
1803
- <p>Generated by ${E(Ie)} on ${E(p.toISOString())}. Three evaluation layers ran: axe-core (rule-based), wcagcheckr DOM analyzers (state-matrix iteration + structural heuristics for criteria axe doesn't cover), and AI walkthroughs (real keyboard input + screenshot judgment for the 6 criteria neither rule-based nor static-DOM analysis can decide). All 50 applicable WCAG 2.1 AA criteria have an evaluation path. Content-meaning criteria (caption accuracy, alt-text correctness, sensory cues) benefit from a human spot-check before any formal conformance claim.</p>
1804
- </footer>
1805
- </body>
1806
- </html>`)}function Zh(e){if(!e||e.length===0)return`
1807
- <h2 id="manual">5. Manual assessment results</h2>
1808
- <p style="font-size: 10pt; color: #475569;">
1809
- No manual workflows were completed for this audit. wcagcheckr's three layers (axe-core, our
1810
- DOM analyzers, AI walkthroughs) already cover all 50 WCAG 2.1 AA criteria structurally; the
1811
- optional Guided Tests workflows below let you record explicit human verification for
1812
- content-meaning criteria (caption accuracy, alt-text correctness, sensory cues) — useful
1813
- when the audit needs to anchor to specific named auditors for formal conformance.
1814
- When manual workflows are completed, their results are integrated into both the executive
1815
- summary's compliance grade and this section's per-criterion findings.
1816
- </p>`;const t=new Map(e.map(c=>[c.workflowId,c])),a=Pe.map(c=>ep(c,t.get(c.id))).filter(c=>c!==null).join("");let n=0,o=0,r=0,i=0;for(const c of Pe){i+=c.steps.length;const d=t.get(c.id);if(d)for(const l of c.steps){const p=d.steps[l.id];p&&(r++,p.status==="fail"&&(l.severity==="required"?n++:o++))}}return`
1817
- <h2 id="manual">5. Manual assessment results</h2>
1818
- <p style="font-size: 10pt; color: #475569; margin-bottom: 8pt;">
1819
- Manual workflows performed by the auditor. ${r} of ${i} steps answered
1820
- across ${e.length} workflow${e.length===1?"":"s"}.
1821
- ${n>0?`<strong style="color: #b91c1c;">${n} required step${n===1?"":"s"} failed</strong> — each is a confirmed WCAG breach contributing to the compliance grade above.`:"No required steps failed."}
1822
- ${o>0?` ${o} advisory step${o===1?"":"s"} failed (best-practice findings).`:""}
1823
- </p>
1824
- ${a}`}function ep(e,t){if(!t)return null;const a=[];for(const l of e.steps){const p=t.steps[l.id];p&&a.push({step:l,status:p.status,notes:p.notes})}if(a.length===0)return null;const n=a.filter(l=>l.status==="pass").length,o=a.filter(l=>l.status==="fail").length,r=a.filter(l=>l.status==="skip").length,i=a.filter(l=>l.status==="not-applicable").length,d=a.filter(l=>l.status==="fail").map(l=>`
1825
- <tr>
1826
- <td><span class="impact impact-${l.step.severity==="required"?"serious":"moderate"}">${E(l.step.severity)}</span></td>
1827
- <td>${l.step.wcag?`<code>${E(l.step.wcag)}</code>`:"—"}</td>
1828
- <td><strong>${E(l.step.question)}</strong>${l.notes?`<br/><span style="font-size: 9pt; color: #475569;">Auditor notes: ${E(l.notes)}</span>`:""}</td>
1829
- </tr>
1830
- `).join("");return`
1831
- <h3>${E(e.name)}</h3>
1832
- <p style="font-size: 10pt; color: #475569; margin: 0 0 6pt;">${E(e.blurb)}</p>
1833
- <p style="font-size: 10pt; margin: 0 0 6pt;">
1834
- <span class="cat-pass">${n} passed</span>
1835
- ${o>0?` · <span class="cat-fail">${o} failed</span>`:""}
1836
- ${r>0?` · <span style="color: #64748b;">${r} skipped</span>`:""}
1837
- ${i>0?` · <span style="color: #64748b;">${i} N/A</span>`:""}
1838
- · ${a.length} of ${e.steps.length} answered
1839
- </p>
1840
- ${o>0?`
1841
- <table>
1842
- <thead><tr><th style="width: 80pt;">Severity</th><th style="width: 70pt;">WCAG</th><th>Failed check + auditor notes</th></tr></thead>
1843
- <tbody>${d}</tbody>
1844
- </table>
1845
- `:""}`}function Ut(e,t,a="defense",n,o,r,i,c,d,l,p,m){var N,O,W;const u=Qh[a],g=((N=e[0])==null?void 0:N.componentId)??"unknown",h=qe(e),f=i??e.reduce((P,V)=>P+V.durationMs,0),w=e.flatMap(P=>P.violations),b=n&&n.length>0?{runs:n,workflows:Pe}:void 0,k=et(w,b,e,l,c,d,p,ft(e),m),v=k.score,s=new Date,x=new Map;for(const P of w){const V=Fe(P.ruleId,P.target.selector),M=`${P.currentState.pseudoState} · ${P.currentState.theme} · ${P.currentState.direction}`,j=x.get(V);if(j){j._states.includes(M)||j._states.push(M);continue}x.set(V,{...P,_states:[M]})}const $=Array.from(x.values()).sort((P,V)=>{const M={critical:0,serious:1,moderate:2,minor:3};return(M[P.impact]??99)-(M[V.impact]??99)}),A=zh(e),C=new Map;for(const P of A)for(const V of P.violations){const M=Fe(V.ruleId,V.target.selector);C.has(M)||C.set(M,V._idx)}const F=$.map((P,V)=>`
1846
- <tr>
1847
- <td>${V+1}</td>
1848
- <td><span class="impact impact-${E(P.impact)}">${E(P.impact)}</span></td>
1849
- <td><code>${E(P.ruleId)}</code></td>
1850
- <td>${E(P.wcagCriterion)} ${E(P.wcagLevel)}</td>
1851
- <td>${E(P.description)}</td>
1852
- <td><code class="sel">${E(P.target.selector)}</code></td>
1853
- <td>${E(P._states.join(", "))}</td>
1854
- </tr>`).join(""),T=l??new Set,I=new Set(w.filter(P=>!T.has(P.matchKey)).map(P=>P.ruleId)),D=new Set(I);for(const P of e){const V=P.axeRulesEvaluated;if(V){for(const M of V.passed)D.add(M.ruleId);for(const M of V.inapplicable)D.add(M.ruleId);for(const M of V.incomplete)D.add(M.ruleId)}}const S=new Map;for(const P of p??[])S.set(P.criterionId,P.verdict);const _=Bi.map(P=>{const{conformance:V,hits:M}=Hi(P,I,D,c,S.get(P.ref));return`
1855
- <tr class="${V==="Supports"?"supports":V==="Partially Supports"?"partial":V==="Not Evaluated"?"not-evaluated":"na"}">
1856
- <td><code>${E(P.ref)}</code></td>
1857
- <td>${E(P.title)} <span class="lvl">(${P.level})</span></td>
1858
- <td>${V}</td>
1859
- <td>${M.length>0?`Detected violations of: ${M.map(q=>`<code>${E(q)}</code>`).join(", ")}`:V==="Not Applicable"?"Not addressable by automated audit; requires manual review.":"No automated violations detected."}</td>
1860
- </tr>`}).join("");return tt(`<!doctype html>
1861
- <html lang="en">
1862
- <head>
1863
- <meta charset="utf-8" />
1864
- <title>${E(u.title)} — ${E(g)}</title>
1865
- <style>
1866
- *, *::before, *::after { box-sizing: border-box; }
1867
- body { font: 11pt/1.55 -apple-system, system-ui, "Segoe UI", sans-serif; color: #0f172a; max-width: 8in; margin: 0.5in auto; padding: 0 0.25in; }
1868
- h1 { font-size: 22pt; margin: 0 0 4pt; }
1869
- h2 { font-size: 14pt; margin: 24pt 0 8pt; padding-bottom: 4pt; border-bottom: 1px solid #cbd5e1; page-break-after: avoid; }
1870
- h3 { font-size: 12pt; margin: 14pt 0 6pt; page-break-after: avoid; }
1871
- .doc-meta { font-size: 10pt; color: #475569; margin-bottom: 12pt; }
1872
- .toc { background: #f8fafc; border: 1px solid #e2e8f0; padding: 10pt 14pt; border-radius: 4pt; margin: 14pt 0; }
1873
- .toc ol { margin: 4pt 0 0; padding-left: 20pt; }
1874
- .toc a { color: #1e40af; text-decoration: none; }
1875
- .exec { border: 1px solid #cbd5e1; border-radius: 4pt; overflow: hidden; margin: 12pt 0; display: flex; }
1876
- .exec-grade { width: 1.4in; display: flex; align-items: center; justify-content: center; color: white; font-size: 56pt; font-weight: 700; line-height: 1; }
1877
- .exec-body { flex: 1; padding: 14pt 18pt; }
1878
- .risk-tier { display: inline-block; padding: 2pt 10pt; border-radius: 12pt; font-size: 10pt; font-weight: 600; margin-bottom: 6pt; }
1879
- .categories { display: grid; grid-template-columns: 1fr 1fr; gap: 4pt 16pt; margin: 8pt 0; font-size: 10pt; }
1880
- .cat-pass { color: #15803d; }
1881
- .cat-fail { color: #b91c1c; font-weight: 600; }
1882
- .cat-unchecked { color: #b45309; }
1883
- table { width: 100%; border-collapse: collapse; margin: 6pt 0 10pt; font-size: 9.5pt; }
1884
- th, td { border: 1px solid #cbd5e1; padding: 4pt 7pt; text-align: left; vertical-align: top; }
1885
- th { background: #f1f5f9; }
1886
- td.sel, code { font-family: "SF Mono", Menlo, monospace; font-size: 9pt; word-break: break-all; }
1887
- .impact { font-size: 8.5pt; padding: 1pt 5pt; border-radius: 2pt; font-weight: 600; text-transform: uppercase; letter-spacing: 0.04em; }
1888
- .impact-critical { background: #fee2e2; color: #991b1b; }
1889
- .impact-serious { background: #ffedd5; color: #9a3412; }
1890
- .impact-moderate { background: #fef9c3; color: #854d0e; }
1891
- .impact-minor { background: #dbeafe; color: #1e40af; }
1892
- tr.supports td:nth-child(3) { color: #15803d; font-weight: 600; }
1893
- tr.partial td:nth-child(3) { color: #b45309; font-weight: 600; }
1894
- tr.na td:nth-child(3) { color: #64748b; }
1895
- .lvl { color: #475569; font-weight: 400; font-size: 9pt; }
1896
- .disclaimer { background: #fef3c7; border: 1px solid #f59e0b; padding: 10pt 14pt; border-radius: 3pt; margin: 16pt 0; font-size: 10pt; }
1897
- .evidence-state { margin: 12pt 0 18pt; page-break-inside: avoid; }
1898
- .evidence-state h3 { font-size: 11pt; margin-bottom: 4pt; }
1899
- .evidence-state .caption { font-size: 9.5pt; color: #475569; margin-bottom: 4pt; }
1900
- .evidence-frame { display: block; width: 100%; border: 1px solid #cbd5e1; }
1901
- .evidence-frame svg { display: block; width: 100%; height: auto; }
1902
- .evidence-frame svg rect.violation-mark { fill: rgba(220, 38, 38, 0.10); stroke: #dc2626; stroke-width: 3; }
1903
- .evidence-frame svg text.violation-num { font: bold 14px ui-monospace, Menlo, monospace; fill: white; }
1904
- .evidence-frame svg rect.label-bg { fill: #dc2626; }
1905
- .methodology { font-size: 10pt; }
1906
- .methodology dt { font-weight: 600; margin-top: 6pt; }
1907
- .methodology dd { margin: 0 0 4pt 0; }
1908
- footer { margin-top: 28pt; padding-top: 8pt; border-top: 1px solid #cbd5e1; font-size: 8.5pt; color: #64748b; }
1909
- @media print { body { margin: 0; max-width: none; } .toc { page-break-after: always; } table, tr { page-break-inside: avoid; } }
1910
- </style>
1911
- </head>
1912
- <body>
1913
-
1914
- <h1>${E(u.title)}</h1>
1915
- <p class="doc-meta">
1916
- <strong>Subject:</strong> <code>${E(g)}</code> &nbsp;·&nbsp;
1917
- <strong>URL:</strong> ${E(h)}<br/>
1918
- <strong>Audit date:</strong> ${E(s.toLocaleString())} &nbsp;·&nbsp;
1919
- <strong>Audit engine:</strong> axe-core ${E(((O=e[0])==null?void 0:O.axeVersion)??"n/a")} &nbsp;·&nbsp;
1920
- <strong>Tool:</strong> ${E(Ie)} v${E(Ee())}
1921
- </p>
1922
-
1923
- <nav class="toc">
1924
- <strong>Contents</strong>
1925
- <ol>
1926
- <li><a href="#exec">Executive summary</a></li>
1927
- <li><a href="#methodology">Methodology &amp; scope</a></li>
1928
- <li><a href="#findings">Detailed findings (automated)</a></li>
1929
- <li><a href="#evidence">Visual evidence (per-state screenshots)</a></li>
1930
- <li><a href="#manual">Manual assessment results</a></li>
1931
- <li><a href="#conformance">WCAG 2.1 conformance assessment</a></li>
1932
- <li><a href="#remediation">${a==="evidence"?"Recommended approach before legal action":"Remediation plan"}</a></li>
1933
- <li><a href="#disclaimer">Disclaimer &amp; limitations</a></li>
1934
- </ol>
1935
- </nav>
1936
-
1937
- <h2 id="exec">1. Executive summary</h2>
1938
- <div class="exec">
1939
- <div class="exec-grade" style="background: ${Xh[k.combined]};">${k.combined}</div>
1940
- <div class="exec-body">
1941
- <span class="risk-tier" style="background: ${Yh[v.risk]}; color: ${Jh[v.risk]};">
1942
- ${E(Kh[v.risk])}
1943
- </span>
1944
- <p style="margin: 0 0 6pt;"><strong>${v.totals.unique} unique violations detected</strong> across ${e.length} state combinations
1945
- (${v.totals.critical} critical · ${v.totals.serious} serious · ${v.totals.moderate} moderate · ${v.totals.minor} minor).</p>
1946
- <p style="margin: 0; font-size: 10pt; color: #475569;">${E(xc[v.risk])}</p>
1947
- </div>
1948
- </div>
1949
- ${r&&(r.lead||r.body||r.closer)?`
1950
- <div style="margin-top: 12pt; padding: 12pt 14pt; border-left: 4px solid #2563eb; background: #f0f6ff; border-radius: 0 4pt 4pt 0;">
1951
- <p style="margin: 0 0 6pt; font-size: 10pt; color: #1e40af; text-transform: uppercase; letter-spacing: 0.04em;">
1952
- AI-generated narrative summary (${E(r.model)})
1953
- </p>
1954
- ${r.lead?`<p style="margin: 0 0 8pt; font-size: 11.5pt; font-weight: 500;">${E(r.lead)}</p>`:""}
1955
- ${r.body?r.body.split(/\n{2,}/).map(P=>`<p style="margin: 0 0 6pt;">${E(P.trim())}</p>`).join(`
1956
- `):""}
1957
- ${r.closer?`<p style="margin: 8pt 0 0; font-style: italic;">${E(r.closer)}</p>`:""}
1958
- <p style="margin: 6pt 0 0; font-size: 9pt; color: #475569;">
1959
- This narrative was generated by an LLM from the audit's structured findings. The numerical
1960
- data in §1 above and the per-violation details in §3 are the authoritative record.
1961
- </p>
1962
- </div>`:""}
1963
-
1964
- <h3>Per-category breakdown (top-6 lawsuit-magnet categories)</h3>
1965
- <div class="categories">
1966
- ${v.categories.map(P=>{const V=P.status==="pass"?"✓":P.status==="fail"?"✗":"⚠",M=P.status==="pass"?"cat-pass":P.status==="fail"?"cat-fail":"cat-unchecked",j=P.status==="fail"?` (${P.violationCount})`:P.needsManualCheck?" — requires manual review":"";return`<div class="${M}">${V} ${E(P.label)}${E(j)}</div>`}).join("")}
1967
- </div>
1968
-
1969
- <h2 id="methodology">2. Methodology &amp; scope</h2>
1970
- <dl class="methodology">
1971
- <dt>Audit engine</dt>
1972
- <dd>axe-core ${E(((W=e[0])==null?void 0:W.axeVersion)??"n/a")} (industry-standard, used by Deque, IBM, Microsoft, and Google's Lighthouse).
1973
- Rule sets enabled: WCAG 2.0 A/AA, WCAG 2.1 A/AA, WCAG 2.2 A/AA, axe-core best-practice.</dd>
1974
- <dt>State coverage</dt>
1975
- <dd>${e.length} state combinations were audited, including pseudo-states (<code>:hover</code>, <code>:focus</code>, <code>:focus-visible</code>, <code>:active</code>, <code>:disabled</code>),
1976
- color-scheme themes (<code>prefers-color-scheme: dark</code>, <code>forced-colors: active</code>),
1977
- text direction (LTR / RTL), and viewport breakpoints (mobile / tablet / desktop).
1978
- Audits at non-default states are uncommon among automated tools and represent significant additional WCAG coverage relative to single-state audits.</dd>
1979
- <dt>Audit duration</dt>
1980
- <dd>${(f/1e3).toFixed(1)} seconds across ${e.length} states (${(f/Math.max(1,e.length)).toFixed(0)}ms per state).</dd>
1981
- <dt>Scope</dt>
1982
- <dd>Component / region: <code>${E(g)}</code></dd>
1983
- <dt>What this audit covers</dt>
1984
- <dd>All 50 applicable WCAG 2.1 AA criteria evaluated across three layers: <strong>axe-core</strong> (rule-based DOM checks — color contrast, image alt presence, form labels, accessible names, document structure, ID uniqueness, ARIA validity), <strong>${E(Ie)} DOM analyzers</strong> (state-matrix iteration through hover / focus / active / disabled states + structural heuristics for criteria axe doesn't reach — pointer gestures, motion actuation, reflow, autoplay, character key shortcuts, redundant entry, sensory cues, text spacing, images-of-text candidates), and <strong>AI walkthroughs</strong> (real keyboard input + screenshot-by-screenshot vision judgment for the 6 criteria neither rule-based nor static-DOM analysis can decide — focus order, no keyboard trap, focus visible, meaningful sequence, non-text contrast, label-in-name).</dd>
1985
- <dt>What still requires human spot-checks</dt>
1986
- <dd>Content meaning, not structural correctness: whether caption text actually matches the audio, whether alt text accurately describes the image's purpose, whether sensory phrasing ("click the red button") has an inclusive alternative. The ${E(Ie)} Guided Tests workflows provide a structured manual-audit path for these content-meaning criteria.</dd>
1987
- </dl>
1988
-
1989
- <h2 id="findings">3. Detailed findings</h2>
1990
- ${$.length===0?"<p>No automated violations were detected during this audit.</p>":`<table>
1991
- <thead>
1992
- <tr><th>#</th><th>Impact</th><th>Rule</th><th>WCAG</th><th>Description</th><th>Selector</th><th>States</th></tr>
1993
- </thead>
1994
- <tbody>${F}</tbody>
1995
- </table>`}
1996
-
1997
- ${jh(v.walkthroughFindings,v.walkthroughAcknowledgements,d??[])}
1998
-
1999
- <h2 id="evidence">4. Visual evidence (per-state screenshots)</h2>
2000
- ${A.length===0?'<p style="font-size: 10pt; color: #64748b;">No per-state screenshots were captured for this audit (no states had violations, or screenshot capture failed).</p>':`<p class="caption">Top ${A.length} state${A.length===1?"":"s"} by violation count shown below. Red rectangles mark violation locations; numbers correspond to entries in §3.</p>`+A.map(P=>{const V=P.violations.filter(M=>M.target.boundingRect).map(M=>{const j=M.target.boundingRect,q=String(M._idx).length*8+14,z=22;return[`<rect class="violation-mark" x="${j.x}" y="${j.y}" width="${j.w}" height="${j.h}" />`,`<rect class="label-bg" x="${j.x}" y="${Math.max(0,j.y-z)}" width="${q}" height="${z}" rx="2" />`,`<text class="violation-num" x="${j.x+6}" y="${Math.max(0,j.y-z)+16}">${M._idx}</text>`].join("")}).join("");return`
2001
- <div class="evidence-state">
2002
- <h3>State: ${E(P.stateLabel)} (${P.violations.length} violation${P.violations.length===1?"":"s"})</h3>
2003
- <div class="evidence-frame">
2004
- <svg viewBox="0 0 ${Xo} ${Qo}" xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMinYMin meet">
2005
- <image href="${P.screenshotDataUrl}" x="0" y="0" width="${Xo}" height="${Qo}" preserveAspectRatio="xMidYMid slice" />
2006
- ${V}
2007
- </svg>
2008
- </div>
2009
- </div>`}).join("")}
2010
-
2011
- ${Zh(n)}
2012
-
2013
- <h2 id="conformance">6. WCAG 2.1 conformance assessment</h2>
2014
- <p style="font-size: 10pt;">Per-criterion conformance based on automated detection. Conformance values follow the VPAT 2.5-INT vocabulary.${t&&t.baselineSnapshotMeta?" Comparison against an accepted baseline is available; see Section 6.":""}</p>
2015
- <table>
2016
- <thead><tr><th>Criterion</th><th>Title</th><th>Conformance</th><th>Notes</th></tr></thead>
2017
- <tbody>${_}</tbody>
2018
- </table>
2019
-
2020
- ${(()=>{const P=o!==void 0,V=P?"8":"7",M=P?"9":"8",j=P?`<h2 id="audit-history">7. Audit history</h2>
2021
- <p style="font-size: 10pt; margin-bottom: 8pt;">Chronological record of audits this user has run, with cryptographic hashes of each audit's identifying fields (component, page URL, grade, severity totals, axe version, timestamp, state-matrix size). Hashes are SHA-256 of canonical-JSON serialization, so any tampering with a logged audit's identity is detectable client-side. Entries marked <em>Anchored</em> additionally carry a third-party RFC 3161 trusted timestamp issued by the named TSA — those entries cannot be backdated.</p>
2022
- ${o&&o.length>0?`<table>
2023
- <thead>
2024
- <tr>
2025
- <th>Captured</th>
2026
- <th>Component</th>
2027
- <th>Page</th>
2028
- <th>Grade</th>
2029
- <th>Crit</th>
2030
- <th>Sev</th>
2031
- <th>States</th>
2032
- <th>Hash (first 12)</th>
2033
- <th>Source</th>
2034
- </tr>
2035
- </thead>
2036
- <tbody>${o.map(z=>`
2037
- <tr>
2038
- <td style="white-space: nowrap;">${E(z.capturedAt)}</td>
2039
- <td><code>${E(z.componentId)}</code></td>
2040
- <td style="word-break: break-all;">${E(z.pageUrl)}</td>
2041
- <td><strong>${E(z.grade)}</strong></td>
2042
- <td>${z.totals.critical}</td>
2043
- <td>${z.totals.serious}</td>
2044
- <td>${z.statesAudited}</td>
2045
- <td><code title="${E(z.hash)}">${E(z.hash.slice(0,12))}…</code></td>
2046
- <td>${z.receipt?`RFC 3161 (${E(z.receipt.tsaName)})`:"Local"}</td>
2047
- </tr>`).join("")}
2048
- </tbody>
2049
- </table>`:'<p style="color: #64748b; font-style: italic;">No prior audits recorded — this is the first audit on record for this installation.</p>'}
2050
- `:"",q=a==="evidence"?`<h2 id="remediation">${V}. Recommended approach before legal action</h2>
2051
- <div style="background: #f0f9ff; border: 1px solid #38bdf8; padding: 12pt 16pt; border-radius: 4pt; font-size: 10.5pt;">
2052
- <p style="margin: 0 0 8pt;"><strong>Most businesses are unaware their digital properties have accessibility defects.</strong> Many will fix them once notified. A good-faith notice-and-cure approach is more likely to resolve the underlying accessibility barrier (which is the actual purpose of disability-rights law) and, where remediation does not occur, strengthens any subsequent legal claim by establishing both notice and a reasonable opportunity to comply.</p>
2053
- <p style="margin: 0 0 8pt;"><strong>Recommended steps before considering legal action:</strong></p>
2054
- <ol style="margin: 0 0 8pt; padding-left: 20pt;">
2055
- <li><strong>Send written notice to the site owner / business operator.</strong> Include this evidence bundle as an attachment. Identify yourself, the date you encountered the barrier, the specific access need affected (e.g., screen-reader use, keyboard-only navigation, low-vision contrast), and a reasonable timeframe for response (commonly 30–60 days, depending on jurisdiction and severity).</li>
2056
- <li><strong>Offer to discuss remediation.</strong> Many businesses don't have an accessibility lead — pointing them at the WCAG criteria in §5 of this document and the per-rule canonical fixes (axe-core's documentation, linked from each violation's "More info") gives them a starting point.</li>
2057
- <li><strong>Document the response (or lack of one).</strong> Save the original notice, any reply, dates, and any remediation activity (or absence of it).</li>
2058
- <li><strong>If after the notice period the business has not engaged or remediated</strong>, the documented good-faith notice combined with this evidence bundle materially strengthens an ADA Title III, EAA, EN 301 549, AODA, or analogous claim, depending on jurisdiction.</li>
2059
- </ol>
2060
- <p style="margin: 0; font-size: 9.5pt; color: #475569;">This guidance is general and not legal advice. Specific procedural requirements vary by jurisdiction (e.g., some US states require pre-suit notice under "Unruh Act" amendments; others do not). Consult qualified counsel about the procedural posture appropriate for your situation.</p>
2061
- </div>`:`<h2 id="remediation">${V}. Remediation plan</h2>
2062
- <p>Each violation in §3 has a documented canonical fix pattern. The remediation workflow we recommend:</p>
2063
- <ol>
2064
- <li>Findings are classified by severity. Address critical and serious findings first.</li>
2065
- <li>For each rule, ${E(Ie)} produces a structured fix prompt that can be processed by a code-fluent AI assistant operating against the codebase. The fix prompt includes per-violation context (selector, state, recipe), pre-flight safety checks (clean git working tree, atomic commits per fix), and explicit constraints (no scope creep, native HTML preferred over ARIA, fix state-specific failures in state-specific styles).</li>
2066
- <li>After remediation, re-run the audit to verify each violation is resolved without introducing regressions.</li>
2067
- <li>Manual workflows (keyboard, screen-reader, focus-management, forms) should be re-completed via the Guided Tests panel.</li>
2068
- <li>Once resolved, the audited state should be accepted as a baseline; future audits surface only NEW debt vs. that baseline.</li>
2069
- </ol>`;return`${j}
2070
-
2071
- ${q}
2072
-
2073
- <h2 id="disclaimer">${M}. Disclaimer &amp; limitations</h2>`})()}
2074
- <div class="disclaimer">
2075
- <p style="margin: 0 0 6pt;"><strong>${E(u.disclaimerHeading)}</strong></p>
2076
- <p style="margin: 0 0 6pt;">${u.disclaimerBody}</p>
2077
- <p style="margin: 0;">This document represents detected violations at the time and scope of audit. Subsequent changes to the audited resource may produce different results. The presence or absence of detected violations in this report is not, by itself, ${a==="defense"?"a defense against":"a determination of"} any specific accessibility claim, regulation, or legal action. This document is provided for ${E(u.documentLabel)} purposes.</p>
2078
- </div>
2079
-
2080
- <footer>
2081
- Generated by ${E(Ie)} v${E(Ee())} on ${E(s.toISOString())}.
2082
- Audit run identifier: ${E(s.getTime().toString(36))}-${E(g.replace(/[^a-z0-9]/gi,"").slice(0,8))}.
2083
- </footer>
2084
-
2085
- </body>
2086
- </html>`)}async function tp(){const t=(await chrome.storage.local.get("aiConfig")).aiConfig;return{...ms,...t??{}}}async function ap(e){return xa(e.map(t=>t.componentId))}async function an(e,t,a,n){const o=await tp();if(!o.enabled||!o.apiKey||e.length===0)return null;const r=e.flatMap(p=>p.violations),i=et(r,void 0,e,void 0,n),c=i.score,d=c.categories.filter(p=>p.status==="fail").sort((p,m)=>m.violationCount-p.violationCount).slice(0,3).map(p=>p.label),l=e[0];return Ui({framing:t,riskTier:c.risk,grade:i.combined,totals:{critical:c.totals.critical,serious:c.totals.serious,moderate:c.totals.moderate,minor:c.totals.minor,unique:c.totals.unique},riskDrivers:d,pageUrl:(l==null?void 0:l.pageUrl)??(l==null?void 0:l.scope)??"",auditDate:(l==null?void 0:l.startedAt)??new Date().toISOString(),priorAuditCount:a},o)}const np={json:"exportJson",sarif:"exportSarif",junit:"exportJunit","html-print":"exportHtmlPrint",vpat:"exportVpat","ai-prompt":"exportAiPrompts","ai-prompt-owner":"exportAiPrompts","ai-prompt-site-crawl":"exportAiPrompts","defense-bundle":"exportDefenseBundle","evidence-bundle":"exportEvidenceBundle","developer-letter":"exportDeveloperLetter","owner-report":"exportOwnerReport","accessibility-statement-markdown":"exportEaaStatement","accessibility-statement-html":"exportEaaStatement","deposition-packet":"exportDepositionPacket","methodology-doc":"exportMethodologyDoc","conformance-crosswalk":"exportConformanceCrosswalk","ticket-bundle":"exportTicketBundle","executive-report":"exportExecutiveReport"};function op(){return $e("EXPORT_REQUEST",async e=>{var a;if(await He())return{type:"EXPORT_RESPONSE",format:e.format,content:"wcagcheckr is in private build phase. A team license is required to export reports."};const t=np[e.format];if(t){const n=await pe();if(!he(n,t))return{type:"EXPORT_RESPONSE",format:e.format,content:`The ${e.format} export format is not available on your current plan.`}}if(e.siteCrawlSource&&e.format!=="ai-prompt-site-crawl"){const n=await Zt();if(!n||n.length===0)return{type:"EXPORT_RESPONSE",format:e.format,content:"No site-crawl results found in storage. Run a site crawl from the Crawl tab first, then try this export again."};e.results=n.flatMap(o=>o.results??[])}if(e.format==="sarif")return{type:"EXPORT_RESPONSE",format:"sarif",content:JSON.stringify(Gi(e.results,e.delta),null,2)};if(e.format==="junit")return{type:"EXPORT_RESPONSE",format:"junit",content:ji(e.results,e.delta)};if(e.format==="html-print")return{type:"EXPORT_RESPONSE",format:"html-print",content:Kn(e.results,e.delta,e.wallClockMs)};if(e.format==="vpat"){const n=await Le(e.results,e.auditTargetId?[e.auditTargetId]:[]),o=new Set(n.walkthroughAcks.map(i=>`${i.criterionId}::${i.pageUrl}`)),r=n.walkthroughs.map(i=>o.has(`${i.criterionId}::${i.pageUrl}`)?{...i,verdict:"pass",reasoning:`Human verified: ${i.reasoning}`}:i);return{type:"EXPORT_RESPONSE",format:"vpat",content:qi(e.results,e.delta,r,n.acknowledgedMatchKeys,n.humanCriterionVerdicts,n.incompleteResolutions)}}if(e.format==="ai-prompt"){const n=await Cc();let o="";const r=[];try{const c=((a=e.results[0])==null?void 0:a.componentId)??"",d=c?await ea(c):[];for(const l of d)r.push({criterionId:l.criterionId,verdict:l.verdict,reasoning:l.reasoning,pageUrl:l.pageUrl});o=Zi(d)}catch(c){console.warn("[report-exporter] walkthrough render skipped:",c)}const i=zi(e.results,e.delta,e.manualRuns,e.siteCrawlReport,e.dismissedKeys,e.incompleteResolutions,n,r,e.acknowledgedKeys);return{type:"EXPORT_RESPONSE",format:"ai-prompt",content:o?`${i}
2087
-
2088
- ${o}`:i}}if(e.format==="defense-bundle"){const n=await Tt(),o=await Le(e.results,e.auditTargetId?[e.auditTargetId]:[]),r=await an(e.results,"defense",n.length,o.walkthroughs);return{type:"EXPORT_RESPONSE",format:"defense-bundle",content:Ut(e.results,e.delta,"defense",e.manualRuns,n,r,e.wallClockMs,o.walkthroughs,o.walkthroughAcks,o.acknowledgedMatchKeys,o.humanCriterionVerdicts,o.incompleteResolutions)}}if(e.format==="deposition-packet"){const n=await Tt(),o=await Le(e.results,e.auditTargetId?[e.auditTargetId]:[]),r=await an(e.results,"defense",n.length,o.walkthroughs),i=await ga().catch(()=>null);return{type:"EXPORT_RESPONSE",format:"deposition-packet",content:(await Ni({results:e.results,delta:e.delta,manualRuns:e.manualRuns,aiSummary:r,licenseId:i??void 0,wallClockMs:e.wallClockMs,interactiveAuditResults:o.walkthroughs,walkthroughAcks:o.walkthroughAcks,acknowledgedMatchKeys:o.acknowledgedMatchKeys,humanCriterionVerdicts:o.humanCriterionVerdicts,incompleteResolutions:o.incompleteResolutions})).html}}if(e.format==="methodology-doc")return{type:"EXPORT_RESPONSE",format:"methodology-doc",content:wh({results:e.results,manualRuns:e.manualRuns})};if(e.format==="conformance-crosswalk")return{type:"EXPORT_RESPONSE",format:"conformance-crosswalk",content:Sh({results:e.results})};if(e.format==="ticket-bundle")return{type:"EXPORT_RESPONSE",format:"ticket-bundle",content:Eh({results:e.results})};if(e.format==="executive-report"){const n=await Le(e.results,e.auditTargetId?[e.auditTargetId]:[]);return{type:"EXPORT_RESPONSE",format:"executive-report",content:Dh(e.results,{...e.executiveInputs??{},interactiveAuditResults:n.walkthroughs,walkthroughAcks:n.walkthroughAcks,acknowledgedMatchKeys:n.acknowledgedMatchKeys,humanCriterionVerdicts:n.humanCriterionVerdicts,incompleteResolutions:n.incompleteResolutions})}}if(e.format==="evidence-bundle"){const n=await Tt(),o=await ap(e.results),r=await an(e.results,"evidence",n.length,o);return{type:"EXPORT_RESPONSE",format:"evidence-bundle",content:Ki(e.results,e.delta,e.manualRuns,n,r,e.wallClockMs,o)}}if(e.format==="developer-letter"){const n=await Le(e.results,e.auditTargetId?[e.auditTargetId]:[]);return{type:"EXPORT_RESPONSE",format:"developer-letter",content:Yi(e.results,n.walkthroughs,n.acknowledgedMatchKeys,n.walkthroughAcks,n.humanCriterionVerdicts,n.incompleteResolutions)}}if(e.format==="owner-report"){const n=await Le(e.results,e.auditTargetId?[e.auditTargetId]:[]);return{type:"EXPORT_RESPONSE",format:"owner-report",content:Ji(e.results,n.walkthroughs,n.acknowledgedMatchKeys,n.walkthroughAcks,n.humanCriterionVerdicts,n.incompleteResolutions)}}if(e.format==="ai-prompt-owner"){const n=await Le(e.results,e.auditTargetId?[e.auditTargetId]:[]);return{type:"EXPORT_RESPONSE",format:"ai-prompt-owner",content:Xi(e.results,n.walkthroughs,n.acknowledgedMatchKeys,n.walkthroughAcks,n.humanCriterionVerdicts,n.incompleteResolutions)}}if(e.format==="accessibility-statement-markdown"||e.format==="accessibility-statement-html"){if(!e.statementInputs)return{type:"EXPORT_RESPONSE",format:e.format,content:"# Accessibility statement — error\n\nMissing `statementInputs` payload. The accessibility-statement export needs organization info (name, contact, conformance status). Provide it via the side panel UI or the EXPORT_REQUEST `statementInputs` field."};const n=e.format==="accessibility-statement-html"?"html":"markdown";try{const o=Rc({results:e.results,inputs:e.statementInputs,outputFormat:n,customDescriptions:e.statementCustomDescriptions});return{type:"EXPORT_RESPONSE",format:e.format,content:o}}catch(o){const r=o instanceof Error?o.message:String(o),c=n==="html"?`<article><h1>Accessibility statement — render error</h1><p>The statement render failed: <code>${r}</code>. Provide a complete <code>StatementInputs</code> via the side panel UI or EXPORT_REQUEST and try again.</p></article>`:`# Accessibility statement — render error
2089
-
2090
- The statement render failed: \`${r}\`. Provide a complete \`StatementInputs\` via the side panel UI or EXPORT_REQUEST and try again.`;return{type:"EXPORT_RESPONSE",format:e.format,content:c}}}if(e.format==="ai-prompt-site-crawl"){const[n,o]=await Promise.all([En(),Zt()]);if(!n||!o||o.length===0)return{type:"EXPORT_RESPONSE",format:"ai-prompt-site-crawl",content:`# Accessibility Fix Request — Site Crawl
2091
-
2092
- No crawl results found in storage. Run a site crawl from the Crawl tab and try again.
2093
- `};if(e.ownerLawfare){const g=await Le(o.flatMap(f=>f.results)),h=Mc(o,g.acknowledgedMatchKeys);return{type:"EXPORT_RESPONSE",format:"ai-prompt-site-crawl",content:es(o,h,g.acknowledgedMatchKeys)}}const r=new Map;await Promise.all(o.map(async g=>{if(g.componentId)try{const h=await ea(g.componentId);r.set(g.componentId,h.map(f=>({criterionId:f.criterionId,verdict:f.verdict,reasoning:f.reasoning,pageUrl:f.pageUrl})))}catch{}}));const{getAllResolutions:i,applySelfCorrectionSalvage:c,applyContrastMathSalvage:d}=await kn(async()=>{const{getAllResolutions:g,applySelfCorrectionSalvage:h,applyContrastMathSalvage:f}=await Promise.resolve().then(()=>dc);return{getAllResolutions:g,applySelfCorrectionSalvage:h,applyContrastMathSalvage:f}},void 0),p=(await i()).map(c).map(d),m=new Map;for(const g of p){if(g.verdict!=="fail"||/aria-hidden=["']true["']/.test(g.selector))continue;const h=Yn(g.pageUrl),f=m.get(h)??[];f.push(g),m.set(h,f)}const u=await jr([n.startUrl]);return{type:"EXPORT_RESPONSE",format:"ai-prompt-site-crawl",content:ts(o,n,r,m,u)}}return{type:"EXPORT_RESPONSE",format:"json",content:JSON.stringify(Wi(e.results,e.delta),null,2)}})}function Zi(e){if(!Array.isArray(e)||e.length===0)return"";const t=[];t.push("## AI keyboard walkthroughs — interactive WCAG audits"),t.push(""),t.push("The audit ran AI-driven keyboard walkthroughs against the page. Each one Tab-walked the live DOM and AI judged the result against a specific WCAG criterion. Fail verdicts here are NOT heuristic guesses — AI watched the actual focus path and identified a concrete problem. Treat each fail as a required fix."),t.push("");for(const a of e)if(!(!a||typeof a!="object"))try{const n=a.verdict==="pass"||a.verdict==="fail"?a.verdict:"uncertain",o=n==="pass"?"[PASS]":n==="fail"?"[FAIL]":"[UNCERTAIN]",r=String(a.criterionId??"?"),i=r==="2.4.3"?"Focus Order (Level A)":r==="2.1.2"?"No Keyboard Trap (Level A)":r==="2.4.7"?"Focus Visible (Level AA)":r==="1.3.2"?"Meaningful Sequence (Level A)":r==="1.4.11"?"Non-text Contrast (Level AA)":r==="2.5.3"?"Label in Name (Level A)":r,c=typeof a.confidence=="number"?Math.max(0,Math.min(1,a.confidence)):0,d=typeof a.reasoning=="string"?a.reasoning:"",l=typeof a.model=="string"?a.model:"unknown";t.push(`### WCAG ${r} — ${i} — ${o}`),t.push(""),t.push(`**AI reasoning** (${Math.round(c*100)}% confidence, model ${l}):`),t.push(""),t.push(d?`> ${d.replace(/\n/g,`
2094
- > `)}`:"> (no reasoning recorded)"),t.push(""),n==="fail"?(r==="2.4.3"?(t.push("**Fix this:** Reorder DOM source so the natural tab sequence matches the visual reading order, or assign `tabindex` only where you intentionally diverge from source order (and document the reason). Avoid positive `tabindex` values. The tab sequence the AI walked is below — fix every element whose position is out of order vs. its visible position on the page."),t.push(""),t.push('**Anti-patterns to avoid:** adding `tabindex="1"`, `"2"`, etc. (positive values create a parallel focus order that\'s a maintenance nightmare); using `tabindex="-1"` to skip elements that should be reachable; adding JS focus() management to "fix" what DOM-order should solve directly.'),t.push(""),t.push("**Verify by re-auditing:** after the fix, the 2.4.3 walkthrough should return pass.")):r==="2.1.2"?(t.push("**Fix this:** Identify any region where focus gets stuck. Common offenders: modal dialogs that intercept Tab without an escape route (add Escape handler + restore focus on close), custom widgets that loop within their own focus trap without an exit, contenteditable elements consuming Tab as literal input. Ensure forward Tab AND backward Shift+Tab can always reach the rest of the page from any focused element."),t.push(""),t.push("**Anti-patterns to avoid:** suppressing Tab in keydown handlers (event.preventDefault on Tab without specific intent); using `inert` on the wrong container so users can't reach controls that should be focusable."),t.push(""),t.push("**Verify by re-auditing:** after the fix, the 2.1.2 walkthrough should return pass — Tab should cycle forward AND Shift+Tab should cycle backward through every focusable element on the page.")):r==="2.4.7"?(t.push("**Fix this:** Every focusable element must show a visible focus indicator. If you use `outline: none` (e.g., for design reasons), you MUST compensate with a `:focus-visible` box-shadow, border, or background change that has at least 3:1 contrast against the unfocused state. Check every selector in the recorded walk below."),t.push(""),t.push("**Anti-patterns to avoid:** `outline: 0 !important` in a global reset without a `:focus-visible` replacement; relying on `:focus` instead of `:focus-visible` (the latter is the correct hook for keyboard-only focus styling); using ONLY a background color change with insufficient contrast (3:1 minimum against the unfocused state)."),t.push(""),t.push("**Verify by re-auditing:** after the fix, the 2.4.7 walkthrough should return pass on every captured focus state.")):r==="1.3.2"?(t.push("**Fix this:** ensure the DOM source order matches the visual reading order. Screen readers read DOM order; CSS (`flex-direction: row-reverse`, `order:`, `grid-area`, absolute positioning) does NOT reorder what the SR hears. Reorder the HTML so the source flows in the same direction the eye reads, then use minimal CSS for visual placement. Where DOM-reorder is genuinely not feasible (legitimate multi-column footers, RTL emulation, sticky-banner overlays), document the decision and verify the SR experience is still coherent."),t.push(""),t.push('**Anti-patterns to avoid:** using `tabindex` to "fix" reading order (tabindex affects keyboard order, not screen-reader order); adding `aria-flowto` (broadly unsupported; not a real fix); leaving inline `display: none` content that holds the "logical" reading order (it won\'t reach the SR).'),t.push(""),t.push("**Verify by re-auditing:** after the fix, the 1.3.2 walkthrough should return pass — the AI judges whether DOM-flagged divergences are real reading-order breaks vs. legitimate layout patterns.")):r==="1.4.11"?(t.push("**Fix this:** every UI component (button border, form input border, focus ring, icon, status indicator, graphical content needed for understanding) must have at least 3:1 contrast against adjacent colors. For each failed element: raise the foreground/border color, add a darker/lighter background to increase contrast, or thicken the indicator (e.g., 2px instead of 1px border). The AI vision identified specific elements; fix the CSS for each."),t.push(""),t.push('**Anti-patterns to avoid:** ONLY changing opacity/transparency (the rendered contrast on a varied background still fails); using box-shadow as a "border" without ensuring the shadow color meets 3:1 against the surrounding pixels; relying on hover state for contrast (must be visible in default state too).'),t.push(""),t.push("**Verify by re-auditing:** after the fix, the 1.4.11 walkthrough should return pass. Re-run with a fresh screenshot; AI will re-judge the updated colors.")):r==="2.5.3"&&(t.push('**Fix this:** every interactive control\'s accessible name must contain its visible text (case-insensitive, allowing icons/punctuation to be ignored). The AI listed which elements failed. For each, choose ONE of: (a) ensure the visible text matches the accessible name (e.g., button text); (b) use `aria-label` or `aria-labelledby` that STARTS WITH the visible text (e.g., `aria-label="Search — search the catalog"` when visible text is "Search"); (c) remove the conflicting `aria-label` and let the textContent serve as the name. Test by saying "click [visible text]" with speech recognition (Voice Control / Dragon) — the correct fix activates the right control.'),t.push(""),t.push('**Anti-patterns to avoid:** using `aria-label` that REPLACES the visible text entirely (e.g., visible "Cancel" + `aria-label="Close form"` — speech-recognition users saying "click Cancel" will fail); using `title=` attribute alone (not all SRs respect it as the accessible name); using `aria-describedby` for naming (that\'s for descriptions, not names).'),t.push(""),t.push("**Verify by re-auditing:** after the fix, the 2.5.3 walkthrough should return pass — the DOM walker re-collects {visibleText, accessibleName} pairs and AI re-judges ambiguous cases.")),t.push("")):n==="pass"?(t.push("_AI walked the criterion and found no issues. No action needed; this is positive evidence the criterion is met._"),t.push("")):(t.push("_AI could not confidently decide. Manually verify or re-run the walkthrough after rendering changes settle._"),t.push(""));const m=(Array.isArray(a.steps)?a.steps:[]).filter(u=>u&&u.action!=="initial");if(m.length>0){t.push(`<details><summary>Recorded ${m.length}-step keyboard walkthrough</summary>`),t.push(""),t.push("| # | Action | Selector | Role | Accessible name |"),t.push("|---|---|---|---|---|");for(const u of m.slice(0,30)){const g=u.focused??{selector:"?",role:"",name:""},h=String(g.selector??"?"),f=String(g.role??"-")||"-",w=String(g.name??"(no name)").replace(/\|/g,"\\|").slice(0,60),b=String(u.action??""),k=typeof u.ordinal=="number"?u.ordinal:"?";t.push(`| ${k} | ${b} | \`${h}\` | ${f} | ${w} |`)}m.length>30&&t.push(`| … | ${m.length-30} more steps elided | | | |`),t.push(""),t.push("</details>"),t.push("")}}catch(n){console.warn("[report-exporter] walkthrough render skipped:",n)}return t.push("---"),t.join(`
2095
- `)}function rp(e){var a;const t=new Set;for(const n of e){const o=n.currentState;if(!o)continue;const r=[];o.pseudoState&&o.pseudoState!=="default"&&r.push(o.pseudoState),o.theme&&o.theme!=="light"&&r.push(o.theme),o.direction&&o.direction!=="ltr"&&r.push(o.direction),(a=o.breakpoint)!=null&&a.id&&o.breakpoint.id!=="desktop"&&r.push(o.breakpoint.id),o.ariaVariation&&o.ariaVariation.id!=="none"&&r.push(`aria=${o.ariaVariation.id}`),t.add(r.length===0?"default":r.join("/"))}return{stateCount:t.size,states:Array.from(t).sort()}}const ip=/-needs-site-crawl$/;function Yn(e){try{const t=new URL(e);t.hash="";let a=t.toString();return a.endsWith("/")&&t.pathname!=="/"&&(a=a.slice(0,-1)),a}catch{return e}}function es(e,t,a=new Set){var l;const n=new Map;for(const p of e){const m=p.results.flatMap(u=>u.violations).filter(u=>!u.needsReview&&!a.has(u.matchKey)&&Gr(u.ruleId));for(const u of m){const g=n.get(u.ruleId)??{vs:[],urls:new Set};g.vs.push(u),g.urls.add(p.url),n.set(u.ruleId,g)}}const o={critical:0,serious:1,moderate:2,minor:3},r=Array.from(n.entries()).sort(([,p],[,m])=>(o[p.vs[0].impact]??99)-(o[m.vs[0].impact]??99)),i=r.length,c=[];if(c.push("# Help me reduce my website’s lawsuit-target risk"),c.push(""),c.push("You are an accessibility advisor helping me — a non-technical site owner — lower my exposure to the automated tools that ADA demand-letter firms use to find targets. I crawled my whole site and the findings below are ONLY the issues those automated scanners commonly flag. Please explain in plain English."),c.push(""),c.push("> **Scope.** This is the lawsuit-target (lawfare) view, not a full WCAG conformance audit. It covers the whole crawled site. Fixing everything here gets me off the easy-target list; it is not the same as a formal WCAG 2.1 AA conformance claim (for that I’d use Power or Dev mode in the auditor)."),c.push(""),c.push("## What I need from you"),c.push(""),c.push("1. **First, ask what I use to manage my site** (Squarespace, Wix, Shopify, WordPress + theme, Webflow, custom, etc.) — your advice differs per platform."),c.push("2. **For each finding:** tell me whether **I can fix it myself** in my editor (colors, alt text, link/button labels, page titles/language) or whether **my developer needs to** — and give me a short paragraph I can forward."),c.push("3. **If a finding spans multiple pages, it’s probably a shared template/theme element** — fixing it once helps every page."),c.push(""),c.push("## Site-wide lawsuit-target summary"),c.push(""),c.push(`- **Pages crawled:** ${e.length}`),c.push(`- **Lawsuit-target grade:** ${t.site.letter} — ${t.site.tier} risk`),c.push(`- **${t.site.headline}**`),c.push(`- **Lawsuit-target findings site-wide:** ${i}`),c.push(""),c.push("## The findings, in plain language"),c.push(""),i===0)return c.push("No findings of the kind automated demand-letter scanners commonly flag (missing image alt text, low color contrast, unlabeled buttons/links, missing page language or title). That keeps the site off the easy-target list. This is not a guarantee — scanners add checks over time, and a full WCAG conformance review (Power/Dev mode) covers far more. Re-crawl as the site changes."),c.push(""),c.push("Since there’s nothing to fix here, help me understand: what should I keep an eye on as I add new pages or content, to stay off the radar?"),c.join(`
2096
- `);let d=1;for(const[p,{vs:m,urls:u}]of r){const g=(l=m.find(b=>b.target.opacityContext))==null?void 0:l.target.opacityContext,h=Fn(p,g),f=m[0].impact,w=Array.from(u);c.push(`### ${d}. [${f.toUpperCase()}] ${h.whatsWrong}`),c.push(""),c.push(`**Why this matters.** ${h.whyItMatters}`),c.push(""),c.push(`**Plain-language fix guidance.** ${h.howToFix}`),c.push(""),c.push(`**Where (${w.length} ${w.length===1?"page":"pages"}${w.length>1?" — likely a shared template element, fix once":""}):**`);for(const b of w.slice(0,8))c.push(`- ${b}`);w.length>8&&c.push(`- (and ${w.length-8} more pages)`),c.push(""),c.push(`*Technical reference for your developer:* axe-core rule \`${p}\` — https://dequeuniversity.com/rules/axe/4.11/${p}`),c.push(""),d++}return c.push("---"),c.push(""),c.push("## How to use this"),c.push(""),c.push("Walk through these with me one at a time. Start by asking which platform I use, then for each finding tell me if it’s a self-fix or a developer task, and help me knock out the shared-template items first since they clear multiple pages at once."),c.push(""),c.push(`_Generated by wcagcheckr v${Ee()} — site crawl (owner / lawsuit-target lens, ${e.length} pages)._`),c.join(`
2097
- `)}const sp={"1.3.2":"Meaningful Sequence (A)","1.4.11":"Non-text Contrast (AA)","2.1.2":"No Keyboard Trap (A)","2.4.3":"Focus Order (A)","2.4.7":"Focus Visible (AA)","2.5.3":"Label in Name (A)"},cp={"1.3.2":"Make the DOM source order match the visual reading order — CSS (order / flex-direction / grid-area / absolute positioning) does NOT move what a screen reader announces. Reorder the HTML; use minimal CSS for visual placement.","1.4.11":"Bring the cited component/state to >= 3:1 contrast against its adjacent color, OR distinguish the state by a non-color means (weight, underline, icon, border) so a sub-3:1 color delta is not the only differentiator. The reasoning above names the exact element + measured ratio + colors.","2.1.2":"Remove the focus trap: Tab AND Shift+Tab must always be able to leave any focused element (modals add Escape-to-close + restore focus on close).","2.4.3":"Reorder DOM source so the tab sequence matches the visual reading order; avoid positive tabindex values.","2.4.7":"Give every focusable element a visible :focus-visible indicator with >= 3:1 contrast against the unfocused state (never outline:none with no replacement).","2.5.3":"Ensure each control's accessible name CONTAINS its visible text — e.g. aria-label should START WITH the visible label rather than replace it."};function Zo(e){const t=[];if(!e||e.length===0)return t;t.push("**AI-walkthrough findings to fix on this page** — the AI watched the live DOM/keyboard and identified a concrete failure; treat each as a required fix:"),t.push("");for(const a of e){const n=String(a.criterionId),o=sp[n]??n,r=typeof a.reasoning=="string"&&a.reasoning.trim()?a.reasoning.trim():"(no reasoning recorded — re-run the walkthrough on this page)";t.push(`- **WCAG ${n} — ${o} — [FAIL]:** ${r}`);const i=cp[n];i&&t.push(` - **Fix:** ${i}`),t.push(" - **Verify:** re-run the crawl at the same depth; this walkthrough should then return pass.")}return t.push(""),t}function ts(e,t,a=new Map,n=new Map,o=[]){var m;const r=[];r.push("# Accessibility Fix Request — Site Crawl"),r.push(""),r.push("> **Your job is to APPLY the fixes in this report — not to evaluate, second-guess, or re-litigate whether the findings are correct.** This report is the output of a real automated crawl + audit (axe-core run in a live browser across many UI states) plus AI verification; the triage already happened upstream. Do not debate severity or skip items you personally doubt. Work page by page, apply the canonical fix for each finding, and report the outcome per the Work contract below. A genuine blocker or a real user-decision is the only acceptable non-fix — and those are reported explicitly per the contract, never silently dropped."),r.push(""),r.push(`You are a senior accessibility engineer pairing with the user on their codebase. The user has crawled ${t.pagesAudited} page${t.pagesAudited===1?"":"s"} on this site and below you'll find the per-page WCAG findings + the cross-page consistency findings. Your task: walk page by page, apply fixes, and produce one atomic commit per fix.`),r.push(""),r.push(`> **Note on this report's scope.** This is a triage + bulk-fix prompt covering all crawled pages in one document. The user can also drop into any single page in the wcagcheckr side panel for per-finding acknowledgements, guided manual checks, fix-preview overlays, and interactive walkthrough re-runs — those are intentionally NOT in this report; they live in the per-page UI surface. If you need that level of control for a specific finding, suggest the user click that page in the Crawl tab's "Pages, worst first" list.`),r.push("");let i=0;for(const u of n.values())i+=u.length;let c=0;for(const u of a.values())for(const g of u)g.verdict==="fail"&&(c+=1);const d=t.totalUniqueViolations+i+c;r.push("## [!] Work contract — read before doing anything else"),r.push(""),r.push(`**Below you have ${d} finding${d===1?"":"s"} across ${t.pagesAudited} page${t.pagesAudited===1?"":"s"}** (${t.totalUniqueViolations} axe violation${t.totalUniqueViolations===1?"":"s"}${i>0?` + ${i} pixel-contrast-sampler fail${i===1?"":"s"}`:""}${c>0?` + ${c} AI-walkthrough fail${c===1?"":"s"}`:""}). When you respond, every numbered finding needs an outcome. Do not stop early. Do not declare done without addressing every finding.`),r.push(""),r.push("**For each numbered finding, produce one of:**"),r.push(""),r.push("- [DONE] **Applied** — the canonical fix was applied. Cite the file + line. If one shared-component fix resolves N findings, group them under the SAME fix and list which findings it covers."),r.push("- [BLOCKED] **Blocked** — explicitly state WHY (missing info, ambiguous user content, dependency change required). One sentence per blocked finding."),r.push("- [NEEDS-DECISION] **Needs user decision** — list the options inline."),r.push(""),r.push(`**The single answer you cannot use: "skipped" or "didn't get to it."** Stop and tell the user if you ran out of context — do not silently omit items.`),r.push(""),r.push("**Required final response format** — completion table:"),r.push(""),r.push("```"),r.push("| # | Rule ID | Page(s) | Status | Notes |"),r.push("|---|---------|---------|--------|-------|"),r.push("| 1 | <rule> | <url> | DONE / BLOCKED / NEEDS-DECISION | <file:line OR reason> |"),r.push(`| ${d} | ... | ... | ... | ... |`),r.push("```"),r.push(""),r.push("**Every row must be present.** One pass through this prompt should produce a fix or a clear next action for every finding — not a partial sweep that forces the user to re-run."),r.push(""),r.push("---"),r.push(""),r.push(Fh),r.push("---"),r.push(""),r.push("## Site-wide summary"),r.push(""),r.push(`- **Start URL:** ${t.startUrl}`),r.push(`- **Pages audited:** ${t.pagesAudited}${t.pagesFailed>0?` (${t.pagesFailed} failed)`:""}`),r.push(`- **Site grade:** ${Hr(t.siteGrade,t.spotCheckGate)}`),r.push(`- **Total findings site-wide:** ${d} (${t.totalUniqueViolations} axe, ${i} pixel-contrast-sampler)`),r.push(`- **Severity breakdown:** ${t.totals.critical} critical · ${t.totals.serious+i} serious · ${t.totals.moderate} moderate · ${t.totals.minor} minor`),r.push(""),r.push(`> ${Vr}`),r.push(""),r.push(`- **Audit rigor (settings this grade was earned under):** ${oi(t.auditSettings)}`);{const u=ri(t.auditSettings);u?r.push(` - [!] **${u}**`):r.push(" - [OK] **Full 2.1 AA audit** — settings cleared the conformance bar.")}r.push("");const l=t.topViolations.filter(u=>!/-needs-site-crawl$/.test(u.ruleId));if(l.length>0){r.push("**Most-frequent rules across the site** (fixing one of these in a shared component / layout resolves N pages at once):"),r.push("");for(const u of l.slice(0,8)){const h=u.urlsAffected>=Math.ceil(t.pagesAudited/2)?" — **likely a single shared-component fix**":"";r.push(`- \`${u.ruleId}\` — ${u.impact} — found on ${u.urlsAffected} page${u.urlsAffected===1?"":"s"} (${u.totalOccurrences} total instance${u.totalOccurrences===1?"":"s"})${h}`)}r.push("")}const p=t.consistencyFindings??[];if(p.length>0){r.push("## Cross-page consistency findings"),r.push(""),r.push("These are divergences detected by comparing structure across pages (WCAG 3.2.3, 3.2.4, 3.2.6, 3.3.7). Each finding references multiple pages — typically the fix is in a SHARED component (header / nav / footer / form)."),r.push("");for(const u of p){const g=u.aiVerdict?u.aiVerdict.verdict==="uncertain"?" _(AI: uncertain — verify manually)_":` _(AI: confirmed real, confidence ${(u.aiVerdict.confidence*100).toFixed(0)}%)_`:"";r.push(`### ${u.wcagCriterion} ${u.impact} — ${u.description}${g}`),r.push("");for(const h of u.details.split(`
2098
- `))r.push(h);(m=u.aiVerdict)!=null&&m.reasoning&&(r.push(""),r.push(`AI reasoning: ${u.aiVerdict.reasoning}`)),r.push("")}}else r.push("## Cross-page consistency findings"),r.push(""),r.push("No cross-page divergences detected by the heuristic comparators. Still verify manually that nav order, accessible names of shared components, and help-mechanism position are consistent across pages."),r.push("");return r.push("---"),r.push(""),r.push(`## Per-page findings (${e.length} page${e.length===1?"":"s"})`),r.push(""),r.push("Each page section below is shaped like a single-page audit report — violations to fix + relevant recipes. Fix one page at a time. The cross-page findings above usually point at a SHARED component; fix that once and re-run the audit to see N pages resolve together."),r.push(""),e.forEach((u,g)=>{const h=g+1;if(r.push(`### Page ${h} of ${e.length}: ${u.url}`),r.push(""),u.error){r.push(`> [!] Audit failed for this page: \`${u.error}\``),r.push(""),r.push("---"),r.push("");return}const f=u.results.flatMap(A=>A.violations).filter(A=>!ip.test(A.ruleId)),w=n.get(Yn(u.url))??[];if(f.length===0&&w.length===0){const A=a.get(u.componentId)??[],C=A.filter(F=>F.verdict==="fail");if(C.length>0?r.push(`No axe/automated violations on this page, but **${C.length} AI-walkthrough finding${C.length===1?"":"s"}** below require a fix. Also apply the manual checklist.`):r.push("No automated violations detected on this page. Still apply the manual checklist below."),r.push(""),A.length>0){r.push("**AI walkthrough verdicts on this page:**");for(const F of A){const T=F.verdict==="pass"?"[PASS]":F.verdict==="fail"?"[FAIL]":"[?]";r.push(`- ${T} WCAG ${F.criterionId} — ${F.verdict.toUpperCase()}`)}r.push(""),r.push(...Zo(C))}r.push("---"),r.push("");return}const b=new Map,k=new Map;for(const A of f){const C=Fe(A.ruleId,A.target.selector);b.has(C)||b.set(C,A);const F=k.get(C)??[];F.push(A),k.set(C,F)}const v=Array.from(b.entries()).map(([A,C])=>({v:C,instances:k.get(A)??[C]})).sort((A,C)=>{const F={critical:0,serious:1,moderate:2,minor:3};return(F[A.v.impact]??99)-(F[C.v.impact]??99)}),s={critical:0,serious:0,moderate:0,minor:0};for(const{v:A}of v)s[A.impact]++;s.serious+=w.length;const x=v.length+w.length;r.push(`**${x} finding${x===1?"":"s"}** · severity: ${s.critical} critical · ${s.serious} serious · ${s.moderate} moderate · ${s.minor} minor`),r.push(""),v.forEach(({v:A,instances:C},F)=>{const T=lt[A.ruleId],I=Ko(`${A.ruleId} ${A.wcagCriterion}`)==="human-verify"?"[Human-verify]":"[AI-fixable]";r.push(`#### ${h}.${F+1} \`${A.ruleId}\` — ${A.impact} — WCAG ${A.wcagCriterion} ${A.wcagLevel} — ${I}`),r.push(""),r.push(`**Description:** ${A.description}`),r.push(""),r.push(Rr(A)),r.push(""),r.push(`**Selector:** \`${A.target.selector}\``);const{stateCount:D,states:S}=rp(C);D>1?(r.push(""),r.push(`_Failed in ${D} matrix state${D===1?"":"s"}:_ ${S.join(", ")}`)):C.length>1&&(r.push(""),r.push(`_${C.length} element instances on this page (same state)._`)),r.push(""),A.target.failureSummary&&(r.push("**Diagnostic:**"),r.push("```"),r.push(A.target.failureSummary.trim()),r.push("```"),r.push("")),A.target.outerHTML&&(r.push("**Element HTML:**"),r.push("```html"),r.push(A.target.outerHTML.slice(0,500)),r.push("```"),r.push(""));const _=_i(A);if(_){r.push("**Suggested fix for this element** (apply to the source, not the rendered DOM):"),r.push("```diff");for(const N of _.current.split(`
2099
- `))r.push(`- ${N}`);for(const N of _.suggested.split(`
2100
- `))r.push(`+ ${N}`);r.push("```"),_.note&&r.push(`> ${_.note}`),r.push("")}T!=null&&T.summary&&(r.push("**Recipe:**"),r.push(T.summary),T.snippet&&(r.push(""),r.push("```"+(T.snippetLang??"")),r.push(T.snippet),r.push("```")),r.push("")),A.helpUrl&&(r.push(`**More info:** ${A.helpUrl}`),r.push(""))}),w.forEach((A,C)=>{const F=v.length+C,T=Ko(`${A.ruleId} ${A.wcagCriterion??"1.4.3"}`)==="human-verify"?"[Human-verify]":"[AI-fixable]";r.push(`#### ${h}.${F+1} \`${A.ruleId}\` — serious — WCAG ${A.wcagCriterion??"1.4.3"} AA — ${T}`),r.push(""),r.push("**Description:** Empirical pixel-contrast measurement below the AA threshold (pixel-contrast-sampler)."),r.push(""),r.push(`**Selector:** \`${A.selector}\``),r.push(""),r.push("**Diagnostic:**"),r.push("```"),r.push(A.reasoning.trim()),r.push("```"),r.push(""),r.push("**Recipe:**"),r.push('Pixel-level contrast measurement — the sampler diffed hide-text vs visible viewport screenshots and recovered the rendered foreground/background colors at the worst-contrast pixel. Verify the live computed colors at the cited selector (devtools → Computed → color / background-color). Fix by raising the foreground contrast against the actual rendered background (account for transparency, gradients, and overlay layers). If the sampler caught a transient state (loading skeleton, hover) and the steady-state contrast is fine, surface that as a "Blocked" entry with a note.'),r.push("")});const $=a.get(u.componentId)??[];if($.length>0){r.push("**AI walkthrough verdicts on this page:**");for(const A of $){const C=A.verdict==="pass"?"[PASS]":A.verdict==="fail"?"[FAIL]":"[?]";r.push(`- ${C} WCAG ${A.criterionId} — ${A.verdict.toUpperCase()}: ${A.reasoning.slice(0,240)}${A.reasoning.length>240?"…":""}`)}r.push(""),r.push(...Zo($.filter(A=>A.verdict==="fail")))}r.push("---"),r.push("")}),r.push(Lh(o)),r.push(""),r.push("## Combined verification checklist"),r.push(""),r.push("After all per-page fixes:"),r.push(""),r.push("1. **Re-run the site crawl** at the same depth used here."),r.push("2. Verify the **cross-page consistency findings** above all resolve (or document why a flagged divergence is intentional)."),r.push("3. Verify the **top-frequency rules** across pages resolve in bulk (a single shared-component fix should drop the count on multiple pages)."),r.push("4. **Manual WCAG checks** (audio/video transcripts, character key shortcuts, timing controls, etc.) — the per-page sections above only contain automatable findings. The non-automatable WCAG criteria still apply per page."),r.push("5. **Diff review** — every fix should be reviewable in under 10 minutes. One atomic commit per fix."),r.push(""),r.push(`_Generated by ${Ie} v${Ee()} — site crawl mode (${e.length} pages)._`),r.join(`
2101
- `)}const cf=Object.freeze(Object.defineProperty({__proto__:null,normUrlKey:Yn,registerReportExporterHandlers:op,renderAiWalkthroughsForPrompt:Zi,toAiPrompt:zi,toAiPromptForSiteCrawl:ts,toAiPromptOwner:Xi,toDefenseBundle:Ut,toDeveloperLetter:Yi,toEvidenceBundle:Ki,toHtmlPrint:Kn,toJUnit:ji,toJson:Wi,toLawfarePromptForSiteCrawl:es,toOwnerReport:Ji,toSarif:Gi,toVpat:qi,toolVersion:Ee},Symbol.toStringTag,{value:"Module"})),Xt=Z("sw-auto-export");function lp(e,t,a){const n=vs(e,a);let o="audit";try{o=new URL(t).hostname.replace(/^www\./,"").replace(/[^a-z0-9.-]/gi,"-")}catch{}return`wcagcheckr/${o}/${n}`}async function dp(e,t,a){try{if(e==="html-print")return Kn(t,a);if(e==="defense-bundle"){const n=await Tt().catch(()=>[]);return Ut(t,a,"defense",void 0,n)}if(e==="deposition-packet")return(await Ni({results:t,delta:a,manualRuns:void 0,aiSummary:null})).html}catch(n){return Xt.warn(`buildContent failed for format=${e}`,n),null}return null}async function up(e,t){var a,n,o;if(e.length!==0)try{const r=await bs();if(!r.enabled||await He())return;const i=await pe().catch(()=>"free");if(!he(i,"autoExportAuditReports"))return;const c=((a=e[0])==null?void 0:a.pageUrl)??((n=e[0])==null?void 0:n.scope)??"",d=((o=e[0])==null?void 0:o.componentId)??null;for(const l of r.formats)try{const p=await dp(l,e,t);if(!p||p.length<200)continue;const m=lp(l,c,d),u=l==="ai-prompt"?"text/markdown":"text/html",{body:g}=ys(p,u),h=`data:${u};charset=utf-8,${encodeURIComponent(g)}`,f=await chrome.downloads.download({url:h,filename:m,saveAs:!1,conflictAction:"uniquify"});Xt.info(`scheduled auto-export started (id=${f}, file=${m})`),c&&await ws({url:c,exportedAt:new Date().toISOString(),format:l,filename:m})}catch(p){Xt.warn(`format ${l} failed in scheduled auto-export`,p)}}catch(r){Xt.warn("autoExportFromScheduledRun failed (audit itself still succeeded)",r)}}const je=Z("scheduled-audit-runner"),fa="scheduled-audit:",er={hourly:60,"every-4-hours":240,daily:1440,weekly:10080};function Jn(e){return`${fa}${e}`}function lf(e){return e.startsWith(fa)?e.slice(fa.length):null}async function hp(e){const t=Jn(e.id);await chrome.alarms.create(t,{periodInMinutes:er[e.cadence],delayInMinutes:er[e.cadence]})}async function df(e){await chrome.alarms.clear(Jn(e))}async function uf(){try{const{listScheduledAudits:e}=await kn(async()=>{const{listScheduledAudits:o}=await Promise.resolve().then(()=>Vs);return{listScheduledAudits:o}},void 0),t=await e(),a=await chrome.alarms.getAll(),n=new Set(t.filter(o=>o.enabled).map(o=>Jn(o.id)));for(const o of a)o.name.startsWith(fa)&&!n.has(o.name)&&await chrome.alarms.clear(o.name);for(const o of t)o.enabled&&await hp(o);je.info(`reconciled ${t.length} scheduled-audit alarms`)}catch(e){je.warn("failed to reconcile scheduled alarms",e)}}async function hf(e){var r;const t=Date.now(),a=await lr(e);if(!a){je.warn(`scheduled audit ${e} not found — alarm fired for deleted schedule`);return}if(!a.enabled){je.debug(`scheduled audit ${e} is disabled — skipping`);return}if(await He()){await Ct(a,{result:"failed",error:Ze,durationMs:Date.now()-t,totalViolations:0,newVsBaselineViolations:0});return}const n=await pe();if(!he(n,"scheduledAudits")){await Ct(a,{result:"failed",error:"Scheduled audits are not available on your current plan.",durationMs:Date.now()-t,totalViolations:0,newVsBaselineViolations:0});return}await Tn({...a,lastResult:"running",lastRunAt:new Date().toISOString()});let o;try{if(o=(await chrome.tabs.create({url:a.url,active:!1})).id,!o)throw new Error("chrome.tabs.create returned no id");await pp(o,3e4);const d=await pt("html",{isCanceled:()=>!1},0,void 0,{asSubroutine:!0,tabIdOverride:o});if(!d.ok){await Ct(a,{result:"failed",error:d.error??"audit failed",durationMs:Date.now()-t,totalViolations:0,newVsBaselineViolations:0});return}const l=d.results.reduce((g,h)=>g+h.violations.length,0),p=(r=d.results[0])==null?void 0:r.delta,m=(p==null?void 0:p.newCount)??0,u=new Date().toISOString();if(await Ct(a,{result:"ok",durationMs:Date.now()-t,totalViolations:l,newVsBaselineViolations:m}),up(d.results,p),m>0)try{const g=await Ku({scheduleId:a.id,auditedUrl:a.url,ranAt:u,results:d.results});je.debug(`alert outcome for ${a.id}`,g)}catch(g){je.warn(`alert fire threw for ${a.id}`,g)}}catch(i){const c=i instanceof Error?i.message:String(i);je.warn(`scheduled audit ${e} failed:`,c),await Ct(a,{result:"failed",error:c,durationMs:Date.now()-t,totalViolations:0,newVsBaselineViolations:0})}finally{if(o!==void 0)try{await chrome.tabs.remove(o)}catch{}}}async function Ct(e,t){const a=new Date().toISOString();await dr({scheduleId:e.id,ranAt:a,durationMs:t.durationMs,totalViolations:t.totalViolations,newVsBaselineViolations:t.newVsBaselineViolations,error:t.error}),await Tn({...e,lastRunAt:a,lastResult:t.result,lastError:t.error,lastTotalViolations:t.totalViolations,lastNewViolationCount:t.newVsBaselineViolations}),await ur(e.id);try{await th()}catch(n){je.warn("status badge refresh failed",n)}}function pp(e,t){return new Promise(a=>{const n=setTimeout(()=>{chrome.tabs.onUpdated.removeListener(o),a()},t),o=(r,i)=>{r===e&&i.status==="complete"&&(clearTimeout(n),chrome.tabs.onUpdated.removeListener(o),setTimeout(a,500))};chrome.tabs.onUpdated.addListener(o)})}export{Pp as $,Cp as A,Sc as B,zp as C,Np as D,Hs as E,Mp as F,Dp as G,Lp as H,Fr as I,et as J,Kt as K,_p as L,Up as M,Mr as N,Le as O,Mc as P,qr as Q,kr as R,wr as S,xr as T,Vr as U,$a as V,Vp as W,Gp as X,Bp as Y,jp as Z,Fp as _,Kp as a,oi as a$,tt as a0,Tr as a1,Wp as a2,Gr as a3,Tt as a4,ol as a5,Ra as a6,dt as a7,Sa as a8,qp as a9,xd as aA,cl as aB,Zp as aC,Jp as aD,Qp as aE,Xp as aF,pc as aG,uf as aH,lf as aI,hf as aJ,ef as aK,op as aL,sf as aM,Hp as aN,pt as aO,Mu as aP,Ou as aQ,Yp as aR,Uu as aS,_u as aT,Wu as aU,tf as aV,af as aW,xp as aX,rf as aY,Rp as aZ,xc as a_,uo as aa,Fn as ab,na as ac,Ge as ad,gc as ae,Ep as af,uc as ag,qu as ah,zu as ai,cr as aj,of as ak,Tn as al,hp as am,th as an,er as ao,df as ap,_s as aq,Gs as ar,Ws as as,fe as at,_e as au,Pd as av,Md as aw,Dd as ax,Ed as ay,Sd as az,ka as b,ri as b0,Fl as b1,Hn as b2,bn as b3,Yt as b4,wp as b5,Sp as b6,dc as b7,$p as b8,nf as b9,cf as ba,Pl as c,Au as d,De as e,Bs as f,Op as g,jr as h,wa as i,En as j,hr as k,Zt as l,kp as m,Ap as n,Ip as o,vp as p,fr as q,yr as r,Tp as s,Fe as t,Ir as u,ea as v,$r as w,ec as x,Ac as y,oc as z};