@wcag-checkr/ci 1.0.0-rc.366 → 1.0.0-rc.367
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/assets/{ErrorBoundary-BH1wbHb3.js → ErrorBoundary-Ck0XMUiQ.js} +22 -22
- package/dist/assets/{copy-ai-fixer-prompt-FO0N3IMf.js → copy-ai-fixer-prompt-CKp52Td1.js} +2 -2
- package/dist/assets/{devtools-panel-BAHfgRsc.js → devtools-panel-Dw0aFhIc.js} +1 -1
- package/dist/assets/{parallel-tab-flow-C4bjrDqL.js → parallel-tab-flow-BuZZIdRb.js} +1 -1
- package/dist/assets/{scheduled-audit-runner-XCDyFhY6.js → scheduled-audit-runner-9R-aGzwO.js} +137 -137
- package/dist/assets/{service-worker.ts-57FwiS_-.js → service-worker.ts-CyL2aQvI.js} +2 -2
- package/dist/assets/{side-panel-Dl247dJv.js → side-panel-CuEUwRBD.js} +3 -3
- package/dist/assets/{site-report-renderer-CNWZjbOd.js → site-report-renderer-46_JyAkB.js} +1 -1
- package/dist/devtools/panel.html +3 -3
- package/dist/manifest.json +3 -4
- package/dist/service-worker-loader.js +1 -1
- package/dist/side-panel/side-panel.html +4 -4
- package/package.json +1 -1
- package/dist/side-panel/App.tsx +0 -308
- package/dist/side-panel/README.md +0 -57
- package/dist/side-panel/audit-launcher.test.ts +0 -56
- package/dist/side-panel/audit-launcher.ts +0 -98
- package/dist/side-panel/azure-devops-issue.test.ts +0 -68
- package/dist/side-panel/azure-devops-issue.ts +0 -89
- package/dist/side-panel/format-component-id.test.ts +0 -89
- package/dist/side-panel/format-component-id.ts +0 -40
- package/dist/side-panel/github-issue.test.ts +0 -102
- package/dist/side-panel/github-issue.ts +0 -66
- package/dist/side-panel/gitlab-issue.test.ts +0 -53
- package/dist/side-panel/gitlab-issue.ts +0 -78
- package/dist/side-panel/jira-issue.ts +0 -64
- package/dist/side-panel/main.tsx +0 -86
- package/dist/side-panel/store.ts +0 -435
- package/dist/side-panel/styles.css +0 -55
- package/dist/side-panel/use-audit-view-model.ts +0 -116
- package/dist/side-panel/wire-messaging.test.ts +0 -234
- package/dist/side-panel/wire-messaging.ts +0 -521
package/dist/assets/{scheduled-audit-runner-XCDyFhY6.js → scheduled-audit-runner-9R-aGzwO.js}
RENAMED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/parallel-tab-flow-
|
|
2
|
-
var ci=Object.defineProperty;var li=(e,t,a)=>t in e?ci(e,t,{enumerable:!0,configurable:!0,writable:!0,value:a}):e[t]=a;var Mt=(e,t,a)=>li(e,typeof t!="symbol"?t+"":t,a);import{_ as en}from"./preload-helper-D7HrI6pR.js";import{a as de,m as Rn,d as di,T as ui,b as On,c as tn,g as an,i as Mn}from"./diff-NSOR-wHP.js";import{c as ee,f as ue,o as Ie,k as z,r as ve,h as At,j as Ro}from"./crash-reporter-7_6X-wSd.js";import{m as we,e as Na,n as pi,p as hi,q as fi,u as gi,v as mi,w as bi,b as yi,g as wi,r as vi,f as Ai}from"./ai-usage-log-CvwMbWGw.js";const La=(e,t)=>t.some(a=>e instanceof a);let Dn,Nn;function ki(){return Dn||(Dn=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function Ii(){return Nn||(Nn=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])}const Pa=new WeakMap,wa=new WeakMap,na=new WeakMap;function xi(e){const t=new Promise((a,n)=>{const o=()=>{e.removeEventListener("success",i),e.removeEventListener("error",r)},i=()=>{a(Ge(e.result)),o()},r=()=>{n(e.error),o()};e.addEventListener("success",i),e.addEventListener("error",r)});return na.set(t,e),t}function Si(e){if(Pa.has(e))return;const t=new Promise((a,n)=>{const o=()=>{e.removeEventListener("complete",i),e.removeEventListener("error",r),e.removeEventListener("abort",r)},i=()=>{a(),o()},r=()=>{n(e.error||new DOMException("AbortError","AbortError")),o()};e.addEventListener("complete",i),e.addEventListener("error",r),e.addEventListener("abort",r)});Pa.set(e,t)}let Fa={get(e,t,a){if(e instanceof IDBTransaction){if(t==="done")return Pa.get(e);if(t==="store")return a.objectStoreNames[1]?void 0:a.objectStore(a.objectStoreNames[0])}return Ge(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 Oo(e){Fa=e(Fa)}function Ci(e){return Ii().includes(e)?function(...t){return e.apply(_a(this),t),Ge(this.request)}:function(...t){return Ge(e.apply(_a(this),t))}}function Ti(e){return typeof e=="function"?Ci(e):(e instanceof IDBTransaction&&Si(e),La(e,ki())?new Proxy(e,Fa):e)}function Ge(e){if(e instanceof IDBRequest)return xi(e);if(wa.has(e))return wa.get(e);const t=Ti(e);return t!==e&&(wa.set(e,t),na.set(t,e)),t}const _a=e=>na.get(e);function Mo(e,t,{blocked:a,upgrade:n,blocking:o,terminated:i}={}){const r=indexedDB.open(e,t),c=Ge(r);return n&&r.addEventListener("upgradeneeded",l=>{n(Ge(r.result),l.oldVersion,l.newVersion,Ge(r.transaction),l)}),a&&r.addEventListener("blocked",l=>a(l.oldVersion,l.newVersion,l)),c.then(l=>{i&&l.addEventListener("close",()=>i()),o&&l.addEventListener("versionchange",d=>o(d.oldVersion,d.newVersion,d))}).catch(()=>{}),c}const $i=["get","getKey","getAll","getAllKeys","count"],Ei=["put","add","delete","clear"],va=new Map;function Ln(e,t){if(!(e instanceof IDBDatabase&&!(t in e)&&typeof t=="string"))return;if(va.get(t))return va.get(t);const a=t.replace(/FromIndex$/,""),n=t!==a,o=Ei.includes(a);if(!(a in(n?IDBIndex:IDBObjectStore).prototype)||!(o||$i.includes(a)))return;const i=async function(r,...c){const l=this.transaction(r,o?"readwrite":"readonly");let d=l.store;return n&&(d=d.index(c.shift())),(await Promise.all([d[a](...c),o&&l.done]))[0]};return va.set(t,i),i}Oo(e=>({...e,get:(t,a,n)=>Ln(t,a)||e.get(t,a,n),has:(t,a)=>!!Ln(t,a)||e.has(t,a)}));const Ri=["continue","continuePrimaryKey","advance"],Pn={},Ua=new WeakMap,Do=new WeakMap,Oi={get(e,t){if(!Ri.includes(t))return e[t];let a=Pn[t];return a||(a=Pn[t]=function(...n){Ua.set(this,Do.get(this)[t](...n))}),a}};async function*Mi(...e){let t=this;if(t instanceof IDBCursor||(t=await t.openCursor(...e)),!t)return;t=t;const a=new Proxy(t,Oi);for(Do.set(a,t),na.set(a,_a(t));t;)yield a,t=await(Ua.get(a)||t.continue()),Ua.delete(a)}function Fn(e,t){return t===Symbol.asyncIterator&&La(e,[IDBIndex,IDBObjectStore,IDBCursor])||t==="iterate"&&La(e,[IDBIndex,IDBObjectStore])}Oo(e=>({...e,get(t,a,n){return Fn(t,a)?Mi:e.get(t,a,n)},has(t,a){return Fn(t,a)||e.has(t,a)}}));const Di="wcag-component-auditor",Ni=3;let Xe=null;function re(){return Xe||(Xe=Mo(Di,Ni,{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")}}})),Xe}async function Li(){Xe&&(await Xe).close(),Xe=null}async function oa(e){return(await re()).get("baselines",e)}async function nn(e){await(await re()).put("baselines",e)}async function No(e){await(await re()).delete("baselines",e)}async function Lo(){return(await re()).getAll("baselines")}async function Pi(e){return(await re()).getAllFromIndex("baselines","byUrl",e)}async function Fi(e){return(await re()).add("audit-history",e)}async function _i(e){return(await re()).getAllFromIndex("audit-history","byComponentId",e)}async function Po(){return(await re()).get("site-crawl-per-url","current")}async function Fo(e){await(await re()).put("site-crawl-per-url",{...e,slot:"current"})}async function on(){await(await re()).delete("site-crawl-per-url","current")}async function _o(){return(await re()).getAll("scheduled-audits")}async function Uo(e){return(await re()).get("scheduled-audits",e)}async function rn(e){await(await re()).put("scheduled-audits",e)}async function Ui(e){await(await re()).delete("scheduled-audits",e)}async function Wo(e){return(await re()).add("scheduled-audit-results",e)}async function Wi(e){return(await re()).getAllFromIndex("scheduled-audit-results","byScheduleId",e)}async function qi(){return(await re()).getAll("scheduled-audit-results")}async function qo(e,t=50){const a=await re(),n=await a.getAllFromIndex("scheduled-audit-results","byScheduleId",e);if(n.length<=t)return;n.sort((r,c)=>c.ranAt.localeCompare(r.ranAt));const o=n.slice(t),i=a.transaction("scheduled-audit-results","readwrite");for(const r of o)r.resultId!==void 0&&await i.store.delete(r.resultId);await i.done}async function Vi(e){const a=(await re()).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 ji=Object.freeze(Object.defineProperty({__proto__:null,_resetDbForTesting:Li,appendAuditHistory:Fi,appendScheduledAuditResult:Wo,deleteBaseline:No,deleteScheduledAudit:Ui,deleteScheduledAuditResultsForScheduleId:Vi,deleteSiteCrawlPerUrl:on,getBaseline:oa,getDb:re,getScheduledAudit:Uo,getSiteCrawlPerUrl:Po,listAllScheduledAuditResults:qi,listAuditHistoryForComponent:_i,listBaselines:Lo,listBaselinesByUrl:Pi,listScheduledAuditResultsByScheduleId:Wi,listScheduledAudits:_o,pruneScheduledAuditResults:qo,putScheduledAudit:rn,setBaseline:nn,setSiteCrawlPerUrl:Fo},Symbol.toStringTag,{value:"Module"})),jt="siteCrawlReport";async function sn(){var a;if(typeof chrome>"u"||!((a=chrome.storage)!=null&&a.local))return null;const t=(await chrome.storage.local.get([jt]))[jt];return t&&typeof t=="object"?t:null}async function Vo(e){var t;if(!(typeof chrome>"u"||!((t=chrome.storage)!=null&&t.local))){if(e===null){await chrome.storage.local.remove([jt]),await on().catch(()=>{});return}await chrome.storage.local.set({[jt]:e})}}async function Gt(){try{const e=await Po();return(e==null?void 0:e.perUrl)??null}catch{return null}}async function jo(e,t){if(e===null){await on();return}await Fo({startUrl:(t==null?void 0:t.startUrl)??"",finishedAt:(t==null?void 0:t.finishedAt)??new Date().toISOString(),perUrl:e})}const xp=Object.freeze(Object.defineProperty({__proto__:null,loadSiteCrawlPerUrlResults:Gt,loadSiteCrawlReport:sn,saveSiteCrawlPerUrlResults:jo,saveSiteCrawlReport:Vo},Symbol.toStringTag,{value:"Module"})),Gi=ee("headless-build-lockdown"),Go="team";async function Fe(){try{return await de()!==Go}catch(e){return Gi.warn("tier resolution failed during lockout check — denying",e),!0}}function Sp(e){return e!==Go}const St="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 zo(){const e=await chrome.tabs.query({currentWindow:!0}),t=e.find(n=>n.active);if(t!=null&&t.id&&_n(t.url))return t.id;const a=e.find(n=>n.id&&_n(n.url));return(a==null?void 0:a.id)??null}function _n(e){return typeof e=="string"&&/^https?:\/\//.test(e)}const Wa="rubricConfigCache",zi=7*24*60*60*1e3;function Cp(e){const t=Date.now()-e.fetchedAt;return t>=zi?"expired":t>=60*60*1e3?"stale":"fresh"}async function Tp(){var a;if(typeof chrome>"u"||!((a=chrome.storage)!=null&&a.local))return null;const t=(await chrome.storage.local.get(Wa))[Wa];return!t||typeof t!="object"?null:t}async function $p(e){var t;typeof chrome>"u"||!((t=chrome.storage)!=null&&t.local)||await chrome.storage.local.set({[Wa]:e})}let Ho=null;function Ep(e){Ho=e}function Hi(){return Ho}const qa="acknowledgedFindings";async function ra(){var a;if(typeof chrome>"u"||!((a=chrome.storage)!=null&&a.local))return[];const t=(await chrome.storage.local.get([qa]))[qa];return Array.isArray(t)?t:[]}async function ia(e){const t=await ra();return new Set(t.filter(a=>a.componentId===e).map(a=>a.matchKey))}async function Bi(e){const a=(await ra()).filter(n=>!(n.componentId===e.componentId&&n.matchKey===e.matchKey));a.push({...e,acknowledgedAt:new Date().toISOString()}),await Bo(a)}async function Ki(e,t){const n=(await ra()).filter(o=>!(o.componentId===e&&o.matchKey===t));await Bo(n)}async function Bo(e){var t;typeof chrome>"u"||!((t=chrome.storage)!=null&&t.local)||await chrome.storage.local.set({[qa]:e})}const Rp=Object.freeze(Object.defineProperty({__proto__:null,acknowledgeFinding:Bi,loadAcknowledged:ra,loadAcknowledgedKeysForComponent:ia,unacknowledgeFinding:Ki},Symbol.toStringTag,{value:"Module"})),Yi=/:nth-(?:last-)?(?:child|of-type)\([^)]+\)/g,Ji=/\[id="[^"]*"\]/g,Xi=/\[data-testid="[^"]*"\]/g,Qi=/#[\w-]*\d[\w-]*/g,Zi=/\[href(?:[\^$*~|]?=("|')[^"']*\1)?\]/g,es=/\[aria-label(?:[\^$*~|]?=("|')[^"']*\1)?\]/g,ts=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 as(e){return e&&e.replace(Yi,"").replace(Ji,"").replace(Xi,"").replace(Qi,"").replace(Zi,"").replace(es,"").replace(/\s+/g," ").trim()}function Te(e,t){return ts.has(e)?`${e}::__structural__`:`${e}::${as(t)}`}const Un={minor:0,moderate:1,serious:2,critical:3};function Ko(e){const t=new Map;for(const a of e){const n=Te(a.ruleId,a.target.selector),o=t.get(n);if(!o){t.set(n,a);continue}(Un[a.impact]??0)>(Un[o.impact]??0)&&t.set(n,a)}return Array.from(t.values())}const Yo=[{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 Op(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 Yo)for(const o of n.axeRules)if(a.has(o))return n.id;return null}function ns(e){const t=Yo.map(o=>rs(o,e)),a=os(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 os(e){const t=e.filter(r=>r==="A").length,a=e.filter(r=>r==="C").length,n=e.filter(r=>r==="D").length,o=e.filter(r=>r==="F").length,i=e.length-t;return t===0&&n+o>a?"F":i===0?"A":i<=3?"B":i<=6?"C":"D"}function rs(e,t){const a=new Set(e.axeRules),n=t.violations.filter(E=>a.has(E.ruleId)),o=t.manualRuns.filter(E=>e.igtWorkflowIds.includes(E.workflowId)),i=e.igtWorkflowIds.map(E=>t.workflows.find(V=>V.id===E)).filter(E=>E!=null);let r=i.length>0;for(const E of i){const V=o.find($=>$.workflowId===E.id);if((V?Object.keys(V.steps).length:0)!==E.steps.length){r=!1;break}}const c=o.some(E=>Object.keys(E.steps).length>0),l=e.verifiedByWorkflowIds??[],d=t.manualRuns.filter(E=>l.includes(E.workflowId)),u=l.map(E=>t.workflows.find(V=>V.id===E)).filter(E=>E!=null);let m=l.length>0&&u.length===l.length;for(const E of u){const V=d.find($=>$.workflowId===E.id);if((V?Object.keys(V.steps).length:0)!==E.steps.length){m=!1;break}}let p=null;if(m)for(const E of d)E.completedAt&&(p===null||E.completedAt>p)&&(p=E.completedAt);const f=e.heuristic==="tab-order"?t.heuristicCounts.tabOrder??0:e.heuristic==="reading-order"?t.heuristicCounts.readingOrder??0:0,g=l[0]??e.igtWorkflowIds[0]??null,h=t.interactiveAuditVerdicts,y=[];h&&(e.id==="tab-order"&&h.focusOrder&&y.push({verdict:h.focusOrder,criterionId:"2.4.3"}),e.id==="keyboard"&&(h.keyboardTrap&&y.push({verdict:h.keyboardTrap,criterionId:"2.1.2"}),h.focusVisible&&y.push({verdict:h.focusVisible,criterionId:"2.4.7"})),e.id==="reading-order"&&h.readingOrder&&y.push({verdict:h.readingOrder,criterionId:"1.3.2"}),e.id==="contrast"&&h.nonTextContrast&&y.push({verdict:h.nonTextContrast,criterionId:"1.4.11"}));const b=y.some(E=>E.verdict==="fail");if(y.length>0&&y.every(E=>E.verdict==="pass")&&l.length>0&&!m)return{id:e.id,label:e.label,letter:"A",untested:!1,needsIgt:!1,igtCompleted:!1,verifiedByIgt:!1,verifiedAt:y.length>0?new Date().toISOString():null,suppressedHeuristicCount:f,primaryVerifierWorkflowId:g,counts:{critical:0,serious:0,moderate:0,minor:0},caps:{cappedAtC:!1,cappedAtB:!1},aiVerifiedCriteria:y.map(E=>E.criterionId)};if(m&&l.length>0)return{id:e.id,label:e.label,letter:"A",untested:!1,needsIgt:!1,igtCompleted:!0,verifiedByIgt:!0,verifiedAt:p,suppressedHeuristicCount:f,primaryVerifierWorkflowId:g,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||l.length>0,igtCompleted:!1,verifiedByIgt:!1,verifiedAt:null,suppressedHeuristicCount:0,primaryVerifierWorkflowId:g,counts:{critical:0,serious:0,moderate:0,minor:0},caps:{cappedAtC:!1,cappedAtB:!1}};const x={critical:0,serious:0,moderate:0,minor:0},w=Ko(n);for(const E of w)x[E.impact]++;const R=(t.aiResolvedFails??[]).filter(E=>a.has(E.ruleId));if(R.length>0){const E=new Set(w.map(V=>`${V.ruleId}::${V.target.selector}`));for(const V of R){const D=`${V.ruleId}::${V.selector}`;E.has(D)||(E.add(D),x[V.impact]++)}}const T=y.length>0&&y.some(E=>E.verdict==="pass"||E.verdict==="fail"),P=T?f:0;T||(x.serious+=f),b&&(x.serious+=y.filter(E=>E.verdict==="fail").length);for(const E of o){const V=i.find(D=>D.id===E.workflowId);if(V)for(const D of V.steps){const $=E.steps[D.id];($==null?void 0:$.status)==="fail"&&(D.severity==="required"?x.serious++:x.moderate++)}}const _=x.critical>0,N=x.serious>0;let M;x.critical>=5?M="F":x.critical>=1?M="D":x.serious>=1?M="C":x.moderate>=1?M="B":M="A";const S=M!=="A"&&(s&&!r||l.length>0&&!m);return{id:e.id,label:e.label,letter:M,untested:!1,needsIgt:S,igtCompleted:r,verifiedByIgt:!1,verifiedAt:null,suppressedHeuristicCount:P,primaryVerifierWorkflowId:g,counts:x,caps:{cappedAtC:_,cappedAtB:N}}}const Qe="incompleteResolutions",Wn=2e3,qn=600;function cn(e,t,a){return`${e}::${t}::${a}`}function Jo(e){return e.reasoning&&e.reasoning.length>qn?{...e,reasoning:e.reasoning.slice(0,qn-1)+"…"}:e}function is(e){const t=Object.entries(e);if(t.length<=Wn)return e;const a=t.sort(([,n],[,o])=>{const i=Date.parse(n.resolvedAt)||0;return(Date.parse(o.resolvedAt)||0)-i});return Object.fromEntries(a.slice(0,Wn))}async function sa(){try{const t=(await chrome.storage.local.get(Qe))[Qe];return t&&typeof t=="object"?t:{}}catch{return{}}}async function ln(e){const t=is(e);try{await chrome.storage.local.set({[Qe]:t})}catch(a){const n=Object.entries(t).sort(([,i],[,r])=>{const c=Date.parse(i.resolvedAt)||0;return(Date.parse(r.resolvedAt)||0)-c}),o=Object.fromEntries(n.slice(0,Math.floor(n.length/2)));try{await chrome.storage.local.set({[Qe]:o}),console.warn("[incomplete-resolutions] storage quota hit; pruned to",Object.keys(o).length,"entries",a)}catch(i){await chrome.storage.local.remove(Qe).catch(()=>{}),console.warn("[incomplete-resolutions] storage quota still exceeded after prune; wiped key",i)}}}async function qe(e){const t=await sa();t[cn(e.pageUrl,e.ruleId,e.selector)]=Jo(e),await ln(t)}async function ss(e){if(e.length===0)return;const t=await sa();for(const a of e)t[cn(a.pageUrl,a.ruleId,a.selector)]=Jo(a);await ln(t)}async function Xo(){const e=await sa();return Object.values(e)}async function dn(e){return(await Xo()).filter(a=>a.pageUrl===e)}async function cs(e,t,a){const n=await sa();delete n[cn(e,t,a)],await ln(n)}async function ls(){await chrome.storage.local.remove(Qe)}function ds(e){if(!e.reasoning)return e;const t=e.reasoning.toLowerCase(),a=Dt(t,/verdict\s+corrected\s+to\s+pass|verdict:\s*pass\s+\(corrected\)/gi),n=Dt(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=Dt(t,/actually\s+passes|in\s+fact\s+passes|passes\s+aa/gi),i=Dt(t,/actually\s+fails|in\s+fact\s+fails|fails\s+aa/gi);return o<0&&i<0?e:o>i&&o/t.length>=.5?{...e,verdict:"pass"}:i>o&&i/t.length>=.5?{...e,verdict:"fail"}:e}function Dt(e,t){let a=-1;const n=t.flags.includes("g")?t.flags:t.flags+"g",o=new RegExp(t.source,n);let i;for(;(i=o.exec(e))!==null;)a=i.index,i.index===o.lastIndex&&o.lastIndex++;return a}function us(e){if(e.ruleId!=="color-contrast"&&e.ruleId!=="color-contrast-enhanced"||!e.reasoning||e.verdict!=="fail")return e;const t=ps(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},i=fs(o,{r:n.r,g:n.g,b:n.b}),r=hs(e.reasoning)??4.5;return i<r+.05?e:{...e,verdict:"pass",reasoning:`${e.reasoning}
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/parallel-tab-flow-BuZZIdRb.js","assets/crash-reporter-7_6X-wSd.js","assets/preload-helper-D7HrI6pR.js","assets/diff-NSOR-wHP.js","assets/ai-usage-log-CvwMbWGw.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
var sr=Object.defineProperty;var cr=(e,t,a)=>t in e?sr(e,t,{enumerable:!0,configurable:!0,writable:!0,value:a}):e[t]=a;var Mt=(e,t,a)=>cr(e,typeof t!="symbol"?t+"":t,a);import{_ as en}from"./preload-helper-D7HrI6pR.js";import{c as ee,f as de,o as Ie,k as z,r as ve,h as At,j as Ro}from"./crash-reporter-7_6X-wSd.js";import{a as fe,m as Rn,d as lr,T as dr,b as On,c as tn,g as an,i as Mn}from"./diff-NSOR-wHP.js";import{m as we,e as Na,n as ur,p as pr,q as hr,u as fr,v as gr,w as mr,b as br,g as yr,r as wr,f as vr}from"./ai-usage-log-CvwMbWGw.js";const La=(e,t)=>t.some(a=>e instanceof a);let Dn,Nn;function Ar(){return Dn||(Dn=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function kr(){return Nn||(Nn=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])}const Pa=new WeakMap,wa=new WeakMap,na=new WeakMap;function Ir(e){const t=new Promise((a,n)=>{const o=()=>{e.removeEventListener("success",r),e.removeEventListener("error",i)},r=()=>{a(Ge(e.result)),o()},i=()=>{n(e.error),o()};e.addEventListener("success",r),e.addEventListener("error",i)});return na.set(t,e),t}function xr(e){if(Pa.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)});Pa.set(e,t)}let Fa={get(e,t,a){if(e instanceof IDBTransaction){if(t==="done")return Pa.get(e);if(t==="store")return a.objectStoreNames[1]?void 0:a.objectStore(a.objectStoreNames[0])}return Ge(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 Oo(e){Fa=e(Fa)}function Sr(e){return kr().includes(e)?function(...t){return e.apply(_a(this),t),Ge(this.request)}:function(...t){return Ge(e.apply(_a(this),t))}}function Cr(e){return typeof e=="function"?Sr(e):(e instanceof IDBTransaction&&xr(e),La(e,Ar())?new Proxy(e,Fa):e)}function Ge(e){if(e instanceof IDBRequest)return Ir(e);if(wa.has(e))return wa.get(e);const t=Cr(e);return t!==e&&(wa.set(e,t),na.set(t,e)),t}const _a=e=>na.get(e);function Mo(e,t,{blocked:a,upgrade:n,blocking:o,terminated:r}={}){const i=indexedDB.open(e,t),c=Ge(i);return n&&i.addEventListener("upgradeneeded",l=>{n(Ge(i.result),l.oldVersion,l.newVersion,Ge(i.transaction),l)}),a&&i.addEventListener("blocked",l=>a(l.oldVersion,l.newVersion,l)),c.then(l=>{r&&l.addEventListener("close",()=>r()),o&&l.addEventListener("versionchange",d=>o(d.oldVersion,d.newVersion,d))}).catch(()=>{}),c}const Tr=["get","getKey","getAll","getAllKeys","count"],$r=["put","add","delete","clear"],va=new Map;function Ln(e,t){if(!(e instanceof IDBDatabase&&!(t in e)&&typeof t=="string"))return;if(va.get(t))return va.get(t);const a=t.replace(/FromIndex$/,""),n=t!==a,o=$r.includes(a);if(!(a in(n?IDBIndex:IDBObjectStore).prototype)||!(o||Tr.includes(a)))return;const r=async function(i,...c){const l=this.transaction(i,o?"readwrite":"readonly");let d=l.store;return n&&(d=d.index(c.shift())),(await Promise.all([d[a](...c),o&&l.done]))[0]};return va.set(t,r),r}Oo(e=>({...e,get:(t,a,n)=>Ln(t,a)||e.get(t,a,n),has:(t,a)=>!!Ln(t,a)||e.has(t,a)}));const Er=["continue","continuePrimaryKey","advance"],Pn={},Ua=new WeakMap,Do=new WeakMap,Rr={get(e,t){if(!Er.includes(t))return e[t];let a=Pn[t];return a||(a=Pn[t]=function(...n){Ua.set(this,Do.get(this)[t](...n))}),a}};async function*Or(...e){let t=this;if(t instanceof IDBCursor||(t=await t.openCursor(...e)),!t)return;t=t;const a=new Proxy(t,Rr);for(Do.set(a,t),na.set(a,_a(t));t;)yield a,t=await(Ua.get(a)||t.continue()),Ua.delete(a)}function Fn(e,t){return t===Symbol.asyncIterator&&La(e,[IDBIndex,IDBObjectStore,IDBCursor])||t==="iterate"&&La(e,[IDBIndex,IDBObjectStore])}Oo(e=>({...e,get(t,a,n){return Fn(t,a)?Or:e.get(t,a,n)},has(t,a){return Fn(t,a)||e.has(t,a)}}));const Mr="wcag-component-auditor",Dr=3;let Xe=null;function ie(){return Xe||(Xe=Mo(Mr,Dr,{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")}}})),Xe}async function Nr(){Xe&&(await Xe).close(),Xe=null}async function oa(e){return(await ie()).get("baselines",e)}async function nn(e){await(await ie()).put("baselines",e)}async function No(e){await(await ie()).delete("baselines",e)}async function Lo(){return(await ie()).getAll("baselines")}async function Lr(e){return(await ie()).getAllFromIndex("baselines","byUrl",e)}async function Pr(e){return(await ie()).add("audit-history",e)}async function Fr(e){return(await ie()).getAllFromIndex("audit-history","byComponentId",e)}async function Po(){return(await ie()).get("site-crawl-per-url","current")}async function Fo(e){await(await ie()).put("site-crawl-per-url",{...e,slot:"current"})}async function on(){await(await ie()).delete("site-crawl-per-url","current")}async function _o(){return(await ie()).getAll("scheduled-audits")}async function Uo(e){return(await ie()).get("scheduled-audits",e)}async function rn(e){await(await ie()).put("scheduled-audits",e)}async function _r(e){await(await ie()).delete("scheduled-audits",e)}async function Wo(e){return(await ie()).add("scheduled-audit-results",e)}async function Ur(e){return(await ie()).getAllFromIndex("scheduled-audit-results","byScheduleId",e)}async function Wr(){return(await ie()).getAll("scheduled-audit-results")}async function qo(e,t=50){const a=await ie(),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 qr(e){const a=(await ie()).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 Vr=Object.freeze(Object.defineProperty({__proto__:null,_resetDbForTesting:Nr,appendAuditHistory:Pr,appendScheduledAuditResult:Wo,deleteBaseline:No,deleteScheduledAudit:_r,deleteScheduledAuditResultsForScheduleId:qr,deleteSiteCrawlPerUrl:on,getBaseline:oa,getDb:ie,getScheduledAudit:Uo,getSiteCrawlPerUrl:Po,listAllScheduledAuditResults:Wr,listAuditHistoryForComponent:Fr,listBaselines:Lo,listBaselinesByUrl:Lr,listScheduledAuditResultsByScheduleId:Ur,listScheduledAudits:_o,pruneScheduledAuditResults:qo,putScheduledAudit:rn,setBaseline:nn,setSiteCrawlPerUrl:Fo},Symbol.toStringTag,{value:"Module"})),jt="siteCrawlReport";async function sn(){var a;if(typeof chrome>"u"||!((a=chrome.storage)!=null&&a.local))return null;const t=(await chrome.storage.local.get([jt]))[jt];return t&&typeof t=="object"?t:null}async function Vo(e){var t;if(!(typeof chrome>"u"||!((t=chrome.storage)!=null&&t.local))){if(e===null){await chrome.storage.local.remove([jt]),await on().catch(()=>{});return}await chrome.storage.local.set({[jt]:e})}}async function Gt(){try{const e=await Po();return(e==null?void 0:e.perUrl)??null}catch{return null}}async function jo(e,t){if(e===null){await on();return}await Fo({startUrl:(t==null?void 0:t.startUrl)??"",finishedAt:(t==null?void 0:t.finishedAt)??new Date().toISOString(),perUrl:e})}const kp=Object.freeze(Object.defineProperty({__proto__:null,loadSiteCrawlPerUrlResults:Gt,loadSiteCrawlReport:sn,saveSiteCrawlPerUrlResults:jo,saveSiteCrawlReport:Vo},Symbol.toStringTag,{value:"Module"}));async function Fe(){return!1}function Ip(e){return!1}const St="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 Go(){const e=await chrome.tabs.query({currentWindow:!0}),t=e.find(n=>n.active);if(t!=null&&t.id&&_n(t.url))return t.id;const a=e.find(n=>n.id&&_n(n.url));return(a==null?void 0:a.id)??null}function _n(e){return typeof e=="string"&&/^https?:\/\//.test(e)}const Wa="rubricConfigCache",jr=7*24*60*60*1e3;function xp(e){const t=Date.now()-e.fetchedAt;return t>=jr?"expired":t>=60*60*1e3?"stale":"fresh"}async function Sp(){var a;if(typeof chrome>"u"||!((a=chrome.storage)!=null&&a.local))return null;const t=(await chrome.storage.local.get(Wa))[Wa];return!t||typeof t!="object"?null:t}async function Cp(e){var t;typeof chrome>"u"||!((t=chrome.storage)!=null&&t.local)||await chrome.storage.local.set({[Wa]:e})}let zo=null;function Tp(e){zo=e}function Gr(){return zo}const qa="acknowledgedFindings";async function ia(){var a;if(typeof chrome>"u"||!((a=chrome.storage)!=null&&a.local))return[];const t=(await chrome.storage.local.get([qa]))[qa];return Array.isArray(t)?t:[]}async function ra(e){const t=await ia();return new Set(t.filter(a=>a.componentId===e).map(a=>a.matchKey))}async function zr(e){const a=(await ia()).filter(n=>!(n.componentId===e.componentId&&n.matchKey===e.matchKey));a.push({...e,acknowledgedAt:new Date().toISOString()}),await Ho(a)}async function Hr(e,t){const n=(await ia()).filter(o=>!(o.componentId===e&&o.matchKey===t));await Ho(n)}async function Ho(e){var t;typeof chrome>"u"||!((t=chrome.storage)!=null&&t.local)||await chrome.storage.local.set({[qa]:e})}const $p=Object.freeze(Object.defineProperty({__proto__:null,acknowledgeFinding:zr,loadAcknowledged:ia,loadAcknowledgedKeysForComponent:ra,unacknowledgeFinding:Hr},Symbol.toStringTag,{value:"Module"})),Br=/:nth-(?:last-)?(?:child|of-type)\([^)]+\)/g,Kr=/\[id="[^"]*"\]/g,Yr=/\[data-testid="[^"]*"\]/g,Jr=/#[\w-]*\d[\w-]*/g,Xr=/\[href(?:[\^$*~|]?=("|')[^"']*\1)?\]/g,Qr=/\[aria-label(?:[\^$*~|]?=("|')[^"']*\1)?\]/g,Zr=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 es(e){return e&&e.replace(Br,"").replace(Kr,"").replace(Yr,"").replace(Jr,"").replace(Xr,"").replace(Qr,"").replace(/\s+/g," ").trim()}function Te(e,t){return Zr.has(e)?`${e}::__structural__`:`${e}::${es(t)}`}const Un={minor:0,moderate:1,serious:2,critical:3};function Bo(e){const t=new Map;for(const a of e){const n=Te(a.ruleId,a.target.selector),o=t.get(n);if(!o){t.set(n,a);continue}(Un[a.impact]??0)>(Un[o.impact]??0)&&t.set(n,a)}return Array.from(t.values())}const Ko=[{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 Ep(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 Ko)for(const o of n.axeRules)if(a.has(o))return n.id;return null}function ts(e){const t=Ko.map(o=>ns(o,e)),a=as(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 as(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 ns(e,t){const a=new Set(e.axeRules),n=t.violations.filter(E=>a.has(E.ruleId)),o=t.manualRuns.filter(E=>e.igtWorkflowIds.includes(E.workflowId)),r=e.igtWorkflowIds.map(E=>t.workflows.find(V=>V.id===E)).filter(E=>E!=null);let i=r.length>0;for(const E of r){const V=o.find($=>$.workflowId===E.id);if((V?Object.keys(V.steps).length:0)!==E.steps.length){i=!1;break}}const c=o.some(E=>Object.keys(E.steps).length>0),l=e.verifiedByWorkflowIds??[],d=t.manualRuns.filter(E=>l.includes(E.workflowId)),u=l.map(E=>t.workflows.find(V=>V.id===E)).filter(E=>E!=null);let m=l.length>0&&u.length===l.length;for(const E of u){const V=d.find($=>$.workflowId===E.id);if((V?Object.keys(V.steps).length:0)!==E.steps.length){m=!1;break}}let p=null;if(m)for(const E of d)E.completedAt&&(p===null||E.completedAt>p)&&(p=E.completedAt);const f=e.heuristic==="tab-order"?t.heuristicCounts.tabOrder??0:e.heuristic==="reading-order"?t.heuristicCounts.readingOrder??0:0,g=l[0]??e.igtWorkflowIds[0]??null,h=t.interactiveAuditVerdicts,y=[];h&&(e.id==="tab-order"&&h.focusOrder&&y.push({verdict:h.focusOrder,criterionId:"2.4.3"}),e.id==="keyboard"&&(h.keyboardTrap&&y.push({verdict:h.keyboardTrap,criterionId:"2.1.2"}),h.focusVisible&&y.push({verdict:h.focusVisible,criterionId:"2.4.7"})),e.id==="reading-order"&&h.readingOrder&&y.push({verdict:h.readingOrder,criterionId:"1.3.2"}),e.id==="contrast"&&h.nonTextContrast&&y.push({verdict:h.nonTextContrast,criterionId:"1.4.11"}));const b=y.some(E=>E.verdict==="fail");if(y.length>0&&y.every(E=>E.verdict==="pass")&&l.length>0&&!m)return{id:e.id,label:e.label,letter:"A",untested:!1,needsIgt:!1,igtCompleted:!1,verifiedByIgt:!1,verifiedAt:y.length>0?new Date().toISOString():null,suppressedHeuristicCount:f,primaryVerifierWorkflowId:g,counts:{critical:0,serious:0,moderate:0,minor:0},caps:{cappedAtC:!1,cappedAtB:!1},aiVerifiedCriteria:y.map(E=>E.criterionId)};if(m&&l.length>0)return{id:e.id,label:e.label,letter:"A",untested:!1,needsIgt:!1,igtCompleted:!0,verifiedByIgt:!0,verifiedAt:p,suppressedHeuristicCount:f,primaryVerifierWorkflowId:g,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||l.length>0,igtCompleted:!1,verifiedByIgt:!1,verifiedAt:null,suppressedHeuristicCount:0,primaryVerifierWorkflowId:g,counts:{critical:0,serious:0,moderate:0,minor:0},caps:{cappedAtC:!1,cappedAtB:!1}};const x={critical:0,serious:0,moderate:0,minor:0},w=Bo(n);for(const E of w)x[E.impact]++;const R=(t.aiResolvedFails??[]).filter(E=>a.has(E.ruleId));if(R.length>0){const E=new Set(w.map(V=>`${V.ruleId}::${V.target.selector}`));for(const V of R){const D=`${V.ruleId}::${V.selector}`;E.has(D)||(E.add(D),x[V.impact]++)}}const T=y.length>0&&y.some(E=>E.verdict==="pass"||E.verdict==="fail"),P=T?f:0;T||(x.serious+=f),b&&(x.serious+=y.filter(E=>E.verdict==="fail").length);for(const E of o){const V=r.find(D=>D.id===E.workflowId);if(V)for(const D of V.steps){const $=E.steps[D.id];($==null?void 0:$.status)==="fail"&&(D.severity==="required"?x.serious++:x.moderate++)}}const _=x.critical>0,N=x.serious>0;let M;x.critical>=5?M="F":x.critical>=1?M="D":x.serious>=1?M="C":x.moderate>=1?M="B":M="A";const S=M!=="A"&&(s&&!i||l.length>0&&!m);return{id:e.id,label:e.label,letter:M,untested:!1,needsIgt:S,igtCompleted:i,verifiedByIgt:!1,verifiedAt:null,suppressedHeuristicCount:P,primaryVerifierWorkflowId:g,counts:x,caps:{cappedAtC:_,cappedAtB:N}}}const Qe="incompleteResolutions",Wn=2e3,qn=600;function cn(e,t,a){return`${e}::${t}::${a}`}function Yo(e){return e.reasoning&&e.reasoning.length>qn?{...e,reasoning:e.reasoning.slice(0,qn-1)+"…"}:e}function os(e){const t=Object.entries(e);if(t.length<=Wn)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,Wn))}async function sa(){try{const t=(await chrome.storage.local.get(Qe))[Qe];return t&&typeof t=="object"?t:{}}catch{return{}}}async function ln(e){const t=os(e);try{await chrome.storage.local.set({[Qe]: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({[Qe]:o}),console.warn("[incomplete-resolutions] storage quota hit; pruned to",Object.keys(o).length,"entries",a)}catch(r){await chrome.storage.local.remove(Qe).catch(()=>{}),console.warn("[incomplete-resolutions] storage quota still exceeded after prune; wiped key",r)}}}async function qe(e){const t=await sa();t[cn(e.pageUrl,e.ruleId,e.selector)]=Yo(e),await ln(t)}async function is(e){if(e.length===0)return;const t=await sa();for(const a of e)t[cn(a.pageUrl,a.ruleId,a.selector)]=Yo(a);await ln(t)}async function Jo(){const e=await sa();return Object.values(e)}async function dn(e){return(await Jo()).filter(a=>a.pageUrl===e)}async function rs(e,t,a){const n=await sa();delete n[cn(e,t,a)],await ln(n)}async function ss(){await chrome.storage.local.remove(Qe)}function cs(e){if(!e.reasoning)return e;const t=e.reasoning.toLowerCase(),a=Dt(t,/verdict\s+corrected\s+to\s+pass|verdict:\s*pass\s+\(corrected\)/gi),n=Dt(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=Dt(t,/actually\s+passes|in\s+fact\s+passes|passes\s+aa/gi),r=Dt(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 Dt(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 ls(e){if(e.ruleId!=="color-contrast"&&e.ruleId!=="color-contrast-enhanced"||!e.reasoning||e.verdict!=="fail")return e;const t=ds(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=ps(o,{r:n.r,g:n.g,b:n.b}),i=us(e.reasoning)??4.5;return r<i+.05?e:{...e,verdict:"pass",reasoning:`${e.reasoning}
|
|
3
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}) → ${i.toFixed(2)}:1 against threshold ${r}: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 ps(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 hs(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 fs(e,t){const a=l=>{const d=l/255;return d<=.03928?d/12.92:Math.pow((d+.055)/1.055,2.4)},n=l=>.2126*a(l.r)+.7152*a(l.g)+.0722*a(l.b),o=n(e),i=n(t),r=Math.max(o,i),c=Math.min(o,i);return(r+.05)/(c+.05)}const gs=Object.freeze(Object.defineProperty({__proto__:null,applyContrastMathSalvage:us,applySelfCorrectionSalvage:ds,clearAllResolutions:ls,deleteResolution:cs,getAllResolutions:Xo,getResolutionsForPage:dn,saveResolution:qe,saveResolutions:ss},Symbol.toStringTag,{value:"Module"})),ms={id:"keyboard",name:"Keyboard navigation",blurb:"Verify everyone who relies on the keyboard can reach, operate, and escape every interactive element. WCAG 2.1.1, 2.1.2, 2.4.3, 2.4.7.",steps:[{id:"tab-reaches-all",prompt:"Tab through the component from start to finish. Compare against the Tab-order overlay.",question:"Did Tab reach every interactive element (button, link, form field, custom widget)?",wcag:"2.1.1",visualizer:"tab-order",severity:"required"},{id:"tab-order-logical",prompt:"Watch the focus indicator as you Tab. Compare visual order vs the Tab-order numbered overlay.",question:"Does focus move in a logical order matching the visual layout (left-to-right, top-to-bottom)? Red badges indicate visual mismatches.",wcag:"2.4.3",visualizer:"tab-order",severity:"required",autoDismissActivity:"tab-order"},{id:"focus-visible",prompt:"On each focused element, confirm a visible focus indicator (outline, ring, color change).",question:"Is the focus indicator clearly visible on every interactive element?",wcag:"2.4.7",relatedAxeRule:"focus-order-semantics",severity:"required"},{id:"no-trap",prompt:"Tab forward and Shift+Tab backward through any modal, dropdown, or custom widget.",question:"Can you escape the widget with Tab/Shift+Tab/Esc — no trapping?",wcag:"2.1.2",severity:"required"},{id:"enter-activates",prompt:"Focus a button or link and press Enter (and Space for buttons).",question:"Did Enter/Space activate the control as expected?",wcag:"2.1.1",severity:"required"},{id:"esc-closes",prompt:"Open any modal, dropdown, or popover and press Escape.",question:"Did Escape close the overlay and return focus to the trigger?",wcag:"2.1.2",severity:"required"},{id:"arrow-keys-grouped",prompt:"For grouped widgets (radio, tabs, listbox, menu): focus into the group, then use arrow keys.",question:"Do arrow keys move within the group as expected (and Tab moves out of it)?",wcag:"2.1.1",severity:"advisory"},{id:"character-key-shortcuts",prompt:'Identify any single-character keyboard shortcuts (e.g., "S" to open search, "/" to focus the search box, J/K for next/prev). If none exist, mark N/A.',question:"For every single-character shortcut: can it be turned off, remapped to a modifier-key combo, OR is it only active when the relevant control has focus? (Prevents accidental activation by speech-input users.)",wcag:"2.1.4",severity:"required"}]},bs={id:"screen-reader",name:"Screen reader readiness",blurb:"Verify the component is operable and meaningful via a screen reader. Use NVDA (Windows), VoiceOver (macOS/iOS), or TalkBack (Android). WCAG 1.3.1, 4.1.2.",steps:[{id:"sr-announces-on-focus",prompt:"Activate your screen reader and Tab to each interactive element.",question:"Does the SR announce a meaningful name + role + state for every focused element?",wcag:"4.1.2",relatedAxeRule:"aria-required-attr",severity:"required"},{id:"sr-headings-navigate",prompt:"Use the SR's heading-navigation shortcut (NVDA: H, VoiceOver: VO+Cmd+H). Compare against the Outline overlay.",question:"Are all logical sections reachable via heading navigation, in correct hierarchy order?",wcag:"1.3.1",relatedAxeRule:"heading-order",visualizer:"outline",severity:"required"},{id:"sr-reading-order",prompt:"Read the page top-to-bottom using the SR's read-all command (NVDA: NumPad+Down, VoiceOver: VO+A). Compare against the Reading-order numbered overlay.",question:"Does the SR read content in the meaningful order implied by the visual layout (1.3.2 Meaningful Sequence)? Red badges in the Reading-order overlay show DOM-vs-visual divergences.",wcag:"1.3.2",visualizer:"reading-order",severity:"required",autoDismissActivity:"reading-order"},{id:"sr-landmarks",prompt:"Use the SR's landmark-navigation shortcut (NVDA: D, VoiceOver: VO+U → Landmarks). Compare against the Outline overlay.",question:"Can the user jump to main, nav, banner, contentinfo via landmark navigation?",wcag:"1.3.1",relatedAxeRule:"region",visualizer:"outline",severity:"required"},{id:"sr-live-region",prompt:"Trigger any dynamic update (form submission, status change, toast).",question:'Does the SR announce the change automatically (via aria-live or role="status"/role="alert")?',wcag:"4.1.3",severity:"required"},{id:"sr-form-errors",prompt:"Submit a form with an invalid field.",question:"Does the SR announce the error and which field it relates to?",wcag:"3.3.1",severity:"required"},{id:"sr-images-meaningful",prompt:"Navigate over each image (NVDA: G, VoiceOver: VO+Cmd+G).",question:"Does each meaningful image have descriptive alt text? Are decorative images silent?",wcag:"1.1.1",relatedAxeRule:"image-alt",severity:"required"}]},ys={id:"focus-management",name:"Focus management",blurb:"Verify focus moves and restores correctly across overlays, navigations, and dynamic content. WCAG 2.4.3, 2.4.7, 3.2.2.",steps:[{id:"modal-initial-focus",prompt:"Open a modal/dialog.",question:"Did focus move into the modal automatically (typically to the first focusable element or a heading)?",severity:"required"},{id:"modal-restored-on-close",prompt:"Close a modal/dialog (via close button or Esc).",question:"Was focus restored to the element that opened it?",severity:"required"},{id:"modal-trap-while-open",prompt:"While a modal is open, Tab/Shift+Tab through it.",question:"Is focus trapped inside the modal until it closes?",severity:"required"},{id:"route-change-focus",prompt:"Trigger a client-side route change.",question:"Did focus move sensibly (to the new page heading, or main landmark) — not to <body>?",severity:"required"},{id:"expanded-focus",prompt:"Open an expandable section (accordion, dropdown, collapsible).",question:"Is focus moved into or near the newly-revealed content (or kept on the trigger appropriately)?",severity:"advisory"},{id:"no-unexpected-focus-move",prompt:"Type or click in form fields without explicitly tabbing.",question:"Does focus stay where you put it (no auto-jump on input)?",wcag:"3.2.2",severity:"required"},{id:"no-context-change-on-focus",prompt:"Tab into each interactive element on the page.",question:"Does merely RECEIVING focus on an element NOT trigger a context change (auto-submit, open modal, navigate elsewhere, change focus to a different field)? (Context change on focus violates 3.2.1; activating a control via click/Enter is fine.)",wcag:"3.2.1",severity:"required"}]},ws={id:"forms",name:"Forms",blurb:"Verify form fields are properly labeled, errors are clear, and the experience works for assistive technology. WCAG 1.3.1, 3.3.1, 3.3.2, 4.1.2.",steps:[{id:"visible-labels",prompt:"Look at every form field.",question:"Does every field have a visible label (not just placeholder text)?",wcag:"3.3.2",relatedAxeRule:"label",severity:"required"},{id:"label-association",prompt:"Click each visible label.",question:"Did clicking the label focus the associated input?",wcag:"1.3.1",relatedAxeRule:"label",severity:"required"},{id:"required-marked",prompt:"Identify required fields.",question:"Are required fields marked both visually AND programmatically (aria-required or required attribute)?",wcag:"3.3.2",severity:"required"},{id:"autocomplete-set",prompt:"For personal-info fields (name, email, phone, address): inspect the autocomplete attribute.",question:'Is autocomplete set with a valid HTML5 token (e.g., "email", "given-name", "tel")?',wcag:"1.3.5",relatedAxeRule:"autocomplete-valid",severity:"required"},{id:"error-text",prompt:"Submit with invalid input.",question:'Are error messages specific (not just "invalid"), shown near the field, and programmatically associated (aria-describedby)?',wcag:"3.3.1",severity:"required"},{id:"no-color-only-error",prompt:"Look at how errors are signaled.",question:"Is the error indicated by more than just color (also icon, text, or border style)?",wcag:"1.4.1",severity:"required"},{id:"success-announced",prompt:"Submit a form successfully.",question:'Is the success state announced to screen readers (via aria-live or role="status")?',wcag:"4.1.3",severity:"advisory"},{id:"error-suggestion",prompt:"Submit a form with an obvious invalid input (wrong email format, password too short, missing required field).",question:'Does the error message INCLUDE a specific suggestion for fixing it (not just "invalid")?',wcag:"3.3.3",severity:"required"},{id:"redundant-entry",prompt:"Identify any multi-step or multi-form flow where the user re-enters previously provided information (shipping = billing, profile data repeated in another form).",question:"Is previously-entered information auto-populated, selectable from a list, or otherwise NOT manually re-entered?",wcag:"3.3.7",severity:"required"},{id:"accessible-authentication",prompt:"Identify the site's authentication flow (login, password reset, multi-factor).",question:'Does auth NOT require a cognitive function test (e.g., remembering / transcribing characters), OR is an accessible alternative offered (passkey, magic link, password-manager autofill, "show password" toggle)?',wcag:"3.3.8",severity:"required"}]},vs={id:"page-structure",name:"Page structure",blurb:"Verify the page declares its language, has a meaningful title, and exposes a sensible heading + landmark hierarchy. WCAG 2.4.2, 3.1.1, 3.1.2, 1.3.1, 2.4.6.",steps:[{id:"page-title",prompt:"Look at the browser tab — is the page title set and meaningful?",question:'Does the title describe the page topic / purpose (not just "Untitled" or the site name)?',wcag:"2.4.2",relatedAxeRule:"document-title",severity:"required"},{id:"page-lang",prompt:"Inspect the <html> element's lang attribute.",question:'Is lang set to a valid language code (e.g., "en", "es-MX")?',wcag:"3.1.1",relatedAxeRule:"html-has-lang",severity:"required"},{id:"lang-of-parts",prompt:"For any text not in the page's primary language (foreign quote, brand name in another language), inspect the parent element.",question:"Is lang attribute set on those elements to indicate the language change?",wcag:"3.1.2",severity:"advisory"},{id:"h1-present",prompt:"Use the Outline visualizer or SR heading shortcut to find the h1.",question:"Is there exactly one h1, and does it describe the main content of the page?",wcag:"1.3.1",relatedAxeRule:"page-has-heading-one",visualizer:"outline",severity:"required"},{id:"descriptive-headings",prompt:"Read each heading. Imagine someone listening only to the heading text.",question:"Does each heading describe its section meaningfully on its own?",wcag:"2.4.6",severity:"required"},{id:"main-landmark",prompt:"Use the Outline visualizer or SR landmark shortcut.",question:"Is there exactly one <main> landmark wrapping the page's primary content?",wcag:"1.3.1",relatedAxeRule:"landmark-one-main",visualizer:"outline",severity:"required"},{id:"parsing-well-formed",prompt:"Open DevTools → Console. Reload the page and check for HTML parse errors. Or run W3C validator on the URL.",question:"Is the page's markup well-formed (no duplicate IDs in scope, no invalid nesting, no missing required attributes)? WCAG 4.1.1 was obsoleted in 2.2 but still applies to 2.1 conformance claims.",wcag:"4.1.1",severity:"required"}]},As={id:"visual-indicators",name:"Visual indicators",blurb:"Verify nothing relies on color/shape/position alone, and non-text contrast meets thresholds for UI components and focus rings. WCAG 1.3.3, 1.4.1, 1.4.11.",steps:[{id:"no-color-only-info",prompt:"Scan instructions, error messages, charts, status indicators.",question:"Is information conveyed by something OTHER than color alone (text, icon, pattern, label)?",wcag:"1.4.1",severity:"required"},{id:"no-sensory-only",prompt:'Look for instructions referencing shape ("the round button"), location ("on the left"), sound ("the chime"), or visual cues alone.',question:"Are those instructions backed up by a programmatic identifier (label, role, accessible name)?",wcag:"1.3.3",severity:"required"},{id:"non-text-contrast",prompt:"For UI components (form-field borders, focus rings, icons-as-buttons), verify contrast vs adjacent colors. Use a contrast checker if needed.",question:"Do non-text UI components meet ≥3:1 contrast against adjacent colors?",wcag:"1.4.11",severity:"required"},{id:"focus-ring-contrast",prompt:"Tab through; for each focused element, verify the focus ring is visible against both the element and the page background.",question:"Does the focus ring meet ≥3:1 contrast on every focusable surface?",wcag:"1.4.11",visualizer:"tab-order",severity:"required"},{id:"state-changes-visible",prompt:"For toggleable controls (checkboxes, switches, expanded states): change them and observe.",question:"Is the state change conveyed visibly AND programmatically (aria-pressed/expanded/checked)?",wcag:"4.1.2",severity:"required"}]},ks={id:"reflow",name:"Reflow & text spacing",blurb:"Verify the layout survives narrow viewports, browser zoom, and user-overridden text spacing. WCAG 1.4.4, 1.4.10, 1.4.12.",steps:[{id:"resize-320",prompt:"Resize the browser to 320px wide (or set DevTools device toolbar to 320×256).",question:"Does content reflow without two-dimensional scrolling? (Vertical scroll OK; horizontal scroll within content blocks NOT OK.)",wcag:"1.4.10",relatedAxeRule:"wcagcheckr-reflow",severity:"required"},{id:"zoom-200",prompt:"In a desktop viewport, zoom the browser to 200%.",question:"Is all content + functionality available, with no text clipping or unusable controls?",wcag:"1.4.4",severity:"required"},{id:"text-spacing-override",prompt:"Apply text-spacing override (line-height: 1.5, paragraph spacing 2x font-size, letter-spacing 0.12em, word-spacing 0.16em) via a bookmarklet or DevTools.",question:"Does content stay readable with no overlap or clipping?",wcag:"1.4.12",severity:"required"},{id:"no-fixed-pixel-text",prompt:"Inspect text styles for fixed px-based font sizes, line-heights.",question:"Are text dimensions set in relative units (rem/em/%) so they scale with user settings?",severity:"advisory"},{id:"orientation-not-locked",prompt:"Rotate a mobile device (or use DevTools device toolbar to rotate) between portrait and landscape.",question:"Does the layout adapt to both orientations? (Content not locked to one orientation unless essential.)",wcag:"1.3.4",severity:"required"},{id:"images-of-text",prompt:"Look for marketing banners, hero images, or any image that contains substantial text content as part of the raster.",question:"Is real HTML text used in preference to images-of-text, except for logos / decorative purposes? (Images-of-text fail to scale with zoom, can't be selected, and don't respect user text settings.)",wcag:"1.4.5",severity:"required"}]},Is={id:"hover-focus-content",name:"Content on hover or focus",blurb:"Tooltips, dropdown previews, and any content revealed on hover or focus must be dismissable, hoverable, and persistent. WCAG 1.4.13.",steps:[{id:"dismissable",prompt:"Hover or focus to reveal a tooltip / popover. Press Escape.",question:"Did Escape dismiss the revealed content without moving pointer or focus?",wcag:"1.4.13",severity:"required"},{id:"hoverable",prompt:"Hover to reveal a tooltip. Move the pointer over the tooltip itself (without losing the trigger's hover).",question:"Does the revealed content stay visible when the pointer enters it?",wcag:"1.4.13",severity:"required"},{id:"persistent",prompt:"Reveal a tooltip and don't do anything else.",question:"Does the content remain visible until the user dismisses it, moves focus/pointer away, or the trigger info is no longer valid?",wcag:"1.4.13",severity:"required"}]},xs={id:"pointer",name:"Pointer interactions",blurb:"Verify gestures, target sizes, and pointer cancellation respect users with motor limitations. WCAG 2.5.1, 2.5.2, 2.5.5/2.5.8.",steps:[{id:"no-multi-point-gesture",prompt:"Identify any feature that requires a multi-point gesture (pinch, two-finger swipe) or path-based gesture (drag along a line).",question:"Is there a single-tap / single-click alternative for that feature?",wcag:"2.5.1",severity:"required"},{id:"pointer-cancellation",prompt:"Mouse-down on a button, drag the pointer OFF the button, then release.",question:"Was the action canceled (the button did NOT activate)? Activation should fire on up-event over the target, not down-event.",wcag:"2.5.2",severity:"required"},{id:"target-size-aa",prompt:"Toggle the Targets visualizer. Look for any red overlays (≥24×24 fail).",question:"Are all interactive targets ≥24×24 CSS px (or have sufficient spacing per WCAG 2.5.8)?",wcag:"2.5.8",relatedAxeRule:"target-size",visualizer:"targets",severity:"required"},{id:"label-in-name",prompt:"For every visually-labeled control (button, link), inspect its accessible name (use the SR or DevTools).",question:"Does the accessible name START with — or fully contain — the visible label text?",wcag:"2.5.3",relatedAxeRule:"label-content-name-mismatch",severity:"required"},{id:"motion-actuation-alt",prompt:"Identify any feature that triggers on device motion (shake to undo, tilt to scroll, step counter).",question:"Is there a non-motion alternative (button / control) for every motion-triggered function, AND can motion be disabled?",wcag:"2.5.4",severity:"required"},{id:"dragging-alternative",prompt:"Identify any feature that requires a dragging movement (slider thumb, drag-to-rearrange, swipe-to-delete).",question:"Is there a single-tap / single-click alternative for every dragging action (e.g., +/- buttons next to a slider, up/down buttons next to draggable list items)?",wcag:"2.5.7",severity:"required"}]},Ss={id:"time-based",name:"Time-based behaviors",blurb:"Verify time limits, auto-updating content, and motion can be controlled by users. WCAG 2.2.1, 2.2.2, 2.3.1.",steps:[{id:"time-limits-adjustable",prompt:"Identify any time-limited interaction (session timeout, form auto-submit, OTP expiration).",question:"Can the user turn off, adjust, or extend the time limit before it expires (warning + control before the deadline)?",wcag:"2.2.1",severity:"required"},{id:"pause-moving-content",prompt:"Look for content that moves, blinks, scrolls, or auto-updates for >5 seconds (carousels, animated banners, news tickers, auto-refreshing feeds).",question:"Is there a control to pause / stop / hide the moving content?",wcag:"2.2.2",severity:"required"},{id:"no-flash",prompt:"Identify any flashing or blinking content (>3 flashes per second).",question:"Is flashing absent, OR limited below the general/red flash thresholds?",wcag:"2.3.1",severity:"required"},{id:"reduced-motion-honored",prompt:'Enable system "reduce motion" preference. Reload the page.',question:"Does the site honor prefers-reduced-motion (parallax / animations / spinners minimized or disabled)?",wcag:"2.3.3",severity:"advisory"}]},Cs={id:"error-prevention",name:"Error prevention",blurb:"Verify destructive, financial, or legal actions are reversible, checked, or confirmed. WCAG 3.3.4, 3.3.6.",steps:[{id:"destructive-confirm",prompt:"Identify destructive actions (delete account, cancel subscription, destroy data, send irreversible message).",question:'Is each destructive action reversible (undo), or checked (validation), or confirmed (explicit "Are you sure?" dialog)?',wcag:"3.3.4",severity:"required"},{id:"financial-confirm",prompt:"Identify financial / legal commitments (purchase, contract sign, transfer).",question:"Before submission, does the user see a review screen and an explicit confirmation step?",wcag:"3.3.4",severity:"required"},{id:"undo-available",prompt:'Test "destructive" actions on user content (delete a note, archive an item).',question:'Is there an undo / restore mechanism, even briefly (toast with "undo" button)?',wcag:"3.3.6",severity:"advisory"}]},Ts={id:"consistency",name:"Consistency",blurb:"Verify navigation, identification, and user paths are consistent across pages. WCAG 2.4.5, 3.2.3, 3.2.4.",steps:[{id:"consistent-nav",prompt:"Compare the primary navigation across 3+ pages.",question:"Does the same navigation appear in the same order on every page?",wcag:"3.2.3",severity:"required"},{id:"consistent-id",prompt:'Compare the same UI element appearing on multiple pages (e.g., a search icon, a "Help" link).',question:"Does the same component have the same accessible name everywhere it appears?",wcag:"3.2.4",severity:"required"},{id:"multiple-ways",prompt:"Beyond the primary navigation, is there a second way to find a page (search, sitemap, related links, breadcrumbs)?",question:"Are there at least 2 ways to locate any page (single-process pages exempt)?",wcag:"2.4.5",severity:"required"},{id:"skip-link",prompt:"Tab once when the page loads.",question:'Does the first focusable element offer a "Skip to main content" link (or equivalent bypass)?',wcag:"2.4.1",relatedAxeRule:"bypass",severity:"required"},{id:"consistent-help",prompt:"Identify pages that surface a help mechanism (contact info, help link, FAQ link, chatbot trigger). Compare position + order across pages.",question:"When the same help mechanism appears on multiple pages, does it appear in the same relative order (e.g., always last in the header)?",wcag:"3.2.6",severity:"required"}]},$s={id:"time-based-media",name:"Time-based media",blurb:'Verify audio + video have the alternatives required by WCAG. If the site has no time-based media, mark every step "Not applicable." WCAG 1.2.1, 1.2.2, 1.2.3, 1.2.4, 1.2.5, 1.4.2.',steps:[{id:"prerecorded-audio-only-alt",prompt:"Identify any prerecorded audio-only content (podcast embed, audio quote, voice message).",question:"Does each prerecorded audio-only file have a text transcript readable on the page (or linked from it)?",wcag:"1.2.1",severity:"required"},{id:"prerecorded-video-only-alt",prompt:"Identify any prerecorded silent video (animated GIF with content, silent screencast, animated explainer).",question:"Does each prerecorded video-only file have an equivalent text or audio description?",wcag:"1.2.1",severity:"required"},{id:"prerecorded-captions",prompt:"Identify any prerecorded video that includes audio (interviews, tutorials, marketing videos).",question:"Does each video provide synchronized captions for ALL spoken content + meaningful non-speech sound?",wcag:"1.2.2",severity:"required"},{id:"prerecorded-alt-for-video",prompt:"For each prerecorded video with audio, check if there's a full text transcript on the page (covering both audio dialog AND visual action) OR if audio description is provided.",question:"Does each prerecorded video have either a full text alternative OR an audio-description track?",wcag:"1.2.3",severity:"required"},{id:"prerecorded-audio-description",prompt:"Watch each prerecorded video without looking at it. Listen only.",question:"Is all visually-conveyed information also conveyed in the audio (either built into the narration OR via a separate audio-description track)?",wcag:"1.2.5",severity:"required"},{id:"live-captions",prompt:"Identify any LIVE audio/video stream (live shopping, webinar, conference broadcast).",question:"Does each live broadcast provide real-time captions?",wcag:"1.2.4",severity:"required"},{id:"audio-control",prompt:"Reload the page. Listen for audio that starts automatically and plays for >3 seconds (background music, autoplay video with sound).",question:"Is there a mechanism to pause / stop the audio, OR can the volume be controlled INDEPENDENTLY from the system volume?",wcag:"1.4.2",severity:"required"}]},Oe=[ms,bs,ys,ws,vs,As,ks,Is,xs,Ss,$s,Cs,Ts];function Mp(e,t){let a=0,n=0,o=0,i=0,r=0;for(const c of t.steps){const l=e.steps[c.id];if(!l){r++;continue}l.status==="pass"?a++:l.status==="fail"?n++:l.status==="not-applicable"?i++:l.status==="skip"?o++:r++}return{passed:a,failed:n,skipped:o,notApplicable:i,unanswered:r,total:t.steps.length,fullyAnswered:r===0}}const zt="interactiveAuditResults";function un(e,t){return`${e}::${t}`}async function Ct(){try{const t=(await chrome.storage.local.get(zt))[zt];return t&&typeof t=="object"?t:{}}catch{return{}}}async function pn(e){await chrome.storage.local.set({[zt]:e})}async function ae(e){const t=await Ct(),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[un(e.componentId,e.criterionId)]=a,await pn(t)}async function Ne(e,t){return(await Ct())[un(e,t)]??null}async function Es(){const e=await Ct();return Object.values(e)}async function Va(e){return(await Es()).filter(a=>a.componentId===e)}async function Dp(e,t){const a=await Ct();delete a[un(e,t)],await pn(a)}async function hn(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 Va(n);for(const i of o)a.push({criterionId:i.criterionId,ruleId:`ai-interactive::${i.criterionId}`,pageUrl:i.pageUrl,verdict:i.verdict,reasoning:i.reasoning})}catch{}return a}async function Np(){try{const e=await Ct();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 pn(e)}catch{try{await chrome.storage.local.remove(zt)}catch{}}}const Rs=ee("walkthrough-acks"),ja="walkthroughAcks";function fn(e,t,a){return`${e}::${t}::${a}`}async function ca(){try{const t=(await chrome.storage.local.get(ja))[ja];return t&&typeof t=="object"?t:{}}catch{return{}}}async function Qo(e){await chrome.storage.local.set({[ja]:e})}async function Lp(e){if(!e.note||!e.note.trim())throw new Error("Acknowledgement requires a non-empty note explaining manual verification.");const t=await ca();t[fn(e.componentId,e.criterionId,e.pageUrl)]={...e,note:e.note.trim()},await Qo(t),Rs.info(`acknowledged ${e.criterionId} on ${e.pageUrl}`)}async function Pp(e,t,a){const n=await ca();delete n[fn(e,t,a)],await Qo(n)}async function Os(e,t,a){return(await ca())[fn(e,t,a)]??null}async function Ms(){const e=await ca();return Object.values(e)}async function Zo(e){const t=new Set;for(const n of e)n&&t.add(n);return t.size===0?[]:(await Ms()).filter(n=>t.has(n.componentId))}const Ds=[{id:"1.1.1",title:"Non-text Content",level:"A",addedIn:"2.0",understandingSlug:"non-text-content",shortDescription:"All non-text content has a text alternative."},{id:"1.2.1",title:"Audio-only and Video-only (Prerecorded)",level:"A",addedIn:"2.0",understandingSlug:"audio-only-and-video-only-prerecorded",shortDescription:"Alternatives for prerecorded audio-only or video-only."},{id:"1.2.2",title:"Captions (Prerecorded)",level:"A",addedIn:"2.0",understandingSlug:"captions-prerecorded",shortDescription:"Captions for prerecorded audio in synchronized media."},{id:"1.2.3",title:"Audio Description or Media Alternative (Prerecorded)",level:"A",addedIn:"2.0",understandingSlug:"audio-description-or-media-alternative-prerecorded",shortDescription:"Alternative for time-based media (prerecorded)."},{id:"1.2.4",title:"Captions (Live)",level:"AA",addedIn:"2.0",understandingSlug:"captions-live",shortDescription:"Captions for live synchronized media."},{id:"1.2.5",title:"Audio Description (Prerecorded)",level:"AA",addedIn:"2.0",understandingSlug:"audio-description-prerecorded",shortDescription:"Audio description for prerecorded video in synchronized media."},{id:"1.2.6",title:"Sign Language (Prerecorded)",level:"AAA",addedIn:"2.0",understandingSlug:"sign-language-prerecorded",shortDescription:"Sign-language interpretation for prerecorded audio."},{id:"1.2.7",title:"Extended Audio Description (Prerecorded)",level:"AAA",addedIn:"2.0",understandingSlug:"extended-audio-description-prerecorded",shortDescription:"Extended audio description for prerecorded video."},{id:"1.2.8",title:"Media Alternative (Prerecorded)",level:"AAA",addedIn:"2.0",understandingSlug:"media-alternative-prerecorded",shortDescription:"Alternative for time-based media (prerecorded)."},{id:"1.2.9",title:"Audio-only (Live)",level:"AAA",addedIn:"2.0",understandingSlug:"audio-only-live",shortDescription:"Alternative for live audio-only content."},{id:"1.3.1",title:"Info and Relationships",level:"A",addedIn:"2.0",understandingSlug:"info-and-relationships",shortDescription:"Information and structural relationships are programmatically determinable."},{id:"1.3.2",title:"Meaningful Sequence",level:"A",addedIn:"2.0",understandingSlug:"meaningful-sequence",shortDescription:"Reading sequence is programmatically determinable."},{id:"1.3.3",title:"Sensory Characteristics",level:"A",addedIn:"2.0",understandingSlug:"sensory-characteristics",shortDescription:"Instructions don't rely solely on shape, color, size, or sound."},{id:"1.3.4",title:"Orientation",level:"AA",addedIn:"2.1",understandingSlug:"orientation",shortDescription:"Content doesn't restrict view to portrait or landscape."},{id:"1.3.5",title:"Identify Input Purpose",level:"AA",addedIn:"2.1",understandingSlug:"identify-input-purpose",shortDescription:"Purpose of input fields is programmatically identifiable."},{id:"1.3.6",title:"Identify Purpose",level:"AAA",addedIn:"2.1",understandingSlug:"identify-purpose",shortDescription:"Purpose of UI components, icons, and regions is identifiable."},{id:"1.4.1",title:"Use of Color",level:"A",addedIn:"2.0",understandingSlug:"use-of-color",shortDescription:"Color is not the only means of conveying information."},{id:"1.4.2",title:"Audio Control",level:"A",addedIn:"2.0",understandingSlug:"audio-control",shortDescription:"Mechanism to pause/stop auto-playing audio over 3s."},{id:"1.4.3",title:"Contrast (Minimum)",level:"AA",addedIn:"2.0",understandingSlug:"contrast-minimum",shortDescription:"Text has 4.5:1 contrast (3:1 for large text)."},{id:"1.4.4",title:"Resize Text",level:"AA",addedIn:"2.0",understandingSlug:"resize-text",shortDescription:"Text resizable to 200% without loss of content/function."},{id:"1.4.5",title:"Images of Text",level:"AA",addedIn:"2.0",understandingSlug:"images-of-text",shortDescription:"Text used in preference to images of text where possible."},{id:"1.4.6",title:"Contrast (Enhanced)",level:"AAA",addedIn:"2.0",understandingSlug:"contrast-enhanced",shortDescription:"Text has 7:1 contrast (4.5:1 for large text)."},{id:"1.4.7",title:"Low or No Background Audio",level:"AAA",addedIn:"2.0",understandingSlug:"low-or-no-background-audio",shortDescription:"Background audio at least 20dB lower than speech."},{id:"1.4.8",title:"Visual Presentation",level:"AAA",addedIn:"2.0",understandingSlug:"visual-presentation",shortDescription:"Configurable visual presentation for blocks of text."},{id:"1.4.9",title:"Images of Text (No Exception)",level:"AAA",addedIn:"2.0",understandingSlug:"images-of-text-no-exception",shortDescription:"Images of text used only for decoration / essential."},{id:"1.4.10",title:"Reflow",level:"AA",addedIn:"2.1",understandingSlug:"reflow",shortDescription:"Content reflows at 320 CSS px without 2D scrolling."},{id:"1.4.11",title:"Non-text Contrast",level:"AA",addedIn:"2.1",understandingSlug:"non-text-contrast",shortDescription:"UI components and graphical objects have 3:1 contrast."},{id:"1.4.12",title:"Text Spacing",level:"AA",addedIn:"2.1",understandingSlug:"text-spacing",shortDescription:"Text spacing overrides don't cause content loss."},{id:"1.4.13",title:"Content on Hover or Focus",level:"AA",addedIn:"2.1",understandingSlug:"content-on-hover-or-focus",shortDescription:"Hover/focus tooltips are dismissible, hoverable, persistent."},{id:"2.1.1",title:"Keyboard",level:"A",addedIn:"2.0",understandingSlug:"keyboard",shortDescription:"All functionality available from the keyboard."},{id:"2.1.2",title:"No Keyboard Trap",level:"A",addedIn:"2.0",understandingSlug:"no-keyboard-trap",shortDescription:"Keyboard focus can move away from any component."},{id:"2.1.3",title:"Keyboard (No Exception)",level:"AAA",addedIn:"2.0",understandingSlug:"keyboard-no-exception",shortDescription:"All functionality is keyboard-operable without timing."},{id:"2.1.4",title:"Character Key Shortcuts",level:"A",addedIn:"2.1",understandingSlug:"character-key-shortcuts",shortDescription:"Single-key shortcuts can be turned off or remapped."},{id:"2.2.1",title:"Timing Adjustable",level:"A",addedIn:"2.0",understandingSlug:"timing-adjustable",shortDescription:"User can turn off, adjust, or extend time limits."},{id:"2.2.2",title:"Pause, Stop, Hide",level:"A",addedIn:"2.0",understandingSlug:"pause-stop-hide",shortDescription:"Moving/blinking/scrolling content can be paused."},{id:"2.2.3",title:"No Timing",level:"AAA",addedIn:"2.0",understandingSlug:"no-timing",shortDescription:"No timing essential to content/function (with exceptions)."},{id:"2.2.4",title:"Interruptions",level:"AAA",addedIn:"2.0",understandingSlug:"interruptions",shortDescription:"User can postpone/suppress non-emergency interruptions."},{id:"2.2.5",title:"Re-authenticating",level:"AAA",addedIn:"2.0",understandingSlug:"re-authenticating",shortDescription:"Authenticated session can be resumed without data loss."},{id:"2.2.6",title:"Timeouts",level:"AAA",addedIn:"2.1",understandingSlug:"timeouts",shortDescription:"Inactivity timeouts warned in advance."},{id:"2.3.1",title:"Three Flashes or Below Threshold",level:"A",addedIn:"2.0",understandingSlug:"three-flashes-or-below-threshold",shortDescription:"No content flashes more than 3 times per second."},{id:"2.3.2",title:"Three Flashes",level:"AAA",addedIn:"2.0",understandingSlug:"three-flashes",shortDescription:"No content flashes more than 3 times per second (no exceptions)."},{id:"2.3.3",title:"Animation from Interactions",level:"AAA",addedIn:"2.1",understandingSlug:"animation-from-interactions",shortDescription:"Motion animation from interactions can be disabled."},{id:"2.4.1",title:"Bypass Blocks",level:"A",addedIn:"2.0",understandingSlug:"bypass-blocks",shortDescription:"Mechanism to skip blocks of repeated content."},{id:"2.4.2",title:"Page Titled",level:"A",addedIn:"2.0",understandingSlug:"page-titled",shortDescription:"Pages have titles that describe topic/purpose."},{id:"2.4.3",title:"Focus Order",level:"A",addedIn:"2.0",understandingSlug:"focus-order",shortDescription:"Components receive focus in a meaningful order."},{id:"2.4.4",title:"Link Purpose (In Context)",level:"A",addedIn:"2.0",understandingSlug:"link-purpose-in-context",shortDescription:"Link purpose is clear from the link text + context."},{id:"2.4.5",title:"Multiple Ways",level:"AA",addedIn:"2.0",understandingSlug:"multiple-ways",shortDescription:"Two or more ways to locate a page within a set."},{id:"2.4.6",title:"Headings and Labels",level:"AA",addedIn:"2.0",understandingSlug:"headings-and-labels",shortDescription:"Headings and labels describe topic or purpose."},{id:"2.4.7",title:"Focus Visible",level:"AA",addedIn:"2.0",understandingSlug:"focus-visible",shortDescription:"Keyboard focus indicator is visible."},{id:"2.4.8",title:"Location",level:"AAA",addedIn:"2.0",understandingSlug:"location",shortDescription:"Information about user's location within a set is available."},{id:"2.4.9",title:"Link Purpose (Link Only)",level:"AAA",addedIn:"2.0",understandingSlug:"link-purpose-link-only",shortDescription:"Link purpose clear from the link text alone."},{id:"2.4.10",title:"Section Headings",level:"AAA",addedIn:"2.0",understandingSlug:"section-headings",shortDescription:"Section headings are used to organize content."},{id:"2.4.11",title:"Focus Not Obscured (Minimum)",level:"AA",addedIn:"2.2",understandingSlug:"focus-not-obscured-minimum",shortDescription:"Focused component not entirely hidden by other content."},{id:"2.4.12",title:"Focus Not Obscured (Enhanced)",level:"AAA",addedIn:"2.2",understandingSlug:"focus-not-obscured-enhanced",shortDescription:"Focused component fully visible."},{id:"2.4.13",title:"Focus Appearance",level:"AAA",addedIn:"2.2",understandingSlug:"focus-appearance",shortDescription:"Focus indicator meets specific size/contrast requirements."},{id:"2.5.1",title:"Pointer Gestures",level:"A",addedIn:"2.1",understandingSlug:"pointer-gestures",shortDescription:"Multi-point or path-based gestures have single-pointer alternatives."},{id:"2.5.2",title:"Pointer Cancellation",level:"A",addedIn:"2.1",understandingSlug:"pointer-cancellation",shortDescription:"Pointer actions can be aborted or undone."},{id:"2.5.3",title:"Label in Name",level:"A",addedIn:"2.1",understandingSlug:"label-in-name",shortDescription:"Accessible name includes the visible label text."},{id:"2.5.4",title:"Motion Actuation",level:"A",addedIn:"2.1",understandingSlug:"motion-actuation",shortDescription:"Motion-triggered functions have UI alternatives + can be disabled."},{id:"2.5.5",title:"Target Size (Enhanced)",level:"AAA",addedIn:"2.1",understandingSlug:"target-size-enhanced",shortDescription:"Pointer target size at least 44×44 CSS px."},{id:"2.5.6",title:"Concurrent Input Mechanisms",level:"AAA",addedIn:"2.1",understandingSlug:"concurrent-input-mechanisms",shortDescription:"Content doesn't restrict input modality."},{id:"2.5.7",title:"Dragging Movements",level:"AA",addedIn:"2.2",understandingSlug:"dragging-movements",shortDescription:"Dragging actions have single-pointer alternatives."},{id:"2.5.8",title:"Target Size (Minimum)",level:"AA",addedIn:"2.2",understandingSlug:"target-size-minimum",shortDescription:"Pointer target size at least 24×24 CSS px."},{id:"3.1.1",title:"Language of Page",level:"A",addedIn:"2.0",understandingSlug:"language-of-page",shortDescription:"Default human language of the page is programmatically set."},{id:"3.1.2",title:"Language of Parts",level:"AA",addedIn:"2.0",understandingSlug:"language-of-parts",shortDescription:"Language of each passage is programmatically set."},{id:"3.1.3",title:"Unusual Words",level:"AAA",addedIn:"2.0",understandingSlug:"unusual-words",shortDescription:"Definitions provided for jargon, idioms, etc."},{id:"3.1.4",title:"Abbreviations",level:"AAA",addedIn:"2.0",understandingSlug:"abbreviations",shortDescription:"Expanded form or meaning of abbreviations is available."},{id:"3.1.5",title:"Reading Level",level:"AAA",addedIn:"2.0",understandingSlug:"reading-level",shortDescription:"Supplemental content provided for advanced reading levels."},{id:"3.1.6",title:"Pronunciation",level:"AAA",addedIn:"2.0",understandingSlug:"pronunciation",shortDescription:"Mechanism for pronunciation of words where meaning is ambiguous."},{id:"3.2.1",title:"On Focus",level:"A",addedIn:"2.0",understandingSlug:"on-focus",shortDescription:"Focus does not trigger an unexpected context change."},{id:"3.2.2",title:"On Input",level:"A",addedIn:"2.0",understandingSlug:"on-input",shortDescription:"Input does not trigger an unexpected context change."},{id:"3.2.3",title:"Consistent Navigation",level:"AA",addedIn:"2.0",understandingSlug:"consistent-navigation",shortDescription:"Navigation is consistent across a set of pages."},{id:"3.2.4",title:"Consistent Identification",level:"AA",addedIn:"2.0",understandingSlug:"consistent-identification",shortDescription:"Components with the same function are identified consistently."},{id:"3.2.5",title:"Change on Request",level:"AAA",addedIn:"2.0",understandingSlug:"change-on-request",shortDescription:"Changes of context only on user request."},{id:"3.2.6",title:"Consistent Help",level:"A",addedIn:"2.2",understandingSlug:"consistent-help",shortDescription:"Help mechanisms appear in consistent order across pages."},{id:"3.3.1",title:"Error Identification",level:"A",addedIn:"2.0",understandingSlug:"error-identification",shortDescription:"Form errors are identified and described in text."},{id:"3.3.2",title:"Labels or Instructions",level:"A",addedIn:"2.0",understandingSlug:"labels-or-instructions",shortDescription:"Form fields have labels or instructions."},{id:"3.3.3",title:"Error Suggestion",level:"AA",addedIn:"2.0",understandingSlug:"error-suggestion",shortDescription:"Error suggestions provided when known."},{id:"3.3.4",title:"Error Prevention (Legal, Financial, Data)",level:"AA",addedIn:"2.0",understandingSlug:"error-prevention-legal-financial-data",shortDescription:"Submissions are reversible, checked, or confirmed."},{id:"3.3.5",title:"Help",level:"AAA",addedIn:"2.0",understandingSlug:"help",shortDescription:"Context-sensitive help is available."},{id:"3.3.6",title:"Error Prevention (All)",level:"AAA",addedIn:"2.0",understandingSlug:"error-prevention-all",shortDescription:"All submissions reversible, checked, or confirmed."},{id:"3.3.7",title:"Redundant Entry",level:"A",addedIn:"2.2",understandingSlug:"redundant-entry",shortDescription:"Previously-entered information is auto-populated or selectable."},{id:"3.3.8",title:"Accessible Authentication (Minimum)",level:"AA",addedIn:"2.2",understandingSlug:"accessible-authentication-minimum",shortDescription:"Auth doesn't require cognitive function test."},{id:"3.3.9",title:"Accessible Authentication (Enhanced)",level:"AAA",addedIn:"2.2",understandingSlug:"accessible-authentication-enhanced",shortDescription:"Auth doesn't require cognitive function test (no exceptions)."},{id:"4.1.1",title:"Parsing",level:"A",addedIn:"2.0",removedIn:"2.2",understandingSlug:"parsing",shortDescription:"Markup is well-formed (obsoleted in WCAG 2.2)."},{id:"4.1.2",title:"Name, Role, Value",level:"A",addedIn:"2.0",understandingSlug:"name-role-value",shortDescription:"UI components have programmatically determinable name + role + state."},{id:"4.1.3",title:"Status Messages",level:"AA",addedIn:"2.1",understandingSlug:"status-messages",shortDescription:"Status messages programmatically announced without focus change."}];function Tt(e,t){const a={A:1,AA:2,AAA:3},n={"2.0":1,"2.1":2,"2.2":3};return Ds.filter(o=>n[o.addedIn]>n[e]||o.removedIn&&n[o.removedIn]<=n[e]?!1:a[o.level]<=a[t])}function Fp(e,t){return`https://www.w3.org/WAI/WCAG${t.replace(".","")}/Understanding/${e.understandingSlug}`}let Le="2.1";const gn="AA";function _p(e){Le=e}async function Up(){var e,t;try{const n=(await chrome.storage.local.get("wcagTargetVersion")).wcagTargetVersion;(n==="2.1"||n==="2.2")&&(Le=n),(t=(e=chrome.storage.onChanged)==null?void 0:e.addListener)==null||t.call(e,(o,i)=>{if(i!=="local")return;const r=o.wcagTargetVersion;if(!r)return;const c=r.newValue;(c==="2.1"||c==="2.2")&&(Le=c)})}catch{}}const Ns=["3.2.3","3.2.4","3.2.6","3.3.7"];function Ls(e){const t=Tt(Le,gn),a=new Map;for(const i of t)a.set(i.id,{criterionId:i.id,level:i.level,title:i.title,state:"not-evaluated",evidence:[]});const n=new Map;function o(i,r){let c=n.get(i);return c||(c=new Set,n.set(i,c)),c.has(r)?!0:(c.add(r),!1)}for(const i of e.audits){const r=i.pageUrl??i.scope;for(const l of i.violations){if(!l.wcagCriterion)continue;const d=a.get(l.wcagCriterion);if(!d)continue;const u=l.ruleId.startsWith("ai-"),m=l.target.selector;if(e.acknowledgedMatchKeys.has(l.matchKey)){const f=`ack::${l.ruleId}::${r}::${m}`;if(o(l.wcagCriterion,f))continue;d.evidence.push({source:u?"ai":"axe",ruleOrStepId:l.ruleId,outcome:"ack",pageUrl:r,selector:m});continue}if(l.needsReview){const f=`needsReview::${l.ruleId}::${r}::${m}`;if(o(l.wcagCriterion,f))continue;d.evidence.push({source:"ai",ruleOrStepId:l.ruleId,outcome:"incomplete",pageUrl:r,selector:m,resolutionHint:"Acknowledge in the Matrix view if not an issue, or fix the underlying alt text."});continue}const p=`fail::${l.ruleId}::${r}::${m}`;o(l.wcagCriterion,p)||d.evidence.push({source:u?"ai":"axe",ruleOrStepId:l.ruleId,outcome:"fail",pageUrl:r,selector:m,resolutionHint:`Fix ${l.ruleId} on ${m}.`})}const c=i.axeRulesEvaluated;if(c){for(const l of c.passed){const d=a.get(l.wcagCriterion);if(!d)continue;const u=`axe::${l.ruleId}::${r}::pass`;o(l.wcagCriterion,u)||d.evidence.push({source:"axe",ruleOrStepId:l.ruleId,outcome:"pass",pageUrl:r})}for(const l of c.inapplicable){const d=a.get(l.wcagCriterion);if(!d)continue;const u=`axe::${l.ruleId}::${r}::inapplicable`;o(l.wcagCriterion,u)||d.evidence.push({source:"axe",ruleOrStepId:l.ruleId,outcome:"inapplicable",pageUrl:r})}for(const l of c.incomplete){const d=a.get(l.wcagCriterion);if(!d)continue;const u=`axe::${l.ruleId}::${r}::incomplete`,m=d.evidence.findIndex(p=>p.source==="axe"&&p.outcome==="incomplete"&&p.ruleOrStepId===l.ruleId&&p.pageUrl===r);if(m>=0){if(l.elements&&l.elements.length>0){const p=d.evidence[m],f=new Set((p.elements??[]).map(g=>g.selector));for(const g of l.elements)f.has(g.selector)||((p.elements??(p.elements=[])).push(g),f.add(g.selector))}continue}o(l.wcagCriterion,u)||d.evidence.push({source:"axe",ruleOrStepId:l.ruleId,outcome:"incomplete",pageUrl:r,elements:l.elements?[...l.elements]:void 0,resolutionHint:"axe-core couldn't fully determine. Common causes: text against an image/gradient background, or aria-role on a hidden element. Review the page manually."})}}}if(e.incompleteResolutions&&e.incompleteResolutions.length>0){const i=new Map;for(const r of e.incompleteResolutions)i.set(`${r.pageUrl}::${r.ruleId}::${r.selector}`,r);for(const r of a.values()){const c=[];for(const l of r.evidence){if(l.source!=="axe"||l.outcome!=="incomplete"||!l.elements||l.elements.length===0){c.push(l);continue}const d=[];for(const u of l.elements){const m=`${l.pageUrl}::${l.ruleOrStepId}::${u.selector}`,p=i.get(m);if(!p){d.push(u);continue}p.verdict==="pass"?c.push({source:"ai",ruleOrStepId:`ai-resolved::${l.ruleOrStepId}`,outcome:"pass",pageUrl:l.pageUrl,selector:u.selector,notes:p.reasoning}):p.verdict==="fail"?c.push({source:"ai",ruleOrStepId:`ai-resolved::${l.ruleOrStepId}`,outcome:"fail",pageUrl:l.pageUrl,selector:u.selector,notes:p.reasoning,resolutionHint:`AI determined ${l.ruleOrStepId} fails on this element. Review and fix or override.`}):d.push(u)}d.length>0&&c.push({...l,elements:d})}r.evidence=c}}if(e.interactiveAuditResults&&e.interactiveAuditResults.length>0)for(const i of e.interactiveAuditResults){const r=a.get(i.criterionId);r&&r.evidence.push({source:"ai",ruleOrStepId:i.ruleId,outcome:i.verdict==="pass"?"pass":i.verdict==="fail"?"fail":"incomplete",pageUrl:i.pageUrl,notes:i.reasoning,resolutionHint:i.verdict==="fail"?"Review the AI walkthrough in the Compliance tab; fix the underlying focus-order issue and re-run.":i.verdict==="uncertain"?"Re-run the interactive audit, or manually verify via Guided Tests.":void 0})}for(const i of e.workflows)for(const r of i.steps){if(!r.wcag)continue;const c=a.get(r.wcag);if(c)for(const l of e.igtRuns){if(l.workflowId!==i.id)continue;const d=l.steps[r.id],u=`${i.id}.${r.id}`;if(!d){c.evidence.push({source:"igt",ruleOrStepId:u,outcome:"skip",resolutionHint:`Open Guided Tests → ${i.name} → answer "${r.id}" as Pass / Fail / N/A.`});continue}d.status==="pass"?c.evidence.push({source:"igt",ruleOrStepId:u,outcome:"pass",notes:d.notes}):d.status==="fail"?c.evidence.push({source:"igt",ruleOrStepId:u,outcome:"fail",notes:d.notes,resolutionHint:`Address the failing manual check: ${r.question}`}):d.status==="not-applicable"?c.evidence.push({source:"igt",ruleOrStepId:u,outcome:"n/a",notes:d.notes}):d.status==="skip"&&c.evidence.push({source:"igt",ruleOrStepId:u,outcome:"skip",notes:d.notes,resolutionHint:`Open Guided Tests → ${i.name} → re-answer "${r.id}" as Pass / Fail / N/A.`})}}for(const i of a.values())i.state=Ps(i.evidence);if(e.auditScope==="single-page")for(const i of Ns){const r=a.get(i);r&&r.state==="not-evaluated"&&(r.state="not-applicable",r.evidence.push({source:"axe",ruleOrStepId:"wcc-multi-page-only-na",outcome:"n/a",notes:"Single-page audit cannot evaluate this cross-page criterion. Treated as N/A for this audit; run Site Crawl to evaluate."}))}if(e.humanCriterionVerdicts&&e.humanCriterionVerdicts.length>0)for(const i of e.humanCriterionVerdicts){const r=a.get(i.criterionId);if(!r)continue;const c=i.verdict==="na"?"n/a":i.verdict,l=i.verdict==="na"?"not-applicable":i.verdict==="fail"?"fail":"pass";r.state=l,r.evidence.push({source:"human",ruleOrStepId:"human-criterion-verdict",outcome:c,notes:`Human verified ${i.verdict.toUpperCase()} on ${i.verifiedAt}: ${i.note}`})}return a}function Ps(e){return e.length===0?"not-evaluated":e.some(a=>a.outcome==="fail")?"fail":e.some(a=>a.outcome==="incomplete"||a.outcome==="skip")?"inconclusive":e.some(a=>a.outcome==="pass"||a.outcome==="inapplicable"||a.outcome==="ack")?"pass":"not-applicable"}function Fs(e){const t={pass:[],fail:[],inconclusive:[],notApplicable:[],notEvaluated:[]};for(const n of e.values())t[_s(n.state)].push(n.criterionId);const a=e.size;return{pass:t.pass.length,fail:t.fail.length,inconclusive:t.inconclusive.length,notApplicable:t.notApplicable.length,notEvaluated:t.notEvaluated.length,totalApplicable:a,canClaimConformance:t.fail.length===0&&t.inconclusive.length===0&&t.notEvaluated.length===0,byState:t}}function _s(e){return e==="not-applicable"?"notApplicable":e==="not-evaluated"?"notEvaluated":e}function Wp(e,t=Oe){const a=new Set,n=new Set,o=new Set;for(const r of e.values())for(const c of r.evidence)c.source==="axe"?a.add(r.criterionId):c.source==="ai"?n.add(r.criterionId):c.source==="igt"&&o.add(r.criterionId);for(const r of t)for(const c of r.steps)c.wcag&&e.has(c.wcag)&&o.add(c.wcag);function i(r,c){const l=Array.from(c).sort();let d=0;const u=[],m=[],p=[];for(const f of l){const g=e.get(f);if(!g)continue;const h=g.evidence.filter(v=>r==="automation"&&v.source==="axe"||r==="ai"&&v.source==="ai"||r==="human"&&v.source==="igt");if(h.length===0){p.push(f);continue}const y=h.some(v=>v.outcome==="fail"),b=h.some(v=>v.outcome==="incomplete"||v.outcome==="skip"),A=h.some(v=>v.outcome==="pass"||v.outcome==="inapplicable"||v.outcome==="ack"||v.outcome==="n/a");y?u.push(f):b?m.push(f):A?d++:p.push(f)}return{layer:r,coveredCriteria:l,cleared:d,failing:u,inconclusive:m,blocked:[...u,...m].sort(),unevaluated:p}}return{automation:i("automation",a),ai:i("ai",n),human:i("human",o)}}const Aa=[{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 Us(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 Ws(e,t,a="2.1",n="AA",o,i,r,c,l){const d=Ls({audits:e??[],igtRuns:(t==null?void 0:t.runs)??[],workflows:(t==null?void 0:t.workflows)??Oe,acknowledgedMatchKeys:o??new Set,incompleteResolutions:i,interactiveAuditResults:r,auditScope:c,humanCriterionVerdicts:l}),u={},m={},p=[],f=[],g=[];let h=0;for(const b of d.values()){if(b.state==="not-evaluated"){p.push(b.criterionId);continue}if(h++,b.state==="fail"){g.push(b.criterionId);const A=[];for(const v of b.evidence)v.outcome==="fail"&&A.push({source:v.source,ruleOrStepId:v.ruleOrStepId,selector:v.selector,notes:v.notes,pageUrl:v.pageUrl});A.length>0&&(m[b.criterionId]=A)}if(b.state==="inconclusive"){f.push(b.criterionId);const A=[];for(const v of b.evidence)if(v.outcome==="incomplete"){const s=v.source==="ai"?"ai-uncertain":"axe-incomplete";A.push({source:s,ruleOrStepId:v.ruleOrStepId,resolutionHint:v.resolutionHint,elements:v.elements,pageUrl:v.pageUrl})}else v.outcome==="skip"&&A.push({source:"igt-skip",ruleOrStepId:v.ruleOrStepId,resolutionHint:v.resolutionHint});A.length>0&&(u[b.criterionId]=A)}}const y=Fs(d);return{targetVersion:Le,targetLevel:gn,totalApplicable:d.size,evaluated:h,untestedCriteria:p,inconclusiveCriteria:f,failingCriteria:g,inconclusiveReasons:u,failingReasons:m,canClaimConformance:y.canClaimConformance}}function $e(e,t,a,n,o,i,r,c,l){const d=n??new Set,u=Us(e).filter(N=>!d.has(N.matchKey)),m=u.filter(N=>N.needsReview),p=u.filter(N=>!N.needsReview),f={critical:0,serious:0,moderate:0,minor:0,unique:p.length};for(const N of p)f[N.impact]++;let g;t&&(g=qs(t.runs,t.workflows),f.serious+=g.failedRequired,f.moderate+=g.failedAdvisory,f.unique+=g.failedRequired+g.failedAdvisory);const h=[],y=[];if(o&&o.length>0){const N=new Set;if(i)for(const S of i)N.add(`${S.criterionId}::${S.pageUrl}`);const M=new Set;for(const S of o){if(S.verdict==="pass")continue;const E=`${S.criterionId}::${S.pageUrl}`;if(M.has(E))continue;M.add(E);const V=S.verdict==="fail"?"serious":"moderate",D={criterionId:S.criterionId,pageUrl:S.pageUrl,verdict:S.verdict,impact:V,reasoning:S.reasoning};if(N.has(E)){y.push(D);continue}h.push(D),f[V]++,f.unique++}}const b=new Map;for(const N of Aa)for(const M of N.rules)b.set(M,N);const A=new Map;for(const N of Aa)A.set(N.id,{count:0,rules:new Set});for(const N of Ko(p)){const M=b.get(N.ruleId);if(!M)continue;const S=A.get(M.id);S.count++,S.rules.add(N.ruleId)}const v=Aa.map(N=>{const M=A.get(N.id);let S="pass";return M.count>0?S="fail":N.needsManualCheck&&(S="unchecked"),{id:N.id,label:N.label,status:S,violationCount:M.count,rules:Array.from(M.rules),needsManualCheck:N.needsManualCheck}}),s=f.critical>0,k=f.serious>0,x=(()=>{if(!o||o.length===0||!i||i.length===0)return o;const N=new Set;for(const M of i)N.add(`${M.criterionId}::${M.pageUrl}`);return o.map(M=>N.has(`${M.criterionId}::${M.pageUrl}`)?{...M,verdict:"pass",reasoning:`Human verified: ${M.reasoning}`}:M)})(),w=a?Ws(a,t,"2.1","AA",n,l,x,c,r):void 0,R=w?!w.canClaimConformance:!1;let T;f.critical>=5?T="F":f.critical>=1?T="D":f.serious>=5||f.serious>=1?T="C":f.moderate>=3||f.moderate>=1?T="B":(f.minor>=1,T="A"),R&&T==="A"&&(T="B");const P=v.filter(N=>N.status==="fail").length;let _;return f.critical>0||P>=4?_="critical":f.serious>=3||P>=2?_="high":f.serious>=1||f.moderate>=3?_="moderate":_="low",{letter:T,risk:_,caps:{cappedAtC:s,cappedAtB:k,cappedAtBByCoverage:R},totals:f,categories:v,coverage:w,manual:g,reviewQueue:{count:m.length,rules:Array.from(new Set(m.map(N=>N.ruleId)))},walkthroughFindings:h,walkthroughAcknowledgements:y}}function qs(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,i=0;const r=t.map(c=>{const l=a.get(c.id);let d=0,u=0,m=0,p=0,f=0;for(const g of c.steps){const h=l==null?void 0:l.steps[g.id];h&&(f++,h.status==="pass"?d++:h.status==="skip"?p++:h.status==="fail"&&(g.severity==="required"?u++:m++))}return f===c.steps.length&&i++,n+=u,o+=m,{workflowId:c.id,name:c.name,passed:d,failedRequired:u,failedAdvisory:m,skipped:p,answered:f,total:c.steps.length}});return{workflowsCompleted:i,workflowsTotal:t.length,failedRequired:n,failedAdvisory:o,perWorkflow:r}}const Vs={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."},er={low:"✓ Off the radar",moderate:"⚡ Some lawsuit exposure",high:"⚠️ High target risk",critical:"🚨 Lawsuit magnet"},tr={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."},Vn={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 qp(e,t){if(e!=="B")return Vn[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.`:Vn.B}const at={"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 -->
|
|
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 ds(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 us(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 ps(e,t){const a=l=>{const d=l/255;return d<=.03928?d/12.92:Math.pow((d+.055)/1.055,2.4)},n=l=>.2126*a(l.r)+.7152*a(l.g)+.0722*a(l.b),o=n(e),r=n(t),i=Math.max(o,r),c=Math.min(o,r);return(i+.05)/(c+.05)}const hs=Object.freeze(Object.defineProperty({__proto__:null,applyContrastMathSalvage:ls,applySelfCorrectionSalvage:cs,clearAllResolutions:ss,deleteResolution:rs,getAllResolutions:Jo,getResolutionsForPage:dn,saveResolution:qe,saveResolutions:is},Symbol.toStringTag,{value:"Module"})),fs={id:"keyboard",name:"Keyboard navigation",blurb:"Verify everyone who relies on the keyboard can reach, operate, and escape every interactive element. WCAG 2.1.1, 2.1.2, 2.4.3, 2.4.7.",steps:[{id:"tab-reaches-all",prompt:"Tab through the component from start to finish. Compare against the Tab-order overlay.",question:"Did Tab reach every interactive element (button, link, form field, custom widget)?",wcag:"2.1.1",visualizer:"tab-order",severity:"required"},{id:"tab-order-logical",prompt:"Watch the focus indicator as you Tab. Compare visual order vs the Tab-order numbered overlay.",question:"Does focus move in a logical order matching the visual layout (left-to-right, top-to-bottom)? Red badges indicate visual mismatches.",wcag:"2.4.3",visualizer:"tab-order",severity:"required",autoDismissActivity:"tab-order"},{id:"focus-visible",prompt:"On each focused element, confirm a visible focus indicator (outline, ring, color change).",question:"Is the focus indicator clearly visible on every interactive element?",wcag:"2.4.7",relatedAxeRule:"focus-order-semantics",severity:"required"},{id:"no-trap",prompt:"Tab forward and Shift+Tab backward through any modal, dropdown, or custom widget.",question:"Can you escape the widget with Tab/Shift+Tab/Esc — no trapping?",wcag:"2.1.2",severity:"required"},{id:"enter-activates",prompt:"Focus a button or link and press Enter (and Space for buttons).",question:"Did Enter/Space activate the control as expected?",wcag:"2.1.1",severity:"required"},{id:"esc-closes",prompt:"Open any modal, dropdown, or popover and press Escape.",question:"Did Escape close the overlay and return focus to the trigger?",wcag:"2.1.2",severity:"required"},{id:"arrow-keys-grouped",prompt:"For grouped widgets (radio, tabs, listbox, menu): focus into the group, then use arrow keys.",question:"Do arrow keys move within the group as expected (and Tab moves out of it)?",wcag:"2.1.1",severity:"advisory"},{id:"character-key-shortcuts",prompt:'Identify any single-character keyboard shortcuts (e.g., "S" to open search, "/" to focus the search box, J/K for next/prev). If none exist, mark N/A.',question:"For every single-character shortcut: can it be turned off, remapped to a modifier-key combo, OR is it only active when the relevant control has focus? (Prevents accidental activation by speech-input users.)",wcag:"2.1.4",severity:"required"}]},gs={id:"screen-reader",name:"Screen reader readiness",blurb:"Verify the component is operable and meaningful via a screen reader. Use NVDA (Windows), VoiceOver (macOS/iOS), or TalkBack (Android). WCAG 1.3.1, 4.1.2.",steps:[{id:"sr-announces-on-focus",prompt:"Activate your screen reader and Tab to each interactive element.",question:"Does the SR announce a meaningful name + role + state for every focused element?",wcag:"4.1.2",relatedAxeRule:"aria-required-attr",severity:"required"},{id:"sr-headings-navigate",prompt:"Use the SR's heading-navigation shortcut (NVDA: H, VoiceOver: VO+Cmd+H). Compare against the Outline overlay.",question:"Are all logical sections reachable via heading navigation, in correct hierarchy order?",wcag:"1.3.1",relatedAxeRule:"heading-order",visualizer:"outline",severity:"required"},{id:"sr-reading-order",prompt:"Read the page top-to-bottom using the SR's read-all command (NVDA: NumPad+Down, VoiceOver: VO+A). Compare against the Reading-order numbered overlay.",question:"Does the SR read content in the meaningful order implied by the visual layout (1.3.2 Meaningful Sequence)? Red badges in the Reading-order overlay show DOM-vs-visual divergences.",wcag:"1.3.2",visualizer:"reading-order",severity:"required",autoDismissActivity:"reading-order"},{id:"sr-landmarks",prompt:"Use the SR's landmark-navigation shortcut (NVDA: D, VoiceOver: VO+U → Landmarks). Compare against the Outline overlay.",question:"Can the user jump to main, nav, banner, contentinfo via landmark navigation?",wcag:"1.3.1",relatedAxeRule:"region",visualizer:"outline",severity:"required"},{id:"sr-live-region",prompt:"Trigger any dynamic update (form submission, status change, toast).",question:'Does the SR announce the change automatically (via aria-live or role="status"/role="alert")?',wcag:"4.1.3",severity:"required"},{id:"sr-form-errors",prompt:"Submit a form with an invalid field.",question:"Does the SR announce the error and which field it relates to?",wcag:"3.3.1",severity:"required"},{id:"sr-images-meaningful",prompt:"Navigate over each image (NVDA: G, VoiceOver: VO+Cmd+G).",question:"Does each meaningful image have descriptive alt text? Are decorative images silent?",wcag:"1.1.1",relatedAxeRule:"image-alt",severity:"required"}]},ms={id:"focus-management",name:"Focus management",blurb:"Verify focus moves and restores correctly across overlays, navigations, and dynamic content. WCAG 2.4.3, 2.4.7, 3.2.2.",steps:[{id:"modal-initial-focus",prompt:"Open a modal/dialog.",question:"Did focus move into the modal automatically (typically to the first focusable element or a heading)?",severity:"required"},{id:"modal-restored-on-close",prompt:"Close a modal/dialog (via close button or Esc).",question:"Was focus restored to the element that opened it?",severity:"required"},{id:"modal-trap-while-open",prompt:"While a modal is open, Tab/Shift+Tab through it.",question:"Is focus trapped inside the modal until it closes?",severity:"required"},{id:"route-change-focus",prompt:"Trigger a client-side route change.",question:"Did focus move sensibly (to the new page heading, or main landmark) — not to <body>?",severity:"required"},{id:"expanded-focus",prompt:"Open an expandable section (accordion, dropdown, collapsible).",question:"Is focus moved into or near the newly-revealed content (or kept on the trigger appropriately)?",severity:"advisory"},{id:"no-unexpected-focus-move",prompt:"Type or click in form fields without explicitly tabbing.",question:"Does focus stay where you put it (no auto-jump on input)?",wcag:"3.2.2",severity:"required"},{id:"no-context-change-on-focus",prompt:"Tab into each interactive element on the page.",question:"Does merely RECEIVING focus on an element NOT trigger a context change (auto-submit, open modal, navigate elsewhere, change focus to a different field)? (Context change on focus violates 3.2.1; activating a control via click/Enter is fine.)",wcag:"3.2.1",severity:"required"}]},bs={id:"forms",name:"Forms",blurb:"Verify form fields are properly labeled, errors are clear, and the experience works for assistive technology. WCAG 1.3.1, 3.3.1, 3.3.2, 4.1.2.",steps:[{id:"visible-labels",prompt:"Look at every form field.",question:"Does every field have a visible label (not just placeholder text)?",wcag:"3.3.2",relatedAxeRule:"label",severity:"required"},{id:"label-association",prompt:"Click each visible label.",question:"Did clicking the label focus the associated input?",wcag:"1.3.1",relatedAxeRule:"label",severity:"required"},{id:"required-marked",prompt:"Identify required fields.",question:"Are required fields marked both visually AND programmatically (aria-required or required attribute)?",wcag:"3.3.2",severity:"required"},{id:"autocomplete-set",prompt:"For personal-info fields (name, email, phone, address): inspect the autocomplete attribute.",question:'Is autocomplete set with a valid HTML5 token (e.g., "email", "given-name", "tel")?',wcag:"1.3.5",relatedAxeRule:"autocomplete-valid",severity:"required"},{id:"error-text",prompt:"Submit with invalid input.",question:'Are error messages specific (not just "invalid"), shown near the field, and programmatically associated (aria-describedby)?',wcag:"3.3.1",severity:"required"},{id:"no-color-only-error",prompt:"Look at how errors are signaled.",question:"Is the error indicated by more than just color (also icon, text, or border style)?",wcag:"1.4.1",severity:"required"},{id:"success-announced",prompt:"Submit a form successfully.",question:'Is the success state announced to screen readers (via aria-live or role="status")?',wcag:"4.1.3",severity:"advisory"},{id:"error-suggestion",prompt:"Submit a form with an obvious invalid input (wrong email format, password too short, missing required field).",question:'Does the error message INCLUDE a specific suggestion for fixing it (not just "invalid")?',wcag:"3.3.3",severity:"required"},{id:"redundant-entry",prompt:"Identify any multi-step or multi-form flow where the user re-enters previously provided information (shipping = billing, profile data repeated in another form).",question:"Is previously-entered information auto-populated, selectable from a list, or otherwise NOT manually re-entered?",wcag:"3.3.7",severity:"required"},{id:"accessible-authentication",prompt:"Identify the site's authentication flow (login, password reset, multi-factor).",question:'Does auth NOT require a cognitive function test (e.g., remembering / transcribing characters), OR is an accessible alternative offered (passkey, magic link, password-manager autofill, "show password" toggle)?',wcag:"3.3.8",severity:"required"}]},ys={id:"page-structure",name:"Page structure",blurb:"Verify the page declares its language, has a meaningful title, and exposes a sensible heading + landmark hierarchy. WCAG 2.4.2, 3.1.1, 3.1.2, 1.3.1, 2.4.6.",steps:[{id:"page-title",prompt:"Look at the browser tab — is the page title set and meaningful?",question:'Does the title describe the page topic / purpose (not just "Untitled" or the site name)?',wcag:"2.4.2",relatedAxeRule:"document-title",severity:"required"},{id:"page-lang",prompt:"Inspect the <html> element's lang attribute.",question:'Is lang set to a valid language code (e.g., "en", "es-MX")?',wcag:"3.1.1",relatedAxeRule:"html-has-lang",severity:"required"},{id:"lang-of-parts",prompt:"For any text not in the page's primary language (foreign quote, brand name in another language), inspect the parent element.",question:"Is lang attribute set on those elements to indicate the language change?",wcag:"3.1.2",severity:"advisory"},{id:"h1-present",prompt:"Use the Outline visualizer or SR heading shortcut to find the h1.",question:"Is there exactly one h1, and does it describe the main content of the page?",wcag:"1.3.1",relatedAxeRule:"page-has-heading-one",visualizer:"outline",severity:"required"},{id:"descriptive-headings",prompt:"Read each heading. Imagine someone listening only to the heading text.",question:"Does each heading describe its section meaningfully on its own?",wcag:"2.4.6",severity:"required"},{id:"main-landmark",prompt:"Use the Outline visualizer or SR landmark shortcut.",question:"Is there exactly one <main> landmark wrapping the page's primary content?",wcag:"1.3.1",relatedAxeRule:"landmark-one-main",visualizer:"outline",severity:"required"},{id:"parsing-well-formed",prompt:"Open DevTools → Console. Reload the page and check for HTML parse errors. Or run W3C validator on the URL.",question:"Is the page's markup well-formed (no duplicate IDs in scope, no invalid nesting, no missing required attributes)? WCAG 4.1.1 was obsoleted in 2.2 but still applies to 2.1 conformance claims.",wcag:"4.1.1",severity:"required"}]},ws={id:"visual-indicators",name:"Visual indicators",blurb:"Verify nothing relies on color/shape/position alone, and non-text contrast meets thresholds for UI components and focus rings. WCAG 1.3.3, 1.4.1, 1.4.11.",steps:[{id:"no-color-only-info",prompt:"Scan instructions, error messages, charts, status indicators.",question:"Is information conveyed by something OTHER than color alone (text, icon, pattern, label)?",wcag:"1.4.1",severity:"required"},{id:"no-sensory-only",prompt:'Look for instructions referencing shape ("the round button"), location ("on the left"), sound ("the chime"), or visual cues alone.',question:"Are those instructions backed up by a programmatic identifier (label, role, accessible name)?",wcag:"1.3.3",severity:"required"},{id:"non-text-contrast",prompt:"For UI components (form-field borders, focus rings, icons-as-buttons), verify contrast vs adjacent colors. Use a contrast checker if needed.",question:"Do non-text UI components meet ≥3:1 contrast against adjacent colors?",wcag:"1.4.11",severity:"required"},{id:"focus-ring-contrast",prompt:"Tab through; for each focused element, verify the focus ring is visible against both the element and the page background.",question:"Does the focus ring meet ≥3:1 contrast on every focusable surface?",wcag:"1.4.11",visualizer:"tab-order",severity:"required"},{id:"state-changes-visible",prompt:"For toggleable controls (checkboxes, switches, expanded states): change them and observe.",question:"Is the state change conveyed visibly AND programmatically (aria-pressed/expanded/checked)?",wcag:"4.1.2",severity:"required"}]},vs={id:"reflow",name:"Reflow & text spacing",blurb:"Verify the layout survives narrow viewports, browser zoom, and user-overridden text spacing. WCAG 1.4.4, 1.4.10, 1.4.12.",steps:[{id:"resize-320",prompt:"Resize the browser to 320px wide (or set DevTools device toolbar to 320×256).",question:"Does content reflow without two-dimensional scrolling? (Vertical scroll OK; horizontal scroll within content blocks NOT OK.)",wcag:"1.4.10",relatedAxeRule:"wcagcheckr-reflow",severity:"required"},{id:"zoom-200",prompt:"In a desktop viewport, zoom the browser to 200%.",question:"Is all content + functionality available, with no text clipping or unusable controls?",wcag:"1.4.4",severity:"required"},{id:"text-spacing-override",prompt:"Apply text-spacing override (line-height: 1.5, paragraph spacing 2x font-size, letter-spacing 0.12em, word-spacing 0.16em) via a bookmarklet or DevTools.",question:"Does content stay readable with no overlap or clipping?",wcag:"1.4.12",severity:"required"},{id:"no-fixed-pixel-text",prompt:"Inspect text styles for fixed px-based font sizes, line-heights.",question:"Are text dimensions set in relative units (rem/em/%) so they scale with user settings?",severity:"advisory"},{id:"orientation-not-locked",prompt:"Rotate a mobile device (or use DevTools device toolbar to rotate) between portrait and landscape.",question:"Does the layout adapt to both orientations? (Content not locked to one orientation unless essential.)",wcag:"1.3.4",severity:"required"},{id:"images-of-text",prompt:"Look for marketing banners, hero images, or any image that contains substantial text content as part of the raster.",question:"Is real HTML text used in preference to images-of-text, except for logos / decorative purposes? (Images-of-text fail to scale with zoom, can't be selected, and don't respect user text settings.)",wcag:"1.4.5",severity:"required"}]},As={id:"hover-focus-content",name:"Content on hover or focus",blurb:"Tooltips, dropdown previews, and any content revealed on hover or focus must be dismissable, hoverable, and persistent. WCAG 1.4.13.",steps:[{id:"dismissable",prompt:"Hover or focus to reveal a tooltip / popover. Press Escape.",question:"Did Escape dismiss the revealed content without moving pointer or focus?",wcag:"1.4.13",severity:"required"},{id:"hoverable",prompt:"Hover to reveal a tooltip. Move the pointer over the tooltip itself (without losing the trigger's hover).",question:"Does the revealed content stay visible when the pointer enters it?",wcag:"1.4.13",severity:"required"},{id:"persistent",prompt:"Reveal a tooltip and don't do anything else.",question:"Does the content remain visible until the user dismisses it, moves focus/pointer away, or the trigger info is no longer valid?",wcag:"1.4.13",severity:"required"}]},ks={id:"pointer",name:"Pointer interactions",blurb:"Verify gestures, target sizes, and pointer cancellation respect users with motor limitations. WCAG 2.5.1, 2.5.2, 2.5.5/2.5.8.",steps:[{id:"no-multi-point-gesture",prompt:"Identify any feature that requires a multi-point gesture (pinch, two-finger swipe) or path-based gesture (drag along a line).",question:"Is there a single-tap / single-click alternative for that feature?",wcag:"2.5.1",severity:"required"},{id:"pointer-cancellation",prompt:"Mouse-down on a button, drag the pointer OFF the button, then release.",question:"Was the action canceled (the button did NOT activate)? Activation should fire on up-event over the target, not down-event.",wcag:"2.5.2",severity:"required"},{id:"target-size-aa",prompt:"Toggle the Targets visualizer. Look for any red overlays (≥24×24 fail).",question:"Are all interactive targets ≥24×24 CSS px (or have sufficient spacing per WCAG 2.5.8)?",wcag:"2.5.8",relatedAxeRule:"target-size",visualizer:"targets",severity:"required"},{id:"label-in-name",prompt:"For every visually-labeled control (button, link), inspect its accessible name (use the SR or DevTools).",question:"Does the accessible name START with — or fully contain — the visible label text?",wcag:"2.5.3",relatedAxeRule:"label-content-name-mismatch",severity:"required"},{id:"motion-actuation-alt",prompt:"Identify any feature that triggers on device motion (shake to undo, tilt to scroll, step counter).",question:"Is there a non-motion alternative (button / control) for every motion-triggered function, AND can motion be disabled?",wcag:"2.5.4",severity:"required"},{id:"dragging-alternative",prompt:"Identify any feature that requires a dragging movement (slider thumb, drag-to-rearrange, swipe-to-delete).",question:"Is there a single-tap / single-click alternative for every dragging action (e.g., +/- buttons next to a slider, up/down buttons next to draggable list items)?",wcag:"2.5.7",severity:"required"}]},Is={id:"time-based",name:"Time-based behaviors",blurb:"Verify time limits, auto-updating content, and motion can be controlled by users. WCAG 2.2.1, 2.2.2, 2.3.1.",steps:[{id:"time-limits-adjustable",prompt:"Identify any time-limited interaction (session timeout, form auto-submit, OTP expiration).",question:"Can the user turn off, adjust, or extend the time limit before it expires (warning + control before the deadline)?",wcag:"2.2.1",severity:"required"},{id:"pause-moving-content",prompt:"Look for content that moves, blinks, scrolls, or auto-updates for >5 seconds (carousels, animated banners, news tickers, auto-refreshing feeds).",question:"Is there a control to pause / stop / hide the moving content?",wcag:"2.2.2",severity:"required"},{id:"no-flash",prompt:"Identify any flashing or blinking content (>3 flashes per second).",question:"Is flashing absent, OR limited below the general/red flash thresholds?",wcag:"2.3.1",severity:"required"},{id:"reduced-motion-honored",prompt:'Enable system "reduce motion" preference. Reload the page.',question:"Does the site honor prefers-reduced-motion (parallax / animations / spinners minimized or disabled)?",wcag:"2.3.3",severity:"advisory"}]},xs={id:"error-prevention",name:"Error prevention",blurb:"Verify destructive, financial, or legal actions are reversible, checked, or confirmed. WCAG 3.3.4, 3.3.6.",steps:[{id:"destructive-confirm",prompt:"Identify destructive actions (delete account, cancel subscription, destroy data, send irreversible message).",question:'Is each destructive action reversible (undo), or checked (validation), or confirmed (explicit "Are you sure?" dialog)?',wcag:"3.3.4",severity:"required"},{id:"financial-confirm",prompt:"Identify financial / legal commitments (purchase, contract sign, transfer).",question:"Before submission, does the user see a review screen and an explicit confirmation step?",wcag:"3.3.4",severity:"required"},{id:"undo-available",prompt:'Test "destructive" actions on user content (delete a note, archive an item).',question:'Is there an undo / restore mechanism, even briefly (toast with "undo" button)?',wcag:"3.3.6",severity:"advisory"}]},Ss={id:"consistency",name:"Consistency",blurb:"Verify navigation, identification, and user paths are consistent across pages. WCAG 2.4.5, 3.2.3, 3.2.4.",steps:[{id:"consistent-nav",prompt:"Compare the primary navigation across 3+ pages.",question:"Does the same navigation appear in the same order on every page?",wcag:"3.2.3",severity:"required"},{id:"consistent-id",prompt:'Compare the same UI element appearing on multiple pages (e.g., a search icon, a "Help" link).',question:"Does the same component have the same accessible name everywhere it appears?",wcag:"3.2.4",severity:"required"},{id:"multiple-ways",prompt:"Beyond the primary navigation, is there a second way to find a page (search, sitemap, related links, breadcrumbs)?",question:"Are there at least 2 ways to locate any page (single-process pages exempt)?",wcag:"2.4.5",severity:"required"},{id:"skip-link",prompt:"Tab once when the page loads.",question:'Does the first focusable element offer a "Skip to main content" link (or equivalent bypass)?',wcag:"2.4.1",relatedAxeRule:"bypass",severity:"required"},{id:"consistent-help",prompt:"Identify pages that surface a help mechanism (contact info, help link, FAQ link, chatbot trigger). Compare position + order across pages.",question:"When the same help mechanism appears on multiple pages, does it appear in the same relative order (e.g., always last in the header)?",wcag:"3.2.6",severity:"required"}]},Cs={id:"time-based-media",name:"Time-based media",blurb:'Verify audio + video have the alternatives required by WCAG. If the site has no time-based media, mark every step "Not applicable." WCAG 1.2.1, 1.2.2, 1.2.3, 1.2.4, 1.2.5, 1.4.2.',steps:[{id:"prerecorded-audio-only-alt",prompt:"Identify any prerecorded audio-only content (podcast embed, audio quote, voice message).",question:"Does each prerecorded audio-only file have a text transcript readable on the page (or linked from it)?",wcag:"1.2.1",severity:"required"},{id:"prerecorded-video-only-alt",prompt:"Identify any prerecorded silent video (animated GIF with content, silent screencast, animated explainer).",question:"Does each prerecorded video-only file have an equivalent text or audio description?",wcag:"1.2.1",severity:"required"},{id:"prerecorded-captions",prompt:"Identify any prerecorded video that includes audio (interviews, tutorials, marketing videos).",question:"Does each video provide synchronized captions for ALL spoken content + meaningful non-speech sound?",wcag:"1.2.2",severity:"required"},{id:"prerecorded-alt-for-video",prompt:"For each prerecorded video with audio, check if there's a full text transcript on the page (covering both audio dialog AND visual action) OR if audio description is provided.",question:"Does each prerecorded video have either a full text alternative OR an audio-description track?",wcag:"1.2.3",severity:"required"},{id:"prerecorded-audio-description",prompt:"Watch each prerecorded video without looking at it. Listen only.",question:"Is all visually-conveyed information also conveyed in the audio (either built into the narration OR via a separate audio-description track)?",wcag:"1.2.5",severity:"required"},{id:"live-captions",prompt:"Identify any LIVE audio/video stream (live shopping, webinar, conference broadcast).",question:"Does each live broadcast provide real-time captions?",wcag:"1.2.4",severity:"required"},{id:"audio-control",prompt:"Reload the page. Listen for audio that starts automatically and plays for >3 seconds (background music, autoplay video with sound).",question:"Is there a mechanism to pause / stop the audio, OR can the volume be controlled INDEPENDENTLY from the system volume?",wcag:"1.4.2",severity:"required"}]},Oe=[fs,gs,ms,bs,ys,ws,vs,As,ks,Is,Cs,xs,Ss];function Rp(e,t){let a=0,n=0,o=0,r=0,i=0;for(const c of t.steps){const l=e.steps[c.id];if(!l){i++;continue}l.status==="pass"?a++:l.status==="fail"?n++:l.status==="not-applicable"?r++:l.status==="skip"?o++:i++}return{passed:a,failed:n,skipped:o,notApplicable:r,unanswered:i,total:t.steps.length,fullyAnswered:i===0}}const zt="interactiveAuditResults";function un(e,t){return`${e}::${t}`}async function Ct(){try{const t=(await chrome.storage.local.get(zt))[zt];return t&&typeof t=="object"?t:{}}catch{return{}}}async function pn(e){await chrome.storage.local.set({[zt]:e})}async function ae(e){const t=await Ct(),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[un(e.componentId,e.criterionId)]=a,await pn(t)}async function Ne(e,t){return(await Ct())[un(e,t)]??null}async function Ts(){const e=await Ct();return Object.values(e)}async function Va(e){return(await Ts()).filter(a=>a.componentId===e)}async function Op(e,t){const a=await Ct();delete a[un(e,t)],await pn(a)}async function hn(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 Va(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 Mp(){try{const e=await Ct();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 pn(e)}catch{try{await chrome.storage.local.remove(zt)}catch{}}}const $s=ee("walkthrough-acks"),ja="walkthroughAcks";function fn(e,t,a){return`${e}::${t}::${a}`}async function ca(){try{const t=(await chrome.storage.local.get(ja))[ja];return t&&typeof t=="object"?t:{}}catch{return{}}}async function Xo(e){await chrome.storage.local.set({[ja]:e})}async function Dp(e){if(!e.note||!e.note.trim())throw new Error("Acknowledgement requires a non-empty note explaining manual verification.");const t=await ca();t[fn(e.componentId,e.criterionId,e.pageUrl)]={...e,note:e.note.trim()},await Xo(t),$s.info(`acknowledged ${e.criterionId} on ${e.pageUrl}`)}async function Np(e,t,a){const n=await ca();delete n[fn(e,t,a)],await Xo(n)}async function Es(e,t,a){return(await ca())[fn(e,t,a)]??null}async function Rs(){const e=await ca();return Object.values(e)}async function Qo(e){const t=new Set;for(const n of e)n&&t.add(n);return t.size===0?[]:(await Rs()).filter(n=>t.has(n.componentId))}const Os=[{id:"1.1.1",title:"Non-text Content",level:"A",addedIn:"2.0",understandingSlug:"non-text-content",shortDescription:"All non-text content has a text alternative."},{id:"1.2.1",title:"Audio-only and Video-only (Prerecorded)",level:"A",addedIn:"2.0",understandingSlug:"audio-only-and-video-only-prerecorded",shortDescription:"Alternatives for prerecorded audio-only or video-only."},{id:"1.2.2",title:"Captions (Prerecorded)",level:"A",addedIn:"2.0",understandingSlug:"captions-prerecorded",shortDescription:"Captions for prerecorded audio in synchronized media."},{id:"1.2.3",title:"Audio Description or Media Alternative (Prerecorded)",level:"A",addedIn:"2.0",understandingSlug:"audio-description-or-media-alternative-prerecorded",shortDescription:"Alternative for time-based media (prerecorded)."},{id:"1.2.4",title:"Captions (Live)",level:"AA",addedIn:"2.0",understandingSlug:"captions-live",shortDescription:"Captions for live synchronized media."},{id:"1.2.5",title:"Audio Description (Prerecorded)",level:"AA",addedIn:"2.0",understandingSlug:"audio-description-prerecorded",shortDescription:"Audio description for prerecorded video in synchronized media."},{id:"1.2.6",title:"Sign Language (Prerecorded)",level:"AAA",addedIn:"2.0",understandingSlug:"sign-language-prerecorded",shortDescription:"Sign-language interpretation for prerecorded audio."},{id:"1.2.7",title:"Extended Audio Description (Prerecorded)",level:"AAA",addedIn:"2.0",understandingSlug:"extended-audio-description-prerecorded",shortDescription:"Extended audio description for prerecorded video."},{id:"1.2.8",title:"Media Alternative (Prerecorded)",level:"AAA",addedIn:"2.0",understandingSlug:"media-alternative-prerecorded",shortDescription:"Alternative for time-based media (prerecorded)."},{id:"1.2.9",title:"Audio-only (Live)",level:"AAA",addedIn:"2.0",understandingSlug:"audio-only-live",shortDescription:"Alternative for live audio-only content."},{id:"1.3.1",title:"Info and Relationships",level:"A",addedIn:"2.0",understandingSlug:"info-and-relationships",shortDescription:"Information and structural relationships are programmatically determinable."},{id:"1.3.2",title:"Meaningful Sequence",level:"A",addedIn:"2.0",understandingSlug:"meaningful-sequence",shortDescription:"Reading sequence is programmatically determinable."},{id:"1.3.3",title:"Sensory Characteristics",level:"A",addedIn:"2.0",understandingSlug:"sensory-characteristics",shortDescription:"Instructions don't rely solely on shape, color, size, or sound."},{id:"1.3.4",title:"Orientation",level:"AA",addedIn:"2.1",understandingSlug:"orientation",shortDescription:"Content doesn't restrict view to portrait or landscape."},{id:"1.3.5",title:"Identify Input Purpose",level:"AA",addedIn:"2.1",understandingSlug:"identify-input-purpose",shortDescription:"Purpose of input fields is programmatically identifiable."},{id:"1.3.6",title:"Identify Purpose",level:"AAA",addedIn:"2.1",understandingSlug:"identify-purpose",shortDescription:"Purpose of UI components, icons, and regions is identifiable."},{id:"1.4.1",title:"Use of Color",level:"A",addedIn:"2.0",understandingSlug:"use-of-color",shortDescription:"Color is not the only means of conveying information."},{id:"1.4.2",title:"Audio Control",level:"A",addedIn:"2.0",understandingSlug:"audio-control",shortDescription:"Mechanism to pause/stop auto-playing audio over 3s."},{id:"1.4.3",title:"Contrast (Minimum)",level:"AA",addedIn:"2.0",understandingSlug:"contrast-minimum",shortDescription:"Text has 4.5:1 contrast (3:1 for large text)."},{id:"1.4.4",title:"Resize Text",level:"AA",addedIn:"2.0",understandingSlug:"resize-text",shortDescription:"Text resizable to 200% without loss of content/function."},{id:"1.4.5",title:"Images of Text",level:"AA",addedIn:"2.0",understandingSlug:"images-of-text",shortDescription:"Text used in preference to images of text where possible."},{id:"1.4.6",title:"Contrast (Enhanced)",level:"AAA",addedIn:"2.0",understandingSlug:"contrast-enhanced",shortDescription:"Text has 7:1 contrast (4.5:1 for large text)."},{id:"1.4.7",title:"Low or No Background Audio",level:"AAA",addedIn:"2.0",understandingSlug:"low-or-no-background-audio",shortDescription:"Background audio at least 20dB lower than speech."},{id:"1.4.8",title:"Visual Presentation",level:"AAA",addedIn:"2.0",understandingSlug:"visual-presentation",shortDescription:"Configurable visual presentation for blocks of text."},{id:"1.4.9",title:"Images of Text (No Exception)",level:"AAA",addedIn:"2.0",understandingSlug:"images-of-text-no-exception",shortDescription:"Images of text used only for decoration / essential."},{id:"1.4.10",title:"Reflow",level:"AA",addedIn:"2.1",understandingSlug:"reflow",shortDescription:"Content reflows at 320 CSS px without 2D scrolling."},{id:"1.4.11",title:"Non-text Contrast",level:"AA",addedIn:"2.1",understandingSlug:"non-text-contrast",shortDescription:"UI components and graphical objects have 3:1 contrast."},{id:"1.4.12",title:"Text Spacing",level:"AA",addedIn:"2.1",understandingSlug:"text-spacing",shortDescription:"Text spacing overrides don't cause content loss."},{id:"1.4.13",title:"Content on Hover or Focus",level:"AA",addedIn:"2.1",understandingSlug:"content-on-hover-or-focus",shortDescription:"Hover/focus tooltips are dismissible, hoverable, persistent."},{id:"2.1.1",title:"Keyboard",level:"A",addedIn:"2.0",understandingSlug:"keyboard",shortDescription:"All functionality available from the keyboard."},{id:"2.1.2",title:"No Keyboard Trap",level:"A",addedIn:"2.0",understandingSlug:"no-keyboard-trap",shortDescription:"Keyboard focus can move away from any component."},{id:"2.1.3",title:"Keyboard (No Exception)",level:"AAA",addedIn:"2.0",understandingSlug:"keyboard-no-exception",shortDescription:"All functionality is keyboard-operable without timing."},{id:"2.1.4",title:"Character Key Shortcuts",level:"A",addedIn:"2.1",understandingSlug:"character-key-shortcuts",shortDescription:"Single-key shortcuts can be turned off or remapped."},{id:"2.2.1",title:"Timing Adjustable",level:"A",addedIn:"2.0",understandingSlug:"timing-adjustable",shortDescription:"User can turn off, adjust, or extend time limits."},{id:"2.2.2",title:"Pause, Stop, Hide",level:"A",addedIn:"2.0",understandingSlug:"pause-stop-hide",shortDescription:"Moving/blinking/scrolling content can be paused."},{id:"2.2.3",title:"No Timing",level:"AAA",addedIn:"2.0",understandingSlug:"no-timing",shortDescription:"No timing essential to content/function (with exceptions)."},{id:"2.2.4",title:"Interruptions",level:"AAA",addedIn:"2.0",understandingSlug:"interruptions",shortDescription:"User can postpone/suppress non-emergency interruptions."},{id:"2.2.5",title:"Re-authenticating",level:"AAA",addedIn:"2.0",understandingSlug:"re-authenticating",shortDescription:"Authenticated session can be resumed without data loss."},{id:"2.2.6",title:"Timeouts",level:"AAA",addedIn:"2.1",understandingSlug:"timeouts",shortDescription:"Inactivity timeouts warned in advance."},{id:"2.3.1",title:"Three Flashes or Below Threshold",level:"A",addedIn:"2.0",understandingSlug:"three-flashes-or-below-threshold",shortDescription:"No content flashes more than 3 times per second."},{id:"2.3.2",title:"Three Flashes",level:"AAA",addedIn:"2.0",understandingSlug:"three-flashes",shortDescription:"No content flashes more than 3 times per second (no exceptions)."},{id:"2.3.3",title:"Animation from Interactions",level:"AAA",addedIn:"2.1",understandingSlug:"animation-from-interactions",shortDescription:"Motion animation from interactions can be disabled."},{id:"2.4.1",title:"Bypass Blocks",level:"A",addedIn:"2.0",understandingSlug:"bypass-blocks",shortDescription:"Mechanism to skip blocks of repeated content."},{id:"2.4.2",title:"Page Titled",level:"A",addedIn:"2.0",understandingSlug:"page-titled",shortDescription:"Pages have titles that describe topic/purpose."},{id:"2.4.3",title:"Focus Order",level:"A",addedIn:"2.0",understandingSlug:"focus-order",shortDescription:"Components receive focus in a meaningful order."},{id:"2.4.4",title:"Link Purpose (In Context)",level:"A",addedIn:"2.0",understandingSlug:"link-purpose-in-context",shortDescription:"Link purpose is clear from the link text + context."},{id:"2.4.5",title:"Multiple Ways",level:"AA",addedIn:"2.0",understandingSlug:"multiple-ways",shortDescription:"Two or more ways to locate a page within a set."},{id:"2.4.6",title:"Headings and Labels",level:"AA",addedIn:"2.0",understandingSlug:"headings-and-labels",shortDescription:"Headings and labels describe topic or purpose."},{id:"2.4.7",title:"Focus Visible",level:"AA",addedIn:"2.0",understandingSlug:"focus-visible",shortDescription:"Keyboard focus indicator is visible."},{id:"2.4.8",title:"Location",level:"AAA",addedIn:"2.0",understandingSlug:"location",shortDescription:"Information about user's location within a set is available."},{id:"2.4.9",title:"Link Purpose (Link Only)",level:"AAA",addedIn:"2.0",understandingSlug:"link-purpose-link-only",shortDescription:"Link purpose clear from the link text alone."},{id:"2.4.10",title:"Section Headings",level:"AAA",addedIn:"2.0",understandingSlug:"section-headings",shortDescription:"Section headings are used to organize content."},{id:"2.4.11",title:"Focus Not Obscured (Minimum)",level:"AA",addedIn:"2.2",understandingSlug:"focus-not-obscured-minimum",shortDescription:"Focused component not entirely hidden by other content."},{id:"2.4.12",title:"Focus Not Obscured (Enhanced)",level:"AAA",addedIn:"2.2",understandingSlug:"focus-not-obscured-enhanced",shortDescription:"Focused component fully visible."},{id:"2.4.13",title:"Focus Appearance",level:"AAA",addedIn:"2.2",understandingSlug:"focus-appearance",shortDescription:"Focus indicator meets specific size/contrast requirements."},{id:"2.5.1",title:"Pointer Gestures",level:"A",addedIn:"2.1",understandingSlug:"pointer-gestures",shortDescription:"Multi-point or path-based gestures have single-pointer alternatives."},{id:"2.5.2",title:"Pointer Cancellation",level:"A",addedIn:"2.1",understandingSlug:"pointer-cancellation",shortDescription:"Pointer actions can be aborted or undone."},{id:"2.5.3",title:"Label in Name",level:"A",addedIn:"2.1",understandingSlug:"label-in-name",shortDescription:"Accessible name includes the visible label text."},{id:"2.5.4",title:"Motion Actuation",level:"A",addedIn:"2.1",understandingSlug:"motion-actuation",shortDescription:"Motion-triggered functions have UI alternatives + can be disabled."},{id:"2.5.5",title:"Target Size (Enhanced)",level:"AAA",addedIn:"2.1",understandingSlug:"target-size-enhanced",shortDescription:"Pointer target size at least 44×44 CSS px."},{id:"2.5.6",title:"Concurrent Input Mechanisms",level:"AAA",addedIn:"2.1",understandingSlug:"concurrent-input-mechanisms",shortDescription:"Content doesn't restrict input modality."},{id:"2.5.7",title:"Dragging Movements",level:"AA",addedIn:"2.2",understandingSlug:"dragging-movements",shortDescription:"Dragging actions have single-pointer alternatives."},{id:"2.5.8",title:"Target Size (Minimum)",level:"AA",addedIn:"2.2",understandingSlug:"target-size-minimum",shortDescription:"Pointer target size at least 24×24 CSS px."},{id:"3.1.1",title:"Language of Page",level:"A",addedIn:"2.0",understandingSlug:"language-of-page",shortDescription:"Default human language of the page is programmatically set."},{id:"3.1.2",title:"Language of Parts",level:"AA",addedIn:"2.0",understandingSlug:"language-of-parts",shortDescription:"Language of each passage is programmatically set."},{id:"3.1.3",title:"Unusual Words",level:"AAA",addedIn:"2.0",understandingSlug:"unusual-words",shortDescription:"Definitions provided for jargon, idioms, etc."},{id:"3.1.4",title:"Abbreviations",level:"AAA",addedIn:"2.0",understandingSlug:"abbreviations",shortDescription:"Expanded form or meaning of abbreviations is available."},{id:"3.1.5",title:"Reading Level",level:"AAA",addedIn:"2.0",understandingSlug:"reading-level",shortDescription:"Supplemental content provided for advanced reading levels."},{id:"3.1.6",title:"Pronunciation",level:"AAA",addedIn:"2.0",understandingSlug:"pronunciation",shortDescription:"Mechanism for pronunciation of words where meaning is ambiguous."},{id:"3.2.1",title:"On Focus",level:"A",addedIn:"2.0",understandingSlug:"on-focus",shortDescription:"Focus does not trigger an unexpected context change."},{id:"3.2.2",title:"On Input",level:"A",addedIn:"2.0",understandingSlug:"on-input",shortDescription:"Input does not trigger an unexpected context change."},{id:"3.2.3",title:"Consistent Navigation",level:"AA",addedIn:"2.0",understandingSlug:"consistent-navigation",shortDescription:"Navigation is consistent across a set of pages."},{id:"3.2.4",title:"Consistent Identification",level:"AA",addedIn:"2.0",understandingSlug:"consistent-identification",shortDescription:"Components with the same function are identified consistently."},{id:"3.2.5",title:"Change on Request",level:"AAA",addedIn:"2.0",understandingSlug:"change-on-request",shortDescription:"Changes of context only on user request."},{id:"3.2.6",title:"Consistent Help",level:"A",addedIn:"2.2",understandingSlug:"consistent-help",shortDescription:"Help mechanisms appear in consistent order across pages."},{id:"3.3.1",title:"Error Identification",level:"A",addedIn:"2.0",understandingSlug:"error-identification",shortDescription:"Form errors are identified and described in text."},{id:"3.3.2",title:"Labels or Instructions",level:"A",addedIn:"2.0",understandingSlug:"labels-or-instructions",shortDescription:"Form fields have labels or instructions."},{id:"3.3.3",title:"Error Suggestion",level:"AA",addedIn:"2.0",understandingSlug:"error-suggestion",shortDescription:"Error suggestions provided when known."},{id:"3.3.4",title:"Error Prevention (Legal, Financial, Data)",level:"AA",addedIn:"2.0",understandingSlug:"error-prevention-legal-financial-data",shortDescription:"Submissions are reversible, checked, or confirmed."},{id:"3.3.5",title:"Help",level:"AAA",addedIn:"2.0",understandingSlug:"help",shortDescription:"Context-sensitive help is available."},{id:"3.3.6",title:"Error Prevention (All)",level:"AAA",addedIn:"2.0",understandingSlug:"error-prevention-all",shortDescription:"All submissions reversible, checked, or confirmed."},{id:"3.3.7",title:"Redundant Entry",level:"A",addedIn:"2.2",understandingSlug:"redundant-entry",shortDescription:"Previously-entered information is auto-populated or selectable."},{id:"3.3.8",title:"Accessible Authentication (Minimum)",level:"AA",addedIn:"2.2",understandingSlug:"accessible-authentication-minimum",shortDescription:"Auth doesn't require cognitive function test."},{id:"3.3.9",title:"Accessible Authentication (Enhanced)",level:"AAA",addedIn:"2.2",understandingSlug:"accessible-authentication-enhanced",shortDescription:"Auth doesn't require cognitive function test (no exceptions)."},{id:"4.1.1",title:"Parsing",level:"A",addedIn:"2.0",removedIn:"2.2",understandingSlug:"parsing",shortDescription:"Markup is well-formed (obsoleted in WCAG 2.2)."},{id:"4.1.2",title:"Name, Role, Value",level:"A",addedIn:"2.0",understandingSlug:"name-role-value",shortDescription:"UI components have programmatically determinable name + role + state."},{id:"4.1.3",title:"Status Messages",level:"AA",addedIn:"2.1",understandingSlug:"status-messages",shortDescription:"Status messages programmatically announced without focus change."}];function Tt(e,t){const a={A:1,AA:2,AAA:3},n={"2.0":1,"2.1":2,"2.2":3};return Os.filter(o=>n[o.addedIn]>n[e]||o.removedIn&&n[o.removedIn]<=n[e]?!1:a[o.level]<=a[t])}function Lp(e,t){return`https://www.w3.org/WAI/WCAG${t.replace(".","")}/Understanding/${e.understandingSlug}`}let Le="2.1";const gn="AA";function Pp(e){Le=e}async function Fp(){var e,t;try{const n=(await chrome.storage.local.get("wcagTargetVersion")).wcagTargetVersion;(n==="2.1"||n==="2.2")&&(Le=n),(t=(e=chrome.storage.onChanged)==null?void 0:e.addListener)==null||t.call(e,(o,r)=>{if(r!=="local")return;const i=o.wcagTargetVersion;if(!i)return;const c=i.newValue;(c==="2.1"||c==="2.2")&&(Le=c)})}catch{}}const Ms=["3.2.3","3.2.4","3.2.6","3.3.7"];function Ds(e){const t=Tt(Le,gn),a=new Map;for(const r of t)a.set(r.id,{criterionId:r.id,level:r.level,title:r.title,state:"not-evaluated",evidence:[]});const n=new Map;function o(r,i){let c=n.get(r);return c||(c=new Set,n.set(r,c)),c.has(i)?!0:(c.add(i),!1)}for(const r of e.audits){const i=r.pageUrl??r.scope;for(const l of r.violations){if(!l.wcagCriterion)continue;const d=a.get(l.wcagCriterion);if(!d)continue;const u=l.ruleId.startsWith("ai-"),m=l.target.selector;if(e.acknowledgedMatchKeys.has(l.matchKey)){const f=`ack::${l.ruleId}::${i}::${m}`;if(o(l.wcagCriterion,f))continue;d.evidence.push({source:u?"ai":"axe",ruleOrStepId:l.ruleId,outcome:"ack",pageUrl:i,selector:m});continue}if(l.needsReview){const f=`needsReview::${l.ruleId}::${i}::${m}`;if(o(l.wcagCriterion,f))continue;d.evidence.push({source:"ai",ruleOrStepId:l.ruleId,outcome:"incomplete",pageUrl:i,selector:m,resolutionHint:"Acknowledge in the Matrix view if not an issue, or fix the underlying alt text."});continue}const p=`fail::${l.ruleId}::${i}::${m}`;o(l.wcagCriterion,p)||d.evidence.push({source:u?"ai":"axe",ruleOrStepId:l.ruleId,outcome:"fail",pageUrl:i,selector:m,resolutionHint:`Fix ${l.ruleId} on ${m}.`})}const c=r.axeRulesEvaluated;if(c){for(const l of c.passed){const d=a.get(l.wcagCriterion);if(!d)continue;const u=`axe::${l.ruleId}::${i}::pass`;o(l.wcagCriterion,u)||d.evidence.push({source:"axe",ruleOrStepId:l.ruleId,outcome:"pass",pageUrl:i})}for(const l of c.inapplicable){const d=a.get(l.wcagCriterion);if(!d)continue;const u=`axe::${l.ruleId}::${i}::inapplicable`;o(l.wcagCriterion,u)||d.evidence.push({source:"axe",ruleOrStepId:l.ruleId,outcome:"inapplicable",pageUrl:i})}for(const l of c.incomplete){const d=a.get(l.wcagCriterion);if(!d)continue;const u=`axe::${l.ruleId}::${i}::incomplete`,m=d.evidence.findIndex(p=>p.source==="axe"&&p.outcome==="incomplete"&&p.ruleOrStepId===l.ruleId&&p.pageUrl===i);if(m>=0){if(l.elements&&l.elements.length>0){const p=d.evidence[m],f=new Set((p.elements??[]).map(g=>g.selector));for(const g of l.elements)f.has(g.selector)||((p.elements??(p.elements=[])).push(g),f.add(g.selector))}continue}o(l.wcagCriterion,u)||d.evidence.push({source:"axe",ruleOrStepId:l.ruleId,outcome:"incomplete",pageUrl:i,elements:l.elements?[...l.elements]:void 0,resolutionHint:"axe-core couldn't fully determine. Common causes: text against an image/gradient background, or aria-role on a hidden element. Review the page manually."})}}}if(e.incompleteResolutions&&e.incompleteResolutions.length>0){const r=new Map;for(const i of e.incompleteResolutions)r.set(`${i.pageUrl}::${i.ruleId}::${i.selector}`,i);for(const i of a.values()){const c=[];for(const l of i.evidence){if(l.source!=="axe"||l.outcome!=="incomplete"||!l.elements||l.elements.length===0){c.push(l);continue}const d=[];for(const u of l.elements){const m=`${l.pageUrl}::${l.ruleOrStepId}::${u.selector}`,p=r.get(m);if(!p){d.push(u);continue}p.verdict==="pass"?c.push({source:"ai",ruleOrStepId:`ai-resolved::${l.ruleOrStepId}`,outcome:"pass",pageUrl:l.pageUrl,selector:u.selector,notes:p.reasoning}):p.verdict==="fail"?c.push({source:"ai",ruleOrStepId:`ai-resolved::${l.ruleOrStepId}`,outcome:"fail",pageUrl:l.pageUrl,selector:u.selector,notes:p.reasoning,resolutionHint:`AI determined ${l.ruleOrStepId} fails on this element. Review and fix or override.`}):d.push(u)}d.length>0&&c.push({...l,elements:d})}i.evidence=c}}if(e.interactiveAuditResults&&e.interactiveAuditResults.length>0)for(const r of e.interactiveAuditResults){const i=a.get(r.criterionId);i&&i.evidence.push({source:"ai",ruleOrStepId:r.ruleId,outcome:r.verdict==="pass"?"pass":r.verdict==="fail"?"fail":"incomplete",pageUrl:r.pageUrl,notes:r.reasoning,resolutionHint:r.verdict==="fail"?"Review the AI walkthrough in the Compliance tab; fix the underlying focus-order issue and re-run.":r.verdict==="uncertain"?"Re-run the interactive audit, or manually verify via Guided Tests.":void 0})}for(const r of e.workflows)for(const i of r.steps){if(!i.wcag)continue;const c=a.get(i.wcag);if(c)for(const l of e.igtRuns){if(l.workflowId!==r.id)continue;const d=l.steps[i.id],u=`${r.id}.${i.id}`;if(!d){c.evidence.push({source:"igt",ruleOrStepId:u,outcome:"skip",resolutionHint:`Open Guided Tests → ${r.name} → answer "${i.id}" as Pass / Fail / N/A.`});continue}d.status==="pass"?c.evidence.push({source:"igt",ruleOrStepId:u,outcome:"pass",notes:d.notes}):d.status==="fail"?c.evidence.push({source:"igt",ruleOrStepId:u,outcome:"fail",notes:d.notes,resolutionHint:`Address the failing manual check: ${i.question}`}):d.status==="not-applicable"?c.evidence.push({source:"igt",ruleOrStepId:u,outcome:"n/a",notes:d.notes}):d.status==="skip"&&c.evidence.push({source:"igt",ruleOrStepId:u,outcome:"skip",notes:d.notes,resolutionHint:`Open Guided Tests → ${r.name} → re-answer "${i.id}" as Pass / Fail / N/A.`})}}for(const r of a.values())r.state=Ns(r.evidence);if(e.auditScope==="single-page")for(const r of Ms){const i=a.get(r);i&&i.state==="not-evaluated"&&(i.state="not-applicable",i.evidence.push({source:"axe",ruleOrStepId:"wcc-multi-page-only-na",outcome:"n/a",notes:"Single-page audit cannot evaluate this cross-page criterion. Treated as N/A for this audit; run Site Crawl to evaluate."}))}if(e.humanCriterionVerdicts&&e.humanCriterionVerdicts.length>0)for(const r of e.humanCriterionVerdicts){const i=a.get(r.criterionId);if(!i)continue;const c=r.verdict==="na"?"n/a":r.verdict,l=r.verdict==="na"?"not-applicable":r.verdict==="fail"?"fail":"pass";i.state=l,i.evidence.push({source:"human",ruleOrStepId:"human-criterion-verdict",outcome:c,notes:`Human verified ${r.verdict.toUpperCase()} on ${r.verifiedAt}: ${r.note}`})}return a}function Ns(e){return e.length===0?"not-evaluated":e.some(a=>a.outcome==="fail")?"fail":e.some(a=>a.outcome==="incomplete"||a.outcome==="skip")?"inconclusive":e.some(a=>a.outcome==="pass"||a.outcome==="inapplicable"||a.outcome==="ack")?"pass":"not-applicable"}function Ls(e){const t={pass:[],fail:[],inconclusive:[],notApplicable:[],notEvaluated:[]};for(const n of e.values())t[Ps(n.state)].push(n.criterionId);const a=e.size;return{pass:t.pass.length,fail:t.fail.length,inconclusive:t.inconclusive.length,notApplicable:t.notApplicable.length,notEvaluated:t.notEvaluated.length,totalApplicable:a,canClaimConformance:t.fail.length===0&&t.inconclusive.length===0&&t.notEvaluated.length===0,byState:t}}function Ps(e){return e==="not-applicable"?"notApplicable":e==="not-evaluated"?"notEvaluated":e}function _p(e,t=Oe){const a=new Set,n=new Set,o=new Set;for(const i of e.values())for(const c of i.evidence)c.source==="axe"?a.add(i.criterionId):c.source==="ai"?n.add(i.criterionId):c.source==="igt"&&o.add(i.criterionId);for(const i of t)for(const c of i.steps)c.wcag&&e.has(c.wcag)&&o.add(c.wcag);function r(i,c){const l=Array.from(c).sort();let d=0;const u=[],m=[],p=[];for(const f of l){const g=e.get(f);if(!g)continue;const h=g.evidence.filter(v=>i==="automation"&&v.source==="axe"||i==="ai"&&v.source==="ai"||i==="human"&&v.source==="igt");if(h.length===0){p.push(f);continue}const y=h.some(v=>v.outcome==="fail"),b=h.some(v=>v.outcome==="incomplete"||v.outcome==="skip"),A=h.some(v=>v.outcome==="pass"||v.outcome==="inapplicable"||v.outcome==="ack"||v.outcome==="n/a");y?u.push(f):b?m.push(f):A?d++:p.push(f)}return{layer:i,coveredCriteria:l,cleared:d,failing:u,inconclusive:m,blocked:[...u,...m].sort(),unevaluated:p}}return{automation:r("automation",a),ai:r("ai",n),human:r("human",o)}}const Aa=[{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 Fs(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 _s(e,t,a="2.1",n="AA",o,r,i,c,l){const d=Ds({audits:e??[],igtRuns:(t==null?void 0:t.runs)??[],workflows:(t==null?void 0:t.workflows)??Oe,acknowledgedMatchKeys:o??new Set,incompleteResolutions:r,interactiveAuditResults:i,auditScope:c,humanCriterionVerdicts:l}),u={},m={},p=[],f=[],g=[];let h=0;for(const b of d.values()){if(b.state==="not-evaluated"){p.push(b.criterionId);continue}if(h++,b.state==="fail"){g.push(b.criterionId);const A=[];for(const v of b.evidence)v.outcome==="fail"&&A.push({source:v.source,ruleOrStepId:v.ruleOrStepId,selector:v.selector,notes:v.notes,pageUrl:v.pageUrl});A.length>0&&(m[b.criterionId]=A)}if(b.state==="inconclusive"){f.push(b.criterionId);const A=[];for(const v of b.evidence)if(v.outcome==="incomplete"){const s=v.source==="ai"?"ai-uncertain":"axe-incomplete";A.push({source:s,ruleOrStepId:v.ruleOrStepId,resolutionHint:v.resolutionHint,elements:v.elements,pageUrl:v.pageUrl})}else v.outcome==="skip"&&A.push({source:"igt-skip",ruleOrStepId:v.ruleOrStepId,resolutionHint:v.resolutionHint});A.length>0&&(u[b.criterionId]=A)}}const y=Ls(d);return{targetVersion:Le,targetLevel:gn,totalApplicable:d.size,evaluated:h,untestedCriteria:p,inconclusiveCriteria:f,failingCriteria:g,inconclusiveReasons:u,failingReasons:m,canClaimConformance:y.canClaimConformance}}function $e(e,t,a,n,o,r,i,c,l){const d=n??new Set,u=Fs(e).filter(N=>!d.has(N.matchKey)),m=u.filter(N=>N.needsReview),p=u.filter(N=>!N.needsReview),f={critical:0,serious:0,moderate:0,minor:0,unique:p.length};for(const N of p)f[N.impact]++;let g;t&&(g=Us(t.runs,t.workflows),f.serious+=g.failedRequired,f.moderate+=g.failedAdvisory,f.unique+=g.failedRequired+g.failedAdvisory);const h=[],y=[];if(o&&o.length>0){const N=new Set;if(r)for(const S of r)N.add(`${S.criterionId}::${S.pageUrl}`);const M=new Set;for(const S of o){if(S.verdict==="pass")continue;const E=`${S.criterionId}::${S.pageUrl}`;if(M.has(E))continue;M.add(E);const V=S.verdict==="fail"?"serious":"moderate",D={criterionId:S.criterionId,pageUrl:S.pageUrl,verdict:S.verdict,impact:V,reasoning:S.reasoning};if(N.has(E)){y.push(D);continue}h.push(D),f[V]++,f.unique++}}const b=new Map;for(const N of Aa)for(const M of N.rules)b.set(M,N);const A=new Map;for(const N of Aa)A.set(N.id,{count:0,rules:new Set});for(const N of Bo(p)){const M=b.get(N.ruleId);if(!M)continue;const S=A.get(M.id);S.count++,S.rules.add(N.ruleId)}const v=Aa.map(N=>{const M=A.get(N.id);let S="pass";return M.count>0?S="fail":N.needsManualCheck&&(S="unchecked"),{id:N.id,label:N.label,status:S,violationCount:M.count,rules:Array.from(M.rules),needsManualCheck:N.needsManualCheck}}),s=f.critical>0,k=f.serious>0,x=(()=>{if(!o||o.length===0||!r||r.length===0)return o;const N=new Set;for(const M of r)N.add(`${M.criterionId}::${M.pageUrl}`);return o.map(M=>N.has(`${M.criterionId}::${M.pageUrl}`)?{...M,verdict:"pass",reasoning:`Human verified: ${M.reasoning}`}:M)})(),w=a?_s(a,t,"2.1","AA",n,l,x,c,i):void 0,R=w?!w.canClaimConformance:!1;let T;f.critical>=5?T="F":f.critical>=1?T="D":f.serious>=5||f.serious>=1?T="C":f.moderate>=3||f.moderate>=1?T="B":(f.minor>=1,T="A"),R&&T==="A"&&(T="B");const P=v.filter(N=>N.status==="fail").length;let _;return f.critical>0||P>=4?_="critical":f.serious>=3||P>=2?_="high":f.serious>=1||f.moderate>=3?_="moderate":_="low",{letter:T,risk:_,caps:{cappedAtC:s,cappedAtB:k,cappedAtBByCoverage:R},totals:f,categories:v,coverage:w,manual:g,reviewQueue:{count:m.length,rules:Array.from(new Set(m.map(N=>N.ruleId)))},walkthroughFindings:h,walkthroughAcknowledgements:y}}function Us(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 l=a.get(c.id);let d=0,u=0,m=0,p=0,f=0;for(const g of c.steps){const h=l==null?void 0:l.steps[g.id];h&&(f++,h.status==="pass"?d++:h.status==="skip"?p++:h.status==="fail"&&(g.severity==="required"?u++:m++))}return f===c.steps.length&&r++,n+=u,o+=m,{workflowId:c.id,name:c.name,passed:d,failedRequired:u,failedAdvisory:m,skipped:p,answered:f,total:c.steps.length}});return{workflowsCompleted:r,workflowsTotal:t.length,failedRequired:n,failedAdvisory:o,perWorkflow:i}}const Ws={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."},Zo={low:"✓ Off the radar",moderate:"⚡ Some lawsuit exposure",high:"⚠️ High target risk",critical:"🚨 Lawsuit magnet"},ei={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."},Vn={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 Up(e,t){if(e!=="B")return Vn[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.`:Vn.B}const at={"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
5
|
<img src="/assets/logo.png" alt="">
|
|
6
6
|
|
|
7
7
|
<!-- Passing — descriptive alt -->
|
|
@@ -359,13 +359,13 @@ p { color: #333; }
|
|
|
359
359
|
p a { color: #06f; text-decoration: none; }
|
|
360
360
|
|
|
361
361
|
/* Passing — underline added */
|
|
362
|
-
p a { color: #06f; text-decoration: underline; }`,snippetLang:"css"}};function
|
|
363
|
-
`)}function
|
|
364
|
-
`)}function Hs(e,t={},a=new Set){var c;const n=e.flatMap(l=>l.violations),o=new Map;for(const l of n){const d=Te(l.ruleId,l.target.selector);o.has(d)||o.set(d,l)}const i=new Map;for(const l of o.values()){const d=l.wcagCriterion;if(!d||a.has(d))continue;const u=i.get(d)??[];u.push(l),i.set(d,u)}const r=[];for(const[l,d]of i.entries()){const u=d[0];let m=t[l];if(!m){const p=at[u.ruleId];p!=null&&p.summary?m=((c=p.summary.split(/[.!?]\s+/)[0])==null?void 0:c.trim())??u.description:m=u.description}d.length>1&&(m+=` (affects ${d.length} components on the audited page${e.length>1?"s":""})`),r.push({criterion:l,description:m})}return r.sort((l,d)=>{const u=f=>f.split(".").map(g=>parseInt(g,10)),m=u(l.criterion),p=u(d.criterion);for(let f=0;f<Math.max(m.length,p.length);f++){const g=(m[f]??0)-(p[f]??0);if(g!==0)return g}return 0}),r}function Bs(e){const t=Hs(e.results,e.customDescriptions,e.dismissedCriteria);return e.outputFormat==="html"?zs(e.inputs,t):Gs(e.inputs,t)}function Hp(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 Wt(e){return/\[Cascade resolution — rc\.\d+ escalation\]/.test(e)}function Bp(e){return/\[Manual verification — rc\.\d+\]/.test(e)}function Kp(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 Ks="wcag-forensic-log",Ys=1,Pe="audits";let ka=null;function da(){return ka||(ka=Mo(Ks,Ys,{upgrade(e){if(!e.objectStoreNames.contains(Pe)){const t=e.createObjectStore(Pe,{keyPath:["componentId","capturedAt"]});t.createIndex("byCapturedAt","capturedAt"),t.createIndex("byComponentId","componentId")}}})),ka}function za(e){return e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?"["+e.map(n=>za(n)).join(",")+"]":"{"+Object.keys(e).sort().map(n=>{const o=e[n];return JSON.stringify(n)+":"+za(o)}).join(",")+"}"}async function Js(e){const t=za(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 cr(e,t,a){if(e.length===0)return null;const n=e[0],o=n.componentId,i=n.pageUrl??n.scope,r=n.startedAt,c={componentId:o,pageUrl:i,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:r,statesAudited:e.length},d={hash:await Js(c),componentId:o,pageUrl:i,scope:n.scope,grade:t.letter,totals:c.totals,axeVersion:n.axeVersion,capturedAt:r,statesAudited:e.length,durationMs:a};try{await(await da()).put(Pe,d)}catch(u){return console.warn("[forensic-log] failed to record audit",u),d}return d}async function lr(e,t,a){try{const n=await da(),o=await n.get(Pe,[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(Pe,o)}catch(n){console.warn("[forensic-log] failed to attach receipt",n)}}async function kt(){try{return(await(await da()).getAll(Pe)).sort((a,n)=>a.capturedAt<n.capturedAt?1:-1)}catch(e){return console.warn("[forensic-log] listAudits failed",e),[]}}async function Xs(e){try{return(await(await da()).transaction(Pe).objectStore(Pe).index("byComponentId").getAll(IDBKeyRange.only(e))).sort((o,i)=>o.capturedAt<i.capturedAt?1:-1)}catch(t){return console.warn("[forensic-log] listAuditsForComponent failed",t),[]}}const Qs={"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 Zs(e){const t=Qs[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 ec={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 dr(e,t){return e==="color-contrast"&&t&&(t.self<.99||t.ancestor<.99)?ec:Zs(e)}const Ht="inflight:audit";async function ua(){return(await chrome.storage.local.get(Ht))[Ht]??null}async function Be(e){await chrome.storage.local.set({[Ht]:e})}async function nt(){await chrome.storage.local.remove(Ht)}async function Yp(){const e=await ua();e&&e.state==="running"&&await Be({...e,state:"interrupted",lastProgressAt:new Date().toISOString()})}async function $t(e){const t=await ua();t&&await Be({...t,...e,lastProgressAt:new Date().toISOString()})}function Et(){return crypto.randomUUID()}const Ha="humanCriterionVerdicts";async function mn(){var a;if(typeof chrome>"u"||!((a=chrome.storage)!=null&&a.local))return[];const t=(await chrome.storage.local.get(Ha))[Ha];return Array.isArray(t)?t:[]}async function tc(e){const t=new Set;for(const n of e)n&&t.add(n);return t.size===0?[]:(await mn()).filter(n=>t.has(n.componentId))}async function Jp(e){if(!e.note||!e.note.trim())throw new Error("Human criterion verdict requires a non-empty note explaining the determination.");const a=(await mn()).filter(n=>!(n.componentId===e.componentId&&n.criterionId===e.criterionId));a.push({...e,note:e.note.trim()}),await ur(a)}async function Xp(e,t){const n=(await mn()).filter(o=>!(o.componentId===e&&o.criterionId===t));await ur(n)}async function ur(e){var t;typeof chrome>"u"||!((t=chrome.storage)!=null&&t.local)||await chrome.storage.local.set({[Ha]:e})}function st(e){return new Set(e.map(a=>a.pageUrl??a.scope??"").filter(Boolean)).size>1?"site-crawl":"single-page"}function ac(e){const t=new Set;for(const a of e)a.componentId&&t.add(a.componentId);return Array.from(t)}async function Re(e,t=[]){const a=ac(e),n=new Set(t.filter(h=>!!h)),o=Array.from(new Set([...a,...n]));if(o.length===0)return{walkthroughs:[],walkthroughAcks:[],acknowledgedMatchKeys:new Set,humanCriterionVerdicts:[],incompleteResolutions:[],walkthroughsByComponent:new Map,walkthroughAcksByComponent:new Map,ackedKeysByComponent:new Map,humanVerdictsByComponent:new Map,incompleteResolutionsByComponent:new Map};const[i,r,c,l,d]=await Promise.all([nc(o),oc(o),rc(o),ic(o),sc(e,o)]);if(n.size>0&&a.length>0){const h=new Map;for(const y of n){const b=l.get(y)??[];for(const A of b)h.has(A.criterionId)||h.set(A.criterionId,A)}if(h.size>0)for(const y of a){const b=l.get(y)??[],A=new Set(b.map(s=>s.criterionId)),v=[...b];for(const s of h.values())A.has(s.criterionId)||v.push({...s,componentId:y});l.set(y,v)}}const u=[];for(const h of i.values())u.push(...h);const m=[];for(const h of r.values())m.push(...h);const p=new Set;for(const h of c.values())for(const y of h)p.add(y);const f=[];for(const h of l.values())f.push(...h);const g=[];for(const h of d.values())g.push(...h);return{walkthroughs:u,walkthroughAcks:m,acknowledgedMatchKeys:p,humanCriterionVerdicts:f,incompleteResolutions:g,walkthroughsByComponent:i,walkthroughAcksByComponent:r,ackedKeysByComponent:c,humanVerdictsByComponent:l,incompleteResolutionsByComponent:d}}async function nc(e){const t=new Map;return await Promise.all(e.map(async a=>{const n=await hn([a]);t.set(a,n)})),t}async function oc(e){const t=new Map,a=await Zo(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 rc(e){const t=new Map;return await Promise.all(e.map(async a=>{const n=await ia(a);t.set(a,n)})),t}async function ic(e){const t=new Map,a=await tc(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 sc(e,t){const a=new Map;for(const o of e)if(o.componentId&&!a.has(o.componentId)){const i=o.pageUrl??o.scope;i&&a.set(o.componentId,i)}const n=new Map;return await Promise.all(t.map(async o=>{const i=a.get(o);n.set(o,i?await dn(i):[])})),n}function cc(e){return e.length<2?[]:[...lc(e),...uc(e),...pc(e),...hc(e)]}function lc(e){const t=[];for(const a of["primary","footer","utility"]){const n=e.map(o=>({snapshot:o,hrefs:o.navLinks.filter(i=>i.region===a&&i.href).map(i=>i.href)})).filter(o=>o.hrefs.length>0);if(!(n.length<2))for(let o=0;o<n.length-1;o++){const i=n[o],r=n[o+1],c=i.hrefs.filter(g=>r.hrefs.includes(g));if(c.length<2)continue;const l=c.map(g=>i.hrefs.indexOf(g)),d=c.map(g=>r.hrefs.indexOf(g)),u=[...l].sort((g,h)=>g-h),m=[...d].sort((g,h)=>g-h),p=u.map(g=>c[l.indexOf(g)]),f=m.map(g=>c[d.indexOf(g)]);dc(p,f)||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: ${i.snapshot.url}`,` order: [${p.join(", ")}]`,`Page B: ${r.snapshot.url}`,` order: [${f.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(`
|
|
365
|
-
`),pages:[{url:
|
|
366
|
-
`),pages:o.map(
|
|
367
|
-
`),pages:o.map(
|
|
368
|
-
`),pages:i.map(r=>({url:r.url,evidence:`${r.label} (${r.type})`}))});return t}const Bt={A:0,B:1,C:2,D:3,F:4},jn={low:0,moderate:1,high:2,critical:3};function fc(e,t){return Bt[e]>Bt[t]?e:t}function gc(e,t){return jn[e]>jn[t]?e:t}function mc(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 bc(e,t){const a=[];for(const n of e){const o=t==null?void 0:t.get(n.componentId);for(const i of n.results)for(const r of i.violations)r.needsReview&&(o!=null&&o.has(r.matchKey)||a.push({url:n.url,v:r}))}return a}function pr(e,t,a,n,o,i,r,c,l,d){const u=t.filter(C=>!C.error).length,m=t.filter(C=>!!C.error).length,p=t.length<=1?"single-page":"site-crawl",f=t.map(C=>{if(C.error)return{url:C.url,grade:"F",risk:"critical",uniqueViolations:0,totals:{critical:0,serious:0,moderate:0,minor:0},durationMs:C.durationMs,error:C.error,walkthroughFindings:[],walkthroughAcknowledgements:[]};const W=C.results.flatMap(K=>K.violations),H=i==null?void 0:i.get(C.componentId),Q=r==null?void 0:r.get(C.componentId),se={};if(H&&H.length>0){const K=new Set((Q??[]).map(X=>X.criterionId));for(const X of H){const j=K.has(X.criterionId)?"pass":X.verdict;X.criterionId==="2.4.3"?se.focusOrder=j:X.criterionId==="2.1.2"?se.keyboardTrap=j:X.criterionId==="2.4.7"?se.focusVisible=j:X.criterionId==="1.3.2"?se.readingOrder=j:X.criterionId==="1.4.11"&&(se.nonTextContrast=j)}}const ce=c==null?void 0:c.get(C.componentId),I=l==null?void 0:l.get(C.componentId),B=d==null?void 0:d.get(C.componentId),L=$e(W,void 0,C.results,ce?new Set(ce):void 0,H?[...H]:void 0,Q?[...Q]:void 0,I?[...I]:void 0,p,B?[...B]:void 0);return ns({violations:W,auditRan:!0,manualRuns:[],workflows:Oe,heuristicCounts:{},interactiveAuditVerdicts:se}),{url:C.url,grade:L.letter,risk:L.risk,uniqueViolations:L.totals.unique,totals:{critical:L.totals.critical,serious:L.totals.serious,moderate:L.totals.moderate,minor:L.totals.minor},durationMs:C.durationMs,walkthroughFindings:L.walkthroughFindings,walkthroughAcknowledgements:L.walkthroughAcknowledgements}});f.sort((C,W)=>{const H=Bt[W.grade]-Bt[C.grade];return H!==0?H:W.uniqueViolations-C.uniqueViolations});let g="A",h="low";for(const C of f)g=fc(g,C.grade),h=gc(h,C.risk);const y=mc(t).filter(({v:C,componentId:W})=>{const H=c==null?void 0:c.get(W);return!(H!=null&&H.has(C.matchKey))}),b=C=>`${C.ruleId}::${C.target.selector}`,A=new Map;for(const{v:C}of y){const W=b(C);A.has(W)||A.set(W,C)}const v=A.size,s={critical:0,serious:0,moderate:0,minor:0};for(const C of A.values())s[C.impact]++;const k=new Map;for(const{url:C,v:W}of y){let H=k.get(W.ruleId);H||(H={ruleId:W.ruleId,description:W.description,impact:W.impact,urls:new Set,totalOccurrences:0},k.set(W.ruleId,H)),H.urls.add(C),H.totalOccurrences++}const x=Array.from(k.values()).map(C=>({ruleId:C.ruleId,description:C.description,impact:C.impact,urlsAffected:C.urls.size,totalOccurrences:C.totalOccurrences,sampleUrls:Array.from(C.urls).slice(0,5)})).sort((C,W)=>W.urlsAffected!==C.urlsAffected?W.urlsAffected-C.urlsAffected:W.totalOccurrences-C.totalOccurrences),w=bc(t,c),R=new Map,T=new Set;for(const{url:C,v:W}of w){T.add(`${W.ruleId}::${W.target.selector}`);let H=R.get(W.ruleId);H||(H={ruleId:W.ruleId,description:W.description,impact:W.impact,urls:new Set,totalOccurrences:0},R.set(W.ruleId,H)),H.urls.add(C),H.totalOccurrences++}const P=Array.from(R.values()).map(C=>({ruleId:C.ruleId,description:C.description,impact:C.impact,urlsAffected:C.urls.size,totalOccurrences:C.totalOccurrences,sampleUrls:Array.from(C.urls).slice(0,5)})).sort((C,W)=>W.urlsAffected!==C.urlsAffected?W.urlsAffected-C.urlsAffected:W.totalOccurrences-C.totalOccurrences),_=T.size,N={minor:0,moderate:1,serious:2,critical:3},M=new Map;for(const C of t){if(C.error)continue;const W=c==null?void 0:c.get(C.componentId);for(const H of C.results)for(const Q of H.violations){if(W!=null&&W.has(Q.matchKey))continue;const se=`${Te(Q.ruleId,Q.target.selector)}::${Q.needsReview?"NR":"ACT"}`;let ce=M.get(se);ce||(ce={ruleId:Q.ruleId,representativeSelector:Q.target.selector,representativeOuterHTML:Q.target.outerHTML??"",impact:Q.impact,wcagCriterion:Q.wcagCriterion??null,axeDescription:Q.description??"",pages:new Map,totalOccurrences:0,needsReview:Q.needsReview??!1,failureSummary:Q.target.failureSummary??null},M.set(se,ce)),N[Q.impact]>N[ce.impact]&&(ce.impact=Q.impact),ce.totalOccurrences++,ce.pages.has(C.url)||ce.pages.set(C.url,{selector:Q.target.selector,outerHTML:Q.target.outerHTML??""}),!ce.failureSummary&&Q.target.failureSummary&&(ce.failureSummary=Q.target.failureSummary)}}const S=Array.from(M.values()).map(C=>({ruleId:C.ruleId,representativeSelector:C.representativeSelector,representativeOuterHTML:C.representativeOuterHTML,impact:C.impact,wcagCriterion:C.wcagCriterion,axeDescription:C.axeDescription,pages:Array.from(C.pages.entries()).map(([W,H])=>({url:W,selector:H.selector,outerHTML:H.outerHTML})),totalOccurrences:C.totalOccurrences,isShared:C.pages.size>=2,needsReview:C.needsReview,failureSummary:C.failureSummary})).sort((C,W)=>N[W.impact]!==N[C.impact]?N[W.impact]-N[C.impact]:W.pages.length-C.pages.length),E={A:0,B:0,C:0,D:0,F:0};for(const C of f)E[C.grade]++;const V=t.map(C=>C.snapshot).filter(C=>!!C),D=cc(V),$=new Set,U=[],q=[];for(const C of f){for(const W of C.walkthroughFindings){const H=`${W.criterionId}::${W.pageUrl}`;$.has(H)||($.add(H),U.push(W))}for(const W of C.walkthroughAcknowledgements){const H=`${W.criterionId}::${W.pageUrl}::ack`;$.has(H)||($.add(H),q.push(W))}}const Y=new Map,Z={untested:0,inconclusive:1,failing:2},ke=new Map;for(const C of Tt("2.1","AA"))ke.set(C.id,C.title);const ie=new Map;function ne(C,W){const H=`${W.pageUrl}::${W.selector??""}::${W.source}::${W.ruleOrStepId}`;let Q=ie.get(C);if(Q||(Q=new Set,ie.set(C,Q)),Q.has(H))return;Q.add(H);const se=Y.get(C);se&&(se.evidence.length>=6||se.evidence.push(W))}for(const C of t){if(C.error)continue;const W=C.results.flatMap(j=>j.violations),H=i==null?void 0:i.get(C.componentId),Q=r==null?void 0:r.get(C.componentId),se=c==null?void 0:c.get(C.componentId),ce=l==null?void 0:l.get(C.componentId),I=d==null?void 0:d.get(C.componentId),B=$e(W,void 0,C.results,se?new Set(se):void 0,H?[...H]:void 0,Q?[...Q]:void 0,ce?[...ce]:void 0,p,I?[...I]:void 0);if(!B.coverage)continue;const L=(j,J)=>{for(const G of j){const be=ke.get(G)??G,Ue=Y.get(G);Ue?Z[J]>Z[Ue.state]&&Y.set(G,{state:J,title:be,evidence:Ue.evidence}):Y.set(G,{state:J,title:be,evidence:[]})}};L(B.coverage.untestedCriteria,"untested"),L(B.coverage.inconclusiveCriteria,"inconclusive"),L(B.coverage.failingCriteria,"failing");const K=B.coverage.inconclusiveReasons??{};for(const[j,J]of Object.entries(K))for(const G of J)if(G.elements&&G.elements.length>0)for(const be of G.elements)ne(j,{pageUrl:G.pageUrl??C.url,selector:be.selector,ruleOrStepId:G.ruleOrStepId,source:G.source,notes:be.failureSummary});else ne(j,{pageUrl:G.pageUrl??C.url,ruleOrStepId:G.ruleOrStepId,source:G.source,notes:G.resolutionHint});const X=B.coverage.failingReasons??{};for(const[j,J]of Object.entries(X))for(const G of J)ne(j,{pageUrl:G.pageUrl??C.url,selector:G.selector,ruleOrStepId:G.ruleOrStepId,source:G.source,notes:G.notes})}const ge=Array.from(Y.entries()).map(([C,W])=>({criterionId:C,title:W.title,state:W.state,evidence:W.evidence})).sort((C,W)=>C.criterionId.localeCompare(W.criterionId,void 0,{numeric:!0}));return{startedAt:a,finishedAt:n,startUrl:e,pagesAudited:u,pagesFailed:m,totalDurationMs:o,siteGrade:g,siteRisk:h,totalUniqueViolations:v,totals:s,topViolations:x,needsReviewItems:P,totalNeedsReview:_,findingGroups:S,pages:f,pagesByGrade:E,consistencyFindings:D,walkthroughFindings:U,walkthroughAcknowledgements:q,totalWalkthroughFindings:U.length,blockingCriteria:ge}}const yc="offscreen/offscreen.html";let Nt=null;async function wc(){return Nt||(Nt=(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:yc,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 Nt=null,e})),Nt}async function vc(e,t){try{await wc()}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 Ac(e,t){var a;try{return((a=(await chrome.scripting.executeScript({target:{tabId:e},func:kc,args:[t]}))[0])==null?void 0:a.result)??null}catch{return null}}function kc(e){var A;function t(v){var R,T;const s=v.getAttribute("aria-label");if(s&&s.trim())return s.trim();const k=v.getAttribute("aria-labelledby");if(k){const P=k.split(/\s+/).map(_=>{var N,M;return((M=(N=document.getElementById(_))==null?void 0:N.textContent)==null?void 0:M.trim())??""}).filter(Boolean);if(P.length)return P.join(" ")}if(v instanceof HTMLInputElement||v instanceof HTMLTextAreaElement||v instanceof HTMLSelectElement){if(v.id){const _=document.querySelector(`label[for="${CSS.escape(v.id)}"]`);if((R=_==null?void 0:_.textContent)!=null&&R.trim())return _.textContent.trim()}const P=v.closest("label");if((T=P==null?void 0:P.textContent)!=null&&T.trim())return P.textContent.trim();if(v instanceof HTMLInputElement&&v.placeholder)return v.placeholder}const x=(v.textContent??"").replace(/\s+/g," ").trim();if(x)return x.slice(0,120);const w=v.getAttribute("title");return w?w.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 k=s.getAttribute("role");if(k==="banner")return"header";if(k==="contentinfo")return"footer";if(k==="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 i=[],r=document.querySelectorAll('nav, [role="navigation"]');for(const v of Array.from(r)){const s=o(v),k=v.querySelectorAll("a[href]");let x=0;for(const w of Array.from(k)){const R=a(w.getAttribute("href")),T=t(w);!T&&!R||i.push({href:R,accessibleName:T,index:x++,region:s})}}const c=[],l=new Set;for(const v of i)v.href&&(l.has(v.href)||(l.add(v.href),c.push({fingerprint:`href:${v.href}`,accessibleName:v.accessibleName,role:"link"})));const d=[{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:k}of d){const x=document.querySelector(v);if(!x)continue;const w=`alias:${s}`;l.has(w)||(l.add(w),c.push({fingerprint:w,accessibleName:t(x),role:k}))}const u=[],m=/(help|support|contact|faq|chat|live\s*chat)\b/i,p=document.querySelectorAll('a, button, [role="button"], [role="link"]'),f=new Set;for(const v of Array.from(p)){const s=t(v),k=v.getAttribute("aria-label")??"",x=s||k;if(!m.test(x))continue;const w=`${x.toLowerCase().slice(0,32)}::${v.tagName}`;f.has(w)||(f.add(w),u.push({label:x.slice(0,80),href:v instanceof HTMLAnchorElement?a(v.getAttribute("href")):null,landmark:n(v)}))}const g=[],h=/(password|cvc|cvv|otp|one[-_\s]?time|security[-_\s]?answer|secret|2fa|mfa)/i,y=document.querySelectorAll("input, textarea, select");for(const v of Array.from(y)){if(v instanceof HTMLInputElement){const R=(v.type||"text").toLowerCase();if(R==="hidden"||R==="submit"||R==="button"||R==="image"||R==="reset")continue}const s=v.getAttribute("name")||v.id||"";if(!s)continue;const k=v instanceof HTMLInputElement?v.type||"text":v instanceof HTMLTextAreaElement?"textarea":"select",x=t(v),w=h.test(s)||h.test(x)||k==="password";g.push({name:s,type:k,label:x,isSecurityEssential:w})}let b=!1;if(document.querySelector('[role="progressbar"]')&&(b=!0),!b){const v=document.querySelectorAll('button, a, [role="button"]');let s=0,k=0;for(const x of Array.from(v)){const w=(x.textContent??"").trim();if(/step\s*\d+\s*of\s*\d+/i.test(w)){b=!0;break}/^(next|continue)$/i.test(w)&&s++,/^(previous|prev|back)$/i.test(w)&&k++}s>0&&k>0&&(b=!0)}return{url:e,title:(document.title||(((A=document.querySelector("h1"))==null?void 0:A.textContent)??"")).trim(),navLinks:i,sharedComponents:c,helpMechanisms:u,formFields:g,isMultiStep:b}}const Ic=`Respond ONLY with a JSON object — no markdown, no preamble:
|
|
362
|
+
p a { color: #06f; text-decoration: underline; }`,snippetLang:"css"}};function Wp(e){return at[e]??null}const Ga="aiColorSuggestions";async function la(){try{const t=(await chrome.storage.local.get(Ga))[Ga];return t&&typeof t=="object"?t:{}}catch{return{}}}async function ti(e){await chrome.storage.local.set({[Ga]:e})}async function qp(e){const t=await la();t[e.matchKey]=e,await ti(t)}async function Vp(e){if(e.length===0)return;const t=await la();for(const a of e)t[a.matchKey]=a;await ti(t)}async function jp(e){return(await la())[e]??null}async function qs(){return await la()}const ai={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/"}},ni=(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}.`,oi=(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}.`,ii=(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.`}},ri=(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 Vs(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"?ni(e.organizationName,e.siteUrl):oi(e.organizationName,e.siteUrl)),i.push(""),i.push("## Conformance status"),i.push(""),i.push(ii(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 l=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}${l}`)}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(ri(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=ai[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(`
|
|
363
|
+
`)}function js(e,t){const a=l=>l==null?"":String(l).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,"""),n=e.language||"English",o=e.auditedBy||"wcagcheckr (self-evaluation)",r=e.wcagVersion||"2.1",i=e.wcagLevel||"AA",c=[];if(c.push(`<article lang="${a(n)}">`),c.push(`<h1>Accessibility Statement — ${a(e.organizationName)}</h1>`),c.push(`<p><em>Statement prepared on ${a(e.preparedAt)}. Language: ${a(n)}.</em></p>`),c.push(`<p>${a(e.framing==="wad"?ni(e.organizationName,e.siteUrl):oi(e.organizationName,e.siteUrl))}</p>`),c.push("<h2>Conformance status</h2>"),c.push(`<p>${a(ii(e.conformanceStatus,r,i))}</p>`),t.length>0){c.push("<h2>Non-accessible content</h2>"),c.push("<p>The following content is not yet accessible:</p>"),c.push("<ul>");for(const l of t){const d=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>":"";c.push(`<li><strong>WCAG ${a(l.criterion)}</strong> — ${a(l.description)}${d}</li>`)}c.push("</ul>")}else e.conformanceStatus==="full"&&(c.push("<h2>Non-accessible content</h2>"),c.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(c.push("<h2>Preparation of this accessibility statement</h2>"),c.push(`<p>${a(ri(o,e.evaluatedAt))}</p>`),c.push("<h2>Feedback and contact information</h2>"),c.push(`<p>If you experience accessibility barriers on ${a(e.siteUrl)}, please contact us so we can address them:</p>`),c.push("<ul>"),e.contact.email&&c.push(`<li><strong>Email:</strong> <a href="mailto:${a(e.contact.email)}">${a(e.contact.email)}</a></li>`),e.contact.phone&&c.push(`<li><strong>Phone:</strong> ${a(e.contact.phone)}</li>`),e.contact.formUrl&&c.push(`<li><strong>Web form:</strong> <a href="${a(e.contact.formUrl)}">${a(e.contact.formUrl)}</a></li>`),c.push("</ul>"),e.framing==="wad"&&e.countryCode){const l=ai[e.countryCode];l&&(c.push("<h2>Enforcement procedure</h2>"),c.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"&&(c.push("<h2>Enforcement</h2>"),c.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>")),c.push("<hr>"),c.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>`),c.push("</article>"),c.join(`
|
|
364
|
+
`)}function Gs(e,t={},a=new Set){var c;const n=e.flatMap(l=>l.violations),o=new Map;for(const l of n){const d=Te(l.ruleId,l.target.selector);o.has(d)||o.set(d,l)}const r=new Map;for(const l of o.values()){const d=l.wcagCriterion;if(!d||a.has(d))continue;const u=r.get(d)??[];u.push(l),r.set(d,u)}const i=[];for(const[l,d]of r.entries()){const u=d[0];let m=t[l];if(!m){const p=at[u.ruleId];p!=null&&p.summary?m=((c=p.summary.split(/[.!?]\s+/)[0])==null?void 0:c.trim())??u.description:m=u.description}d.length>1&&(m+=` (affects ${d.length} components on the audited page${e.length>1?"s":""})`),i.push({criterion:l,description:m})}return i.sort((l,d)=>{const u=f=>f.split(".").map(g=>parseInt(g,10)),m=u(l.criterion),p=u(d.criterion);for(let f=0;f<Math.max(m.length,p.length);f++){const g=(m[f]??0)-(p[f]??0);if(g!==0)return g}return 0}),i}function zs(e){const t=Gs(e.results,e.customDescriptions,e.dismissedCriteria);return e.outputFormat==="html"?js(e.inputs,t):Vs(e.inputs,t)}function Gp(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 Wt(e){return/\[Cascade resolution — rc\.\d+ escalation\]/.test(e)}function zp(e){return/\[Manual verification — rc\.\d+\]/.test(e)}function Hp(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 Hs="wcag-forensic-log",Bs=1,Pe="audits";let ka=null;function da(){return ka||(ka=Mo(Hs,Bs,{upgrade(e){if(!e.objectStoreNames.contains(Pe)){const t=e.createObjectStore(Pe,{keyPath:["componentId","capturedAt"]});t.createIndex("byCapturedAt","capturedAt"),t.createIndex("byComponentId","componentId")}}})),ka}function za(e){return e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?"["+e.map(n=>za(n)).join(",")+"]":"{"+Object.keys(e).sort().map(n=>{const o=e[n];return JSON.stringify(n)+":"+za(o)}).join(",")+"}"}async function Ks(e){const t=za(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 si(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},d={hash:await Ks(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 da()).put(Pe,d)}catch(u){return console.warn("[forensic-log] failed to record audit",u),d}return d}async function ci(e,t,a){try{const n=await da(),o=await n.get(Pe,[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(Pe,o)}catch(n){console.warn("[forensic-log] failed to attach receipt",n)}}async function kt(){try{return(await(await da()).getAll(Pe)).sort((a,n)=>a.capturedAt<n.capturedAt?1:-1)}catch(e){return console.warn("[forensic-log] listAudits failed",e),[]}}async function Ys(e){try{return(await(await da()).transaction(Pe).objectStore(Pe).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 Js={"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 Xs(e){const t=Js[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 Qs={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 li(e,t){return e==="color-contrast"&&t&&(t.self<.99||t.ancestor<.99)?Qs:Xs(e)}const Ht="inflight:audit";async function ua(){return(await chrome.storage.local.get(Ht))[Ht]??null}async function Be(e){await chrome.storage.local.set({[Ht]:e})}async function nt(){await chrome.storage.local.remove(Ht)}async function Bp(){const e=await ua();e&&e.state==="running"&&await Be({...e,state:"interrupted",lastProgressAt:new Date().toISOString()})}async function $t(e){const t=await ua();t&&await Be({...t,...e,lastProgressAt:new Date().toISOString()})}function Et(){return crypto.randomUUID()}const Ha="humanCriterionVerdicts";async function mn(){var a;if(typeof chrome>"u"||!((a=chrome.storage)!=null&&a.local))return[];const t=(await chrome.storage.local.get(Ha))[Ha];return Array.isArray(t)?t:[]}async function Zs(e){const t=new Set;for(const n of e)n&&t.add(n);return t.size===0?[]:(await mn()).filter(n=>t.has(n.componentId))}async function Kp(e){if(!e.note||!e.note.trim())throw new Error("Human criterion verdict requires a non-empty note explaining the determination.");const a=(await mn()).filter(n=>!(n.componentId===e.componentId&&n.criterionId===e.criterionId));a.push({...e,note:e.note.trim()}),await di(a)}async function Yp(e,t){const n=(await mn()).filter(o=>!(o.componentId===e&&o.criterionId===t));await di(n)}async function di(e){var t;typeof chrome>"u"||!((t=chrome.storage)!=null&&t.local)||await chrome.storage.local.set({[Ha]:e})}function st(e){return new Set(e.map(a=>a.pageUrl??a.scope??"").filter(Boolean)).size>1?"site-crawl":"single-page"}function ec(e){const t=new Set;for(const a of e)a.componentId&&t.add(a.componentId);return Array.from(t)}async function Re(e,t=[]){const a=ec(e),n=new Set(t.filter(h=>!!h)),o=Array.from(new Set([...a,...n]));if(o.length===0)return{walkthroughs:[],walkthroughAcks:[],acknowledgedMatchKeys:new Set,humanCriterionVerdicts:[],incompleteResolutions:[],walkthroughsByComponent:new Map,walkthroughAcksByComponent:new Map,ackedKeysByComponent:new Map,humanVerdictsByComponent:new Map,incompleteResolutionsByComponent:new Map};const[r,i,c,l,d]=await Promise.all([tc(o),ac(o),nc(o),oc(o),ic(e,o)]);if(n.size>0&&a.length>0){const h=new Map;for(const y of n){const b=l.get(y)??[];for(const A of b)h.has(A.criterionId)||h.set(A.criterionId,A)}if(h.size>0)for(const y of a){const b=l.get(y)??[],A=new Set(b.map(s=>s.criterionId)),v=[...b];for(const s of h.values())A.has(s.criterionId)||v.push({...s,componentId:y});l.set(y,v)}}const u=[];for(const h of r.values())u.push(...h);const m=[];for(const h of i.values())m.push(...h);const p=new Set;for(const h of c.values())for(const y of h)p.add(y);const f=[];for(const h of l.values())f.push(...h);const g=[];for(const h of d.values())g.push(...h);return{walkthroughs:u,walkthroughAcks:m,acknowledgedMatchKeys:p,humanCriterionVerdicts:f,incompleteResolutions:g,walkthroughsByComponent:r,walkthroughAcksByComponent:i,ackedKeysByComponent:c,humanVerdictsByComponent:l,incompleteResolutionsByComponent:d}}async function tc(e){const t=new Map;return await Promise.all(e.map(async a=>{const n=await hn([a]);t.set(a,n)})),t}async function ac(e){const t=new Map,a=await Qo(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 nc(e){const t=new Map;return await Promise.all(e.map(async a=>{const n=await ra(a);t.set(a,n)})),t}async function oc(e){const t=new Map,a=await Zs(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 ic(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 dn(r):[])})),n}function rc(e){return e.length<2?[]:[...sc(e),...lc(e),...dc(e),...uc(e)]}function sc(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(g=>i.hrefs.includes(g));if(c.length<2)continue;const l=c.map(g=>r.hrefs.indexOf(g)),d=c.map(g=>i.hrefs.indexOf(g)),u=[...l].sort((g,h)=>g-h),m=[...d].sort((g,h)=>g-h),p=u.map(g=>c[l.indexOf(g)]),f=m.map(g=>c[d.indexOf(g)]);cc(p,f)||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: [${p.join(", ")}]`,`Page B: ${i.snapshot.url}`,` order: [${f.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(`
|
|
365
|
+
`),pages:[{url:r.snapshot.url,evidence:p.join(" → ")},{url:i.snapshot.url,evidence:f.join(" → ")}]})}}return t}function cc(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 lc(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=>bn(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(`
|
|
366
|
+
`),pages:o.map(i=>({url:i.url,evidence:i.accessibleName}))})}return t}function bn(e){return e.toLowerCase().replace(/\s+/g," ").trim()}function dc(e){const t=[],a=new Map;for(const n of e)for(const o of n.helpMechanisms){const r=bn(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(`
|
|
367
|
+
`),pages:o.map(i=>({url:i.url,evidence:`${i.rawLabel} in ${i.landmark}`}))})}return t}function uc(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=bn(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(`
|
|
368
|
+
`),pages:r.map(i=>({url:i.url,evidence:`${i.label} (${i.type})`}))});return t}const Bt={A:0,B:1,C:2,D:3,F:4},jn={low:0,moderate:1,high:2,critical:3};function pc(e,t){return Bt[e]>Bt[t]?e:t}function hc(e,t){return jn[e]>jn[t]?e:t}function fc(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 gc(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 ui(e,t,a,n,o,r,i,c,l,d){const u=t.filter(C=>!C.error).length,m=t.filter(C=>!!C.error).length,p=t.length<=1?"single-page":"site-crawl",f=t.map(C=>{if(C.error)return{url:C.url,grade:"F",risk:"critical",uniqueViolations:0,totals:{critical:0,serious:0,moderate:0,minor:0},durationMs:C.durationMs,error:C.error,walkthroughFindings:[],walkthroughAcknowledgements:[]};const W=C.results.flatMap(K=>K.violations),H=r==null?void 0:r.get(C.componentId),Q=i==null?void 0:i.get(C.componentId),se={};if(H&&H.length>0){const K=new Set((Q??[]).map(X=>X.criterionId));for(const X of H){const j=K.has(X.criterionId)?"pass":X.verdict;X.criterionId==="2.4.3"?se.focusOrder=j:X.criterionId==="2.1.2"?se.keyboardTrap=j:X.criterionId==="2.4.7"?se.focusVisible=j:X.criterionId==="1.3.2"?se.readingOrder=j:X.criterionId==="1.4.11"&&(se.nonTextContrast=j)}}const ce=c==null?void 0:c.get(C.componentId),I=l==null?void 0:l.get(C.componentId),B=d==null?void 0:d.get(C.componentId),L=$e(W,void 0,C.results,ce?new Set(ce):void 0,H?[...H]:void 0,Q?[...Q]:void 0,I?[...I]:void 0,p,B?[...B]:void 0);return ts({violations:W,auditRan:!0,manualRuns:[],workflows:Oe,heuristicCounts:{},interactiveAuditVerdicts:se}),{url:C.url,grade:L.letter,risk:L.risk,uniqueViolations:L.totals.unique,totals:{critical:L.totals.critical,serious:L.totals.serious,moderate:L.totals.moderate,minor:L.totals.minor},durationMs:C.durationMs,walkthroughFindings:L.walkthroughFindings,walkthroughAcknowledgements:L.walkthroughAcknowledgements}});f.sort((C,W)=>{const H=Bt[W.grade]-Bt[C.grade];return H!==0?H:W.uniqueViolations-C.uniqueViolations});let g="A",h="low";for(const C of f)g=pc(g,C.grade),h=hc(h,C.risk);const y=fc(t).filter(({v:C,componentId:W})=>{const H=c==null?void 0:c.get(W);return!(H!=null&&H.has(C.matchKey))}),b=C=>`${C.ruleId}::${C.target.selector}`,A=new Map;for(const{v:C}of y){const W=b(C);A.has(W)||A.set(W,C)}const v=A.size,s={critical:0,serious:0,moderate:0,minor:0};for(const C of A.values())s[C.impact]++;const k=new Map;for(const{url:C,v:W}of y){let H=k.get(W.ruleId);H||(H={ruleId:W.ruleId,description:W.description,impact:W.impact,urls:new Set,totalOccurrences:0},k.set(W.ruleId,H)),H.urls.add(C),H.totalOccurrences++}const x=Array.from(k.values()).map(C=>({ruleId:C.ruleId,description:C.description,impact:C.impact,urlsAffected:C.urls.size,totalOccurrences:C.totalOccurrences,sampleUrls:Array.from(C.urls).slice(0,5)})).sort((C,W)=>W.urlsAffected!==C.urlsAffected?W.urlsAffected-C.urlsAffected:W.totalOccurrences-C.totalOccurrences),w=gc(t,c),R=new Map,T=new Set;for(const{url:C,v:W}of w){T.add(`${W.ruleId}::${W.target.selector}`);let H=R.get(W.ruleId);H||(H={ruleId:W.ruleId,description:W.description,impact:W.impact,urls:new Set,totalOccurrences:0},R.set(W.ruleId,H)),H.urls.add(C),H.totalOccurrences++}const P=Array.from(R.values()).map(C=>({ruleId:C.ruleId,description:C.description,impact:C.impact,urlsAffected:C.urls.size,totalOccurrences:C.totalOccurrences,sampleUrls:Array.from(C.urls).slice(0,5)})).sort((C,W)=>W.urlsAffected!==C.urlsAffected?W.urlsAffected-C.urlsAffected:W.totalOccurrences-C.totalOccurrences),_=T.size,N={minor:0,moderate:1,serious:2,critical:3},M=new Map;for(const C of t){if(C.error)continue;const W=c==null?void 0:c.get(C.componentId);for(const H of C.results)for(const Q of H.violations){if(W!=null&&W.has(Q.matchKey))continue;const se=`${Te(Q.ruleId,Q.target.selector)}::${Q.needsReview?"NR":"ACT"}`;let ce=M.get(se);ce||(ce={ruleId:Q.ruleId,representativeSelector:Q.target.selector,representativeOuterHTML:Q.target.outerHTML??"",impact:Q.impact,wcagCriterion:Q.wcagCriterion??null,axeDescription:Q.description??"",pages:new Map,totalOccurrences:0,needsReview:Q.needsReview??!1,failureSummary:Q.target.failureSummary??null},M.set(se,ce)),N[Q.impact]>N[ce.impact]&&(ce.impact=Q.impact),ce.totalOccurrences++,ce.pages.has(C.url)||ce.pages.set(C.url,{selector:Q.target.selector,outerHTML:Q.target.outerHTML??""}),!ce.failureSummary&&Q.target.failureSummary&&(ce.failureSummary=Q.target.failureSummary)}}const S=Array.from(M.values()).map(C=>({ruleId:C.ruleId,representativeSelector:C.representativeSelector,representativeOuterHTML:C.representativeOuterHTML,impact:C.impact,wcagCriterion:C.wcagCriterion,axeDescription:C.axeDescription,pages:Array.from(C.pages.entries()).map(([W,H])=>({url:W,selector:H.selector,outerHTML:H.outerHTML})),totalOccurrences:C.totalOccurrences,isShared:C.pages.size>=2,needsReview:C.needsReview,failureSummary:C.failureSummary})).sort((C,W)=>N[W.impact]!==N[C.impact]?N[W.impact]-N[C.impact]:W.pages.length-C.pages.length),E={A:0,B:0,C:0,D:0,F:0};for(const C of f)E[C.grade]++;const V=t.map(C=>C.snapshot).filter(C=>!!C),D=rc(V),$=new Set,U=[],q=[];for(const C of f){for(const W of C.walkthroughFindings){const H=`${W.criterionId}::${W.pageUrl}`;$.has(H)||($.add(H),U.push(W))}for(const W of C.walkthroughAcknowledgements){const H=`${W.criterionId}::${W.pageUrl}::ack`;$.has(H)||($.add(H),q.push(W))}}const Y=new Map,Z={untested:0,inconclusive:1,failing:2},ke=new Map;for(const C of Tt("2.1","AA"))ke.set(C.id,C.title);const re=new Map;function ne(C,W){const H=`${W.pageUrl}::${W.selector??""}::${W.source}::${W.ruleOrStepId}`;let Q=re.get(C);if(Q||(Q=new Set,re.set(C,Q)),Q.has(H))return;Q.add(H);const se=Y.get(C);se&&(se.evidence.length>=6||se.evidence.push(W))}for(const C of t){if(C.error)continue;const W=C.results.flatMap(j=>j.violations),H=r==null?void 0:r.get(C.componentId),Q=i==null?void 0:i.get(C.componentId),se=c==null?void 0:c.get(C.componentId),ce=l==null?void 0:l.get(C.componentId),I=d==null?void 0:d.get(C.componentId),B=$e(W,void 0,C.results,se?new Set(se):void 0,H?[...H]:void 0,Q?[...Q]:void 0,ce?[...ce]:void 0,p,I?[...I]:void 0);if(!B.coverage)continue;const L=(j,J)=>{for(const G of j){const be=ke.get(G)??G,Ue=Y.get(G);Ue?Z[J]>Z[Ue.state]&&Y.set(G,{state:J,title:be,evidence:Ue.evidence}):Y.set(G,{state:J,title:be,evidence:[]})}};L(B.coverage.untestedCriteria,"untested"),L(B.coverage.inconclusiveCriteria,"inconclusive"),L(B.coverage.failingCriteria,"failing");const K=B.coverage.inconclusiveReasons??{};for(const[j,J]of Object.entries(K))for(const G of J)if(G.elements&&G.elements.length>0)for(const be of G.elements)ne(j,{pageUrl:G.pageUrl??C.url,selector:be.selector,ruleOrStepId:G.ruleOrStepId,source:G.source,notes:be.failureSummary});else ne(j,{pageUrl:G.pageUrl??C.url,ruleOrStepId:G.ruleOrStepId,source:G.source,notes:G.resolutionHint});const X=B.coverage.failingReasons??{};for(const[j,J]of Object.entries(X))for(const G of J)ne(j,{pageUrl:G.pageUrl??C.url,selector:G.selector,ruleOrStepId:G.ruleOrStepId,source:G.source,notes:G.notes})}const ge=Array.from(Y.entries()).map(([C,W])=>({criterionId:C,title:W.title,state:W.state,evidence:W.evidence})).sort((C,W)=>C.criterionId.localeCompare(W.criterionId,void 0,{numeric:!0}));return{startedAt:a,finishedAt:n,startUrl:e,pagesAudited:u,pagesFailed:m,totalDurationMs:o,siteGrade:g,siteRisk:h,totalUniqueViolations:v,totals:s,topViolations:x,needsReviewItems:P,totalNeedsReview:_,findingGroups:S,pages:f,pagesByGrade:E,consistencyFindings:D,walkthroughFindings:U,walkthroughAcknowledgements:q,totalWalkthroughFindings:U.length,blockingCriteria:ge}}const mc="offscreen/offscreen.html";let Nt=null;async function bc(){return Nt||(Nt=(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:mc,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 Nt=null,e})),Nt}async function yc(e,t){try{await bc()}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 wc(e,t){var a;try{return((a=(await chrome.scripting.executeScript({target:{tabId:e},func:vc,args:[t]}))[0])==null?void 0:a.result)??null}catch{return null}}function vc(e){var A;function t(v){var R,T;const s=v.getAttribute("aria-label");if(s&&s.trim())return s.trim();const k=v.getAttribute("aria-labelledby");if(k){const P=k.split(/\s+/).map(_=>{var N,M;return((M=(N=document.getElementById(_))==null?void 0:N.textContent)==null?void 0:M.trim())??""}).filter(Boolean);if(P.length)return P.join(" ")}if(v instanceof HTMLInputElement||v instanceof HTMLTextAreaElement||v instanceof HTMLSelectElement){if(v.id){const _=document.querySelector(`label[for="${CSS.escape(v.id)}"]`);if((R=_==null?void 0:_.textContent)!=null&&R.trim())return _.textContent.trim()}const P=v.closest("label");if((T=P==null?void 0:P.textContent)!=null&&T.trim())return P.textContent.trim();if(v instanceof HTMLInputElement&&v.placeholder)return v.placeholder}const x=(v.textContent??"").replace(/\s+/g," ").trim();if(x)return x.slice(0,120);const w=v.getAttribute("title");return w?w.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 k=s.getAttribute("role");if(k==="banner")return"header";if(k==="contentinfo")return"footer";if(k==="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),k=v.querySelectorAll("a[href]");let x=0;for(const w of Array.from(k)){const R=a(w.getAttribute("href")),T=t(w);!T&&!R||r.push({href:R,accessibleName:T,index:x++,region:s})}}const c=[],l=new Set;for(const v of r)v.href&&(l.has(v.href)||(l.add(v.href),c.push({fingerprint:`href:${v.href}`,accessibleName:v.accessibleName,role:"link"})));const d=[{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:k}of d){const x=document.querySelector(v);if(!x)continue;const w=`alias:${s}`;l.has(w)||(l.add(w),c.push({fingerprint:w,accessibleName:t(x),role:k}))}const u=[],m=/(help|support|contact|faq|chat|live\s*chat)\b/i,p=document.querySelectorAll('a, button, [role="button"], [role="link"]'),f=new Set;for(const v of Array.from(p)){const s=t(v),k=v.getAttribute("aria-label")??"",x=s||k;if(!m.test(x))continue;const w=`${x.toLowerCase().slice(0,32)}::${v.tagName}`;f.has(w)||(f.add(w),u.push({label:x.slice(0,80),href:v instanceof HTMLAnchorElement?a(v.getAttribute("href")):null,landmark:n(v)}))}const g=[],h=/(password|cvc|cvv|otp|one[-_\s]?time|security[-_\s]?answer|secret|2fa|mfa)/i,y=document.querySelectorAll("input, textarea, select");for(const v of Array.from(y)){if(v instanceof HTMLInputElement){const R=(v.type||"text").toLowerCase();if(R==="hidden"||R==="submit"||R==="button"||R==="image"||R==="reset")continue}const s=v.getAttribute("name")||v.id||"";if(!s)continue;const k=v instanceof HTMLInputElement?v.type||"text":v instanceof HTMLTextAreaElement?"textarea":"select",x=t(v),w=h.test(s)||h.test(x)||k==="password";g.push({name:s,type:k,label:x,isSecurityEssential:w})}let b=!1;if(document.querySelector('[role="progressbar"]')&&(b=!0),!b){const v=document.querySelectorAll('button, a, [role="button"]');let s=0,k=0;for(const x of Array.from(v)){const w=(x.textContent??"").trim();if(/step\s*\d+\s*of\s*\d+/i.test(w)){b=!0;break}/^(next|continue)$/i.test(w)&&s++,/^(previous|prev|back)$/i.test(w)&&k++}s>0&&k>0&&(b=!0)}return{url:e,title:(document.title||(((A=document.querySelector("h1"))==null?void 0:A.textContent)??"")).trim(),navLinks:r,sharedComponents:c,helpMechanisms:u,formFields:g,isMultiStep:b}}const Ac=`Respond ONLY with a JSON object — no markdown, no preamble:
|
|
369
369
|
{
|
|
370
370
|
"verdict": "pass" | "fail" | "uncertain",
|
|
371
371
|
"reasoning": "one-sentence explanation",
|
|
@@ -373,7 +373,7 @@ p a { color: #06f; text-decoration: underline; }`,snippetLang:"css"}};function V
|
|
|
373
373
|
}`,Lt=`
|
|
374
374
|
|
|
375
375
|
Previous verdict on this page: {{verdict}} ({{confidence}}% confidence). Reasoning: "{{reasoning}}". Keep the same verdict unless concrete new evidence has changed.
|
|
376
|
-
`,
|
|
376
|
+
`,kc={version:0,jsonOutputInstructions:Ac,altText:{template:`You are an accessibility auditor. Judge whether the alt text describes the image.
|
|
377
377
|
|
|
378
378
|
Alt: {{alt}}
|
|
379
379
|
{{surroundingContextLine}}
|
|
@@ -548,23 +548,23 @@ Screenshot of {{pageUrl}} attached.
|
|
|
548
548
|
|
|
549
549
|
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.
|
|
550
550
|
|
|
551
|
-
{{jsonOutputInstructions}}`,maxTokens:1500}};function
|
|
552
|
-
Nearby page context: ${
|
|
553
|
-
Accessible name (alt / aria-label) of this image: "${o.slice(0,200)}"`:""}),d=await oe({apiKey:e.apiKey,model:t,maxTokens:l,signal:
|
|
554
|
-
`)||" (no tabbable elements found)",m=
|
|
555
|
-
`)||" (Shift-Tab moved to body / no reverse path)",p=
|
|
551
|
+
{{jsonOutputInstructions}}`,maxTokens:1500}};function pi(e,t){return e.replace(/\{\{(\w+)\}\}/g,(a,n)=>{const o=t[n];return o??""})}function hi(){var e;return((e=Gr())==null?void 0:e.aiPrompts)??kc}function me(e,t){const a=hi(),n=e(a),o={...t,jsonOutputInstructions:a.jsonOutputInstructions};return{text:pi(n.template,o),maxTokens:n.maxTokens}}function Pt(e,t){if(!t)return"";const a=e(hi());return a.anchorTemplate?pi(a.anchorTemplate,{verdict:t.verdict.toUpperCase(),confidence:(t.confidence*100).toFixed(0),reasoning:t.reasoning.slice(0,400).replace(/"/g,"'")}):""}const Ic={input:3/1e6,output:15/1e6},xc={input:1/1e6,output:5/1e6},Sc="claude-sonnet-4-6",Cc="https://api.anthropic.com/v1/messages",Tc="2023-06-01";function $c(e){const t=e.model||Sc,a=t.includes("haiku")?xc:Ic;return{providerId:"anthropic",async judgeAltText({imageUrl:n,alt:o,surroundingContext:r,signal:i}){const c=await Hn(n,i);if(!c)return Bn("Could not fetch image to verify alt text",0,t);const{text:l,maxTokens:d}=me(m=>m.altText,{alt:o?`"${o}"`:"(empty / missing)",surroundingContextLine:r?`
|
|
552
|
+
Nearby page context: ${r.slice(0,500)}`:""}),u=await oe({apiKey:e.apiKey,model:t,maxTokens:d,signal:i,messages:[{role:"user",content:[{type:"image",source:{type:"base64",media_type:c.mediaType,data:c.data}},{type:"text",text:l}]}]});return pe(u,a)},async judgeHeading({headingText:n,sectionContent:o,signal:r}){const{text:i,maxTokens:c}=me(d=>d.heading,{headingText:n,sectionContent:o.slice(0,800)}),l=await oe({apiKey:e.apiKey,model:t,maxTokens:c,signal:r,messages:[{role:"user",content:[{type:"text",text:i}]}]});return pe(l,a)},async judgeSensoryLanguage({instructionText:n,signal:o}){const{text:r,maxTokens:i}=me(l=>l.sensoryLanguage,{instructionText:n.slice(0,800)}),c=await oe({apiKey:e.apiKey,model:t,maxTokens:i,signal:o,messages:[{role:"user",content:[{type:"text",text:r}]}]});return pe(c,a)},async judgeAriaSemantics({elementHtml:n,computedRole:o,surroundingHtml:r,signal:i}){const{text:c,maxTokens:l}=me(u=>u.ariaSemantics,{elementHtml:n.slice(0,600),computedRole:o,surroundingHtml:r.slice(0,500)}),d=await oe({apiKey:e.apiKey,model:t,maxTokens:l,signal:i,messages:[{role:"user",content:[{type:"text",text:c}]}]});return pe(d,a)},async judgeImageOfText({imageUrl:n,accessibleName:o,signal:r}){const i=await Hn(n,r);if(!i)return Bn("Could not fetch image to inspect for embedded text",0,t);const{text:c,maxTokens:l}=me(u=>u.imageOfText,{accessibleNameLine:o?`
|
|
553
|
+
Accessible name (alt / aria-label) of this image: "${o.slice(0,200)}"`:""}),d=await oe({apiKey:e.apiKey,model:t,maxTokens:l,signal:r,messages:[{role:"user",content:[{type:"image",source:{type:"base64",media_type:i.mediaType,data:i.data}},{type:"text",text:c}]}]});return pe(d,a)},async judgeColorOnlyMeaning({elementHtml:n,contextDescription:o,signal:r}){const{text:i,maxTokens:c}=me(d=>d.colorOnlyMeaning,{elementHtml:n.slice(0,800),contextDescription:o.slice(0,400)}),l=await oe({apiKey:e.apiKey,model:t,maxTokens:c,signal:r,messages:[{role:"user",content:[{type:"text",text:i}]}]});return pe(l,a)},async judgeGenericLinkText({linkText:n,surroundingText:o,signal:r}){const{text:i,maxTokens:c}=me(d=>d.genericLinkText,{linkText:n.slice(0,200),surroundingText:o.slice(0,800)}),l=await oe({apiKey:e.apiKey,model:t,maxTokens:c,signal:r,messages:[{role:"user",content:[{type:"text",text:i}]}]});return pe(l,a)},async judgeWallOfText({blockText:n,structuralChildrenCount:o,signal:r}){const{text:i,maxTokens:c}=me(d=>d.wallOfText,{blockText:n.slice(0,1200),structuralChildrenCount:String(o)}),l=await oe({apiKey:e.apiKey,model:t,maxTokens:c,signal:r,messages:[{role:"user",content:[{type:"text",text:i}]}]});return pe(l,a)},async judgeLanguageMismatch({declaredLang:n,bodyTextSample:o,signal:r}){const{text:i,maxTokens:c}=me(d=>d.languageMismatch,{declaredLang:n||"(none / empty)",bodyTextSample:o.slice(0,1200)}),l=await oe({apiKey:e.apiKey,model:t,maxTokens:c,signal:r,messages:[{role:"user",content:[{type:"text",text:i}]}]});return pe(l,a)},async suggestColorFix(n){const o=await oe({apiKey:e.apiKey,model:t,maxTokens:600,messages:[{role:"user",content:[{type:"text",text:Uc(n)}]}]});return qc(o,a)},async generateExecutiveSummary(n){const o=await oe({apiKey:e.apiKey,model:t,maxTokens:800,messages:[{role:"user",content:[{type:"text",text:Wc(n)}]}]});return Gc(o,a)},async resolveAxeIncomplete(n){const o=await oe({apiKey:e.apiKey,model:t,maxTokens:400,signal:n.signal,messages:[{role:"user",content:[{type:"text",text:Vc(n)}]}]});return jc(o,a,t)},async judgeFocusVisible({pageUrl:n,samples:o,signal:r}){const i=[];for(const u of o){const m=/^data:(image\/[a-z]+);base64,(.+)$/i.exec(u.screenshot);m&&(i.push({type:"image",source:{type:"base64",media_type:m[1],data:m[2]}}),i.push({type:"text",text:`Image #${u.ordinal} — selector: ${u.selector} — role: ${u.role||"(none)"} — name: "${u.name||"(no name)"}" — rect: x=${Math.round(u.rect.x)} y=${Math.round(u.rect.y)} w=${Math.round(u.rect.width)} h=${Math.round(u.rect.height)} — outline: ${u.focusStyle.outlineStyle} ${u.focusStyle.outlineWidth} ${u.focusStyle.outlineColor} (offset ${u.focusStyle.outlineOffset}) — box-shadow: ${u.focusStyle.boxShadow||"none"}`}))}const{text:c,maxTokens:l}=me(u=>u.focusVisible,{pageUrl:n,sampleCount:String(o.length)});i.push({type:"text",text:c});const d=await oe({apiKey:e.apiKey,model:t,maxTokens:l,signal:r,messages:[{role:"user",content:i}]});return pe(d,a)},async judgeConsistencyDivergence({wcagCriterion:n,ruleId:o,description:r,details:i,pages:c,signal:l}){const d=Fc(n,o,r,i,c),u=await oe({apiKey:e.apiKey,model:t,maxTokens:500,signal:l,messages:[{role:"user",content:[{type:"text",text:d}]}]});return pe(u,a)},async judgeKeyboardTrap({pageUrl:n,forwardSequence:o,reverseSequence:r,stuckRuns:i,reverseMismatches:c,previousVerdict:l,signal:d}){const u=o.map((b,A)=>` ${A+1}. ${b}`).join(`
|
|
554
|
+
`)||" (no tabbable elements found)",m=r.map((b,A)=>` ${A+1}. ${b}`).join(`
|
|
555
|
+
`)||" (Shift-Tab moved to body / no reverse path)",p=i.length===0?" (none detected)":i.map(b=>` - ${b}`).join(`
|
|
556
556
|
`),f=c.length===0?" (none — Shift-Tab cleanly reversed the forward order)":c.map(b=>` - position ${b.index}: expected ${b.expected}, got ${b.actual}`).join(`
|
|
557
|
-
`),{text:g,maxTokens:h}=me(b=>b.keyboardTrap,{pageUrl:n,anchor:Pt(b=>b.keyboardTrap,l),forwardSequence:u,reverseSequence:m,stuckRuns:p,reverseMismatches:f}),y=await oe({apiKey:e.apiKey,model:t,maxTokens:h,signal:d,messages:[{role:"user",content:[{type:"text",text:g}]}]});return
|
|
558
|
-
`),{text:d,maxTokens:u}=me(f=>f.readingOrder,{pageUrl:n,anchor:Pt(f=>f.readingOrder,
|
|
557
|
+
`),{text:g,maxTokens:h}=me(b=>b.keyboardTrap,{pageUrl:n,anchor:Pt(b=>b.keyboardTrap,l),forwardSequence:u,reverseSequence:m,stuckRuns:p,reverseMismatches:f}),y=await oe({apiKey:e.apiKey,model:t,maxTokens:h,signal:d,messages:[{role:"user",content:[{type:"text",text:g}]}]});return pe(y,a)},async judgeNonTextContrast({pageUrl:n,pageScreenshot:o,previousVerdict:r,signal:i}){const{text:c,maxTokens:l}=me(p=>p.nonTextContrast,{pageUrl:n,anchor:Pt(p=>p.nonTextContrast,r)}),d=[],u=/^data:(image\/[a-z]+);base64,(.+)$/i.exec(o);u&&d.push({type:"image",source:{type:"base64",media_type:u[1],data:u[2]}}),d.push({type:"text",text:c});const m=await oe({apiKey:e.apiKey,model:t,maxTokens:l,signal:i,messages:[{role:"user",content:d}]});return pe(m,a)},async judgeReadingOrder({pageUrl:n,pageScreenshot:o,flaggedIssues:r,previousVerdict:i,signal:c}){const l=r.map(f=>` - DOM #${f.domIndex} → Visual #${f.visualIndex} | selector ${f.selector} | at (x=${Math.round(f.rect.x)}, y=${Math.round(f.rect.y)}, w=${Math.round(f.rect.w)}, h=${Math.round(f.rect.h)}) | text: "${f.textSnippet.slice(0,80).replace(/"/g,"'")}"`).join(`
|
|
558
|
+
`),{text:d,maxTokens:u}=me(f=>f.readingOrder,{pageUrl:n,anchor:Pt(f=>f.readingOrder,i),flaggedCount:String(r.length),issuesList:l}),m=[];if(o){const f=/^data:(image\/[a-z]+);base64,(.+)$/i.exec(o);f&&m.push({type:"image",source:{type:"base64",media_type:f[1],data:f[2]}})}m.push({type:"text",text:d});const p=await oe({apiKey:e.apiKey,model:t,maxTokens:u,signal:c,messages:[{role:"user",content:m}]});return pe(p,a)},async judgeFocusOrder({pageUrl:n,pageScreenshot:o,tabSequence:r,previousVerdict:i,signal:c}){const{text:l,maxTokens:d}=me(p=>p.focusOrder,{pageUrl:n,anchor:Pt(p=>p.focusOrder,i),rowBucketPx:String(Kt),seq:Gn(r)}),u=[];if(o){const p=/^data:(image\/[a-z]+);base64,(.+)$/i.exec(o);p&&u.push({type:"image",source:{type:"base64",media_type:p[1],data:p[2]}})}u.push({type:"text",text:l});const m=await oe({apiKey:e.apiKey,model:t,maxTokens:d,signal:c,messages:[{role:"user",content:u}]});return pe(m,a)},async judgeLabelInName({pageUrl:n,pageScreenshot:o,candidates:r,signal:i}){const c=r.map((p,f)=>`${f+1}. [${p.role}] selector=${p.selector}
|
|
559
559
|
visibleText: "${p.visibleText}"
|
|
560
560
|
accessibleName: "${p.accessibleName}"`).join(`
|
|
561
|
-
`),{text:l,maxTokens:d}=me(p=>p.labelInName,{pageUrl:n,candidatesList:c}),u=[];if(o){const p=/^data:(image\/[a-z]+);base64,(.+)$/i.exec(o);p&&u.push({type:"image",source:{type:"base64",media_type:p[1],data:p[2]}})}u.push({type:"text",text:l});const m=await oe({apiKey:e.apiKey,model:t,maxTokens:d,signal:
|
|
561
|
+
`),{text:l,maxTokens:d}=me(p=>p.labelInName,{pageUrl:n,candidatesList:c}),u=[];if(o){const p=/^data:(image\/[a-z]+);base64,(.+)$/i.exec(o);p&&u.push({type:"image",source:{type:"base64",media_type:p[1],data:p[2]}})}u.push({type:"text",text:l});const m=await oe({apiKey:e.apiKey,model:t,maxTokens:d,signal:i,messages:[{role:"user",content:u}]});return pe(m,a)},async judgeFocusOrderFallback({pageUrl:n,pageScreenshot:o,tabSequence:r,primaryUncertainReason:i,signal:c}){const{text:l,maxTokens:d}=me(p=>p.focusOrderFallback,{pageUrl:n,primaryUncertainReason:i.replace(/"/g,"'").slice(0,600),rowBucketPx:String(Kt),seq:Gn(r)}),u=[];if(o){const p=/^data:(image\/[a-z]+);base64,(.+)$/i.exec(o);p&&u.push({type:"image",source:{type:"base64",media_type:p[1],data:p[2]}})}u.push({type:"text",text:l});const m=await oe({apiKey:e.apiKey,model:t,maxTokens:d,signal:c,messages:[{role:"user",content:u}]});return pe(m,a)}}}function Gn(e){return _c(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(`
|
|
562
562
|
`);return` Row ~y=${a.row*Kt} (${a.items.length} item${a.items.length===1?"":"s"}):
|
|
563
563
|
${n}`}).join(`
|
|
564
|
-
`)}class It extends Error{constructor(){super("Anthropic API: canceled by caller"),this.name="ExternalAbortError"}}const
|
|
564
|
+
`)}class It extends Error{constructor(){super("Anthropic API: canceled by caller"),this.name="ExternalAbortError"}}const fi=3e4,zn=3,Ec=1e4;function Rc(e){return e===429||e>=500}function Oc(e){return e instanceof Error?e.name==="TimeoutError"||e.name==="AbortError"||e instanceof TypeError:!1}function Mc(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 Dc(e){var o,r;const t=AbortSignal.timeout(fi),a=Mc(t,e.signal);let n;try{n=await fetch(Cc,{method:"POST",headers:{"x-api-key":e.apiKey,"anthropic-version":Tc,"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 It:i}if(!n.ok){const c=((r=(await n.json().catch(()=>({}))).error)==null?void 0:r.message)??`${n.status} ${n.statusText}`,l=new Error(`Anthropic API: ${c}`);throw l.status=n.status,l}return await n.json()}async function oe(e){var a;let t=null;for(let n=1;n<=zn;n++){if((a=e.signal)!=null&&a.aborted)throw new It;try{return await Dc(e)}catch(o){if(o instanceof It)throw o;const r=o.status;if(!(Oc(o)||typeof r=="number"&&Rc(r))||n===zn)throw o instanceof Error&&(o.name==="TimeoutError"||o.name==="AbortError")?new Error(`Anthropic API: timed out after ${fi/1e3}s on each of ${n} attempt${n===1?"":"s"}`):o;t=o instanceof Error?o:new Error(String(o)),await Nc(n*1e3,e.signal)}}throw t??new Error("Anthropic API: all retries failed")}function Nc(e,t){return new Promise((a,n)=>{if(t!=null&&t.aborted){n(new It);return}const o=setTimeout(()=>{t==null||t.removeEventListener("abort",r),a()},e),r=()=>{clearTimeout(o),n(new It)};t==null||t.addEventListener("abort",r,{once:!0})})}async function Hn(e,t){var r,i;const a=new AbortController,n=setTimeout(()=>a.abort(),Ec),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 l=((i=(r=c.headers.get("content-type"))==null?void 0:r.split(";")[0])==null?void 0:i.trim())??"image/png";if(!l.startsWith("image/")||l!=="image/jpeg"&&l!=="image/png"&&l!=="image/gif"&&l!=="image/webp")return null;const d=await c.arrayBuffer();let u="";const m=new Uint8Array(d),p=32768;for(let f=0;f<m.length;f+=p)u+=String.fromCharCode(...m.slice(f,f+p));return{data:btoa(u),mediaType:l}}catch{return null}finally{clearTimeout(n),t&&t.removeEventListener("abort",o)}}function pe(e,t){var r;const a=((r=e.content.find(i=>i.type==="text"))==null?void 0:r.text)??"",n=Lc(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 Lc(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 Bn(e,t,a){return{verdict:"uncertain",reasoning:e,confidence:0,costUsd:t,model:a}}const Pc=`
|
|
565
565
|
Respond ONLY with a single JSON object — no preamble, no markdown:
|
|
566
566
|
{ "verdict": "pass" | "fail" | "uncertain", "reasoning": "1-3 sentences", "confidence": 0.0-1.0 }
|
|
567
|
-
`.trim();function
|
|
567
|
+
`.trim();function Fc(e,t,a,n,o){const r=o.map((c,l)=>` ${l+1}. ${c.url}
|
|
568
568
|
${c.evidence}`).join(`
|
|
569
569
|
`);return`You are an accessibility auditor evaluating whether a heuristic finding is a real WCAG violation or a false positive.
|
|
570
570
|
|
|
@@ -578,7 +578,7 @@ Diagnostic details:
|
|
|
578
578
|
${n}
|
|
579
579
|
|
|
580
580
|
Pages involved:
|
|
581
|
-
${
|
|
581
|
+
${r}
|
|
582
582
|
|
|
583
583
|
WCAG context for this criterion:
|
|
584
584
|
${{"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]}
|
|
@@ -598,7 +598,7 @@ Verdict mapping:
|
|
|
598
598
|
- "fail" = real divergence. This IS a WCAG ${e} violation and should be reported to the user.
|
|
599
599
|
- "uncertain" = the evidence is genuinely ambiguous; surface the finding so a human can decide.
|
|
600
600
|
|
|
601
|
-
${
|
|
601
|
+
${Pc}`}const Kt=32;function _c(e){const t=[];let a=null;for(const n of e){const o=Math.round(n.rect.y/Kt);a===null||a.row!==o?(a={row:o,items:[n]},t.push(a)):a.items.push(n)}return t}function Uc(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.
|
|
602
602
|
|
|
603
603
|
Current pair (FAILING):
|
|
604
604
|
- Foreground: ${e.foreground}
|
|
@@ -625,7 +625,7 @@ Respond ONLY with a JSON object — no preamble, no markdown:
|
|
|
625
625
|
{ "foreground": "#hexHEX", "background": "#hexHEX", "contrast": 4.6, "rationale": "1 sentence" }
|
|
626
626
|
],
|
|
627
627
|
"reasoning": "1-3 sentences explaining your overall approach or why no suggestions are possible"
|
|
628
|
-
}`}function
|
|
628
|
+
}`}function Wc(e){return`You are an accessibility auditor writing the executive summary for an automated audit report.
|
|
629
629
|
|
|
630
630
|
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"}.
|
|
631
631
|
Framing: ${e.framing} report.
|
|
@@ -656,7 +656,7 @@ Respond ONLY with a JSON object — no preamble, no markdown:
|
|
|
656
656
|
"lead": "2-3 sentence headline framing",
|
|
657
657
|
"body": "2-3 paragraphs of risk explanation + audit-date framing + ongoing-diligence context if applicable. ~150-300 words total.",
|
|
658
658
|
"closer": "1-2 sentence closing line"
|
|
659
|
-
}`}function
|
|
659
|
+
}`}function qc(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]),l=(c.candidates??[]).slice(0,3).map(d=>({foreground:typeof d.foreground=="string"?d.foreground:"",background:typeof d.background=="string"?d.background:"",contrast:typeof d.contrast=="number"?d.contrast:0,rationale:typeof d.rationale=="string"?d.rationale:""})).filter(d=>d.foreground&&d.background);return{verdict:c.verdict==="suggested"&&l.length>0?"suggested":"no-suggestion",candidates:l,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 Vc(e){var n,o,r,i,c,l;const t=(n=e.element.styles)==null?void 0:n.effectiveBackground,a=e.ruleId==="color-contrast"||e.ruleId==="color-contrast-enhanced"?`
|
|
660
660
|
This is a COLOR-CONTRAST evaluation. axe-core couldn't determine the
|
|
661
661
|
contrast ratio (commonly because the element's own background-color
|
|
662
662
|
is transparent and axe didn't walk the DOM cascade to find the
|
|
@@ -666,8 +666,8 @@ element's own background-color, when computing contrast.
|
|
|
666
666
|
|
|
667
667
|
Computed styles axe captured at audit time:
|
|
668
668
|
- Foreground (color): ${((o=e.element.styles)==null?void 0:o.foreground)??"unknown"}
|
|
669
|
-
- Element's OWN background-color: ${((
|
|
670
|
-
- Font size: ${((
|
|
669
|
+
- Element's OWN background-color: ${((r=e.element.styles)==null?void 0:r.background)??"unknown"} (often transparent; ignore unless solid)
|
|
670
|
+
- Font size: ${((i=e.element.styles)==null?void 0:i.fontSize)??"unknown"} px
|
|
671
671
|
- Font weight: ${((c=e.element.styles)==null?void 0:c.fontWeight)??"unknown"}
|
|
672
672
|
- Text sample: ${JSON.stringify(((l=e.element.styles)==null?void 0:l.textSample)??"")}
|
|
673
673
|
|
|
@@ -729,7 +729,7 @@ Respond with strict JSON (no markdown fences):
|
|
|
729
729
|
{
|
|
730
730
|
"verdict": "pass" | "fail" | "uncertain",
|
|
731
731
|
"reasoning": "one or two sentences explaining the determination, citing the contrast ratio for color-contrast"
|
|
732
|
-
}`}function zc(e,t,a){var c;const n=((c=e.content.find(l=>l.type==="text"))==null?void 0:c.text)??"",i=n.replace(/```(?:json)?/g,"").trim().match(/\{[\s\S]*\}/),r=e.usage.input_tokens*t.input+e.usage.output_tokens*t.output;if(!i)return{verdict:"uncertain",reasoning:n||"AI returned no parseable response.",costUsd:r,model:e.model||a};try{const l=JSON.parse(i[0]);return{verdict:l.verdict==="pass"||l.verdict==="fail"?l.verdict:"uncertain",reasoning:typeof l.reasoning=="string"&&l.reasoning?l.reasoning:"AI returned no rationale.",costUsd:r,model:e.model||a}}catch{return{verdict:"uncertain",reasoning:n,costUsd:r,model:e.model||a}}}function Hc(e,t){var r;const a=((r=e.content.find(c=>c.type==="text"))==null?void 0:r.text)??"",o=a.replace(/```(?:json)?/g,"").trim().match(/\{[\s\S]*\}/),i=e.usage.input_tokens*t.input+e.usage.output_tokens*t.output;if(!o)return{lead:"",body:a||"Summary generation failed.",closer:"",costUsd:i,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:i,model:e.model}}catch{return{lead:"",body:a,closer:"",costUsd:i,model:e.model}}}function pe(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:Rc({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 gt=ee("consistency-ai-suppression");async function Bc(e,t={}){var u;if(e.length===0)return{emitted:[],suppressed:0,uncertain:0,apiCalls:0};const a=await de();if(!ue(a,"aiConsistencySuppression"))return{emitted:e,suppressed:0,uncertain:0,apiCalls:0};let n;try{const m=await chrome.storage.local.get("aiConfig");n=we(m.aiConfig)}catch{return gt.debug("aiConfig load failed; emitting heuristic findings unchanged"),{emitted:e,suppressed:0,uncertain:0,apiCalls:0}}const o=pe(n);if(!o.ok)return gt.info(`AI client unavailable (${o.reason}); emitting heuristic findings unchanged`),{emitted:e,suppressed:0,uncertain:0,apiCalls:0};const i=o.client;if(typeof i.judgeConsistencyDivergence!="function")return gt.info("AI client does not support judgeConsistencyDivergence; emitting heuristic findings unchanged"),{emitted:e,suppressed:0,uncertain:0,apiCalls:0};const r=[];let c=0,l=0,d=0;for(const m of e){if((u=t.signal)!=null&&u.aborted){r.push(m);continue}try{const p=await i.judgeConsistencyDivergence({wcagCriterion:m.wcagCriterion,ruleId:m.ruleId,description:m.description,details:m.details,pages:m.pages,signal:t.signal});if(d++,p.verdict==="pass"){c++;continue}if(p.verdict==="fail"){r.push({...m,aiVerdict:{verdict:"real-divergence",confidence:p.confidence??0,reasoning:p.reasoning??""}});continue}l++,r.push({...m,aiVerdict:{verdict:"uncertain",confidence:p.confidence??0,reasoning:p.reasoning??""}})}catch(p){gt.warn(`AI suppression failed for ${m.ruleId} ${m.wcagCriterion}: ${p instanceof Error?p.message:String(p)}`),r.push(m)}}return gt.info(`consistency AI suppression: ${d} API calls, ${c} false-positives suppressed, ${l} uncertain, ${r.length} emitted`),{emitted:r,suppressed:c,uncertain:l,apiCalls:d}}function Kc(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 i of e.directions)for(const r of e.themes){const c=e.ariaVariations.length===0?[null]:e.ariaVariations;for(const l of c)for(const d of e.pseudoStates)a.push({pseudoState:d,ariaVariation:l,theme:r,direction:i,breakpoint:o})}}return a}const mr=["color-contrast","color-contrast-enhanced","link-in-text-block"],Yc=["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(mr),t=Yc.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 Jc=ee("chrome-api"),Xc="1.3",Kn=3e4;class Qc extends Error{constructor(t,a){super(`CDP ${t} timed out after ${a}ms`),this.method=t,this.timeoutMs=a,this.name="CdpTimeoutError"}}class br{constructor(t){this.target=t}async attach(){await chrome.debugger.attach(this.target,Xc)}async detach(){try{await chrome.debugger.detach(this.target)}catch(t){Jc.debug("detach soft-failure",t)}}async send(t,a){const n=chrome.debugger.sendCommand(this.target,t,a);let o;const i=new Promise((r,c)=>{o=setTimeout(()=>c(new Qc(t,Kn)),Kn)});try{return await Promise.race([n,i])}finally{o!==void 0&&clearTimeout(o)}}}function Zc(e){const t=e instanceof Error?e.message:String(e);return/Another debugger is already attached|Cannot attach to/i.test(t)}function yr(e){const t=e instanceof Error?e.message:String(e);return Zc(e)?Rn("DEBUGGER_BUSY","DevTools is open on this tab. Close it to run the audit.",!0,{raw:t}):Rn("STATE_DRIVE_FAILED",t,!1)}function el(e){const t=(a,n)=>e(a,n);return chrome.debugger.onDetach.addListener(t),()=>chrome.debugger.onDetach.removeListener(t)}const ye=ee("state-driver"),tl=60*1e3,Me=new Map,Yt=new Map,ct=new Map,ot=new Map,al='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"]',xt=new Map,nl={default:[],hover:["hover"],focus:["focus"],"focus-visible":["focus","focus-visible"],active:["active"],disabled:[]};async function wr(e){let t=Me.get(e);if(!t){t=new br({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}Me.set(e,t),ct.set(e,new Map),ol(e),ye.info("attached",{tabId:e})}return il(e),t}function ol(e){const t=(a,n,o)=>{var r,c;if(a.tabId!==e)return;const i=ct.get(e);if(i)if(n==="Runtime.executionContextCreated"){const l=o,d=l==null?void 0:l.context;d&&((r=d.auxData)!=null&&r.isDefault)&&((c=d.auxData)!=null&&c.frameId)&&i.set(d.auxData.frameId,d.id)}else if(n==="Runtime.executionContextDestroyed"){const l=o,d=l==null?void 0:l.executionContextId;if(d!==void 0)for(const[u,m]of i.entries())m===d&&i.delete(u)}else n==="Runtime.executionContextsCleared"&&i.clear()};chrome.debugger.onEvent.addListener(t)}async function rl(e){const t=Me.get(e);if(Me.delete(e),ct.delete(e),ot.delete(e),xt.delete(e),t)try{await t.detach()}catch{}}function il(e){const t=Yt.get(e);t&&clearTimeout(t),Yt.set(e,setTimeout(()=>{pa(e).catch(a=>ye.warn("idle detach failed",a))},tl))}async function pa(e){const t=Me.get(e);t&&(await t.detach(),Me.delete(e)),ct.delete(e),ot.delete(e),xt.delete(e);const a=Yt.get(e);a&&(clearTimeout(a),Yt.delete(e))}function vr(e){const t=[{id:e.frame.id,url:e.frame.url}];for(const a of e.childFrames??[])t.push(...vr(a));return t}async function sl(e,t,a){var i;if(!a||a===0)return;const n=ct.get(t);if(!n)return;let o;try{o=(i=(await chrome.scripting.executeScript({target:{tabId:t,frameIds:[a]},func:()=>location.href}))[0])==null?void 0:i.result}catch(r){ye.debug("frame URL lookup failed",r)}try{const r=await e.send("Page.getFrameTree"),c=vr(r.frameTree);if(o){const u=c.find(m=>m.url===o);if(u){const m=n.get(u.id);if(m!==void 0)return m}}const l=r.frameTree.frame.id,d=c.find(u=>u.id!==l);return d?n.get(d.id):void 0}catch(r){ye.warn("Page.getFrameTree failed",r);return}}async function cl(e,t,a){var r;const n={expression:`document.querySelector(${JSON.stringify(t)})`,objectGroup:"wcag-auditor",returnByValue:!1};a!==void 0&&(n.contextId=a);const i=(r=(await e.send("Runtime.evaluate",n)).result)==null?void 0:r.objectId;if(!i)return null;try{return(await e.send("DOM.requestNode",{objectId:i})).nodeId??null}finally{e.send("Runtime.releaseObject",{objectId:i}).catch(()=>{})}}async function Ar(e){const t=ot.get(e);if(!t||t.length===0)return;const a=Me.get(e);if(a){for(const n of t)try{await a.send("CSS.forcePseudoState",{nodeId:n,forcedPseudoClasses:[]})}catch(o){ye.debug("forcePseudoState clear failed (node may be gone)",o)}ot.delete(e)}}async function ll(e,t){try{return(await e.send("DOM.querySelectorAll",{nodeId:t,selector:al})).nodeIds??[]}catch(a){return ye.debug("querySelectorAll for interactive descendants failed",a),[]}}async function Ba(e,t,a,n){await chrome.scripting.executeScript({target:yn(e,t),func:(o,i)=>{const r=document.querySelector(o);r&&(i?r.setAttribute("disabled",""):r.removeAttribute("disabled"))},args:[a,n]})}async function kr(e,t){await chrome.scripting.executeScript({target:yn(e,t),func:()=>{const a=document.activeElement;a&&typeof a.blur=="function"&&a.blur()}})}async function Ir(e,t){await chrome.scripting.executeScript({target:{tabId:e,frameIds:[0]},func:a=>{document.documentElement.setAttribute("dir",a)},args:[t]})}async function dl(e,t,a,n){await chrome.scripting.executeScript({target:yn(e,t),func:(o,i)=>{const r=document.querySelector(o);if(r)for(const[c,l]of Object.entries(i))r.setAttribute(c,l)},args:[a,n]})}function yn(e,t){return t!==void 0&&t!==0?{tabId:e,frameIds:[t]}:{tabId:e}}async function ul(e,t,a,n){const o=await wr(e),i=xt.get(e),r=(i==null?void 0:i.scope)===a&&(i==null?void 0:i.frameId)===n,c=t.ariaVariation?JSON.stringify(t.ariaVariation.attributes):"",l=!r||(i==null?void 0:i.pseudoState)!==t.pseudoState,d=!i||i.theme!==t.theme,u=!i||i.direction!==t.direction,m=!i||i.breakpointId!==t.breakpoint.id,p=!r||(i==null?void 0:i.ariaVariationKey)!==c;if(l&&(await Ar(e),a)){t.pseudoState==="disabled"?await Ba(e,n,a,!0):(await Ba(e,n,a,!1),await kr(e,n));const f=nl[t.pseudoState];if(f.length>0){const g=await sl(o,e,n),h=await cl(o,a,g);if(h!==null){const y=await ll(o,h),b=[h,...y];for(const A of b)try{await o.send("CSS.forcePseudoState",{nodeId:A,forcedPseudoClasses:f})}catch(v){ye.debug(`CSS.forcePseudoState failed for nodeId=${A}`,v)}ot.set(e,b),ye.debug(`forced :${t.pseudoState} on ${b.length} node(s)`)}else ye.debug(`could not resolve nodeId for ${a} (frameId=${n})`)}}if(d){const f=[{name:"prefers-reduced-motion",value:"reduce"}];t.theme==="dark"?(f.push({name:"prefers-color-scheme",value:"dark"}),f.push({name:"forced-colors",value:"none"})):t.theme==="light"?(f.push({name:"prefers-color-scheme",value:"light"}),f.push({name:"forced-colors",value:"none"})):t.theme==="forced-colors-active"?f.push({name:"forced-colors",value:"active"}):t.theme==="forced-colors-none"&&f.push({name:"forced-colors",value:"none"}),await o.send("Emulation.setEmulatedMedia",{features:f}),await new Promise(g=>setTimeout(g,50))}u&&await Ir(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}),p&&t.ariaVariation&&a&&await dl(e,n,a,t.ariaVariation.attributes),xt.set(e,{scope:a,frameId:n,pseudoState:t.pseudoState,theme:t.theme,direction:t.direction,breakpointId:t.breakpoint.id,ariaVariationKey:c})}async function pl(e,t,a){const n=Me.get(e);if(n){if(await Ar(e),xt.delete(e),t)try{await Ba(e,a,t,!1),await kr(e,a),await Ir(e,"ltr")}catch(o){ye.warn("element-level reset partial failure",o)}try{await n.send("Emulation.setEmulatedMedia",{features:[]}),await n.send("Emulation.clearDeviceMetricsOverride")}catch(o){ye.warn("reset partial failure",o)}await pa(e)}}async function Ka(e,t,a,n){try{return await ul(e,t,a,n),z({type:"STATE_CHANGED_EVENT",tabId:e,currentState:t}),{type:"STATE_DRIVE_RESPONSE",success:!0,appliedState:t}}catch(o){return ye.error("state drive failed",o),await rl(e),{type:"STATE_DRIVE_RESPONSE",success:!1,error:yr(o)}}}async function qt(e,t,a){await pl(e,t,a)}async function Qp(e){await pa(e);try{await chrome.debugger.detach({tabId:e})}catch{}}async function hl(e,t={}){try{const a=await wr(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 ye.debug("Page.captureScreenshot failed",a),null}}function Zp(){var a;const e=[];if(e.push(Ie("STATE_DRIVE_REQUEST",n=>Ka(n.tabId,n.state,n.scope,n.frameId))),e.push(Ie("STATE_RESET_REQUEST",n=>qt(n.tabId))),(a=chrome.tabs)!=null&&a.onRemoved){const n=o=>{pa(o).catch(()=>{})};chrome.tabs.onRemoved.addListener(n),e.push(()=>chrome.tabs.onRemoved.removeListener(n))}const t=el((n,o)=>{n.tabId!==void 0&&(Me.delete(n.tabId),ct.delete(n.tabId),ot.delete(n.tabId),ye.warn("unexpected detach",{tabId:n.tabId,reason:o}))});return e.push(t),ye.info("handlers registered"),()=>e.forEach(n=>n())}const Ze=ee("cloud-sync"),Yn="cloudSyncEnabled",Ia="cloudSyncEndpoint",xa="licenseToken",Ya="cloudSyncVersionCache";async function wn(){try{const e=await de();if(!ue(e,"cloudSync"))return null;const t=await chrome.storage.local.get([Yn,Ia,xa]),a=t[Yn]===!0,n=typeof t[Ia]=="string"?t[Ia]:"",o=typeof t[xa]=="string"?t[xa]:"";return!a||!n||!o?null:{endpoint:n.replace(/\/$/,""),token:o,enabled:a}}catch{return null}}async function xr(){try{const t=(await chrome.storage.local.get(Ya))[Ya];return t&&typeof t=="object"?t:{}}catch{return{}}}async function Jt(e){try{await chrome.storage.local.set({[Ya]:e})}catch{}}async function fl(e,t,a){const n=await wn();if(!n)return!1;const o=await xr(),i=o[e];try{const r=`${n.endpoint}/v1/products/wcagcheckr/baselines/${encodeURIComponent(e)}`,c=await fetch(r,{method:"PUT",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n.token}`},body:JSON.stringify({snapshot:t,axeVersion:a,expectedVersion:i})});if(c.status===409)return Ze.warn(`baseline ${e} version conflict on push`,{expectedVersion:i}),delete o[e],await Jt(o),!1;if(!c.ok)return Ze.warn("baseline push failed",{status:c.status}),!1;const l=await c.json();return typeof l.version=="number"&&(o[e]=l.version,await Jt(o)),!0}catch(r){return Ze.debug("push network failure (offline?)",r),!1}}async function gl(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 xr();delete o[e],await Jt(o)}return n.ok}catch(a){return Ze.debug("delete network failure",a),!1}}async function ml(){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 Ze.warn("pull failed",{status:t.status}),[];const n=(await t.json()).items??[],o={};for(const i of n)o[i.componentId]=i.version;return await Jt(o),n}catch(t){return Ze.debug("pull network failure",t),[]}}const Sr=ee("baseline-store"),Jn="componentIdAliases";async function rt(e,t){try{return await t()}catch(a){const n=a instanceof Error?a.message:String(a);throw Sr.error(`baseline IDB ${e} failed: ${n}`),new ui({code:"BASELINE_DB_ERROR",message:`Baseline storage is unavailable (${e}: ${n}).`,recoverable:!1,details:n})}}async function ha(e){return((await chrome.storage.local.get(Jn))[Jn]??{})[e]??e}async function bl(e){const t=await ha(e),a=await rt("get",()=>oa(t));return a?{violations:a.violations,snapshotMeta:a.snapshotMeta}:null}async function yl(e,t,a,n){const o=await ha(e),i=await rt("get-for-set",()=>oa(o)),r=(i==null?void 0:i.seenOnUrls)??[],c=r.includes(a.url)?r:[...r,a.url];await rt("set",()=>nn({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})),fl(o,{violations:t,snapshotMeta:a},a.axeVersion).catch(()=>{})}function wl(e,t){if(!e||!t||On(e)===On(t))return;const a=i=>{var r,c,l,d,u;return(((r=i.pseudoStates)==null?void 0:r.length)??0)*Math.max(1,((c=i.ariaVariations)==null?void 0:c.length)??0)*(((l=i.themes)==null?void 0:l.length)??0)*(((d=i.directions)==null?void 0:d.length)??0)*(((u=i.breakpoints)==null?void 0:u.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 vn(e,t,a,n){var d;const o=await ha(e),i=await ia(o),r=await rt("compare",()=>oa(o));if(!r){const u=t.filter(p=>i.has(p.matchKey)),m=t.filter(p=>!i.has(p.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:u,acknowledgedCount:u.length}}const c=di(r.violations,t,r.snapshotMeta,{baselineAnnouncements:r.announcements,currentAnnouncements:a==null?void 0:a.announcements,baselineFocusEvents:r.focusEvents,currentFocusEvents:a==null?void 0:a.focusEvents},i),l=wl((d=r.snapshotMeta)==null?void 0:d.matrixConfig,n);return l&&(c.matrixMismatchWarning=l),c}async function vl(e){const t=await ha(e);await rt("delete",()=>No(t)),gl(t).catch(()=>{})}async function eh(){const e=await ml();for(const t of e)await nn({componentId:t.componentId,violations:t.snapshot.violations,snapshotMeta:t.snapshot.snapshotMeta,lastUpdated:t.updatedAt,axeVersion:t.axeVersion});return e.length>0&&z({type:"SCORECARD_UPDATED_EVENT"}),e.length}async function Al(e){let t=await rt("list",()=>Lo());return e!=null&&e.url&&(t=t.filter(a=>a.snapshotMeta.url===e.url)),t.map(a=>{const n=(a.focusEvents??[]).filter(d=>d.isFocusReset).length,o=(a.announcements??[]).length,i=a.violations.filter(d=>d.ruleId==="target-size").length,r=a.violations.some(d=>d.ruleId==="color-contrast"&&d.currentState.pseudoState==="hover"),c=a.violations.filter(d=>d.impact==="critical").length,l=a.violations.filter(d=>d.impact==="serious").length;return{componentId:a.componentId,violationCount:a.violations.length,lastUpdated:a.lastUpdated,seenOnUrlsCount:(a.seenOnUrls??[]).length,metrics:{criticalCount:c,seriousCount:l,focusResetCount:n,announcementCount:o,targetSizeFailCount:i,hoverContrastFail:r}}})}function th(){const e=[];return e.push(Ie("BASELINE_GET",async t=>({type:"BASELINE_GET_RESPONSE",baseline:await bl(t.componentId)}))),e.push(Ie("BASELINE_SET",async t=>{await yl(t.componentId,t.violations,t.snapshotMeta,{announcements:t.announcements,focusEvents:t.focusEvents}),z({type:"SCORECARD_UPDATED_EVENT"})})),e.push(Ie("BASELINE_COMPARE",async t=>({type:"BASELINE_COMPARE_RESPONSE",delta:await vn(t.componentId,t.currentViolations,{announcements:t.announcements,focusEvents:t.focusEvents},t.currentMatrix)}))),e.push(Ie("BASELINE_DELETE",async t=>{await vl(t.componentId),z({type:"SCORECARD_UPDATED_EVENT"})})),e.push(Ie("BASELINE_LIST",async t=>({type:"BASELINE_LIST_RESPONSE",items:await Al(t.filter)}))),Sr.info("handlers registered"),()=>e.forEach(t=>t())}const kl=ee("settings-store"),Xn=1,Qn="__schemaVersion",Ja={stateMatrix:Na,componentIdAliases:{},ignorePatterns:[]};async function Ve(e,t){return(await chrome.storage.local.get(e))[e]??t}async function ah(){const e=await chrome.storage.local.get();if(e[Qn]===Xn)return;const t={[Qn]:Xn};for(const[a,n]of Object.entries(Ja))a in e||(t[a]=n);await chrome.storage.local.set(t),kl.info("defaults ensured")}const Il=["__","inflight:","license:","support:"];function xl(e){return!Il.some(t=>e.startsWith(t))}function nh(){const e=[];return e.push(Ie("SETTINGS_GET",async t=>({type:"SETTINGS_RESPONSE",data:(await chrome.storage.local.get(t.key))[t.key]??Ja[t.key]}))),e.push(Ie("SETTINGS_SET",async t=>{await chrome.storage.local.set({[t.key]:t.value})})),e.push(Ie("SETTINGS_GET_ALL",async()=>{const t=await chrome.storage.local.get(),a=Object.fromEntries(Object.entries(t).filter(([n])=>xl(n)));return{type:"SETTINGS_RESPONSE",data:{...Ja,...a}}})),()=>e.forEach(t=>t())}function Ee(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 Sl=ee("ai-alt-text");async function Cl(e,t,a={}){var m,p;if(!t.enabled||!t.enabledChecks.altText)return{findings:[],totalCostUsd:0,capExceeded:!1,errors:[]};const n=pe(t);if(!n.ok)return{findings:[],totalCostUsd:0,capExceeded:!1,errors:[`AI client unavailable: ${n.reason}`]};const o=n.client,i=Ee(t.costCapUsd),r=[],c=[],l=Math.max(1,t.maxCandidatesPerCheck??10),d=e.slice(0,l),u=d.length;for(let f=0;f<d.length;f++){const g=d[f];if(!i.canCharge())break;try{if((m=a.signal)!=null&&m.aborted){c.push(`canceled after ${f}/${u} candidates`);break}const h=await o.judgeAltText({imageUrl:g.imageUrl,alt:g.alt,surroundingContext:g.surroundingContext,signal:a.signal});i.recordCharge(h.costUsd),(h.verdict==="fail"||h.verdict==="uncertain"&&h.confidence<.6)&&r.push(await Tl(g,h))}catch(h){if(h instanceof Error&&(h.name==="AbortError"||h.name==="ExternalAbortError")){c.push(`canceled after ${f}/${u} candidates`);break}const b=h instanceof Error?h.message:String(h);c.push(`${g.selector}: ${b}`),Sl.warn("alt-text judgment failed",h)}(p=a.onProgress)==null||p.call(a,f+1,u)}return{findings:r,totalCostUsd:i.state.spentUsd,capExceeded:i.state.exceeded,errors:c}}async function Tl(e,t){const a=t.verdict==="uncertain"?"ai-alt-uncertain":"ai-alt-misleading",n={selector:e.selector,outerHTML:e.outerHTML.slice(0,500),failureSummary:`AI assessment: ${t.reasoning}`,tagName:"IMG",role:null,accessibleName:e.alt,textSnippet:null,attrId:null,attrTestid:null},o=await tn({ruleId:a,componentId:e.componentId,currentState:e.currentState,target:n}),i=t.verdict==="uncertain";return{ruleId:a,wcagCriterion:"1.1.1",wcagLevel:"A",impact:i?"minor":"serious",description:i?"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:n,componentId:e.componentId,currentState:e.currentState,axeVersion:e.axeVersion,detectedAt:new Date().toISOString(),matchKey:o,ai:{reasoning:t.reasoning,confidence:t.confidence,model:t.model,costUsd:t.costUsd},...i?{needsReview:!0}:{}}}const mt=ee("interactive-audit"),$l="1.3",El={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 An{constructor(t){Mt(this,"session");Mt(this,"attached",!1);Mt(this,"steps",[]);this.tabId=t,this.session=new br({tabId:t})}async attach(){if(!this.attached)try{await chrome.debugger.attach({tabId:this.tabId},$l),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 mt.error("attach failed",t),yr(t)}}async dispose(){if(this.attached){try{await chrome.debugger.detach({tabId:this.tabId})}catch(t){mt.debug("detach soft-failure",t)}this.attached=!1}}async pressKey(t,a){const n=El[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 Zn(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 Zn(50)}async countFocusables(){var a;const t=`(() => {
|
|
732
|
+
}`}function jc(e,t,a){var c;const n=((c=e.content.find(l=>l.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 l=JSON.parse(r[0]);return{verdict:l.verdict==="pass"||l.verdict==="fail"?l.verdict:"uncertain",reasoning:typeof l.reasoning=="string"&&l.reasoning?l.reasoning:"AI returned no rationale.",costUsd:i,model:e.model||a}}catch{return{verdict:"uncertain",reasoning:n,costUsd:i,model:e.model||a}}}function Gc(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 ue(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:$c({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 gt=ee("consistency-ai-suppression");async function zc(e,t={}){var u;if(e.length===0)return{emitted:[],suppressed:0,uncertain:0,apiCalls:0};const a=await fe();if(!de(a,"aiConsistencySuppression"))return{emitted:e,suppressed:0,uncertain:0,apiCalls:0};let n;try{const m=await chrome.storage.local.get("aiConfig");n=we(m.aiConfig)}catch{return gt.debug("aiConfig load failed; emitting heuristic findings unchanged"),{emitted:e,suppressed:0,uncertain:0,apiCalls:0}}const o=ue(n);if(!o.ok)return gt.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 gt.info("AI client does not support judgeConsistencyDivergence; emitting heuristic findings unchanged"),{emitted:e,suppressed:0,uncertain:0,apiCalls:0};const i=[];let c=0,l=0,d=0;for(const m of e){if((u=t.signal)!=null&&u.aborted){i.push(m);continue}try{const p=await r.judgeConsistencyDivergence({wcagCriterion:m.wcagCriterion,ruleId:m.ruleId,description:m.description,details:m.details,pages:m.pages,signal:t.signal});if(d++,p.verdict==="pass"){c++;continue}if(p.verdict==="fail"){i.push({...m,aiVerdict:{verdict:"real-divergence",confidence:p.confidence??0,reasoning:p.reasoning??""}});continue}l++,i.push({...m,aiVerdict:{verdict:"uncertain",confidence:p.confidence??0,reasoning:p.reasoning??""}})}catch(p){gt.warn(`AI suppression failed for ${m.ruleId} ${m.wcagCriterion}: ${p instanceof Error?p.message:String(p)}`),i.push(m)}}return gt.info(`consistency AI suppression: ${d} API calls, ${c} false-positives suppressed, ${l} uncertain, ${i.length} emitted`),{emitted:i,suppressed:c,uncertain:l,apiCalls:d}}function Hc(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 l of c)for(const d of e.pseudoStates)a.push({pseudoState:d,ariaVariation:l,theme:i,direction:r,breakpoint:o})}}return a}const gi=["color-contrast","color-contrast-enhanced","link-in-text-block"],Bc=["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(gi),t=Bc.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 Kc=ee("chrome-api"),Yc="1.3",Kn=3e4;class Jc extends Error{constructor(t,a){super(`CDP ${t} timed out after ${a}ms`),this.method=t,this.timeoutMs=a,this.name="CdpTimeoutError"}}class mi{constructor(t){this.target=t}async attach(){await chrome.debugger.attach(this.target,Yc)}async detach(){try{await chrome.debugger.detach(this.target)}catch(t){Kc.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 Jc(t,Kn)),Kn)});try{return await Promise.race([n,r])}finally{o!==void 0&&clearTimeout(o)}}}function Xc(e){const t=e instanceof Error?e.message:String(e);return/Another debugger is already attached|Cannot attach to/i.test(t)}function bi(e){const t=e instanceof Error?e.message:String(e);return Xc(e)?Rn("DEBUGGER_BUSY","DevTools is open on this tab. Close it to run the audit.",!0,{raw:t}):Rn("STATE_DRIVE_FAILED",t,!1)}function Qc(e){const t=(a,n)=>e(a,n);return chrome.debugger.onDetach.addListener(t),()=>chrome.debugger.onDetach.removeListener(t)}const ye=ee("state-driver"),Zc=60*1e3,Me=new Map,Yt=new Map,ct=new Map,ot=new Map,el='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"]',xt=new Map,tl={default:[],hover:["hover"],focus:["focus"],"focus-visible":["focus","focus-visible"],active:["active"],disabled:[]};async function yi(e){let t=Me.get(e);if(!t){t=new mi({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}Me.set(e,t),ct.set(e,new Map),al(e),ye.info("attached",{tabId:e})}return ol(e),t}function al(e){const t=(a,n,o)=>{var i,c;if(a.tabId!==e)return;const r=ct.get(e);if(r)if(n==="Runtime.executionContextCreated"){const l=o,d=l==null?void 0:l.context;d&&((i=d.auxData)!=null&&i.isDefault)&&((c=d.auxData)!=null&&c.frameId)&&r.set(d.auxData.frameId,d.id)}else if(n==="Runtime.executionContextDestroyed"){const l=o,d=l==null?void 0:l.executionContextId;if(d!==void 0)for(const[u,m]of r.entries())m===d&&r.delete(u)}else n==="Runtime.executionContextsCleared"&&r.clear()};chrome.debugger.onEvent.addListener(t)}async function nl(e){const t=Me.get(e);if(Me.delete(e),ct.delete(e),ot.delete(e),xt.delete(e),t)try{await t.detach()}catch{}}function ol(e){const t=Yt.get(e);t&&clearTimeout(t),Yt.set(e,setTimeout(()=>{pa(e).catch(a=>ye.warn("idle detach failed",a))},Zc))}async function pa(e){const t=Me.get(e);t&&(await t.detach(),Me.delete(e)),ct.delete(e),ot.delete(e),xt.delete(e);const a=Yt.get(e);a&&(clearTimeout(a),Yt.delete(e))}function wi(e){const t=[{id:e.frame.id,url:e.frame.url}];for(const a of e.childFrames??[])t.push(...wi(a));return t}async function il(e,t,a){var r;if(!a||a===0)return;const n=ct.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){ye.debug("frame URL lookup failed",i)}try{const i=await e.send("Page.getFrameTree"),c=wi(i.frameTree);if(o){const u=c.find(m=>m.url===o);if(u){const m=n.get(u.id);if(m!==void 0)return m}}const l=i.frameTree.frame.id,d=c.find(u=>u.id!==l);return d?n.get(d.id):void 0}catch(i){ye.warn("Page.getFrameTree failed",i);return}}async function rl(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 vi(e){const t=ot.get(e);if(!t||t.length===0)return;const a=Me.get(e);if(a){for(const n of t)try{await a.send("CSS.forcePseudoState",{nodeId:n,forcedPseudoClasses:[]})}catch(o){ye.debug("forcePseudoState clear failed (node may be gone)",o)}ot.delete(e)}}async function sl(e,t){try{return(await e.send("DOM.querySelectorAll",{nodeId:t,selector:el})).nodeIds??[]}catch(a){return ye.debug("querySelectorAll for interactive descendants failed",a),[]}}async function Ba(e,t,a,n){await chrome.scripting.executeScript({target:yn(e,t),func:(o,r)=>{const i=document.querySelector(o);i&&(r?i.setAttribute("disabled",""):i.removeAttribute("disabled"))},args:[a,n]})}async function Ai(e,t){await chrome.scripting.executeScript({target:yn(e,t),func:()=>{const a=document.activeElement;a&&typeof a.blur=="function"&&a.blur()}})}async function ki(e,t){await chrome.scripting.executeScript({target:{tabId:e,frameIds:[0]},func:a=>{document.documentElement.setAttribute("dir",a)},args:[t]})}async function cl(e,t,a,n){await chrome.scripting.executeScript({target:yn(e,t),func:(o,r)=>{const i=document.querySelector(o);if(i)for(const[c,l]of Object.entries(r))i.setAttribute(c,l)},args:[a,n]})}function yn(e,t){return t!==void 0&&t!==0?{tabId:e,frameIds:[t]}:{tabId:e}}async function ll(e,t,a,n){const o=await yi(e),r=xt.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):"",l=!i||(r==null?void 0:r.pseudoState)!==t.pseudoState,d=!r||r.theme!==t.theme,u=!r||r.direction!==t.direction,m=!r||r.breakpointId!==t.breakpoint.id,p=!i||(r==null?void 0:r.ariaVariationKey)!==c;if(l&&(await vi(e),a)){t.pseudoState==="disabled"?await Ba(e,n,a,!0):(await Ba(e,n,a,!1),await Ai(e,n));const f=tl[t.pseudoState];if(f.length>0){const g=await il(o,e,n),h=await rl(o,a,g);if(h!==null){const y=await sl(o,h),b=[h,...y];for(const A of b)try{await o.send("CSS.forcePseudoState",{nodeId:A,forcedPseudoClasses:f})}catch(v){ye.debug(`CSS.forcePseudoState failed for nodeId=${A}`,v)}ot.set(e,b),ye.debug(`forced :${t.pseudoState} on ${b.length} node(s)`)}else ye.debug(`could not resolve nodeId for ${a} (frameId=${n})`)}}if(d){const f=[{name:"prefers-reduced-motion",value:"reduce"}];t.theme==="dark"?(f.push({name:"prefers-color-scheme",value:"dark"}),f.push({name:"forced-colors",value:"none"})):t.theme==="light"?(f.push({name:"prefers-color-scheme",value:"light"}),f.push({name:"forced-colors",value:"none"})):t.theme==="forced-colors-active"?f.push({name:"forced-colors",value:"active"}):t.theme==="forced-colors-none"&&f.push({name:"forced-colors",value:"none"}),await o.send("Emulation.setEmulatedMedia",{features:f}),await new Promise(g=>setTimeout(g,50))}u&&await ki(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}),p&&t.ariaVariation&&a&&await cl(e,n,a,t.ariaVariation.attributes),xt.set(e,{scope:a,frameId:n,pseudoState:t.pseudoState,theme:t.theme,direction:t.direction,breakpointId:t.breakpoint.id,ariaVariationKey:c})}async function dl(e,t,a){const n=Me.get(e);if(n){if(await vi(e),xt.delete(e),t)try{await Ba(e,a,t,!1),await Ai(e,a),await ki(e,"ltr")}catch(o){ye.warn("element-level reset partial failure",o)}try{await n.send("Emulation.setEmulatedMedia",{features:[]}),await n.send("Emulation.clearDeviceMetricsOverride")}catch(o){ye.warn("reset partial failure",o)}await pa(e)}}async function Ka(e,t,a,n){try{return await ll(e,t,a,n),z({type:"STATE_CHANGED_EVENT",tabId:e,currentState:t}),{type:"STATE_DRIVE_RESPONSE",success:!0,appliedState:t}}catch(o){return ye.error("state drive failed",o),await nl(e),{type:"STATE_DRIVE_RESPONSE",success:!1,error:bi(o)}}}async function qt(e,t,a){await dl(e,t,a)}async function Jp(e){await pa(e);try{await chrome.debugger.detach({tabId:e})}catch{}}async function ul(e,t={}){try{const a=await yi(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 ye.debug("Page.captureScreenshot failed",a),null}}function Xp(){var a;const e=[];if(e.push(Ie("STATE_DRIVE_REQUEST",n=>Ka(n.tabId,n.state,n.scope,n.frameId))),e.push(Ie("STATE_RESET_REQUEST",n=>qt(n.tabId))),(a=chrome.tabs)!=null&&a.onRemoved){const n=o=>{pa(o).catch(()=>{})};chrome.tabs.onRemoved.addListener(n),e.push(()=>chrome.tabs.onRemoved.removeListener(n))}const t=Qc((n,o)=>{n.tabId!==void 0&&(Me.delete(n.tabId),ct.delete(n.tabId),ot.delete(n.tabId),ye.warn("unexpected detach",{tabId:n.tabId,reason:o}))});return e.push(t),ye.info("handlers registered"),()=>e.forEach(n=>n())}const Ze=ee("cloud-sync"),Yn="cloudSyncEnabled",Ia="cloudSyncEndpoint",xa="licenseToken",Ya="cloudSyncVersionCache";async function wn(){try{const e=await fe();if(!de(e,"cloudSync"))return null;const t=await chrome.storage.local.get([Yn,Ia,xa]),a=t[Yn]===!0,n=typeof t[Ia]=="string"?t[Ia]:"",o=typeof t[xa]=="string"?t[xa]:"";return!a||!n||!o?null:{endpoint:n.replace(/\/$/,""),token:o,enabled:a}}catch{return null}}async function Ii(){try{const t=(await chrome.storage.local.get(Ya))[Ya];return t&&typeof t=="object"?t:{}}catch{return{}}}async function Jt(e){try{await chrome.storage.local.set({[Ya]:e})}catch{}}async function pl(e,t,a){const n=await wn();if(!n)return!1;const o=await Ii(),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 Ze.warn(`baseline ${e} version conflict on push`,{expectedVersion:r}),delete o[e],await Jt(o),!1;if(!c.ok)return Ze.warn("baseline push failed",{status:c.status}),!1;const l=await c.json();return typeof l.version=="number"&&(o[e]=l.version,await Jt(o)),!0}catch(i){return Ze.debug("push network failure (offline?)",i),!1}}async function hl(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 Ii();delete o[e],await Jt(o)}return n.ok}catch(a){return Ze.debug("delete network failure",a),!1}}async function fl(){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 Ze.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 Jt(o),n}catch(t){return Ze.debug("pull network failure",t),[]}}const xi=ee("baseline-store"),Jn="componentIdAliases";async function it(e,t){try{return await t()}catch(a){const n=a instanceof Error?a.message:String(a);throw xi.error(`baseline IDB ${e} failed: ${n}`),new dr({code:"BASELINE_DB_ERROR",message:`Baseline storage is unavailable (${e}: ${n}).`,recoverable:!1,details:n})}}async function ha(e){return((await chrome.storage.local.get(Jn))[Jn]??{})[e]??e}async function gl(e){const t=await ha(e),a=await it("get",()=>oa(t));return a?{violations:a.violations,snapshotMeta:a.snapshotMeta}:null}async function ml(e,t,a,n){const o=await ha(e),r=await it("get-for-set",()=>oa(o)),i=(r==null?void 0:r.seenOnUrls)??[],c=i.includes(a.url)?i:[...i,a.url];await it("set",()=>nn({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})),pl(o,{violations:t,snapshotMeta:a},a.axeVersion).catch(()=>{})}function bl(e,t){if(!e||!t||On(e)===On(t))return;const a=r=>{var i,c,l,d,u;return(((i=r.pseudoStates)==null?void 0:i.length)??0)*Math.max(1,((c=r.ariaVariations)==null?void 0:c.length)??0)*(((l=r.themes)==null?void 0:l.length)??0)*(((d=r.directions)==null?void 0:d.length)??0)*(((u=r.breakpoints)==null?void 0:u.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 vn(e,t,a,n){var d;const o=await ha(e),r=await ra(o),i=await it("compare",()=>oa(o));if(!i){const u=t.filter(p=>r.has(p.matchKey)),m=t.filter(p=>!r.has(p.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:u,acknowledgedCount:u.length}}const c=lr(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),l=bl((d=i.snapshotMeta)==null?void 0:d.matrixConfig,n);return l&&(c.matrixMismatchWarning=l),c}async function yl(e){const t=await ha(e);await it("delete",()=>No(t)),hl(t).catch(()=>{})}async function Qp(){const e=await fl();for(const t of e)await nn({componentId:t.componentId,violations:t.snapshot.violations,snapshotMeta:t.snapshot.snapshotMeta,lastUpdated:t.updatedAt,axeVersion:t.axeVersion});return e.length>0&&z({type:"SCORECARD_UPDATED_EVENT"}),e.length}async function wl(e){let t=await it("list",()=>Lo());return e!=null&&e.url&&(t=t.filter(a=>a.snapshotMeta.url===e.url)),t.map(a=>{const n=(a.focusEvents??[]).filter(d=>d.isFocusReset).length,o=(a.announcements??[]).length,r=a.violations.filter(d=>d.ruleId==="target-size").length,i=a.violations.some(d=>d.ruleId==="color-contrast"&&d.currentState.pseudoState==="hover"),c=a.violations.filter(d=>d.impact==="critical").length,l=a.violations.filter(d=>d.impact==="serious").length;return{componentId:a.componentId,violationCount:a.violations.length,lastUpdated:a.lastUpdated,seenOnUrlsCount:(a.seenOnUrls??[]).length,metrics:{criticalCount:c,seriousCount:l,focusResetCount:n,announcementCount:o,targetSizeFailCount:r,hoverContrastFail:i}}})}function Zp(){const e=[];return e.push(Ie("BASELINE_GET",async t=>({type:"BASELINE_GET_RESPONSE",baseline:await gl(t.componentId)}))),e.push(Ie("BASELINE_SET",async t=>{await ml(t.componentId,t.violations,t.snapshotMeta,{announcements:t.announcements,focusEvents:t.focusEvents}),z({type:"SCORECARD_UPDATED_EVENT"})})),e.push(Ie("BASELINE_COMPARE",async t=>({type:"BASELINE_COMPARE_RESPONSE",delta:await vn(t.componentId,t.currentViolations,{announcements:t.announcements,focusEvents:t.focusEvents},t.currentMatrix)}))),e.push(Ie("BASELINE_DELETE",async t=>{await yl(t.componentId),z({type:"SCORECARD_UPDATED_EVENT"})})),e.push(Ie("BASELINE_LIST",async t=>({type:"BASELINE_LIST_RESPONSE",items:await wl(t.filter)}))),xi.info("handlers registered"),()=>e.forEach(t=>t())}const vl=ee("settings-store"),Xn=1,Qn="__schemaVersion",Ja={stateMatrix:Na,componentIdAliases:{},ignorePatterns:[]};async function Ve(e,t){return(await chrome.storage.local.get(e))[e]??t}async function eh(){const e=await chrome.storage.local.get();if(e[Qn]===Xn)return;const t={[Qn]:Xn};for(const[a,n]of Object.entries(Ja))a in e||(t[a]=n);await chrome.storage.local.set(t),vl.info("defaults ensured")}const Al=["__","inflight:","license:","support:"];function kl(e){return!Al.some(t=>e.startsWith(t))}function th(){const e=[];return e.push(Ie("SETTINGS_GET",async t=>({type:"SETTINGS_RESPONSE",data:(await chrome.storage.local.get(t.key))[t.key]??Ja[t.key]}))),e.push(Ie("SETTINGS_SET",async t=>{await chrome.storage.local.set({[t.key]:t.value})})),e.push(Ie("SETTINGS_GET_ALL",async()=>{const t=await chrome.storage.local.get(),a=Object.fromEntries(Object.entries(t).filter(([n])=>kl(n)));return{type:"SETTINGS_RESPONSE",data:{...Ja,...a}}})),()=>e.forEach(t=>t())}function Ee(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 Il=ee("ai-alt-text");async function xl(e,t,a={}){var m,p;if(!t.enabled||!t.enabledChecks.altText)return{findings:[],totalCostUsd:0,capExceeded:!1,errors:[]};const n=ue(t);if(!n.ok)return{findings:[],totalCostUsd:0,capExceeded:!1,errors:[`AI client unavailable: ${n.reason}`]};const o=n.client,r=Ee(t.costCapUsd),i=[],c=[],l=Math.max(1,t.maxCandidatesPerCheck??10),d=e.slice(0,l),u=d.length;for(let f=0;f<d.length;f++){const g=d[f];if(!r.canCharge())break;try{if((m=a.signal)!=null&&m.aborted){c.push(`canceled after ${f}/${u} candidates`);break}const h=await o.judgeAltText({imageUrl:g.imageUrl,alt:g.alt,surroundingContext:g.surroundingContext,signal:a.signal});r.recordCharge(h.costUsd),(h.verdict==="fail"||h.verdict==="uncertain"&&h.confidence<.6)&&i.push(await Sl(g,h))}catch(h){if(h instanceof Error&&(h.name==="AbortError"||h.name==="ExternalAbortError")){c.push(`canceled after ${f}/${u} candidates`);break}const b=h instanceof Error?h.message:String(h);c.push(`${g.selector}: ${b}`),Il.warn("alt-text judgment failed",h)}(p=a.onProgress)==null||p.call(a,f+1,u)}return{findings:i,totalCostUsd:r.state.spentUsd,capExceeded:r.state.exceeded,errors:c}}async function Sl(e,t){const a=t.verdict==="uncertain"?"ai-alt-uncertain":"ai-alt-misleading",n={selector:e.selector,outerHTML:e.outerHTML.slice(0,500),failureSummary:`AI assessment: ${t.reasoning}`,tagName:"IMG",role:null,accessibleName:e.alt,textSnippet:null,attrId:null,attrTestid:null},o=await tn({ruleId:a,componentId:e.componentId,currentState:e.currentState,target:n}),r=t.verdict==="uncertain";return{ruleId:a,wcagCriterion:"1.1.1",wcagLevel:"A",impact:r?"minor":"serious",description:r?"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:n,componentId:e.componentId,currentState:e.currentState,axeVersion:e.axeVersion,detectedAt:new Date().toISOString(),matchKey:o,ai:{reasoning:t.reasoning,confidence:t.confidence,model:t.model,costUsd:t.costUsd},...r?{needsReview:!0}:{}}}const mt=ee("interactive-audit"),Cl="1.3",Tl={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 An{constructor(t){Mt(this,"session");Mt(this,"attached",!1);Mt(this,"steps",[]);this.tabId=t,this.session=new mi({tabId:t})}async attach(){if(!this.attached)try{await chrome.debugger.attach({tabId:this.tabId},Cl),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 mt.error("attach failed",t),bi(t)}}async dispose(){if(this.attached){try{await chrome.debugger.detach({tabId:this.tabId})}catch(t){mt.debug("detach soft-failure",t)}this.attached=!1}}async pressKey(t,a){const n=Tl[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 Zn(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 Zn(50)}async countFocusables(){var a;const t=`(() => {
|
|
733
733
|
const sel = [
|
|
734
734
|
'a[href]', 'button', 'input', 'select', 'textarea',
|
|
735
735
|
'[tabindex]', 'audio[controls]', 'video[controls]', '[contenteditable]'
|
|
@@ -748,7 +748,7 @@ Respond with strict JSON (no markdown fences):
|
|
|
748
748
|
return true;
|
|
749
749
|
};
|
|
750
750
|
return all.filter(visible).length;
|
|
751
|
-
})()`;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:
|
|
751
|
+
})()`;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:El,returnByValue:!0});try{const n=(a=t.result)==null?void 0:a.value;return typeof n=="string"?JSON.parse(n):n}catch(n){return mt.error("getFocusedElement: probe returned non-JSON",n),$l}}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 mt.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 mt.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 Zn(e){return new Promise(t=>setTimeout(t,e))}const $l={selector:"body",tag:"body",role:"",name:"",outerHtml:"",rect:{x:0,y:0,width:0,height:0},isBody:!0},El=`(() => {
|
|
752
752
|
const el = document.activeElement;
|
|
753
753
|
if (!el || el === document.body) {
|
|
754
754
|
return JSON.stringify({
|
|
@@ -819,7 +819,7 @@ Respond with strict JSON (no markdown fences):
|
|
|
819
819
|
},
|
|
820
820
|
isBody: false,
|
|
821
821
|
});
|
|
822
|
-
})()`,Ml=[/no parseable JSON/i,/invalid JSON/i];function eo(e){if(e.verdict!=="uncertain"||e.confidence!==0)return!1;const t=e.reasoning??"";return Ml.some(a=>a.test(t))}async function Ke(e){const t=await e();if(!eo(t))return t;try{const a=await e();if(!eo(a))return a}catch{}return t}async function Dl(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),i=new OffscreenCanvas(o.width,o.height),r=i.getContext("2d");if(!r)return e;r.drawImage(o,0,0);const c=Math.max(...t.map(g=>g.rect.x+g.rect.width),0),l=c>0&&o.width/c>1.5?o.width/Math.max(1280,c):1;for(const g of t){const h=(g.rect.x+g.rect.width/2)*l,y=(g.rect.y+g.rect.height/2)*l,b=16*l;r.fillStyle="rgba(220, 38, 38, 0.92)",r.strokeStyle="rgba(255, 255, 255, 0.95)",r.lineWidth=2*l,r.beginPath(),r.arc(h,y,b,0,2*Math.PI),r.fill(),r.stroke(),r.fillStyle="white",r.font=`bold ${Math.round(18*l)}px sans-serif`,r.textAlign="center",r.textBaseline="middle",r.fillText(String(g.ordinal),h,y)}const u=await(await i.convertToBlob({type:"image/jpeg",quality:.85})).arrayBuffer(),m=new Uint8Array(u);let p="";const f=8192;for(let g=0;g<m.byteLength;g+=f){const h=m.subarray(g,Math.min(g+f,m.byteLength));p+=String.fromCharCode(...h)}return`data:image/jpeg;base64,${btoa(p)}`}catch{return e}}async function Xt(e,t={}){var r;const a=Date.now(),n=5e3,o=200,i=e;for(;Date.now()-a<n;){const l=(r=(await i.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:r.value;if(l&&l.ready&&(l.focusables??0)>0)break;await new Promise(d=>setTimeout(d,o))}t.extraDelayMs&&t.extraDelayMs>0&&await new Promise(c=>setTimeout(c,t.extraDelayMs))}function kn(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),i=Math.round(e.rect.height);return`${e.selector}|${e.tag}|${t}|${a},${n},${o},${i}`}async function Nl(e,t){const a=JSON.stringify({criterionId:e,sequence:t.map(r=>({o:r.ordinal,s:r.selector,r:r.role,x:Math.round(r.rect.x),y:Math.round(r.rect.y),w:Math.round(r.rect.width),h:Math.round(r.rect.height)}))}),n=new TextEncoder().encode(a),o=await crypto.subtle.digest("SHA-256",n);return Array.from(new Uint8Array(o)).map(r=>r.toString(16).padStart(2,"0")).join("")}const Sa=ee("focus-order-audit"),Ca="2.4.3",to=50;async function Ll(e){var r,c,l;const t=await chrome.storage.local.get("aiConfig"),a=we(t.aiConfig),n=pe(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 i=new An(e.tabId);try{await i.attach(),await Xt(i),await Pl(i),await i.recordStep("initial",{screenshot:!0});const d=await i.countFocusables(),u=d>0?Math.min(to,d):to,m=new Set;for(let s=0;s<u;s++){if((r=e.signal)!=null&&r.aborted)return{ok:!1,error:"Audit cancelled."};await i.pressKey("Tab");const k=await i.recordStep(`Tab #${s+1}`,{screenshot:!1});if(k.focused.isBody)break;const x=kn(k.focused);if(m.has(x))break;m.add(x),(c=e.onStep)==null||c.call(e,{ordinal:k.ordinal,selector:k.focused.selector,role:k.focused.role,name:k.focused.name})}const p=i.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})),f=(l=i.steps[0])==null?void 0:l.screenshot,g=f?await Dl(f,p):void 0,h=await Nl(Ca,p);let y,b=null;try{b=await Ne(e.componentId,Ca),b&&!Wt(b.reasoning)?y={verdict:b.verdict,reasoning:b.reasoning,confidence:b.confidence}:b&&Wt(b.reasoning)&&Sa.info("Skipping anchor — previous 2.4.3 verdict was cascade-escalated (system-imposed); letting primary judge fresh")}catch{}if(b&&b.inputHash===h&&!Wt(b.reasoning)){Sa.info(`2.4.3 inputs unchanged (hash match: ${h.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:h};return await ae(s),{ok:!0,result:s}}const A=await Ke(()=>o.judgeFocusOrder({pageUrl:e.pageUrl,pageScreenshot:g,tabSequence:p,previousVerdict:y,signal:e.signal})),v={componentId:e.componentId,criterionId:Ca,verdict:A.verdict==="pass"?"pass":A.verdict==="fail"?"fail":"uncertain",reasoning:A.reasoning,confidence:A.confidence,steps:i.steps,pageUrl:e.pageUrl,finishedAt:new Date().toISOString(),costUsd:A.costUsd,model:A.model,inputHash:h};return await ae(v),{ok:!0,result:v}}catch(d){return Sa.error("focus-order audit failed",d),{ok:!1,error:d instanceof Error?d.message:String(d)}}finally{await i.dispose()}}async function Pl(e){await e.session.send("Runtime.evaluate",{expression:"(() => { if (document.activeElement && document.activeElement !== document.body) document.activeElement.blur(); window.scrollTo(0, 0); })()"})}async function fa(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(r=>r.toString(16).padStart(2,"0")).join("")}async function ga(e,t,a){const n=await Ne(e,t);return n?n.inputHash!==a?{hit:!1,previous:n}:n.verdict==="uncertain"?{hit:!1,previous:n}:Wt(n.reasoning)?{hit:!1,previous:n}:{hit:!0,previous:n}:{hit:!1,previous:null}}function ma(e,t){return{...e,finishedAt:new Date().toISOString(),costUsd:0,model:`${e.model} (cached, hash-match)`,inputHash:t}}const Ta=ee("keyboard-trap-audit"),bt="2.1.2",ao=50;async function Fl(e){const t=await chrome.storage.local.get("aiConfig"),a=we(t.aiConfig),n=pe(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 i=new An(e.tabId);try{await i.attach(),await Xt(i),await no(i),await i.recordStep("initial",{screenshot:!0});const r=await i.countFocusables(),c=r>0?Math.min(ao,r):ao;let l=await oo(i,c,e.signal);if(l.forwardSelectors.length===0&&l.reverseSelectors.length>0&&(Ta.info("2.1.2 detected degenerate 0/N walk — retrying after extra hydration wait"),await Xt(i,{extraDelayMs:1500}),await no(i),l=await oo(i,c,e.signal)),l.forwardSelectors.length===0){const s=_l(r),k={componentId:e.componentId,criterionId:bt,verdict:s,reasoning:s==="pass"?`The page has ${r} focusable element${r===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: ${l.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:i.steps,pageUrl:e.pageUrl,finishedAt:new Date().toISOString(),costUsd:0,model:s==="pass"?"heuristic-reconciled":"heuristic-degenerate-walk"};return await ae(k),{ok:!0,result:k}}const{forwardSelectors:d,reverseSelectors:u,stuckRuns:m}=l,p=d.slice(0,-1).reverse(),f=[];for(let s=0;s<Math.min(p.length,u.length);s++){const k=p[s],x=u[s];k!==x&&f.push({index:s,expected:k,actual:x})}const g=Ul(p,u,f,m);if(g.detected){const s={componentId:e.componentId,criterionId:bt,verdict:"pass",reasoning:g.reasoning,confidence:.95,steps:i.steps,pageUrl:e.pageUrl,finishedAt:new Date().toISOString(),costUsd:0,model:"heuristic-only"};return await ae(s),{ok:!0,result:s}}const h=await fa(bt,{forwardSequence:d,reverseSequence:u,stuckRuns:m,reverseMismatches:f.slice(0,10)}),y=await ga(e.componentId,bt,h);if(y.hit){Ta.info(`2.1.2 inputs unchanged (hash match); reusing verdict=${y.previous.verdict}`);const s=ma(y.previous,h);return await ae(s),{ok:!0,result:s}}const b=y.previous?{verdict:y.previous.verdict,reasoning:y.previous.reasoning,confidence:y.previous.confidence}:void 0,A=await Ke(()=>o.judgeKeyboardTrap({pageUrl:e.pageUrl,forwardSequence:d,reverseSequence:u,stuckRuns:m,reverseMismatches:f.slice(0,10),previousVerdict:b,signal:e.signal})),v={componentId:e.componentId,criterionId:bt,verdict:A.verdict==="pass"?"pass":A.verdict==="fail"?"fail":"uncertain",reasoning:A.reasoning,confidence:A.confidence,steps:i.steps,pageUrl:e.pageUrl,finishedAt:new Date().toISOString(),costUsd:A.costUsd,model:A.model,inputHash:h};return await ae(v),{ok:!0,result:v}}catch(r){return Ta.error("keyboard-trap audit failed",r),{ok:!1,error:r instanceof Error?r.message:String(r)}}finally{await i.dispose()}}async function no(e){await e.session.send("Runtime.evaluate",{expression:"(() => { if (document.activeElement && document.activeElement !== document.body) document.activeElement.blur(); window.scrollTo(0, 0); })()"})}async function oo(e,t,a){const o=[],i=[];for(let m=0;m<t&&!(a!=null&&a.aborted);m++){await e.pressKey("Tab");const p=await e.recordStep(`Tab #${m+1}`,{screenshot:!1});if(p.focused.isBody){if(o.length===0)continue;break}o.push(p.focused.selector);const f=kn(p.focused);if(i.length>2&&f===i[0])break;i.push(f)}const r=[];let c=0;for(let m=1;m<=i.length;m++)if(m===i.length||i[m]!==i[m-1]){const p=m-c;p>=3&&r.push(`${o[c]} (×${p} consecutive)`),c=m}const l=[],u=Math.min(50,t);for(let m=0;m<u&&!(a!=null&&a.aborted);m++){await e.pressKey("Tab",{shift:!0});const p=await e.recordStep(`Shift+Tab #${m+1}`,{screenshot:!1});if(p.focused.isBody||(l.push(p.focused.selector),l.length>=o.length))break}return{forwardSelectors:o,reverseSelectors:l,stuckRuns:r}}function _l(e){return e>0?"pass":"uncertain"}function Ul(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 i=b=>{let A=0;for(let v=0;v<e.length;v++){const s=t[v+b];s!==void 0&&s===e[v]&&A++}return A},r=i(0),c=i(1),l=i(-1),d=Math.floor(e.length*.7),u=Math.max(c,l);if(u<d||u<=r)return{detected:!1};const m=new Set(e),p=new Set(t),f=[...m].filter(b=>p.has(b)),g=new Set([...m,...p]);return g.size-f.length>2?{detected:!1}:{detected:!0,reasoning:`Comparator artifact detected: every reverse-walk position mismatched by the same ${c>=l?"+1":"-1"} offset, but the SET of focused elements matches the forward walk (${f.length}/${g.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 ro=ee("focus-visible-audit"),$a="2.4.7",io=30,Wl=10;async function ql(e){var r;const t=await chrome.storage.local.get("aiConfig"),a=we(t.aiConfig),n=pe(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 i=new An(e.tabId);try{await i.attach(),await Xt(i),await Vl(i);const c=[],l=await i.countFocusables(),d=l>0?Math.min(io,l):io,u=new Set;for(let h=0;h<d&&c.length<Wl;h++){if((r=e.signal)!=null&&r.aborted)return{ok:!1,error:"Audit cancelled."};await i.pressKey("Tab");const y=await i.recordStep(`Tab #${h+1}`,{screenshot:!0});if(y.focused.isBody)break;const b=kn(y.focused);if(u.has(b))break;u.add(b);const A=await jl(i);y.screenshot&&c.push({ordinal:c.length+1,selector:y.focused.selector,role:y.focused.role,name:y.focused.name,rect:y.focused.rect,screenshot:y.screenshot,focusStyle:A})}if(c.length===0)return{ok:!1,error:"No focusable elements found on the page; cannot evaluate 2.4.7."};const m=await fa($a,{samples:c.map(h=>({ordinal:h.ordinal,selector:h.selector,role:h.role,focusStyle:h.focusStyle,rect:{x:Math.round(h.rect.x),y:Math.round(h.rect.y),w:Math.round(h.rect.width),h:Math.round(h.rect.height)}}))}),p=await ga(e.componentId,$a,m);if(p.hit){ro.info(`2.4.7 inputs unchanged (hash match); reusing verdict=${p.previous.verdict}`);const h=ma(p.previous,m);return await ae(h),{ok:!0,result:h}}const f=await Ke(()=>o.judgeFocusVisible({pageUrl:e.pageUrl,samples:c,signal:e.signal})),g={componentId:e.componentId,criterionId:$a,verdict:f.verdict==="pass"?"pass":f.verdict==="fail"?"fail":"uncertain",reasoning:f.reasoning,confidence:f.confidence,steps:i.steps,pageUrl:e.pageUrl,finishedAt:new Date().toISOString(),costUsd:f.costUsd,model:f.model,inputHash:m};return await ae(g),{ok:!0,result:g}}catch(c){return ro.error("focus-visible audit failed",c),{ok:!1,error:c instanceof Error?c.message:String(c)}}finally{await i.dispose()}}async function Vl(e){await e.session.send("Runtime.evaluate",{expression:"(() => { if (document.activeElement && document.activeElement !== document.body) document.activeElement.blur(); window.scrollTo(0, 0); })()"})}async function jl(e){const t=`(() => {
|
|
822
|
+
})()`,Rl=[/no parseable JSON/i,/invalid JSON/i];function eo(e){if(e.verdict!=="uncertain"||e.confidence!==0)return!1;const t=e.reasoning??"";return Rl.some(a=>a.test(t))}async function Ke(e){const t=await e();if(!eo(t))return t;try{const a=await e();if(!eo(a))return a}catch{}return t}async function Ol(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(g=>g.rect.x+g.rect.width),0),l=c>0&&o.width/c>1.5?o.width/Math.max(1280,c):1;for(const g of t){const h=(g.rect.x+g.rect.width/2)*l,y=(g.rect.y+g.rect.height/2)*l,b=16*l;i.fillStyle="rgba(220, 38, 38, 0.92)",i.strokeStyle="rgba(255, 255, 255, 0.95)",i.lineWidth=2*l,i.beginPath(),i.arc(h,y,b,0,2*Math.PI),i.fill(),i.stroke(),i.fillStyle="white",i.font=`bold ${Math.round(18*l)}px sans-serif`,i.textAlign="center",i.textBaseline="middle",i.fillText(String(g.ordinal),h,y)}const u=await(await r.convertToBlob({type:"image/jpeg",quality:.85})).arrayBuffer(),m=new Uint8Array(u);let p="";const f=8192;for(let g=0;g<m.byteLength;g+=f){const h=m.subarray(g,Math.min(g+f,m.byteLength));p+=String.fromCharCode(...h)}return`data:image/jpeg;base64,${btoa(p)}`}catch{return e}}async function Xt(e,t={}){var i;const a=Date.now(),n=5e3,o=200,r=e;for(;Date.now()-a<n;){const l=(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(l&&l.ready&&(l.focusables??0)>0)break;await new Promise(d=>setTimeout(d,o))}t.extraDelayMs&&t.extraDelayMs>0&&await new Promise(c=>setTimeout(c,t.extraDelayMs))}function kn(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 Ml(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 Sa=ee("focus-order-audit"),Ca="2.4.3",to=50;async function Dl(e){var i,c,l;const t=await chrome.storage.local.get("aiConfig"),a=we(t.aiConfig),n=ue(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 An(e.tabId);try{await r.attach(),await Xt(r),await Nl(r),await r.recordStep("initial",{screenshot:!0});const d=await r.countFocusables(),u=d>0?Math.min(to,d):to,m=new Set;for(let s=0;s<u;s++){if((i=e.signal)!=null&&i.aborted)return{ok:!1,error:"Audit cancelled."};await r.pressKey("Tab");const k=await r.recordStep(`Tab #${s+1}`,{screenshot:!1});if(k.focused.isBody)break;const x=kn(k.focused);if(m.has(x))break;m.add(x),(c=e.onStep)==null||c.call(e,{ordinal:k.ordinal,selector:k.focused.selector,role:k.focused.role,name:k.focused.name})}const p=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})),f=(l=r.steps[0])==null?void 0:l.screenshot,g=f?await Ol(f,p):void 0,h=await Ml(Ca,p);let y,b=null;try{b=await Ne(e.componentId,Ca),b&&!Wt(b.reasoning)?y={verdict:b.verdict,reasoning:b.reasoning,confidence:b.confidence}:b&&Wt(b.reasoning)&&Sa.info("Skipping anchor — previous 2.4.3 verdict was cascade-escalated (system-imposed); letting primary judge fresh")}catch{}if(b&&b.inputHash===h&&!Wt(b.reasoning)){Sa.info(`2.4.3 inputs unchanged (hash match: ${h.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:h};return await ae(s),{ok:!0,result:s}}const A=await Ke(()=>o.judgeFocusOrder({pageUrl:e.pageUrl,pageScreenshot:g,tabSequence:p,previousVerdict:y,signal:e.signal})),v={componentId:e.componentId,criterionId:Ca,verdict:A.verdict==="pass"?"pass":A.verdict==="fail"?"fail":"uncertain",reasoning:A.reasoning,confidence:A.confidence,steps:r.steps,pageUrl:e.pageUrl,finishedAt:new Date().toISOString(),costUsd:A.costUsd,model:A.model,inputHash:h};return await ae(v),{ok:!0,result:v}}catch(d){return Sa.error("focus-order audit failed",d),{ok:!1,error:d instanceof Error?d.message:String(d)}}finally{await r.dispose()}}async function Nl(e){await e.session.send("Runtime.evaluate",{expression:"(() => { if (document.activeElement && document.activeElement !== document.body) document.activeElement.blur(); window.scrollTo(0, 0); })()"})}async function fa(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 ga(e,t,a){const n=await Ne(e,t);return n?n.inputHash!==a?{hit:!1,previous:n}:n.verdict==="uncertain"?{hit:!1,previous:n}:Wt(n.reasoning)?{hit:!1,previous:n}:{hit:!0,previous:n}:{hit:!1,previous:null}}function ma(e,t){return{...e,finishedAt:new Date().toISOString(),costUsd:0,model:`${e.model} (cached, hash-match)`,inputHash:t}}const Ta=ee("keyboard-trap-audit"),bt="2.1.2",ao=50;async function Ll(e){const t=await chrome.storage.local.get("aiConfig"),a=we(t.aiConfig),n=ue(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 An(e.tabId);try{await r.attach(),await Xt(r),await no(r),await r.recordStep("initial",{screenshot:!0});const i=await r.countFocusables(),c=i>0?Math.min(ao,i):ao;let l=await oo(r,c,e.signal);if(l.forwardSelectors.length===0&&l.reverseSelectors.length>0&&(Ta.info("2.1.2 detected degenerate 0/N walk — retrying after extra hydration wait"),await Xt(r,{extraDelayMs:1500}),await no(r),l=await oo(r,c,e.signal)),l.forwardSelectors.length===0){const s=Pl(i),k={componentId:e.componentId,criterionId:bt,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: ${l.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 ae(k),{ok:!0,result:k}}const{forwardSelectors:d,reverseSelectors:u,stuckRuns:m}=l,p=d.slice(0,-1).reverse(),f=[];for(let s=0;s<Math.min(p.length,u.length);s++){const k=p[s],x=u[s];k!==x&&f.push({index:s,expected:k,actual:x})}const g=Fl(p,u,f,m);if(g.detected){const s={componentId:e.componentId,criterionId:bt,verdict:"pass",reasoning:g.reasoning,confidence:.95,steps:r.steps,pageUrl:e.pageUrl,finishedAt:new Date().toISOString(),costUsd:0,model:"heuristic-only"};return await ae(s),{ok:!0,result:s}}const h=await fa(bt,{forwardSequence:d,reverseSequence:u,stuckRuns:m,reverseMismatches:f.slice(0,10)}),y=await ga(e.componentId,bt,h);if(y.hit){Ta.info(`2.1.2 inputs unchanged (hash match); reusing verdict=${y.previous.verdict}`);const s=ma(y.previous,h);return await ae(s),{ok:!0,result:s}}const b=y.previous?{verdict:y.previous.verdict,reasoning:y.previous.reasoning,confidence:y.previous.confidence}:void 0,A=await Ke(()=>o.judgeKeyboardTrap({pageUrl:e.pageUrl,forwardSequence:d,reverseSequence:u,stuckRuns:m,reverseMismatches:f.slice(0,10),previousVerdict:b,signal:e.signal})),v={componentId:e.componentId,criterionId:bt,verdict:A.verdict==="pass"?"pass":A.verdict==="fail"?"fail":"uncertain",reasoning:A.reasoning,confidence:A.confidence,steps:r.steps,pageUrl:e.pageUrl,finishedAt:new Date().toISOString(),costUsd:A.costUsd,model:A.model,inputHash:h};return await ae(v),{ok:!0,result:v}}catch(i){return Ta.error("keyboard-trap audit failed",i),{ok:!1,error:i instanceof Error?i.message:String(i)}}finally{await r.dispose()}}async function no(e){await e.session.send("Runtime.evaluate",{expression:"(() => { if (document.activeElement && document.activeElement !== document.body) document.activeElement.blur(); window.scrollTo(0, 0); })()"})}async function oo(e,t,a){const o=[],r=[];for(let m=0;m<t&&!(a!=null&&a.aborted);m++){await e.pressKey("Tab");const p=await e.recordStep(`Tab #${m+1}`,{screenshot:!1});if(p.focused.isBody){if(o.length===0)continue;break}o.push(p.focused.selector);const f=kn(p.focused);if(r.length>2&&f===r[0])break;r.push(f)}const i=[];let c=0;for(let m=1;m<=r.length;m++)if(m===r.length||r[m]!==r[m-1]){const p=m-c;p>=3&&i.push(`${o[c]} (×${p} consecutive)`),c=m}const l=[],u=Math.min(50,t);for(let m=0;m<u&&!(a!=null&&a.aborted);m++){await e.pressKey("Tab",{shift:!0});const p=await e.recordStep(`Shift+Tab #${m+1}`,{screenshot:!1});if(p.focused.isBody||(l.push(p.focused.selector),l.length>=o.length))break}return{forwardSelectors:o,reverseSelectors:l,stuckRuns:i}}function Pl(e){return e>0?"pass":"uncertain"}function Fl(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 A=0;for(let v=0;v<e.length;v++){const s=t[v+b];s!==void 0&&s===e[v]&&A++}return A},i=r(0),c=r(1),l=r(-1),d=Math.floor(e.length*.7),u=Math.max(c,l);if(u<d||u<=i)return{detected:!1};const m=new Set(e),p=new Set(t),f=[...m].filter(b=>p.has(b)),g=new Set([...m,...p]);return g.size-f.length>2?{detected:!1}:{detected:!0,reasoning:`Comparator artifact detected: every reverse-walk position mismatched by the same ${c>=l?"+1":"-1"} offset, but the SET of focused elements matches the forward walk (${f.length}/${g.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 io=ee("focus-visible-audit"),$a="2.4.7",ro=30,_l=10;async function Ul(e){var i;const t=await chrome.storage.local.get("aiConfig"),a=we(t.aiConfig),n=ue(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 An(e.tabId);try{await r.attach(),await Xt(r),await Wl(r);const c=[],l=await r.countFocusables(),d=l>0?Math.min(ro,l):ro,u=new Set;for(let h=0;h<d&&c.length<_l;h++){if((i=e.signal)!=null&&i.aborted)return{ok:!1,error:"Audit cancelled."};await r.pressKey("Tab");const y=await r.recordStep(`Tab #${h+1}`,{screenshot:!0});if(y.focused.isBody)break;const b=kn(y.focused);if(u.has(b))break;u.add(b);const A=await ql(r);y.screenshot&&c.push({ordinal:c.length+1,selector:y.focused.selector,role:y.focused.role,name:y.focused.name,rect:y.focused.rect,screenshot:y.screenshot,focusStyle:A})}if(c.length===0)return{ok:!1,error:"No focusable elements found on the page; cannot evaluate 2.4.7."};const m=await fa($a,{samples:c.map(h=>({ordinal:h.ordinal,selector:h.selector,role:h.role,focusStyle:h.focusStyle,rect:{x:Math.round(h.rect.x),y:Math.round(h.rect.y),w:Math.round(h.rect.width),h:Math.round(h.rect.height)}}))}),p=await ga(e.componentId,$a,m);if(p.hit){io.info(`2.4.7 inputs unchanged (hash match); reusing verdict=${p.previous.verdict}`);const h=ma(p.previous,m);return await ae(h),{ok:!0,result:h}}const f=await Ke(()=>o.judgeFocusVisible({pageUrl:e.pageUrl,samples:c,signal:e.signal})),g={componentId:e.componentId,criterionId:$a,verdict:f.verdict==="pass"?"pass":f.verdict==="fail"?"fail":"uncertain",reasoning:f.reasoning,confidence:f.confidence,steps:r.steps,pageUrl:e.pageUrl,finishedAt:new Date().toISOString(),costUsd:f.costUsd,model:f.model,inputHash:m};return await ae(g),{ok:!0,result:g}}catch(c){return io.error("focus-visible audit failed",c),{ok:!1,error:c instanceof Error?c.message:String(c)}}finally{await r.dispose()}}async function Wl(e){await e.session.send("Runtime.evaluate",{expression:"(() => { if (document.activeElement && document.activeElement !== document.body) document.activeElement.blur(); window.scrollTo(0, 0); })()"})}async function ql(e){const t=`(() => {
|
|
823
823
|
const el = document.activeElement;
|
|
824
824
|
if (!el || el === document.body) return JSON.stringify({
|
|
825
825
|
outlineStyle: '', outlineWidth: '', outlineColor: '', outlineOffset: '',
|
|
@@ -835,25 +835,25 @@ Respond with strict JSON (no markdown fences):
|
|
|
835
835
|
border: cs.border,
|
|
836
836
|
backgroundColor: cs.backgroundColor,
|
|
837
837
|
});
|
|
838
|
-
})()`;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 so=ee("reading-order-audit"),Ft="1.3.2";async function Gl(e){var u,m,p;const t=await chrome.storage.local.get("aiConfig"),a=we(t.aiConfig),n=pe(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 i=((u=e.results[0])==null?void 0:u.readingOrderIssues)??[],r=(m=e.results[0])==null?void 0:m.screenshotDataUrl;if(i.length===0){const f={componentId:e.componentId,criterionId:Ft,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 ae(f),{ok:!0,result:f}}if((p=e.signal)!=null&&p.aborted)return{ok:!1,error:"Audit cancelled."};const c=await fa(Ft,{flaggedIssues:i.map(f=>({selector:f.selector,textSnippet:f.textSnippet,domIndex:f.domIndex,visualIndex:f.visualIndex}))}),l=await ga(e.componentId,Ft,c);if(l.hit){so.info(`1.3.2 inputs unchanged (hash match); reusing verdict=${l.previous.verdict}`);const f=ma(l.previous,c);return await ae(f),{ok:!0,result:f}}const d=l.previous?{verdict:l.previous.verdict,reasoning:l.previous.reasoning,confidence:l.previous.confidence}:void 0;try{const f=await Ke(()=>o.judgeReadingOrder({pageUrl:e.pageUrl,pageScreenshot:r,flaggedIssues:i.map(h=>({selector:h.selector,textSnippet:h.textSnippet,domIndex:h.domIndex,visualIndex:h.visualIndex,rect:h.boundingRect})),previousVerdict:d,signal:e.signal})),g={componentId:e.componentId,criterionId:Ft,verdict:f.verdict==="pass"?"pass":f.verdict==="fail"?"fail":"uncertain",reasoning:f.reasoning,confidence:f.confidence,steps:[],pageUrl:e.pageUrl,finishedAt:new Date().toISOString(),costUsd:f.costUsd,model:f.model,inputHash:c};return await ae(g),{ok:!0,result:g}}catch(f){return so.error("reading-order audit failed",f),{ok:!1,error:f instanceof Error?f.message:String(f)}}}const co=ee("non-text-contrast-audit"),_t="1.4.11";async function zl(e){var l,d,u,m;const t=await chrome.storage.local.get("aiConfig"),a=we(t.aiConfig),n=pe(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 i=(l=e.results[0])==null?void 0:l.screenshotDataUrl;if(!i)return{ok:!1,error:"No page screenshot available — re-run the audit so a screenshot is captured."};if((d=e.signal)!=null&&d.aborted)return{ok:!1,error:"Audit cancelled."};let r=null;if(e.tabId!==void 0)try{const p=await chrome.scripting.executeScript({target:{tabId:e.tabId},func:Hl});r=((u=p==null?void 0:p[0])==null?void 0:u.result)??null}catch(p){co.warn("component contrast measurement failed; falling back to AI",p)}if(r&&r.measured.length>=1){const p=r.measured.filter(h=>h.ratio<3&&h.confident),f=r.measured.filter(h=>h.ratio>=3),g=r.measured.filter(h=>!h.confident);if(p.length>0){const h={componentId:e.componentId,criterionId:_t,verdict:"fail",reasoning:`Programmatic measurement: ${p.length} of ${r.measured.length} measured components fail WCAG 1.4.11 (< 3:1 contrast against adjacent background). `+p.slice(0,6).map(y=>`${y.selector} — ${y.ratio.toFixed(2)}:1 (${y.borderColor} on ${y.backgroundColor})`).join("; ")+(f.length>0?` · ${f.length} other components pass.`:""),confidence:.98,steps:[],pageUrl:e.pageUrl,finishedAt:new Date().toISOString(),costUsd:0,model:"programmatic-contrast-measurement"};return await ae(h),{ok:!0,result:h}}if(g.length===0&&f.length===r.measured.length){const h={componentId:e.componentId,criterionId:_t,verdict:"pass",reasoning:`Programmatic measurement: ${f.length===1?"the":"all"} ${f.length} measured component${f.length===1?"":"s"} pass${f.length===1?"es":""} WCAG 1.4.11 (≥ 3:1 contrast against adjacent background). Lowest measured: ${(m=f.map(y=>y.ratio).sort((y,b)=>y-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 ae(h),{ok:!0,result:h}}}let c;try{const p=await Ne(e.componentId,_t);p&&(c={verdict:p.verdict,reasoning:p.reasoning,confidence:p.confidence})}catch{}try{const p=await Ke(()=>o.judgeNonTextContrast({pageUrl:e.pageUrl,pageScreenshot:i,previousVerdict:c,signal:e.signal})),f={componentId:e.componentId,criterionId:_t,verdict:p.verdict==="pass"?"pass":p.verdict==="fail"?"fail":"uncertain",reasoning:p.reasoning,confidence:p.confidence,steps:[],pageUrl:e.pageUrl,finishedAt:new Date().toISOString(),costUsd:p.costUsd,model:p.model};return await ae(f),{ok:!0,result:f}}catch(p){return co.error("non-text-contrast audit failed",p),{ok:!1,error:p instanceof Error?p.message:String(p)}}}function Hl(){function e(g){const h=g.match(/rgba?\(\s*([0-9.]+)\s*,?\s*([0-9.]+)\s*,?\s*([0-9.]+)(?:\s*[,/]\s*([0-9.]+))?\s*\)/i);if(!h)return null;const y=Math.round(parseFloat(h[1])),b=Math.round(parseFloat(h[2])),A=Math.round(parseFloat(h[3])),v=h[4]!==void 0?parseFloat(h[4]):1;return{r:y,g:b,b:A,a:v}}function t(g){const h=y=>{const b=y/255;return b<=.03928?b/12.92:Math.pow((b+.055)/1.055,2.4)};return .2126*h(g.r)+.7152*h(g.g)+.0722*h(g.b)}function a(g,h){const y=t(g),b=t(h),A=Math.max(y,b),v=Math.min(y,b);return(A+.05)/(v+.05)}function n(g,h){const y=Math.max(0,Math.min(1,g.a));return{r:Math.round(g.r*y+h.r*(1-y)),g:Math.round(g.g*y+h.g*(1-y)),b:Math.round(g.b*y+h.b*(1-y))}}function o(g){let h=g.parentElement;for(;h&&h!==document.documentElement;){const y=getComputedStyle(h);if(y.backgroundImage&&y.backgroundImage!=="none")return{color:y.backgroundColor,hasImage:!0};const A=e(y.backgroundColor);if(A&&A.a>.5)return{color:y.backgroundColor,hasImage:!1};h=h.parentElement}return{color:"rgb(255, 255, 255)",hasImage:!1}}function i(g){if(g.id)return`#${g.id}`;const h=g.tagName.toLowerCase(),y=g.className&&typeof g.className=="string"?g.className.split(/\s+/).filter(Boolean).slice(0,2).join("."):"";return y?`${h}.${y}`:h}function r(g,h){const y=getComputedStyle(g),b=e(y.backgroundColor);return b?b.a>=.999?b:b.a<=.001?h:n(b,h):h}function c(g,h){if((g.textContent??"").trim().length===0)return!1;const y=document.createTreeWalker(g,NodeFilter.SHOW_TEXT);let b;for(;b=y.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 N=parseFloat(s.width),M=parseFloat(s.height);if(N>0&&N<=1||M>0&&M<=1||s.clip==="rect(0px, 0px, 0px, 0px)"||s.clipPath==="inset(50%)")continue}const k=e(s.color);if(!k)continue;const x=k.a<1?n(k,h):k,w=a(x,h),R=parseFloat(s.fontSize)||16,T=parseInt(s.fontWeight,10)||400,_=R>=24||R>=18.5&&T>=700?3:4.5;if(w>=_)return!0}return!1}function l(g){const h=g.tagName.toLowerCase();if(h==="textarea"||h==="select")return!0;if(h==="input"){const y=(g.getAttribute("type")??"text").toLowerCase();return y!=="hidden"&&y!=="checkbox"&&y!=="radio"&&y!=="submit"&&y!=="button"&&y!=="reset"&&y!=="image"}return!1}function d(g,h){const y=document.activeElement;try{g.focus({preventScroll:!0})}catch{return null}if(document.activeElement!==g){if(y)try{y.focus({preventScroll:!0})}catch{}return null}const b=getComputedStyle(g);let A=0,v="";const s=b.outlineStyle,k=parseFloat(b.outlineWidth)||0;if(s!=="none"&&k>0){const w=e(b.outlineColor);if(w){const R=w.a<1?n(w,h):w,T=a(R,h);T>A&&(A=T,v=`outline ${k}px ${b.outlineColor}`)}}const x=b.boxShadow;if(x&&x!=="none"){const w=e(x);if(w){const R=w.a<1?n(w,h):w,T=a(R,h);T>A&&(A=T,v=`box-shadow ${x.slice(0,60)}`)}}try{g.blur()}catch{}if(y)try{y.focus({preventScroll:!0})}catch{}return A===0?null:{ratio:A,indicator:v}}function u(g){const h=[{attr:"aria-current",activeVal:"page"},{attr:"aria-pressed",activeVal:"true"},{attr:"aria-selected",activeVal:"true"},{attr:"aria-checked",activeVal:"true"}];let y=null;for(const P of h){const _=g.getAttribute(P.attr);if(_&&(P.attr==="aria-current"?_!=="false"&&_!=="":_===P.activeVal)){y=P;break}}if(!y)return null;const b=g.parentElement;if(!b)return null;const A=g.tagName.toLowerCase(),v=Array.from(b.children).filter(P=>{if(!(P instanceof HTMLElement)||P===g||P.tagName.toLowerCase()!==A)return!1;const _=P.getAttribute(y.attr);return _?y.attr==="aria-current"?_==="false"||_==="":_!==y.activeVal:!0});if(v.length===0)return null;const s=v[0],k=getComputedStyle(g),x=getComputedStyle(s),w=[["backgroundColor","background"],["color","text color"],["borderTopColor","border"]],R=o(g),T=e(R.color);if(!T)return null;for(const[P,_]of w){const N=e(k[P]),M=e(x[P]);if(!N||!M||N.r===M.r&&N.g===M.g&&N.b===M.b&&N.a===M.a)continue;const S=N.a<1?n(N,T):N,E=M.a<1?n(M,T):M,V=a(S,E);return{activeColor:S,inactiveColor:E,ratio:V,ariaMarker:`${y.attr}="${g.getAttribute(y.attr)}" vs ${_}`}}return null}const p=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(g=>{const h=g.getBoundingClientRect();if(h.width<8||h.height<8)return!1;const y=getComputedStyle(g);return!(y.visibility==="hidden"||y.display==="none")}),f=[];for(const g of p){const h=getComputedStyle(g),y=o(g),b=y.hasImage?null:e(y.color),A=b?r(g,b):null;if(b&&A){const w=u(g);w&&w.ratio<3&&f.push({selector:i(g),role:g.getAttribute("role")??g.tagName.toLowerCase(),borderColor:`state: ${w.ariaMarker}`,backgroundColor:`active rgb(${w.activeColor.r},${w.activeColor.g},${w.activeColor.b}) vs inactive rgb(${w.inactiveColor.r},${w.inactiveColor.g},${w.inactiveColor.b})`,ratio:w.ratio,confident:!0})}if(b){const w=d(g,b);w!==null&&w.ratio<3&&f.push({selector:i(g),role:g.getAttribute("role")??g.tagName.toLowerCase(),borderColor:`focus: ${w.indicator}`,backgroundColor:y.color,ratio:w.ratio,confident:!0})}if(parseFloat(h.borderTopWidth)+parseFloat(h.borderRightWidth)+parseFloat(h.borderBottomWidth)+parseFloat(h.borderLeftWidth)===0)continue;const s=e(h.borderTopColor);if(!s)continue;if(y.hasImage){f.push({selector:i(g),role:g.getAttribute("role")??g.tagName.toLowerCase(),borderColor:h.borderTopColor,backgroundColor:y.color,ratio:0,confident:!1});continue}if(!b||!A||!l(g)&&c(g,A))continue;const k=s.a<1?n(s,b):s,x=a(k,b);if(f.push({selector:i(g),role:g.getAttribute("role")??g.tagName.toLowerCase(),borderColor:h.borderTopColor,backgroundColor:y.color,ratio:x,confident:!0}),f.length>=20)break}return{measured:f}}const yt=ee("label-in-name-audit"),Je="2.5.3";function Bl(){function e(c){return c.replace(/\s+/g," ").trim().toLowerCase()}function t(c){const l=c.cloneNode(!0);return l.querySelectorAll('[aria-hidden="true"]').forEach(d=>d.remove()),l.querySelectorAll(".sr-only, .visually-hidden, .screen-reader-text, .visuallyhidden").forEach(d=>d.remove()),(l.textContent??"").replace(/\s+/g," ").trim()}function a(c){var m,p,f,g;const l=c.getAttribute("aria-label");if(l&&l.trim())return l.trim();const d=c.getAttribute("aria-labelledby");if(d){const h=d.split(/\s+/).map(y=>document.getElementById(y)).filter(y=>y!==null).map(y=>{var b;return((b=y.textContent)==null?void 0:b.trim())??""}).filter(Boolean);if(h.length>0)return h.join(" ")}if(c.tagName==="INPUT"||c.tagName==="SELECT"||c.tagName==="TEXTAREA"){const h=c.getAttribute("id");if(h){const A=document.querySelector(`label[for="${h}"]`);if(A)return((m=A.textContent)==null?void 0:m.trim())??""}const y=c.closest("label");if(y)return((p=y.textContent)==null?void 0:p.trim())??"";const b=c.getAttribute("placeholder");if(b)return b.trim()}if(c.tagName==="BUTTON"||c.tagName==="A")return((f=c.textContent)==null?void 0:f.trim())??"";const u=c.getAttribute("value");return u&&c.type==="submit"?u.trim():((g=c.textContent)==null?void 0:g.trim())??""}function n(c){if(c.id)return`#${c.id}`;const l=c.tagName.toLowerCase(),d=c.className&&typeof c.className=="string"?"."+c.className.split(/\s+/).filter(Boolean).slice(0,2).join("."):"";return l+d}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"]'],i=Array.from(new Set(o.flatMap(c=>Array.from(document.querySelectorAll(c))))).filter(c=>{if(c.hasAttribute("disabled"))return!1;const l=c.getBoundingClientRect();if(l.width===0||l.height===0)return!1;const d=getComputedStyle(c);return!(d.visibility==="hidden"||d.display==="none")}),r=[];for(const c of i){const l=t(c),d=a(c);if(!l||!d)continue;const u=e(l),m=e(d);let p;m.includes(u)?p="pass":m.length===0||u.length===0?p="fail":p="ambiguous";const f=c.getAttribute("role")??c.tagName.toLowerCase();r.push({selector:n(c),role:f,visibleText:l.slice(0,200),accessibleName:d.slice(0,200),programmaticMatch:p})}return r}async function Kl(e){var f,g,h,y;if((f=e.signal)!=null&&f.aborted)return{ok:!1,error:"Audit cancelled."};let t;try{const A=(await chrome.scripting.executeScript({target:{tabId:e.tabId},world:"MAIN",func:Bl}))[0];if(!A||!A.result)return{ok:!1,error:"DOM walker returned no result."};t=A.result}catch(b){return yt.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:Je,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 ae(b),{ok:!0,result:b}}if(a.length===0&&n.length===0){const b={componentId:e.componentId,criterionId:Je,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 ae(b),yt.info(`2.5.3 passed programmatically (${o} candidates, all substring-matched)`),{ok:!0,result:b}}const i=await chrome.storage.local.get("aiConfig"),r=we(i.aiConfig),c=pe(r);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.`,A={componentId:e.componentId,criterionId:Je,verdict:a.length>0?"fail":"uncertain",reasoning:b,confidence:.6,pageUrl:e.pageUrl,finishedAt:new Date().toISOString(),costUsd:0,model:"programmatic-only"};return await ae(A),{ok:!0,result:A}}const l=c.client;if(typeof l.judgeLabelInName!="function")return{ok:!1,error:"AI client does not support judgeLabelInName."};if((g=e.signal)!=null&&g.aborted)return{ok:!1,error:"Audit cancelled."};const d=(y=(h=e.results)==null?void 0:h[0])==null?void 0:y.screenshotDataUrl,u=[...a,...n],m=await fa(Je,{candidates:u.map(b=>({selector:b.selector,role:b.role,visibleText:b.visibleText,accessibleName:b.accessibleName,programmaticMatch:b.programmaticMatch}))}),p=await ga(e.componentId,Je,m);if(p.hit){yt.info(`2.5.3 inputs unchanged (hash match); reusing verdict=${p.previous.verdict}`);const b=ma(p.previous,m);return await ae(b),{ok:!0,result:b}}try{const b=await Ke(()=>l.judgeLabelInName({pageUrl:e.pageUrl,pageScreenshot:d,candidates:u,signal:e.signal})),A=b.verdict==="pass"?"pass":b.verdict==="fail"?"fail":"uncertain",v={componentId:e.componentId,criterionId:Je,verdict:A,reasoning:`${o} interactive controls audited. ${t.length-u.length} passed the strict substring match; ${u.length} (${a.length} strict fails + ${n.length} ambiguous) sent to AI judgment. AI verdict: ${A}. `+b.reasoning,confidence:b.confidence,pageUrl:e.pageUrl,finishedAt:new Date().toISOString(),costUsd:b.costUsd,model:b.model,inputHash:m};return await ae(v),yt.info(`2.5.3 resolved to ${A} (${u.length} ambiguous cases AI-judged)`),{ok:!0,result:v}}catch(b){return yt.error("label-in-name AI judgment failed",b),{ok:!1,error:b instanceof Error?b.message:String(b)}}}const je=ee("focus-order-cascade");function Yl(){const e=Array.from(document.querySelectorAll('a[href], button, input:not([type=hidden]), select, textarea, [tabindex]:not([tabindex="-1"])')).filter(i=>{if(i.hasAttribute("disabled"))return!1;const r=i.getBoundingClientRect();if(r.width===0||r.height===0)return!1;const c=getComputedStyle(i);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 i of e){let r=i.parentElement;for(;r&&r!==document.body&&r!==document.documentElement;){const c=getComputedStyle(r);let l="";if(c.display==="grid"||c.display==="inline-grid"){const d=c.gridTemplateColumns.trim().split(/\s+/).filter(Boolean);d.length>=2&&c.gridTemplateColumns!=="none"&&(l=`grid-${d.length}-cols`)}else if(c.display==="flex"||c.display==="inline-flex")c.flexDirection.startsWith("row")&&(c.flexWrap==="wrap"||c.flexWrap==="wrap-reverse"?l="flex-row-wrap":r.children.length>=2&&(l="flex-row"));else{const d=c.columnCount;d&&d!=="auto"&&parseInt(d,10)>=2&&(l=`css-columns-${d}`)}if(l){const d=t.get(r);d?d.count++:t.set(r,{count:1,pattern:l});break}r=r.parentElement}}let a={count:0,pattern:"none"};for(const i of t.values())i.count>a.count&&(a={count:i.count,pattern:i.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 Jl(){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(i=>t.some(r=>r!==i&&r.contains(i))?!1:!t.some(r=>r!==i&&i.contains(r)));let n=0;for(const i of a)i.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 Xl(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 Ne(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 r=(await chrome.scripting.executeScript({target:{tabId:e.tabId},world:"MAIN",func:Yl}))[0];r&&r.result&&(a=r.result)}catch(i){je.warn("focus-order cascade detector failed",i)}if(a&&a.matches){const i={...t,verdict:"pass",reasoning:t.reasoning+`
|
|
838
|
+
})()`;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 so=ee("reading-order-audit"),Ft="1.3.2";async function Vl(e){var u,m,p;const t=await chrome.storage.local.get("aiConfig"),a=we(t.aiConfig),n=ue(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=((u=e.results[0])==null?void 0:u.readingOrderIssues)??[],i=(m=e.results[0])==null?void 0:m.screenshotDataUrl;if(r.length===0){const f={componentId:e.componentId,criterionId:Ft,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 ae(f),{ok:!0,result:f}}if((p=e.signal)!=null&&p.aborted)return{ok:!1,error:"Audit cancelled."};const c=await fa(Ft,{flaggedIssues:r.map(f=>({selector:f.selector,textSnippet:f.textSnippet,domIndex:f.domIndex,visualIndex:f.visualIndex}))}),l=await ga(e.componentId,Ft,c);if(l.hit){so.info(`1.3.2 inputs unchanged (hash match); reusing verdict=${l.previous.verdict}`);const f=ma(l.previous,c);return await ae(f),{ok:!0,result:f}}const d=l.previous?{verdict:l.previous.verdict,reasoning:l.previous.reasoning,confidence:l.previous.confidence}:void 0;try{const f=await Ke(()=>o.judgeReadingOrder({pageUrl:e.pageUrl,pageScreenshot:i,flaggedIssues:r.map(h=>({selector:h.selector,textSnippet:h.textSnippet,domIndex:h.domIndex,visualIndex:h.visualIndex,rect:h.boundingRect})),previousVerdict:d,signal:e.signal})),g={componentId:e.componentId,criterionId:Ft,verdict:f.verdict==="pass"?"pass":f.verdict==="fail"?"fail":"uncertain",reasoning:f.reasoning,confidence:f.confidence,steps:[],pageUrl:e.pageUrl,finishedAt:new Date().toISOString(),costUsd:f.costUsd,model:f.model,inputHash:c};return await ae(g),{ok:!0,result:g}}catch(f){return so.error("reading-order audit failed",f),{ok:!1,error:f instanceof Error?f.message:String(f)}}}const co=ee("non-text-contrast-audit"),_t="1.4.11";async function jl(e){var l,d,u,m;const t=await chrome.storage.local.get("aiConfig"),a=we(t.aiConfig),n=ue(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=(l=e.results[0])==null?void 0:l.screenshotDataUrl;if(!r)return{ok:!1,error:"No page screenshot available — re-run the audit so a screenshot is captured."};if((d=e.signal)!=null&&d.aborted)return{ok:!1,error:"Audit cancelled."};let i=null;if(e.tabId!==void 0)try{const p=await chrome.scripting.executeScript({target:{tabId:e.tabId},func:Gl});i=((u=p==null?void 0:p[0])==null?void 0:u.result)??null}catch(p){co.warn("component contrast measurement failed; falling back to AI",p)}if(i&&i.measured.length>=1){const p=i.measured.filter(h=>h.ratio<3&&h.confident),f=i.measured.filter(h=>h.ratio>=3),g=i.measured.filter(h=>!h.confident);if(p.length>0){const h={componentId:e.componentId,criterionId:_t,verdict:"fail",reasoning:`Programmatic measurement: ${p.length} of ${i.measured.length} measured components fail WCAG 1.4.11 (< 3:1 contrast against adjacent background). `+p.slice(0,6).map(y=>`${y.selector} — ${y.ratio.toFixed(2)}:1 (${y.borderColor} on ${y.backgroundColor})`).join("; ")+(f.length>0?` · ${f.length} other components pass.`:""),confidence:.98,steps:[],pageUrl:e.pageUrl,finishedAt:new Date().toISOString(),costUsd:0,model:"programmatic-contrast-measurement"};return await ae(h),{ok:!0,result:h}}if(g.length===0&&f.length===i.measured.length){const h={componentId:e.componentId,criterionId:_t,verdict:"pass",reasoning:`Programmatic measurement: ${f.length===1?"the":"all"} ${f.length} measured component${f.length===1?"":"s"} pass${f.length===1?"es":""} WCAG 1.4.11 (≥ 3:1 contrast against adjacent background). Lowest measured: ${(m=f.map(y=>y.ratio).sort((y,b)=>y-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 ae(h),{ok:!0,result:h}}}let c;try{const p=await Ne(e.componentId,_t);p&&(c={verdict:p.verdict,reasoning:p.reasoning,confidence:p.confidence})}catch{}try{const p=await Ke(()=>o.judgeNonTextContrast({pageUrl:e.pageUrl,pageScreenshot:r,previousVerdict:c,signal:e.signal})),f={componentId:e.componentId,criterionId:_t,verdict:p.verdict==="pass"?"pass":p.verdict==="fail"?"fail":"uncertain",reasoning:p.reasoning,confidence:p.confidence,steps:[],pageUrl:e.pageUrl,finishedAt:new Date().toISOString(),costUsd:p.costUsd,model:p.model};return await ae(f),{ok:!0,result:f}}catch(p){return co.error("non-text-contrast audit failed",p),{ok:!1,error:p instanceof Error?p.message:String(p)}}}function Gl(){function e(g){const h=g.match(/rgba?\(\s*([0-9.]+)\s*,?\s*([0-9.]+)\s*,?\s*([0-9.]+)(?:\s*[,/]\s*([0-9.]+))?\s*\)/i);if(!h)return null;const y=Math.round(parseFloat(h[1])),b=Math.round(parseFloat(h[2])),A=Math.round(parseFloat(h[3])),v=h[4]!==void 0?parseFloat(h[4]):1;return{r:y,g:b,b:A,a:v}}function t(g){const h=y=>{const b=y/255;return b<=.03928?b/12.92:Math.pow((b+.055)/1.055,2.4)};return .2126*h(g.r)+.7152*h(g.g)+.0722*h(g.b)}function a(g,h){const y=t(g),b=t(h),A=Math.max(y,b),v=Math.min(y,b);return(A+.05)/(v+.05)}function n(g,h){const y=Math.max(0,Math.min(1,g.a));return{r:Math.round(g.r*y+h.r*(1-y)),g:Math.round(g.g*y+h.g*(1-y)),b:Math.round(g.b*y+h.b*(1-y))}}function o(g){let h=g.parentElement;for(;h&&h!==document.documentElement;){const y=getComputedStyle(h);if(y.backgroundImage&&y.backgroundImage!=="none")return{color:y.backgroundColor,hasImage:!0};const A=e(y.backgroundColor);if(A&&A.a>.5)return{color:y.backgroundColor,hasImage:!1};h=h.parentElement}return{color:"rgb(255, 255, 255)",hasImage:!1}}function r(g){if(g.id)return`#${g.id}`;const h=g.tagName.toLowerCase(),y=g.className&&typeof g.className=="string"?g.className.split(/\s+/).filter(Boolean).slice(0,2).join("."):"";return y?`${h}.${y}`:h}function i(g,h){const y=getComputedStyle(g),b=e(y.backgroundColor);return b?b.a>=.999?b:b.a<=.001?h:n(b,h):h}function c(g,h){if((g.textContent??"").trim().length===0)return!1;const y=document.createTreeWalker(g,NodeFilter.SHOW_TEXT);let b;for(;b=y.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 N=parseFloat(s.width),M=parseFloat(s.height);if(N>0&&N<=1||M>0&&M<=1||s.clip==="rect(0px, 0px, 0px, 0px)"||s.clipPath==="inset(50%)")continue}const k=e(s.color);if(!k)continue;const x=k.a<1?n(k,h):k,w=a(x,h),R=parseFloat(s.fontSize)||16,T=parseInt(s.fontWeight,10)||400,_=R>=24||R>=18.5&&T>=700?3:4.5;if(w>=_)return!0}return!1}function l(g){const h=g.tagName.toLowerCase();if(h==="textarea"||h==="select")return!0;if(h==="input"){const y=(g.getAttribute("type")??"text").toLowerCase();return y!=="hidden"&&y!=="checkbox"&&y!=="radio"&&y!=="submit"&&y!=="button"&&y!=="reset"&&y!=="image"}return!1}function d(g,h){const y=document.activeElement;try{g.focus({preventScroll:!0})}catch{return null}if(document.activeElement!==g){if(y)try{y.focus({preventScroll:!0})}catch{}return null}const b=getComputedStyle(g);let A=0,v="";const s=b.outlineStyle,k=parseFloat(b.outlineWidth)||0;if(s!=="none"&&k>0){const w=e(b.outlineColor);if(w){const R=w.a<1?n(w,h):w,T=a(R,h);T>A&&(A=T,v=`outline ${k}px ${b.outlineColor}`)}}const x=b.boxShadow;if(x&&x!=="none"){const w=e(x);if(w){const R=w.a<1?n(w,h):w,T=a(R,h);T>A&&(A=T,v=`box-shadow ${x.slice(0,60)}`)}}try{g.blur()}catch{}if(y)try{y.focus({preventScroll:!0})}catch{}return A===0?null:{ratio:A,indicator:v}}function u(g){const h=[{attr:"aria-current",activeVal:"page"},{attr:"aria-pressed",activeVal:"true"},{attr:"aria-selected",activeVal:"true"},{attr:"aria-checked",activeVal:"true"}];let y=null;for(const P of h){const _=g.getAttribute(P.attr);if(_&&(P.attr==="aria-current"?_!=="false"&&_!=="":_===P.activeVal)){y=P;break}}if(!y)return null;const b=g.parentElement;if(!b)return null;const A=g.tagName.toLowerCase(),v=Array.from(b.children).filter(P=>{if(!(P instanceof HTMLElement)||P===g||P.tagName.toLowerCase()!==A)return!1;const _=P.getAttribute(y.attr);return _?y.attr==="aria-current"?_==="false"||_==="":_!==y.activeVal:!0});if(v.length===0)return null;const s=v[0],k=getComputedStyle(g),x=getComputedStyle(s),w=[["backgroundColor","background"],["color","text color"],["borderTopColor","border"]],R=o(g),T=e(R.color);if(!T)return null;for(const[P,_]of w){const N=e(k[P]),M=e(x[P]);if(!N||!M||N.r===M.r&&N.g===M.g&&N.b===M.b&&N.a===M.a)continue;const S=N.a<1?n(N,T):N,E=M.a<1?n(M,T):M,V=a(S,E);return{activeColor:S,inactiveColor:E,ratio:V,ariaMarker:`${y.attr}="${g.getAttribute(y.attr)}" vs ${_}`}}return null}const p=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(g=>{const h=g.getBoundingClientRect();if(h.width<8||h.height<8)return!1;const y=getComputedStyle(g);return!(y.visibility==="hidden"||y.display==="none")}),f=[];for(const g of p){const h=getComputedStyle(g),y=o(g),b=y.hasImage?null:e(y.color),A=b?i(g,b):null;if(b&&A){const w=u(g);w&&w.ratio<3&&f.push({selector:r(g),role:g.getAttribute("role")??g.tagName.toLowerCase(),borderColor:`state: ${w.ariaMarker}`,backgroundColor:`active rgb(${w.activeColor.r},${w.activeColor.g},${w.activeColor.b}) vs inactive rgb(${w.inactiveColor.r},${w.inactiveColor.g},${w.inactiveColor.b})`,ratio:w.ratio,confident:!0})}if(b){const w=d(g,b);w!==null&&w.ratio<3&&f.push({selector:r(g),role:g.getAttribute("role")??g.tagName.toLowerCase(),borderColor:`focus: ${w.indicator}`,backgroundColor:y.color,ratio:w.ratio,confident:!0})}if(parseFloat(h.borderTopWidth)+parseFloat(h.borderRightWidth)+parseFloat(h.borderBottomWidth)+parseFloat(h.borderLeftWidth)===0)continue;const s=e(h.borderTopColor);if(!s)continue;if(y.hasImage){f.push({selector:r(g),role:g.getAttribute("role")??g.tagName.toLowerCase(),borderColor:h.borderTopColor,backgroundColor:y.color,ratio:0,confident:!1});continue}if(!b||!A||!l(g)&&c(g,A))continue;const k=s.a<1?n(s,b):s,x=a(k,b);if(f.push({selector:r(g),role:g.getAttribute("role")??g.tagName.toLowerCase(),borderColor:h.borderTopColor,backgroundColor:y.color,ratio:x,confident:!0}),f.length>=20)break}return{measured:f}}const yt=ee("label-in-name-audit"),Je="2.5.3";function zl(){function e(c){return c.replace(/\s+/g," ").trim().toLowerCase()}function t(c){const l=c.cloneNode(!0);return l.querySelectorAll('[aria-hidden="true"]').forEach(d=>d.remove()),l.querySelectorAll(".sr-only, .visually-hidden, .screen-reader-text, .visuallyhidden").forEach(d=>d.remove()),(l.textContent??"").replace(/\s+/g," ").trim()}function a(c){var m,p,f,g;const l=c.getAttribute("aria-label");if(l&&l.trim())return l.trim();const d=c.getAttribute("aria-labelledby");if(d){const h=d.split(/\s+/).map(y=>document.getElementById(y)).filter(y=>y!==null).map(y=>{var b;return((b=y.textContent)==null?void 0:b.trim())??""}).filter(Boolean);if(h.length>0)return h.join(" ")}if(c.tagName==="INPUT"||c.tagName==="SELECT"||c.tagName==="TEXTAREA"){const h=c.getAttribute("id");if(h){const A=document.querySelector(`label[for="${h}"]`);if(A)return((m=A.textContent)==null?void 0:m.trim())??""}const y=c.closest("label");if(y)return((p=y.textContent)==null?void 0:p.trim())??"";const b=c.getAttribute("placeholder");if(b)return b.trim()}if(c.tagName==="BUTTON"||c.tagName==="A")return((f=c.textContent)==null?void 0:f.trim())??"";const u=c.getAttribute("value");return u&&c.type==="submit"?u.trim():((g=c.textContent)==null?void 0:g.trim())??""}function n(c){if(c.id)return`#${c.id}`;const l=c.tagName.toLowerCase(),d=c.className&&typeof c.className=="string"?"."+c.className.split(/\s+/).filter(Boolean).slice(0,2).join("."):"";return l+d}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 l=c.getBoundingClientRect();if(l.width===0||l.height===0)return!1;const d=getComputedStyle(c);return!(d.visibility==="hidden"||d.display==="none")}),i=[];for(const c of r){const l=t(c),d=a(c);if(!l||!d)continue;const u=e(l),m=e(d);let p;m.includes(u)?p="pass":m.length===0||u.length===0?p="fail":p="ambiguous";const f=c.getAttribute("role")??c.tagName.toLowerCase();i.push({selector:n(c),role:f,visibleText:l.slice(0,200),accessibleName:d.slice(0,200),programmaticMatch:p})}return i}async function Hl(e){var f,g,h,y;if((f=e.signal)!=null&&f.aborted)return{ok:!1,error:"Audit cancelled."};let t;try{const A=(await chrome.scripting.executeScript({target:{tabId:e.tabId},world:"MAIN",func:zl}))[0];if(!A||!A.result)return{ok:!1,error:"DOM walker returned no result."};t=A.result}catch(b){return yt.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:Je,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 ae(b),{ok:!0,result:b}}if(a.length===0&&n.length===0){const b={componentId:e.componentId,criterionId:Je,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 ae(b),yt.info(`2.5.3 passed programmatically (${o} candidates, all substring-matched)`),{ok:!0,result:b}}const r=await chrome.storage.local.get("aiConfig"),i=we(r.aiConfig),c=ue(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.`,A={componentId:e.componentId,criterionId:Je,verdict:a.length>0?"fail":"uncertain",reasoning:b,confidence:.6,pageUrl:e.pageUrl,finishedAt:new Date().toISOString(),costUsd:0,model:"programmatic-only"};return await ae(A),{ok:!0,result:A}}const l=c.client;if(typeof l.judgeLabelInName!="function")return{ok:!1,error:"AI client does not support judgeLabelInName."};if((g=e.signal)!=null&&g.aborted)return{ok:!1,error:"Audit cancelled."};const d=(y=(h=e.results)==null?void 0:h[0])==null?void 0:y.screenshotDataUrl,u=[...a,...n],m=await fa(Je,{candidates:u.map(b=>({selector:b.selector,role:b.role,visibleText:b.visibleText,accessibleName:b.accessibleName,programmaticMatch:b.programmaticMatch}))}),p=await ga(e.componentId,Je,m);if(p.hit){yt.info(`2.5.3 inputs unchanged (hash match); reusing verdict=${p.previous.verdict}`);const b=ma(p.previous,m);return await ae(b),{ok:!0,result:b}}try{const b=await Ke(()=>l.judgeLabelInName({pageUrl:e.pageUrl,pageScreenshot:d,candidates:u,signal:e.signal})),A=b.verdict==="pass"?"pass":b.verdict==="fail"?"fail":"uncertain",v={componentId:e.componentId,criterionId:Je,verdict:A,reasoning:`${o} interactive controls audited. ${t.length-u.length} passed the strict substring match; ${u.length} (${a.length} strict fails + ${n.length} ambiguous) sent to AI judgment. AI verdict: ${A}. `+b.reasoning,confidence:b.confidence,pageUrl:e.pageUrl,finishedAt:new Date().toISOString(),costUsd:b.costUsd,model:b.model,inputHash:m};return await ae(v),yt.info(`2.5.3 resolved to ${A} (${u.length} ambiguous cases AI-judged)`),{ok:!0,result:v}}catch(b){return yt.error("label-in-name AI judgment failed",b),{ok:!1,error:b instanceof Error?b.message:String(b)}}}const je=ee("focus-order-cascade");function Bl(){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 l="";if(c.display==="grid"||c.display==="inline-grid"){const d=c.gridTemplateColumns.trim().split(/\s+/).filter(Boolean);d.length>=2&&c.gridTemplateColumns!=="none"&&(l=`grid-${d.length}-cols`)}else if(c.display==="flex"||c.display==="inline-flex")c.flexDirection.startsWith("row")&&(c.flexWrap==="wrap"||c.flexWrap==="wrap-reverse"?l="flex-row-wrap":i.children.length>=2&&(l="flex-row"));else{const d=c.columnCount;d&&d!=="auto"&&parseInt(d,10)>=2&&(l=`css-columns-${d}`)}if(l){const d=t.get(i);d?d.count++:t.set(i,{count:1,pattern:l});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 Kl(){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 Yl(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 Ne(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:Bl}))[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+`
|
|
839
839
|
|
|
840
840
|
[Cascade resolution — rc.167 fallback-1]
|
|
841
|
-
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 ae(
|
|
841
|
+
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 ae(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 Jl(e,t);if(n.ran&&n.resolved==="pass"||n.ran&&n.resolved==="fail")return n;const o={...t,verdict:"fail",reasoning:t.reasoning+`
|
|
842
842
|
|
|
843
843
|
[Cascade resolution — rc.169 escalation]
|
|
844
|
-
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 ae(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
|
|
844
|
+
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 ae(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 Jl(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=we(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=ue(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 Ke(()=>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+`
|
|
845
845
|
|
|
846
846
|
[Cascade resolution — rc.169 fallback-2]
|
|
847
|
-
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: `+
|
|
847
|
+
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+`
|
|
848
848
|
|
|
849
|
-
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+
|
|
849
|
+
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 ae(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+`
|
|
850
850
|
|
|
851
851
|
[Cascade resolution — rc.169 fallback-2]
|
|
852
|
-
Primary AI verdict was uncertain. Programmatic multi-column detector found no matching pattern. Focused AI re-call resolved to FAIL with reasoning: `+
|
|
852
|
+
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 ae(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 ba(){const e=await fe();return de(e,"aiWalkthroughs")}const he=ee("interactive-walkthroughs");async function et(e,t){if(!e.verifyFixesOnly)return null;const a=await Ne(e.componentId,t);return a?await Es(e.componentId,t,e.pageUrl)?(he.info(`${t} skipped (verify-fixes): ack present`),a):a.verdict==="pass"?(he.info(`${t} skipped (verify-fixes): previously passed`),a):null:null}async function Xl(e){var a,n,o,r,i,c,l;if(!await ba())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 d=await et(e,"2.4.3");if(d)t.push({criterionId:"2.4.3",ran:!1,ok:!0,verdict:d.verdict,skippedForVerifyFixes:!0});else{const u=await Dl({tabId:e.tabId,componentId:e.componentId,pageUrl:e.pageUrl,signal:e.signal});t.push({criterionId:"2.4.3",ran:!0,ok:u.ok,verdict:u.ok?u.result.verdict:void 0,error:u.ok?void 0:u.error})}}}catch(d){he.warn("2.4.3 walkthrough threw",d),t.push({criterionId:"2.4.3",ran:!0,ok:!1,error:d instanceof Error?d.message:String(d)})}try{if((n=e.signal)!=null&&n.aborted)t.push({criterionId:"2.1.2",ran:!1,ok:!1,error:"cancelled"});else{const d=await et(e,"2.1.2");if(d)t.push({criterionId:"2.1.2",ran:!1,ok:!0,verdict:d.verdict,skippedForVerifyFixes:!0});else{const u=await Ll({tabId:e.tabId,componentId:e.componentId,pageUrl:e.pageUrl,signal:e.signal});t.push({criterionId:"2.1.2",ran:!0,ok:u.ok,verdict:u.ok?u.result.verdict:void 0,error:u.ok?void 0:u.error})}}}catch(d){he.warn("2.1.2 walkthrough threw",d),t.push({criterionId:"2.1.2",ran:!0,ok:!1,error:d instanceof Error?d.message:String(d)})}try{if((o=e.signal)!=null&&o.aborted)t.push({criterionId:"2.4.7",ran:!1,ok:!1,error:"cancelled"});else{const d=await et(e,"2.4.7");if(d)t.push({criterionId:"2.4.7",ran:!1,ok:!0,verdict:d.verdict,skippedForVerifyFixes:!0});else{const u=await Ul({tabId:e.tabId,componentId:e.componentId,pageUrl:e.pageUrl,signal:e.signal});t.push({criterionId:"2.4.7",ran:!0,ok:u.ok,verdict:u.ok?u.result.verdict:void 0,error:u.ok?void 0:u.error})}}}catch(d){he.warn("2.4.7 walkthrough threw",d),t.push({criterionId:"2.4.7",ran:!0,ok:!1,error:d instanceof Error?d.message:String(d)})}try{const d=t.find(u=>u.criterionId==="2.4.3");if(d!=null&&d.ok&&d.verdict==="fail"){const u=await chrome.scripting.executeScript({target:{tabId:e.tabId},func:Kl}),m=(r=u==null?void 0:u[0])==null?void 0:r.result;if(m!=null&&m.matches){const p=await Ne(e.componentId,"2.4.3");if(p&&p.verdict==="fail"){const f={...p,verdict:"pass",reasoning:p.reasoning+`
|
|
853
853
|
|
|
854
|
-
[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 ae(f),d.verdict="pass",
|
|
854
|
+
[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 ae(f),d.verdict="pass",he.info(`2.4.3 fail overridden → pass (rc.270 labeled-group nav: ${m.groupsWithFocusables} regions)`)}}}}catch(d){he.warn("2.4.3 labeled-group nav override step failed",d)}try{const d=t.find(m=>m.criterionId==="2.4.3"),u=t.find(m=>m.criterionId==="2.1.2");if(d!=null&&d.ok&&d.verdict==="fail"&&(u!=null&&u.ok)&&u.verdict==="pass"){const m=await Ne(e.componentId,"2.4.3");if(m&&m.verdict==="fail"){const p={...m,verdict:"uncertain",reasoning:m.reasoning+`
|
|
855
855
|
|
|
856
|
-
[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 ae(p),d.verdict="uncertain",
|
|
856
|
+
[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 ae(p),d.verdict="uncertain",he.info("2.4.3 fail downgraded to uncertain — 2.1.2 PASSed (multi-column layout corroboration)")}}}catch(d){he.warn("2.4.3 ↔ 2.1.2 cross-corroboration step failed",d)}try{const d=t.find(m=>m.criterionId==="2.4.3"),u=t.find(m=>m.criterionId==="2.1.2");if(d&&d.verdict==="uncertain"&&(u==null?void 0:u.verdict)==="pass"){const m=await Ne(e.componentId,"2.4.3"),p=await Yl({tabId:e.tabId,componentId:e.componentId,pageUrl:e.pageUrl,focusOrderVerdict:d.verdict,keyboardTrapVerdict:u.verdict,tabSequence:(i=m==null?void 0:m.steps)==null?void 0:i.filter(f=>f.action!=="initial").map(f=>({ordinal:f.ordinal,selector:f.focused.selector,role:f.focused.role,name:f.focused.name,rect:f.focused.rect??{x:0,y:0,width:0,height:0}})),pageScreenshot:(l=(c=m==null?void 0:m.steps)==null?void 0:c[0])==null?void 0:l.screenshot,signal:e.signal});p.ran&&p.resolved==="pass"?(d.verdict="pass",he.info(`2.4.3 uncertain resolved to PASS via cascade ${p.via} (${p.pattern??p.evidence.slice(0,80)})`)):p.ran&&p.resolved==="fail"?(d.verdict="fail",he.info(`2.4.3 resolved to FAIL via cascade ${p.via}: ${p.evidence.slice(0,80)}`)):p.ran&&p.resolved==="uncertain"?he.info("2.4.3 cascade exhausted all paths — uncertain stays. (this shouldn't happen post-rc.169; escalation should have fired)"):p.ran||he.info(`2.4.3 cascade did not run: ${p.reason}`)}}catch(d){he.warn("2.4.3 cascade step failed",d)}return t}async function Ql(e){var t;try{if(!await ba())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 et(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 Vl({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 he.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 Zl(e){var t;try{if(!await ba())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 et(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 jl({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 he.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 ed(e){var t;try{if(!await ba())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 et(e,"2.5.3");if(a)return{criterionId:"2.5.3",ran:!1,ok:!0,verdict:a.verdict,skippedForVerifyFixes:!0};const n=await Hl({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 he.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 td(e){const t=JSON.stringify({algo:"rc356-css-crosscheck",ruleId:e.ruleId,selector:e.selector,fg:e.foreground??null,fs:e.fontSize??null,fw:e.fontWeight??null,summary:e.failureSummary??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 tt=ee("pixel-contrast-sampler"),ad="1.3",nd=4.5,od=3;function id(e,t){return e?e>=24||e>=18.66&&(t??400)>=700:!1}function rd(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 lo({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 In(e,t){const a=lo(e),n=lo(t),o=Math.max(a,n),r=Math.min(a,n);return(o+.05)/(r+.05)}function sd(e,t,a,n){return e>=n||!a?!1:In(t,a)>=n}async function cd(e,t){var n;const a=`(() => {
|
|
857
857
|
const dpr = window.devicePixelRatio || 1;
|
|
858
858
|
const sx = window.scrollX || 0;
|
|
859
859
|
const sy = window.scrollY || 0;
|
|
@@ -933,7 +933,7 @@ Primary AI verdict was uncertain. Programmatic multi-column detector found no ma
|
|
|
933
933
|
} catch { out[sel] = null; }
|
|
934
934
|
}
|
|
935
935
|
return JSON.stringify(out);
|
|
936
|
-
})()`;try{const o=await chrome.debugger.sendCommand({tabId:e},"Runtime.evaluate",{expression:a,returnByValue:!0}),
|
|
936
|
+
})()`;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 tt.debug("getAllRectsAtOnce failed",o),new Map}}const xn="__wcagcheckr_hidetext";async function ld(e){const t=`
|
|
937
937
|
(async () => {
|
|
938
938
|
// Wait for fonts so hide/restore screenshots show identical glyph metrics.
|
|
939
939
|
try { await document.fonts.ready; } catch {}
|
|
@@ -945,17 +945,17 @@ Primary AI verdict was uncertain. Programmatic multi-column detector found no ma
|
|
|
945
945
|
document.body.offsetHeight;
|
|
946
946
|
return true;
|
|
947
947
|
})()
|
|
948
|
-
`;await chrome.debugger.sendCommand({tabId:e},"Runtime.evaluate",{expression:t,awaitPromise:!0})}async function
|
|
948
|
+
`;await chrome.debugger.sendCommand({tabId:e},"Runtime.evaluate",{expression:t,awaitPromise:!0})}async function dd(e){const t=`
|
|
949
949
|
(() => {
|
|
950
950
|
const el = document.getElementById(${JSON.stringify(xn)});
|
|
951
951
|
if (el) el.remove();
|
|
952
952
|
document.body.offsetHeight;
|
|
953
953
|
return true;
|
|
954
954
|
})()
|
|
955
|
-
`;await chrome.debugger.sendCommand({tabId:e},"Runtime.evaluate",{expression:t})}async function uo(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 tt.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(l=>l.blob()),i=await createImageBitmap(o),c=new OffscreenCanvas(i.width,i.height).getContext("2d");return c?(c.drawImage(i,0,0),c.getImageData(0,0,i.width,i.height)):null}catch(n){return tt.warn(`clip decode failed: ${n instanceof Error?n.message:String(n)}`),null}}const hd=25,Cr=8,fd=150,gd=.95,md=4,bd=400;function yd(e,t,a){if(e.width!==t.width||e.height!==t.height)return null;const n=e.width,o=e.height;let i=0,r=0;for(let v=0;v<o;v++)for(let s=0;s<n;s++){const k=(v*n+s)*4,x=t.data[k],w=t.data[k+1],R=t.data[k+2],T=e.data[k],P=e.data[k+1],_=e.data[k+2],N=Math.abs(T-x)+Math.abs(P-w)+Math.abs(_-R);N>r&&(r=N),N>=hd&&i++}if(i<Cr)return null;const c=r*gd;let l=0,d=0,u=0,m=0;if(r>=bd)for(let v=0;v<o;v++)for(let s=0;s<n;s++){const k=(v*n+s)*4,x=t.data[k],w=t.data[k+1],R=t.data[k+2],T=e.data[k],P=e.data[k+1],_=e.data[k+2];Math.abs(T-x)+Math.abs(P-w)+Math.abs(_-R)>=c&&(l+=x,d+=w,u+=R,m++)}const p=m>=md?{r:Math.round(l/m),g:Math.round(d/m),b:Math.round(u/m)}:a,f=new Map;let g=0;for(let v=0;v<o;v++)for(let s=0;s<n;s++){const k=(v*n+s)*4,x=t.data[k],w=t.data[k+1],R=t.data[k+2];if(Math.abs(x-p.r)+Math.abs(w-p.g)+Math.abs(R-p.b)>=fd){g++;const P=x>>4<<8|w>>4<<4|R>>4,_=f.get(P);_?(_.r+=x,_.g+=w,_.b+=R,_.count++):f.set(P,{r:x,g:w,b:R,count:1})}}const h=n*o;if(g<h*.2){f.clear();for(let v=0;v<o;v++)for(let s=0;s<n;s++){const k=(v*n+s)*4,x=e.data[k],w=e.data[k+1],R=e.data[k+2],T=x>>4<<8|w>>4<<4|R>>4,P=f.get(T);P?(P.r+=x,P.g+=w,P.b+=R,P.count++):f.set(T,{r:x,g:w,b:R,count:1})}}let y={r:0,g:0,b:0,count:0};for(const v of f.values())v.count>y.count&&(y=v);const b={r:Math.round(y.r/y.count),g:Math.round(y.g/y.count),b:Math.round(y.b/y.count)},A=In(p,b);return{textPixelCount:i,worstRatio:A,worstBackground:b,worstForeground:p}}async function wd(e,t,a){var l,d,u,m,p;const n=new Map;for(const f of t){const g=f.pageUrl??f.scope??"";for(const h of((l=f.axeRulesEvaluated)==null?void 0:l.incomplete)??[])if(h.ruleId==="color-contrast")for(const y of h.elements??[]){const b=`${g}::${h.ruleId}::${y.selector}`;n.has(b)||n.set(b,{pageUrl:g,ruleId:h.ruleId,selector:y.selector,wcagCriterion:h.wcagCriterion??"1.4.3",foreground:(d=y.styles)==null?void 0:d.foreground,fontSize:(u=y.styles)==null?void 0:u.fontSize,fontWeight:(m=y.styles)==null?void 0:m.fontWeight,failureSummary:y.failureSummary})}}if(n.size===0)return{resolved:0,skipped:0};let o=!1,i=null;for(let f=1;f<=6;f++)try{await chrome.debugger.attach({tabId:e},od),o=!0;break}catch(g){i=g;const h=g instanceof Error?g.message:String(g);if(/already attached/i.test(h)){await new Promise(y=>setTimeout(y,500));continue}break}if(!o)return tt.warn("debugger attach failed after retries; skipping pixel sampling",i),{resolved:0,skipped:n.size};let r=0,c=0;try{const f=Array.from(n.values()),g=f.map(w=>w.selector),h=await dd(e,g);if(a!=null&&a.aborted)return{resolved:0,skipped:n.size};const y=((p=f[0])==null?void 0:p.pageUrl)??"",b=y?await dn(y):[],A=new Map;for(const w of b)A.set(`${w.ruleId}::${w.selector}`,w);const v=new Map,s=[];for(const w of f){const R=await nd(w);v.set(w.selector,R);const T=A.get(`${w.ruleId}::${w.selector}`);if(T&&T.inputHash===R&&T.verdict!=="uncertain"){const P={...T,resolvedAt:new Date().toISOString(),reasoning:T.reasoning.includes("(cached, hash-match)")?T.reasoning:`${T.reasoning} (cached, hash-match)`};await qe(P),r++;continue}s.push(w)}if(s.length===0)return tt.info(`pixel-contrast sampler: all ${f.length} targets reused from hash-cache`),{resolved:r,skipped:c};await ud(e);const k=new Map;for(const w of s){if(a!=null&&a.aborted)break;const R=h.get(w.selector);if(!R)continue;const T=await uo(e,R);T&&k.set(w.selector,T)}if(await pd(e),a!=null&&a.aborted)return{resolved:0,skipped:n.size};const x=new Map;for(const w of s){if(a!=null&&a.aborted)break;const R=h.get(w.selector);if(!R)continue;const T=await uo(e,R);T&&x.set(w.selector,T)}for(const w of s){if(a!=null&&a.aborted)break;const R=v.get(w.selector),T=h.get(w.selector);if(!T){c++;const q={pageUrl:w.pageUrl,ruleId:w.ruleId,selector:w.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:w.wcagCriterion,inputHash:R};await qe(q);continue}const P=k.get(w.selector),_=x.get(w.selector);if(!P||!_){c++;const q={pageUrl:w.pageUrl,ruleId:w.ruleId,selector:w.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:w.wcagCriterion,inputHash:R};await qe(q);continue}const N=cd(w.foreground);if(!N){c++;const q={pageUrl:w.pageUrl,ruleId:w.ruleId,selector:w.selector,verdict:"uncertain",reasoning:`Hide-text observation: element's computed CSS foreground color could not be parsed (got ${JSON.stringify(w.foreground)}). Cannot compute contrast against rendered background without an intended foreground color. Manual verification required.`,resolvedAt:new Date().toISOString(),costUsd:0,wcagCriterion:w.wcagCriterion,inputHash:R};await qe(q);continue}const M=yd(P,_,N);if(!M){c++;const q={pageUrl:w.pageUrl,ruleId:w.ruleId,selector:w.selector,verdict:"uncertain",reasoning:`Hide-text observation: too few text pixels detected (under ${Cr} after diffing hidden vs visible captures). Element may be canvas-rendered, SVG with non-standard rendering, or carry styles that prevent color: transparent from hiding the text. Manual verification required.`,resolvedAt:new Date().toISOString(),costUsd:0,wcagCriterion:w.wcagCriterion,inputHash:R};await qe(q);continue}const S=sd(w.fontSize,w.fontWeight),E=S?id:rd,V=q=>`rgb(${q.r},${q.g},${q.b})`;let D=M.worstRatio>=E,$="";if(ld(M.worstRatio,N,T.resolvedBg,E)){const q=In(N,T.resolvedBg);D=!0,$=` Cross-check (rc.356): computed CSS contrast ${V(N)} on resolved background ${V(T.resolvedBg)} = ${q.toFixed(2)}:1, which PASSES ${E}:1 — the sub-threshold pixel reading is an anti-aliasing/sampling artifact, not a real failure. Suppressed.`}const U={pageUrl:w.pageUrl,ruleId:w.ruleId,selector:w.selector,verdict:D?"pass":"fail",reasoning:`Hide-text observation: ${M.textPixelCount} text-core pixels detected by diffing hidden-vs-visible viewport screenshots. Worst per-pixel contrast: ${M.worstRatio.toFixed(2)}:1 against AA threshold ${E}:1 (${S?"large text":"normal text"}). At worst pixel: rendered foreground ${V(M.worstForeground)} on rendered background ${V(M.worstBackground)}. ${D&&$?"Passes (computed cross-check).":D?"Passes threshold.":"Falls below threshold — at least one text pixel reads against a background that fails contrast."}`+$,resolvedAt:new Date().toISOString(),costUsd:0,wcagCriterion:w.wcagCriterion,inputHash:R};await qe(U),r++}}finally{try{await chrome.debugger.sendCommand({tabId:e},"Runtime.evaluate",{expression:`(() => { const el = document.getElementById(${JSON.stringify(xn)}); if (el) el.remove(); return true; })()`})}catch{}try{await chrome.debugger.detach({tabId:e})}catch{}}return tt.info(`pixel-contrast sampler: resolved ${r}, skipped ${c}/${n.size}`),{resolved:r,skipped:c}}const lt=ee("ai-text");function dt(e){if(e!=null&&e.aborted){const t=new Error("aborted");throw t.name="AbortError",t}}function ut(e){return e instanceof Error&&(e.name==="AbortError"||e.name==="ExternalAbortError"||e.message==="aborted")}async function vd(e,t,a,n={}){var p;if(!a.enabled||!a.enabledChecks.headings)return{findings:[],totalCostUsd:0,capExceeded:!1,errors:[]};const o=pe(a);if(!o.ok)return{findings:[],totalCostUsd:0,capExceeded:!1,errors:[`AI client unavailable: ${o.reason}`]};const i=o.client,r=Ee(a.costCapUsd),c=[],l=[],d=Math.max(1,a.maxCandidatesPerCheck??10),u=e.slice(0,d),m=u.length;for(let f=0;f<u.length;f++){const g=u[f];if(!r.canCharge())break;try{dt(n.signal);const h=await i.judgeHeading({headingText:g.text,sectionContent:g.sectionContent,signal:n.signal});r.recordCharge(h.costUsd),h.verdict==="fail"&&h.confidence>=.6&&c.push(await pt("ai-heading-not-descriptive","2.4.6","AA","moderate","AI judged this heading does not describe its section content.",g.selector,g.outerHTML,g.text,h,t))}catch(h){if(ut(h)){l.push(`canceled after ${f}/${m} candidates`);break}const y=h instanceof Error?h.message:String(h);l.push(`${g.selector}: ${y}`),lt.warn("heading judgment failed",h)}(p=n.onProgress)==null||p.call(n,f+1,m)}return{findings:c,totalCostUsd:r.state.spentUsd,capExceeded:r.state.exceeded,errors:l}}async function Ad(e,t,a,n={}){var p;if(!a.enabled||!a.enabledChecks.sensory)return{findings:[],totalCostUsd:0,capExceeded:!1,errors:[]};const o=pe(a);if(!o.ok)return{findings:[],totalCostUsd:0,capExceeded:!1,errors:[`AI client unavailable: ${o.reason}`]};const i=o.client,r=Ee(a.costCapUsd),c=[],l=[],d=Math.max(1,a.maxCandidatesPerCheck??10),u=e.slice(0,d),m=u.length;for(let f=0;f<u.length;f++){const g=u[f];if(!r.canCharge())break;try{dt(n.signal);const h=await i.judgeSensoryLanguage({instructionText:g.text,signal:n.signal});r.recordCharge(h.costUsd),h.verdict==="fail"&&h.confidence>=.6&&c.push(await pt("ai-sensory-instruction","1.3.3","A","serious","AI flagged this instruction as relying on sensory characteristics (shape, color, location) without a programmatic identifier.",g.selector,g.outerHTML,g.text.slice(0,100),h,t))}catch(h){if(ut(h)){l.push(`canceled after ${f}/${m} candidates`);break}const y=h instanceof Error?h.message:String(h);l.push(`${g.selector}: ${y}`),lt.warn("sensory judgment failed",h)}(p=n.onProgress)==null||p.call(n,f+1,m)}return{findings:c,totalCostUsd:r.state.spentUsd,capExceeded:r.state.exceeded,errors:l}}async function kd(e,t,a,n={}){var p;if(!a.enabled||!a.enabledChecks.aria)return{findings:[],totalCostUsd:0,capExceeded:!1,errors:[]};const o=pe(a);if(!o.ok)return{findings:[],totalCostUsd:0,capExceeded:!1,errors:[`AI client unavailable: ${o.reason}`]};const i=o.client,r=Ee(a.costCapUsd),c=[],l=[],d=Math.max(1,a.maxCandidatesPerCheck??10),u=e.slice(0,d),m=u.length;for(let f=0;f<u.length;f++){const g=u[f];if(!r.canCharge())break;try{dt(n.signal);const h=await i.judgeAriaSemantics({elementHtml:g.outerHTML,computedRole:g.role,surroundingHtml:g.surroundingHtml,signal:n.signal});r.recordCharge(h.costUsd),h.verdict==="fail"&&h.confidence>=.65&&c.push(await pt("ai-aria-misuse","4.1.2","A","serious",`AI judged role="${g.role}" is being used inappropriately on this element.`,g.selector,g.outerHTML,g.role,h,t))}catch(h){if(ut(h)){l.push(`canceled after ${f}/${m} candidates`);break}const y=h instanceof Error?h.message:String(h);l.push(`${g.selector}: ${y}`),lt.warn("aria judgment failed",h)}(p=n.onProgress)==null||p.call(n,f+1,m)}return{findings:c,totalCostUsd:r.state.spentUsd,capExceeded:r.state.exceeded,errors:l}}async function Id(e,t,a,n={}){var p;if(!a.enabled||!a.enabledChecks.genericLinkText)return{findings:[],totalCostUsd:0,capExceeded:!1,errors:[]};const o=pe(a);if(!o.ok)return{findings:[],totalCostUsd:0,capExceeded:!1,errors:[`AI client unavailable: ${o.reason}`]};const i=o.client,r=Ee(a.costCapUsd),c=[],l=[],d=Math.max(1,a.maxCandidatesPerCheck??10),u=e.slice(0,d),m=u.length;for(let f=0;f<u.length;f++){const g=u[f];if(!r.canCharge())break;try{dt(n.signal);const h=await i.judgeGenericLinkText({linkText:g.linkText,surroundingText:g.surroundingText,signal:n.signal});r.recordCharge(h.costUsd),h.verdict==="fail"&&h.confidence>=.6&&c.push(await pt("ai-generic-link-text","2.4.4","A","serious","AI judged this link's purpose is not clear from its text or surrounding context.",g.selector,g.outerHTML,g.linkText,h,t))}catch(h){if(ut(h)){l.push(`canceled after ${f}/${m} candidates`);break}const y=h instanceof Error?h.message:String(h);l.push(`${g.selector}: ${y}`),lt.warn("generic-link judgment failed",h)}(p=n.onProgress)==null||p.call(n,f+1,m)}return{findings:c,totalCostUsd:r.state.spentUsd,capExceeded:r.state.exceeded,errors:l}}async function xd(e,t,a,n={}){var p;if(!a.enabled||!a.enabledChecks.wallOfText)return{findings:[],totalCostUsd:0,capExceeded:!1,errors:[]};const o=pe(a);if(!o.ok)return{findings:[],totalCostUsd:0,capExceeded:!1,errors:[`AI client unavailable: ${o.reason}`]};const i=o.client,r=Ee(a.costCapUsd),c=[],l=[],d=Math.max(1,a.maxCandidatesPerCheck??10),u=e.slice(0,d),m=u.length;for(let f=0;f<u.length;f++){const g=u[f];if(!r.canCharge())break;try{dt(n.signal);const h=await i.judgeWallOfText({blockText:g.blockText,structuralChildrenCount:g.structuralChildrenCount,signal:n.signal});r.recordCharge(h.costUsd),h.verdict==="fail"&&h.confidence>=.6&&c.push(await pt("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).",g.selector,g.outerHTML,g.blockText.slice(0,80),h,t))}catch(h){if(ut(h)){l.push(`canceled after ${f}/${m} candidates`);break}const y=h instanceof Error?h.message:String(h);l.push(`${g.selector}: ${y}`),lt.warn("wall-of-text judgment failed",h)}(p=n.onProgress)==null||p.call(n,f+1,m)}return{findings:c,totalCostUsd:r.state.spentUsd,capExceeded:r.state.exceeded,errors:l}}async function Sd(e,t,a,n={}){var p;if(!a.enabled||!a.enabledChecks.languageMismatch)return{findings:[],totalCostUsd:0,capExceeded:!1,errors:[]};const o=pe(a);if(!o.ok)return{findings:[],totalCostUsd:0,capExceeded:!1,errors:[`AI client unavailable: ${o.reason}`]};const i=o.client,r=Ee(a.costCapUsd),c=[],l=[],d=Math.max(1,a.maxCandidatesPerCheck??10),u=e.slice(0,d),m=u.length;for(let f=0;f<u.length;f++){const g=u[f];if(!r.canCharge())break;try{dt(n.signal);const h=await i.judgeLanguageMismatch({declaredLang:g.declaredLang,bodyTextSample:g.bodyTextSample,signal:n.signal});r.recordCharge(h.costUsd),h.verdict==="fail"&&h.confidence>=.7&&c.push(await pt("ai-language-mismatch","3.1.1","A","serious",`AI judged the page's content does not match the declared lang="${g.declaredLang||"(none)"}".`,g.selector,g.outerHTML,g.bodyTextSample.slice(0,80),h,t))}catch(h){if(ut(h)){l.push(`canceled after ${f}/${m} candidates`);break}const y=h instanceof Error?h.message:String(h);l.push(`${g.selector}: ${y}`),lt.warn("language-mismatch judgment failed",h)}(p=n.onProgress)==null||p.call(n,f+1,m)}return{findings:c,totalCostUsd:r.state.spentUsd,capExceeded:r.state.exceeded,errors:l}}async function pt(e,t,a,n,o,i,r,c,l,d){const u={selector:i,outerHTML:r.slice(0,500),failureSummary:`AI assessment: ${l.reasoning}`,tagName:"AI",role:null,accessibleName:null,textSnippet:c.slice(0,100)||null,attrId:null,attrTestid:null},m=await tn({ruleId:e,componentId:d.componentId,currentState:d.currentState,target:u});return{ruleId:e,wcagCriterion:t,wcagLevel:a,impact:n,description:o,helpUrl:"https://www.w3.org/WAI/WCAG21/Understanding/",target:u,componentId:d.componentId,currentState:d.currentState,axeVersion:d.axeVersion,detectedAt:new Date().toISOString(),matchKey:m,ai:{reasoning:l.reasoning,confidence:l.confidence,model:l.model,costUsd:l.costUsd}}}const Tr=ee("ai-vision");function $r(e){if(e!=null&&e.aborted){const t=new Error("aborted");throw t.name="AbortError",t}}function Er(e){return e instanceof Error&&(e.name==="AbortError"||e.name==="ExternalAbortError"||e.message==="aborted")}async function Cd(e,t,a,n={}){var p;if(!a.enabled||!a.enabledChecks.imageOfText)return{findings:[],totalCostUsd:0,capExceeded:!1,errors:[]};const o=pe(a);if(!o.ok)return{findings:[],totalCostUsd:0,capExceeded:!1,errors:[`AI client unavailable: ${o.reason}`]};const i=o.client,r=Ee(a.costCapUsd),c=Math.max(1,a.imageOfTextMaxImages??5),l=[...e].sort((f,g)=>g.pixelArea-f.pixelArea).slice(0,c),d=l.length,u=[],m=[];for(let f=0;f<l.length;f++){const g=l[f];if(!r.canCharge())break;try{$r(n.signal);const h=await i.judgeImageOfText({imageUrl:g.imageUrl,accessibleName:g.accessibleName,signal:n.signal});r.recordCharge(h.costUsd),h.verdict==="fail"&&h.confidence>=.65&&u.push(await Rr("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.",g.selector,g.outerHTML,g.accessibleName??"",h,t))}catch(h){if(Er(h)){m.push(`canceled after ${f}/${d} candidates`);break}const y=h instanceof Error?h.message:String(h);m.push(`${g.selector}: ${y}`),Tr.warn("image-of-text judgment failed",h)}(p=n.onProgress)==null||p.call(n,f+1,d)}return{findings:u,totalCostUsd:r.state.spentUsd,capExceeded:r.state.exceeded,errors:m}}async function Td(e,t,a,n={}){var p;if(!a.enabled||!a.enabledChecks.colorOnlyMeaning)return{findings:[],totalCostUsd:0,capExceeded:!1,errors:[]};const o=pe(a);if(!o.ok)return{findings:[],totalCostUsd:0,capExceeded:!1,errors:[o.reason]};const i=o.client,r=Ee(a.costCapUsd),c=[],l=[],d=Math.max(1,a.maxCandidatesPerCheck??10),u=e.slice(0,d),m=u.length;for(let f=0;f<u.length;f++){const g=u[f];if(!r.canCharge())break;try{$r(n.signal);const h=await i.judgeColorOnlyMeaning({elementHtml:g.elementHtml,contextDescription:g.contextDescription,signal:n.signal});r.recordCharge(h.costUsd),h.verdict==="fail"&&h.confidence>=.65&&c.push(await Rr("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).",g.selector,g.outerHTML,g.contextDescription,h,t))}catch(h){if(Er(h)){l.push(`canceled after ${f}/${m} candidates`);break}const y=h instanceof Error?h.message:String(h);l.push(y),Tr.warn("color-only judgment failed",h)}(p=n.onProgress)==null||p.call(n,f+1,m)}return{findings:c,totalCostUsd:r.state.spentUsd,capExceeded:r.state.exceeded,errors:l}}async function Rr(e,t,a,n,o,i,r,c,l,d){const u={selector:i,outerHTML:r.slice(0,500),failureSummary:`AI assessment: ${l.reasoning}`,tagName:"AI",role:null,accessibleName:null,textSnippet:c.slice(0,100)||null,attrId:null,attrTestid:null},m=await tn({ruleId:e,componentId:d.componentId,currentState:d.currentState,target:u});return{ruleId:e,wcagCriterion:t,wcagLevel:a,impact:n,description:o,helpUrl:"https://www.w3.org/WAI/WCAG21/Understanding/",target:u,componentId:d.componentId,currentState:d.currentState,axeVersion:d.axeVersion,detectedAt:new Date().toISOString(),matchKey:m,ai:{reasoning:l.reasoning,confidence:l.confidence,model:l.model,costUsd:l.costUsd}}}const Xa=ee("ensure-content-script"),$d=1500,Ed=300;async function Sn(e,t){if(await po(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 Xa.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 Rd(o)}return await Od(Ed),await po(e,t)?(Xa.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 po(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,i)=>setTimeout(()=>i(new Error("ping timeout")),$d))]);return(n==null?void 0:n.type)==="PING_RESPONSE"}catch{return!1}}function Rd(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}:(Xa.warn("content-script injection failed",e),{ok:!1,reason:"inject-failed",detail:t})}function Od(e){return new Promise(t=>setTimeout(t,e))}function Qa(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 Ea=ee("forensic-anchor-client"),Md="https://api.wcagcheckr.com",Dd="wcagcheckr",Nd=15e3;function Ld(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 Or(e,t){const a={auditHash:e.hash,pageUrl:e.pageUrl,capturedAt:e.capturedAt,...t?{licenseId:t}:{}},n=`${Md}/v1/products/${Dd}/forensic/anchor`;try{const o=await fetch(n,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(a),signal:AbortSignal.timeout(Nd)});if(!o.ok)return Ea.warn(`anchor HTTP ${o.status}; entry stays local-only`),null;const i=await o.json();return Ld(i)?i:(Ea.warn("anchor returned malformed receipt; entry stays local-only",i),null)}catch(o){return Ea.warn("anchor request failed; entry stays local-only",o),null}}const ho="4.11.4";async function Pd(e){try{return(await chrome.tabs.get(e)).url??""}catch{return""}}const F=ee("flows");async function ht(){const e=await zo();if(!e)throw new Error("no audit target tab found");return e}async function Cn(){var a,n,o,i,r;const e=await Ve("stateMatrix",Na);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&&((i=e.breakpoints)==null?void 0:i.length)>0&&((r=e.breakpointPresets)==null?void 0:r.length)>0?e:(F.warn("stored stateMatrix is invalid; using defaults"),Na)}async function Fd(e,t,a){const n=t.themes.includes("light"),o=t.themes.includes("dark");if(!n||!o)return t;let i=null;try{i=await ve(e,{type:"THEME_AWARENESS_REQUEST"},a)}catch{return t}return!i||i.hasUnreadableSheets?t:i.hasDarkModeCss&&!i.hasLightModeCss?(F.info("theme-axis prune: site is dark-only, skipping light pass"),{...t,themes:t.themes.filter(r=>r!=="light")}):i.hasLightModeCss&&!i.hasDarkModeCss?(F.info("theme-axis prune: site is light-only, skipping dark pass"),{...t,themes:t.themes.filter(r=>r!=="dark")}):t}const _d=200,Ra=3,fo=8;async function Ud(e,t){const a=[];let n=null,o=null;for(let r=0;r<fo&&!t();r++){const c=await e();if(c.error&&(o=c.error),!c.result)break;if(n=c.result,a.push(c.violations),r===1&&a[0].length===0&&a[1].length===0)return{violations:[],lastResult:n,sampleCount:2,stabilized:!0,lastError:o};if(a.length>=Ra){const l=a.slice(-Ra);if(Wd(l))return{violations:l[l.length-1],lastResult:n,sampleCount:a.length,stabilized:!0,lastError:o}}r<fo-1&&await new Promise(l=>setTimeout(l,_d))}const i=a.slice(-Ra);return{violations:qd(i),lastResult:n,sampleCount:a.length,stabilized:!1,lastError:o}}function Wd(e){if(e.length<2)return!0;const t=go(e[0]);for(let a=1;a<e.length;a++){const n=go(e[a]);if(n.size!==t.size)return!1;for(const o of t)if(!n.has(o))return!1}return!0}function go(e){return new Set(e.map(t=>`${t.ruleId}::${t.target.selector}::${t.matchKey}`))}function qd(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 i=`${o.ruleId}::${o.target.selector}::${o.matchKey}`;t.has(i)||t.set(i,{...o,needsReview:!0,flakyAcrossRuns:!0,target:{...o.target,failureSummary:o.target.failureSummary?`${o.target.failureSummary} ${a}`:a}})}return Array.from(t.values())}async function mo(e,t,a,n,o){await Promise.all([(async()=>{var i;try{const r=await ve(e,{type:"READING_ORDER_REQUEST",selector:t},a);n[0]&&(r.issues.length>0?(n[0].readingOrderIssues=r.issues,n[0].positionAnalysisCapturedAt=o):(i=n[0].axeRulesEvaluated)==null||i.passed.push({ruleId:"wcc-reading-order-clean",wcagCriterion:"1.3.2"}))}catch(r){F.debug("reading-order analysis skipped",r)}})(),(async()=>{var i;try{const r=await ve(e,{type:"TAB_ORDER_ANALYZE_REQUEST"},a);n[0]&&(r.issues.length>0?(n[0].tabOrderIssues=r.issues,n[0].positionAnalysisCapturedAt=o):(i=n[0].axeRulesEvaluated)==null||i.passed.push({ruleId:"wcc-tab-order-clean",wcagCriterion:"2.4.3"}))}catch(r){F.debug("tab-order analysis skipped",r)}})(),(async()=>{var i;try{const r=await ve(e,{type:"TYPOGRAPHY_ANALYZE_REQUEST",selector:t},a);r.issues.length>0&&n[0]?n[0].typographyIssues=r.issues:n[0]&&((i=n[0].axeRulesEvaluated)==null||i.passed.push({ruleId:"wcc-typography-clean",wcagCriterion:"1.4.12"}))}catch(r){F.debug("typography analysis skipped",r)}})(),(async()=>{try{const i=await ve(e,{type:"CUSTOM_PROPERTY_REQUEST"},a);i.undefined.length>0&&n[0]&&(n[0].undefinedCustomProperties=i.undefined)}catch(i){F.debug("custom-property analysis skipped",i)}})()])}async function it(e,t,a,n,o={}){var _,N,M;const i=o.asSubroutine===!0;if(await Fe())return i||z({type:"AUDIT_FAILED_EVENT",error:{code:St,message:ze,recoverable:!1}}),{ok:!1,results:[],error:ze};const r=o.tabIdOverride??await ht(),c=await Sn(r,a);if(!c.ok)return i||z({type:"AUDIT_FAILED_EVENT",error:{code:c.reason==="restricted-url"?"RESTRICTED_URL":"CONTENT_SCRIPT_UNREACHABLE",message:Qa(c),recoverable:c.reason!=="restricted-url"}}),{ok:!1,results:[],error:Qa(c)};try{await chrome.scripting.executeScript({target:{tabId:r,frameIds:a!==void 0?[a]:void 0},world:"MAIN",func:()=>{try{let S=document.getElementById("__wcagcheckr_audit_freeze");S||(S=document.createElement("style"),S.id="__wcagcheckr_audit_freeze",S.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(S)),window.scrollTo(0,0);const E=document.activeElement;E&&E instanceof HTMLElement&&E!==document.body&&E.blur()}catch{}}}),await chrome.scripting.executeScript({target:{tabId:r,frameIds:a!==void 0?[a]:void 0},world:"MAIN",func:async()=>{try{await document.fonts.ready}catch{}}})}catch(S){F.debug("audit-start state stabilization failed (non-fatal)",S)}const l=n??await Cn(),d=await Fd(r,l,a),u=Kc(d),m=await pi(`${await Pd(r)}|${e}|${a??0}`),p=await hi(d),f=await Ve("axeDisabledRules",[]),g=await fi(f);let h=null;try{h=(await ve(r,{type:"SCOPE_FINGERPRINT_REQUEST",selector:e},a)).fingerprint}catch(S){F.debug("scope fingerprint failed; skipping cache fast-path",S)}if(h){const S=await gi(m);if(S&&S.fingerprint===h&&S.axeVersion===ho&&S.matrixConfigHash===p&&S.disabledRulesHash===g)return F.info(`audit-cache HIT for ${S.componentId} — skipping matrix iteration`),i||(z({type:"AUDIT_COMPLETE_EVENT",componentId:S.componentId,results:S.results,delta:S.delta}),z({type:"SCORECARD_UPDATED_EVENT"})),{ok:!0,results:S.results}}i||await Be({sessionId:Et(),mode:"single-element",scope:e,startedAt:new Date().toISOString(),lastProgressAt:new Date().toISOString(),state:"running"}),await At(r,{type:"LIVE_REGIONS_ARM_REQUEST"},a).catch(()=>{}),await At(r,{type:"FOCUS_TRACE_ARM_REQUEST"},a).catch(()=>{}),await ve(r,{type:"WARMUP_REQUEST"},a).catch(()=>{});const y=[],b=[];let A="",v,s=!1,k=null,x=null,w=null,R=null,T=!1,P=null;try{for(let S=0;S<u.length;S++){if(t.isCanceled()){F.info("single audit canceled by user");break}const E=u[S];try{const V=await Ka(r,E,e,a);if(!V.success){v=(_=V.error)==null?void 0:_.message,F.warn(`state ${S+1}/${u.length} drive failed`,v);continue}E.breakpoint.id!==k&&(await ve(r,{type:"WARMUP_REQUEST"},a).catch(()=>{}),k=E.breakpoint.id);const D=S===0?void 0:[...mr],$=await Ud(async()=>{var Y;const q=await ve(r,{type:"AUDIT_REQUEST",selector:e,currentState:E,rulesToRun:D},a);return q.success&&q.result?{result:q.result,violations:q.result.violations,error:null}:{result:null,violations:[],error:((Y=q.error)==null?void 0:Y.message)??null}},()=>t.isCanceled());$.lastError&&(v=$.lastError,F.warn(`state ${S+1}/${u.length} sampling: ${$.lastError}`));const U=$.lastResult;if(!$.stabilized&&$.sampleCount>0&&F.info(`state ${S+1}/${u.length} did not stabilize after ${$.sampleCount} samples — ${$.violations.length} finding(s) routed to needs-review as flickering`),U){s=!0;const q=$.violations;F.info(`[adaptive-sample] state ${S+1}/${u.length} ${E.pseudoState}·${E.theme}·${E.direction}·${E.breakpoint.id}: ${$.sampleCount} sample(s), ${$.stabilized?"stabilized":"flickering"}, ${q.length} finding(s)`);const Y=await hl(r,{quality:75})??void 0;let Z,ke;try{Z=(await ve(r,{type:"LIVE_REGIONS_DRAIN_REQUEST"},a)).announcements}catch{}try{ke=(await ve(r,{type:"FOCUS_TRACE_DRAIN_REQUEST"},a)).focusEvents}catch{}if(b.push({...U,violations:q,frameId:a,announcements:Z,focusEvents:ke,screenshotDataUrl:Y}),y.push(...q),A=U.componentId,S===0&&x===null)try{const ie=await Ve("aiConfig",{}),ne=we(ie);if(ne.enabled&&ne.apiKey&&A){x=ta(r,e,a,ne,b,A,t).catch(C=>{F.warn("ai augmentation (parallel) failed",C)});const ge=((N=b[0])==null?void 0:N.pageUrl)??((M=b[0])==null?void 0:M.scope)??"";w=td({tabId:r,componentId:A,pageUrl:ge,results:b,verifyFixesOnly:o.verifyFixesOnly}).catch(C=>(F.warn("1.4.11 walkthrough (parallel) failed",C),{criterionId:"1.4.11",ran:!0,ok:!1,error:String(C)}))}}catch(ie){F.debug("ai augmentation (parallel) gate-read failed",ie)}!T&&E.pseudoState==="default"&&E.theme==="light"&&E.direction==="ltr"&&E.breakpoint.id==="desktop"&&b[0]&&(T=!0,P=mo(r,e,a,b,E).catch(ne=>{F.debug("lightweight deep analyzers (parallel) failed",ne)}))}}catch(V){v=V instanceof Error?V.message:String(V),F.warn(`state ${S+1}/${u.length} threw`,V)}z({type:"AUDIT_PROGRESS_EVENT",current:S+1,total:u.length,currentState:E,componentId:A||void 0}),i||await $t({})}if(s&&A){const S={pseudoState:"default",ariaVariation:null,theme:"light",direction:"ltr",breakpoint:{id:"desktop",label:"Desktop",width:1280,height:800,deviceScaleFactor:1,mobile:!1}};if(T){if(P)try{await P}catch{}}else{try{await Ka(r,S,e,a),await new Promise($=>setTimeout($,200))}catch($){F.debug("reference-state drive failed; analyzers will use last matrix state",$)}await mo(r,e,a,b,S).catch($=>{F.debug("lightweight deep analyzers (post-matrix fallback) failed",$)})}try{const $=await Ve("aiConfig",{}),U=we($);if(U.enabled&&U.apiKey&&A&&b[0]){const q=b[0].pageUrl??b[0].scope??"";R=ed({tabId:r,componentId:A,pageUrl:q,results:b,verifyFixesOnly:o.verifyFixesOnly}).catch(Y=>(F.warn("1.3.2 walkthrough (parallel) failed",Y),{criterionId:"1.3.2",ran:!0,ok:!1,error:String(Y)}))}}catch($){F.debug("1.3.2 walkthrough (parallel) gate-read failed",$)}try{if(x)await x;else{const $=await Ve("aiConfig",{}),U=we($);U.enabled&&U.apiKey&&await ta(r,e,a,U,b,A,t)}}catch($){F.warn("ai augmentation skipped",$)}try{const $=await Ve("aiConfig",{}),U=we($);if(U.enabled&&U.apiKey&&A&&b[0]){await qt(r,e,a).catch(ie=>F.warn("pre-walkthrough resetState failed",ie));const q=b[0].pageUrl??b[0].scope??"",Y=new AbortController,Z=setInterval(()=>{t.isCanceled()&&Y.abort()},250),ke=await Zl({tabId:r,componentId:A,pageUrl:q,results:b,signal:Y.signal,verifyFixesOnly:o.verifyFixesOnly}).finally(()=>clearInterval(Z));F.info("keyboard walkthroughs complete",ke)}}catch($){F.warn("keyboard walkthroughs failed",$)}try{const $=[];w&&$.push(await w),R&&$.push(await R),$.length>0&&F.info("parallel AI walkthroughs joined",$)}catch($){F.warn("parallel AI walkthrough join failed",$)}try{if(A&&b[0]){const $=b[0].pageUrl??b[0].scope??"",U=new AbortController,q=setInterval(()=>{t.isCanceled()&&U.abort()},250),Y=await ad({tabId:r,componentId:A,pageUrl:$,results:b,signal:U.signal,verifyFixesOnly:o.verifyFixesOnly}).finally(()=>clearInterval(q));F.info("2.5.3 label-in-name walkthrough complete",Y)}}catch($){F.warn("2.5.3 walkthrough failed",$)}try{if(A&&b[0]){await qt(r,e,a).catch(Z=>F.warn("pre-sampler resetState failed",Z));const $=new AbortController,U=setInterval(()=>{t.isCanceled()&&$.abort()},250),{resolved:q,skipped:Y}=await wd(r,b,$.signal).finally(()=>clearInterval(U));F.info(`pixel contrast sampler: resolved=${q} skipped=${Y}`)}}catch($){F.warn("pixel contrast sampler failed",$)}const E=b.flatMap($=>$.announcements??[]),V=b.flatMap($=>$.focusEvents??[]),D=await vn(A,y,{announcements:E,focusEvents:V},l);try{const $=await hn(b.map(ne=>ne.componentId)),U=await Zo(b.map(ne=>ne.componentId)),q=new Set;for(const ne of new Set(b.map(ge=>ge.componentId))){const ge=await ia(ne);for(const C of ge)q.add(C)}const Y=$e(y,void 0,b,q,$,U),Z=b.reduce((ne,ge)=>ne+ge.durationMs,0),ke=await de(),ie=ue(ke,"forensicLog")?await cr(b,Y,Z):null;if(ie){const ne=await de();if(ue(ne,"forensicAnchoring"))try{const ge=await an(),C=await Or(ie,ge??void 0);C&&await lr(ie.componentId,ie.capturedAt,C)}catch(ge){F.warn("forensic anchoring failed (entry stays local-only)",ge)}}}catch($){F.warn("forensic log recording failed",$)}if(h)try{await mi({lookupKey:m,fingerprint:h,axeVersion:ho,matrixConfigHash:p,disabledRulesHash:g,results:b,delta:D,componentId:A,cachedAt:Date.now()})}catch($){F.warn("audit-cache write failed",$)}try{await chrome.scripting.executeScript({target:{tabId:r,frameIds:a!==void 0?[a]:void 0},world:"MAIN",func:()=>{const $=document.getElementById("__wcagcheckr_audit_freeze");$&&$.remove()}})}catch($){F.debug("audit-end state-freeze cleanup failed",$)}i||z({type:"AUDIT_COMPLETE_EVENT",componentId:A,results:b,delta:D})}else i||z({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}});i||await nt()}catch(S){F.error("single audit failed",S),i||z({type:"AUDIT_FAILED_EVENT",componentId:A||void 0,error:Mn(S)?S.payload:{code:"UNKNOWN",message:String(S),recoverable:!1}}),v=Mn(S)?S.payload.message:String(S)}finally{await At(r,{type:"LIVE_REGIONS_DISARM_REQUEST"},a).catch(()=>{}),await At(r,{type:"FOCUS_TRACE_DISARM_REQUEST"},a).catch(()=>{}),await qt(r,e,a)}return{ok:s,results:b,error:s?void 0:v}}async function Mr(e){var t;try{const n=(await chrome.scripting.executeScript({target:{tabId:e,allFrames:!0},world:"MAIN",func:()=>{var i;const o=window;return{detected:typeof o.__STORYBOOK_PREVIEW__=="object",version:(i=o.__STORYBOOK_PREVIEW__)==null?void 0:i.version}}})).find(o=>{var i;return(i=o.result)==null?void 0:i.detected});if(n)return{detected:!0,version:(t=n.result)==null?void 0:t.version,frameId:n.frameId}}catch(a){F.warn("storybook detection scripting failed",a)}return{detected:!1}}async function Vd(e){if(await Fe()){z({type:"AUDIT_FAILED_EVENT",error:{code:St,message:ze,recoverable:!1}});return}const t=await ht(),a=await Lr(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){z({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"){z({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 zd(t,n):await Bd(t,n);if(!o.length){F.warn(`${a.kind} detected but no stories returned`),z({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 Be({sessionId:Et(),mode:"storybook-all",totalStories:o.length,completedStories:[],startedAt:new Date().toISOString(),lastProgressAt:new Date().toISOString(),state:"running"});for(const i of o){if(e.isCanceled()){F.info(`${a.kind} iteration canceled by user`);break}try{if(a.kind==="storybook"){await Hd(t,n,i.id);const c=await At(t,{type:"STORYBOOK_GET_STORY_TARGET_REQUEST",tabId:t},n);await it(c.selector,e,n)}else await Kd(t,n,i.id),await it("#ladle-root",e,n)}catch(c){F.warn(`story ${i.id} failed; continuing with next`,c)}const r=await ua();if((r==null?void 0:r.state)==="interrupted"){F.info("storybook iteration interrupted");break}await $t({completedStories:[...(r==null?void 0:r.completedStories)??[],i.id]})}z({type:"SCORECARD_UPDATED_EVENT"}),await nt()}async function jd(e){if(await Fe()){z({type:"AUDIT_FAILED_EVENT",error:{code:St,message:ze,recoverable:!1}});return}const t=await de();if(!ue(t,"allFramesAudit")){z({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 ht();let n=[];try{n=(await chrome.scripting.executeScript({target:{tabId:a,allFrames:!0},func:()=>({url:window.location.href})})).map(i=>{var r;return{frameId:i.frameId,url:((r=i.result)==null?void 0:r.url)??""}}).filter(i=>/^https?:/i.test(i.url))}catch(o){F.warn("multi-frame discovery failed",o)}if(n.length===0){z({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 Be({sessionId:Et(),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()){F.info("all-frames iteration canceled");break}try{await it("html",e,o.frameId)}catch(r){F.warn(`frame ${o.frameId} (${o.url.slice(0,80)}) audit failed; continuing`,r)}const i=await ua();if((i==null?void 0:i.state)==="interrupted"){F.info("all-frames iteration interrupted");break}await $t({completedFrames:[...(i==null?void 0:i.completedFrames)??[],o.frameId]})}z({type:"SCORECARD_UPDATED_EVENT"}),await nt()}async function Gd(e){var o;const t=await de();if(!ue(t,"parallelScan")){z({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 zo();let n;if(a!==null)try{n=(await chrome.tabs.get(a)).url}catch(i){F.warn("failed to get target tab url",i)}if(!n){z({type:"AUDIT_FAILED_EVENT",error:{code:"NETWORK",message:"Could not determine target URL for parallel scan.",recoverable:!1}});return}await Be({sessionId:Et(),mode:"single-element",scope:"html",startedAt:new Date().toISOString(),lastProgressAt:new Date().toISOString(),state:"running"});try{const i=await Cn(),{runParallelTabAudit:r}=await en(async()=>{const{runParallelTabAudit:m}=await import("./parallel-tab-flow-C4bjrDqL.js");return{runParallelTabAudit:m}},__vite__mapDeps([0,1,2,3,4])),c=await r({targetUrl:n,scope:"html",matrix:i,parallelism:4,cancel:e});if(F.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){z({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 l=((o=c.results[0])==null?void 0:o.componentId)??"parallel-scan";if(a!==null)try{const m=await Ve("aiConfig",{}),p=we(m);p.enabled&&p.apiKey&&await ta(a,"html",void 0,p,c.results,l,e)}catch(m){F.warn("parallel scan: ai augmentation skipped",m)}const d=c.results.flatMap(m=>m.violations);let u;try{u=await vn(l,d)}catch(m){F.warn("parallel scan: baseline compare failed",m),u={new:[],persistent:[],fixed:[],newCount:0,persistentCount:0,fixedCount:0,baselineSnapshotMeta:null,comparedAt:new Date().toISOString()}}z({type:"AUDIT_COMPLETE_EVENT",componentId:l,results:c.results,delta:u}),z({type:"SCORECARD_UPDATED_EVENT"})}catch(i){F.warn("parallel scan failed",i),z({type:"AUDIT_FAILED_EVENT",error:{code:"UNKNOWN",message:i instanceof Error?i.message:String(i),recoverable:!0}})}finally{await nt()}}async function zd(e,t){var a;try{return((a=(await chrome.scripting.executeScript({target:{tabId:e,frameIds:[t]},world:"MAIN",func:async()=>{var l,d;const o=window.__STORYBOOK_PREVIEW__;if(!o)return[];const i=o.storyStoreValue??o.storyStore;if(!i)return[];typeof i.cacheAllCSFFiles=="function"&&await i.cacheAllCSFFiles();const r=((l=i.extract)==null?void 0:l.call(i))??((d=i.cachedCSFFiles)==null?void 0:d.call(i));if(!r)return[];const c=[];if(r instanceof Map)for(const[u,m]of r){const p=m;c.push({id:String(u),name:p.name??String(u),kind:p.title??p.kind??""})}else if(typeof r=="object"&&r!==null)for(const[u,m]of Object.entries(r)){const p=m;c.push({id:u,name:p.name??u,kind:p.title??p.kind??""})}return c}}))[0])==null?void 0:a.result)??[]}catch(n){return F.warn("listStoriesViaMainWorld failed",n),[]}}async function Hd(e,t,a){try{await chrome.scripting.executeScript({target:{tabId:e,frameIds:[t]},world:"MAIN",args:[a,3e3],func:async(n,o)=>{const i=new URL(window.location.href);i.searchParams.set("id",n),i.searchParams.set("viewMode","story"),window.location.href!==i.href&&(window.history.pushState({},"",i.href),window.dispatchEvent(new PopStateEvent("popstate"))),await new Promise(r=>{const c=setTimeout(()=>r(),o),l=()=>{clearTimeout(c),r()};window.addEventListener("storyrendered",l,{once:!0})})}})}catch(n){F.warn(`navigateToStoryViaMainWorld(${a}) failed`,n)}}async function Dr(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,i=document.title==="Ladle",r=!!document.querySelector('link[href*="ladle.css"]');return{detected:o&&(i||r),version:void 0}}})).find(o=>{var i;return(i=o.result)==null?void 0:i.detected});if(n)return{detected:!0,version:(t=n.result)==null?void 0:t.version,frameId:n.frameId}}catch(a){F.warn("ladle detection scripting failed",a)}return{detected:!1}}async function Bd(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 r=(await o.json()).stories??{};return Object.entries(r).map(([c,l])=>({id:c,name:l.name??c,kind:(l.levels??[]).join(" / ")}))}catch{return[]}}}))[0])==null?void 0:a.result)??[]}catch(n){return F.warn("listLadleStoriesViaMainWorld failed",n),[]}}async function Kd(e,t,a){try{await chrome.scripting.executeScript({target:{tabId:e,frameIds:[t]},world:"MAIN",args:[a,3e3],func:async(n,o)=>{const i=new URL(window.location.href);i.searchParams.set("story",n),window.location.href!==i.href&&(window.history.pushState({},"",i.href),window.dispatchEvent(new PopStateEvent("popstate"))),await new Promise(r=>setTimeout(r,Math.min(o,500)))}})}catch(n){F.warn(`navigateToLadleStoryViaMainWorld(${a}) failed`,n)}}async function Nr(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 Lr(e){const t=await Mr(e);if(t.detected)return{kind:"storybook",...t};const a=await Dr(e);return a.detected?{kind:"ladle",...a}:await Nr(e)?{kind:"bit",detected:!0}:{kind:null,detected:!1}}const Qt=200,Pr=6e4;function Zt(e,t){try{return new URL(e).origin===new URL(t).origin}catch{return!1}}function Fr(e,t){try{const a=new URL(e,t);return a.hash="",a.toString()}catch{return null}}async function _r(e,t,a){await chrome.tabs.update(e,{url:t}),await new Promise((n,o)=>{const i=setTimeout(()=>{chrome.tabs.onUpdated.removeListener(r),o(new Error(`navigation timeout (${a}ms): ${t}`))},a);function r(c,l){c===e&&l.status==="complete"&&(clearTimeout(i),chrome.tabs.onUpdated.removeListener(r),n())}chrome.tabs.onUpdated.addListener(r)}),await new Promise(n=>setTimeout(n,400))}async function Ur(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 F.debug("link discovery failed",a),[]}}async function Wr(e,t){var a,n;try{const i=new URL(t).pathname.toLowerCase().replace(/\/+$/,"");if(/(?:^|\/)(?:404|not-found|page-not-found|error|server-error)$/.test(i))return`URL path "${i||"/"}" matches a common error-route pattern.`}catch{}try{const o=await chrome.scripting.executeScript({target:{tabId:e},func:()=>document.title||""}),i=((n=(a=o==null?void 0:o[0])==null?void 0:a.result)==null?void 0:n.trim())??"";if(!i)return null;const r=[[/^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,l]of r)if(c.test(i))return`${l} (title: "${i.slice(0,80)}").`;return null}catch(o){return F.debug("error-page detection failed; proceeding with audit",o),null}}const bo=/Linked PDF at (\S+)\./;async function qr(e,t){if(!ue(t,"pdfAudit")){F.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 i of o.violations){if(i.ruleId!=="pdf-needs-cli-audit")continue;const r=bo.exec(i.description);if(!r)continue;const c=r[1];let l;try{l=new URL(c,n.url).href}catch{continue}if(!/^https?:\/\//i.test(l))continue;let d=a.get(l);d||(d=new Set,a.set(l,d)),d.add(n)}if(a.size!==0){F.info(`PDF audit pass: ${a.size} unique PDF(s) across the crawl`);for(const[n,o]of a){let i;try{i=await vc(n)}catch(r){F.warn(`PDF audit threw for ${n}`,r);continue}for(const r of o){const c=r.results[0];if(!c)continue;const l=c.componentId,d=c.state,u=i.findings.map(m=>yo(m,n,l,d));c.violations=c.violations.filter(m=>{if(m.ruleId!=="pdf-needs-cli-audit")return!0;const p=bo.exec(m.description);if(!p)return!0;try{return new URL(p[1],r.url).href!==n}catch{return!0}}),c.violations.push(...u),i.fatalError&&c.violations.push(yo({ruleId:"pdf-audit-skipped",impact:"minor",wcagCriterion:"1.1.1",description:`PDF audit skipped: ${i.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,l,d))}}}}function yo(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 Yd(e,t,a){if(await Fe())return z({type:"CRAWL_DISCOVERY_FAILED_EVENT",error:{code:St,message:ze,recoverable:!1}}),[];const n=await de();if(!ue(n,"siteCrawl"))return z({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 ht(),i=Ro(n).siteCrawlMaxPages,r=Number.isFinite(i)?Math.min(i,Qt):Qt,c=Math.min(t.maxPages??25,r),l=t.includeRegex?ea(t.includeRegex):null,d=t.excludeRegex?ea(t.excludeRegex):null,u=[e],m=new Set,p=[];try{for(;u.length>0&&p.length<c;){if(a.isCanceled()){F.info("crawl discovery canceled by user");break}const f=u.shift();if(!(!f||m.has(f))&&Zt(f,e)&&!(l&&!l.test(f))&&!(d&&d.test(f))){m.add(f);try{if(await _r(o,f,Pr),!(await Sn(o,0)).ok||await Wr(o,f))continue;p.push(f),z({type:"CRAWL_DISCOVERY_PROGRESS_EVENT",found:p.length,url:f});const y=await Ur(o);for(const b of y){const A=Fr(b,f);A&&Zt(A,e)&&!m.has(A)&&!u.includes(A)&&u.push(A)}}catch(g){F.debug("discovery: page navigation/link-read failed; skipping",g);continue}await $t({})}}return z({type:"CRAWL_DISCOVERY_COMPLETE_EVENT",urls:p}),p}catch(f){return F.error("crawl discovery failed",f),z({type:"CRAWL_DISCOVERY_FAILED_EVENT",error:{code:"CRAWL_DISCOVERY_FAILED",message:String(f),recoverable:!0}}),[]}}async function Jd(e,t,a){if(await Fe()){z({type:"SITE_CRAWL_FAILED_EVENT",error:{code:St,message:ze,recoverable:!1}});return}const n=await de();if(!ue(n,"siteCrawl")){z({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 ht(),i=Ro(n).siteCrawlMaxPages,r=Number.isFinite(i)?Math.min(i,Qt):Qt,c=Array.isArray(t.urls)&&t.urls.length>0,l=Math.min(c?t.urls.length:t.maxPages??25,r),d=t.includeRegex?ea(t.includeRegex):null,u=t.excludeRegex?ea(t.excludeRegex):null,m=new Date().toISOString(),p=Date.now(),f=c?[...t.urls]:[e],g=new Set,h=[];await Be({sessionId:Et(),mode:"storybook-all",scope:e,startedAt:m,lastProgressAt:new Date().toISOString(),state:"running"});try{for(;f.length>0&&g.size<l;){if(a.isCanceled()){F.info("site crawl canceled by user");break}const k=f.shift();if(!k||g.has(k)||!Zt(k,e)||d&&!d.test(k)||u&&u.test(k))continue;g.add(k);const x=g.size,w=Date.now();z({type:"SITE_CRAWL_PROGRESS_EVENT",current:x,total:Math.min(l,g.size+f.length),url:k,status:"auditing"});try{await _r(o,k,Pr);const R=await Sn(o,0);if(!R.ok)throw new Error(Qa(R));const T=await Wr(o,k);if(T){const S=`Skipped — page appears to be an error response. ${T}`;h.push({url:k,results:[],delta:null,componentId:k,durationMs:Date.now()-w,error:S}),z({type:"SITE_CRAWL_PROGRESS_EVENT",current:x,total:Math.min(l,g.size+f.length),url:k,status:"failed",error:S});continue}await ve(o,{type:"WARMUP_REQUEST"},0).catch(()=>{});const P=await it("html",a,0,void 0,{asSubroutine:!0,tabIdOverride:o,verifyFixesOnly:t.verifyFixesOnly}),_=P.results,N=P.ok?void 0:P.error,M=Date.now()-w;if(_.length>0){const S=await Ac(o,k).catch(()=>null),E=_.reduce((V,D)=>V+D.violations.length,0);h.push({url:k,results:_,delta:null,componentId:_[0].componentId,durationMs:M,snapshot:S??void 0}),z({type:"SITE_CRAWL_PROGRESS_EVENT",current:x,total:Math.min(l,g.size+f.length),url:k,status:"completed",violations:E})}else{const S=N??"audit returned no result";h.push({url:k,results:[],delta:null,componentId:k,durationMs:M,error:S}),z({type:"SITE_CRAWL_PROGRESS_EVENT",current:x,total:Math.min(l,g.size+f.length),url:k,status:"failed",error:S})}if(!c){const S=await Ur(o);for(const E of S){const V=Fr(E,k);V&&Zt(V,e)&&!g.has(V)&&!f.includes(V)&&f.push(V)}}}catch(R){const T=Date.now()-w,P=R instanceof Error?R.message:String(R);h.push({url:k,results:[],delta:null,componentId:k,durationMs:T,error:P}),z({type:"SITE_CRAWL_PROGRESS_EVENT",current:x,total:Math.min(l,g.size+f.length),url:k,status:"failed",error:P})}await $t({})}try{const k=await de();await qr(h,k)}catch(k){F.warn("PDF audit pass failed",k)}const y=new Date().toISOString(),b=Date.now()-p,A=h.flatMap(k=>k.results),v=await Re(A,[e]),s=pr(e,h,m,y,b,v.walkthroughsByComponent,v.walkthroughAcksByComponent,v.ackedKeysByComponent,v.humanVerdictsByComponent,v.incompleteResolutionsByComponent);if(s.consistencyFindings.length>0)try{const k=await Bc(s.consistencyFindings);s.consistencyFindings=k.emitted}catch(k){F.warn("consistency AI suppression failed; emitting heuristic findings",k)}try{const k=h.map(x=>({...x,results:x.results.map(({screenshotDataUrl:w,...R})=>R)}));await jo(k,{startUrl:e,finishedAt:y})}catch(k){const x=k instanceof Error?k.message:String(k);F.error("persisting siteCrawlPerUrlResults failed",k),z({type:"SITE_CRAWL_FAILED_EVENT",error:{code:"CRAWL_PERSIST_FAILED",message:`Crawl finished but persistence failed (${x}). The AI fix prompt export won't have per-page data.`,recoverable:!1}})}z({type:"SITE_CRAWL_COMPLETE_EVENT",report:s}),await nt()}catch(y){F.error("site crawl failed",y),z({type:"SITE_CRAWL_FAILED_EVENT",error:{code:"UNKNOWN",message:String(y),recoverable:!1}}),await nt()}}function ea(e){try{return new RegExp(e)}catch{return null}}async function Xd(){const[e,t]=await Promise.all([sn(),Gt()]);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(r=>r.results),n=await Re(a,[e.startUrl]),o=new Date().toISOString(),i=pr(e.startUrl,t,e.startedAt,o,e.totalDurationMs,n.walkthroughsByComponent,n.walkthroughAcksByComponent,n.ackedKeysByComponent,n.humanVerdictsByComponent,n.incompleteResolutionsByComponent);return await Vo(i),z({type:"SITE_CRAWL_COMPLETE_EVENT",report:i}),{ok:!0}}const Oa=5*6e4,wo=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…"},Qd={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 ta(e,t,a,n,o,i,r){const c=await de();if(!ue(c,"aiJudgment")){F.debug("aiJudgment not allowed on current tier — skipping AI augmentation");return}let l;try{l=await ve(e,{type:"AI_CANDIDATES_REQUEST",selector:t},a)}catch(M){F.debug("ai candidates fetch failed",M);return}const d=o[0];if(!d)return;const u={componentId:i,currentState:d.state,axeVersion:d.axeVersion},m={at:new Date().toISOString(),componentId:i,pageUrl:d.pageUrl??t,enabledChecks:n.enabledChecks,candidateCounts:{images:l.images.length,headings:l.headings.length,instructions:l.instructions.length,ariaElements:l.ariaElements.length,links:l.links.length,longTextBlocks:l.longTextBlocks.length,colorOnlyRegions:l.colorOnlyRegions.length,languageInfo:l.languageInfo?"present":"null"}};F.info("ai augmentation gate snapshot",JSON.stringify(m));try{await chrome.storage.local.set({aiDiagnosticLatest:m})}catch(M){F.warn("failed to persist ai diagnostic to storage.local",M)}const p=[];if(n.enabledChecks.altText&&p.push({key:"altText",run:M=>{const S=l.images.map(E=>({imageUrl:E.imageUrl,alt:E.alt,selector:E.selector,outerHTML:E.outerHTML,surroundingContext:E.surroundingContext,...u}));return Cl(S,n,M)}}),n.enabledChecks.headings&&p.push({key:"headings",run:M=>vd(l.headings,u,n,M)}),n.enabledChecks.sensory&&p.push({key:"sensory",run:M=>Ad(l.instructions,u,n,M)}),n.enabledChecks.aria&&p.push({key:"aria",run:M=>kd(l.ariaElements,u,n,M)}),n.enabledChecks.imageOfText&&p.push({key:"imageOfText",run:M=>{const S=l.images.map(E=>({imageUrl:E.imageUrl,accessibleName:E.alt||void 0,selector:E.selector,outerHTML:E.outerHTML,pixelArea:E.pixelArea}));return Cd(S,u,n,M)}}),n.enabledChecks.colorOnlyMeaning&&p.push({key:"colorOnlyMeaning",run:M=>Td(l.colorOnlyRegions,u,n,M)}),n.enabledChecks.genericLinkText&&p.push({key:"genericLinkText",run:M=>Id(l.links,u,n,M)}),n.enabledChecks.wallOfText&&p.push({key:"wallOfText",run:M=>xd(l.longTextBlocks,u,n,M)}),n.enabledChecks.languageMismatch){const M=l.languageInfo;p.push({key:"languageMismatch",run:S=>Sd(M?[M]:[],u,n,S)})}if(p.length===0)return;let f=0,g=0,h=!1;const y={};let b=0,A=0,v=0;const s=[];let k=!1,x=!1;function w(M,S){if(y[M]=(y[M]??0)+S.totalCostUsd,f+=S.totalCostUsd,g+=S.findings.length,h=h||S.capExceeded,b++,S.errors.length>0){v++;for(const E of S.errors)s.includes(E)||s.push(E)}else A++;F.info(`ai ${M}: ${S.findings.length} findings, $${S.totalCostUsd.toFixed(4)}, errs=${S.errors.length}`),S.capExceeded&&F.warn(`ai cost cap exceeded after $${S.totalCostUsd.toFixed(4)} during ${M}`)}const R=(async()=>{for(let M=0;M<p.length;M++){if(r!=null&&r.isCanceled()){x=!0;break}const S=p[M];z({type:"AI_AUGMENTATION_PROGRESS_EVENT",componentId:i,currentCheck:S.key,currentCheckLabel:vo[S.key],current:M+1,total:p.length});const E=new AbortController,V=setTimeout(()=>E.abort(),wo),D=r?setInterval(()=>{r.isCanceled()&&E.abort()},500):null;let $;try{$=await S.run({signal:E.signal,onProgress:(U,q)=>{q>0&&z({type:"AI_AUGMENTATION_PROGRESS_EVENT",componentId:i,currentCheck:S.key,currentCheckLabel:vo[S.key],current:M+1,total:p.length,candidatesDone:U,candidatesTotal:q})}}),E.signal.aborted&&(r!=null&&r.isCanceled())?$.errors=[...$.errors,`${S.key} canceled by user`]:E.signal.aborted}catch(U){const q=U instanceof Error?U.message:String(U),Y=E.signal.aborted,Z=Y&&(r!=null&&r.isCanceled())?`${S.key} canceled by user`:Y?`${S.key} hit per-check ${wo/1e3}s cap — analyzer aborted`:`${S.key} threw: ${q}`;$={findings:[],totalCostUsd:0,capExceeded:!1,errors:[Z]}}finally{clearTimeout(V),D&&clearInterval(D)}if($.findings.length>0&&(d.violations=[...d.violations,...$.findings]),$.errors.length===0){const U=Qd[S.key];if(U&&U.length>0&&d.axeRulesEvaluated)for(const q of U)d.axeRulesEvaluated.passed.push({ruleId:`ai-${S.key}-coverage`,wcagCriterion:q})}w(S.key,$)}})(),T=new Promise(M=>{setTimeout(()=>M("timeout"),Oa)});await Promise.race([R.then(()=>"done"),T])==="timeout"&&(k=!0,F.warn(`ai augmentation hit global ${Oa/1e3}s timeout after ${b}/${p.length} checks`));let _;if(v>0||k||x){k?_=`AI augmentation timed out after ${Oa/1e3}s`:x?_="AI augmentation canceled":_=s[0]??"AI analyzer error";const M=A===0?"total":"partial";z({type:"AI_AUGMENTATION_FAILED_EVENT",componentId:i,severity:M,reason:_,checksAttempted:b,checksSucceeded:A,checksErrored:v,errorDetails:k||x?[_,...s.slice(0,4)]:s.slice(0,5)}),F.warn(`ai augmentation ${M} failure: ${v}/${b} checks errored — ${_}`)}(f>0||g>0||_)&&await bi({at:new Date().toISOString(),pageUrl:d.pageUrl??t,componentId:i,totalCostUsd:f,byCheck:y,findingsCount:g,capExceeded:h,failureReason:_})}const oh=Object.freeze(Object.defineProperty({__proto__:null,auditCrawlPdfs:qr,detectBit:Nr,detectLadleAcrossFrames:Dr,detectPlayground:Lr,detectStorybookAcrossFrames:Mr,discoverCrawlUrls:Yd,getActiveTabId:ht,getMatrixSettings:Cn,regradeSiteCrawl:Xd,runAiAugmentation:ta,runAllFramesAudit:jd,runParallelScan:Gd,runSingleElementAudit:it,runSiteCrawl:Jd,runStorybookAllAudit:Vd},Symbol.toStringTag,{value:"Module"})),wt=ee("alert-sender"),Zd="wcagcheckr",eu="https://api.wcagcheckr.com",tu=`${eu}/v1/products/${Zd}/alerts/send`,au=1e4,Za="alertConfig:v1",nu={emailEnabled:!1,webhookEnabled:!1,webhookUrl:"",minImpact:"serious"},Ut={minor:1,moderate:2,serious:3,critical:4};async function ou(){const t=(await chrome.storage.local.get(Za))[Za];return{...nu,...t??{}}}async function rh(e){await chrome.storage.local.set({[Za]:e})}async function ru(e){let t;try{t=await ou()}catch(g){return wt.warn("failed to read alert config",g),{fired:!1,reason:"config_read_failed"}}if(!t.emailEnabled&&!t.webhookEnabled)return{fired:!1,reason:"no_channel_enabled"};const a=await de(),n=ue(a,"emailAlerts"),o=ue(a,"webhookAlerts"),i=t.emailEnabled&&n,r=t.webhookEnabled&&o;if(!i&&!r)return{fired:!1,reason:"no_channel_enabled"};const c=[];for(const g of e.results){const h=g.delta;h!=null&&h.new&&c.push(...h.new)}const l=Ut[t.minImpact],d=c.filter(g=>Ut[g.impact]>=l);if(d.length===0)return{fired:!1,reason:"below_impact_threshold"};const u=await an();if(!u)return wt.debug("no license token; alert skipped"),{fired:!1,reason:"no_license_token"};d.sort((g,h)=>Ut[h.impact]-Ut[g.impact]);const m=d.slice(0,10).map(g=>({wcag:g.wcagCriterion,impact:g.impact,selector:g.target.selector,help:g.description.slice(0,480),helpUrl:g.helpUrl})),p=e.results.reduce((g,h)=>g+h.violations.length,0),f={token:u,scheduleId:e.scheduleId,auditedUrl:e.auditedUrl,totalViolations:p,newViolationCount:d.length,topViolations:m,webhookUrl:r&&t.webhookUrl?t.webhookUrl:void 0,emailEnabled:i,ranAt:e.ranAt};try{const g=await fetch(tu,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(f),signal:AbortSignal.timeout(au)}),h=await g.json().catch(()=>null);return g.ok?(wt.info("alert delivered",{emailSent:h==null?void 0:h.emailSent,webhookSent:h==null?void 0:h.webhookSent}),{fired:!0,emailSent:(h==null?void 0:h.emailSent)??!1,webhookSent:(h==null?void 0:h.webhookSent)??!1,serverStatus:g.status}):(wt.warn(`alert server returned ${g.status}`,h),{fired:!1,reason:`server_${g.status}`,serverStatus:g.status})}catch(g){return wt.warn("alert send failed",g),{fired:!1,reason:g instanceof Error?g.message:"unknown_error"}}}const iu="#dc2626",su="#f59e0b",cu="#059669",lu="#94a3b8";function du(e){const t=e.filter(c=>c.enabled);let a=0,n=0,o=0,i=0;for(const c of t){const l=c.lastNewViolationCount??0;c.lastResult==="failed"?n++:c.lastResult==="ok"?l>0?a+=l:o++:i++}let r;return t.length===0?r="no-schedules":a>0?r="new-violations":n>0?r="failed":o>0?r="all-clear":r="pending-first-run",{state:r,newViolationsTotal:a,failingCount:n,okCount:o,pendingCount:i,totalEnabled:t.length}}async function uu(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:iu}),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:su}),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:cu}),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:lu}),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 pu(){const e=await de();if(!ue(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 _o(),a=du(t);try{await uu(a)}catch(n){console.warn("[status-badge] failed to apply",n)}return a}const Ao=ee("deposition-packet"),Vr="https://api.wcagcheckr.com/verify";function te(e){return e.replace(/[&<>"']/g,t=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[t])}function hu(e,t,a){if(!e)return`<section class="dp-cover dp-cover-error">
|
|
955
|
+
`;await chrome.debugger.sendCommand({tabId:e},"Runtime.evaluate",{expression:t})}async function uo(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 tt.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(l=>l.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 tt.warn(`clip decode failed: ${n instanceof Error?n.message:String(n)}`),null}}const ud=25,Si=8,pd=150,hd=.95,fd=4,gd=400;function md(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 k=(v*n+s)*4,x=t.data[k],w=t.data[k+1],R=t.data[k+2],T=e.data[k],P=e.data[k+1],_=e.data[k+2],N=Math.abs(T-x)+Math.abs(P-w)+Math.abs(_-R);N>i&&(i=N),N>=ud&&r++}if(r<Si)return null;const c=i*hd;let l=0,d=0,u=0,m=0;if(i>=gd)for(let v=0;v<o;v++)for(let s=0;s<n;s++){const k=(v*n+s)*4,x=t.data[k],w=t.data[k+1],R=t.data[k+2],T=e.data[k],P=e.data[k+1],_=e.data[k+2];Math.abs(T-x)+Math.abs(P-w)+Math.abs(_-R)>=c&&(l+=x,d+=w,u+=R,m++)}const p=m>=fd?{r:Math.round(l/m),g:Math.round(d/m),b:Math.round(u/m)}:a,f=new Map;let g=0;for(let v=0;v<o;v++)for(let s=0;s<n;s++){const k=(v*n+s)*4,x=t.data[k],w=t.data[k+1],R=t.data[k+2];if(Math.abs(x-p.r)+Math.abs(w-p.g)+Math.abs(R-p.b)>=pd){g++;const P=x>>4<<8|w>>4<<4|R>>4,_=f.get(P);_?(_.r+=x,_.g+=w,_.b+=R,_.count++):f.set(P,{r:x,g:w,b:R,count:1})}}const h=n*o;if(g<h*.2){f.clear();for(let v=0;v<o;v++)for(let s=0;s<n;s++){const k=(v*n+s)*4,x=e.data[k],w=e.data[k+1],R=e.data[k+2],T=x>>4<<8|w>>4<<4|R>>4,P=f.get(T);P?(P.r+=x,P.g+=w,P.b+=R,P.count++):f.set(T,{r:x,g:w,b:R,count:1})}}let y={r:0,g:0,b:0,count:0};for(const v of f.values())v.count>y.count&&(y=v);const b={r:Math.round(y.r/y.count),g:Math.round(y.g/y.count),b:Math.round(y.b/y.count)},A=In(p,b);return{textPixelCount:r,worstRatio:A,worstBackground:b,worstForeground:p}}async function bd(e,t,a){var l,d,u,m,p;const n=new Map;for(const f of t){const g=f.pageUrl??f.scope??"";for(const h of((l=f.axeRulesEvaluated)==null?void 0:l.incomplete)??[])if(h.ruleId==="color-contrast")for(const y of h.elements??[]){const b=`${g}::${h.ruleId}::${y.selector}`;n.has(b)||n.set(b,{pageUrl:g,ruleId:h.ruleId,selector:y.selector,wcagCriterion:h.wcagCriterion??"1.4.3",foreground:(d=y.styles)==null?void 0:d.foreground,fontSize:(u=y.styles)==null?void 0:u.fontSize,fontWeight:(m=y.styles)==null?void 0:m.fontWeight,failureSummary:y.failureSummary})}}if(n.size===0)return{resolved:0,skipped:0};let o=!1,r=null;for(let f=1;f<=6;f++)try{await chrome.debugger.attach({tabId:e},ad),o=!0;break}catch(g){r=g;const h=g instanceof Error?g.message:String(g);if(/already attached/i.test(h)){await new Promise(y=>setTimeout(y,500));continue}break}if(!o)return tt.warn("debugger attach failed after retries; skipping pixel sampling",r),{resolved:0,skipped:n.size};let i=0,c=0;try{const f=Array.from(n.values()),g=f.map(w=>w.selector),h=await cd(e,g);if(a!=null&&a.aborted)return{resolved:0,skipped:n.size};const y=((p=f[0])==null?void 0:p.pageUrl)??"",b=y?await dn(y):[],A=new Map;for(const w of b)A.set(`${w.ruleId}::${w.selector}`,w);const v=new Map,s=[];for(const w of f){const R=await td(w);v.set(w.selector,R);const T=A.get(`${w.ruleId}::${w.selector}`);if(T&&T.inputHash===R&&T.verdict!=="uncertain"){const P={...T,resolvedAt:new Date().toISOString(),reasoning:T.reasoning.includes("(cached, hash-match)")?T.reasoning:`${T.reasoning} (cached, hash-match)`};await qe(P),i++;continue}s.push(w)}if(s.length===0)return tt.info(`pixel-contrast sampler: all ${f.length} targets reused from hash-cache`),{resolved:i,skipped:c};await ld(e);const k=new Map;for(const w of s){if(a!=null&&a.aborted)break;const R=h.get(w.selector);if(!R)continue;const T=await uo(e,R);T&&k.set(w.selector,T)}if(await dd(e),a!=null&&a.aborted)return{resolved:0,skipped:n.size};const x=new Map;for(const w of s){if(a!=null&&a.aborted)break;const R=h.get(w.selector);if(!R)continue;const T=await uo(e,R);T&&x.set(w.selector,T)}for(const w of s){if(a!=null&&a.aborted)break;const R=v.get(w.selector),T=h.get(w.selector);if(!T){c++;const q={pageUrl:w.pageUrl,ruleId:w.ruleId,selector:w.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:w.wcagCriterion,inputHash:R};await qe(q);continue}const P=k.get(w.selector),_=x.get(w.selector);if(!P||!_){c++;const q={pageUrl:w.pageUrl,ruleId:w.ruleId,selector:w.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:w.wcagCriterion,inputHash:R};await qe(q);continue}const N=rd(w.foreground);if(!N){c++;const q={pageUrl:w.pageUrl,ruleId:w.ruleId,selector:w.selector,verdict:"uncertain",reasoning:`Hide-text observation: element's computed CSS foreground color could not be parsed (got ${JSON.stringify(w.foreground)}). Cannot compute contrast against rendered background without an intended foreground color. Manual verification required.`,resolvedAt:new Date().toISOString(),costUsd:0,wcagCriterion:w.wcagCriterion,inputHash:R};await qe(q);continue}const M=md(P,_,N);if(!M){c++;const q={pageUrl:w.pageUrl,ruleId:w.ruleId,selector:w.selector,verdict:"uncertain",reasoning:`Hide-text observation: too few text pixels detected (under ${Si} after diffing hidden vs visible captures). Element may be canvas-rendered, SVG with non-standard rendering, or carry styles that prevent color: transparent from hiding the text. Manual verification required.`,resolvedAt:new Date().toISOString(),costUsd:0,wcagCriterion:w.wcagCriterion,inputHash:R};await qe(q);continue}const S=id(w.fontSize,w.fontWeight),E=S?od:nd,V=q=>`rgb(${q.r},${q.g},${q.b})`;let D=M.worstRatio>=E,$="";if(sd(M.worstRatio,N,T.resolvedBg,E)){const q=In(N,T.resolvedBg);D=!0,$=` Cross-check (rc.356): computed CSS contrast ${V(N)} on resolved background ${V(T.resolvedBg)} = ${q.toFixed(2)}:1, which PASSES ${E}:1 — the sub-threshold pixel reading is an anti-aliasing/sampling artifact, not a real failure. Suppressed.`}const U={pageUrl:w.pageUrl,ruleId:w.ruleId,selector:w.selector,verdict:D?"pass":"fail",reasoning:`Hide-text observation: ${M.textPixelCount} text-core pixels detected by diffing hidden-vs-visible viewport screenshots. Worst per-pixel contrast: ${M.worstRatio.toFixed(2)}:1 against AA threshold ${E}:1 (${S?"large text":"normal text"}). At worst pixel: rendered foreground ${V(M.worstForeground)} on rendered background ${V(M.worstBackground)}. ${D&&$?"Passes (computed cross-check).":D?"Passes threshold.":"Falls below threshold — at least one text pixel reads against a background that fails contrast."}`+$,resolvedAt:new Date().toISOString(),costUsd:0,wcagCriterion:w.wcagCriterion,inputHash:R};await qe(U),i++}}finally{try{await chrome.debugger.sendCommand({tabId:e},"Runtime.evaluate",{expression:`(() => { const el = document.getElementById(${JSON.stringify(xn)}); if (el) el.remove(); return true; })()`})}catch{}try{await chrome.debugger.detach({tabId:e})}catch{}}return tt.info(`pixel-contrast sampler: resolved ${i}, skipped ${c}/${n.size}`),{resolved:i,skipped:c}}const lt=ee("ai-text");function dt(e){if(e!=null&&e.aborted){const t=new Error("aborted");throw t.name="AbortError",t}}function ut(e){return e instanceof Error&&(e.name==="AbortError"||e.name==="ExternalAbortError"||e.message==="aborted")}async function yd(e,t,a,n={}){var p;if(!a.enabled||!a.enabledChecks.headings)return{findings:[],totalCostUsd:0,capExceeded:!1,errors:[]};const o=ue(a);if(!o.ok)return{findings:[],totalCostUsd:0,capExceeded:!1,errors:[`AI client unavailable: ${o.reason}`]};const r=o.client,i=Ee(a.costCapUsd),c=[],l=[],d=Math.max(1,a.maxCandidatesPerCheck??10),u=e.slice(0,d),m=u.length;for(let f=0;f<u.length;f++){const g=u[f];if(!i.canCharge())break;try{dt(n.signal);const h=await r.judgeHeading({headingText:g.text,sectionContent:g.sectionContent,signal:n.signal});i.recordCharge(h.costUsd),h.verdict==="fail"&&h.confidence>=.6&&c.push(await pt("ai-heading-not-descriptive","2.4.6","AA","moderate","AI judged this heading does not describe its section content.",g.selector,g.outerHTML,g.text,h,t))}catch(h){if(ut(h)){l.push(`canceled after ${f}/${m} candidates`);break}const y=h instanceof Error?h.message:String(h);l.push(`${g.selector}: ${y}`),lt.warn("heading judgment failed",h)}(p=n.onProgress)==null||p.call(n,f+1,m)}return{findings:c,totalCostUsd:i.state.spentUsd,capExceeded:i.state.exceeded,errors:l}}async function wd(e,t,a,n={}){var p;if(!a.enabled||!a.enabledChecks.sensory)return{findings:[],totalCostUsd:0,capExceeded:!1,errors:[]};const o=ue(a);if(!o.ok)return{findings:[],totalCostUsd:0,capExceeded:!1,errors:[`AI client unavailable: ${o.reason}`]};const r=o.client,i=Ee(a.costCapUsd),c=[],l=[],d=Math.max(1,a.maxCandidatesPerCheck??10),u=e.slice(0,d),m=u.length;for(let f=0;f<u.length;f++){const g=u[f];if(!i.canCharge())break;try{dt(n.signal);const h=await r.judgeSensoryLanguage({instructionText:g.text,signal:n.signal});i.recordCharge(h.costUsd),h.verdict==="fail"&&h.confidence>=.6&&c.push(await pt("ai-sensory-instruction","1.3.3","A","serious","AI flagged this instruction as relying on sensory characteristics (shape, color, location) without a programmatic identifier.",g.selector,g.outerHTML,g.text.slice(0,100),h,t))}catch(h){if(ut(h)){l.push(`canceled after ${f}/${m} candidates`);break}const y=h instanceof Error?h.message:String(h);l.push(`${g.selector}: ${y}`),lt.warn("sensory judgment failed",h)}(p=n.onProgress)==null||p.call(n,f+1,m)}return{findings:c,totalCostUsd:i.state.spentUsd,capExceeded:i.state.exceeded,errors:l}}async function vd(e,t,a,n={}){var p;if(!a.enabled||!a.enabledChecks.aria)return{findings:[],totalCostUsd:0,capExceeded:!1,errors:[]};const o=ue(a);if(!o.ok)return{findings:[],totalCostUsd:0,capExceeded:!1,errors:[`AI client unavailable: ${o.reason}`]};const r=o.client,i=Ee(a.costCapUsd),c=[],l=[],d=Math.max(1,a.maxCandidatesPerCheck??10),u=e.slice(0,d),m=u.length;for(let f=0;f<u.length;f++){const g=u[f];if(!i.canCharge())break;try{dt(n.signal);const h=await r.judgeAriaSemantics({elementHtml:g.outerHTML,computedRole:g.role,surroundingHtml:g.surroundingHtml,signal:n.signal});i.recordCharge(h.costUsd),h.verdict==="fail"&&h.confidence>=.65&&c.push(await pt("ai-aria-misuse","4.1.2","A","serious",`AI judged role="${g.role}" is being used inappropriately on this element.`,g.selector,g.outerHTML,g.role,h,t))}catch(h){if(ut(h)){l.push(`canceled after ${f}/${m} candidates`);break}const y=h instanceof Error?h.message:String(h);l.push(`${g.selector}: ${y}`),lt.warn("aria judgment failed",h)}(p=n.onProgress)==null||p.call(n,f+1,m)}return{findings:c,totalCostUsd:i.state.spentUsd,capExceeded:i.state.exceeded,errors:l}}async function Ad(e,t,a,n={}){var p;if(!a.enabled||!a.enabledChecks.genericLinkText)return{findings:[],totalCostUsd:0,capExceeded:!1,errors:[]};const o=ue(a);if(!o.ok)return{findings:[],totalCostUsd:0,capExceeded:!1,errors:[`AI client unavailable: ${o.reason}`]};const r=o.client,i=Ee(a.costCapUsd),c=[],l=[],d=Math.max(1,a.maxCandidatesPerCheck??10),u=e.slice(0,d),m=u.length;for(let f=0;f<u.length;f++){const g=u[f];if(!i.canCharge())break;try{dt(n.signal);const h=await r.judgeGenericLinkText({linkText:g.linkText,surroundingText:g.surroundingText,signal:n.signal});i.recordCharge(h.costUsd),h.verdict==="fail"&&h.confidence>=.6&&c.push(await pt("ai-generic-link-text","2.4.4","A","serious","AI judged this link's purpose is not clear from its text or surrounding context.",g.selector,g.outerHTML,g.linkText,h,t))}catch(h){if(ut(h)){l.push(`canceled after ${f}/${m} candidates`);break}const y=h instanceof Error?h.message:String(h);l.push(`${g.selector}: ${y}`),lt.warn("generic-link judgment failed",h)}(p=n.onProgress)==null||p.call(n,f+1,m)}return{findings:c,totalCostUsd:i.state.spentUsd,capExceeded:i.state.exceeded,errors:l}}async function kd(e,t,a,n={}){var p;if(!a.enabled||!a.enabledChecks.wallOfText)return{findings:[],totalCostUsd:0,capExceeded:!1,errors:[]};const o=ue(a);if(!o.ok)return{findings:[],totalCostUsd:0,capExceeded:!1,errors:[`AI client unavailable: ${o.reason}`]};const r=o.client,i=Ee(a.costCapUsd),c=[],l=[],d=Math.max(1,a.maxCandidatesPerCheck??10),u=e.slice(0,d),m=u.length;for(let f=0;f<u.length;f++){const g=u[f];if(!i.canCharge())break;try{dt(n.signal);const h=await r.judgeWallOfText({blockText:g.blockText,structuralChildrenCount:g.structuralChildrenCount,signal:n.signal});i.recordCharge(h.costUsd),h.verdict==="fail"&&h.confidence>=.6&&c.push(await pt("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).",g.selector,g.outerHTML,g.blockText.slice(0,80),h,t))}catch(h){if(ut(h)){l.push(`canceled after ${f}/${m} candidates`);break}const y=h instanceof Error?h.message:String(h);l.push(`${g.selector}: ${y}`),lt.warn("wall-of-text judgment failed",h)}(p=n.onProgress)==null||p.call(n,f+1,m)}return{findings:c,totalCostUsd:i.state.spentUsd,capExceeded:i.state.exceeded,errors:l}}async function Id(e,t,a,n={}){var p;if(!a.enabled||!a.enabledChecks.languageMismatch)return{findings:[],totalCostUsd:0,capExceeded:!1,errors:[]};const o=ue(a);if(!o.ok)return{findings:[],totalCostUsd:0,capExceeded:!1,errors:[`AI client unavailable: ${o.reason}`]};const r=o.client,i=Ee(a.costCapUsd),c=[],l=[],d=Math.max(1,a.maxCandidatesPerCheck??10),u=e.slice(0,d),m=u.length;for(let f=0;f<u.length;f++){const g=u[f];if(!i.canCharge())break;try{dt(n.signal);const h=await r.judgeLanguageMismatch({declaredLang:g.declaredLang,bodyTextSample:g.bodyTextSample,signal:n.signal});i.recordCharge(h.costUsd),h.verdict==="fail"&&h.confidence>=.7&&c.push(await pt("ai-language-mismatch","3.1.1","A","serious",`AI judged the page's content does not match the declared lang="${g.declaredLang||"(none)"}".`,g.selector,g.outerHTML,g.bodyTextSample.slice(0,80),h,t))}catch(h){if(ut(h)){l.push(`canceled after ${f}/${m} candidates`);break}const y=h instanceof Error?h.message:String(h);l.push(`${g.selector}: ${y}`),lt.warn("language-mismatch judgment failed",h)}(p=n.onProgress)==null||p.call(n,f+1,m)}return{findings:c,totalCostUsd:i.state.spentUsd,capExceeded:i.state.exceeded,errors:l}}async function pt(e,t,a,n,o,r,i,c,l,d){const u={selector:r,outerHTML:i.slice(0,500),failureSummary:`AI assessment: ${l.reasoning}`,tagName:"AI",role:null,accessibleName:null,textSnippet:c.slice(0,100)||null,attrId:null,attrTestid:null},m=await tn({ruleId:e,componentId:d.componentId,currentState:d.currentState,target:u});return{ruleId:e,wcagCriterion:t,wcagLevel:a,impact:n,description:o,helpUrl:"https://www.w3.org/WAI/WCAG21/Understanding/",target:u,componentId:d.componentId,currentState:d.currentState,axeVersion:d.axeVersion,detectedAt:new Date().toISOString(),matchKey:m,ai:{reasoning:l.reasoning,confidence:l.confidence,model:l.model,costUsd:l.costUsd}}}const Ci=ee("ai-vision");function Ti(e){if(e!=null&&e.aborted){const t=new Error("aborted");throw t.name="AbortError",t}}function $i(e){return e instanceof Error&&(e.name==="AbortError"||e.name==="ExternalAbortError"||e.message==="aborted")}async function xd(e,t,a,n={}){var p;if(!a.enabled||!a.enabledChecks.imageOfText)return{findings:[],totalCostUsd:0,capExceeded:!1,errors:[]};const o=ue(a);if(!o.ok)return{findings:[],totalCostUsd:0,capExceeded:!1,errors:[`AI client unavailable: ${o.reason}`]};const r=o.client,i=Ee(a.costCapUsd),c=Math.max(1,a.imageOfTextMaxImages??5),l=[...e].sort((f,g)=>g.pixelArea-f.pixelArea).slice(0,c),d=l.length,u=[],m=[];for(let f=0;f<l.length;f++){const g=l[f];if(!i.canCharge())break;try{Ti(n.signal);const h=await r.judgeImageOfText({imageUrl:g.imageUrl,accessibleName:g.accessibleName,signal:n.signal});i.recordCharge(h.costUsd),h.verdict==="fail"&&h.confidence>=.65&&u.push(await Ei("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.",g.selector,g.outerHTML,g.accessibleName??"",h,t))}catch(h){if($i(h)){m.push(`canceled after ${f}/${d} candidates`);break}const y=h instanceof Error?h.message:String(h);m.push(`${g.selector}: ${y}`),Ci.warn("image-of-text judgment failed",h)}(p=n.onProgress)==null||p.call(n,f+1,d)}return{findings:u,totalCostUsd:i.state.spentUsd,capExceeded:i.state.exceeded,errors:m}}async function Sd(e,t,a,n={}){var p;if(!a.enabled||!a.enabledChecks.colorOnlyMeaning)return{findings:[],totalCostUsd:0,capExceeded:!1,errors:[]};const o=ue(a);if(!o.ok)return{findings:[],totalCostUsd:0,capExceeded:!1,errors:[o.reason]};const r=o.client,i=Ee(a.costCapUsd),c=[],l=[],d=Math.max(1,a.maxCandidatesPerCheck??10),u=e.slice(0,d),m=u.length;for(let f=0;f<u.length;f++){const g=u[f];if(!i.canCharge())break;try{Ti(n.signal);const h=await r.judgeColorOnlyMeaning({elementHtml:g.elementHtml,contextDescription:g.contextDescription,signal:n.signal});i.recordCharge(h.costUsd),h.verdict==="fail"&&h.confidence>=.65&&c.push(await Ei("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).",g.selector,g.outerHTML,g.contextDescription,h,t))}catch(h){if($i(h)){l.push(`canceled after ${f}/${m} candidates`);break}const y=h instanceof Error?h.message:String(h);l.push(y),Ci.warn("color-only judgment failed",h)}(p=n.onProgress)==null||p.call(n,f+1,m)}return{findings:c,totalCostUsd:i.state.spentUsd,capExceeded:i.state.exceeded,errors:l}}async function Ei(e,t,a,n,o,r,i,c,l,d){const u={selector:r,outerHTML:i.slice(0,500),failureSummary:`AI assessment: ${l.reasoning}`,tagName:"AI",role:null,accessibleName:null,textSnippet:c.slice(0,100)||null,attrId:null,attrTestid:null},m=await tn({ruleId:e,componentId:d.componentId,currentState:d.currentState,target:u});return{ruleId:e,wcagCriterion:t,wcagLevel:a,impact:n,description:o,helpUrl:"https://www.w3.org/WAI/WCAG21/Understanding/",target:u,componentId:d.componentId,currentState:d.currentState,axeVersion:d.axeVersion,detectedAt:new Date().toISOString(),matchKey:m,ai:{reasoning:l.reasoning,confidence:l.confidence,model:l.model,costUsd:l.costUsd}}}const Xa=ee("ensure-content-script"),Cd=1500,Td=300;async function Sn(e,t){if(await po(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 Xa.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 $d(o)}return await Ed(Td),await po(e,t)?(Xa.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 po(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")),Cd))]);return(n==null?void 0:n.type)==="PING_RESPONSE"}catch{return!1}}function $d(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}:(Xa.warn("content-script injection failed",e),{ok:!1,reason:"inject-failed",detail:t})}function Ed(e){return new Promise(t=>setTimeout(t,e))}function Qa(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 Ea=ee("forensic-anchor-client"),Rd="https://api.wcagcheckr.com",Od="wcagcheckr",Md=15e3;function Dd(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 Ri(e,t){const a={auditHash:e.hash,pageUrl:e.pageUrl,capturedAt:e.capturedAt,...t?{licenseId:t}:{}},n=`${Rd}/v1/products/${Od}/forensic/anchor`;try{const o=await fetch(n,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(a),signal:AbortSignal.timeout(Md)});if(!o.ok)return Ea.warn(`anchor HTTP ${o.status}; entry stays local-only`),null;const r=await o.json();return Dd(r)?r:(Ea.warn("anchor returned malformed receipt; entry stays local-only",r),null)}catch(o){return Ea.warn("anchor request failed; entry stays local-only",o),null}}const ho="4.11.4";async function Nd(e){try{return(await chrome.tabs.get(e)).url??""}catch{return""}}const F=ee("flows");async function ht(){const e=await Go();if(!e)throw new Error("no audit target tab found");return e}async function Cn(){var a,n,o,r,i;const e=await Ve("stateMatrix",Na);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:(F.warn("stored stateMatrix is invalid; using defaults"),Na)}async function Ld(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 ve(e,{type:"THEME_AWARENESS_REQUEST"},a)}catch{return t}return!r||r.hasUnreadableSheets?t:r.hasDarkModeCss&&!r.hasLightModeCss?(F.info("theme-axis prune: site is dark-only, skipping light pass"),{...t,themes:t.themes.filter(i=>i!=="light")}):r.hasLightModeCss&&!r.hasDarkModeCss?(F.info("theme-axis prune: site is light-only, skipping dark pass"),{...t,themes:t.themes.filter(i=>i!=="dark")}):t}const Pd=200,Ra=3,fo=8;async function Fd(e,t){const a=[];let n=null,o=null;for(let i=0;i<fo&&!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>=Ra){const l=a.slice(-Ra);if(_d(l))return{violations:l[l.length-1],lastResult:n,sampleCount:a.length,stabilized:!0,lastError:o}}i<fo-1&&await new Promise(l=>setTimeout(l,Pd))}const r=a.slice(-Ra);return{violations:Ud(r),lastResult:n,sampleCount:a.length,stabilized:!1,lastError:o}}function _d(e){if(e.length<2)return!0;const t=go(e[0]);for(let a=1;a<e.length;a++){const n=go(e[a]);if(n.size!==t.size)return!1;for(const o of t)if(!n.has(o))return!1}return!0}function go(e){return new Set(e.map(t=>`${t.ruleId}::${t.target.selector}::${t.matchKey}`))}function Ud(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 mo(e,t,a,n,o){await Promise.all([(async()=>{var r;try{const i=await ve(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){F.debug("reading-order analysis skipped",i)}})(),(async()=>{var r;try{const i=await ve(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){F.debug("tab-order analysis skipped",i)}})(),(async()=>{var r;try{const i=await ve(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){F.debug("typography analysis skipped",i)}})(),(async()=>{try{const r=await ve(e,{type:"CUSTOM_PROPERTY_REQUEST"},a);r.undefined.length>0&&n[0]&&(n[0].undefinedCustomProperties=r.undefined)}catch(r){F.debug("custom-property analysis skipped",r)}})()])}async function rt(e,t,a,n,o={}){var _,N,M;const r=o.asSubroutine===!0;if(await Fe())return r||z({type:"AUDIT_FAILED_EVENT",error:{code:St,message:ze,recoverable:!1}}),{ok:!1,results:[],error:ze};const i=o.tabIdOverride??await ht(),c=await Sn(i,a);if(!c.ok)return r||z({type:"AUDIT_FAILED_EVENT",error:{code:c.reason==="restricted-url"?"RESTRICTED_URL":"CONTENT_SCRIPT_UNREACHABLE",message:Qa(c),recoverable:c.reason!=="restricted-url"}}),{ok:!1,results:[],error:Qa(c)};try{await chrome.scripting.executeScript({target:{tabId:i,frameIds:a!==void 0?[a]:void 0},world:"MAIN",func:()=>{try{let S=document.getElementById("__wcagcheckr_audit_freeze");S||(S=document.createElement("style"),S.id="__wcagcheckr_audit_freeze",S.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(S)),window.scrollTo(0,0);const E=document.activeElement;E&&E instanceof HTMLElement&&E!==document.body&&E.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(S){F.debug("audit-start state stabilization failed (non-fatal)",S)}const l=n??await Cn(),d=await Ld(i,l,a),u=Hc(d),m=await ur(`${await Nd(i)}|${e}|${a??0}`),p=await pr(d),f=await Ve("axeDisabledRules",[]),g=await hr(f);let h=null;try{h=(await ve(i,{type:"SCOPE_FINGERPRINT_REQUEST",selector:e},a)).fingerprint}catch(S){F.debug("scope fingerprint failed; skipping cache fast-path",S)}if(h){const S=await fr(m);if(S&&S.fingerprint===h&&S.axeVersion===ho&&S.matrixConfigHash===p&&S.disabledRulesHash===g)return F.info(`audit-cache HIT for ${S.componentId} — skipping matrix iteration`),r||(z({type:"AUDIT_COMPLETE_EVENT",componentId:S.componentId,results:S.results,delta:S.delta}),z({type:"SCORECARD_UPDATED_EVENT"})),{ok:!0,results:S.results}}r||await Be({sessionId:Et(),mode:"single-element",scope:e,startedAt:new Date().toISOString(),lastProgressAt:new Date().toISOString(),state:"running"}),await At(i,{type:"LIVE_REGIONS_ARM_REQUEST"},a).catch(()=>{}),await At(i,{type:"FOCUS_TRACE_ARM_REQUEST"},a).catch(()=>{}),await ve(i,{type:"WARMUP_REQUEST"},a).catch(()=>{});const y=[],b=[];let A="",v,s=!1,k=null,x=null,w=null,R=null,T=!1,P=null;try{for(let S=0;S<u.length;S++){if(t.isCanceled()){F.info("single audit canceled by user");break}const E=u[S];try{const V=await Ka(i,E,e,a);if(!V.success){v=(_=V.error)==null?void 0:_.message,F.warn(`state ${S+1}/${u.length} drive failed`,v);continue}E.breakpoint.id!==k&&(await ve(i,{type:"WARMUP_REQUEST"},a).catch(()=>{}),k=E.breakpoint.id);const D=S===0?void 0:[...gi],$=await Fd(async()=>{var Y;const q=await ve(i,{type:"AUDIT_REQUEST",selector:e,currentState:E,rulesToRun:D},a);return q.success&&q.result?{result:q.result,violations:q.result.violations,error:null}:{result:null,violations:[],error:((Y=q.error)==null?void 0:Y.message)??null}},()=>t.isCanceled());$.lastError&&(v=$.lastError,F.warn(`state ${S+1}/${u.length} sampling: ${$.lastError}`));const U=$.lastResult;if(!$.stabilized&&$.sampleCount>0&&F.info(`state ${S+1}/${u.length} did not stabilize after ${$.sampleCount} samples — ${$.violations.length} finding(s) routed to needs-review as flickering`),U){s=!0;const q=$.violations;F.info(`[adaptive-sample] state ${S+1}/${u.length} ${E.pseudoState}·${E.theme}·${E.direction}·${E.breakpoint.id}: ${$.sampleCount} sample(s), ${$.stabilized?"stabilized":"flickering"}, ${q.length} finding(s)`);const Y=await ul(i,{quality:75})??void 0;let Z,ke;try{Z=(await ve(i,{type:"LIVE_REGIONS_DRAIN_REQUEST"},a)).announcements}catch{}try{ke=(await ve(i,{type:"FOCUS_TRACE_DRAIN_REQUEST"},a)).focusEvents}catch{}if(b.push({...U,violations:q,frameId:a,announcements:Z,focusEvents:ke,screenshotDataUrl:Y}),y.push(...q),A=U.componentId,S===0&&x===null)try{const re=await Ve("aiConfig",{}),ne=we(re);if(ne.enabled&&ne.apiKey&&A){x=ta(i,e,a,ne,b,A,t).catch(C=>{F.warn("ai augmentation (parallel) failed",C)});const ge=((N=b[0])==null?void 0:N.pageUrl)??((M=b[0])==null?void 0:M.scope)??"";w=Zl({tabId:i,componentId:A,pageUrl:ge,results:b,verifyFixesOnly:o.verifyFixesOnly}).catch(C=>(F.warn("1.4.11 walkthrough (parallel) failed",C),{criterionId:"1.4.11",ran:!0,ok:!1,error:String(C)}))}}catch(re){F.debug("ai augmentation (parallel) gate-read failed",re)}!T&&E.pseudoState==="default"&&E.theme==="light"&&E.direction==="ltr"&&E.breakpoint.id==="desktop"&&b[0]&&(T=!0,P=mo(i,e,a,b,E).catch(ne=>{F.debug("lightweight deep analyzers (parallel) failed",ne)}))}}catch(V){v=V instanceof Error?V.message:String(V),F.warn(`state ${S+1}/${u.length} threw`,V)}z({type:"AUDIT_PROGRESS_EVENT",current:S+1,total:u.length,currentState:E,componentId:A||void 0}),r||await $t({})}if(s&&A){const S={pseudoState:"default",ariaVariation:null,theme:"light",direction:"ltr",breakpoint:{id:"desktop",label:"Desktop",width:1280,height:800,deviceScaleFactor:1,mobile:!1}};if(T){if(P)try{await P}catch{}}else{try{await Ka(i,S,e,a),await new Promise($=>setTimeout($,200))}catch($){F.debug("reference-state drive failed; analyzers will use last matrix state",$)}await mo(i,e,a,b,S).catch($=>{F.debug("lightweight deep analyzers (post-matrix fallback) failed",$)})}try{const $=await Ve("aiConfig",{}),U=we($);if(U.enabled&&U.apiKey&&A&&b[0]){const q=b[0].pageUrl??b[0].scope??"";R=Ql({tabId:i,componentId:A,pageUrl:q,results:b,verifyFixesOnly:o.verifyFixesOnly}).catch(Y=>(F.warn("1.3.2 walkthrough (parallel) failed",Y),{criterionId:"1.3.2",ran:!0,ok:!1,error:String(Y)}))}}catch($){F.debug("1.3.2 walkthrough (parallel) gate-read failed",$)}try{if(x)await x;else{const $=await Ve("aiConfig",{}),U=we($);U.enabled&&U.apiKey&&await ta(i,e,a,U,b,A,t)}}catch($){F.warn("ai augmentation skipped",$)}try{const $=await Ve("aiConfig",{}),U=we($);if(U.enabled&&U.apiKey&&A&&b[0]){await qt(i,e,a).catch(re=>F.warn("pre-walkthrough resetState failed",re));const q=b[0].pageUrl??b[0].scope??"",Y=new AbortController,Z=setInterval(()=>{t.isCanceled()&&Y.abort()},250),ke=await Xl({tabId:i,componentId:A,pageUrl:q,results:b,signal:Y.signal,verifyFixesOnly:o.verifyFixesOnly}).finally(()=>clearInterval(Z));F.info("keyboard walkthroughs complete",ke)}}catch($){F.warn("keyboard walkthroughs failed",$)}try{const $=[];w&&$.push(await w),R&&$.push(await R),$.length>0&&F.info("parallel AI walkthroughs joined",$)}catch($){F.warn("parallel AI walkthrough join failed",$)}try{if(A&&b[0]){const $=b[0].pageUrl??b[0].scope??"",U=new AbortController,q=setInterval(()=>{t.isCanceled()&&U.abort()},250),Y=await ed({tabId:i,componentId:A,pageUrl:$,results:b,signal:U.signal,verifyFixesOnly:o.verifyFixesOnly}).finally(()=>clearInterval(q));F.info("2.5.3 label-in-name walkthrough complete",Y)}}catch($){F.warn("2.5.3 walkthrough failed",$)}try{if(A&&b[0]){await qt(i,e,a).catch(Z=>F.warn("pre-sampler resetState failed",Z));const $=new AbortController,U=setInterval(()=>{t.isCanceled()&&$.abort()},250),{resolved:q,skipped:Y}=await bd(i,b,$.signal).finally(()=>clearInterval(U));F.info(`pixel contrast sampler: resolved=${q} skipped=${Y}`)}}catch($){F.warn("pixel contrast sampler failed",$)}const E=b.flatMap($=>$.announcements??[]),V=b.flatMap($=>$.focusEvents??[]),D=await vn(A,y,{announcements:E,focusEvents:V},l);try{const $=await hn(b.map(ne=>ne.componentId)),U=await Qo(b.map(ne=>ne.componentId)),q=new Set;for(const ne of new Set(b.map(ge=>ge.componentId))){const ge=await ra(ne);for(const C of ge)q.add(C)}const Y=$e(y,void 0,b,q,$,U),Z=b.reduce((ne,ge)=>ne+ge.durationMs,0),ke=await fe(),re=de(ke,"forensicLog")?await si(b,Y,Z):null;if(re){const ne=await fe();if(de(ne,"forensicAnchoring"))try{const ge=await an(),C=await Ri(re,ge??void 0);C&&await ci(re.componentId,re.capturedAt,C)}catch(ge){F.warn("forensic anchoring failed (entry stays local-only)",ge)}}}catch($){F.warn("forensic log recording failed",$)}if(h)try{await gr({lookupKey:m,fingerprint:h,axeVersion:ho,matrixConfigHash:p,disabledRulesHash:g,results:b,delta:D,componentId:A,cachedAt:Date.now()})}catch($){F.warn("audit-cache write failed",$)}try{await chrome.scripting.executeScript({target:{tabId:i,frameIds:a!==void 0?[a]:void 0},world:"MAIN",func:()=>{const $=document.getElementById("__wcagcheckr_audit_freeze");$&&$.remove()}})}catch($){F.debug("audit-end state-freeze cleanup failed",$)}r||z({type:"AUDIT_COMPLETE_EVENT",componentId:A,results:b,delta:D})}else r||z({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 nt()}catch(S){F.error("single audit failed",S),r||z({type:"AUDIT_FAILED_EVENT",componentId:A||void 0,error:Mn(S)?S.payload:{code:"UNKNOWN",message:String(S),recoverable:!1}}),v=Mn(S)?S.payload.message:String(S)}finally{await At(i,{type:"LIVE_REGIONS_DISARM_REQUEST"},a).catch(()=>{}),await At(i,{type:"FOCUS_TRACE_DISARM_REQUEST"},a).catch(()=>{}),await qt(i,e,a)}return{ok:s,results:b,error:s?void 0:v}}async function Oi(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){F.warn("storybook detection scripting failed",a)}return{detected:!1}}async function Wd(e){if(await Fe()){z({type:"AUDIT_FAILED_EVENT",error:{code:St,message:ze,recoverable:!1}});return}const t=await ht(),a=await Ni(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){z({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"){z({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 jd(t,n):await zd(t,n);if(!o.length){F.warn(`${a.kind} detected but no stories returned`),z({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 Be({sessionId:Et(),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()){F.info(`${a.kind} iteration canceled by user`);break}try{if(a.kind==="storybook"){await Gd(t,n,r.id);const c=await At(t,{type:"STORYBOOK_GET_STORY_TARGET_REQUEST",tabId:t},n);await rt(c.selector,e,n)}else await Hd(t,n,r.id),await rt("#ladle-root",e,n)}catch(c){F.warn(`story ${r.id} failed; continuing with next`,c)}const i=await ua();if((i==null?void 0:i.state)==="interrupted"){F.info("storybook iteration interrupted");break}await $t({completedStories:[...(i==null?void 0:i.completedStories)??[],r.id]})}z({type:"SCORECARD_UPDATED_EVENT"}),await nt()}async function qd(e){if(await Fe()){z({type:"AUDIT_FAILED_EVENT",error:{code:St,message:ze,recoverable:!1}});return}const t=await fe();if(!de(t,"allFramesAudit")){z({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 ht();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){F.warn("multi-frame discovery failed",o)}if(n.length===0){z({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 Be({sessionId:Et(),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()){F.info("all-frames iteration canceled");break}try{await rt("html",e,o.frameId)}catch(i){F.warn(`frame ${o.frameId} (${o.url.slice(0,80)}) audit failed; continuing`,i)}const r=await ua();if((r==null?void 0:r.state)==="interrupted"){F.info("all-frames iteration interrupted");break}await $t({completedFrames:[...(r==null?void 0:r.completedFrames)??[],o.frameId]})}z({type:"SCORECARD_UPDATED_EVENT"}),await nt()}async function Vd(e){var o;const t=await fe();if(!de(t,"parallelScan")){z({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 Go();let n;if(a!==null)try{n=(await chrome.tabs.get(a)).url}catch(r){F.warn("failed to get target tab url",r)}if(!n){z({type:"AUDIT_FAILED_EVENT",error:{code:"NETWORK",message:"Could not determine target URL for parallel scan.",recoverable:!1}});return}await Be({sessionId:Et(),mode:"single-element",scope:"html",startedAt:new Date().toISOString(),lastProgressAt:new Date().toISOString(),state:"running"});try{const r=await Cn(),{runParallelTabAudit:i}=await en(async()=>{const{runParallelTabAudit:m}=await import("./parallel-tab-flow-BuZZIdRb.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(F.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){z({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 l=((o=c.results[0])==null?void 0:o.componentId)??"parallel-scan";if(a!==null)try{const m=await Ve("aiConfig",{}),p=we(m);p.enabled&&p.apiKey&&await ta(a,"html",void 0,p,c.results,l,e)}catch(m){F.warn("parallel scan: ai augmentation skipped",m)}const d=c.results.flatMap(m=>m.violations);let u;try{u=await vn(l,d)}catch(m){F.warn("parallel scan: baseline compare failed",m),u={new:[],persistent:[],fixed:[],newCount:0,persistentCount:0,fixedCount:0,baselineSnapshotMeta:null,comparedAt:new Date().toISOString()}}z({type:"AUDIT_COMPLETE_EVENT",componentId:l,results:c.results,delta:u}),z({type:"SCORECARD_UPDATED_EVENT"})}catch(r){F.warn("parallel scan failed",r),z({type:"AUDIT_FAILED_EVENT",error:{code:"UNKNOWN",message:r instanceof Error?r.message:String(r),recoverable:!0}})}finally{await nt()}}async function jd(e,t){var a;try{return((a=(await chrome.scripting.executeScript({target:{tabId:e,frameIds:[t]},world:"MAIN",func:async()=>{var l,d;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=((l=r.extract)==null?void 0:l.call(r))??((d=r.cachedCSFFiles)==null?void 0:d.call(r));if(!i)return[];const c=[];if(i instanceof Map)for(const[u,m]of i){const p=m;c.push({id:String(u),name:p.name??String(u),kind:p.title??p.kind??""})}else if(typeof i=="object"&&i!==null)for(const[u,m]of Object.entries(i)){const p=m;c.push({id:u,name:p.name??u,kind:p.title??p.kind??""})}return c}}))[0])==null?void 0:a.result)??[]}catch(n){return F.warn("listStoriesViaMainWorld failed",n),[]}}async function Gd(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),l=()=>{clearTimeout(c),i()};window.addEventListener("storyrendered",l,{once:!0})})}})}catch(n){F.warn(`navigateToStoryViaMainWorld(${a}) failed`,n)}}async function Mi(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){F.warn("ladle detection scripting failed",a)}return{detected:!1}}async function zd(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,l])=>({id:c,name:l.name??c,kind:(l.levels??[]).join(" / ")}))}catch{return[]}}}))[0])==null?void 0:a.result)??[]}catch(n){return F.warn("listLadleStoriesViaMainWorld failed",n),[]}}async function Hd(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){F.warn(`navigateToLadleStoryViaMainWorld(${a}) failed`,n)}}async function Di(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 Ni(e){const t=await Oi(e);if(t.detected)return{kind:"storybook",...t};const a=await Mi(e);return a.detected?{kind:"ladle",...a}:await Di(e)?{kind:"bit",detected:!0}:{kind:null,detected:!1}}const Qt=200,Li=6e4;function Zt(e,t){try{return new URL(e).origin===new URL(t).origin}catch{return!1}}function Pi(e,t){try{const a=new URL(e,t);return a.hash="",a.toString()}catch{return null}}async function Fi(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,l){c===e&&l.status==="complete"&&(clearTimeout(r),chrome.tabs.onUpdated.removeListener(i),n())}chrome.tabs.onUpdated.addListener(i)}),await new Promise(n=>setTimeout(n,400))}async function _i(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 F.debug("link discovery failed",a),[]}}async function Ui(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,l]of i)if(c.test(r))return`${l} (title: "${r.slice(0,80)}").`;return null}catch(o){return F.debug("error-page detection failed; proceeding with audit",o),null}}const bo=/Linked PDF at (\S+)\./;async function Wi(e,t){if(!de(t,"pdfAudit")){F.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=bo.exec(r.description);if(!i)continue;const c=i[1];let l;try{l=new URL(c,n.url).href}catch{continue}if(!/^https?:\/\//i.test(l))continue;let d=a.get(l);d||(d=new Set,a.set(l,d)),d.add(n)}if(a.size!==0){F.info(`PDF audit pass: ${a.size} unique PDF(s) across the crawl`);for(const[n,o]of a){let r;try{r=await yc(n)}catch(i){F.warn(`PDF audit threw for ${n}`,i);continue}for(const i of o){const c=i.results[0];if(!c)continue;const l=c.componentId,d=c.state,u=r.findings.map(m=>yo(m,n,l,d));c.violations=c.violations.filter(m=>{if(m.ruleId!=="pdf-needs-cli-audit")return!0;const p=bo.exec(m.description);if(!p)return!0;try{return new URL(p[1],i.url).href!==n}catch{return!0}}),c.violations.push(...u),r.fatalError&&c.violations.push(yo({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,l,d))}}}}function yo(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 Bd(e,t,a){if(await Fe())return z({type:"CRAWL_DISCOVERY_FAILED_EVENT",error:{code:St,message:ze,recoverable:!1}}),[];const n=await fe();if(!de(n,"siteCrawl"))return z({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 ht(),r=Ro(n).siteCrawlMaxPages,i=Number.isFinite(r)?Math.min(r,Qt):Qt,c=Math.min(t.maxPages??25,i),l=t.includeRegex?ea(t.includeRegex):null,d=t.excludeRegex?ea(t.excludeRegex):null,u=[e],m=new Set,p=[];try{for(;u.length>0&&p.length<c;){if(a.isCanceled()){F.info("crawl discovery canceled by user");break}const f=u.shift();if(!(!f||m.has(f))&&Zt(f,e)&&!(l&&!l.test(f))&&!(d&&d.test(f))){m.add(f);try{if(await Fi(o,f,Li),!(await Sn(o,0)).ok||await Ui(o,f))continue;p.push(f),z({type:"CRAWL_DISCOVERY_PROGRESS_EVENT",found:p.length,url:f});const y=await _i(o);for(const b of y){const A=Pi(b,f);A&&Zt(A,e)&&!m.has(A)&&!u.includes(A)&&u.push(A)}}catch(g){F.debug("discovery: page navigation/link-read failed; skipping",g);continue}await $t({})}}return z({type:"CRAWL_DISCOVERY_COMPLETE_EVENT",urls:p}),p}catch(f){return F.error("crawl discovery failed",f),z({type:"CRAWL_DISCOVERY_FAILED_EVENT",error:{code:"CRAWL_DISCOVERY_FAILED",message:String(f),recoverable:!0}}),[]}}async function Kd(e,t,a){if(await Fe()){z({type:"SITE_CRAWL_FAILED_EVENT",error:{code:St,message:ze,recoverable:!1}});return}const n=await fe();if(!de(n,"siteCrawl")){z({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 ht(),r=Ro(n).siteCrawlMaxPages,i=Number.isFinite(r)?Math.min(r,Qt):Qt,c=Array.isArray(t.urls)&&t.urls.length>0,l=Math.min(c?t.urls.length:t.maxPages??25,i),d=t.includeRegex?ea(t.includeRegex):null,u=t.excludeRegex?ea(t.excludeRegex):null,m=new Date().toISOString(),p=Date.now(),f=c?[...t.urls]:[e],g=new Set,h=[];await Be({sessionId:Et(),mode:"storybook-all",scope:e,startedAt:m,lastProgressAt:new Date().toISOString(),state:"running"});try{for(;f.length>0&&g.size<l;){if(a.isCanceled()){F.info("site crawl canceled by user");break}const k=f.shift();if(!k||g.has(k)||!Zt(k,e)||d&&!d.test(k)||u&&u.test(k))continue;g.add(k);const x=g.size,w=Date.now();z({type:"SITE_CRAWL_PROGRESS_EVENT",current:x,total:Math.min(l,g.size+f.length),url:k,status:"auditing"});try{await Fi(o,k,Li);const R=await Sn(o,0);if(!R.ok)throw new Error(Qa(R));const T=await Ui(o,k);if(T){const S=`Skipped — page appears to be an error response. ${T}`;h.push({url:k,results:[],delta:null,componentId:k,durationMs:Date.now()-w,error:S}),z({type:"SITE_CRAWL_PROGRESS_EVENT",current:x,total:Math.min(l,g.size+f.length),url:k,status:"failed",error:S});continue}await ve(o,{type:"WARMUP_REQUEST"},0).catch(()=>{});const P=await rt("html",a,0,void 0,{asSubroutine:!0,tabIdOverride:o,verifyFixesOnly:t.verifyFixesOnly}),_=P.results,N=P.ok?void 0:P.error,M=Date.now()-w;if(_.length>0){const S=await wc(o,k).catch(()=>null),E=_.reduce((V,D)=>V+D.violations.length,0);h.push({url:k,results:_,delta:null,componentId:_[0].componentId,durationMs:M,snapshot:S??void 0}),z({type:"SITE_CRAWL_PROGRESS_EVENT",current:x,total:Math.min(l,g.size+f.length),url:k,status:"completed",violations:E})}else{const S=N??"audit returned no result";h.push({url:k,results:[],delta:null,componentId:k,durationMs:M,error:S}),z({type:"SITE_CRAWL_PROGRESS_EVENT",current:x,total:Math.min(l,g.size+f.length),url:k,status:"failed",error:S})}if(!c){const S=await _i(o);for(const E of S){const V=Pi(E,k);V&&Zt(V,e)&&!g.has(V)&&!f.includes(V)&&f.push(V)}}}catch(R){const T=Date.now()-w,P=R instanceof Error?R.message:String(R);h.push({url:k,results:[],delta:null,componentId:k,durationMs:T,error:P}),z({type:"SITE_CRAWL_PROGRESS_EVENT",current:x,total:Math.min(l,g.size+f.length),url:k,status:"failed",error:P})}await $t({})}try{const k=await fe();await Wi(h,k)}catch(k){F.warn("PDF audit pass failed",k)}const y=new Date().toISOString(),b=Date.now()-p,A=h.flatMap(k=>k.results),v=await Re(A,[e]),s=ui(e,h,m,y,b,v.walkthroughsByComponent,v.walkthroughAcksByComponent,v.ackedKeysByComponent,v.humanVerdictsByComponent,v.incompleteResolutionsByComponent);if(s.consistencyFindings.length>0)try{const k=await zc(s.consistencyFindings);s.consistencyFindings=k.emitted}catch(k){F.warn("consistency AI suppression failed; emitting heuristic findings",k)}try{const k=h.map(x=>({...x,results:x.results.map(({screenshotDataUrl:w,...R})=>R)}));await jo(k,{startUrl:e,finishedAt:y})}catch(k){const x=k instanceof Error?k.message:String(k);F.error("persisting siteCrawlPerUrlResults failed",k),z({type:"SITE_CRAWL_FAILED_EVENT",error:{code:"CRAWL_PERSIST_FAILED",message:`Crawl finished but persistence failed (${x}). The AI fix prompt export won't have per-page data.`,recoverable:!1}})}z({type:"SITE_CRAWL_COMPLETE_EVENT",report:s}),await nt()}catch(y){F.error("site crawl failed",y),z({type:"SITE_CRAWL_FAILED_EVENT",error:{code:"UNKNOWN",message:String(y),recoverable:!1}}),await nt()}}function ea(e){try{return new RegExp(e)}catch{return null}}async function Yd(){const[e,t]=await Promise.all([sn(),Gt()]);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 Re(a,[e.startUrl]),o=new Date().toISOString(),r=ui(e.startUrl,t,e.startedAt,o,e.totalDurationMs,n.walkthroughsByComponent,n.walkthroughAcksByComponent,n.ackedKeysByComponent,n.humanVerdictsByComponent,n.incompleteResolutionsByComponent);return await Vo(r),z({type:"SITE_CRAWL_COMPLETE_EVENT",report:r}),{ok:!0}}const Oa=5*6e4,wo=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…"},Jd={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 ta(e,t,a,n,o,r,i){const c=await fe();if(!de(c,"aiJudgment")){F.debug("aiJudgment not allowed on current tier — skipping AI augmentation");return}let l;try{l=await ve(e,{type:"AI_CANDIDATES_REQUEST",selector:t},a)}catch(M){F.debug("ai candidates fetch failed",M);return}const d=o[0];if(!d)return;const u={componentId:r,currentState:d.state,axeVersion:d.axeVersion},m={at:new Date().toISOString(),componentId:r,pageUrl:d.pageUrl??t,enabledChecks:n.enabledChecks,candidateCounts:{images:l.images.length,headings:l.headings.length,instructions:l.instructions.length,ariaElements:l.ariaElements.length,links:l.links.length,longTextBlocks:l.longTextBlocks.length,colorOnlyRegions:l.colorOnlyRegions.length,languageInfo:l.languageInfo?"present":"null"}};F.info("ai augmentation gate snapshot",JSON.stringify(m));try{await chrome.storage.local.set({aiDiagnosticLatest:m})}catch(M){F.warn("failed to persist ai diagnostic to storage.local",M)}const p=[];if(n.enabledChecks.altText&&p.push({key:"altText",run:M=>{const S=l.images.map(E=>({imageUrl:E.imageUrl,alt:E.alt,selector:E.selector,outerHTML:E.outerHTML,surroundingContext:E.surroundingContext,...u}));return xl(S,n,M)}}),n.enabledChecks.headings&&p.push({key:"headings",run:M=>yd(l.headings,u,n,M)}),n.enabledChecks.sensory&&p.push({key:"sensory",run:M=>wd(l.instructions,u,n,M)}),n.enabledChecks.aria&&p.push({key:"aria",run:M=>vd(l.ariaElements,u,n,M)}),n.enabledChecks.imageOfText&&p.push({key:"imageOfText",run:M=>{const S=l.images.map(E=>({imageUrl:E.imageUrl,accessibleName:E.alt||void 0,selector:E.selector,outerHTML:E.outerHTML,pixelArea:E.pixelArea}));return xd(S,u,n,M)}}),n.enabledChecks.colorOnlyMeaning&&p.push({key:"colorOnlyMeaning",run:M=>Sd(l.colorOnlyRegions,u,n,M)}),n.enabledChecks.genericLinkText&&p.push({key:"genericLinkText",run:M=>Ad(l.links,u,n,M)}),n.enabledChecks.wallOfText&&p.push({key:"wallOfText",run:M=>kd(l.longTextBlocks,u,n,M)}),n.enabledChecks.languageMismatch){const M=l.languageInfo;p.push({key:"languageMismatch",run:S=>Id(M?[M]:[],u,n,S)})}if(p.length===0)return;let f=0,g=0,h=!1;const y={};let b=0,A=0,v=0;const s=[];let k=!1,x=!1;function w(M,S){if(y[M]=(y[M]??0)+S.totalCostUsd,f+=S.totalCostUsd,g+=S.findings.length,h=h||S.capExceeded,b++,S.errors.length>0){v++;for(const E of S.errors)s.includes(E)||s.push(E)}else A++;F.info(`ai ${M}: ${S.findings.length} findings, $${S.totalCostUsd.toFixed(4)}, errs=${S.errors.length}`),S.capExceeded&&F.warn(`ai cost cap exceeded after $${S.totalCostUsd.toFixed(4)} during ${M}`)}const R=(async()=>{for(let M=0;M<p.length;M++){if(i!=null&&i.isCanceled()){x=!0;break}const S=p[M];z({type:"AI_AUGMENTATION_PROGRESS_EVENT",componentId:r,currentCheck:S.key,currentCheckLabel:vo[S.key],current:M+1,total:p.length});const E=new AbortController,V=setTimeout(()=>E.abort(),wo),D=i?setInterval(()=>{i.isCanceled()&&E.abort()},500):null;let $;try{$=await S.run({signal:E.signal,onProgress:(U,q)=>{q>0&&z({type:"AI_AUGMENTATION_PROGRESS_EVENT",componentId:r,currentCheck:S.key,currentCheckLabel:vo[S.key],current:M+1,total:p.length,candidatesDone:U,candidatesTotal:q})}}),E.signal.aborted&&(i!=null&&i.isCanceled())?$.errors=[...$.errors,`${S.key} canceled by user`]:E.signal.aborted}catch(U){const q=U instanceof Error?U.message:String(U),Y=E.signal.aborted,Z=Y&&(i!=null&&i.isCanceled())?`${S.key} canceled by user`:Y?`${S.key} hit per-check ${wo/1e3}s cap — analyzer aborted`:`${S.key} threw: ${q}`;$={findings:[],totalCostUsd:0,capExceeded:!1,errors:[Z]}}finally{clearTimeout(V),D&&clearInterval(D)}if($.findings.length>0&&(d.violations=[...d.violations,...$.findings]),$.errors.length===0){const U=Jd[S.key];if(U&&U.length>0&&d.axeRulesEvaluated)for(const q of U)d.axeRulesEvaluated.passed.push({ruleId:`ai-${S.key}-coverage`,wcagCriterion:q})}w(S.key,$)}})(),T=new Promise(M=>{setTimeout(()=>M("timeout"),Oa)});await Promise.race([R.then(()=>"done"),T])==="timeout"&&(k=!0,F.warn(`ai augmentation hit global ${Oa/1e3}s timeout after ${b}/${p.length} checks`));let _;if(v>0||k||x){k?_=`AI augmentation timed out after ${Oa/1e3}s`:x?_="AI augmentation canceled":_=s[0]??"AI analyzer error";const M=A===0?"total":"partial";z({type:"AI_AUGMENTATION_FAILED_EVENT",componentId:r,severity:M,reason:_,checksAttempted:b,checksSucceeded:A,checksErrored:v,errorDetails:k||x?[_,...s.slice(0,4)]:s.slice(0,5)}),F.warn(`ai augmentation ${M} failure: ${v}/${b} checks errored — ${_}`)}(f>0||g>0||_)&&await mr({at:new Date().toISOString(),pageUrl:d.pageUrl??t,componentId:r,totalCostUsd:f,byCheck:y,findingsCount:g,capExceeded:h,failureReason:_})}const ah=Object.freeze(Object.defineProperty({__proto__:null,auditCrawlPdfs:Wi,detectBit:Di,detectLadleAcrossFrames:Mi,detectPlayground:Ni,detectStorybookAcrossFrames:Oi,discoverCrawlUrls:Bd,getActiveTabId:ht,getMatrixSettings:Cn,regradeSiteCrawl:Yd,runAiAugmentation:ta,runAllFramesAudit:qd,runParallelScan:Vd,runSingleElementAudit:rt,runSiteCrawl:Kd,runStorybookAllAudit:Wd},Symbol.toStringTag,{value:"Module"})),wt=ee("alert-sender"),Xd="wcagcheckr",Qd="https://api.wcagcheckr.com",Zd=`${Qd}/v1/products/${Xd}/alerts/send`,eu=1e4,Za="alertConfig:v1",tu={emailEnabled:!1,webhookEnabled:!1,webhookUrl:"",minImpact:"serious"},Ut={minor:1,moderate:2,serious:3,critical:4};async function au(){const t=(await chrome.storage.local.get(Za))[Za];return{...tu,...t??{}}}async function nh(e){await chrome.storage.local.set({[Za]:e})}async function nu(e){let t;try{t=await au()}catch(g){return wt.warn("failed to read alert config",g),{fired:!1,reason:"config_read_failed"}}if(!t.emailEnabled&&!t.webhookEnabled)return{fired:!1,reason:"no_channel_enabled"};const a=await fe(),n=de(a,"emailAlerts"),o=de(a,"webhookAlerts"),r=t.emailEnabled&&n,i=t.webhookEnabled&&o;if(!r&&!i)return{fired:!1,reason:"no_channel_enabled"};const c=[];for(const g of e.results){const h=g.delta;h!=null&&h.new&&c.push(...h.new)}const l=Ut[t.minImpact],d=c.filter(g=>Ut[g.impact]>=l);if(d.length===0)return{fired:!1,reason:"below_impact_threshold"};const u=await an();if(!u)return wt.debug("no license token; alert skipped"),{fired:!1,reason:"no_license_token"};d.sort((g,h)=>Ut[h.impact]-Ut[g.impact]);const m=d.slice(0,10).map(g=>({wcag:g.wcagCriterion,impact:g.impact,selector:g.target.selector,help:g.description.slice(0,480),helpUrl:g.helpUrl})),p=e.results.reduce((g,h)=>g+h.violations.length,0),f={token:u,scheduleId:e.scheduleId,auditedUrl:e.auditedUrl,totalViolations:p,newViolationCount:d.length,topViolations:m,webhookUrl:i&&t.webhookUrl?t.webhookUrl:void 0,emailEnabled:r,ranAt:e.ranAt};try{const g=await fetch(Zd,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(f),signal:AbortSignal.timeout(eu)}),h=await g.json().catch(()=>null);return g.ok?(wt.info("alert delivered",{emailSent:h==null?void 0:h.emailSent,webhookSent:h==null?void 0:h.webhookSent}),{fired:!0,emailSent:(h==null?void 0:h.emailSent)??!1,webhookSent:(h==null?void 0:h.webhookSent)??!1,serverStatus:g.status}):(wt.warn(`alert server returned ${g.status}`,h),{fired:!1,reason:`server_${g.status}`,serverStatus:g.status})}catch(g){return wt.warn("alert send failed",g),{fired:!1,reason:g instanceof Error?g.message:"unknown_error"}}}const ou="#dc2626",iu="#f59e0b",ru="#059669",su="#94a3b8";function cu(e){const t=e.filter(c=>c.enabled);let a=0,n=0,o=0,r=0;for(const c of t){const l=c.lastNewViolationCount??0;c.lastResult==="failed"?n++:c.lastResult==="ok"?l>0?a+=l: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 lu(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:ou}),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:iu}),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:ru}),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:su}),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 du(){const e=await fe();if(!de(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 _o(),a=cu(t);try{await lu(a)}catch(n){console.warn("[status-badge] failed to apply",n)}return a}const Ao=ee("deposition-packet"),qi="https://api.wcagcheckr.com/verify";function te(e){return e.replace(/[&<>"']/g,t=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[t])}function uu(e,t,a){if(!e)return`<section class="dp-cover dp-cover-error">
|
|
956
956
|
<h2 style="margin:0 0 8pt 0; color:#b91c1c">⚠ Chain-of-Custody: UNAVAILABLE</h2>
|
|
957
957
|
<p>This packet could not be sealed because the underlying audit record was empty. Provenance cannot be verified.</p>
|
|
958
|
-
</section>`;const n=`${
|
|
958
|
+
</section>`;const n=`${qi}?hash=${encodeURIComponent(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">
|
|
959
959
|
<h2 style="margin:0 0 8pt 0; color:#064e3b">🔒 Chain-of-Custody: SEALED (RFC 3161 + ed25519)</h2>
|
|
960
960
|
<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>
|
|
961
961
|
<dl style="margin:0; font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size:9pt">
|
|
@@ -992,7 +992,7 @@ Primary AI verdict was uncertain. Programmatic multi-column detector found no ma
|
|
|
992
992
|
<dd style="margin:0 0 6pt 16pt">${te(e.grade)}</dd>
|
|
993
993
|
</dl>
|
|
994
994
|
<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>
|
|
995
|
-
</section>`}function
|
|
995
|
+
</section>`}function pu(e,t){var n;if(!e)return"";const a=`${qi}?hash=${encodeURIComponent(e.hash)}`;return`<section class="dp-verification" style="border:1pt solid #cbd5e1; padding:14pt; margin:24pt 0; border-radius:4pt; background:#f8fafc">
|
|
996
996
|
<h2 style="margin:0 0 8pt 0">How to verify this audit's integrity</h2>
|
|
997
997
|
<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>
|
|
998
998
|
|
|
@@ -1025,7 +1025,7 @@ Primary AI verdict was uncertain. Programmatic multi-column detector found no ma
|
|
|
1025
1025
|
<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>
|
|
1026
1026
|
<li style="margin-bottom:4pt">It does not warrant against future protocol breaks (cryptography evolves; an seal valid today may need re-anchoring decades later).</li>
|
|
1027
1027
|
</ul>
|
|
1028
|
-
</section>`}function
|
|
1028
|
+
</section>`}function hu(e){return e?`<section class="dp-declaration" style="border:1pt solid #cbd5e1; padding:14pt; margin:24pt 0; border-radius:4pt; page-break-before:always">
|
|
1029
1029
|
<h2 style="margin:0 0 8pt 0">Declaration under penalty of perjury (template)</h2>
|
|
1030
1030
|
<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>
|
|
1031
1031
|
<div style="border:1pt dashed #94a3b8; padding:12pt; background:#ffffff">
|
|
@@ -1040,11 +1040,11 @@ Primary AI verdict was uncertain. Programmatic multi-column detector found no ma
|
|
|
1040
1040
|
<p style="margin:24pt 0 6pt 0; border-top:1pt solid #0f172a; padding-top:6pt; max-width:300pt"><strong>[Signature]</strong></p>
|
|
1041
1041
|
<p style="margin:0; font-size:10pt"><strong>[Printed name]</strong></p>
|
|
1042
1042
|
</div>
|
|
1043
|
-
</section>`:""}function
|
|
1043
|
+
</section>`:""}function fu(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">
|
|
1044
1044
|
<h2>Raw axe-core JSON (machine-readable)</h2>
|
|
1045
1045
|
<p>The block below is the unfiltered axe-core output included for machine re-verification. View HTML source to extract.</p>
|
|
1046
1046
|
<pre id="wcagcheckr-axe-raw-json" data-product="wcagcheckr" data-format="deposition-packet-v1">${te(JSON.stringify(t,null,2))}</pre>
|
|
1047
|
-
</section>`}async function
|
|
1047
|
+
</section>`}async function gu(e,t,a,n,o,r){if(e.length===0)return null;const i=e[0],l=(await Ys(i.componentId)).find(p=>p.capturedAt===i.startedAt);if(l)return l;const d=e.flatMap(p=>p.violations),u=$e(d,void 0,e,n,t,a,o,st(e),r),m=e.reduce((p,f)=>p+f.durationMs,0);return si(e,u,m)}async function Vi(e){let t;try{t=await gu(e.results,e.interactiveAuditResults,e.walkthroughAcks,e.acknowledgedMatchKeys,e.humanCriterionVerdicts,e.incompleteResolutions)}catch(f){Ao.warn("ensureForensicEntry failed",f),t=null}let a;if(t&&!t.receipt)try{const f=await Ri(t,e.licenseId);f?(await ci(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),Ao.warn("anchor failed",f)}const n=await kt().catch(()=>[]),o=Rt(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=uu(t,(t==null?void 0:t.receipt)??null,a),i=pu(t,(t==null?void 0:t.receipt)??null),c=hu(t),l=fu(e.results);let d=o;const u=d.indexOf("<h1");u>-1?d=d.slice(0,u)+r+d.slice(u):d=r+d;const m=d.lastIndexOf("</body>"),p=i+c+l;return d=m>-1?d.slice(0,m)+p+d.slice(m):d+p,{html:d,entry:t,anchored:!!(t!=null&&t.receipt),anchorError:a}}function Ae(e){return e.replace(/[&<>"']/g,t=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[t])}function mu(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 bu=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 yu(e,t,a,n){return`<section>
|
|
1048
1048
|
<h2>1. Tool identification</h2>
|
|
1049
1049
|
<table style="border-collapse:collapse; margin-top:8pt; font-size:10pt">
|
|
1050
1050
|
<tr><td style="padding:2pt 12pt 2pt 0; color:#475569">Tool</td><td><strong>wcagcheckr</strong> — Chrome MV3 accessibility audit extension</td></tr>
|
|
@@ -1054,7 +1054,7 @@ Primary AI verdict was uncertain. Programmatic multi-column detector found no ma
|
|
|
1054
1054
|
<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>
|
|
1055
1055
|
${n?`<tr><td style="padding:2pt 12pt 2pt 0; color:#475569">Audit captured at</td><td><code>${Ae(n)}</code></td></tr>`:""}
|
|
1056
1056
|
</table>
|
|
1057
|
-
</section>`}function
|
|
1057
|
+
</section>`}function wu(){return`<section>
|
|
1058
1058
|
<h2>2. Methodology overview</h2>
|
|
1059
1059
|
<p>The wcagcheckr audit framework rests on three layers that complement (rather than overlap) one another:</p>
|
|
1060
1060
|
<ol>
|
|
@@ -1063,7 +1063,7 @@ Primary AI verdict was uncertain. Programmatic multi-column detector found no ma
|
|
|
1063
1063
|
<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>
|
|
1064
1064
|
</ol>
|
|
1065
1065
|
<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>
|
|
1066
|
-
</section>`}function
|
|
1066
|
+
</section>`}function vu(){return`<section>
|
|
1067
1067
|
<h2>3. State matrix specification</h2>
|
|
1068
1068
|
<p>For each in-scope interactive element, the audit drives the following dimensions and records the rendered DOM + computed styles at each combination:</p>
|
|
1069
1069
|
<table style="border-collapse:collapse; font-size:10pt; margin-top:8pt">
|
|
@@ -1080,10 +1080,10 @@ Primary AI verdict was uncertain. Programmatic multi-column detector found no ma
|
|
|
1080
1080
|
<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>
|
|
1081
1081
|
</table>
|
|
1082
1082
|
<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>
|
|
1083
|
-
</section>`}function
|
|
1084
|
-
<td style="padding:3pt; font-family:monospace; font-size:9pt"><code>${Ae(
|
|
1083
|
+
</section>`}function Au(e,t){const a=new Set;for(const r of ko)for(const i of r.rules)a.add(i);const o=Array.from(a).sort().map(r=>{const i=t.has(r),l=ko.filter(d=>d.rules.includes(r)).map(d=>`${d.ref} ${d.title}`).join(", ")||"(unmapped)";return`<tr>
|
|
1084
|
+
<td style="padding:3pt; font-family:monospace; font-size:9pt"><code>${Ae(r)}</code></td>
|
|
1085
1085
|
<td style="padding:3pt; font-size:9pt">${Ae(l)}</td>
|
|
1086
|
-
<td style="padding:3pt; font-size:9pt; ${
|
|
1086
|
+
<td style="padding:3pt; font-size:9pt; ${i?"color:#065f46;font-weight:600":"color:#94a3b8"}">${i?"✓ ran":"— not in this run"}</td>
|
|
1087
1087
|
</tr>`}).join("");return`<section>
|
|
1088
1088
|
<h2>4. Automated rule coverage (axe-core)</h2>
|
|
1089
1089
|
<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>
|
|
@@ -1095,7 +1095,7 @@ Primary AI verdict was uncertain. Programmatic multi-column detector found no ma
|
|
|
1095
1095
|
</tr>
|
|
1096
1096
|
${o}
|
|
1097
1097
|
</table>
|
|
1098
|
-
</section>`}function
|
|
1098
|
+
</section>`}function ku(e){const t=new Set((e??[]).map(n=>n.workflowId));return`<section>
|
|
1099
1099
|
<h2>5. Manual workflow framework (Intelligent Guided Tests)</h2>
|
|
1100
1100
|
<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>
|
|
1101
1101
|
<table style="border-collapse:collapse; font-size:10pt; margin-top:8pt; width:100%">
|
|
@@ -1105,15 +1105,15 @@ Primary AI verdict was uncertain. Programmatic multi-column detector found no ma
|
|
|
1105
1105
|
<th style="text-align:right; padding:4pt">Length</th>
|
|
1106
1106
|
<th style="text-align:left; padding:4pt">Status</th>
|
|
1107
1107
|
</tr>
|
|
1108
|
-
${Oe.map(n=>{const o=t.has(n.id),
|
|
1108
|
+
${Oe.map(n=>{const o=t.has(n.id),r=n.steps.length;return`<tr>
|
|
1109
1109
|
<td style="padding:4pt; font-weight:600">${Ae(n.name)}</td>
|
|
1110
1110
|
<td style="padding:4pt; color:#475569; max-width:380pt">${Ae(n.blurb)}</td>
|
|
1111
|
-
<td style="padding:4pt; font-size:9pt; text-align:right">${
|
|
1111
|
+
<td style="padding:4pt; font-size:9pt; text-align:right">${r} step${r===1?"":"s"}</td>
|
|
1112
1112
|
<td style="padding:4pt; font-size:9pt; ${o?"color:#065f46;font-weight:600":"color:#94a3b8"}">${o?"✓ executed":"— not in this run"}</td>
|
|
1113
1113
|
</tr>`}).join("")}
|
|
1114
1114
|
</table>
|
|
1115
1115
|
<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>
|
|
1116
|
-
</section>`}function
|
|
1116
|
+
</section>`}function Iu(e){const a=Tt(e,"AA").filter(o=>!bu.has(o.id)),n=a.map(o=>`<tr>
|
|
1117
1117
|
<td style="padding:3pt; font-family:monospace; font-size:9pt"><code>${Ae(o.id)}</code></td>
|
|
1118
1118
|
<td style="padding:3pt"><strong>${Ae(o.title)}</strong> <span style="color:#475569">(${Ae(o.level)})</span></td>
|
|
1119
1119
|
<td style="padding:3pt; color:#475569; font-size:10pt">${Ae(o.shortDescription)}</td>
|
|
@@ -1128,7 +1128,7 @@ Primary AI verdict was uncertain. Programmatic multi-column detector found no ma
|
|
|
1128
1128
|
</tr>
|
|
1129
1129
|
${n}
|
|
1130
1130
|
</table>
|
|
1131
|
-
</section>`}function
|
|
1131
|
+
</section>`}function xu(){return`<section>
|
|
1132
1132
|
<h2>7. Limitations of automated detection</h2>
|
|
1133
1133
|
<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>
|
|
1134
1134
|
<ul>
|
|
@@ -1140,7 +1140,7 @@ Primary AI verdict was uncertain. Programmatic multi-column detector found no ma
|
|
|
1140
1140
|
<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>
|
|
1141
1141
|
</ul>
|
|
1142
1142
|
<p>Findings produced by this tool support but do not substitute for an expert review.</p>
|
|
1143
|
-
</section>`}function
|
|
1143
|
+
</section>`}function Su(){return`<section>
|
|
1144
1144
|
<h2>8. Audit process (technical specification)</h2>
|
|
1145
1145
|
<ol>
|
|
1146
1146
|
<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>
|
|
@@ -1152,7 +1152,7 @@ Primary AI verdict was uncertain. Programmatic multi-column detector found no ma
|
|
|
1152
1152
|
<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>
|
|
1153
1153
|
<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>
|
|
1154
1154
|
</ol>
|
|
1155
|
-
</section>`}function
|
|
1155
|
+
</section>`}function Cu(){return`<section>
|
|
1156
1156
|
<h2>9. Forensic anchoring (RFC 3161 + ed25519)</h2>
|
|
1157
1157
|
<p>Audit records can be sealed against a trusted third-party timestamp authority and counter-signed by the wcagcheckr server. When sealed:</p>
|
|
1158
1158
|
<ul>
|
|
@@ -1162,7 +1162,7 @@ Primary AI verdict was uncertain. Programmatic multi-column detector found no ma
|
|
|
1162
1162
|
<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>
|
|
1163
1163
|
</ul>
|
|
1164
1164
|
<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>
|
|
1165
|
-
</section>`}function
|
|
1165
|
+
</section>`}function Tu(){return`<section>
|
|
1166
1166
|
<h2>10. References</h2>
|
|
1167
1167
|
<ul style="font-size:10pt; line-height:1.6">
|
|
1168
1168
|
<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>
|
|
@@ -1173,7 +1173,7 @@ Primary AI verdict was uncertain. Programmatic multi-column detector found no ma
|
|
|
1173
1173
|
<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>
|
|
1174
1174
|
<li>IETF RFC 8032, <a href="https://datatracker.ietf.org/doc/html/rfc8032">Edwards-Curve Digital Signature Algorithm (EdDSA)</a>.</li>
|
|
1175
1175
|
</ul>
|
|
1176
|
-
</section>`}const ko=[{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
|
|
1176
|
+
</section>`}const ko=[{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 $u(e={}){var d,u,m,p,f;const t=e.results??[],a=e.manualRuns,n=e.wcagTargetOverride??Le,o=typeof chrome<"u"&&((m=(u=(d=chrome.runtime)==null?void 0:d.getManifest)==null?void 0:u.call(d))==null?void 0:m.version)||"unknown",r=((p=t[0])==null?void 0:p.axeVersion)??"4.11.4",i=((f=t[0])==null?void 0:f.startedAt)??null,c=mu(t),l=c.size>0;return`<!doctype html>
|
|
1177
1177
|
<html lang="en">
|
|
1178
1178
|
<head>
|
|
1179
1179
|
<meta charset="utf-8" />
|
|
@@ -1198,19 +1198,19 @@ Primary AI verdict was uncertain. Programmatic multi-column detector found no ma
|
|
|
1198
1198
|
<h1>Audit Methodology — wcagcheckr</h1>
|
|
1199
1199
|
<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>
|
|
1200
1200
|
|
|
1201
|
-
${
|
|
1202
|
-
${
|
|
1203
|
-
${
|
|
1204
|
-
${
|
|
1205
|
-
${
|
|
1206
|
-
${
|
|
1201
|
+
${yu(n,o,r,i)}
|
|
1202
|
+
${wu()}
|
|
1203
|
+
${vu()}
|
|
1204
|
+
${Au(l,c)}
|
|
1205
|
+
${ku(a)}
|
|
1206
|
+
${Iu(n)}
|
|
1207
|
+
${xu()}
|
|
1208
|
+
${Su()}
|
|
1207
1209
|
${Cu()}
|
|
1208
1210
|
${Tu()}
|
|
1209
|
-
${$u()}
|
|
1210
|
-
${Eu()}
|
|
1211
1211
|
|
|
1212
1212
|
</body>
|
|
1213
|
-
</html>`}const Ou=[{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 Ce(e){return e.replace(/[&<>"']/g,t=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[t])}function Mu(e){const t=new Set;for(const a of e)for(const n of a.violations)t.add(n.wcagCriterion);return t}function Se(e,t){return`<span style="display:inline-block; padding:1pt 6pt; border-radius:3pt; font-size:9pt; background:${t}20; color:${t}; font-weight:600">${Ce(e)}</span>`}function Du(e){switch(e){case"in-scope":return Se("§E207.2 → WCAG 2.0","#059669");case"not-in-scope-2.1":return Se("Not in scope (WCAG 2.1+)","#94a3b8");case"not-in-scope-2.2":return Se("Not in scope (WCAG 2.2)","#94a3b8")}}function Nu(e){switch(e){case"de-facto-standard":return Se("De facto via WCAG AA","#059669");case"gray-area":return Se("Gray area (new SC)","#f59e0b")}}function Lu(e){switch(e){case"in-scope":return Se("In scope","#059669");case"product-related":return Se("Product-related","#0ea5e9");case"gray-area":return Se("Gray area","#f59e0b")}}function Pu(e){switch(e){case"in-scope":return Se("In scope (WCAG 2.0)","#059669");case"not-in-scope-2.1":return Se("Not in scope (2.1+)","#94a3b8");case"not-in-scope-2.2":return Se("Not in scope (2.2)","#94a3b8")}}function Fu(e={}){var l;const t=e.wcagTargetOverride??Le,a=e.results?Mu(e.results):new Set,n=(((l=e.results)==null?void 0:l.length)??0)>0,o=new Set(Tt(t,"AA").map(d=>d.id)),i=Ou.map(d=>{const u=a.has(d.wcagId),m=o.has(d.wcagId),p=u?"background:#fee2e2;":m?"":"background:#f8fafc; opacity:0.6;",f=u?'<div style="font-size:9pt; color:#b91c1c; font-weight:700; margin-top:2pt">⚠ Violated in this audit</div>':"";return`<tr style="${p}">
|
|
1213
|
+
</html>`}const Eu=[{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 Ce(e){return e.replace(/[&<>"']/g,t=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[t])}function Ru(e){const t=new Set;for(const a of e)for(const n of a.violations)t.add(n.wcagCriterion);return t}function Se(e,t){return`<span style="display:inline-block; padding:1pt 6pt; border-radius:3pt; font-size:9pt; background:${t}20; color:${t}; font-weight:600">${Ce(e)}</span>`}function Ou(e){switch(e){case"in-scope":return Se("§E207.2 → WCAG 2.0","#059669");case"not-in-scope-2.1":return Se("Not in scope (WCAG 2.1+)","#94a3b8");case"not-in-scope-2.2":return Se("Not in scope (WCAG 2.2)","#94a3b8")}}function Mu(e){switch(e){case"de-facto-standard":return Se("De facto via WCAG AA","#059669");case"gray-area":return Se("Gray area (new SC)","#f59e0b")}}function Du(e){switch(e){case"in-scope":return Se("In scope","#059669");case"product-related":return Se("Product-related","#0ea5e9");case"gray-area":return Se("Gray area","#f59e0b")}}function Nu(e){switch(e){case"in-scope":return Se("In scope (WCAG 2.0)","#059669");case"not-in-scope-2.1":return Se("Not in scope (2.1+)","#94a3b8");case"not-in-scope-2.2":return Se("Not in scope (2.2)","#94a3b8")}}function Lu(e={}){var l;const t=e.wcagTargetOverride??Le,a=e.results?Ru(e.results):new Set,n=(((l=e.results)==null?void 0:l.length)??0)>0,o=new Set(Tt(t,"AA").map(d=>d.id)),r=Eu.map(d=>{const u=a.has(d.wcagId),m=o.has(d.wcagId),p=u?"background:#fee2e2;":m?"":"background:#f8fafc; opacity:0.6;",f=u?'<div style="font-size:9pt; color:#b91c1c; font-weight:700; margin-top:2pt">⚠ Violated in this audit</div>':"";return`<tr style="${p}">
|
|
1214
1214
|
<td style="padding:5pt 6pt; vertical-align:top; border-bottom:1px solid #e2e8f0">
|
|
1215
1215
|
<div style="font-family:monospace; font-weight:600">${Ce(d.wcagId)}</div>
|
|
1216
1216
|
<div style="font-size:9pt; color:#475569">${Ce(d.level)} · added ${Ce(d.addedIn)}</div>
|
|
@@ -1223,11 +1223,11 @@ ${Eu()}
|
|
|
1223
1223
|
<td style="padding:5pt 6pt; vertical-align:top; border-bottom:1px solid #e2e8f0; font-family:monospace; font-size:9pt">
|
|
1224
1224
|
${d.en301549Clause?`§${Ce(d.en301549Clause)}`:'<span style="color:#94a3b8">—</span>'}
|
|
1225
1225
|
</td>
|
|
1226
|
-
<td style="padding:5pt 6pt; vertical-align:top; border-bottom:1px solid #e2e8f0">${
|
|
1227
|
-
<td style="padding:5pt 6pt; vertical-align:top; border-bottom:1px solid #e2e8f0">${
|
|
1228
|
-
<td style="padding:5pt 6pt; vertical-align:top; border-bottom:1px solid #e2e8f0">${
|
|
1229
|
-
<td style="padding:5pt 6pt; vertical-align:top; border-bottom:1px solid #e2e8f0">${
|
|
1230
|
-
</tr>`}).join(""),
|
|
1226
|
+
<td style="padding:5pt 6pt; vertical-align:top; border-bottom:1px solid #e2e8f0">${Ou(d.section508)}</td>
|
|
1227
|
+
<td style="padding:5pt 6pt; vertical-align:top; border-bottom:1px solid #e2e8f0">${Mu(d.adaTitleIII)}</td>
|
|
1228
|
+
<td style="padding:5pt 6pt; vertical-align:top; border-bottom:1px solid #e2e8f0">${Du(d.eaa)}</td>
|
|
1229
|
+
<td style="padding:5pt 6pt; vertical-align:top; border-bottom:1px solid #e2e8f0">${Nu(d.aoda)}</td>
|
|
1230
|
+
</tr>`}).join(""),i=a.size,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`<!doctype html>
|
|
1231
1231
|
<html lang="en">
|
|
1232
1232
|
<head>
|
|
1233
1233
|
<meta charset="utf-8" />
|
|
@@ -1287,7 +1287,7 @@ ${c}
|
|
|
1287
1287
|
</tr>
|
|
1288
1288
|
</thead>
|
|
1289
1289
|
<tbody>
|
|
1290
|
-
${
|
|
1290
|
+
${r}
|
|
1291
1291
|
</tbody>
|
|
1292
1292
|
</table>
|
|
1293
1293
|
|
|
@@ -1297,14 +1297,14 @@ ${c}
|
|
|
1297
1297
|
</section>
|
|
1298
1298
|
|
|
1299
1299
|
</body>
|
|
1300
|
-
</html>`}const Io={critical:4,serious:3,moderate:2,minor:1},
|
|
1301
|
-
`)}function
|
|
1300
|
+
</html>`}const Io={critical:4,serious:3,moderate:2,minor:1},ji={critical:"🔴",serious:"🟠",moderate:"🟡",minor:"⚪"};function Pu(e,t){return e.length>t?e.slice(0,t-1)+"…":e}function Fu(e){const t=e.split(" > ");return t[t.length-1]??e}function _u(e,t,a){const n=at[t.ruleId],o=[];return o.push(`## Ticket ${e} — ${ji[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(`
|
|
1301
|
+
`)}function Uu(e){var l;const t=e.results.flatMap(d=>d.violations),a=new Map;for(const d of t){const u=Te(d.ruleId,d.target.selector),m=a.get(u);m?m._instances+=1:a.set(u,{...d,_instances:1})}const n=Array.from(a.values()).sort((d,u)=>{const m=Io[u.impact]-Io[d.impact];return m!==0?m:d.ruleId.localeCompare(u.ruleId)}),o=e.pageUrlOverride??((l=e.results[0])==null?void 0:l.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((d,u)=>{const m=Pu(Fu(d.target.selector),32).replace(/\|/g,"\\|");i.push(`| ${u+1} | ${ji[d.impact]} ${d.impact} | \`${d.ruleId}\` | ${d.wcagCriterion} ${d.wcagLevel} | \`${m}\` |`)}),i.push(""),i.push("---"),i.push("");const c=n.map((d,u)=>_u(u+1,d,o)).join(`
|
|
1302
1302
|
---
|
|
1303
1303
|
|
|
1304
|
-
`);return n.length===0?[
|
|
1304
|
+
`);return n.length===0?[i.join(`
|
|
1305
1305
|
`),"_No violations to file. Run an audit first._"].join(`
|
|
1306
|
-
`):
|
|
1307
|
-
`)+c}const xo={critical:4,serious:3,moderate:2,minor:1};function le(e){return e.replace(/[&<>"']/g,t=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[t])}function
|
|
1306
|
+
`):i.join(`
|
|
1307
|
+
`)+c}const xo={critical:4,serious:3,moderate:2,minor:1};function le(e){return e.replace(/[&<>"']/g,t=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[t])}function Wu(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}`,l=r.get(c);if(l){l._instances+=1;continue}r.set(c,{...i,_instances:1})}return Array.from(r.values()).sort((i,c)=>{const l=xo[c.impact]-xo[i.impact];return l!==0?l:i.ruleId.localeCompare(c.ruleId)}).slice(0,t)}function qu(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 Vu(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 ju(e,t={}){const a=e.flatMap(T=>T.violations),n=$e(a,t.manualRuns,e,t.acknowledgedMatchKeys,t.interactiveAuditResults,t.walkthroughAcks,t.humanCriterionVerdicts,st(e),t.incompleteResolutions),o=n.letter,r={critical:n.totals.critical,serious:n.totals.serious,moderate:n.totals.moderate,minor:n.totals.minor},i=Wu(e,3,t.acknowledgedMatchKeys),c=new Map(Tt("2.1","AA").map(T=>[T.id,T.title])),l=new Map,d={untested:0,inconclusive:1,failing:2};function u(T,P){for(const _ of T){const N=l.get(_);(!N||d[P]>d[N.state])&&l.set(_,{id:_,title:c.get(_)??"(criterion title unavailable)",state:P})}}n.coverage&&(u(n.coverage.untestedCriteria,"untested"),u(n.coverage.inconclusiveCriteria,"inconclusive"),u(n.coverage.failingCriteria,"failing"));const m=Array.from(l.values()).sort((T,P)=>T.id.localeCompare(P.id,void 0,{numeric:!0})),p=Vu(i,o,m.length,m.map(T=>T.id)),f=e[0],g=(f==null?void 0:f.pageUrl)??"(unknown)",h=(f==null?void 0:f.axeVersion)??"4.11.4",y=e.length,b=t.asOfDateOverride??(f==null?void 0:f.startedAt)??new Date().toISOString(),A={A:"#059669",B:"#16a34a",C:"#f59e0b",D:"#ea580c",F:"#dc2626"},v=t.orgName?`<p class="org">Prepared for <strong>${le(t.orgName)}</strong></p>`:"",s=t.logoUrl?`<img src="${le(t.logoUrl)}" alt="${le(t.orgName??"Logo")}" class="logo" />`:"",k=i.length===0?'<p class="empty">No findings surfaced. Manual review still recommended for criteria automation cannot evaluate.</p>':`<ol class="risks">${i.map(T=>`<li>
|
|
1308
1308
|
<div class="risk-head">
|
|
1309
1309
|
<span class="risk-impact risk-${le(T.impact)}">${le(T.impact)}</span>
|
|
1310
1310
|
<code>${le(T.ruleId)}</code>
|
|
@@ -1381,8 +1381,8 @@ ${c}
|
|
|
1381
1381
|
<section class="hero" aria-label="Audit summary">
|
|
1382
1382
|
<div class="grade" style="background:${A[o]}">${o}</div>
|
|
1383
1383
|
<div class="hero-text">
|
|
1384
|
-
<strong>${
|
|
1385
|
-
${le(
|
|
1384
|
+
<strong>${r.critical} critical · ${r.serious} serious · ${r.moderate} moderate · ${r.minor} minor</strong>
|
|
1385
|
+
${le(qu(o,{moderate:r.moderate,cappedByCoverage:n.caps.cappedAtBByCoverage}))}
|
|
1386
1386
|
</div>
|
|
1387
1387
|
</section>
|
|
1388
1388
|
|
|
@@ -1412,31 +1412,31 @@ ${R}
|
|
|
1412
1412
|
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.
|
|
1413
1413
|
</footer>
|
|
1414
1414
|
</body>
|
|
1415
|
-
</html>`}const
|
|
1416
|
-
`),Ma=ee("ai-compliance-summarizer");async function
|
|
1415
|
+
</html>`}const Gu=["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 So(e){if(!e)return"ai-fixable";const t=e.toLowerCase();return Gu.some(a=>t.includes(a))?"human-verify":"ai-fixable"}const zu=["## 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(`
|
|
1416
|
+
`),Ma=ee("ai-compliance-summarizer");async function Gi(e,t){if(!t.enabled)return null;const a=ue(t);if(!a.ok)return Ma.debug(`AI client unavailable: ${a.reason}`),null;const n=Ee(t.costCapUsd);if(!n.canCharge())return null;try{const o=await a.client.generateExecutiveSummary(e);return n.recordCharge(o.costUsd),!o.lead&&!o.body?(Ma.debug("AI summary returned empty"),null):o}catch(o){return Ma.warn("compliance-summary generation failed",o),null}}async function Hu(){const e=await chrome.storage.local.get("aiConfig");return we(e.aiConfig)}function oh(){return Ie("AI_COMPLIANCE_SUMMARY_REQUEST",async e=>{const t=await fe();if(!de(t,"aiComplianceSummary"))return{type:"AI_COMPLIANCE_SUMMARY_RESPONSE",summary:null,unavailableReason:"AI compliance summary is not available on your current plan."};const a=await Hu();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 Gi(e.input,a);return{type:"AI_COMPLIANCE_SUMMARY_RESPONSE",summary:n,unavailableReason:n?void 0:"AI summary generation returned no result."}})}const xe="wcag-component-auditor";function He(){try{return chrome.runtime.getManifest().version}catch{return"0.0.0"}}function _e(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 zi(e,t){return{schemaVersion:1,generatedAt:new Date().toISOString(),tool:{name:xe,version:He()},results:e,delta:t}}function Co(e){return e==="critical"||e==="serious"?"error":e==="moderate"?"warning":"note"}function Hi(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:Co(c.impact)},properties:{tags:[c.wcagCriterion,`wcag-${c.wcagLevel}`]}}));const r=_e(e),i=a.map(c=>({ruleId:c.ruleId,level:Co(c.impact),message:{text:`${c.description}`+(c.target.failureSummary?`
|
|
1417
1417
|
|
|
1418
|
-
${c.target.failureSummary}`:"")},locations:[{physicalLocation:{artifactLocation:{uri:
|
|
1418
|
+
${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:xe,version:He(),informationUri:"https://wcagcheckr.com",rules:o}},results:i}]}}function Bi(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function We(e){return Bi(e).replace(/\n/g," ").replace(/\r/g," ")}function Ki(e,t){const a=!!t,n=d=>(a?d.violations.filter(u=>t.new.some(m=>m.matchKey===u.matchKey)):d.violations).filter(u=>!u.needsReview),o=e.reduce((d,u)=>d+Math.max(1,u.violations.length),0),r=e.reduce((d,u)=>d+n(u).length,0),i=e.reduce((d,u)=>d+u.durationMs,0)/1e3,c=[];c.push('<?xml version="1.0" encoding="UTF-8"?>');const l=`${xe} — ${_e(e)}`;c.push(`<testsuites name="${We(l)}" tests="${o}" failures="${r}" time="${i.toFixed(3)}">`);for(const d of e){const u=`${d.state.pseudoState}_${d.state.theme}_${d.state.direction}_${d.state.breakpoint.id}`,m=`${d.componentId}::${u}`,p=n(d),f=Math.max(1,d.violations.length);if(c.push(` <testsuite name="${We(m)}" tests="${f}" failures="${p.length}" time="${(d.durationMs/1e3).toFixed(3)}">`),d.violations.length===0)c.push(` <testcase classname="${We(m)}" name="no-violations" time="${(d.durationMs/1e3).toFixed(3)}" />`);else for(const g of d.violations){const h=p.some(v=>v.matchKey===g.matchKey),y=`classname="${We(m)}" name="${We(g.ruleId)}" time="0"`;if(!h){c.push(` <testcase ${y} />`);continue}const b=`${g.impact} - ${g.description}`,A=`Selector: ${g.target.selector}
|
|
1419
1419
|
WCAG: ${g.wcagCriterion} (${g.wcagLevel})
|
|
1420
1420
|
State: ${u}
|
|
1421
1421
|
`+(g.helpUrl?`Help: ${g.helpUrl}
|
|
1422
1422
|
`:"")+(g.target.failureSummary?`
|
|
1423
|
-
${g.target.failureSummary}`:"");c.push(` <testcase ${y}>`),c.push(` <failure message="${We(b)}" type="${We(g.ruleId)}">${
|
|
1424
|
-
`)}function O(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function
|
|
1423
|
+
${g.target.failureSummary}`:"");c.push(` <testcase ${y}>`),c.push(` <failure message="${We(b)}" type="${We(g.ruleId)}">${Bi(A)}</failure>`),c.push(" </testcase>")}c.push(" </testsuite>")}return c.push("</testsuites>"),c.join(`
|
|
1424
|
+
`)}function O(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function Bu(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)=>`
|
|
1425
1425
|
<tr>
|
|
1426
1426
|
<td>${c+1}</td>
|
|
1427
|
-
<td><span class="impact impact-${O(
|
|
1428
|
-
<td><code>${O(
|
|
1429
|
-
<td>${O(
|
|
1430
|
-
<td>${O(
|
|
1431
|
-
<td><code class="sel">${O(
|
|
1432
|
-
</tr>`).join(""),
|
|
1427
|
+
<td><span class="impact impact-${O(i.impact)}">${O(i.impact)}</span></td>
|
|
1428
|
+
<td><code>${O(i.criterionId)}</code></td>
|
|
1429
|
+
<td>${O(i.verdict.toUpperCase())}</td>
|
|
1430
|
+
<td>${O(i.reasoning)}</td>
|
|
1431
|
+
<td><code class="sel">${O(i.pageUrl)}</code></td>
|
|
1432
|
+
</tr>`).join(""),r=t.map((i,c)=>{const l=n.get(`${i.criterionId}::${i.pageUrl}`),d=(l==null?void 0:l.note)??"(note missing)",u=l!=null&&l.acknowledgedAt?new Date(l.acknowledgedAt).toLocaleString():"(timestamp missing)";return`
|
|
1433
1433
|
<tr>
|
|
1434
1434
|
<td>${c+1}</td>
|
|
1435
|
-
<td><code>${O(
|
|
1436
|
-
<td>AI: ${O(
|
|
1435
|
+
<td><code>${O(i.criterionId)}</code></td>
|
|
1436
|
+
<td>AI: ${O(i.verdict.toUpperCase())} → ✓ Human verified</td>
|
|
1437
1437
|
<td>${O(d)}</td>
|
|
1438
1438
|
<td>${O(u)}</td>
|
|
1439
|
-
<td><code class="sel">${O(
|
|
1439
|
+
<td><code class="sel">${O(i.pageUrl)}</code></td>
|
|
1440
1440
|
</tr>`}).join("");return`
|
|
1441
1441
|
<h2 id="walkthroughs">3a. AI walkthrough findings</h2>
|
|
1442
1442
|
<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>
|
|
@@ -1453,8 +1453,8 @@ ${t.length===0?"":`<h3 style="margin-top:12pt">Human verified (${t.length})</h3>
|
|
|
1453
1453
|
<thead>
|
|
1454
1454
|
<tr><th>#</th><th>Criterion</th><th>Chain</th><th>Verification note</th><th>Recorded at</th><th>Page</th></tr>
|
|
1455
1455
|
</thead>
|
|
1456
|
-
<tbody>${
|
|
1457
|
-
</table>`}`}function Tn(e,t,a){var A,v,s,k,x;const n=((A=e[0])==null?void 0:A.componentId)??"unknown",o=_e(e),
|
|
1456
|
+
<tbody>${r}</tbody>
|
|
1457
|
+
</table>`}`}function Tn(e,t,a){var A,v,s,k,x;const n=((A=e[0])==null?void 0:A.componentId)??"unknown",o=_e(e),r=a??e.reduce((w,R)=>w+R.durationMs,0),i=e.flatMap(w=>w.violations),c=new Map;for(const w of i){const R=`${w.ruleId}::${w.target.selector}`,T=`:${w.currentState.pseudoState} · ${w.currentState.theme} · ${w.currentState.direction}`,P=c.get(R);if(P){P._states.includes(T)||P._states.push(T);continue}c.set(R,{...w,_states:[T]})}const l=Array.from(c.values()),d={critical:[],serious:[],moderate:[],minor:[]};for(const w of l)(d[w.impact]??d.moderate).push(w);const u=new Set(((v=t==null?void 0:t.new)==null?void 0:v.map(w=>`${w.ruleId}::${w.target.selector}`))??[]),m=new Set(((s=t==null?void 0:t.persistent)==null?void 0:s.map(w=>`${w.ruleId}::${w.target.selector}`))??[]),p=new Set(((k=t==null?void 0:t.fixed)==null?void 0:k.map(w=>`${w.ruleId}::${w.target.selector}`))??[]);let f=0,g=0;for(const w of l){const R=`${w.ruleId}::${w.target.selector}`;m.has(R)?g++:u.has(R)&&f++}let h=0;for(const w of p)!m.has(w)&&!u.has(w)&&h++;const y=w=>{const R=u.has(`${w.ruleId}::${w.target.selector}`);return`
|
|
1458
1458
|
<article class="violation impact-${O(w.impact)}${R?" is-new":""}">
|
|
1459
1459
|
<header>
|
|
1460
1460
|
<span class="rule">${O(w.ruleId)}</span>
|
|
@@ -1538,8 +1538,8 @@ ${t.length===0?"":`<h3 style="margin-top:12pt">Human verified (${t.length})</h3>
|
|
|
1538
1538
|
<p class="summary">
|
|
1539
1539
|
<span><strong>States audited:</strong> ${e.length}</span>
|
|
1540
1540
|
<span><strong>Unique violations:</strong> ${l.length}</span>
|
|
1541
|
-
<span><strong>Total violation instances:</strong> ${
|
|
1542
|
-
<span><strong>Audit duration:</strong> ${(
|
|
1541
|
+
<span><strong>Total violation instances:</strong> ${i.length}</span>
|
|
1542
|
+
<span><strong>Audit duration:</strong> ${(r/1e3).toFixed(1)}s</span>
|
|
1543
1543
|
</p>
|
|
1544
1544
|
${t!=null&&t.matrixMismatchWarning?`
|
|
1545
1545
|
<p class="summary" style="background: #fef3c7; border: 1px solid #f59e0b; padding: 8pt 10pt; border-radius: 3pt;">
|
|
@@ -1569,13 +1569,13 @@ ${t.length===0?"":`<h3 style="margin-top:12pt">Human verified (${t.length})</h3>
|
|
|
1569
1569
|
Generated by ${xe} v${He()}. Full audit — all detected violations included, deduped across states. Items flagged "NEW vs baseline" were not present in the most-recent accepted baseline.
|
|
1570
1570
|
</footer>
|
|
1571
1571
|
</body>
|
|
1572
|
-
</html>`}const
|
|
1572
|
+
</html>`}const Yi=[{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 Ji(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 l=e.rules.filter(m=>t.has(m));if(l.length>0)return{conformance:"Partially Supports",hits:l};if((c==null?void 0:c.verdict)==="fail")return{conformance:"Partially Supports",hits:["AI walkthrough verdict: fail"]};const d=e.rules.some(m=>a.has(m)),u=(c==null?void 0:c.verdict)==="pass";return d||u?{conformance:"Supports",hits:[]}:{conformance:"Not Evaluated",hits:[]}}function Xi(e,t,a,n,o,r){var h,y;const i=((h=e[0])==null?void 0:h.componentId)??"unknown",c=_e(e),l=n??new Set,d=e.flatMap(b=>b.violations).filter(b=>!l.has(b.matchKey)),u=new Set(d.map(b=>b.ruleId)),m=new Map;for(const b of o??[])m.set(b.criterionId,b.verdict);const p=new Set(u);for(const b of e){const A=b.axeRulesEvaluated;if(A){for(const v of A.passed)p.add(v.ruleId);for(const v of A.inapplicable)p.add(v.ruleId);for(const v of A.incomplete)p.add(v.ruleId)}}const f=b=>{const{conformance:A,hits:v}=Ji(b,u,p,a,m.get(b.ref),r);return`
|
|
1573
1573
|
<tr class="${A==="Supports"?"supports":A==="Partially Supports"?"partial":A==="Not Evaluated"?"not-evaluated":"na"}">
|
|
1574
1574
|
<td class="ref">${O(b.ref)}</td>
|
|
1575
1575
|
<td class="title">${O(b.title)} <span class="level">(${b.level})</span></td>
|
|
1576
1576
|
<td class="conf">${A}</td>
|
|
1577
1577
|
<td class="notes">${v.length>0?`Auto-detected violations of: ${v.map(k=>`<code>${O(k)}</code>`).join(", ")}. Manual review recommended.`:A==="Not Applicable"?"No automated rule maps to this criterion. Manual evaluation required.":"No automated violations detected. Manual confirmation recommended for full claim."}</td>
|
|
1578
|
-
</tr>`},g=b=>{const A=
|
|
1578
|
+
</tr>`},g=b=>{const A=Yi.filter(v=>v.level===b).map(f).join("");return`
|
|
1579
1579
|
<h2>WCAG 2.1 Level ${b}</h2>
|
|
1580
1580
|
<table>
|
|
1581
1581
|
<thead>
|
|
@@ -1586,7 +1586,7 @@ ${t.length===0?"":`<h3 style="margin-top:12pt">Human verified (${t.length})</h3>
|
|
|
1586
1586
|
<html lang="en">
|
|
1587
1587
|
<head>
|
|
1588
1588
|
<meta charset="utf-8" />
|
|
1589
|
-
<title>VPAT — ${O(
|
|
1589
|
+
<title>VPAT — ${O(i)}</title>
|
|
1590
1590
|
<style>
|
|
1591
1591
|
body { font: 11pt/1.5 -apple-system, system-ui, sans-serif; color: #0f172a; max-width: 8in; margin: 0.5in auto; padding: 0 0.25in; }
|
|
1592
1592
|
h1 { font-size: 18pt; }
|
|
@@ -1609,7 +1609,7 @@ ${t.length===0?"":`<h3 style="margin-top:12pt">Human verified (${t.length})</h3>
|
|
|
1609
1609
|
</head>
|
|
1610
1610
|
<body>
|
|
1611
1611
|
<h1>Voluntary Product Accessibility Template (VPAT 2.5)</h1>
|
|
1612
|
-
<p class="meta"><strong>Product:</strong> ${O(
|
|
1612
|
+
<p class="meta"><strong>Product:</strong> ${O(i)}</p>
|
|
1613
1613
|
<p class="meta" style="word-break: break-all;"><strong>URL evaluated:</strong> <code>${O(c)}</code></p>
|
|
1614
1614
|
<p class="meta"><strong>Date:</strong> ${O(new Date().toLocaleString())}</p>
|
|
1615
1615
|
<p class="meta"><strong>Evaluation method:</strong> Automated audit via wcagcheckr (axe-core ${O(((y=e[0])==null?void 0:y.axeVersion)??"n/a")}) across ${e.length} configured states.</p>
|
|
@@ -1626,12 +1626,12 @@ ${t.length===0?"":`<h3 style="margin-top:12pt">Human verified (${t.length})</h3>
|
|
|
1626
1626
|
Generated by ${xe} v${He()}. Conformance assessed against all violations detected during the audit (not delta-filtered).
|
|
1627
1627
|
</footer>
|
|
1628
1628
|
</body>
|
|
1629
|
-
</html>`}function Ju(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 i=/<(?:i|svg|span)[^>]*class\s*=\s*"([^"]*(?:icon|fa-|material-icon)[^"]*)"/i.exec(a);i&&t.push({label:"Icon class hint",value:`\`${i[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 i=/\btype\s*=\s*"([^"]+)"|\btype\s*=\s*'([^']+)'/i.exec(a);i&&t.push({label:"Input type",value:`\`${i[1]??i[2]}\``});const r=/\bautocomplete\s*=\s*"([^"]+)"|\bautocomplete\s*=\s*'([^']+)'/i.exec(a);r&&t.push({label:"Autocomplete",value:r[1]??r[2]})}return t}function Xu(e,t){var r;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,i=[];for(const c of e){const l=c.pageUrl??c.scope,d=((r=c.axeRulesEvaluated)==null?void 0:r.incomplete)??[];for(const u of d)for(const m of u.elements??[]){const p=`${l}::${u.ruleId}::${m.selector}`;o.has(p)||a.has(p)||(o.add(p),i.push({pageUrl:l,ruleId:u.ruleId,wcagCriterion:u.wcagCriterion,selector:m.selector,failureSummary:m.failureSummary,styles:m.styles,aiAttemptReasoning:n.get(p)}))}}return i}function Zr(e,t,a,n,o,i,r,c,l){var Z,ke,ie,ne,ge,C,W,H,Q,se,ce;const d=new Set(o??[]),u=new Set(l??[]),m=((Z=e[0])==null?void 0:Z.componentId)??"unknown",p=_e(e),f=!!(t&&t.baselineSnapshotMeta),g=e.flatMap(I=>I.violations),h=u.size>0?g.filter(I=>u.has(I.matchKey)):[],y=I=>d.has(`violation::${I}`),b=g.filter(I=>!u.has(I.matchKey)&&!y(I.matchKey)),A=new Map;for(const I of b){const B=I.ruleId.startsWith("ai-")?`${I.ruleId}::${I.target.selector}::${(I.target.outerHTML??"").slice(0,200)}`:Te(I.ruleId,I.target.selector),L=`${I.currentState.pseudoState} · ${I.currentState.theme} · ${I.currentState.direction} · ${I.currentState.breakpoint.id}`,K=A.get(B);if(K){K._states.includes(L)||K._states.push(L),K._instanceSelectors.includes(I.target.selector)||K._instanceSelectors.push(I.target.selector);continue}A.set(B,{...I,_states:[L],_instanceSelectors:[I.target.selector]})}const v=Array.from(A.values()).sort((I,B)=>{const L={critical:0,serious:1,moderate:2,minor:3};return(L[I.impact]??99)-(L[B.impact]??99)}),s=[];s.push("# Accessibility Fix Request"),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 ${((ke=e[0])==null?void 0:ke.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("- ✅ **Applied** — the canonical fix from this prompt was applied to the source. Cite the file + line."),s.push("- ⚠ **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 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> | ✅ / ⚠ / ❓ | <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 k=a&&a.length>0?{runs:a,workflows:Oe}:void 0,x=c==null?void 0:c.map(I=>({criterionId:I.criterionId,ruleId:`ai-interactive::${I.criterionId}`,pageUrl:I.pageUrl,verdict:I.verdict,reasoning:I.reasoning})),w=$e(g,k,e,void 0,x,void 0,void 0,st(e),i);if(s.push("## Context"),s.push(""),s.push(`- **Component / scope:** \`${m}\``),s.push(`- **Audited URL:** ${p}`),s.push(`- **WCAG target:** WCAG ${Le} ${gn} (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 **${w.letter}** · **${w.risk.toUpperCase()} risk** (${w.totals.critical} critical · ${w.totals.serious} serious · ${w.totals.moderate} moderate · ${w.totals.minor} minor). ${w.risk==="critical"||w.risk==="high"?"Treat as triage priority — these violations represent meaningful lawsuit exposure under ADA Title III, EAA, and EN 301 549.":w.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."}`),w.coverage){const I=w.coverage.untestedCriteria.length;I>0?s.push(`- **WCAG ${w.coverage.targetVersion} ${w.coverage.targetLevel} coverage:** ${w.coverage.evaluated} of ${w.coverage.totalApplicable} criteria evaluated. **Cannot claim ${w.coverage.targetLevel} conformance** until ${I} untested criteria are evaluated via Guided Tests (Pass / Fail / N/A). Untested: ${w.coverage.untestedCriteria.join(", ")}.`):s.push(`- **WCAG ${w.coverage.targetVersion} ${w.coverage.targetLevel} coverage:** ${w.coverage.evaluated} of ${w.coverage.totalApplicable} criteria evaluated. Full coverage — defensible conformance claim possible once all violations below are fixed.`)}f&&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("## ⛔ 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 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 R=(((ie=e[0])==null?void 0:ie.readingOrderIssues)??[]).filter(I=>!d.has(`reading-order::${I.selector}`)),T=(ne=e[0])==null?void 0:ne.positionAnalysisCapturedAt,P=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)",_=c==null?void 0:c.some(I=>I.criterionId==="1.3.2");if(R.length>0&&!_){s.push("## Reading-order concerns (DOM ≠ visual order)"),s.push(""),s.push(`_Positions captured at: **${P}**. 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. ${R.length} element${R.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 I of R){const B=I.textSnippet.replace(/\|/g,"\\|").replace(/\n/g," ");s.push(`| ${I.domIndex} | ${I.visualIndex} | \`${I.selector}\` | ${B} |`)}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 N=(((ge=e[0])==null?void 0:ge.tabOrderIssues)??[]).filter(I=>!d.has(`tab-order::${I.selector}`)),M=c==null?void 0:c.some(I=>I.criterionId==="2.1.2"&&I.verdict==="pass");if(N.length>0&&!M){const I=N.filter(L=>L.flag==="visual"||L.flag==="both").length,B=N.filter(L=>L.flag==="tabindex"||L.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: **${P}**. 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. ${N.length} focusable element${N.length===1?" has":"s have"} a notable divergence. Of these: ${I} ${I===1?"has":"have"} a visual-vs-tab mismatch (focus jumps around the page); ${B} ${B===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 L of N){const K=L.textSnippet.replace(/\|/g,"\\|").replace(/\n/g," ");s.push(`| ${L.tabPosition} | ${L.visualPosition} | ${L.domPosition} | ${L.flag} | \`${L.selector}\` | ${K} |`)}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 S=e.flatMap(I=>I.announcements??[]),V=e.flatMap(I=>I.focusEvents??[]).filter(I=>I.isFocusReset);if(S.length>0||V.length>0){if(s.push("## Runtime behavioral observations"),s.push(""),S.length>0){const I=S.filter(L=>L.politeness==="assertive").length;s.push(`**Live-region announcements** (${S.length} total, ${I} 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 B=S.slice(0,8);for(const L of B){const K=L.text.replace(/\|/g,"\\|").replace(/\n/g," ").slice(0,120);s.push(`- \`[${L.politeness}${L.role?`/${L.role}`:""}]\` ${K}`)}S.length>8&&s.push(`- (and ${S.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(V.length>0){s.push(`**Focus resets to body** (${V.length} occurrence${V.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 I of V.slice(0,5))s.push(`- \`${I.fromSelector??"(none)"}\` → \`${I.toSelector}\``);V.length>5&&s.push(`- (and ${V.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 D=((C=e[0])==null?void 0:C.undefinedCustomProperties)??[];if(D.length>0){s.push("## Undefined CSS custom properties (cascade root cause)"),s.push(""),s.push(`${D.length} CSS custom propert${D.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 I of D){const B=I.sampleSites.map(L=>`\`${L.selector} { ${L.property} }\``).join("; ");s.push(`| \`${I.name}\` | ${I.referenceCount} | ${B} |`)}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 I=Oe;s.push("| Workflow | Status | Notes |"),s.push("|---|---|---|");for(const X of a){const j=I.find(ya=>ya.id===X.workflowId);if(!j)continue;let J=0,G=0,be=0,Ue=0,Ye=0;for(const ya of j.steps){const ft=X.steps[ya.id];if(!ft){Ye++;continue}ft.status==="pass"?J++:ft.status==="fail"?G++:ft.status==="skip"?be++:ft.status==="not-applicable"?Ue++:Ye++}const ii=G>0?`❌ ${G} failed`:Ye>0?`⚠ ${Ye} unanswered`:`✓ all ${j.steps.length} answered`,Ot=[`${J}p`,`${G}f`];Ue>0&&Ot.push(`${Ue} N/A`),be>0&&Ot.push(`${be} skip`),Ye>0&&Ot.push(`${Ye} unanswered`);const si=`${Ot.join(" · ")} of ${j.steps.length} steps`;s.push(`| ${j.name} | ${ii} | ${si} |`)}s.push("");const B=[];for(const X of a){const j=I.find(J=>J.id===X.workflowId);if(j)for(const J of j.steps){const G=X.steps[J.id];(G==null?void 0:G.status)==="fail"&&B.push({workflow:j.name,stepTitle:J.question,notes:G.notes})}}if(B.length>0){s.push("**Failed manual checks** (these are real WCAG failures the consultant verified by hand):"),s.push("");for(const X of B)s.push(`- **${X.workflow} → ${X.stepTitle}**${X.notes?`: ${X.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 L=new Set(a.map(X=>X.workflowId)),K=I.filter(X=>!L.has(X.id));K.length>0&&(s.push(`**Not yet manually verified** (${K.length} workflow${K.length===1?"":"s"}): `+K.map(X=>X.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 I=(()=>{try{return new URL(p).origin}catch{return null}})(),B=(()=>{try{return new URL(n.startUrl).origin}catch{return null}})();if(I&&B&&I===B){const L=n.finishedAt,K=L?Date.now()-new Date(L).getTime():0,X=K<6e4?"just now":K<36e5?`${Math.round(K/6e4)} minute${Math.round(K/6e4)===1?"":"s"} ago`:K<864e5?`${Math.round(K/36e5)} hour${Math.round(K/36e5)===1?"":"s"} ago`:`${Math.round(K/864e5)} day${Math.round(K/864e5)===1?"":"s"} ago`;if(s.push("## Site-wide context (from a recent site crawl)"),s.push(""),s.push(`A crawl ${L?`(${X})`:""} of ${n.pagesAudited} page${n.pagesAudited===1?"":"s"} on this origin produced grade **${n.siteGrade}** 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 J of n.topViolations.slice(0,6))s.push(`- \`${J.ruleId}\` — ${J.impact} — found on ${J.urlsAffected} page${J.urlsAffected===1?"":"s"} (${J.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 j=n.consistencyFindings??[];if(j.length===0&&n.topViolations.some(G=>G.ruleId==="wcc-consistency-needs-site-crawl"||G.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("")),j.length>0){s.push("**Cross-page consistency divergences detected:**"),s.push("");for(const J of j){const G=J.aiVerdict?J.aiVerdict.verdict==="uncertain"?" (AI: uncertain — human verify)":` (AI: confirmed real, confidence ${(J.aiVerdict.confidence*100).toFixed(0)}%)`:"";s.push(`- **${J.wcagCriterion} ${J.impact}**${G} — ${J.description}`);for(const be of J.details.split(`
|
|
1630
|
-
`))s.push(` ${be}`);(W=J.aiVerdict)!=null&&W.reasoning&&s.push(` AI reasoning: ${J.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(h.length>0){const I=new Map;for(const L of h)I.has(L.matchKey)||I.set(L.matchKey,L);const B=Array.from(I.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 ${B.length} finding${B.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(""),B.forEach((L,K)=>{s.push(`${K+1}. \`${L.ruleId}\` on \`${L.target.selector}\``),L.target.accessibleName&&s.push(` - Accessible name: "${L.target.accessibleName}"`),L.target.textSnippet&&s.push(` - Text: "${L.target.textSnippet.slice(0,120)}"`),s.push(` - WCAG ${L.wcagCriterion} ${L.wcagLevel} · ${L.impact}`)}),s.push(""),s.push("---"),s.push("")}const $=(
|
|
1629
|
+
</html>`}function Ku(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 Yu(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 l=c.pageUrl??c.scope,d=((i=c.axeRulesEvaluated)==null?void 0:i.incomplete)??[];for(const u of d)for(const m of u.elements??[]){const p=`${l}::${u.ruleId}::${m.selector}`;o.has(p)||a.has(p)||(o.add(p),r.push({pageUrl:l,ruleId:u.ruleId,wcagCriterion:u.wcagCriterion,selector:m.selector,failureSummary:m.failureSummary,styles:m.styles,aiAttemptReasoning:n.get(p)}))}}return r}function Qi(e,t,a,n,o,r,i,c,l){var Z,ke,re,ne,ge,C,W,H,Q,se,ce;const d=new Set(o??[]),u=new Set(l??[]),m=((Z=e[0])==null?void 0:Z.componentId)??"unknown",p=_e(e),f=!!(t&&t.baselineSnapshotMeta),g=e.flatMap(I=>I.violations),h=u.size>0?g.filter(I=>u.has(I.matchKey)):[],y=I=>d.has(`violation::${I}`),b=g.filter(I=>!u.has(I.matchKey)&&!y(I.matchKey)),A=new Map;for(const I of b){const B=I.ruleId.startsWith("ai-")?`${I.ruleId}::${I.target.selector}::${(I.target.outerHTML??"").slice(0,200)}`:Te(I.ruleId,I.target.selector),L=`${I.currentState.pseudoState} · ${I.currentState.theme} · ${I.currentState.direction} · ${I.currentState.breakpoint.id}`,K=A.get(B);if(K){K._states.includes(L)||K._states.push(L),K._instanceSelectors.includes(I.target.selector)||K._instanceSelectors.push(I.target.selector);continue}A.set(B,{...I,_states:[L],_instanceSelectors:[I.target.selector]})}const v=Array.from(A.values()).sort((I,B)=>{const L={critical:0,serious:1,moderate:2,minor:3};return(L[I.impact]??99)-(L[B.impact]??99)}),s=[];s.push("# Accessibility Fix Request"),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 ${((ke=e[0])==null?void 0:ke.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("- ✅ **Applied** — the canonical fix from this prompt was applied to the source. Cite the file + line."),s.push("- ⚠ **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 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> | ✅ / ⚠ / ❓ | <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 k=a&&a.length>0?{runs:a,workflows:Oe}:void 0,x=c==null?void 0:c.map(I=>({criterionId:I.criterionId,ruleId:`ai-interactive::${I.criterionId}`,pageUrl:I.pageUrl,verdict:I.verdict,reasoning:I.reasoning})),w=$e(g,k,e,void 0,x,void 0,void 0,st(e),r);if(s.push("## Context"),s.push(""),s.push(`- **Component / scope:** \`${m}\``),s.push(`- **Audited URL:** ${p}`),s.push(`- **WCAG target:** WCAG ${Le} ${gn} (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 **${w.letter}** · **${w.risk.toUpperCase()} risk** (${w.totals.critical} critical · ${w.totals.serious} serious · ${w.totals.moderate} moderate · ${w.totals.minor} minor). ${w.risk==="critical"||w.risk==="high"?"Treat as triage priority — these violations represent meaningful lawsuit exposure under ADA Title III, EAA, and EN 301 549.":w.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."}`),w.coverage){const I=w.coverage.untestedCriteria.length;I>0?s.push(`- **WCAG ${w.coverage.targetVersion} ${w.coverage.targetLevel} coverage:** ${w.coverage.evaluated} of ${w.coverage.totalApplicable} criteria evaluated. **Cannot claim ${w.coverage.targetLevel} conformance** until ${I} untested criteria are evaluated via Guided Tests (Pass / Fail / N/A). Untested: ${w.coverage.untestedCriteria.join(", ")}.`):s.push(`- **WCAG ${w.coverage.targetVersion} ${w.coverage.targetLevel} coverage:** ${w.coverage.evaluated} of ${w.coverage.totalApplicable} criteria evaluated. Full coverage — defensible conformance claim possible once all violations below are fixed.`)}f&&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("## ⛔ 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 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 R=(((re=e[0])==null?void 0:re.readingOrderIssues)??[]).filter(I=>!d.has(`reading-order::${I.selector}`)),T=(ne=e[0])==null?void 0:ne.positionAnalysisCapturedAt,P=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)",_=c==null?void 0:c.some(I=>I.criterionId==="1.3.2");if(R.length>0&&!_){s.push("## Reading-order concerns (DOM ≠ visual order)"),s.push(""),s.push(`_Positions captured at: **${P}**. 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. ${R.length} element${R.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 I of R){const B=I.textSnippet.replace(/\|/g,"\\|").replace(/\n/g," ");s.push(`| ${I.domIndex} | ${I.visualIndex} | \`${I.selector}\` | ${B} |`)}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 N=(((ge=e[0])==null?void 0:ge.tabOrderIssues)??[]).filter(I=>!d.has(`tab-order::${I.selector}`)),M=c==null?void 0:c.some(I=>I.criterionId==="2.1.2"&&I.verdict==="pass");if(N.length>0&&!M){const I=N.filter(L=>L.flag==="visual"||L.flag==="both").length,B=N.filter(L=>L.flag==="tabindex"||L.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: **${P}**. 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. ${N.length} focusable element${N.length===1?" has":"s have"} a notable divergence. Of these: ${I} ${I===1?"has":"have"} a visual-vs-tab mismatch (focus jumps around the page); ${B} ${B===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 L of N){const K=L.textSnippet.replace(/\|/g,"\\|").replace(/\n/g," ");s.push(`| ${L.tabPosition} | ${L.visualPosition} | ${L.domPosition} | ${L.flag} | \`${L.selector}\` | ${K} |`)}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 S=e.flatMap(I=>I.announcements??[]),V=e.flatMap(I=>I.focusEvents??[]).filter(I=>I.isFocusReset);if(S.length>0||V.length>0){if(s.push("## Runtime behavioral observations"),s.push(""),S.length>0){const I=S.filter(L=>L.politeness==="assertive").length;s.push(`**Live-region announcements** (${S.length} total, ${I} 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 B=S.slice(0,8);for(const L of B){const K=L.text.replace(/\|/g,"\\|").replace(/\n/g," ").slice(0,120);s.push(`- \`[${L.politeness}${L.role?`/${L.role}`:""}]\` ${K}`)}S.length>8&&s.push(`- (and ${S.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(V.length>0){s.push(`**Focus resets to body** (${V.length} occurrence${V.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 I of V.slice(0,5))s.push(`- \`${I.fromSelector??"(none)"}\` → \`${I.toSelector}\``);V.length>5&&s.push(`- (and ${V.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 D=((C=e[0])==null?void 0:C.undefinedCustomProperties)??[];if(D.length>0){s.push("## Undefined CSS custom properties (cascade root cause)"),s.push(""),s.push(`${D.length} CSS custom propert${D.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 I of D){const B=I.sampleSites.map(L=>`\`${L.selector} { ${L.property} }\``).join("; ");s.push(`| \`${I.name}\` | ${I.referenceCount} | ${B} |`)}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 I=Oe;s.push("| Workflow | Status | Notes |"),s.push("|---|---|---|");for(const X of a){const j=I.find(ya=>ya.id===X.workflowId);if(!j)continue;let J=0,G=0,be=0,Ue=0,Ye=0;for(const ya of j.steps){const ft=X.steps[ya.id];if(!ft){Ye++;continue}ft.status==="pass"?J++:ft.status==="fail"?G++:ft.status==="skip"?be++:ft.status==="not-applicable"?Ue++:Ye++}const ir=G>0?`❌ ${G} failed`:Ye>0?`⚠ ${Ye} unanswered`:`✓ all ${j.steps.length} answered`,Ot=[`${J}p`,`${G}f`];Ue>0&&Ot.push(`${Ue} N/A`),be>0&&Ot.push(`${be} skip`),Ye>0&&Ot.push(`${Ye} unanswered`);const rr=`${Ot.join(" · ")} of ${j.steps.length} steps`;s.push(`| ${j.name} | ${ir} | ${rr} |`)}s.push("");const B=[];for(const X of a){const j=I.find(J=>J.id===X.workflowId);if(j)for(const J of j.steps){const G=X.steps[J.id];(G==null?void 0:G.status)==="fail"&&B.push({workflow:j.name,stepTitle:J.question,notes:G.notes})}}if(B.length>0){s.push("**Failed manual checks** (these are real WCAG failures the consultant verified by hand):"),s.push("");for(const X of B)s.push(`- **${X.workflow} → ${X.stepTitle}**${X.notes?`: ${X.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 L=new Set(a.map(X=>X.workflowId)),K=I.filter(X=>!L.has(X.id));K.length>0&&(s.push(`**Not yet manually verified** (${K.length} workflow${K.length===1?"":"s"}): `+K.map(X=>X.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 I=(()=>{try{return new URL(p).origin}catch{return null}})(),B=(()=>{try{return new URL(n.startUrl).origin}catch{return null}})();if(I&&B&&I===B){const L=n.finishedAt,K=L?Date.now()-new Date(L).getTime():0,X=K<6e4?"just now":K<36e5?`${Math.round(K/6e4)} minute${Math.round(K/6e4)===1?"":"s"} ago`:K<864e5?`${Math.round(K/36e5)} hour${Math.round(K/36e5)===1?"":"s"} ago`:`${Math.round(K/864e5)} day${Math.round(K/864e5)===1?"":"s"} ago`;if(s.push("## Site-wide context (from a recent site crawl)"),s.push(""),s.push(`A crawl ${L?`(${X})`:""} of ${n.pagesAudited} page${n.pagesAudited===1?"":"s"} on this origin produced grade **${n.siteGrade}** 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 J of n.topViolations.slice(0,6))s.push(`- \`${J.ruleId}\` — ${J.impact} — found on ${J.urlsAffected} page${J.urlsAffected===1?"":"s"} (${J.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 j=n.consistencyFindings??[];if(j.length===0&&n.topViolations.some(G=>G.ruleId==="wcc-consistency-needs-site-crawl"||G.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("")),j.length>0){s.push("**Cross-page consistency divergences detected:**"),s.push("");for(const J of j){const G=J.aiVerdict?J.aiVerdict.verdict==="uncertain"?" (AI: uncertain — human verify)":` (AI: confirmed real, confidence ${(J.aiVerdict.confidence*100).toFixed(0)}%)`:"";s.push(`- **${J.wcagCriterion} ${J.impact}**${G} — ${J.description}`);for(const be of J.details.split(`
|
|
1630
|
+
`))s.push(` ${be}`);(W=J.aiVerdict)!=null&&W.reasoning&&s.push(` AI reasoning: ${J.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(h.length>0){const I=new Map;for(const L of h)I.has(L.matchKey)||I.set(L.matchKey,L);const B=Array.from(I.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 ${B.length} finding${B.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(""),B.forEach((L,K)=>{s.push(`${K+1}. \`${L.ruleId}\` on \`${L.target.selector}\``),L.target.accessibleName&&s.push(` - Accessible name: "${L.target.accessibleName}"`),L.target.textSnippet&&s.push(` - Text: "${L.target.textSnippet.slice(0,120)}"`),s.push(` - WCAG ${L.wcagCriterion} ${L.wcagLevel} · ${L.impact}`)}),s.push(""),s.push("---"),s.push("")}const $=(r??[]).filter(I=>I.verdict==="fail").filter(I=>!u.has(`${I.ruleId}::${I.selector}`));if($.length>0){const I=new Map;for(const L of $){const K=`${L.ruleId}::${L.selector}`;I.has(K)||I.set(K,L)}const B=Array.from(I.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 ${B.length} element${B.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(""),B.forEach((L,K)=>{const X=L.wcagCriterion?` — WCAG ${L.wcagCriterion}`:"";s.push(`### ${K+1}. \`${L.ruleId}\`${X}`),s.push(""),s.push(`**Selector:** \`${L.selector}\``),s.push(""),s.push(`**AI verdict (FAIL):** ${L.reasoning}`),s.push("");const j=at[L.ruleId];j&&(s.push(`**Recipe:** ${j.summary}`),s.push(""),j.snippet&&(s.push("```"+(j.snippetLang??"")),s.push(j.snippet),s.push("```"),s.push("")))}),s.push("---"),s.push("")}s.push("## Violations to fix"),s.push(""),v.forEach((I,B)=>{const L=at[I.ruleId],K=I._instanceSelectors.length;if(s.push(`### ${B+1}. \`${I.ruleId}\` — ${I.impact} — WCAG ${I.wcagCriterion} ${I.wcagLevel}${K>1?` (${K} instances)`:""}`),s.push(""),s.push(`**Description:** ${I.description}`),s.push(""),K>1){s.push(`**Affects ${K} spots — fix at the SOURCE (one CSS rule, one component, one shared class) — DO NOT patch each instance separately:**`);for(const G of I._instanceSelectors.slice(0,8))s.push(`- \`${G}\``);I._instanceSelectors.length>8&&s.push(`- (and ${I._instanceSelectors.length-8} more)`),s.push(""),s.push(`> **Find the common source.** ${K} 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:** \`${I.target.selector}\``);s.push(""),s.push(`**Found in state(s):** ${I._states.join(" / ")}`),s.push("");const X=Ku(I);if(X.length>0){for(const G of X)s.push(`**${G.label}:** ${G.value}`);s.push("")}I.target.failureSummary&&(s.push(`**Diagnostic:** ${I.target.failureSummary.replace(/\n+/g," ")}`),s.push("")),I.ai&&(s.push(`**🤖 AI-verified finding** (model: ${I.ai.model}, confidence: ${(I.ai.confidence*100).toFixed(0)}%)`),s.push(`> ${I.ai.reasoning}`),s.push(""));const j=I.target.cascadeChain;if(j&&(j.color||j.backgroundColor)){if(s.push("**CSS cascade chain (authored → rendered):**"),j.color){const G=j.color.vars.length>0?` (vars: ${j.color.vars.map(be=>`\`${be}\``).join(", ")})`:"";s.push(`- \`color\`: \`${j.color.authored}\` → \`${j.color.rendered}\`${G}${j.color.ruleSelector?` — set in rule \`${j.color.ruleSelector}\``:""}`)}if(j.backgroundColor){const G=j.backgroundColor.vars.length>0?` (vars: ${j.backgroundColor.vars.map(be=>`\`${be}\``).join(", ")})`:"";s.push(`- \`background-color\`: \`${j.backgroundColor.authored}\` → \`${j.backgroundColor.rendered}\`${G}${j.backgroundColor.ruleSelector?` — set in rule \`${j.backgroundColor.ruleSelector}\``:""}`)}s.push("")}const J=i==null?void 0:i[I.matchKey];if(J&&J.suggestions.length>0){s.push(`**AI color suggestions** (cached from in-UI tooling — ${J.suggestions.length} candidates passing WCAG):`);for(const G of J.suggestions)s.push(`- foreground \`${G.foreground}\` on background \`${G.background}\` → ${G.contrast.toFixed(2)}:1 — ${G.rationale}`);s.push(`> AI reasoning: ${J.reasoning}`),s.push("")}s.push("**Element HTML:**"),s.push("```html"),s.push(I.target.outerHTML),s.push("```"),s.push(""),L?(s.push(`**Recipe:** ${L.summary}`),L.snippet&&(s.push(""),s.push("```"+(L.snippetLang??"")),s.push(L.snippet),s.push("```"))):s.push(`**Recipe:** No curated recipe for this rule — apply the standard WCAG ${I.wcagCriterion} guidance.`),I.helpUrl&&(s.push(""),s.push(`**More info:** ${I.helpUrl}`)),s.push(""),s.push("---"),s.push("")});const U=Yu(e,r);if(U.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 I of U)s.push(`### \`${I.ruleId}\` on \`${I.selector}\``),s.push(""),s.push(`- **WCAG criterion:** ${I.wcagCriterion}`),s.push(`- **Page URL:** ${I.pageUrl}`),I.failureSummary&&s.push(`- **axe diagnostic:** ${I.failureSummary}`),(H=I.styles)!=null&&H.foreground&&s.push(`- **Foreground:** \`${I.styles.foreground}\``),(Q=I.styles)!=null&&Q.background&&s.push(`- **Background:** \`${I.styles.background}\``),(se=I.styles)!=null&&se.fontSize&&s.push(`- **Font size:** ${I.styles.fontSize}px, weight ${I.styles.fontWeight??"unknown"}`),(ce=I.styles)!=null&&ce.textSample&&s.push(`- **Text sample:** ${JSON.stringify(I.styles.textSample)}`),I.aiAttemptReasoning&&(s.push(""),s.push("**Our AI resolver already attempted this element and returned uncertain.** Its reasoning:"),s.push(""),s.push(`> ${I.aiAttemptReasoning.replace(/\n/g,`
|
|
1631
1631
|
> `)}`),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 q=new Map;if(c)for(const I of c)q.set(I.criterionId,I.verdict);function Y(I,B){const L=q.get(I);return L==="pass"?`- [x] **${I}** — ✓ AI walkthrough verified pass during audit (see "AI keyboard walkthroughs" section). No manual verification needed.`:L==="fail"?`- [x] **${I}** — ✗ AI walkthrough FAILED during audit (see "AI keyboard walkthroughs" section for the fix). Confirm the code fix is applied and re-audit.`:L==="uncertain"?`- [ ] **${I}** — AI walkthrough was uncertain. ${B}`:`- [ ] **${I}** — ${B}`}return s.push("### Perceivable (audit-already-verified items pre-checked)"),s.push(""),s.push(Y("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(Y("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(Y("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(Y("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(Y("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(Y("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(""),S.length>0||V.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 ${xe} v${He()}._`),s.join(`
|
|
1632
|
-
`)}const
|
|
1633
|
-
`);let f=1;for(const[h,y]of m.entries()){const b=(g=y.find(s=>s.target.opacityContext))==null?void 0:g.target.opacityContext,A=
|
|
1634
|
-
`)}function
|
|
1632
|
+
`)}const Ju=5;function Xu(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,Ju)}const To=1280,$o=800,Qu={low:"Low risk",moderate:"Moderate risk",high:"High risk",critical:"Critical risk"},Zu={low:"#d1fae5",moderate:"#fef3c7",high:"#fed7aa",critical:"#fecaca"},ep={low:"#065f46",moderate:"#92400e",high:"#9a3412",critical:"#991b1b"},tp={A:"#10b981",B:"#84cc16",C:"#eab308",D:"#f97316",F:"#dc2626"},ap={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 Zi(e,t,a,n,o,r,i){return Rt(e,t,"evidence",a,n,o,r,i)}function er(e,t,a,n,o,r){return nr(e,"letter",t,a,n,o,r)}function tr(e,t,a,n,o,r){return nr(e,"report",t,a,n,o,r)}function ar(e,t,a,n,o,r){var g;const i=e.flatMap(h=>h.violations),c=$e(i,void 0,e,a,t,n,o,st(e),r),l=_e(e),d=new Map;for(const h of i){const y=Te(h.ruleId,h.target.selector);d.has(y)||d.set(y,h)}const u=Array.from(d.values()).sort((h,y)=>{const b={critical:0,serious:1,moderate:2,minor:3};return(b[h.impact]??99)-(b[y.impact]??99)}),m=new Map;for(const h of u){const y=m.get(h.ruleId)??[];y.push(h),m.set(h.ruleId,y)}const p=[];if(p.push("# Help me fix accessibility issues on my website"),p.push(""),p.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."),p.push(""),p.push("## What I need from you"),p.push(""),p.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."),p.push("2. **Then, for each issue below, tell me clearly:**"),p.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"),p.push(" - Or whether **my developer needs to do this** (code-level fix) — and what to ask them to do"),p.push("3. **Prioritize ruthlessly.** I want to start with the issues that:"),p.push(" - Are most likely to come up in an ADA-related lawsuit (critical-impact items)"),p.push(" - Are easiest for me to fix without involving a developer"),p.push("4. **Don't bury me in jargon.** If you have to use a technical term, explain it in plain English first."),p.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."),p.push(""),p.push("## Audit summary"),p.push(""),p.push(`- **Page audited:** ${l}`),p.push(`- **Lawsuit-target risk:** ${Zo[c.risk]} — ${ei[c.risk]}`),p.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?p.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&&p.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.`),p.push(""),p.push("## The issues, in plain language"),p.push(""),m.size===0)return p.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."),p.join(`
|
|
1633
|
+
`);let f=1;for(const[h,y]of m.entries()){const b=(g=y.find(s=>s.target.opacityContext))==null?void 0:g.target.opacityContext,A=li(h,b),v=y[0].impact;p.push(`### ${f}. [${v.toUpperCase()}] ${A.whatsWrong}`),p.push(""),p.push(`**Why this matters.** ${A.whyItMatters}`),p.push(""),p.push(`**Plain-language fix guidance.** ${A.howToFix}`),p.push(""),p.push(`**Where on the page (${y.length} ${y.length===1?"spot":"spots"}):**`);for(const s of y.slice(0,8))p.push(`- \`${s.target.selector}\``);y.length>8&&p.push(`- (and ${y.length-8} more spots)`),p.push(""),p.push(`*Technical reference for your developer:* axe-core rule \`${h}\` — full docs at https://dequeuniversity.com/rules/axe/4.11/${h}`),p.push(""),f++}return p.push("---"),p.push(""),p.push("## How to use this output"),p.push(""),p.push("Walk through this list with me one issue at a time. For each:"),p.push("1. Help me understand the issue with a real example of who it affects."),p.push("2. Tell me clearly if I can fix it myself, and if so, walk me through it for my platform."),p.push("3. If I need a developer, give me a short paragraph I can paste into an email or message to them."),p.push("4. Help me prioritize — I have limited time and want to fix the riskiest things first."),p.push(""),p.push("Start by asking me which platform I use."),p.join(`
|
|
1634
|
+
`)}function nr(e,t,a,n,o,r,i){const c=e.flatMap(b=>b.violations),l=$e(c,void 0,e,n,a,o,r,st(e),i),d=_e(e),u=new Date,m=new Map;for(const b of c){const A=Te(b.ruleId,b.target.selector);m.has(A)||m.set(A,b)}const p=Array.from(m.values()).sort((b,A)=>{const v={critical:0,serious:1,moderate:2,minor:3};return(v[b.impact]??99)-(v[A.impact]??99)}),f=new Map;for(const b of p){const A=f.get(b.ruleId)??[];A.push(b),f.set(b.ruleId,A)}const g=Array.from(f.entries()).map(([b,A])=>{var R;const v=(R=A.find(T=>T.target.opacityContext))==null?void 0:R.target.opacityContext,s=li(b,v),k=A[0].impact,x=A.slice(0,8).map(T=>`<code>${O(T.target.selector)}</code>`).join(", "),w=A.length>8?` <em>(and ${A.length-8} more)</em>`:"";return`
|
|
1635
1635
|
<section class="rule">
|
|
1636
1636
|
<div class="rule-header">
|
|
1637
1637
|
<span class="impact impact-${O(k)}">${O(k)}</span>
|
|
@@ -1685,7 +1685,7 @@ ${t.length===0?"":`<h3 style="margin-top:12pt">Human verified (${t.length})</h3>
|
|
|
1685
1685
|
<p>${h}</p>
|
|
1686
1686
|
|
|
1687
1687
|
<div class="summary">
|
|
1688
|
-
<p style="margin: 0;"><strong>${O(
|
|
1688
|
+
<p style="margin: 0;"><strong>${O(Zo[l.risk])}.</strong> ${O(ei[l.risk])}</p>
|
|
1689
1689
|
<div class="totals">
|
|
1690
1690
|
${l.totals.critical>0?`<span><strong>${l.totals.critical}</strong> critical</span>`:""}
|
|
1691
1691
|
${l.totals.serious>0?`<span><strong>${l.totals.serious}</strong> serious</span>`:""}
|
|
@@ -1721,7 +1721,7 @@ ${t==="letter"?`
|
|
|
1721
1721
|
<p>Generated by ${O(xe)} on ${O(u.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>
|
|
1722
1722
|
</footer>
|
|
1723
1723
|
</body>
|
|
1724
|
-
</html>`}function
|
|
1724
|
+
</html>`}function np(e){if(!e||e.length===0)return`
|
|
1725
1725
|
<h2 id="manual">5. Manual assessment results</h2>
|
|
1726
1726
|
<p style="font-size: 10pt; color: #475569;">
|
|
1727
1727
|
No manual workflows were completed for this audit. wcagcheckr's three layers (axe-core, our
|
|
@@ -1731,15 +1731,15 @@ ${t==="letter"?`
|
|
|
1731
1731
|
when the audit needs to anchor to specific named auditors for formal conformance.
|
|
1732
1732
|
When manual workflows are completed, their results are integrated into both the executive
|
|
1733
1733
|
summary's compliance grade and this section's per-criterion findings.
|
|
1734
|
-
</p>`;const t=new Map(e.map(c=>[c.workflowId,c])),a=Oe.map(c=>
|
|
1734
|
+
</p>`;const t=new Map(e.map(c=>[c.workflowId,c])),a=Oe.map(c=>op(c,t.get(c.id))).filter(c=>c!==null).join("");let n=0,o=0,r=0,i=0;for(const c of Oe){i+=c.steps.length;const l=t.get(c.id);if(l)for(const d of c.steps){const u=l.steps[d.id];u&&(r++,u.status==="fail"&&(d.severity==="required"?n++:o++))}}return`
|
|
1735
1735
|
<h2 id="manual">5. Manual assessment results</h2>
|
|
1736
1736
|
<p style="font-size: 10pt; color: #475569; margin-bottom: 8pt;">
|
|
1737
|
-
Manual workflows performed by the auditor. ${
|
|
1737
|
+
Manual workflows performed by the auditor. ${r} of ${i} steps answered
|
|
1738
1738
|
across ${e.length} workflow${e.length===1?"":"s"}.
|
|
1739
1739
|
${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."}
|
|
1740
1740
|
${o>0?` ${o} advisory step${o===1?"":"s"} failed (best-practice findings).`:""}
|
|
1741
1741
|
</p>
|
|
1742
|
-
${a}`}function
|
|
1742
|
+
${a}`}function op(e,t){if(!t)return null;const a=[];for(const d of e.steps){const u=t.steps[d.id];u&&a.push({step:d,status:u.status,notes:u.notes})}if(a.length===0)return null;const n=a.filter(d=>d.status==="pass").length,o=a.filter(d=>d.status==="fail").length,r=a.filter(d=>d.status==="skip").length,i=a.filter(d=>d.status==="not-applicable").length,l=a.filter(d=>d.status==="fail").map(d=>`
|
|
1743
1743
|
<tr>
|
|
1744
1744
|
<td><span class="impact impact-${d.step.severity==="required"?"serious":"moderate"}">${O(d.step.severity)}</span></td>
|
|
1745
1745
|
<td>${d.step.wcag?`<code>${O(d.step.wcag)}</code>`:"—"}</td>
|
|
@@ -1751,8 +1751,8 @@ ${a}`}function ip(e,t){if(!t)return null;const a=[];for(const d of e.steps){cons
|
|
|
1751
1751
|
<p style="font-size: 10pt; margin: 0 0 6pt;">
|
|
1752
1752
|
<span class="cat-pass">${n} passed</span>
|
|
1753
1753
|
${o>0?` · <span class="cat-fail">${o} failed</span>`:""}
|
|
1754
|
-
${
|
|
1755
|
-
${
|
|
1754
|
+
${r>0?` · <span style="color: #64748b;">${r} skipped</span>`:""}
|
|
1755
|
+
${i>0?` · <span style="color: #64748b;">${i} N/A</span>`:""}
|
|
1756
1756
|
· ${a.length} of ${e.steps.length} answered
|
|
1757
1757
|
</p>
|
|
1758
1758
|
${o>0?`
|
|
@@ -1760,7 +1760,7 @@ ${o>0?`
|
|
|
1760
1760
|
<thead><tr><th style="width: 80pt;">Severity</th><th style="width: 70pt;">WCAG</th><th>Failed check + auditor notes</th></tr></thead>
|
|
1761
1761
|
<tbody>${l}</tbody>
|
|
1762
1762
|
</table>
|
|
1763
|
-
`:""}`}function Rt(e,t,a="defense",n,o,i,
|
|
1763
|
+
`:""}`}function Rt(e,t,a="defense",n,o,r,i,c,l,d,u,m){var S,E,V;const p=ap[a],f=((S=e[0])==null?void 0:S.componentId)??"unknown",g=_e(e),h=i??e.reduce((D,$)=>D+$.durationMs,0),y=e.flatMap(D=>D.violations),b=n&&n.length>0?{runs:n,workflows:Oe}:void 0,A=$e(y,b,e,d,c,l,u,st(e),m),v=new Date,s=new Map;for(const D of y){const $=Te(D.ruleId,D.target.selector),U=`${D.currentState.pseudoState} · ${D.currentState.theme} · ${D.currentState.direction}`,q=s.get($);if(q){q._states.includes(U)||q._states.push(U);continue}s.set($,{...D,_states:[U]})}const k=Array.from(s.values()).sort((D,$)=>{const U={critical:0,serious:1,moderate:2,minor:3};return(U[D.impact]??99)-(U[$.impact]??99)}),x=Xu(e),w=new Map;for(const D of x)for(const $ of D.violations){const U=Te($.ruleId,$.target.selector);w.has(U)||w.set(U,$._idx)}const R=k.map((D,$)=>`
|
|
1764
1764
|
<tr>
|
|
1765
1765
|
<td>${$+1}</td>
|
|
1766
1766
|
<td><span class="impact impact-${O(D.impact)}">${O(D.impact)}</span></td>
|
|
@@ -1769,7 +1769,7 @@ ${o>0?`
|
|
|
1769
1769
|
<td>${O(D.description)}</td>
|
|
1770
1770
|
<td><code class="sel">${O(D.target.selector)}</code></td>
|
|
1771
1771
|
<td>${O(D._states.join(", "))}</td>
|
|
1772
|
-
</tr>`).join(""),T=d??new Set,P=new Set(y.filter(D=>!T.has(D.matchKey)).map(D=>D.ruleId)),_=new Set(P);for(const D of e){const $=D.axeRulesEvaluated;if($){for(const U of $.passed)_.add(U.ruleId);for(const U of $.inapplicable)_.add(U.ruleId);for(const U of $.incomplete)_.add(U.ruleId)}}const N=new Map;for(const D of u??[])N.set(D.criterionId,D.verdict);const M=
|
|
1772
|
+
</tr>`).join(""),T=d??new Set,P=new Set(y.filter(D=>!T.has(D.matchKey)).map(D=>D.ruleId)),_=new Set(P);for(const D of e){const $=D.axeRulesEvaluated;if($){for(const U of $.passed)_.add(U.ruleId);for(const U of $.inapplicable)_.add(U.ruleId);for(const U of $.incomplete)_.add(U.ruleId)}}const N=new Map;for(const D of u??[])N.set(D.criterionId,D.verdict);const M=Yi.map(D=>{const{conformance:$,hits:U}=Ji(D,P,_,c,N.get(D.ref));return`
|
|
1773
1773
|
<tr class="${$==="Supports"?"supports":$==="Partially Supports"?"partial":$==="Not Evaluated"?"not-evaluated":"na"}">
|
|
1774
1774
|
<td><code>${O(D.ref)}</code></td>
|
|
1775
1775
|
<td>${O(D.title)} <span class="lvl">(${D.level})</span></td>
|
|
@@ -1854,25 +1854,25 @@ ${o>0?`
|
|
|
1854
1854
|
|
|
1855
1855
|
<h2 id="exec">1. Executive summary</h2>
|
|
1856
1856
|
<div class="exec">
|
|
1857
|
-
<div class="exec-grade" style="background: ${
|
|
1857
|
+
<div class="exec-grade" style="background: ${tp[A.letter]};">${A.letter}</div>
|
|
1858
1858
|
<div class="exec-body">
|
|
1859
|
-
<span class="risk-tier" style="background: ${
|
|
1860
|
-
${O(
|
|
1859
|
+
<span class="risk-tier" style="background: ${Zu[A.risk]}; color: ${ep[A.risk]};">
|
|
1860
|
+
${O(Qu[A.risk])}
|
|
1861
1861
|
</span>
|
|
1862
1862
|
<p style="margin: 0 0 6pt;"><strong>${A.totals.unique} unique violations detected</strong> across ${e.length} state combinations
|
|
1863
1863
|
(${A.totals.critical} critical · ${A.totals.serious} serious · ${A.totals.moderate} moderate · ${A.totals.minor} minor).</p>
|
|
1864
|
-
<p style="margin: 0; font-size: 10pt; color: #475569;">${O(
|
|
1864
|
+
<p style="margin: 0; font-size: 10pt; color: #475569;">${O(Ws[A.risk])}</p>
|
|
1865
1865
|
</div>
|
|
1866
1866
|
</div>
|
|
1867
|
-
${
|
|
1867
|
+
${r&&(r.lead||r.body||r.closer)?`
|
|
1868
1868
|
<div style="margin-top: 12pt; padding: 12pt 14pt; border-left: 4px solid #2563eb; background: #f0f6ff; border-radius: 0 4pt 4pt 0;">
|
|
1869
1869
|
<p style="margin: 0 0 6pt; font-size: 10pt; color: #1e40af; text-transform: uppercase; letter-spacing: 0.04em;">
|
|
1870
|
-
AI-generated narrative summary (${O(
|
|
1870
|
+
AI-generated narrative summary (${O(r.model)})
|
|
1871
1871
|
</p>
|
|
1872
|
-
${
|
|
1873
|
-
${
|
|
1872
|
+
${r.lead?`<p style="margin: 0 0 8pt; font-size: 11.5pt; font-weight: 500;">${O(r.lead)}</p>`:""}
|
|
1873
|
+
${r.body?r.body.split(/\n{2,}/).map(D=>`<p style="margin: 0 0 6pt;">${O(D.trim())}</p>`).join(`
|
|
1874
1874
|
`):""}
|
|
1875
|
-
${
|
|
1875
|
+
${r.closer?`<p style="margin: 8pt 0 0; font-style: italic;">${O(r.closer)}</p>`:""}
|
|
1876
1876
|
<p style="margin: 6pt 0 0; font-size: 9pt; color: #475569;">
|
|
1877
1877
|
This narrative was generated by an LLM from the audit's structured findings. The numerical
|
|
1878
1878
|
data in §1 above and the per-violation details in §3 are the authoritative record.
|
|
@@ -1912,7 +1912,7 @@ ${k.length===0?"<p>No automated violations were detected during this audit.</p>"
|
|
|
1912
1912
|
<tbody>${R}</tbody>
|
|
1913
1913
|
</table>`}
|
|
1914
1914
|
|
|
1915
|
-
${
|
|
1915
|
+
${Bu(A.walkthroughFindings,A.walkthroughAcknowledgements,l??[])}
|
|
1916
1916
|
|
|
1917
1917
|
<h2 id="evidence">4. Visual evidence (per-state screenshots)</h2>
|
|
1918
1918
|
${x.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 ${x.length} state${x.length===1?"":"s"} by violation count shown below. Red rectangles mark violation locations; numbers correspond to entries in §3.</p>`+x.map(D=>{const $=D.violations.filter(U=>U.target.boundingRect).map(U=>{const q=U.target.boundingRect,Y=String(U._idx).length*8+14,Z=22;return[`<rect class="violation-mark" x="${q.x}" y="${q.y}" width="${q.w}" height="${q.h}" />`,`<rect class="label-bg" x="${q.x}" y="${Math.max(0,q.y-Z)}" width="${Y}" height="${Z}" rx="2" />`,`<text class="violation-num" x="${q.x+6}" y="${Math.max(0,q.y-Z)+16}">${U._idx}</text>`].join("")}).join("");return`
|
|
@@ -1926,7 +1926,7 @@ ${x.length===0?'<p style="font-size: 10pt; color: #64748b;">No per-state screens
|
|
|
1926
1926
|
</div>
|
|
1927
1927
|
</div>`}).join("")}
|
|
1928
1928
|
|
|
1929
|
-
${
|
|
1929
|
+
${np(n)}
|
|
1930
1930
|
|
|
1931
1931
|
<h2 id="conformance">6. WCAG 2.1 conformance assessment</h2>
|
|
1932
1932
|
<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>
|
|
@@ -2001,15 +2001,15 @@ ${Y}
|
|
|
2001
2001
|
</footer>
|
|
2002
2002
|
|
|
2003
2003
|
</body>
|
|
2004
|
-
</html>`}async function
|
|
2004
|
+
</html>`}async function ip(){const t=(await chrome.storage.local.get("aiConfig")).aiConfig;return{...br,...t??{}}}async function rp(e){return hn(e.map(t=>t.componentId))}async function Da(e,t,a,n){const o=await ip();if(!o.enabled||!o.apiKey||e.length===0)return null;const r=e.flatMap(d=>d.violations),i=$e(r,void 0,e,void 0,n),c=i.categories.filter(d=>d.status==="fail").sort((d,u)=>u.violationCount-d.violationCount).slice(0,3).map(d=>d.label),l=e[0];return Gi({framing:t,riskTier:i.risk,grade:i.letter,totals:{critical:i.totals.critical,serious:i.totals.serious,moderate:i.totals.moderate,minor:i.totals.minor,unique:i.totals.unique},riskDrivers:c,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 sp={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 cp(){return Ie("EXPORT_REQUEST",async e=>{var a;if(await Fe())return{type:"EXPORT_RESPONSE",format:e.format,content:"wcagcheckr is in private build phase. A team license is required to export reports."};const t=sp[e.format];if(t){const n=await fe();if(!de(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 Gt();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(Hi(e.results,e.delta),null,2)};if(e.format==="junit")return{type:"EXPORT_RESPONSE",format:"junit",content:Ki(e.results,e.delta)};if(e.format==="html-print")return{type:"EXPORT_RESPONSE",format:"html-print",content:Tn(e.results,e.delta,e.wallClockMs)};if(e.format==="vpat"){const n=await Re(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:Xi(e.results,e.delta,r,n.acknowledgedMatchKeys,n.humanCriterionVerdicts,n.incompleteResolutions)}}if(e.format==="ai-prompt"){const n=await qs();let o="";const r=[];try{const c=((a=e.results[0])==null?void 0:a.componentId)??"",l=c?await Va(c):[];for(const d of l)r.push({criterionId:d.criterionId,verdict:d.verdict,reasoning:d.reasoning,pageUrl:d.pageUrl});o=lp(l)}catch(c){console.warn("[report-exporter] walkthrough render skipped:",c)}const i=Qi(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}
|
|
2005
2005
|
|
|
2006
|
-
${o}`:
|
|
2006
|
+
${o}`:i}}if(e.format==="defense-bundle"){const n=await kt(),o=await Re(e.results,e.auditTargetId?[e.auditTargetId]:[]),r=await Da(e.results,"defense",n.length,o.walkthroughs);return{type:"EXPORT_RESPONSE",format:"defense-bundle",content:Rt(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 kt(),o=await Re(e.results,e.auditTargetId?[e.auditTargetId]:[]),r=await Da(e.results,"defense",n.length,o.walkthroughs),i=await an().catch(()=>null);return{type:"EXPORT_RESPONSE",format:"deposition-packet",content:(await Vi({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:$u({results:e.results,manualRuns:e.manualRuns})};if(e.format==="conformance-crosswalk")return{type:"EXPORT_RESPONSE",format:"conformance-crosswalk",content:Lu({results:e.results})};if(e.format==="ticket-bundle")return{type:"EXPORT_RESPONSE",format:"ticket-bundle",content:Uu({results:e.results})};if(e.format==="executive-report"){const n=await Re(e.results,e.auditTargetId?[e.auditTargetId]:[]);return{type:"EXPORT_RESPONSE",format:"executive-report",content:ju(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 kt(),o=await rp(e.results),r=await Da(e.results,"evidence",n.length,o);return{type:"EXPORT_RESPONSE",format:"evidence-bundle",content:Zi(e.results,e.delta,e.manualRuns,n,r,e.wallClockMs,o)}}if(e.format==="developer-letter"){const n=await Re(e.results,e.auditTargetId?[e.auditTargetId]:[]);return{type:"EXPORT_RESPONSE",format:"developer-letter",content:er(e.results,n.walkthroughs,n.acknowledgedMatchKeys,n.walkthroughAcks,n.humanCriterionVerdicts,n.incompleteResolutions)}}if(e.format==="owner-report"){const n=await Re(e.results,e.auditTargetId?[e.auditTargetId]:[]);return{type:"EXPORT_RESPONSE",format:"owner-report",content:tr(e.results,n.walkthroughs,n.acknowledgedMatchKeys,n.walkthroughAcks,n.humanCriterionVerdicts,n.incompleteResolutions)}}if(e.format==="ai-prompt-owner"){const n=await Re(e.results,e.auditTargetId?[e.auditTargetId]:[]);return{type:"EXPORT_RESPONSE",format:"ai-prompt-owner",content:ar(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=zs({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
|
|
2007
2007
|
|
|
2008
|
-
The statement render failed: \`${
|
|
2008
|
+
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([sn(),Gt()]);if(!n||!o||o.length===0)return{type:"EXPORT_RESPONSE",format:"ai-prompt-site-crawl",content:`# Accessibility Fix Request — Site Crawl
|
|
2009
2009
|
|
|
2010
2010
|
No crawl results found in storage. Run a site crawl from the Crawl tab and try again.
|
|
2011
|
-
`};const
|
|
2012
|
-
> `)}`:"> (no reasoning recorded)"),t.push(""),n==="fail"?(
|
|
2013
|
-
`)}function
|
|
2014
|
-
`))o.push(p);(d=u.aiVerdict)!=null&&d.reasoning&&(o.push(""),o.push(`AI reasoning: ${u.aiVerdict.reasoning}`)),o.push("")}}else o.push("## Cross-page consistency findings"),o.push(""),o.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."),o.push("");return o.push("---"),o.push(""),o.push(`## Per-page findings (${e.length} page${e.length===1?"":"s"})`),o.push(""),o.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."),o.push(""),e.forEach((u,m)=>{const p=m+1;if(o.push(`### Page ${p} of ${e.length}: ${u.url}`),o.push(""),u.error){o.push(`> ⚠️ Audit failed for this page: \`${u.error}\``),o.push(""),o.push("---"),o.push("");return}const f=u.results.flatMap(k=>k.violations).filter(k=>!
|
|
2015
|
-
`)}const
|
|
2011
|
+
`};const r=new Map;await Promise.all(o.map(async p=>{if(p.componentId)try{const f=await Va(p.componentId);r.set(p.componentId,f.map(g=>({criterionId:g.criterionId,verdict:g.verdict,reasoning:g.reasoning,pageUrl:g.pageUrl})))}catch{}}));const{getAllResolutions:i,applySelfCorrectionSalvage:c,applyContrastMathSalvage:l}=await en(async()=>{const{getAllResolutions:p,applySelfCorrectionSalvage:f,applyContrastMathSalvage:g}=await Promise.resolve().then(()=>hs);return{getAllResolutions:p,applySelfCorrectionSalvage:f,applyContrastMathSalvage:g}},void 0),u=(await i()).map(c).map(l),m=new Map;for(const p of u){if(p.verdict!=="fail")continue;const f=$n(p.pageUrl),g=m.get(f)??[];g.push(p),m.set(f,g)}return{type:"EXPORT_RESPONSE",format:"ai-prompt-site-crawl",content:or(o,n,r,m)}}return{type:"EXPORT_RESPONSE",format:"json",content:JSON.stringify(zi(e.results,e.delta),null,2)}})}function lp(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,l=typeof a.reasoning=="string"?a.reasoning:"",d=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 ${d}):`),t.push(""),t.push(l?`> ${l.replace(/\n/g,`
|
|
2012
|
+
> `)}`:"> (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(p=>p&&p.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 p of m.slice(0,30)){const f=p.focused??{selector:"?",role:"",name:""},g=String(f.selector??"?"),h=String(f.role??"-")||"-",y=String(f.name??"(no name)").replace(/\|/g,"\\|").slice(0,60),b=String(p.action??""),A=typeof p.ordinal=="number"?p.ordinal:"?";t.push(`| ${A} | ${b} | \`${g}\` | ${h} | ${y} |`)}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(`
|
|
2013
|
+
`)}function dp(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 up=/-needs-site-crawl$/;function $n(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 or(e,t,a=new Map,n=new Map){var d;const o=[];o.push("# Accessibility Fix Request — Site Crawl"),o.push(""),o.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.`),o.push(""),o.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.`),o.push("");let r=0;for(const u of n.values())r+=u.length;const i=t.totalUniqueViolations+r;o.push("## ⚠ Work contract — read before doing anything else"),o.push(""),o.push(`**Below you have ${i} finding${i===1?"":"s"} across ${t.pagesAudited} page${t.pagesAudited===1?"":"s"}** (${t.totalUniqueViolations} axe violation${t.totalUniqueViolations===1?"":"s"}${r>0?` + ${r} pixel-contrast-sampler fail${r===1?"":"s"}`:""}). When you respond, every numbered finding needs an outcome. Do not stop early. Do not declare done without addressing every finding.`),o.push(""),o.push("**For each numbered finding, produce one of:**"),o.push(""),o.push("- ✅ **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."),o.push("- ⚠ **Blocked** — explicitly state WHY (missing info, ambiguous user content, dependency change required). One sentence per blocked finding."),o.push("- ❓ **Needs user decision** — list the options inline."),o.push(""),o.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.`),o.push(""),o.push("**Required final response format** — completion table:"),o.push(""),o.push("```"),o.push("| # | Rule ID | Page(s) | Status | Notes |"),o.push("|---|---------|---------|--------|-------|"),o.push("| 1 | <rule> | <url> | ✅ / ⚠ / ❓ | <file:line OR reason> |"),o.push(`| ${i} | ... | ... | ... | ... |`),o.push("```"),o.push(""),o.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."),o.push(""),o.push("---"),o.push(""),o.push(zu),o.push("---"),o.push(""),o.push("## Site-wide summary"),o.push(""),o.push(`- **Start URL:** ${t.startUrl}`),o.push(`- **Pages audited:** ${t.pagesAudited}${t.pagesFailed>0?` (${t.pagesFailed} failed)`:""}`),o.push(`- **Site grade:** ${t.siteGrade}`),o.push(`- **Total findings site-wide:** ${i} (${t.totalUniqueViolations} axe, ${r} pixel-contrast-sampler)`),o.push(`- **Severity breakdown:** ${t.totals.critical} critical · ${t.totals.serious+r} serious · ${t.totals.moderate} moderate · ${t.totals.minor} minor`),o.push("");const c=t.topViolations.filter(u=>!/-needs-site-crawl$/.test(u.ruleId));if(c.length>0){o.push("**Most-frequent rules across the site** (fixing one of these in a shared component / layout resolves N pages at once):"),o.push("");for(const u of c.slice(0,8)){const p=u.urlsAffected>=Math.ceil(t.pagesAudited/2)?" — **likely a single shared-component fix**":"";o.push(`- \`${u.ruleId}\` — ${u.impact} — found on ${u.urlsAffected} page${u.urlsAffected===1?"":"s"} (${u.totalOccurrences} total instance${u.totalOccurrences===1?"":"s"})${p}`)}o.push("")}const l=t.consistencyFindings??[];if(l.length>0){o.push("## Cross-page consistency findings"),o.push(""),o.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)."),o.push("");for(const u of l){const m=u.aiVerdict?u.aiVerdict.verdict==="uncertain"?" _(AI: uncertain — verify manually)_":` _(AI: confirmed real, confidence ${(u.aiVerdict.confidence*100).toFixed(0)}%)_`:"";o.push(`### ${u.wcagCriterion} ${u.impact} — ${u.description}${m}`),o.push("");for(const p of u.details.split(`
|
|
2014
|
+
`))o.push(p);(d=u.aiVerdict)!=null&&d.reasoning&&(o.push(""),o.push(`AI reasoning: ${u.aiVerdict.reasoning}`)),o.push("")}}else o.push("## Cross-page consistency findings"),o.push(""),o.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."),o.push("");return o.push("---"),o.push(""),o.push(`## Per-page findings (${e.length} page${e.length===1?"":"s"})`),o.push(""),o.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."),o.push(""),e.forEach((u,m)=>{const p=m+1;if(o.push(`### Page ${p} of ${e.length}: ${u.url}`),o.push(""),u.error){o.push(`> ⚠️ Audit failed for this page: \`${u.error}\``),o.push(""),o.push("---"),o.push("");return}const f=u.results.flatMap(k=>k.violations).filter(k=>!up.test(k.ruleId)),g=n.get($n(u.url))??[];if(f.length===0&&g.length===0){o.push("No automated violations detected on this page. Still apply the manual checklist below."),o.push("");const k=a.get(u.componentId)??[];if(k.length>0){o.push("**AI walkthrough verdicts on this page:**");for(const x of k){const w=x.verdict==="pass"?"✓":x.verdict==="fail"?"✗":"?";o.push(`- ${w} WCAG ${x.criterionId} — ${x.verdict.toUpperCase()}`)}o.push("")}o.push("---"),o.push("");return}const h=new Map,y=new Map;for(const k of f){const x=Te(k.ruleId,k.target.selector);h.has(x)||h.set(x,k);const w=y.get(x)??[];w.push(k),y.set(x,w)}const b=Array.from(h.entries()).map(([k,x])=>({v:x,instances:y.get(k)??[x]})).sort((k,x)=>{const w={critical:0,serious:1,moderate:2,minor:3};return(w[k.v.impact]??99)-(w[x.v.impact]??99)}),A={critical:0,serious:0,moderate:0,minor:0};for(const{v:k}of b)A[k.impact]++;A.serious+=g.length;const v=b.length+g.length;o.push(`**${v} finding${v===1?"":"s"}** · severity: ${A.critical} critical · ${A.serious} serious · ${A.moderate} moderate · ${A.minor} minor`),o.push(""),b.forEach(({v:k,instances:x},w)=>{const R=at[k.ruleId],T=So(`${k.ruleId} ${k.wcagCriterion}`)==="human-verify"?"[Human-verify]":"[AI-fixable]";o.push(`#### ${p}.${w+1} \`${k.ruleId}\` — ${k.impact} — WCAG ${k.wcagCriterion} ${k.wcagLevel} — ${T}`),o.push(""),o.push(`**Description:** ${k.description}`),o.push(""),o.push(`**Selector:** \`${k.target.selector}\``);const{stateCount:P,states:_}=dp(x);P>1?(o.push(""),o.push(`_Failed in ${P} matrix state${P===1?"":"s"}:_ ${_.join(", ")}`)):x.length>1&&(o.push(""),o.push(`_${x.length} element instances on this page (same state)._`)),o.push(""),k.target.failureSummary&&(o.push("**Diagnostic:**"),o.push("```"),o.push(k.target.failureSummary.trim()),o.push("```"),o.push("")),k.target.outerHTML&&(o.push("**Element HTML:**"),o.push("```html"),o.push(k.target.outerHTML.slice(0,500)),o.push("```"),o.push("")),R!=null&&R.summary&&(o.push("**Recipe:**"),o.push(R.summary),R.snippet&&(o.push(""),o.push("```"+(R.snippetLang??"")),o.push(R.snippet),o.push("```")),o.push("")),k.helpUrl&&(o.push(`**More info:** ${k.helpUrl}`),o.push(""))}),g.forEach((k,x)=>{const w=b.length+x,R=So(`${k.ruleId} ${k.wcagCriterion??"1.4.3"}`)==="human-verify"?"[Human-verify]":"[AI-fixable]";o.push(`#### ${p}.${w+1} \`${k.ruleId}\` — serious — WCAG ${k.wcagCriterion??"1.4.3"} AA — ${R}`),o.push(""),o.push("**Description:** Empirical pixel-contrast measurement below the AA threshold (pixel-contrast-sampler)."),o.push(""),o.push(`**Selector:** \`${k.selector}\``),o.push(""),o.push("**Diagnostic:**"),o.push("```"),o.push(k.reasoning.trim()),o.push("```"),o.push(""),o.push("**Recipe:**"),o.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.'),o.push("")});const s=a.get(u.componentId)??[];if(s.length>0){o.push("**AI walkthrough verdicts on this page:**");for(const k of s){const x=k.verdict==="pass"?"✓":k.verdict==="fail"?"✗":"?";o.push(`- ${x} WCAG ${k.criterionId} — ${k.verdict.toUpperCase()}: ${k.reasoning.slice(0,240)}${k.reasoning.length>240?"…":""}`)}o.push("")}o.push("---"),o.push("")}),o.push("## Combined verification checklist"),o.push(""),o.push("After all per-page fixes:"),o.push(""),o.push("1. **Re-run the site crawl** at the same depth used here."),o.push("2. Verify the **cross-page consistency findings** above all resolve (or document why a flagged divergence is intentional)."),o.push("3. Verify the **top-frequency rules** across pages resolve in bulk (a single shared-component fix should drop the count on multiple pages)."),o.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."),o.push("5. **Diff review** — every fix should be reviewable in under 10 minutes. One atomic commit per fix."),o.push(""),o.push(`_Generated by wcag-component-auditor v1.0.0.115 — site crawl mode (${e.length} pages)._`),o.join(`
|
|
2015
|
+
`)}const ih=Object.freeze(Object.defineProperty({__proto__:null,normUrlKey:$n,registerReportExporterHandlers:cp,toAiPrompt:Qi,toAiPromptForSiteCrawl:or,toAiPromptOwner:ar,toDefenseBundle:Rt,toDeveloperLetter:er,toEvidenceBundle:Zi,toHtmlPrint:Tn,toJUnit:Ki,toJson:zi,toOwnerReport:tr,toSarif:Hi,toVpat:Xi},Symbol.toStringTag,{value:"Module"})),Vt=ee("sw-auto-export");function pp(e,t,a){const n=vr(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 hp(e,t,a){try{if(e==="html-print")return Tn(t,a);if(e==="defense-bundle"){const n=await kt().catch(()=>[]);return Rt(t,a,"defense",void 0,n)}if(e==="deposition-packet")return(await Vi({results:t,delta:a,manualRuns:void 0,aiSummary:null})).html}catch(n){return Vt.warn(`buildContent failed for format=${e}`,n),null}return null}async function fp(e,t){var a,n,o;if(e.length!==0)try{const r=await yr();if(!r.enabled||await Fe())return;const i=await fe().catch(()=>"trial");if(!de(i,"autoExportAuditReports"))return;const c=((a=e[0])==null?void 0:a.pageUrl)??((n=e[0])==null?void 0:n.scope)??"",l=((o=e[0])==null?void 0:o.componentId)??null;for(const d of r.formats)try{const u=await hp(d,e,t);if(!u||u.length<200)continue;const m=pp(d,c,l),f=`data:${d==="ai-prompt"?"text/markdown":"text/html"};charset=utf-8,${encodeURIComponent(u)}`,g=await chrome.downloads.download({url:f,filename:m,saveAs:!1,conflictAction:"uniquify"});Vt.info(`scheduled auto-export started (id=${g}, file=${m})`),c&&await wr({url:c,exportedAt:new Date().toISOString(),format:d,filename:m})}catch(u){Vt.warn(`format ${d} failed in scheduled auto-export`,u)}}catch(r){Vt.warn("autoExportFromScheduledRun failed (audit itself still succeeded)",r)}}const De=ee("scheduled-audit-runner"),aa="scheduled-audit:",Eo={hourly:60,"every-4-hours":240,daily:1440,weekly:10080};function En(e){return`${aa}${e}`}function rh(e){return e.startsWith(aa)?e.slice(aa.length):null}async function gp(e){const t=En(e.id);await chrome.alarms.create(t,{periodInMinutes:Eo[e.cadence],delayInMinutes:Eo[e.cadence]})}async function sh(e){await chrome.alarms.clear(En(e))}async function ch(){try{const{listScheduledAudits:e}=await en(async()=>{const{listScheduledAudits:o}=await Promise.resolve().then(()=>Vr);return{listScheduledAudits:o}},void 0),t=await e(),a=await chrome.alarms.getAll(),n=new Set(t.filter(o=>o.enabled).map(o=>En(o.id)));for(const o of a)o.name.startsWith(aa)&&!n.has(o.name)&&await chrome.alarms.clear(o.name);for(const o of t)o.enabled&&await gp(o);De.info(`reconciled ${t.length} scheduled-audit alarms`)}catch(e){De.warn("failed to reconcile scheduled alarms",e)}}async function lh(e){var r;const t=Date.now(),a=await Uo(e);if(!a){De.warn(`scheduled audit ${e} not found — alarm fired for deleted schedule`);return}if(!a.enabled){De.debug(`scheduled audit ${e} is disabled — skipping`);return}if(await Fe()){await vt(a,{result:"failed",error:ze,durationMs:Date.now()-t,totalViolations:0,newVsBaselineViolations:0});return}const n=await fe();if(!de(n,"scheduledAudits")){await vt(a,{result:"failed",error:"Scheduled audits are not available on your current plan.",durationMs:Date.now()-t,totalViolations:0,newVsBaselineViolations:0});return}await rn({...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 mp(o,3e4);const l=await rt("html",{isCanceled:()=>!1},0,void 0,{asSubroutine:!0,tabIdOverride:o});if(!l.ok){await vt(a,{result:"failed",error:l.error??"audit failed",durationMs:Date.now()-t,totalViolations:0,newVsBaselineViolations:0});return}const d=l.results.reduce((f,g)=>f+g.violations.length,0),u=(r=l.results[0])==null?void 0:r.delta,m=(u==null?void 0:u.newCount)??0,p=new Date().toISOString();if(await vt(a,{result:"ok",durationMs:Date.now()-t,totalViolations:d,newVsBaselineViolations:m}),fp(l.results,u),m>0)try{const f=await nu({scheduleId:a.id,auditedUrl:a.url,ranAt:p,results:l.results});De.debug(`alert outcome for ${a.id}`,f)}catch(f){De.warn(`alert fire threw for ${a.id}`,f)}}catch(i){const c=i instanceof Error?i.message:String(i);De.warn(`scheduled audit ${e} failed:`,c),await vt(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 vt(e,t){const a=new Date().toISOString();await Wo({scheduleId:e.id,ranAt:a,durationMs:t.durationMs,totalViolations:t.totalViolations,newVsBaselineViolations:t.newVsBaselineViolations,error:t.error}),await rn({...e,lastRunAt:a,lastResult:t.result,lastError:t.error,lastTotalViolations:t.totalViolations,lastNewViolationCount:t.newVsBaselineViolations}),await qo(e.id);try{await du()}catch(n){De.warn("status badge refresh failed",n)}}function mp(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{Lp as $,_s as A,_p as B,Ds as C,Oe as D,is as E,Ep as F,jp as G,Hr as H,qp as I,Vp as J,Gp as K,Wt as L,zp as M,ai as N,Hp as O,Rp as P,Zo as Q,kt as R,Ko as S,Xs as T,ua as U,nt as V,Os as W,$e as X,Gr as Y,li as Z,Tt as _,ui as a,za as a0,Ne as a1,Es as a2,Np as a3,Op as a4,gn as a5,Le as a6,tu as a7,au as a8,_o as a9,ch as aA,rh as aB,lh as aC,th as aD,cp as aE,oh as aF,Bp as aG,rt as aH,qd as aI,Wd as aJ,Jp as aK,Kd as aL,Bd as aM,Yd as aN,Up as aO,Ws as aP,Hc as aQ,Sn as aR,Ka as aS,qt as aT,kp as aU,$p as aV,hs as aW,ah as aX,ih as aY,nh as aa,rn as ab,gp as ac,du as ad,Eo as ae,sh as af,_r as ag,qr as ah,Wr as ai,Pp as aj,Cp as ak,ue as al,Ee as am,Hl as an,Vl as ao,jl as ap,Ul as aq,Ll as ar,Dl as as,yc as at,eh as au,Xp as av,Zp as aw,Qp as ax,Fp as ay,Mp as az,cs as b,ls as c,Zs as d,Gt as e,Wp as f,dn as g,Dp as h,qe as i,zr as j,ia as k,Re as l,sn as m,Vo as n,Sp as o,xp as p,Tp as q,Yp as r,Kp as s,Ip as t,Go as u,Bo as v,Te as w,Va as x,Qo as y,ts as z};
|