@pie-players/pie-assessment-toolkit 0.3.66 → 0.3.67

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,8 +1,8 @@
1
- import{B as Z0,C as j0,I as q0,J as y,K as K0,L as W0,M as T8,O as U0,Q as M1,R as B0,S as $7,T as O8,b as K2,c as c7,d as Q0,e as Y0,f as s,g as C,h,i as R,j as b8,k as l7,l as S8,m as R1,n as T,o as J0,p as V,q as u,t as C8,u as G0,v as E1,w as b1,x as X0}from"./chunks/ItemToolBar-8jgdz50p.js";import{ContextProvider as t6,ContextRoot as e6,requestContext as A5}from"@pie-players/pie-context";import{attachInstrumentationEventBridge as M5,createStageTracker as N5,resolveInstrumentationProvider as z5,TOOLKIT_INSTRUMENTATION_EVENT_MAP as O5}from"@pie-players/pie-players-shared/pie";import{isInstrumentationProvider as P5}from"@pie-players/pie-players-shared";function s0(Q){return{kind:Q.kind,severity:Q.severity??"error",source:Q.source,message:Q.message,details:[...Q.details||[]],recoverable:Q.recoverable===!0,cause:Q.cause}}function G1(Q){let Y=Q.error instanceof Error&&Q.error.message.trim().length>0?Q.error.message:String(Q.error||"Unknown framework error");return s0({kind:Q.kind,source:Q.source,message:Y,recoverable:Q.recoverable,cause:Q.error})}var n0={"coordinator-ready":"coordinator-init","state-load":"tool-state-load","state-save":"tool-state-save","provider-register":"provider-register","provider-init":"provider-init","tts-init":"tts-init","section-controller-init":"section-controller-init","section-controller-dispose":"section-controller-dispose"};function r8(Q){let Y=n0[Q.context.phase],J=Q.context.providerId?`pie-toolkit-coordinator/${Q.context.providerId}`:`pie-toolkit-coordinator:${Q.context.phase}`;return G1({kind:Y,source:J,error:Q.error,recoverable:Q.recoverable})}function o8(Q){let Y=`[pie-framework:${Q.kind}:${Q.source}]`;if(Q.details.length===0)return`${Y} ${Q.message}`;return`${Y} ${Q.message}
1
+ import{B as j0,C as q0,I as K0,J as y,K as W0,L as U0,M as C8,O as B0,Q as P7,R as D0,S as w7,T as P8,b as W2,c as l7,d as Y0,e as J0,f as s,g as C,h,i as R,j as S8,k as d7,l as T8,m as R1,n as T,o as G0,p as V,q as u,t as y8,u as X0,v as E1,w as b1,x as Z0}from"./chunks/ItemToolBar-8jgdz50p.js";import{ContextProvider as e6,ContextRoot as Q0,requestContext as M5}from"@pie-players/pie-context";import{attachInstrumentationEventBridge as N5,createStageTracker as z5,resolveInstrumentationProvider as O5,TOOLKIT_INSTRUMENTATION_EVENT_MAP as P5}from"@pie-players/pie-players-shared/pie";import{isInstrumentationProvider as L5}from"@pie-players/pie-players-shared";function n0(Q){return{kind:Q.kind,severity:Q.severity??"error",source:Q.source,message:Q.message,details:[...Q.details||[]],recoverable:Q.recoverable===!0,cause:Q.cause}}function X1(Q){let Y=Q.error instanceof Error&&Q.error.message.trim().length>0?Q.error.message:String(Q.error||"Unknown framework error");return n0({kind:Q.kind,source:Q.source,message:Y,recoverable:Q.recoverable,cause:Q.error})}var r0={"coordinator-ready":"coordinator-init","state-load":"tool-state-load","state-save":"tool-state-save","provider-register":"provider-register","provider-init":"provider-init","tts-init":"tts-init","section-controller-init":"section-controller-init","section-controller-dispose":"section-controller-dispose"};function o8(Q){let Y=r0[Q.context.phase],J=Q.context.providerId?`pie-toolkit-coordinator/${Q.context.providerId}`:`pie-toolkit-coordinator:${Q.context.phase}`;return X1({kind:Y,source:J,error:Q.error,recoverable:Q.recoverable})}function a8(Q){let Y=`[pie-framework:${Q.kind}:${Q.source}]`;if(Q.details.length===0)return`${Y} ${Q.message}`;return`${Y} ${Q.message}
2
2
  - ${Q.details.join(`
3
- - `)}`}var r0="error";function u1(Q){if(Q==="off"||Q==="warn"||Q==="error")return Q;return r0}function g(Q){return Q}function o0(Q){if(!Q)return new Map;return new Map(Q.getAllTools().slice().sort((Y,J)=>Y.toolId.localeCompare(J.toolId)).map((Y)=>[Y.toolId,Y]))}function a0(Q,Y,J,G){if(!Y||!J?.provider?.sanitizeConfig)return Y;try{let X=J.provider.sanitizeConfig(Y);if(!X||typeof X!=="object"||Array.isArray(X))return G.push(g({code:"tools.providerSanitizeFailed",severity:"error",path:`providers.${Q}`,message:`Provider sanitizer for "${Q}" must return an object.`,providerId:Q,toolId:Q})),Y;return X}catch(X){return G.push(g({code:"tools.providerSanitizeFailed",severity:"error",path:`providers.${Q}`,message:`Provider sanitizer failed for "${Q}": ${X instanceof Error?X.message:String(X)}`,providerId:Q,toolId:Q})),Y}}function t0(Q,Y,J,G){if(!Y||!J?.provider?.validateConfig)return;try{let X=J.provider.validateConfig(Y);if(!Array.isArray(X)){G.push(g({code:"tools.invalidProviderValidation",severity:"error",path:`providers.${Q}`,message:`Provider validator for "${Q}" must return an array.`,providerId:Q,toolId:Q}));return}for(let j of X)G.push({...j,path:j.path||`providers.${Q}`,providerId:j.providerId||Q,toolId:j.toolId||Q})}catch(X){G.push(g({code:"tools.providerValidateFailed",severity:"error",path:`providers.${Q}`,message:`Provider validator failed for "${Q}": ${X instanceof Error?X.message:String(X)}`,providerId:Q,toolId:Q}))}}function e0(Q,Y,J){if(Y.size===0)return;let G=["section","item","passage"];for(let X of G)for(let j of Q.placement[X]){let Z=Y.get(j);if(!Z){J.push(g({code:"tools.unknownToolId",severity:"error",path:`placement.${X}`,message:`Unknown tool id "${j}" in placement.${X}.`,toolId:j}));continue}if(Z.activation==="region"){J.push(g({code:"tools.unplaceableActivation",severity:"error",path:`placement.${X}`,message:`Tool "${j}" renders into a host surface (activation "region") and cannot be placed on the ${X} toolbar. Remove it from placement.${X}; its availability comes from policy plus its content dependency.`,toolId:j}));continue}let q=Z.supportedLevels.includes(X),K=X==="item"&&Z.supportedLevels.includes("section");if(!q&&!K)J.push(g({code:"tools.unsupportedLevel",severity:"error",path:`placement.${X}`,message:`Tool "${j}" does not support level "${X}".`,toolId:j}))}}function Q3(Q,Y,J){if(Y.size===0)return;for(let G of Q.policy.allowed||[]){if(Y.has(G))continue;J.push(g({code:"tools.unknownToolId",severity:"error",path:"policy.allowed",message:`Unknown tool id "${G}" in policy.allowed.`,toolId:G}))}for(let G of Q.policy.blocked||[]){if(Y.has(G))continue;J.push(g({code:"tools.unknownToolId",severity:"error",path:"policy.blocked",message:`Unknown tool id "${G}" in policy.blocked.`,toolId:G}))}}function Y3(Q,Y,J,G){if(J)G.push(g({code:"tools.removedProviderKey",severity:"error",path:"providers.tts",message:'Provider key "tts" is no longer supported. Use "providers.textToSpeech".',providerId:"tts",toolId:"textToSpeech"}));for(let X of Object.keys(Q.providers).sort()){if(Y.size===0||Y.has(X))continue;G.push(g({code:"tools.unknownProviderKey",severity:"error",path:`providers.${X}`,message:`Unknown provider key "${X}".`,providerId:X,toolId:X}))}}function a8(Q,Y){if(Q.length===0)return;for(let J of Q){let G=`[tool-config-validation:${Y}]`;console.warn(`${G} ${J.path} - ${J.message}`)}}function t8(Q,Y){let J=Q.map((G)=>`- ${G.path}: ${G.message}`).join(`
3
+ - `)}`}var o0="error";function u1(Q){if(Q==="off"||Q==="warn"||Q==="error")return Q;return o0}function g(Q){return Q}function a0(Q){if(!Q)return new Map;return new Map(Q.getAllTools().slice().sort((Y,J)=>Y.toolId.localeCompare(J.toolId)).map((Y)=>[Y.toolId,Y]))}function t0(Q,Y,J,G){if(!Y||!J?.provider?.sanitizeConfig)return Y;try{let X=J.provider.sanitizeConfig(Y);if(!X||typeof X!=="object"||Array.isArray(X))return G.push(g({code:"tools.providerSanitizeFailed",severity:"error",path:`providers.${Q}`,message:`Provider sanitizer for "${Q}" must return an object.`,providerId:Q,toolId:Q})),Y;return X}catch(X){return G.push(g({code:"tools.providerSanitizeFailed",severity:"error",path:`providers.${Q}`,message:`Provider sanitizer failed for "${Q}": ${X instanceof Error?X.message:String(X)}`,providerId:Q,toolId:Q})),Y}}function e0(Q,Y,J,G){if(!Y||!J?.provider?.validateConfig)return;try{let X=J.provider.validateConfig(Y);if(!Array.isArray(X)){G.push(g({code:"tools.invalidProviderValidation",severity:"error",path:`providers.${Q}`,message:`Provider validator for "${Q}" must return an array.`,providerId:Q,toolId:Q}));return}for(let j of X)G.push({...j,path:j.path||`providers.${Q}`,providerId:j.providerId||Q,toolId:j.toolId||Q})}catch(X){G.push(g({code:"tools.providerValidateFailed",severity:"error",path:`providers.${Q}`,message:`Provider validator failed for "${Q}": ${X instanceof Error?X.message:String(X)}`,providerId:Q,toolId:Q}))}}function Q3(Q,Y,J){if(Y.size===0)return;let G=["section","item","passage"];for(let X of G)for(let j of Q.placement[X]){let Z=Y.get(j);if(!Z){J.push(g({code:"tools.unknownToolId",severity:"error",path:`placement.${X}`,message:`Unknown tool id "${j}" in placement.${X}.`,toolId:j}));continue}if(Z.activation==="region"){J.push(g({code:"tools.unplaceableActivation",severity:"error",path:`placement.${X}`,message:`Tool "${j}" renders into a host surface (activation "region") and cannot be placed on the ${X} toolbar. Remove it from placement.${X}; its availability comes from policy plus its content dependency.`,toolId:j}));continue}let q=Z.supportedLevels.includes(X),K=X==="item"&&Z.supportedLevels.includes("section");if(!q&&!K)J.push(g({code:"tools.unsupportedLevel",severity:"error",path:`placement.${X}`,message:`Tool "${j}" does not support level "${X}".`,toolId:j}))}}function Y3(Q,Y,J){if(Y.size===0)return;for(let G of Q.policy.allowed||[]){if(Y.has(G))continue;J.push(g({code:"tools.unknownToolId",severity:"error",path:"policy.allowed",message:`Unknown tool id "${G}" in policy.allowed.`,toolId:G}))}for(let G of Q.policy.blocked||[]){if(Y.has(G))continue;J.push(g({code:"tools.unknownToolId",severity:"error",path:"policy.blocked",message:`Unknown tool id "${G}" in policy.blocked.`,toolId:G}))}}function J3(Q,Y,J,G){if(J)G.push(g({code:"tools.removedProviderKey",severity:"error",path:"providers.tts",message:'Provider key "tts" is no longer supported. Use "providers.textToSpeech".',providerId:"tts",toolId:"textToSpeech"}));for(let X of Object.keys(Q.providers).sort()){if(Y.size===0||Y.has(X))continue;G.push(g({code:"tools.unknownProviderKey",severity:"error",path:`providers.${X}`,message:`Unknown provider key "${X}".`,providerId:X,toolId:X}))}}function t8(Q,Y){if(Q.length===0)return;for(let J of Q){let G=`[tool-config-validation:${Y}]`;console.warn(`${G} ${J.path} - ${J.message}`)}}function e8(Q,Y){let J=Q.map((G)=>`- ${G.path}: ${G.message}`).join(`
4
4
  `);throw Error(`[tool-config-validation:${Y}] Invalid tools config:
5
- ${J}`)}function G7(Q,Y={}){let J=u1(Y.strictness),G=Y.source??"tools",X=o0(Y.toolRegistry),j=$7(Q),Z=[],q=Object.values(j.placement).some((_)=>_.length>0)||Object.keys(j.providers).length>0||(j.policy.allowed?.length??0)>0||(j.policy.blocked?.length??0)>0;if(X.size===0&&q)Z.push(g({code:"tools.registryUnavailable",severity:"warning",path:"tools",message:'No tool registry was supplied, so tool ids, placement levels and provider config were not validated. Pass `toolRegistry` — for the packaged capability set, `createPackagedToolRegistry()` from "@pie-players/pie-default-tool-loaders".'}));let K=Object.hasOwn(j.providers,"tts"),B={...j.providers||{}};for(let _ of Object.keys(B).sort()){if(_==="tts"){delete B.tts;continue}let A=X.get(_);B[_]=a0(_,B[_],A,Z),t0(_,B[_],A,Z)}let U={...j,providers:B};if(e0(U,X,Z),Q3(U,X,Z),Y3(U,X,K,Z),K)t8(Z.filter((_)=>_.code==="tools.removedProviderKey"),G);if(J==="warn")a8(Z,G);let H=Z.filter((_)=>_.severity==="error");if(J==="error"&&H.length>0)t8(H,G);if(J==="error"&&H.length===0)a8(Z,G);return{config:U,diagnostics:Z}}var p1=(Q)=>Array.isArray(Q)&&Q.length>0;function g1(Q){if(Q.kind==="passage")return{ownerKind:"passage",assessmentId:Q.assessmentId,sectionId:Q.sectionId,passageId:Q.canonicalItemId||Q.itemId};return{ownerKind:"itemModel",assessmentId:Q.assessmentId,sectionId:Q.sectionId,itemId:Q.itemId,canonicalItemId:Q.canonicalItemId||Q.itemId}}function e8(Q,Y){if(!Q)return[];let J=g1(Y),G=[];if(p1(Q.accessibilityCatalogs))G.push({context:J,catalogs:Q.accessibilityCatalogs});if(p1(Q.config?.extractedCatalogs))G.push({context:J,catalogs:Q.config.extractedCatalogs});if(Y.kind==="passage")return G;if(J.ownerKind!=="itemModel")return G;for(let X of Q.config?.models??[]){if(!p1(X.accessibilityCatalogs))continue;G.push({context:{...J,modelId:X.id},catalogs:X.accessibilityCatalogs})}return G}var d1=new Set(["speak","break","prosody","emphasis","say-as","sub","mark","phoneme","lang","p","s","voice","audio","lexicon"]),Q9=new Set(["script","style","iframe","object","embed","foreignobject","noscript","template"]),Y9=new Set(["alphabet","ph","time","strength","rate","pitch","volume","name","interpret-as","format","detail","language","xml:lang","lang","gender","src"]),J9=new Set(["break","mark","lexicon"]);function J3(Q){let Y=Q;for(let J of J9){let G=new RegExp(`<${J}\\b([^>/]*?)\\s*/>`,"gi");Y=Y.replace(G,(X,j)=>{let Z=j?j.replace(/\s+$/,""):"";return`<${J}${Z}></${J}>`})}return Y}var G3=[/^localhost$/i,/^127(?:\.\d{1,3}){3}$/,/^0(?:\.\d{1,3}){3}$/,/^10(?:\.\d{1,3}){3}$/,/^192\.168(?:\.\d{1,3}){2}$/,/^172\.(?:1[6-9]|2\d|3[01])(?:\.\d{1,3}){2}$/,/^169\.254(?:\.\d{1,3}){2}$/,/^::1$/,/^fe80:/i,/^fc00:/i,/^fd[0-9a-f]{2}:/i,/^metadata\.google\.internal$/i,/^metadata\.azure\.internal$/i,/^metadata\.packet\.net$/i];function X3(Q){if(typeof Q!=="string"||Q.length===0)return!1;let Y;try{Y=new URL(Q)}catch{return!1}if(Y.protocol!=="http:"&&Y.protocol!=="https:")return!1;let J=Y.hostname.replace(/^\[|\]$/g,"").replace(/\.$/,"");return!G3.some((G)=>G.test(J))}function c1(Q){let Y=Array.from(Q.children);for(let G of Y){let X=G.tagName.toLowerCase();if(Q9.has(X)){G.remove();continue}if(c1(G),!d1.has(X)){let j=Q.ownerDocument.createTextNode(G.textContent??"");G.replaceWith(j)}}let J=Array.from(Q.attributes).map((G)=>G.name);for(let G of J)if(!Y9.has(G.toLowerCase()))Q.removeAttribute(G);if(Q.tagName.toLowerCase()==="audio"){let G=Q.getAttribute("src");if(G!==null&&!X3(G))Q.removeAttribute("src")}}function l1(Q){let Y=Q.tagName.toLowerCase(),J=Array.from(Q.attributes).filter((X)=>Y9.has(X.name.toLowerCase())).map((X)=>` ${X.name}="${Z3(X.value)}"`).join("");if(J9.has(Y))return`<${Y}${J}/>`;let G=[];for(let X of Array.from(Q.childNodes))if(X.nodeType===3)G.push(X1(X.nodeValue??""));else if(X.nodeType===1){let j=X,Z=j.tagName.toLowerCase();if(Q9.has(Z))continue;if(d1.has(Z))G.push(l1(j));else G.push(X1(j.textContent??""))}return`<${Y}${J}>${G.join("")}</${Y}>`}function i1(Q){let Y=String(Q||"").trim();if(!Y||!Y.includes("<"))return Q;if(typeof DOMParser>"u")return Q;let G=new DOMParser().parseFromString(J3(Y),"text/html"),X=G.querySelector("speak");if(X)return c1(X),l1(X);let j=G.createElement("speak");for(let Z of Array.from(G.body.childNodes))j.appendChild(Z);return c1(j),Array.from(j.childNodes).map((Z)=>{if(Z.nodeType===3)return X1(Z.nodeValue??"");if(Z.nodeType===1){let q=Z;if(d1.has(q.tagName.toLowerCase()))return l1(q);return X1(q.textContent??"")}return""}).join("")}function X1(Q){return Q.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function Z3(Q){return Q.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}var q9=new Set(["spoken","sign-language","transcript","braille","tactile","simplified-language","audio-description","extended-description"]),s1="ext:";function G9(Q){if(q9.has(Q))return!0;return Q.startsWith(s1)&&Q.length>s1.length}var X9=new Set;function n1(Q,Y=new Set){if(Q===null||typeof Q==="string"||typeof Q==="number"||typeof Q==="boolean"||typeof Q>"u")return Q;if(typeof Q!=="object")throw TypeError("catalog cards must contain JSON-compatible values");if(Y.has(Q))throw TypeError("catalog cards must not contain cycles");Y.add(Q);try{if(Array.isArray(Q))return Object.freeze(Q.map((X)=>n1(X,Y)));let J=Object.getPrototypeOf(Q);if(J!==Object.prototype&&J!==null)throw TypeError("catalog cards must contain only plain objects and arrays");let G={};for(let[X,j]of Object.entries(Q))G[X]=n1(j,Y);return Object.freeze(G)}finally{Y.delete(Q)}}function Z9(Q,Y,J){let G=`${Y}|${Q}`;if(X9.has(G))return;X9.add(G);let X=`${Array.from(q9).join(", ")}, or an "${s1}" prefixed vendor extension`;if(Y==="card"){console.warn(`[AccessibilityCatalogResolver] catalog "${J}" has a card of unknown type "${Q}"; it is stored but no reader asks for that type, so the alternate will never be shown. Expected one of: ${X}.`);return}console.warn(`[AccessibilityCatalogResolver] lookup for unknown catalog type "${Q}" on "${J}" cannot match any card. Expected one of: ${X}.`)}var j9=(Q)=>Q.payload!==void 0?"payload":"content";class r1{assessmentCatalogs=new Map;itemCatalogs=new Map;scopedCatalogs=new Map;defaultLanguage="en-US";sanitizedSpokenCache=new Map;catalogChangeListeners=new Set;reportedSnapshotProblems=new Set;constructor(Q,Y="en-US"){this.defaultLanguage=Y,this.indexCatalogs(Q??[],"assessment")}setDefaultLanguage(Q){this.defaultLanguage=Q}onCatalogsChange(Q){return this.catalogChangeListeners.add(Q),()=>{this.catalogChangeListeners.delete(Q)}}emitCatalogsChange(Q){for(let Y of Array.from(this.catalogChangeListeners))try{Y(Q)}catch{}}getDefaultLanguage(){return this.defaultLanguage}indexCatalogs(Q,Y){let J=Y==="assessment"?this.assessmentCatalogs:this.itemCatalogs;for(let G of this.sanitizeCatalogs(Q)){if(J.has(G.identifier)){console.warn(`[AccessibilityCatalogResolver] Duplicate ${Y} catalog "${G.identifier}" ignored`);continue}J.set(G.identifier,G)}}insertScopedCatalogs(Q,Y){if(!Y||Y.length===0)return null;let J=this.getOwnerKey(Q),G=this.scopedCatalogs.get(J),X=G?.catalogs??new Map,j=[];for(let Z of this.sanitizeCatalogs(Y)){if(X.has(Z.identifier)){console.warn(`[AccessibilityCatalogResolver] Duplicate scoped catalog "${Z.identifier}" ignored for ${J}`);continue}X.set(Z.identifier,Z),j.push(Z.identifier)}if(!G&&j.length>0)this.scopedCatalogs.set(J,{context:{...Q},catalogs:X});return{key:J,context:{...Q},catalogs:X,insertedIds:j}}removeScopedInsertion(Q){let Y=this.scopedCatalogs.get(Q.key);if(Y?.catalogs!==Q.catalogs)return!1;let J=!1;for(let G of Q.insertedIds)J=Y.catalogs.delete(G)||J;if(Y.catalogs.size===0)this.scopedCatalogs.delete(Q.key);return J}registerCatalogs(Q,Y){let J=this.insertScopedCatalogs(Q,Y);if(J&&J.insertedIds.length>0)this.emitCatalogsChange({reason:"scoped-registered",context:Q});let G=!0;return()=>{if(!G)return;if(G=!1,J&&this.removeScopedInsertion(J))this.emitCatalogsChange({reason:"scoped-removed",context:Q})}}registerOwner(Q){let{owner:Y,entity:J}=Q,G=g1(Y),X=[],j=[];try{j=e8(J,Y)}catch(K){console.warn("[AccessibilityCatalogResolver] A mounted content owner could not be traversed for catalogs; the primary content remains available.",K)}for(let K of j)try{let B=this.insertScopedCatalogs(K.context,K.catalogs);if(B)X.push(B)}catch(B){console.warn("[AccessibilityCatalogResolver] Invalid catalogs on a mounted content owner were ignored; the primary content and other valid catalogs remain available.",B)}if(X.some((K)=>K.insertedIds.length>0))this.emitCatalogsChange({reason:"scoped-registered",context:G});let q=!0;return()=>{if(!q)return;q=!1;let K=!1;for(let B of X)K=this.removeScopedInsertion(B)||K;if(K)this.emitCatalogsChange({reason:"scoped-removed",context:G})}}forOwner(Q){let Y={...Q};return Object.freeze({snapshot:()=>this.createOwnerSnapshot(Y),onChange:(J)=>this.onCatalogsChange((G)=>{if(this.catalogChangeAffectsOwner(G,Y))J()})})}addItemCatalogs(Q){if(!Q||Q.length===0)return;this.indexCatalogs(Q,"item"),this.emitCatalogsChange({reason:"item-added"})}clearItemCatalogs(){if(this.itemCatalogs.size===0)return;this.itemCatalogs.clear(),this.emitCatalogsChange({reason:"item-cleared"})}hasCatalog(Q){return this.itemCatalogs.has(Q)||this.assessmentCatalogs.has(Q)||Array.from(this.scopedCatalogs.values()).some((Y)=>Y.catalogs.has(Q))}getAlternative(Q,Y){if(!G9(Y.type))Z9(Y.type,"lookup",Q);let J=Y.context?this.scopedCatalogs.get(this.getOwnerKey(Y.context))?.catalogs.get(Q):null;if(J){let j=this.findMatchingCard(J,Y);if(j)return this.resolveCard(Q,j,"item")}if(Y.context){let j=this.findScopedCandidates(Q,Y.context);if(j.length===1){let Z=this.findMatchingCard(j[0],Y);if(Z)return this.resolveCard(Q,Z,"item")}else if(j.length>1)return console.warn(`[AccessibilityCatalogResolver] Ambiguous scoped catalog "${Q}" for owner context`,Y.context),null}let G=this.itemCatalogs.get(Q);if(G){let j=this.findMatchingCard(G,Y);if(j)return this.resolveCard(Q,j,"item")}let X=this.assessmentCatalogs.get(Q);if(X){let j=this.findMatchingCard(X,Y);if(j)return this.resolveCard(Q,j,"assessment")}return null}resolveCard(Q,Y,J){return{catalogId:Q,type:Y.catalog,language:Y.language,content:Y.catalog==="spoken"&&Y.content!==void 0?this.ensureSpokenSanitized(Y.content):Y.content,payload:Y.payload,source:J}}ensureSpokenSanitized(Q){let Y=this.sanitizedSpokenCache.get(Q);if(Y!==void 0)return Y;let J=i1(Q);return this.sanitizedSpokenCache.set(Q,J),J}getOwnerKey(Q){return[Q.ownerKind,Q.assessmentId||"",Q.sectionId||"",Q.canonicalItemId||"",Q.itemId||"",Q.passageId||"",Q.modelId||""].join("|")}scopedCatalogEntries(){let Q=[];for(let Y of this.scopedCatalogs.values())for(let J of Y.catalogs.entries())Q.push(J);return Q}findScopedCandidates(Q,Y){return Array.from(this.scopedCatalogs.values()).filter((J)=>this.isCompatibleOwnerContext(J.context,Y)).map((J)=>J.catalogs.get(Q)).filter((J)=>Boolean(J))}isCompatibleOwnerContext(Q,Y){if(Q.ownerKind!==Y.ownerKind)return!1;if(Y.assessmentId&&Q.assessmentId!==Y.assessmentId)return!1;if(Y.sectionId&&Q.sectionId!==Y.sectionId)return!1;if(Y.canonicalItemId&&Q.canonicalItemId!==Y.canonicalItemId)return!1;if(Y.itemId&&Q.itemId!==Y.itemId)return!1;if(Y.passageId&&Q.passageId!==Y.passageId)return!1;if(Y.modelId&&Q.modelId!==Y.modelId)return!1;return!0}ownerScopedCatalogEntries(Q){let Y=[],J=this.scopedCatalogs.get(this.getOwnerKey(Q));if(J)Y.push(...J.catalogs.entries());for(let G of this.scopedCatalogs.values()){if(G===J)continue;if(!this.isCompatibleOwnerContext(G.context,Q))continue;Y.push(...G.catalogs.entries())}return Y}createOwnerSnapshot(Q){let Y=[],J=this.ownerScopedCatalogEntries(Q);if(Q.ownerKind==="global")J.push(...this.assessmentCatalogs.entries());for(let[G,X]of J)for(let j of X.cards)try{Y.push(Object.freeze({catalogId:G,card:n1(j)}))}catch(Z){let q=`${this.getOwnerKey(Q)}\x00${G}`;if(!this.reportedSnapshotProblems.has(q))this.reportedSnapshotProblems.add(q),console.warn(`[AccessibilityCatalogResolver] Catalog "${G}" contains a card that cannot be exposed in an owner snapshot; that card was ignored.`,Z)}return Object.freeze({cards:Object.freeze(Y)})}catalogChangeAffectsOwner(Q,Y){if(!Q.context)return!1;if(this.isCompatibleOwnerContext(Q.context,Y))return!0;if(Y.ownerKind==="itemModel"&&Y.modelId&&Q.context.ownerKind==="itemModel"&&!Q.context.modelId)return this.isCompatibleOwnerContext({...Q.context,modelId:Y.modelId},Y);return!1}sanitizeCatalogs(Q){return Q.map((Y)=>({...Y,cards:Y.cards.map((J)=>{if(!G9(J.catalog))Z9(J.catalog,"card",Y.identifier);return{...J,content:J.catalog==="spoken"&&J.content!==void 0?i1(J.content):J.content}})}))}findMatchingCard(Q,Y){let{type:J,language:G,useFallback:X=!0,form:j}=Y,Z=[];if(G)Z.push((q)=>q.language===G);if(X)Z.push((q)=>q.language===this.defaultLanguage),Z.push(()=>!0);for(let q of Z){let K=Q.cards.filter((B)=>B.catalog===J&&q(B));if(K.length===0)continue;if(j){let B=K.find((U)=>j9(U)===j);if(B)return B}return K[0]}return null}getAllAlternatives(Q){let Y=[],J=new Set,G=(Z,q)=>{let K=`${Z.catalog}|${Z.language??""}|${j9(Z)}`;if(J.has(K))return;J.add(K),Y.push(this.resolveCard(Q,Z,q))},X=this.itemCatalogs.get(Q);if(X)for(let Z of X.cards)G(Z,"item");let j=this.assessmentCatalogs.get(Q);if(j)for(let Z of j.cards)G(Z,"assessment");for(let[Z,q]of this.scopedCatalogEntries()){if(Z!==Q)continue;for(let K of q.cards)G(K,"item")}return Y}getAllCatalogIds(){let Q=this.scopedCatalogEntries().map(([Y])=>Y);return Array.from(new Set([...this.itemCatalogs.keys(),...this.assessmentCatalogs.keys(),...Q]))}getStatistics(){let Q=new Set,Y=new Set;for(let J of this.assessmentCatalogs.values())for(let G of J.cards)if(Q.add(G.catalog),G.language)Y.add(G.language);for(let J of this.itemCatalogs.values())for(let G of J.cards)if(Q.add(G.catalog),G.language)Y.add(G.language);for(let J of this.scopedCatalogs.values())for(let G of J.catalogs.values())for(let X of G.cards)if(Q.add(X.catalog),X.language)Y.add(X.language);return{totalCatalogs:this.assessmentCatalogs.size+this.itemCatalogs.size+Array.from(this.scopedCatalogs.values()).reduce((J,G)=>J+G.catalogs.size,0),assessmentCatalogs:this.assessmentCatalogs.size,itemCatalogs:this.itemCatalogs.size+Array.from(this.scopedCatalogs.values()).reduce((J,G)=>J+G.catalogs.size,0),availableTypes:Q,availableLanguages:Y}}hasAlternativeType(Q,Y){return this.getAllAlternatives(Q).some((G)=>G.type===Y)}getCatalogsByType(Q){let Y=new Set;for(let[J,G]of this.assessmentCatalogs.entries())if(G.cards.some((X)=>X.catalog===Q))Y.add(J);for(let[J,G]of this.itemCatalogs.entries())if(G.cards.some((X)=>X.catalog===Q))Y.add(J);for(let[J,G]of this.scopedCatalogEntries())if(G.cards.some((X)=>X.catalog===Q))Y.add(J);return Array.from(Y)}reset(){this.assessmentCatalogs.clear(),this.itemCatalogs.clear(),this.scopedCatalogs.clear(),this.sanitizedSpokenCache.clear(),this.reportedSnapshotProblems.clear()}destroy(){this.reset()}}class o1{elementStates=new Map;listeners=new Set;onStateChange=null;getGlobalElementId(Q,Y,J,G){return`${Q}:${Y}:${J}:${G}`}parseGlobalElementId(Q){let Y=Q.split(":");if(Y.length!==4)return null;return{assessmentId:Y[0],sectionId:Y[1],itemId:Y[2],elementId:Y[3]}}setState(Q,Y,J){let G=this.elementStates.get(Q);if(!G)G=new Map,this.elementStates.set(Q,G);G.set(Y,J),this._notifyListeners(),this._notifyStateChange()}getState(Q,Y){return this.elementStates.get(Q)?.get(Y)}getElementState(Q){let Y=this.elementStates.get(Q);if(!Y)return{};return Object.fromEntries(Y.entries())}getAllState(){let Q={};for(let[Y,J]of this.elementStates.entries())Q[Y]=Object.fromEntries(J.entries());return Q}subscribe(Q){return this.listeners.add(Q),()=>this.listeners.delete(Q)}_notifyListeners(){for(let Q of this.listeners)Q(this.elementStates)}setOnStateChange(Q){this.onStateChange=Q}_notifyStateChange(){if(this.onStateChange)this.onStateChange(this.getAllState())}loadState(Q){this.elementStates.clear();for(let[Y,J]of Object.entries(Q)){let G=new Map(Object.entries(J));this.elementStates.set(Y,G)}this._notifyListeners()}clearElement(Q){this.elementStates.delete(Q),this._notifyListeners(),this._notifyStateChange()}clearTool(Q){for(let Y of this.elementStates.values())Y.delete(Q);this._notifyListeners(),this._notifyStateChange()}clearSection(Q,Y){let J=`${Q}:${Y}:`,G=[];for(let X of this.elementStates.keys())if(X.startsWith(J))G.push(X);for(let X of G)this.elementStates.delete(X);this._notifyListeners(),this._notifyStateChange()}clearAll(){this.elementStates.clear(),this._notifyListeners(),this._notifyStateChange()}}class v7{listeners=new Set;subscribeFrameworkErrors(Q){this.listeners.add(Q);let Y=!0;return()=>{if(!Y)return;Y=!1,this.listeners.delete(Q)}}reportFrameworkError(Q){let Y=Array.from(this.listeners);for(let J of Y)try{J(Q)}catch(G){console.warn("[FrameworkErrorBus] listener failed:",G)}}dispose(){this.listeners.clear()}getListenerCount(){return this.listeners.size}}class a1{serialize(Q,Y){return{startContainer:this.getNodePath(Q.startContainer,Y),startOffset:Q.startOffset,endContainer:this.getNodePath(Q.endContainer,Y),endOffset:Q.endOffset,text:Q.toString()}}deserialize(Q,Y){let J=this.findNodeByPath(Q.startContainer,Y),G=this.findNodeByPath(Q.endContainer,Y);if(!J||!G)return null;try{let X=new Range;if(X.setStart(J,Q.startOffset),X.setEnd(G,Q.endOffset),X.toString()===Q.text)return X;return null}catch(X){return console.warn("Failed to deserialize range:",X),null}}getNodePath(Q,Y){if(Q===Y)return"";if(Q.nodeType===Node.TEXT_NODE){let J=Q.parentElement;if(!J)throw Error("Text node has no parent");let X=Array.from(J.childNodes).filter((Z)=>Z.nodeType===Node.TEXT_NODE).indexOf(Q);return`${this.getElementPath(J,Y)}::text[${X}]`}if(Q.nodeType===Node.ELEMENT_NODE)return this.getElementPath(Q,Y);throw Error(`Unsupported node type: ${Q.nodeType}`)}getElementPath(Q,Y){if(Q===Y)return"";let J=[],G=Q;while(G&&G!==Y){if(G.id){J.unshift(`#${G.id}`);break}let X=G.parentElement;if(!X)break;let j=Array.from(X.children).filter((K)=>K.tagName===G.tagName),Z=j.indexOf(G),q=j.length>1?`${G.tagName.toLowerCase()}:nth-of-type(${Z+1})`:G.tagName.toLowerCase();J.unshift(q),G=X}return J.join(" > ")}findNodeByPath(Q,Y){if(Q==="")return Y;if(Q.includes("::text[")){let[J,G]=Q.split("::text["),X=Number.parseInt(G.replace("]",""),10),j=J?Y.querySelector(J):Y;if(!j)return null;return Array.from(j.childNodes).filter((q)=>q.nodeType===Node.TEXT_NODE)[X]||null}try{return Y.querySelector(Q)}catch(J){return console.warn("Invalid selector path:",Q,J),null}}serializeMany(Q,Y){return Q.map((J)=>this.serialize(J,Y))}deserializeMany(Q,Y){return Q.map((J)=>this.deserialize(J,Y))}}var m;(function(Q){Q.TTS_WORD="tts-word",Q.TTS_SENTENCE="tts-sentence",Q.ANNOTATION="annotation"})(m||(m={}));var D7;(function(Q){Q.YELLOW="yellow",Q.GREEN="green",Q.BLUE="blue",Q.PINK="pink",Q.ORANGE="orange",Q.UNDERLINE="underline"})(D7||(D7={}));class h7{config;ttsWordHighlight=null;ttsSentenceHighlight=null;ttsWordElementHighlights=new Set;ttsSentenceElementHighlights=new Set;annotations=new Map;colorHighlights=new Map;nextAnnotationId=1;supported=!1;rangeSerializer;themeObserver=null;explicitTTSColorOverride=null;constructor(Q={}){if(this.config=Q,this.rangeSerializer=new a1,typeof CSS>"u"||!("highlights"in CSS)){console.warn("CSS Custom Highlight API not supported (SSR or unsupported browser)");return}this.supported=!0,this.initializeHighlights(),this.registerStyles(),this.applyAdaptiveTTSStyle(),this.setupThemeObservation()}setupThemeObservation(){if(typeof document>"u")return;if(typeof MutationObserver>"u")return;let Q=()=>this.applyAdaptiveTTSStyle();this.themeObserver=new MutationObserver(Q),this.themeObserver.observe(document.documentElement,{attributes:!0,attributeFilter:["style","data-theme","data-color-scheme","class"]});for(let Y of document.querySelectorAll("pie-theme"))this.themeObserver.observe(Y,{attributes:!0,attributeFilter:["theme","scheme","provider","variables","style","data-theme","data-color-scheme"]})}parseColor(Q){if(!Q)return null;let Y=Q.trim();if(!Y)return null;let J=/^#([a-f\d]{3}|[a-f\d]{6})$/i.exec(Y);if(J){let X=J[1];if(X.length===3)return[parseInt(X[0]+X[0],16),parseInt(X[1]+X[1],16),parseInt(X[2]+X[2],16)];return[parseInt(X.slice(0,2),16),parseInt(X.slice(2,4),16),parseInt(X.slice(4,6),16)]}let G=/^rgba?\((.+)\)$/i.exec(Y);if(G){let j=G[1].replace(/\//g,",").split(/[,\s]+/).map((B)=>B.trim()).filter(Boolean),Z=Number(j[0]),q=Number(j[1]),K=Number(j[2]);if(Number.isFinite(Z)&&Number.isFinite(q)&&Number.isFinite(K))return[Z,q,K]}if(typeof document<"u"){let X=document.createElement("span");if(X.style.color=Y,typeof X.style.color==="string"&&X.style.color){document.body?.appendChild(X);let j=typeof getComputedStyle==="function"?getComputedStyle(X).color:"";X.remove();let Z=j.trim();if(Z&&Z!==Y)return this.parseColor(j)}}return null}relativeLuminance([Q,Y,J]){let G=(q)=>{let K=q/255;return K<=0.03928?K/12.92:((K+0.055)/1.055)**2.4},X=G(Q),j=G(Y),Z=G(J);return 0.2126*X+0.7152*j+0.0722*Z}contrastRatio(Q,Y){let J=this.relativeLuminance(Q),G=this.relativeLuminance(Y),X=Math.max(J,G),j=Math.min(J,G);return(X+0.05)/(j+0.05)}blend(Q,Y,J){return[Math.round(Q[0]*J+Y[0]*(1-J)),Math.round(Q[1]*J+Y[1]*(1-J)),Math.round(Q[2]*J+Y[2]*(1-J))]}resolveAdaptiveTTSStyle(Q){let Y=[255,235,59],J=[17,24,39],G=[255,255,255],X=Q||(typeof document<"u"?document.documentElement:null),j=X&&typeof getComputedStyle==="function"?getComputedStyle(X):null,Z=this.parseColor(j?.getPropertyValue("--pie-background")||j?.backgroundColor)||G,q=this.parseColor(j?.getPropertyValue("--pie-text"))||J,K=this.explicitTTSColorOverride?this.parseColor(this.explicitTTSColorOverride.color)||Y:this.parseColor(j?.getPropertyValue("--pie-missing"))||Y,B=this.explicitTTSColorOverride?[Math.max(0.3,Math.min(0.95,this.explicitTTSColorOverride.opacity))]:[0.8,0.72,0.68,0.62,0.56,0.5],U=B[B.length-1],H=-1/0;for(let l of B){let Z7=this.blend(K,Z,l),j7=this.contrastRatio(Z7,Z),P7=this.contrastRatio(Z7,q),q7=j7*1.2+P7*0.8;if(j7>=1.25&&P7>=2.4){U=l;break}if(q7>H)H=q7,U=l}let _=Math.max(0.24,Math.min(0.85,U*0.55)),A=Math.max(0.55,Math.min(0.95,U+0.2)),M=Math.max(0.22,Math.min(0.6,U*0.45)),O=q,L=this.blend(O,Z,A),F=this.contrastRatio(L,Z),$=this.relativeLuminance(Z)>0.45?[0,0,0]:[255,255,255],b=F>=1.35?O:$,v=`rgba(${K[0]}, ${K[1]}, ${K[2]}, ${U})`,k=`rgba(${K[0]}, ${K[1]}, ${K[2]}, ${_})`,p=`rgba(${b[0]}, ${b[1]}, ${b[2]}, ${A})`,w=`rgba(${b[0]}, ${b[1]}, ${b[2]}, ${M})`;return{wordHighlight:v,sentenceHighlight:k,wordUnderline:p,wordShadow:w}}applyAdaptiveTTSStyle(Q){if(typeof document>"u")return;let Y=this.resolveAdaptiveTTSStyle(Q);document.documentElement.style.setProperty("--pie-tts-word-highlight",Y.wordHighlight),document.documentElement.style.setProperty("--pie-tts-sentence-highlight",Y.sentenceHighlight),document.documentElement.style.setProperty("--pie-tts-line-highlight",Y.sentenceHighlight),document.documentElement.style.setProperty("--pie-tts-word-underline",Y.wordUnderline),document.documentElement.style.setProperty("--pie-tts-word-shadow",Y.wordShadow)}initializeHighlights(){if(!this.supported)return;this.ttsWordHighlight=new Highlight,this.ttsSentenceHighlight=new Highlight,CSS.highlights.set("tts-word",this.ttsWordHighlight),CSS.highlights.set("tts-sentence",this.ttsSentenceHighlight);for(let Q of Object.values(D7)){let Y=new Highlight;this.colorHighlights.set(Q,Y),CSS.highlights.set(`annotation-${Q}`,Y)}}registerStyles(){if(!this.supported)return;if(typeof document>"u")return;if(document.getElementById("pie-highlight-styles"))return;let Q=document.createElement("style");Q.id="pie-highlight-styles",Q.textContent=`
5
+ ${J}`)}function G7(Q,Y={}){let J=u1(Y.strictness),G=Y.source??"tools",X=a0(Y.toolRegistry),j=w7(Q),Z=[],q=Object.values(j.placement).some((_)=>_.length>0)||Object.keys(j.providers).length>0||(j.policy.allowed?.length??0)>0||(j.policy.blocked?.length??0)>0;if(X.size===0&&q)Z.push(g({code:"tools.registryUnavailable",severity:"warning",path:"tools",message:'No tool registry was supplied, so tool ids, placement levels and provider config were not validated. Pass `toolRegistry` — for the packaged capability set, `createPackagedToolRegistry()` from "@pie-players/pie-default-tool-loaders".'}));let K=Object.hasOwn(j.providers,"tts"),B={...j.providers||{}};for(let _ of Object.keys(B).sort()){if(_==="tts"){delete B.tts;continue}let A=X.get(_);B[_]=t0(_,B[_],A,Z),e0(_,B[_],A,Z)}let U={...j,providers:B};if(Q3(U,X,Z),Y3(U,X,Z),J3(U,X,K,Z),K)e8(Z.filter((_)=>_.code==="tools.removedProviderKey"),G);if(J==="warn")t8(Z,G);let H=Z.filter((_)=>_.severity==="error");if(J==="error"&&H.length>0)e8(H,G);if(J==="error"&&H.length===0)t8(Z,G);return{config:U,diagnostics:Z}}var p1=(Q)=>Array.isArray(Q)&&Q.length>0;function g1(Q){if(Q.kind==="passage")return{ownerKind:"passage",assessmentId:Q.assessmentId,sectionId:Q.sectionId,passageId:Q.canonicalItemId||Q.itemId};return{ownerKind:"itemModel",assessmentId:Q.assessmentId,sectionId:Q.sectionId,itemId:Q.itemId,canonicalItemId:Q.canonicalItemId||Q.itemId}}function Q9(Q,Y){if(!Q)return[];let J=g1(Y),G=[];if(p1(Q.accessibilityCatalogs))G.push({context:J,catalogs:Q.accessibilityCatalogs});if(p1(Q.config?.extractedCatalogs))G.push({context:J,catalogs:Q.config.extractedCatalogs});if(Y.kind==="passage")return G;if(J.ownerKind!=="itemModel")return G;for(let X of Q.config?.models??[]){if(!p1(X.accessibilityCatalogs))continue;G.push({context:{...J,modelId:X.id},catalogs:X.accessibilityCatalogs})}return G}var d1=new Set(["speak","break","prosody","emphasis","say-as","sub","mark","phoneme","lang","p","s","voice","audio","lexicon"]),Y9=new Set(["script","style","iframe","object","embed","foreignobject","noscript","template"]),J9=new Set(["alphabet","ph","time","strength","rate","pitch","volume","name","interpret-as","format","detail","language","xml:lang","lang","gender","src"]),G9=new Set(["break","mark","lexicon"]);function G3(Q){let Y=Q;for(let J of G9){let G=new RegExp(`<${J}\\b([^>/]*?)\\s*/>`,"gi");Y=Y.replace(G,(X,j)=>{let Z=j?j.replace(/\s+$/,""):"";return`<${J}${Z}></${J}>`})}return Y}var X3=[/^localhost$/i,/^127(?:\.\d{1,3}){3}$/,/^0(?:\.\d{1,3}){3}$/,/^10(?:\.\d{1,3}){3}$/,/^192\.168(?:\.\d{1,3}){2}$/,/^172\.(?:1[6-9]|2\d|3[01])(?:\.\d{1,3}){2}$/,/^169\.254(?:\.\d{1,3}){2}$/,/^::1$/,/^fe80:/i,/^fc00:/i,/^fd[0-9a-f]{2}:/i,/^metadata\.google\.internal$/i,/^metadata\.azure\.internal$/i,/^metadata\.packet\.net$/i];function Z3(Q){if(typeof Q!=="string"||Q.length===0)return!1;let Y;try{Y=new URL(Q)}catch{return!1}if(Y.protocol!=="http:"&&Y.protocol!=="https:")return!1;let J=Y.hostname.replace(/^\[|\]$/g,"").replace(/\.$/,"");return!X3.some((G)=>G.test(J))}function c1(Q){let Y=Array.from(Q.children);for(let G of Y){let X=G.tagName.toLowerCase();if(Y9.has(X)){G.remove();continue}if(c1(G),!d1.has(X)){let j=Q.ownerDocument.createTextNode(G.textContent??"");G.replaceWith(j)}}let J=Array.from(Q.attributes).map((G)=>G.name);for(let G of J)if(!J9.has(G.toLowerCase()))Q.removeAttribute(G);if(Q.tagName.toLowerCase()==="audio"){let G=Q.getAttribute("src");if(G!==null&&!Z3(G))Q.removeAttribute("src")}}function l1(Q){let Y=Q.tagName.toLowerCase(),J=Array.from(Q.attributes).filter((X)=>J9.has(X.name.toLowerCase())).map((X)=>` ${X.name}="${j3(X.value)}"`).join("");if(G9.has(Y))return`<${Y}${J}/>`;let G=[];for(let X of Array.from(Q.childNodes))if(X.nodeType===3)G.push(Z1(X.nodeValue??""));else if(X.nodeType===1){let j=X,Z=j.tagName.toLowerCase();if(Y9.has(Z))continue;if(d1.has(Z))G.push(l1(j));else G.push(Z1(j.textContent??""))}return`<${Y}${J}>${G.join("")}</${Y}>`}function i1(Q){let Y=String(Q||"").trim();if(!Y||!Y.includes("<"))return Q;if(typeof DOMParser>"u")return Q;let G=new DOMParser().parseFromString(G3(Y),"text/html"),X=G.querySelector("speak");if(X)return c1(X),l1(X);let j=G.createElement("speak");for(let Z of Array.from(G.body.childNodes))j.appendChild(Z);return c1(j),Array.from(j.childNodes).map((Z)=>{if(Z.nodeType===3)return Z1(Z.nodeValue??"");if(Z.nodeType===1){let q=Z;if(d1.has(q.tagName.toLowerCase()))return l1(q);return Z1(q.textContent??"")}return""}).join("")}function Z1(Q){return Q.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function j3(Q){return Q.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}var K9=new Set(["spoken","sign-language","transcript","braille","tactile","simplified-language","audio-description","extended-description"]),s1="ext:";function X9(Q){if(K9.has(Q))return!0;return Q.startsWith(s1)&&Q.length>s1.length}var Z9=new Set;function n1(Q,Y=new Set){if(Q===null||typeof Q==="string"||typeof Q==="number"||typeof Q==="boolean"||typeof Q>"u")return Q;if(typeof Q!=="object")throw TypeError("catalog cards must contain JSON-compatible values");if(Y.has(Q))throw TypeError("catalog cards must not contain cycles");Y.add(Q);try{if(Array.isArray(Q))return Object.freeze(Q.map((X)=>n1(X,Y)));let J=Object.getPrototypeOf(Q);if(J!==Object.prototype&&J!==null)throw TypeError("catalog cards must contain only plain objects and arrays");let G={};for(let[X,j]of Object.entries(Q))G[X]=n1(j,Y);return Object.freeze(G)}finally{Y.delete(Q)}}function j9(Q,Y,J){let G=`${Y}|${Q}`;if(Z9.has(G))return;Z9.add(G);let X=`${Array.from(K9).join(", ")}, or an "${s1}" prefixed vendor extension`;if(Y==="card"){console.warn(`[AccessibilityCatalogResolver] catalog "${J}" has a card of unknown type "${Q}"; it is stored but no reader asks for that type, so the alternate will never be shown. Expected one of: ${X}.`);return}console.warn(`[AccessibilityCatalogResolver] lookup for unknown catalog type "${Q}" on "${J}" cannot match any card. Expected one of: ${X}.`)}var q9=(Q)=>Q.payload!==void 0?"payload":"content";class r1{assessmentCatalogs=new Map;itemCatalogs=new Map;scopedCatalogs=new Map;defaultLanguage="en-US";sanitizedSpokenCache=new Map;catalogChangeListeners=new Set;reportedSnapshotProblems=new Set;constructor(Q,Y="en-US"){this.defaultLanguage=Y,this.indexCatalogs(Q??[],"assessment")}setDefaultLanguage(Q){this.defaultLanguage=Q}onCatalogsChange(Q){return this.catalogChangeListeners.add(Q),()=>{this.catalogChangeListeners.delete(Q)}}emitCatalogsChange(Q){for(let Y of Array.from(this.catalogChangeListeners))try{Y(Q)}catch{}}getDefaultLanguage(){return this.defaultLanguage}indexCatalogs(Q,Y){let J=Y==="assessment"?this.assessmentCatalogs:this.itemCatalogs;for(let G of this.sanitizeCatalogs(Q)){if(J.has(G.identifier)){console.warn(`[AccessibilityCatalogResolver] Duplicate ${Y} catalog "${G.identifier}" ignored`);continue}J.set(G.identifier,G)}}insertScopedCatalogs(Q,Y){if(!Y||Y.length===0)return null;let J=this.getOwnerKey(Q),G=this.scopedCatalogs.get(J),X=G?.catalogs??new Map,j=[];for(let Z of this.sanitizeCatalogs(Y)){if(X.has(Z.identifier)){console.warn(`[AccessibilityCatalogResolver] Duplicate scoped catalog "${Z.identifier}" ignored for ${J}`);continue}X.set(Z.identifier,Z),j.push(Z.identifier)}if(!G&&j.length>0)this.scopedCatalogs.set(J,{context:{...Q},catalogs:X});return{key:J,context:{...Q},catalogs:X,insertedIds:j}}removeScopedInsertion(Q){let Y=this.scopedCatalogs.get(Q.key);if(Y?.catalogs!==Q.catalogs)return!1;let J=!1;for(let G of Q.insertedIds)J=Y.catalogs.delete(G)||J;if(Y.catalogs.size===0)this.scopedCatalogs.delete(Q.key);return J}registerCatalogs(Q,Y){let J=this.insertScopedCatalogs(Q,Y);if(J&&J.insertedIds.length>0)this.emitCatalogsChange({reason:"scoped-registered",context:Q});let G=!0;return()=>{if(!G)return;if(G=!1,J&&this.removeScopedInsertion(J))this.emitCatalogsChange({reason:"scoped-removed",context:Q})}}registerOwner(Q){let{owner:Y,entity:J}=Q,G=g1(Y),X=[],j=[];try{j=Q9(J,Y)}catch(K){console.warn("[AccessibilityCatalogResolver] A mounted content owner could not be traversed for catalogs; the primary content remains available.",K)}for(let K of j)try{let B=this.insertScopedCatalogs(K.context,K.catalogs);if(B)X.push(B)}catch(B){console.warn("[AccessibilityCatalogResolver] Invalid catalogs on a mounted content owner were ignored; the primary content and other valid catalogs remain available.",B)}if(X.some((K)=>K.insertedIds.length>0))this.emitCatalogsChange({reason:"scoped-registered",context:G});let q=!0;return()=>{if(!q)return;q=!1;let K=!1;for(let B of X)K=this.removeScopedInsertion(B)||K;if(K)this.emitCatalogsChange({reason:"scoped-removed",context:G})}}forOwner(Q){let Y={...Q};return Object.freeze({snapshot:()=>this.createOwnerSnapshot(Y),onChange:(J)=>this.onCatalogsChange((G)=>{if(this.catalogChangeAffectsOwner(G,Y))J()})})}addItemCatalogs(Q){if(!Q||Q.length===0)return;this.indexCatalogs(Q,"item"),this.emitCatalogsChange({reason:"item-added"})}clearItemCatalogs(){if(this.itemCatalogs.size===0)return;this.itemCatalogs.clear(),this.emitCatalogsChange({reason:"item-cleared"})}hasCatalog(Q){return this.itemCatalogs.has(Q)||this.assessmentCatalogs.has(Q)||Array.from(this.scopedCatalogs.values()).some((Y)=>Y.catalogs.has(Q))}getAlternative(Q,Y){if(!X9(Y.type))j9(Y.type,"lookup",Q);let J=Y.context?this.scopedCatalogs.get(this.getOwnerKey(Y.context))?.catalogs.get(Q):null;if(J){let j=this.findMatchingCard(J,Y);if(j)return this.resolveCard(Q,j,"item")}if(Y.context){let j=this.findScopedCandidates(Q,Y.context);if(j.length===1){let Z=this.findMatchingCard(j[0],Y);if(Z)return this.resolveCard(Q,Z,"item")}else if(j.length>1)return console.warn(`[AccessibilityCatalogResolver] Ambiguous scoped catalog "${Q}" for owner context`,Y.context),null}let G=this.itemCatalogs.get(Q);if(G){let j=this.findMatchingCard(G,Y);if(j)return this.resolveCard(Q,j,"item")}let X=this.assessmentCatalogs.get(Q);if(X){let j=this.findMatchingCard(X,Y);if(j)return this.resolveCard(Q,j,"assessment")}return null}resolveCard(Q,Y,J){return{catalogId:Q,type:Y.catalog,language:Y.language,content:Y.catalog==="spoken"&&Y.content!==void 0?this.ensureSpokenSanitized(Y.content):Y.content,payload:Y.payload,source:J}}ensureSpokenSanitized(Q){let Y=this.sanitizedSpokenCache.get(Q);if(Y!==void 0)return Y;let J=i1(Q);return this.sanitizedSpokenCache.set(Q,J),J}getOwnerKey(Q){return[Q.ownerKind,Q.assessmentId||"",Q.sectionId||"",Q.canonicalItemId||"",Q.itemId||"",Q.passageId||"",Q.modelId||""].join("|")}scopedCatalogEntries(){let Q=[];for(let Y of this.scopedCatalogs.values())for(let J of Y.catalogs.entries())Q.push(J);return Q}findScopedCandidates(Q,Y){return Array.from(this.scopedCatalogs.values()).filter((J)=>this.isCompatibleOwnerContext(J.context,Y)).map((J)=>J.catalogs.get(Q)).filter((J)=>Boolean(J))}isCompatibleOwnerContext(Q,Y){if(Q.ownerKind!==Y.ownerKind)return!1;if(Y.assessmentId&&Q.assessmentId!==Y.assessmentId)return!1;if(Y.sectionId&&Q.sectionId!==Y.sectionId)return!1;if(Y.canonicalItemId&&Q.canonicalItemId!==Y.canonicalItemId)return!1;if(Y.itemId&&Q.itemId!==Y.itemId)return!1;if(Y.passageId&&Q.passageId!==Y.passageId)return!1;if(Y.modelId&&Q.modelId!==Y.modelId)return!1;return!0}ownerScopedCatalogEntries(Q){let Y=[],J=this.scopedCatalogs.get(this.getOwnerKey(Q));if(J)Y.push(...J.catalogs.entries());for(let G of this.scopedCatalogs.values()){if(G===J)continue;if(!this.isCompatibleOwnerContext(G.context,Q))continue;Y.push(...G.catalogs.entries())}return Y}createOwnerSnapshot(Q){let Y=[],J=this.ownerScopedCatalogEntries(Q);if(Q.ownerKind==="global")J.push(...this.assessmentCatalogs.entries());for(let[G,X]of J)for(let j of X.cards)try{Y.push(Object.freeze({catalogId:G,card:n1(j)}))}catch(Z){let q=`${this.getOwnerKey(Q)}\x00${G}`;if(!this.reportedSnapshotProblems.has(q))this.reportedSnapshotProblems.add(q),console.warn(`[AccessibilityCatalogResolver] Catalog "${G}" contains a card that cannot be exposed in an owner snapshot; that card was ignored.`,Z)}return Object.freeze({cards:Object.freeze(Y)})}catalogChangeAffectsOwner(Q,Y){if(!Q.context)return!1;if(this.isCompatibleOwnerContext(Q.context,Y))return!0;if(Y.ownerKind==="itemModel"&&Y.modelId&&Q.context.ownerKind==="itemModel"&&!Q.context.modelId)return this.isCompatibleOwnerContext({...Q.context,modelId:Y.modelId},Y);return!1}sanitizeCatalogs(Q){return Q.map((Y)=>({...Y,cards:Y.cards.map((J)=>{if(!X9(J.catalog))j9(J.catalog,"card",Y.identifier);return{...J,content:J.catalog==="spoken"&&J.content!==void 0?i1(J.content):J.content}})}))}findMatchingCard(Q,Y){let{type:J,language:G,useFallback:X=!0,form:j}=Y,Z=[];if(G)Z.push((q)=>q.language===G);if(X)Z.push((q)=>q.language===this.defaultLanguage),Z.push(()=>!0);for(let q of Z){let K=Q.cards.filter((B)=>B.catalog===J&&q(B));if(K.length===0)continue;if(j){let B=K.find((U)=>q9(U)===j);if(B)return B}return K[0]}return null}getAllAlternatives(Q){let Y=[],J=new Set,G=(Z,q)=>{let K=`${Z.catalog}|${Z.language??""}|${q9(Z)}`;if(J.has(K))return;J.add(K),Y.push(this.resolveCard(Q,Z,q))},X=this.itemCatalogs.get(Q);if(X)for(let Z of X.cards)G(Z,"item");let j=this.assessmentCatalogs.get(Q);if(j)for(let Z of j.cards)G(Z,"assessment");for(let[Z,q]of this.scopedCatalogEntries()){if(Z!==Q)continue;for(let K of q.cards)G(K,"item")}return Y}getAllCatalogIds(){let Q=this.scopedCatalogEntries().map(([Y])=>Y);return Array.from(new Set([...this.itemCatalogs.keys(),...this.assessmentCatalogs.keys(),...Q]))}getStatistics(){let Q=new Set,Y=new Set;for(let J of this.assessmentCatalogs.values())for(let G of J.cards)if(Q.add(G.catalog),G.language)Y.add(G.language);for(let J of this.itemCatalogs.values())for(let G of J.cards)if(Q.add(G.catalog),G.language)Y.add(G.language);for(let J of this.scopedCatalogs.values())for(let G of J.catalogs.values())for(let X of G.cards)if(Q.add(X.catalog),X.language)Y.add(X.language);return{totalCatalogs:this.assessmentCatalogs.size+this.itemCatalogs.size+Array.from(this.scopedCatalogs.values()).reduce((J,G)=>J+G.catalogs.size,0),assessmentCatalogs:this.assessmentCatalogs.size,itemCatalogs:this.itemCatalogs.size+Array.from(this.scopedCatalogs.values()).reduce((J,G)=>J+G.catalogs.size,0),availableTypes:Q,availableLanguages:Y}}hasAlternativeType(Q,Y){return this.getAllAlternatives(Q).some((G)=>G.type===Y)}getCatalogsByType(Q){let Y=new Set;for(let[J,G]of this.assessmentCatalogs.entries())if(G.cards.some((X)=>X.catalog===Q))Y.add(J);for(let[J,G]of this.itemCatalogs.entries())if(G.cards.some((X)=>X.catalog===Q))Y.add(J);for(let[J,G]of this.scopedCatalogEntries())if(G.cards.some((X)=>X.catalog===Q))Y.add(J);return Array.from(Y)}reset(){this.assessmentCatalogs.clear(),this.itemCatalogs.clear(),this.scopedCatalogs.clear(),this.sanitizedSpokenCache.clear(),this.reportedSnapshotProblems.clear()}destroy(){this.reset()}}class o1{elementStates=new Map;listeners=new Set;onStateChange=null;getGlobalElementId(Q,Y,J,G){return`${Q}:${Y}:${J}:${G}`}parseGlobalElementId(Q){let Y=Q.split(":");if(Y.length!==4)return null;return{assessmentId:Y[0],sectionId:Y[1],itemId:Y[2],elementId:Y[3]}}setState(Q,Y,J){let G=this.elementStates.get(Q);if(!G)G=new Map,this.elementStates.set(Q,G);G.set(Y,J),this._notifyListeners(),this._notifyStateChange()}getState(Q,Y){return this.elementStates.get(Q)?.get(Y)}getElementState(Q){let Y=this.elementStates.get(Q);if(!Y)return{};return Object.fromEntries(Y.entries())}getAllState(){let Q={};for(let[Y,J]of this.elementStates.entries())Q[Y]=Object.fromEntries(J.entries());return Q}subscribe(Q){return this.listeners.add(Q),()=>this.listeners.delete(Q)}_notifyListeners(){for(let Q of this.listeners)Q(this.elementStates)}setOnStateChange(Q){this.onStateChange=Q}_notifyStateChange(){if(this.onStateChange)this.onStateChange(this.getAllState())}loadState(Q){this.elementStates.clear();for(let[Y,J]of Object.entries(Q)){let G=new Map(Object.entries(J));this.elementStates.set(Y,G)}this._notifyListeners()}clearElement(Q){this.elementStates.delete(Q),this._notifyListeners(),this._notifyStateChange()}clearTool(Q){for(let Y of this.elementStates.values())Y.delete(Q);this._notifyListeners(),this._notifyStateChange()}clearSection(Q,Y){let J=`${Q}:${Y}:`,G=[];for(let X of this.elementStates.keys())if(X.startsWith(J))G.push(X);for(let X of G)this.elementStates.delete(X);this._notifyListeners(),this._notifyStateChange()}clearAll(){this.elementStates.clear(),this._notifyListeners(),this._notifyStateChange()}}class h7{listeners=new Set;subscribeFrameworkErrors(Q){this.listeners.add(Q);let Y=!0;return()=>{if(!Y)return;Y=!1,this.listeners.delete(Q)}}reportFrameworkError(Q){let Y=Array.from(this.listeners);for(let J of Y)try{J(Q)}catch(G){console.warn("[FrameworkErrorBus] listener failed:",G)}}dispose(){this.listeners.clear()}getListenerCount(){return this.listeners.size}}class a1{serialize(Q,Y){return{startContainer:this.getNodePath(Q.startContainer,Y),startOffset:Q.startOffset,endContainer:this.getNodePath(Q.endContainer,Y),endOffset:Q.endOffset,text:Q.toString()}}deserialize(Q,Y){let J=this.findNodeByPath(Q.startContainer,Y),G=this.findNodeByPath(Q.endContainer,Y);if(!J||!G)return null;try{let X=new Range;if(X.setStart(J,Q.startOffset),X.setEnd(G,Q.endOffset),X.toString()===Q.text)return X;return null}catch(X){return console.warn("Failed to deserialize range:",X),null}}getNodePath(Q,Y){if(Q===Y)return"";if(Q.nodeType===Node.TEXT_NODE){let J=Q.parentElement;if(!J)throw Error("Text node has no parent");let X=Array.from(J.childNodes).filter((Z)=>Z.nodeType===Node.TEXT_NODE).indexOf(Q);return`${this.getElementPath(J,Y)}::text[${X}]`}if(Q.nodeType===Node.ELEMENT_NODE)return this.getElementPath(Q,Y);throw Error(`Unsupported node type: ${Q.nodeType}`)}getElementPath(Q,Y){if(Q===Y)return"";let J=[],G=Q;while(G&&G!==Y){if(G.id){J.unshift(`#${G.id}`);break}let X=G.parentElement;if(!X)break;let j=Array.from(X.children).filter((K)=>K.tagName===G.tagName),Z=j.indexOf(G),q=j.length>1?`${G.tagName.toLowerCase()}:nth-of-type(${Z+1})`:G.tagName.toLowerCase();J.unshift(q),G=X}return J.join(" > ")}findNodeByPath(Q,Y){if(Q==="")return Y;if(Q.includes("::text[")){let[J,G]=Q.split("::text["),X=Number.parseInt(G.replace("]",""),10),j=J?Y.querySelector(J):Y;if(!j)return null;return Array.from(j.childNodes).filter((q)=>q.nodeType===Node.TEXT_NODE)[X]||null}try{return Y.querySelector(Q)}catch(J){return console.warn("Invalid selector path:",Q,J),null}}serializeMany(Q,Y){return Q.map((J)=>this.serialize(J,Y))}deserializeMany(Q,Y){return Q.map((J)=>this.deserialize(J,Y))}}var m;(function(Q){Q.TTS_WORD="tts-word",Q.TTS_SENTENCE="tts-sentence",Q.ANNOTATION="annotation"})(m||(m={}));var D7;(function(Q){Q.YELLOW="yellow",Q.GREEN="green",Q.BLUE="blue",Q.PINK="pink",Q.ORANGE="orange",Q.UNDERLINE="underline"})(D7||(D7={}));class m7{config;ttsWordHighlight=null;ttsSentenceHighlight=null;ttsWordElementHighlights=new Set;ttsSentenceElementHighlights=new Set;annotations=new Map;colorHighlights=new Map;nextAnnotationId=1;supported=!1;rangeSerializer;themeObserver=null;explicitTTSColorOverride=null;constructor(Q={}){if(this.config=Q,this.rangeSerializer=new a1,typeof CSS>"u"||!("highlights"in CSS)){console.warn("CSS Custom Highlight API not supported (SSR or unsupported browser)");return}this.supported=!0,this.initializeHighlights(),this.registerStyles(),this.applyAdaptiveTTSStyle(),this.setupThemeObservation()}setupThemeObservation(){if(typeof document>"u")return;if(typeof MutationObserver>"u")return;let Q=()=>this.applyAdaptiveTTSStyle();this.themeObserver=new MutationObserver(Q),this.themeObserver.observe(document.documentElement,{attributes:!0,attributeFilter:["style","data-theme","data-color-scheme","class"]});for(let Y of document.querySelectorAll("pie-theme"))this.themeObserver.observe(Y,{attributes:!0,attributeFilter:["theme","scheme","provider","variables","style","data-theme","data-color-scheme"]})}parseColor(Q){if(!Q)return null;let Y=Q.trim();if(!Y)return null;let J=/^#([a-f\d]{3}|[a-f\d]{6})$/i.exec(Y);if(J){let X=J[1];if(X.length===3)return[parseInt(X[0]+X[0],16),parseInt(X[1]+X[1],16),parseInt(X[2]+X[2],16)];return[parseInt(X.slice(0,2),16),parseInt(X.slice(2,4),16),parseInt(X.slice(4,6),16)]}let G=/^rgba?\((.+)\)$/i.exec(Y);if(G){let j=G[1].replace(/\//g,",").split(/[,\s]+/).map((B)=>B.trim()).filter(Boolean),Z=Number(j[0]),q=Number(j[1]),K=Number(j[2]);if(Number.isFinite(Z)&&Number.isFinite(q)&&Number.isFinite(K))return[Z,q,K]}if(typeof document<"u"){let X=document.createElement("span");if(X.style.color=Y,typeof X.style.color==="string"&&X.style.color){document.body?.appendChild(X);let j=typeof getComputedStyle==="function"?getComputedStyle(X).color:"";X.remove();let Z=j.trim();if(Z&&Z!==Y)return this.parseColor(j)}}return null}relativeLuminance([Q,Y,J]){let G=(q)=>{let K=q/255;return K<=0.03928?K/12.92:((K+0.055)/1.055)**2.4},X=G(Q),j=G(Y),Z=G(J);return 0.2126*X+0.7152*j+0.0722*Z}contrastRatio(Q,Y){let J=this.relativeLuminance(Q),G=this.relativeLuminance(Y),X=Math.max(J,G),j=Math.min(J,G);return(X+0.05)/(j+0.05)}blend(Q,Y,J){return[Math.round(Q[0]*J+Y[0]*(1-J)),Math.round(Q[1]*J+Y[1]*(1-J)),Math.round(Q[2]*J+Y[2]*(1-J))]}resolveAdaptiveTTSStyle(Q){let Y=[255,235,59],J=[17,24,39],G=[255,255,255],X=Q||(typeof document<"u"?document.documentElement:null),j=X&&typeof getComputedStyle==="function"?getComputedStyle(X):null,Z=this.parseColor(j?.getPropertyValue("--pie-background")||j?.backgroundColor)||G,q=this.parseColor(j?.getPropertyValue("--pie-text"))||J,K=this.explicitTTSColorOverride?this.parseColor(this.explicitTTSColorOverride.color)||Y:this.parseColor(j?.getPropertyValue("--pie-missing"))||Y,B=this.explicitTTSColorOverride?[Math.max(0.3,Math.min(0.95,this.explicitTTSColorOverride.opacity))]:[0.8,0.72,0.68,0.62,0.56,0.5],U=B[B.length-1],H=-1/0;for(let l of B){let Z7=this.blend(K,Z,l),j7=this.contrastRatio(Z7,Z),L7=this.contrastRatio(Z7,q),q7=j7*1.2+L7*0.8;if(j7>=1.25&&L7>=2.4){U=l;break}if(q7>H)H=q7,U=l}let _=Math.max(0.24,Math.min(0.85,U*0.55)),A=Math.max(0.55,Math.min(0.95,U+0.2)),M=Math.max(0.22,Math.min(0.6,U*0.45)),O=q,L=this.blend(O,Z,A),F=this.contrastRatio(L,Z),$=this.relativeLuminance(Z)>0.45?[0,0,0]:[255,255,255],b=F>=1.35?O:$,v=`rgba(${K[0]}, ${K[1]}, ${K[2]}, ${U})`,k=`rgba(${K[0]}, ${K[1]}, ${K[2]}, ${_})`,p=`rgba(${b[0]}, ${b[1]}, ${b[2]}, ${A})`,w=`rgba(${b[0]}, ${b[1]}, ${b[2]}, ${M})`;return{wordHighlight:v,sentenceHighlight:k,wordUnderline:p,wordShadow:w}}applyAdaptiveTTSStyle(Q){if(typeof document>"u")return;let Y=this.resolveAdaptiveTTSStyle(Q);document.documentElement.style.setProperty("--pie-tts-word-highlight",Y.wordHighlight),document.documentElement.style.setProperty("--pie-tts-sentence-highlight",Y.sentenceHighlight),document.documentElement.style.setProperty("--pie-tts-line-highlight",Y.sentenceHighlight),document.documentElement.style.setProperty("--pie-tts-word-underline",Y.wordUnderline),document.documentElement.style.setProperty("--pie-tts-word-shadow",Y.wordShadow)}initializeHighlights(){if(!this.supported)return;this.ttsWordHighlight=new Highlight,this.ttsSentenceHighlight=new Highlight,CSS.highlights.set("tts-word",this.ttsWordHighlight),CSS.highlights.set("tts-sentence",this.ttsSentenceHighlight);for(let Q of Object.values(D7)){let Y=new Highlight;this.colorHighlights.set(Q,Y),CSS.highlights.set(`annotation-${Q}`,Y)}}registerStyles(){if(!this.supported)return;if(typeof document>"u")return;if(document.getElementById("pie-highlight-styles"))return;let Q=document.createElement("style");Q.id="pie-highlight-styles",Q.textContent=`
6
6
  /* TTS highlights - temporary */
7
7
  ::highlight(tts-word) {
8
8
  background-color: var(--pie-tts-word-highlight, color-mix(in srgb, var(--pie-missing, #ffeb3b) 68%, transparent));
@@ -212,7 +212,7 @@ ${J}`)}function G7(Q,Y={}){let J=u1(Y.strictness),G=Y.source??"tools",X=o0(Y.too
212
212
  text-shadow: none;
213
213
  }
214
214
  }
215
- `,document.head.appendChild(Q)}highlightTTSWord(Q,Y,J){if(!this.ttsWordHighlight)return;this.applyAdaptiveTTSStyle(Q.parentElement),this.clearTTSWord();let G=document.createRange();G.setStart(Q,Y),G.setEnd(Q,J),this.ttsWordHighlight.add(G)}highlightTTSWordElement(Q){if(!this.ttsWordHighlight)return;this.applyAdaptiveTTSStyle(Q),this.clearTTSWord(),Q.setAttribute("data-pie-tts-word-element","true"),this.ttsWordElementHighlights.add(Q)}highlightTTSSentence(Q){if(!this.ttsSentenceHighlight)return;let Y=Q[0]?.startContainer,J=Y?.nodeType===Node.ELEMENT_NODE?Y:Y?.parentElement;this.applyAdaptiveTTSStyle(J),this.clearTTSSentence();for(let G of Q)this.ttsSentenceHighlight.add(G);this.highlightTTSElementFallbacks(Q)}highlightTTSSentenceElements(Q){if(!this.ttsSentenceHighlight)return;this.applyAdaptiveTTSStyle(Q[0]||null),this.clearTTSSentence();for(let Y of Q)Y.setAttribute("data-pie-tts-sentence-element","true"),this.ttsSentenceElementHighlights.add(Y)}static SENTENCE_FALLBACK_SELECTOR="math, mjx-container, svg, img, canvas, [role='img']";static WORD_FALLBACK_SELECTOR="svg, img, canvas, [role='img']";highlightTTSElementFallbacks(Q){if(typeof Element>"u")return;this.highlightElementFallbacks(Q,"data-pie-tts-sentence-element",this.ttsSentenceElementHighlights,h7.SENTENCE_FALLBACK_SELECTOR)}highlightTTSWordElementFallbacks(Q){if(typeof Element>"u")return;this.highlightElementFallbacks(Q,"data-pie-tts-word-element",this.ttsWordElementHighlights,h7.WORD_FALLBACK_SELECTOR)}highlightElementFallbacks(Q,Y,J,G){for(let X of Q){let j=X.commonAncestorContainer.nodeType===Node.ELEMENT_NODE?X.commonAncestorContainer:X.commonAncestorContainer.parentElement;if(!j)continue;let Z=[],q=X.startContainer.nodeType===Node.ELEMENT_NODE?X.startContainer:X.startContainer.parentElement,K=X.endContainer.nodeType===Node.ELEMENT_NODE?X.endContainer:X.endContainer.parentElement;for(let B of[q,K]){let U=B;while(U){if(U.matches?.(G))Z.push(U);U=U.parentElement}}if(j.matches?.(G))Z.push(j);Z.push(...Array.from(j.querySelectorAll(G)));for(let B of new Set(Z)){try{if(!X.intersectsNode(B)&&!B.contains(q)&&!B.contains(K))continue}catch{continue}B.setAttribute(Y,"true"),J.add(B)}}}clearTTSWord(){if(!this.ttsWordHighlight)return;this.ttsWordHighlight.clear();for(let Q of this.ttsWordElementHighlights)Q.removeAttribute("data-pie-tts-word-element");this.ttsWordElementHighlights.clear()}clearTTSSentence(){if(!this.ttsSentenceHighlight)return;this.ttsSentenceHighlight.clear();for(let Q of this.ttsSentenceElementHighlights)Q.removeAttribute("data-pie-tts-sentence-element");this.ttsSentenceElementHighlights.clear()}clearTTS(){this.clearTTSWord(),this.clearTTSSentence()}addAnnotation(Q,Y=D7.YELLOW){let J=`annotation-${this.nextAnnotationId++}`,G=Q.cloneRange(),X={id:J,range:G,type:m.ANNOTATION,color:Y,timestamp:Date.now()};this.annotations.set(J,X);let j=this.colorHighlights.get(Y);if(j)j.add(G);return J}removeAnnotation(Q){let Y=this.annotations.get(Q);if(!Y){console.warn(`[HighlightCoordinator] Annotation ${Q} not found`);return}console.log(`[HighlightCoordinator] Removing annotation ${Q} (color: ${Y.color})`);let J=this.colorHighlights.get(Y.color);if(J){let G=J.delete(Y.range);console.log("[HighlightCoordinator] Highlight.delete() returned:",G)}this.annotations.delete(Q),console.log(`[HighlightCoordinator] Annotation ${Q} removed from map. Remaining:`,this.annotations.size)}clearAnnotations(){for(let Q of this.colorHighlights.values())Q.clear();this.annotations.clear()}getAnnotations(){return Array.from(this.annotations.values())}getAnnotation(Q){return this.annotations.get(Q)??null}changeAnnotationColor(Q,Y){let J=this.annotations.get(Q);if(!J)return;let G=J.color;if(G===Y)return;let X=this.colorHighlights.get(G);if(X)X.delete(J.range);J.color=Y;let j=this.colorHighlights.get(Y);if(j)j.add(J.range)}exportAnnotations(Q=document.body){return this.getAnnotations().map((Y)=>({...this.rangeSerializer.serialize(Y.range,Q),id:Y.id,color:Y.color,timestamp:Y.timestamp}))}importAnnotations(Q,Y=document.body){let J=0;for(let G of Q){let X=this.rangeSerializer.deserialize(G,Y);if(X)this.addAnnotation(X,G.color),J++}return J}highlightRange(Q,Y,J=D7.YELLOW){if(!this.supported)return;switch(Y){case m.TTS_WORD:case m.TTS_SENTENCE:{let G=Y===m.TTS_WORD?this.ttsWordHighlight:this.ttsSentenceHighlight;if(G){if(G.clear(),G.add(Q),Y===m.TTS_WORD){for(let X of this.ttsWordElementHighlights)X.removeAttribute("data-pie-tts-word-element");this.ttsWordElementHighlights.clear(),this.highlightTTSWordElementFallbacks([Q])}}break}case m.ANNOTATION:this.addAnnotation(Q,J);break}}clearHighlights(Q){if(!this.supported)return;switch(Q){case m.TTS_WORD:this.clearTTSWord();break;case m.TTS_SENTENCE:this.clearTTSSentence();break;case m.ANNOTATION:this.clearAnnotations();break}}clearAll(){if(!this.supported)return;this.clearTTS(),this.clearAnnotations()}isSupported(){return this.supported}updateTTSHighlightStyle(Q,Y){if(!this.supported)return;if(typeof document>"u")return;if(!document.getElementById("pie-highlight-styles"))return;let X=((j)=>{let Z=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(j);return Z?{r:parseInt(Z[1],16),g:parseInt(Z[2],16),b:parseInt(Z[3],16)}:null})(Q);if(!X)return;this.explicitTTSColorOverride={color:`rgb(${X.r}, ${X.g}, ${X.b})`,opacity:Math.max(0.2,Math.min(0.95,Y))},this.applyAdaptiveTTSStyle()}destroy(){if(!this.supported)return;if(this.clearTTS(),this.clearAnnotations(),typeof document<"u"){let Q=document.getElementById("pie-highlight-styles");if(Q)Q.remove()}this.themeObserver?.disconnect(),this.themeObserver=null}}function K9(Q){return(...Y)=>{console.debug(`[${Q}]`,...Y)}}var o=K9("ToolCoordinator"),X7;(function(Q){Q[Q.BASE=0]="BASE",Q[Q.TOOL=1000]="TOOL",Q[Q.MODAL=2000]="MODAL",Q[Q.CONTROL=3000]="CONTROL",Q[Q.HIGHLIGHT=4000]="HIGHLIGHT"})(X7||(X7={}));class t1{config;tools=new Map;layerCounters=new Map;listeners=new Set;visibilityState=new Map;constructor(Q={}){this.config=Q,this.layerCounters.set(X7.BASE,0),this.layerCounters.set(X7.TOOL,0),this.layerCounters.set(X7.MODAL,0),this.layerCounters.set(X7.CONTROL,0),this.layerCounters.set(X7.HIGHLIGHT,0)}subscribe(Q){return this.listeners.add(Q),()=>{this.listeners.delete(Q)}}notifyListeners(){this.listeners.forEach((Q)=>Q())}registerTool(Q,Y,J,G=X7.MODAL){if(o("registerTool called:",{id:Q,name:Y,hasElement:!!J,layer:G}),this.tools.has(Q)){o(`Tool ${Q} is already registered`);return}let X=this.visibilityState.get(Q)??!1;if(!J){this.tools.set(Q,{id:Q,name:Y,element:null,layer:G,isVisible:X,baseZIndex:G}),o("Tool registered without element:",Q);return}let j=G+this.getNextLayerOffset(G);J.style.zIndex=String(j),J.style.display=X?"":"none";let Z=()=>this.bringToFront(J);if(J.addEventListener("mousedown",Z),this.tools.set(Q,{id:Q,name:Y,element:J,layer:G,isVisible:X,baseZIndex:j,mouseDownHandler:Z}),X)this.bringToFront(J);o("Tool registered with element:",Q)}unregisterTool(Q){let Y=this.tools.get(Q);if(!Y)return;if(Y.element&&Y.mouseDownHandler)Y.element.removeEventListener("mousedown",Y.mouseDownHandler);this.tools.delete(Q)}releaseTool(Q){this.unregisterTool(Q),this.visibilityState.delete(Q)}showTool(Q){let Y=this.tools.get(Q);if(!Y){o(`Tool ${Q} not found`);return}if(Y.element)Y.element.style.display="",this.bringToFront(Y.element);Y.isVisible=!0,this.visibilityState.set(Q,!0),this.notifyListeners()}hideTool(Q){let Y=this.tools.get(Q);if(!Y){o(`Tool ${Q} not found`);return}if(Y.element)Y.element.style.display="none";Y.isVisible=!1,this.visibilityState.set(Q,!1),this.notifyListeners()}toggleTool(Q){o("toggleTool called for:",Q);let Y=this.tools.get(Q);if(!Y){o(`Tool ${Q} not found. Registered tools:`,Array.from(this.tools.keys()));return}if(o("Tool found, current visibility:",Y.isVisible),Y.isVisible)this.hideTool(Q);else this.showTool(Q)}isToolVisible(Q){let Y=this.tools.get(Q);if(Y)return Y.isVisible;return this.visibilityState.get(Q)??!1}bringToFront(Q){let Y=Array.from(this.tools.values()).find((X)=>X.element===Q);if(!Y)return;let J=this.getMaxZIndexInLayer(Y.layer),G=Math.max(J+1,Y.layer+1);Q.style.zIndex=String(G),Y.baseZIndex=G}getRegisteredTools(){return Array.from(this.tools.keys())}getToolElement(Q){return this.tools.get(Q)?.element??null}getNextLayerOffset(Q){let Y=this.layerCounters.get(Q)??0;return this.layerCounters.set(Q,Y+1),Y}getMaxZIndexInLayer(Q){let Y=Q;for(let J of this.tools.values())if(J.layer===Q)Y=Math.max(Y,J.baseZIndex);return Y}resetZIndices(){for(let Q of this.tools.values())if(Q.element)Q.element.style.zIndex=String(Q.baseZIndex)}updateToolElement(Q,Y){let J=this.tools.get(Q);if(!J){o(`Tool ${Q} not found`);return}if(J.element&&J.mouseDownHandler)J.element.removeEventListener("mousedown",J.mouseDownHandler);let G=()=>this.bringToFront(Y);if(Y.addEventListener("mousedown",G),J.element=Y,J.mouseDownHandler=G,Y.style.zIndex=String(J.baseZIndex),J.isVisible)Y.style.display="";else Y.style.display="none"}hideAllTools(){for(let Q of this.tools.keys())this.hideTool(Q);this.notifyListeners()}getToolState(Q){let Y=this.tools.get(Q);if(!Y)return;return{id:Y.id,name:Y.name,isVisible:Y.isVisible,element:Y.element??null,layer:Y.layer}}getVisibleTools(){return Array.from(this.tools.values()).filter((Q)=>Q.isVisible).map((Q)=>({id:Q.id,name:Q.name,isVisible:Q.isVisible,element:Q.element??null,layer:Q.layer}))}}var j3=/^[a-z][a-z0-9+.-]*:/i,q3=new Set(["http:","https:","data:","blob:"]);function K3(Q){if(typeof Q!=="string")return!1;let Y=Q.trim();if(!Y)return!1;if(Y.startsWith("//")||!j3.test(Y))return!0;let J=Y.slice(0,Y.indexOf(":")+1).toLowerCase();return q3.has(J)}function W9(Q){if(!Array.isArray(Q))return[];let Y=[];for(let J of Q){if(!J||typeof J!=="object")continue;let G=J;if(!K3(G.src))continue;let X={src:G.src.trim()};if(typeof G.type==="string"&&G.type.trim())X.type=G.type.trim();if(Number.isFinite(G.width))X.width=G.width;if(Number.isFinite(G.height))X.height=G.height;if(Y.some((j)=>j.src===X.src))continue;Y.push(X)}return Y}function U9(Q){if(!Q||typeof Q!=="object")return;let Y=Q,J=Number(Y.startSeconds);if(!Number.isFinite(J)||J<0)return;let G=Number(Y.endSeconds);if(!Number.isFinite(G)||G<=J)return{startSeconds:J};return{startSeconds:J,endSeconds:G}}function B9(Q){if(typeof Q!=="string")return;return Q.trim()||void 0}function D9(Q,Y){if(!Y)return Q;if(Q.includes("#"))return Q;let J=Y.endSeconds!==void 0?`,${Y.endSeconds}`:"";return`${Q}#t=${Y.startSeconds}${J}`}function V9(Q){if(!Q)return null;let Y=Q.payload;if(!Y||typeof Y!=="object")return null;let J=Y.media;if(!J||typeof J!=="object")return console.warn("[spoken-audio] card carries a `payload` with no `media`; recorded speech needs `media.sources`, so this card is ignored and read-aloud falls back to the script or generated speech"),null;if(J.kind!==void 0&&J.kind!=="audio")return console.warn(`[spoken-audio] card's media is kind "${J.kind}", not "audio"; a spoken card carries recorded speech, so this card is ignored`),null;let G=W9(J.sources);if(G.length===0)return console.warn("[spoken-audio] card's `media.sources` yielded no usable URL; read-aloud falls back to the script or generated speech"),null;return{sources:G,fragment:U9(Y.fragment),label:B9(J.label)}}var w7=(Q,Y)=>{let J=Y?.useSentenceSegmenter!==!1;try{if(!J)throw Error("Segmenter disabled by policy");let q=globalThis.Intl?.Segmenter;if(typeof q==="function"){let K=new q(Y?.locale,{granularity:"sentence"}),B=Array.from(K.segment(Q)).map((U)=>({text:U.segment,offset:U.index})).filter((U)=>U.text.trim().length>0);if(B.length>0)return B}}catch{}let G=/[^.!?]+(?:[.!?]+|$)/g,X=Q.match(G)||[Q],j=[],Z=0;for(let q of X){let K=Q.indexOf(q,Z);if(K===-1)continue;j.push({text:q,offset:K}),Z=K+q.length}return j.length>0?j:[{text:Q,offset:0}]};var H9=5000,_9=2000,F9=(Q)=>String(Q||"").trim().toLowerCase(),W3=()=>{let Q=typeof navigator<"u"?navigator.language||navigator.languages?.[0]:"";return F9(Q||"en-US")},U3=(Q,Y)=>{if(Y)return Q.find((Z)=>Z.voiceURI===Y)||Q.find((Z)=>Z.name===Y)||null;let J=W3(),G=J.split("-")[0]||"en",X=(Z)=>{let q=F9(Z.lang);return q===J||q.startsWith(`${G}-`)},j=[(Z)=>Z.localService&&X(Z),(Z)=>Z.default&&X(Z),(Z)=>X(Z),(Z)=>Z.localService,(Z)=>Z.default];for(let Z of j){let q=Q.find(Z);if(q)return q}return Q[0]||null},B3=(Q)=>!Q.default;class R7{providerId="browser";providerName="Browser Speech Synthesis";version="1.0.0";async initialize(Q){if(typeof window>"u")throw Error("BrowserTTSProvider requires browser environment");if(!("speechSynthesis"in window))throw Error("Browser does not support Speech Synthesis API");return new A9(Q)}supportsFeature(Q){return!0}getCapabilities(){return{supportsPause:!0,supportsResume:!0,supportsWordBoundary:!0,supportsVoiceSelection:!0,supportsRateControl:!0,supportsPitchControl:!0,supportsSSML:!1}}destroy(){}}class A9{utterance=null;config=null;_isPlaying=!1;_isPaused=!1;speakRunId=0;settlePendingVoiceWait=null;settlePendingChunk=null;onPlaybackStart=void 0;constructor(Q){this.config=Q}waitForBrowserVoices(Q,Y){return new Promise((J,G)=>{let X=speechSynthesis,j=typeof X.addEventListener==="function"&&typeof X.removeEventListener==="function",Z=j?null:X.onvoiceschanged,q=!1,K=null,B=null,U=()=>{if(K!==null)clearTimeout(K),K=null;if(j)X.removeEventListener("voiceschanged",A);else if(X.onvoiceschanged===M)X.onvoiceschanged=Z;if(B&&this.settlePendingVoiceWait===B)this.settlePendingVoiceWait=null},H=(O,L)=>{if(q)return;if(q=!0,U(),L)G(L);else J(O)},_=()=>{if(Q!==this.speakRunId){H(!1);return}if(X.getVoices().length>0)H(!0)},A=()=>_(),M=(O)=>{try{Z?.call(X,O)}finally{_()}};if(B=()=>H(!1),this.settlePendingVoiceWait=B,K=setTimeout(()=>H(!1,Error(`Configured browser voice "${Y}" could not be resolved because the browser did not publish its voice inventory within ${_9/1000} seconds.`)),_9),j)X.addEventListener("voiceschanged",A);else X.onvoiceschanged=M;_()})}async resolveBrowserVoice(Q){let Y=typeof this.config?.voice==="string"?this.config.voice.trim():"",J=speechSynthesis.getVoices();if(Y&&J.length===0){if(!await this.waitForBrowserVoices(Q,Y)||Q!==this.speakRunId)return{shouldContinue:!1,voice:null};J=speechSynthesis.getVoices()}if(Q!==this.speakRunId)return{shouldContinue:!1,voice:null};let G=U3(J,Y||void 0);if(Y&&!G)throw Error(`Configured browser voice "${Y}" is unavailable. Select a voice exposed by this browser using its voiceURI or name.`);return{shouldContinue:!0,voice:G}}async speak(Q){if(!this.config)throw Error("TTS not initialized");this.stop();let Y=this.speakRunId,J=await this.resolveBrowserVoice(Y);if(!J.shouldContinue)return;let G=this.splitIntoChunks(Q);for(let X of G){if(Y!==this.speakRunId)break;if(!await this.speakChunk(X.text,X.offset,Y,J.voice))break}}async speakSegments(Q){if(!this.config)throw Error("TTS not initialized");this.stop();let Y=this.speakRunId,J=await this.resolveBrowserVoice(Y);if(!J.shouldContinue)return;for(let G of Q){if(Y!==this.speakRunId)break;let X=this.splitIntoChunks(G.text);for(let Z of X){if(Y!==this.speakRunId)break;if(!await this.speakChunk(Z.text,G.startOffset+Z.offset,Y,J.voice))break}let j=Math.max(0,Number(G.pauseMsAfter||0));if(j>0&&Y===this.speakRunId){if(!await this.waitForPause(j,Y))break}}}async waitForPause(Q,Y){return await new Promise((J)=>setTimeout(J,Q)),Y===this.speakRunId}splitIntoChunks(Q){if(Q.length<=260)return[{text:Q,offset:0}];let J=this.segmentSentences(Q),G=[],X="",j=0;for(let Z of J){let q=Z.text.trim();if(!q)continue;let K=Z.text.search(/\S/),B=Z.offset+(K===-1?0:K);if(!X){X=q,j=B;continue}let U=`${X} ${q}`;if(U.length<=260)X=U;else G.push({text:X,offset:j}),X=q,j=B}if(X)G.push({text:X,offset:j});return G.length?G:[{text:Q,offset:0}]}getHighlightMode(){return(this.config?.providerOptions||{}).highlightMode==="word"?"word":"sentence"}getSegmentationPolicy(){let Q=this.config?.providerOptions||{},Y=Q.segmenter||{},G=Y.mode!=="regexOnly",X=typeof Y.locale==="string"&&Y.locale.trim().length>0?Y.locale:typeof Q.locale==="string"&&Q.locale.trim().length>0?Q.locale:void 0;return{useSentenceSegmenter:G,useWordSegmenter:G,locale:X}}segmentSentences(Q){let Y=this.getSegmentationPolicy();return w7(Q,{locale:Y.locale,useSentenceSegmenter:Y.useSentenceSegmenter})}inferWordLength(Q,Y){let J=Math.max(0,Math.min(Y,Math.max(0,Q.length-1)));return Q.slice(J).match(/^\s*([^\s]+)/)?.[1]?.length||1}async speakChunk(Q,Y,J,G){return new Promise((X,j)=>{if(J!==this.speakRunId){X(!1);return}let Z=new SpeechSynthesisUtterance(Q);if(this.utterance=Z,G&&B3(G))Z.voice=G;if(this.config?.rate)Z.rate=this.config.rate;if(this.config?.pitch)Z.pitch=this.config.pitch;let q=!1,K=!1,B=null,U=null,H=()=>{if(this.utterance===Z)this.utterance=null},_=()=>{if(B!==null)clearTimeout(B),B=null},A=()=>{Z.onstart=null,Z.onend=null,Z.onerror=null,Z.onpause=null,Z.onresume=null,Z.onboundary=null},M=(L,F)=>{if(K)return;if(K=!0,_(),A(),H(),U&&this.settlePendingChunk===U)this.settlePendingChunk=null;if(J===this.speakRunId)this._isPlaying=!1,this._isPaused=!1;if(F)j(F);else X(L)},O=(L)=>Error(L==="ended"?"Browser speech synthesis ended before audio started. The browser speech engine may be unavailable or stuck; try another voice or restart the browser.":`Browser speech synthesis did not start within ${H9/1000} seconds. The browser speech engine may be unavailable or stuck; try another voice or restart the browser.`);U=()=>M(!1),this.settlePendingChunk=U,Z.onstart=()=>{if(J!==this.speakRunId){M(!1);return}q=!0,_(),this._isPlaying=!0,this._isPaused=!1;try{this.onPlaybackStart?.()}catch(L){console.error("Browser TTS playback-start callback failed",L)}},Z.onend=()=>{if(J!==this.speakRunId){M(!1);return}if(!q){M(!1,O("ended"));return}M(!0)},Z.onerror=(L)=>{if(J!==this.speakRunId){M(!1);return}if(L.error==="interrupted"||L.error==="canceled"){M(!1);return}M(!1,Error(`Speech synthesis error: ${L.error}`))},Z.onpause=()=>{if(J!==this.speakRunId)return;this._isPaused=!0},Z.onresume=()=>{if(J!==this.speakRunId)return;this._isPaused=!1},Z.onboundary=(L)=>{if(J!==this.speakRunId)return;if(console.log("[BrowserProvider] Boundary event:",L.name,"charIndex:",L.charIndex,"charLength:",L.charLength),L.name!=="word"||!this.onWordBoundary)return;if(this.getHighlightMode()==="sentence")return;let F=Math.max(0,Math.min(L.charIndex,Math.max(0,Q.length-1))),$=Number(L.charLength||0),b=this.inferWordLength(Q,F),v=Number.isFinite($)&&$>0&&$<=80&&F+$<=Q.length?$:b,k=Q.substring(F,Math.min(Q.length,F+v)).trim(),p=Y+F;console.log("[BrowserProvider] Calling onWordBoundary with word:",k,"at position:",p),this.onWordBoundary(k,p,v)},B=setTimeout(()=>{if(K||q||J!==this.speakRunId)return;M(!1,O("timedOut")),speechSynthesis.cancel()},H9);try{speechSynthesis.speak(Z)}catch(L){M(!1,L instanceof Error?L:Error("Browser speech synthesis failed to queue speech"))}})}pause(){if(this._isPlaying&&!this._isPaused)speechSynthesis.pause()}resume(){if(this._isPlaying&&this._isPaused)speechSynthesis.resume()}stop(){let Q=this.utterance,Y=this._isPlaying||Q!==null;if(this.speakRunId+=1,this.settlePendingVoiceWait?.(),this.settlePendingChunk?.(),Y)speechSynthesis.cancel();this.utterance=null,this._isPlaying=!1,this._isPaused=!1}isPlaying(){return this._isPlaying&&!this._isPaused}isPaused(){return this._isPaused}updateSettings(Q){if(!this.config)this.config={};if(Q.rate!==void 0)this.config.rate=Q.rate;if(Q.pitch!==void 0)this.config.pitch=Q.pitch;if(Q.voice!==void 0)this.config.voice=Q.voice;if(Q.providerOptions!==void 0)this.config.providerOptions={...this.config.providerOptions||{},...Q.providerOptions||{}}}onWordBoundary}var S=(Q)=>Q.trim().replace(/\s+/g," "),Z1=()=>/[\p{L}]+|\d+(?:\.\d+)?|[±√=+\-*/()²³^×÷≤≥≠≈<>|%°'′\u2062]/gu,e1=(Q)=>{if(Q.hidden)return!0;if(Q.tagName?.toLowerCase()==="mjx-assistive-mml")return!0;if(Q.getAttribute("aria-hidden")==="true")return!0;if(Q.hasAttribute("inert"))return!0;let Y=Q.classList;if(Y?.contains("sr-only")||Y?.contains("pie-sr-only")||Y?.contains("visually-hidden"))return!0;if(typeof window<"u"){let J=window.getComputedStyle(Q);if(J.display==="none"||J.visibility==="hidden")return!0;let G=Number.parseFloat(J.width||"0"),X=Number.parseFloat(J.height||"0"),j=Number.isFinite(G)&&Number.isFinite(X)&&G<=1&&X<=1,Z=J.clipPath.includes("inset(50%")||J.clipPath.includes("inset(100%")||J.clip.includes("rect(0px, 0px, 0px, 0px)")||J.clip.includes("rect(0 0 0 0)");if((J.position==="absolute"||J.position==="fixed")&&j&&(J.overflow==="hidden"||Z))return!0;if(J.opacity==="0"&&j)return!0}return!1},j1=(Q,Y)=>{let J=Q.nodeType===1?Q:Q.parentElement;while(J){if(e1(J))return!0;if(Y&&J===Y)break;J=J.parentElement}return!1};var z9=new Set(["computer-read-aloud","all"]),M9=new Set([...z9,"screen-reader"]),N9=new Set,D3=(Q)=>{let Y=Q.getAttribute?.("data-tts-suppress");if(Y===null||Y===void 0)return!1;let J=Y.trim().toLowerCase();if(z9.has(J))return!0;if(M9.has(J))return!1;if(!N9.has(J))N9.add(J),console.warn(`[tts] data-tts-suppress="${Y}" is not one of ${Array.from(M9).join(", ")}; suppressing read-aloud for this content anyway, because a suppression attribute that fails open would leak the answer to items where reading is the construct. Correct the value to silence this.`);return!0},q1=(Q,Y)=>{let J=Q.nodeType===1?Q:Q.parentElement;while(J){if(D3(J))return!0;if(Y&&J===Y)break;J=J.parentElement}return!1},V7=(Q,Y)=>j1(Q,Y)||q1(Q),Q8=(Q,Y)=>{if(typeof document>"u"||typeof document.createTreeWalker!=="function"||typeof NodeFilter>"u"||typeof Q.intersectsNode!=="function")return{text:Q.toString(),filtered:!1};let J=[],G=!1,X=document.createTreeWalker(Y,NodeFilter.SHOW_TEXT),j=X.nextNode();while(j){let Z=j;if(Q.intersectsNode(Z))if(V7(Z,Y))G=!0;else{let q=Z.textContent||"",K=Z===Q.startContainer?Q.startOffset:0,B=Z===Q.endContainer?Q.endOffset:q.length;J.push(q.slice(K,B))}j=X.nextNode()}return{text:J.join(""),filtered:G}},Y8=(Q,Y,J)=>{if(!Q||!Y)return!1;if(/\s/.test(Q)||/\s/.test(Y))return!1;let G=J?.boundarySpacingMode??"segmenterPreferred";if(G==="none")return!1;if(G==="segmenterPreferred")try{let Z=globalThis.Intl?.Segmenter;if(typeof Z==="function"){let q=new Z(J?.locale,{granularity:"word"});if(Array.from(q.segment(`${Q}${Y}`)).filter((U)=>U.isWordLike!==!1&&U.segment.trim().length>0).length>=2)return!0}}catch{}let X=/[A-Za-z0-9]/.test(Q),j=/[A-Za-z0-9]/.test(Y);return X&&j},E7=(Q,Y)=>{let J=new Map;if(typeof document>"u"||typeof document.createTreeWalker!=="function"||typeof NodeFilter>"u")return{text:"",map:J};let G=[],X=0,j=!0,Z=!1,q=null,K=null,B=document.createTreeWalker(Q,NodeFilter.SHOW_TEXT),U=B.nextNode();while(U){let _=U;if(_.parentElement&&!V7(_,Q)){let M=_.textContent||"",O=M.match(/\S/),L=O?O[0]:null;if(!j&&!Z&&Y8(K,L,Y)){if(G.push(" "),q)J.set(X,q);X++,Z=!0}for(let F=0;F<M.length;F++){let $=M[F],b=/\s/.test($);if(j){if(!b)j=!1,G.push($),J.set(X,{node:_,offset:F}),q={node:_,offset:F},X++,Z=!1,K=$}else if(b){if(!Z)G.push(" "),J.set(X,{node:_,offset:F}),q={node:_,offset:F},X++;Z=!0}else G.push($),J.set(X,{node:_,offset:F}),q={node:_,offset:F},X++,Z=!1,K=$}}U=B.nextNode()}let H=G.join("").trimEnd();while(J.has(H.length))J.delete(H.length);return{text:H,map:J}};var V3=new Set(["speak","p","s","emphasis","prosody","say-as","voice","lang"]),O9=new Set(["audio","phoneme"]),L9=(Q)=>Q.replace(/&quot;/g,'"').replace(/&apos;/g,"'").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&nbsp;/g," ").replace(/&#160;/g," ").replace(/&amp;/g,"&"),K1=(Q,Y,J)=>{for(let G=0;G<Y.length;G++)Q.push({char:Y[G],rawOffset:J===null?null:J+G})},H3=(Q,Y,J)=>{let G=Y.slice(J).match(/^&(quot|apos|lt|gt|nbsp|amp|#160);/i);if(!G)return 0;return K1(Q,L9(G[0]),J),G[0].length},P9=(Q)=>{Q.push({char:" ",rawOffset:null})},_3=(Q)=>{let Y=new Map,J=[],G=!0;for(let X of Q){if(/\s/.test(X.char)){if(!G&&J.length>0){if(J.push(" "),X.rawOffset!==null)Y.set(X.rawOffset,J.length-1)}G=!0;continue}if(J.push(X.char),X.rawOffset!==null)Y.set(X.rawOffset,J.length-1);G=!1}while(J.length>0&&J[J.length-1]===" ")J.pop();for(let[X,j]of Y)if(j>=J.length)Y.delete(X);return{text:J.join(""),rawToSpokenOffsetMap:Y}},F3=(Q)=>{return Q.match(/^<\/?\s*([A-Za-z0-9:-]+)/)?.[1]?.toLowerCase()||""},A3=(Q,Y)=>{let J=new RegExp(`${Y}\\s*=\\s*("([^"]*)"|'([^']*)')`,"i"),G=Q.match(J);return L9(G?.[2]??G?.[3]??"")||null},W1=(Q)=>{let Y=[],J=!1,G=!1,X=0;while(X<Q.length){let Z=Q[X];if(Z!=="<"){if(Z==="&"){let _=H3(Y,Q,X);if(_>0){X+=_;continue}}K1(Y,Z,X),X++;continue}let q=Q.indexOf(">",X+1);if(q<0){K1(Y,Z,X),X++;continue}G=!0;let K=Q.slice(X,q+1),B=F3(K),U=/^<\s*\//.test(K),H=/\/\s*>$/.test(K);if(!U&&B==="sub"){let _=A3(K,"alias");if(!_){J=!0,X=q+1;continue}K1(Y,_,null);let A=Q.toLowerCase().indexOf("</sub>",q+1);X=A>=0?A+6:q+1;continue}if(!U&&B==="break"){P9(Y),X=q+1;continue}if(!U&&O9.has(B)){if(J=!0,H){X=q+1;continue}}if(B&&!V3.has(B)&&!O9.has(B)&&B!=="break"&&B!=="sub")J=!0;if(!U&&(B==="p"||B==="s"))P9(Y);X=q+1}let j=_3(Y);return{spokenText:S(j.text),rawToSpokenOffsetMap:j.rawToSpokenOffsetMap,unsupportedSemantic:J,hasMarkup:G}};var M3=Z1(),b9=new Map([["zero","0"],["one","1"],["two","2"],["three","3"],["four","4"],["five","5"],["six","6"],["seven","7"],["eight","8"],["nine","9"],["ten","10"]]),N3=[{phrase:["plus","or","minus"],visible:"±",score:8},{phrase:["square","root"],visible:"√",score:8},{phrase:["divided","by"],visible:"/",score:7},{phrase:["all","over"],visible:"/",score:7},{phrase:["equals"],visible:"=",score:7},{phrase:["equal"],visible:"=",score:7},{phrase:["times"],visible:"⁢",score:7},{phrase:["multiplied","by"],visible:"⁢",score:7},{phrase:["over"],visible:"/",score:6},{phrase:["squared"],visible:"²",score:6},{phrase:["squared"],visible:"2",score:4},{phrase:["negative"],visible:"-",score:5},{phrase:["minus"],visible:"-",score:5},{phrase:["plus"],visible:"+",score:5}],J8=(Q)=>{let Y=[];for(let J of Q.matchAll(M3)){let G=J[0],X=J.index??0;Y.push({text:G,normalized:G.toLowerCase(),start:X,end:X+G.length})}return Y},G8=(Q)=>b9.get(Q.normalized)||Q.normalized,z3=(Q,Y)=>{let J=[];for(let G=0;G<Q.length;G++){for(let X=0;X<Y.length;X++){let j=G8(Q[G]),Z=G8(Y[X]);if(j===Z)J.push({spokenStartToken:G,spokenEndToken:G+1,visibleToken:X,score:10})}for(let X of N3){let j=Q.slice(G,G+X.phrase.length);if(j.length!==X.phrase.length)continue;if(!j.every((Z,q)=>Z.normalized===X.phrase[q]))continue;for(let Z=0;Z<Y.length;Z++){if(Y[Z].normalized!==X.visible)continue;J.push({spokenStartToken:G,spokenEndToken:G+X.phrase.length,visibleToken:Z,score:X.score})}}}return J},O3=(Q,Y)=>{let J=z3(Q,Y).sort((K,B)=>Q[K.spokenStartToken].start-Q[B.spokenStartToken].start||Y[K.visibleToken].start-Y[B.visibleToken].start),G=Array(J.length).fill(0),X=Array(J.length).fill(-1);for(let K=0;K<J.length;K++){let B=J[K];G[K]=B.score;for(let U=0;U<K;U++){let H=J[U];if(H.spokenEndToken<=B.spokenStartToken&&H.visibleToken<B.visibleToken){let _=B.spokenStartToken-H.spokenEndToken,A=B.visibleToken-H.visibleToken-1,M=Math.max(0,Math.abs(_-A)-2),O=G[U]+B.score-M;if(O>G[K])G[K]=O,X[K]=U}}}let j=-1;for(let K=0;K<G.length;K++)if(j<0||G[K]>G[j])j=K;if(j<0)return[];let Z=[],q=j;while(q>=0)Z.unshift(J[q]),q=X[q];return Z.map((K)=>{let B=Q[K.spokenStartToken],U=Q[K.spokenEndToken-1],H=Y[K.visibleToken];return{spokenStart:B.start,spokenEnd:U.end,visibleStart:H.start,visibleEnd:H.end,score:K.score}})},P3=(Q,Y,J)=>{if(Q.length===0)return 0;let G=Q.length/Math.max(1,Math.min(Y.length,J.length)),X=Q.reduce((j,Z)=>j+Z.score,0)/Q.length/10;return Math.min(1,G*X)},U1=(Q)=>{let Y=W1(Q.speechText),J=S(Q.visibleText),G=Y.spokenText,X=J8(G),j=J8(J),Z=Y.unsupportedSemantic?[]:O3(X,j),q=P3(Z,X,j),K=G===J&&G.length>0,B=Z.length===1&&Z[0].score===10&&X.length<=2&&j.length<=2,U=Y.unsupportedSemantic?"region-fallback":K?"exact-word":Z.length>=2||B?q>=0.12?"anchor-span":"region-fallback":"region-fallback",H=Y.unsupportedSemantic?"unsupported":Y.hasMarkup?"raw-ssml":"plain-spoken-text";return{speechText:Q.speechText,spokenText:G,visibleText:J,playbackMode:U,boundaryOffsetMode:H,anchors:Z,confidence:q,spokenTokens:X,visibleTokens:j,rawToSpokenOffsetMap:Y.rawToSpokenOffsetMap}},X8=(Q,Y)=>Q.find((J)=>J.start<=Y&&Y<J.end)||null,S9=(Q)=>{if(!Q)return null;if(/^<[^>]+>$/.test(Q.trim()))return null;let Y=J8(Q)[0];if(!Y)return null;return b9.get(Y.normalized)||Y.normalized},$9=(Q,Y,J)=>{let G=S9(J);if(!Y||!G)return!1;let X=X8(Q.spokenTokens,Y.start);if(!X)return!1;return G8(X)===G},w9=(Q,Y)=>{let J=Q.rawToSpokenOffsetMap.get(Y);if(J!==void 0)return J;for(let G=Y;G<Q.speechText.length;G++){let X=Q.rawToSpokenOffsetMap.get(G);if(X!==void 0)return X;if(Q.speechText[G]===">")break}return null},R9=(Q,Y,J)=>{let G=w9(Q,Y);if(G===null)return null;let X=w9(Q,Math.max(Y,Y+J-1)),j=X8(Q.spokenTokens,G),Z=X!==null&&X>=G?X-G+1:j?j.end-G:J;return{start:G,length:Math.max(1,Z)}},E9=(Q,Y,J)=>{if(Y<0||Y>=Q.spokenText.length)return null;let G=X8(Q.spokenTokens,Y);if(!G)return null;return{start:Y,length:Math.min(J,G.end-Y)}},T9=(Q,Y,J=1,G)=>{if(Q.boundaryOffsetMode==="unsupported"||!Number.isFinite(Y))return null;let X=Math.max(1,Number.isFinite(J)?J:1);if(G&&/^<[^>]+>$/.test(G.trim()))return null;if(Q.boundaryOffsetMode==="raw-ssml"){let j=R9(Q,Y,X),Z=E9(Q,Y,X);if(G){if($9(Q,j,G))return j;if($9(Q,Z,G))return Z;if(S9(G))return null}return j||Z}return E9(Q,Y,X)||R9(Q,Y,X)},C9=(Q,Y)=>{if(Q.playbackMode==="region-fallback")return null;let J=Q.anchors.find((j)=>j.spokenStart<=Y&&Y<j.spokenEnd);if(J)return{start:J.visibleStart,end:J.visibleEnd};let G=null,X=null;for(let j of Q.anchors){if(j.spokenEnd<=Y){G=j;continue}if(j.spokenStart>Y){X=j;break}}if(G&&X)return{start:Math.min(G.visibleStart,X.visibleStart),end:Math.max(G.visibleEnd,X.visibleEnd)};return null};var L3=new Map([["+",["plus"]],["-",["minus","negative"]],["−",["minus","negative"]],["×",["times","multiplied by"]],["÷",["divided by"]],["=",["equals","equal to"]],["≠",["is not equal to","not equal to"]],["≈",["approximately equals"]],["≤",["less than or equal to"]],["≥",["greater than or equal to"]],["<",["less than"]],[">",["greater than"]],["∠",["angle"]],["△",["triangle"]],["□",["box"]],["○",["circle"]],["°",["degrees","degree"]],["%",["percent"]],["'",["prime"]],["′",["prime"]],["•",["times"]],["·",["times"]],["⁢",["times","multiplied by"]]]),$3=new Map([["⁡","function-application"],["⁢","implicit-multiply"],["⁣","invisible-separator"],["⁤","invisible-plus"]]),y9=new Map([["2",["squared"]],["3",["cubed"]]]),w3=new Map([["msqrt","radical"],["mroot","radical"],["msub","subscript"],["msubsup","subsupscript"],["munder","underscript"],["mover","overscript"],["munderover","underoverscript"],["mmultiscripts","multiscript"],["menclose","enclosure"]]),R3=(Q)=>Q.replace(/\s+/g," ").trim(),H7=(Q)=>(Q.localName||Q.tagName||"").toLowerCase(),E3=(Q)=>Q.nodeType===Node.ELEMENT_NODE,b7=(Q)=>Array.from(Q.childNodes).filter(E3),Z8=(Q)=>R3(Q.textContent||""),e=(Q,Y)=>({type:"element-range",quality:Y,element:Q}),b3=(Q)=>{switch(Q){case"mi":return"identifier";case"mn":return"number";case"mo":return"operator";case"mtext":case"ms":return"text";case"mspace":return"space";default:return"unknown"}},S3=(Q,Y)=>{if(Y==="operator"){if(Q==="−")return"-";return Q}return Q.toLowerCase()},T3=(Q,Y,J)=>{if(J==="fraction")return["over","divided by"];if(J==="superscript")return y9.get(Q)??[];if(Q==="|")return["absolute value"];if(Y==="operator")return L3.get(Q)||[];return[]},_7=(Q)=>{let Y=Q.normalized??S3(Q.text,Q.kind||"unknown");return{id:`math-token-${Q.state.nextId++}`,kind:Q.kind,role:Q.role,text:Q.text,normalized:Y,spokenAliases:T3(Q.text,Q.kind,Q.role),sourceElement:Q.sourceElement,path:Q.path,target:Q.target||e(Q.sourceElement,"element-range"),optional:Q.optional}},F7=(Q,Y,J="tokens")=>{Q[J].push(Y)},x9=(Q,Y,J)=>{b7(Q).forEach((G,X)=>Q7(G,Y,`${J}/${H7(G)}[${X}]`))},C3=(Q,Y,J)=>{let G=b7(Q);if(G[0])Q7(G[0],Y,`${J}/numerator`);if(F7(Y,_7({state:Y,kind:"structure",role:"fraction",text:"/",sourceElement:Q,path:J,target:e(Q,"element-range")})),G[1])Q7(G[1],Y,`${J}/denominator`)},y3=(Q,Y,J)=>{let G=Q.getAttribute("open")||"(",X=Q.getAttribute("close")||")";F7(Y,_7({state:Y,kind:"operator",role:G==="|"?"absolute-value-fence":"open-fence",text:G,sourceElement:Q,path:`${J}/open`,target:e(Q,"element-range")})),x9(Q,Y,J),F7(Y,_7({state:Y,kind:"operator",role:X==="|"?"absolute-value-fence":"close-fence",text:X,sourceElement:Q,path:`${J}/close`,target:e(Q,"element-range")}))},x3=(Q,Y,J)=>{let G=b7(Q);if(G[0])Q7(G[0],Y,`${J}/base`);let X=G[1];if(!X)return;let j=Z8(X);if(y9.has(j)){F7(Y,_7({state:Y,kind:"structure",role:"superscript",text:j,normalized:j,sourceElement:X,path:`${J}/exponent`,target:e(Q,"element-range")}));return}Q7(X,Y,`${J}/exponent`)},f3=(Q,Y,J,G)=>{F7(Y,_7({state:Y,kind:"structure",role:G,text:Z8(Q)||G,normalized:`\x00${G}`,sourceElement:Q,path:J,target:e(Q,"element-range")}))},k3=(Q,Y,J)=>{let G=0;for(let X of b7(Q)){if(H7(X)==="mtr"||H7(X)==="mlabeledtr")G++,F7(Y,_7({state:Y,kind:"layout",role:"table-row",text:`row-${G}`,normalized:`row-${G}`,sourceElement:X,path:`${J}/row[${G}]`,target:e(X,"region-fallback")}),"layoutTargets");Q7(X,Y,`${J}/${H7(X)}[${G}]`)}},I3=(Q,Y,J)=>{let G=Z8(Q);if(!G)return;let X=b3(H7(Q)),j=X==="operator"?$3.get(G):void 0,Z=j??(X==="operator"&&(G==="("||G===")")?"grouping-fence":X);F7(Y,_7({state:Y,kind:X,role:Z,text:G,sourceElement:Q,path:J,target:j&&Q.parentElement?e(Q.parentElement,"region-fallback"):void 0,optional:Boolean(j)||Z==="grouping-fence"}))},Q7=(Q,Y,J)=>{let G=H7(Q);switch(G){case"annotation":case"annotation-xml":return;case"semantics":{let X=b7(Q).find((j)=>{let Z=H7(j);return Z!=="annotation"&&Z!=="annotation-xml"});if(X)Q7(X,Y,`${J}/presentation`);return}case"mi":case"mn":case"mo":case"mtext":case"ms":case"mspace":I3(Q,Y,J);return;case"mfrac":C3(Q,Y,J);return;case"msup":x3(Q,Y,J);return;case"mfenced":y3(Q,Y,J);return;case"mtable":k3(Q,Y,J);return;case"mphantom":return;case"maction":{let X=b7(Q)[0];if(X)Q7(X,Y,`${J}/action`);return}default:{let X=w3.get(G);if(X){f3(Q,Y,J,X);return}x9(Q,Y,J)}}},f9=(Q)=>{let Y={tokens:[],layoutTargets:[],nextId:0};return Q7(Q,Y,"/math"),{tokens:Y.tokens,layoutTargets:Y.layoutTargets,expressionTarget:e(Q,"region-fallback")}};var k9=(Q)=>{if(!Q.boundary)return null;return Q.alignment.segments.find((J)=>J.speechTokenIds.includes(Q.boundary.token.id))?.target||null};var v3=(Q)=>{let Y=[],J=new Set,G=(X)=>{let j=X.toLowerCase().trim().split(/\s+/).filter(Boolean);if(j.length===0)return;let Z=j.join(" ");if(J.has(Z))return;J.add(Z),Y.push(j)};G(Q.normalized);for(let X of Q.spokenAliases)G(X);return Y},I9=(Q,Y,J)=>{let G=0;for(let X of J){if(X.length<=G)continue;let j=!0;for(let Z=0;Z<X.length;Z++){let q=Q[Y+Z];if(!q||q.normalized.toLowerCase()!==X[Z]){j=!1;break}}if(j)G=X.length}return G},h3=(Q,Y)=>{let J=[],G=0;for(let X of Y){let j=v3(X);if(X.optional){let Z=I9(Q,G,j);if(Z>0)J.push({speechTokens:Q.slice(G,G+Z),math:X}),G+=Z;continue}while(G<Q.length){let Z=I9(Q,G,j);if(Z>0){J.push({speechTokens:Q.slice(G,G+Z),math:X}),G+=Z;break}G++}}return J},m3=(Q,Y,J)=>{let G=J.filter((Z)=>!Z.optional).length,X=Q.filter((Z)=>!Z.math.optional).length,j=Q.reduce((Z,q)=>Z+q.speechTokens.length,0);return G>0&&X===G&&j===Y.length},u3=(Q)=>Q.map(({speechTokens:Y,math:J})=>({speechTokenIds:Y.map((G)=>G.id),mathTokenIds:[J.id],score:1,confidence:1,target:J.target})),v9=(Q)=>{let Y=Q.minExactWordConfidence??0.95,J=h3(Q.speech.tokens,Q.math.tokens),G=m3(J,Q.speech.tokens,Q.math.tokens)?1:0;return{segments:G>=Y?u3(J):[],confidence:G,fallbackTarget:Q.math.expressionTarget}};var h9=Z1(),p3=new Map([["zero","0"],["one","1"],["two","2"],["three","3"],["four","4"],["five","5"],["six","6"],["seven","7"],["eight","8"],["nine","9"],["ten","10"]]),m9=(Q)=>{let Y=Q.toLowerCase();return p3.get(Y)||Y},g3=(Q)=>{let Y=[];for(let J of Q.matchAll(h9)){let G=J[0],X=J.index??0;Y.push({id:`speech-token-${Y.length}`,text:G,normalized:m9(G),start:X,end:X+G.length,sourceStart:X,sourceEnd:X+G.length,coordinateSystem:"normalized-speech"})}return Y},A7=(Q)=>{let Y=W1(Q.speechText);return{speechText:Q.speechText,spokenText:Y.spokenText,tokens:g3(Y.spokenText),rawToSpokenOffsetMap:Y.rawToSpokenOffsetMap,boundaryOffsetSpace:Y.unsupportedSemantic?"unsupported":Y.hasMarkup?"raw-ssml":"plain-spoken-text",unsupportedSemantic:Y.unsupportedSemantic,hasMarkup:Y.hasMarkup}},K8=(Q)=>{if(!Q)return null;if(/^<[^>]+>$/.test(Q.trim()))return null;let Y=Q.match(h9);if(!Y?.[0])return null;return m9(Y[0])},c3=(Q,Y)=>Q.find((J)=>J.start<=Y&&Y<J.end)||null,l3=(Q,Y)=>{let J=Q.rawToSpokenOffsetMap.get(Y);if(J!==void 0)return J;for(let G=Y;G<Q.speechText.length;G++){let X=Q.rawToSpokenOffsetMap.get(G);if(X!==void 0)return X;if(Q.speechText[G]===">")break}return null},j8=(Q,Y,J)=>{if(Y===null)return null;let G=c3(Q.tokens,Y);if(!G)return null;return{token:G,start:Y,length:Math.max(1,Math.min(J,G.end-Y)),confidence:0.75}},q8=(Q,Y)=>{let J=K8(Y);return Boolean(Q&&J&&Q.token.normalized===J)},W8=(Q)=>{if(Q.tokenization.boundaryOffsetSpace==="unsupported"||!Number.isFinite(Q.position)||Q.boundaryWord&&/^<[^>]+>$/.test(Q.boundaryWord.trim()))return null;let Y=Math.max(1,Number.isFinite(Q.length)?Q.length:1),J=j8(Q.tokenization,l3(Q.tokenization,Q.position),Y),G=j8(Q.tokenization,Q.position>=0&&Q.position<Q.tokenization.spokenText.length?Q.position:null,Y);if(q8(J,Q.boundaryWord))return{...J,confidence:1};if(q8(G,Q.boundaryWord))return{...G,confidence:1};if(Q.boundaryWord&&K8(Q.boundaryWord))return null;return Q.tokenization.boundaryOffsetSpace==="raw-ssml"?J||G:G||J},u9=(Q)=>{if(Q.tokenization.boundaryOffsetSpace==="unsupported"||!Number.isFinite(Q.position)||Q.boundaryWord&&/^<[^>]+>$/.test(Q.boundaryWord.trim()))return null;let Y=Math.max(1,Number.isFinite(Q.length)?Q.length:1),J=j8(Q.tokenization,Q.position>=0&&Q.position<Q.tokenization.spokenText.length?Q.position:null,Y);if(q8(J,Q.boundaryWord))return{...J,confidence:1};if(Q.boundaryWord&&K8(Q.boundaryWord))return null;return J};var S7=(Q)=>{let Y=A7({speechText:Q.speechText}),J=f9(Q.mathElement);return{speech:Y,math:J,result:v9({speech:Y,math:J})}};var p9=(Q,Y)=>{let J=u9({tokenization:Q.speech,position:Y.position,length:Y.length,boundaryWord:Y.boundaryWord});return k9({alignment:Q.result,boundary:J})},g9=(Q,Y)=>{if(!Y.boundaryWord||/^<[^>]+>$/.test(Y.boundaryWord.trim()))return null;let J=A7({speechText:Y.boundaryWord}).tokens[0];if(!J)return null;let G=Q.math.tokens.filter((X)=>{let j=J.normalized.toLowerCase();return X.normalized.toLowerCase()===j||X.spokenAliases.some((Z)=>Z.toLowerCase()===j)});return G.length===1?G[0].target:null};var d3=new Set(["math","maction","menclose","merror","mfenced","mfrac","mi","mmultiscripts","mn","mo","mover","mpadded","mphantom","mprescripts","mroot","mrow","ms","mspace","msqrt","mstyle","msub","msubsup","msup","mtable","mtd","mtext","mtr","munder","munderover","none","semantics","annotation","annotation-xml"]),i3=new Set(["accent","accentunder","align","bevelled","class","close","columnalign","columnlines","columnspacing","columnspan","denomalign","depth","dir","display","encoding","fence","height","href","id","largeop","length","linethickness","lspace","mathbackground","mathcolor","mathsize","mathvariant","maxsize","minsize","movablelimits","notation","numalign","open","rowalign","rowlines","rowspacing","rowspan","rspace","scriptlevel","scriptminsize","scriptsizemultiplier","selection","separator","separators","stretchy","subscriptshift","supscriptshift","symmetric","width","xmlns","xml:lang"]),c9=(Q)=>Q.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),s3=(Q)=>c9(Q).replace(/"/g,"&quot;"),n3=(Q,Y)=>{let J=Q.toLowerCase(),G=Y.trim().toLowerCase();if(J.startsWith("on"))return!0;if(!i3.has(J))return!0;if(G.includes("javascript:"))return!0;if(G.includes("data:text/html"))return!0;return!1},r3=(Q)=>{let Y=Q.localName.toLowerCase();if(!d3.has(Y))return!1;let J=Q.namespaceURI;return!J||J==="http://www.w3.org/1998/Math/MathML"||J==="http://www.w3.org/1999/xhtml"},l9=(Q)=>{if(Q.nodeType===Node.TEXT_NODE)return c9(Q.textContent||"");if(Q.nodeType===Node.COMMENT_NODE)return"";if(Q.nodeType!==Node.ELEMENT_NODE)return null;let Y=Q;if(!r3(Y))return null;let J=Y.localName.toLowerCase(),G=[];for(let Z of Array.from(Y.attributes)){let q=Z.name.toLowerCase();if(n3(q,Z.value))continue;if(q==="xmlns"&&Z.value!=="http://www.w3.org/1998/Math/MathML")return null;G.push(`${q}="${s3(Z.value)}"`)}if(J==="math"&&!G.some((Z)=>Z.startsWith("xmlns=")))G.unshift('xmlns="http://www.w3.org/1998/Math/MathML"');let X=[];for(let Z of Array.from(Y.childNodes)){let q=l9(Z);if(q===null)return null;X.push(q)}let j=G.length>0?` ${G.join(" ")}`:"";return`<${J}${j}>${X.join("")}</${J}>`},o3=(Q)=>{if(typeof DOMParser<"u")return new DOMParser().parseFromString(Q,"application/xml");return null},B1=(Q)=>{let Y=String(Q||"").trim();if(!Y)return null;let J=o3(Y);if(!J)return null;if(J.getElementsByTagName("parsererror").length>0)return null;let G=J.documentElement;if(!G||G.localName.toLowerCase()!=="math")return null;return l9(G)};var d9=(Q)=>({chars:[],map:new Map,position:0,inLeadingWhitespace:!0,lastCharWasWhitespace:!1,lastMapped:null,options:Q}),i9=(Q)=>Q.classList?.contains("MathJax")||Q.tagName?.toLowerCase()==="mjx-container",s9=(Q)=>Q.tagName?.toLowerCase()==="mjx-assistive-mml",n9=(Q)=>{let Y=Q.tagName?.toLowerCase();return Y==="annotation"||Y==="annotation-xml"},a3=(Q)=>{let Y=Q.getAttribute("data-mathml");return Y&&Y.trim()?Y:null},t3=(Q)=>{return Q.querySelector("mjx-assistive-mml math")?.outerHTML||null},e3=(Q)=>{if(Q.tagName.toLowerCase()==="math")return B1(Q.outerHTML);let Y=a3(Q);if(Y){let J=B1(Y);if(J)return J}if(i9(Q)){let J=t3(Q);if(J){let G=B1(J);if(G)return G}}return null};var Q2=new Set(["P","H1","H2","H3","H4","H5","H6","LI","TD","TH","DD","DT","FIGCAPTION","LABEL","BUTTON"]),Y2=new Set(["heading","listitem","option","radio","row","cell","columnheader","rowheader"]),J2=(Q,Y)=>{let J=Q.parentElement,G=null;while(J&&J!==Y){let X=(J.getAttribute("role")||"").toLowerCase(),j=J.tagName.toUpperCase();if(Q2.has(j)||Y2.has(X)){G=J;break}J=J.parentElement}return G||Y},G2=(Q)=>Boolean(typeof Q.querySelector==="function"&&Q.querySelector("math, [data-mathml], .MathJax, mjx-container, mjx-assistive-mml"))||Q.tagName?.toLowerCase()==="math"||Q.hasAttribute?.("data-mathml")||i9(Q),M7=(Q,Y,J)=>{if(/[.,;:!?]/.test(Y)&&Q.chars.length>0&&Q.chars[Q.chars.length-1]===" ")Q.chars.pop(),Q.position--,Q.map.delete(Q.position);if(Q.chars.push(Y),J)Q.map.set(Q.position,J),Q.lastMapped=J;else if(Q.lastMapped)Q.map.set(Q.position,Q.lastMapped);Q.position++},r9=(Q,Y)=>{if(Q.inLeadingWhitespace||Q.lastCharWasWhitespace||Q.chars.length===0)return!1;let J=Q.chars[Q.chars.length-1];return Y8(J,Y,Q.options)},o9=(Q,Y)=>{let J=Y.textContent||"",G=!1;for(let X=0;X<J.length;X++){let j=J[X],Z=/\s/.test(j);if(Q.inLeadingWhitespace){if(!Z)Q.inLeadingWhitespace=!1,M7(Q,j,{node:Y,offset:X}),G=!0,Q.lastCharWasWhitespace=!1;continue}if(Z){if(!Q.lastCharWasWhitespace)M7(Q," ",{node:Y,offset:X});Q.lastCharWasWhitespace=!0;continue}if(!G&&r9(Q,j))M7(Q," ",{node:Y,offset:X});M7(Q,j,{node:Y,offset:X}),G=!0,Q.lastCharWasWhitespace=!1}},X2=(Q,Y)=>{for(let J=0;J<Y.text.length;J++){let G=Y.text[J],X=/\s/.test(G),j=Y.map.get(J)||null,Z=j?.node||Q.lastMapped?.node||null,q=j?.offset??Q.lastMapped?.offset??0,K=j?{node:j.node,offset:j.offset}:Z?{node:Z,offset:q}:null;if(Q.inLeadingWhitespace){if(X)continue;Q.inLeadingWhitespace=!1}if(X){if(!Q.lastCharWasWhitespace)M7(Q," ",K);Q.lastCharWasWhitespace=!0;continue}if(J===0&&r9(Q,G))M7(Q," ",K);if(M7(Q,G,K),Q.lastCharWasWhitespace=!1,j)Q.map.set(Q.position-1,{node:j.node,offset:j.offset}),Q.lastMapped={node:j.node,offset:j.offset};else if(Z)Q.map.set(Q.position-1,{node:Z,offset:q})}},Z2=(Q)=>{if(typeof DOMParser>"u")return"";let Y=new DOMParser().parseFromString(Q,"application/xml");if(Y.getElementsByTagName("parsererror").length>0)return"";let J=[],G=(X)=>{if(X.nodeType===3){let Z=X.textContent||"";if(Z.trim())J.push(Z);return}if(X.nodeType!==1)return;let j=X;if(n9(j))return;for(let Z of Array.from(j.childNodes))G(Z)};return G(Y.documentElement),S(J.join(" "))},j2=(Q,Y,J)=>{let G=d9(J),X=(q)=>{if(V7(q,Q))return;if(q.nodeType===3){o9(G,q);return}if(q.nodeType!==1)return;let K=q;if(s9(K)||n9(K))return;for(let B of Array.from(K.childNodes))X(B)};X(Q),a9(G);let j=S(G.chars.join(""));if(j)return{text:j,map:G.map};let Z=Z2(Y);if(!Z)return E7(Q,J);return{text:Z,map:new Map}},a9=(Q)=>{while(Q.chars.length>0&&/\s/.test(Q.chars[Q.chars.length-1]))Q.chars.pop(),Q.position--,Q.map.delete(Q.position)},q2=(Q,Y)=>{let J=d9(Y),G=[],X=0,j,Z=!1,q=()=>{let U=S(J.chars.slice(X,J.chars.length).join(""));if(U)G.push({type:"text",text:U,sourceElement:j});X=J.chars.length,j=void 0},K=(U)=>{if(V7(U,Q))return;if(U.nodeType===Node.TEXT_NODE){let A=J2(U,Q);if(j&&A!==j)q();j=A,o9(J,U);return}if(U.nodeType!==Node.ELEMENT_NODE)return;let H=U;if(s9(H))return;let _=e3(H);if(_){q();let A=j2(H,_,Y);X2(J,A);let M=S(A.text);G.push({type:"math",mathml:_,fallbackText:M,sourceElement:H}),X=J.chars.length,Z=!0;return}for(let A of Array.from(H.childNodes))K(A)};for(let U of Array.from(Q.childNodes))K(U);a9(J),q();let B=J.chars.join("");while(J.map.has(B.length))J.map.delete(B.length);return{visibleText:B,map:J.map,chunks:G,containsMathMarkup:Z}},N7=(Q,Y)=>{if(!G2(Q)){let{text:J,map:G}=E7(Q,Y);return{visibleText:J,map:G,chunks:J?[{type:"text",text:J}]:[],containsMathMarkup:!1}}return q2(Q,Y)};var U8=null,t9=Promise.resolve(),W2=(Q)=>(Q||"en").split("-")[0].toLowerCase()||"en",U2=async()=>{if(!U8)U8=import("speech-rule-engine").then((Q)=>{let Y=Q.default||Q;if(!Y||typeof Y.toSpeech!=="function")throw Error("speech-rule-engine did not expose toSpeech");return Y});return U8},B2=(Q)=>Q==="en"?"clearspeak":"mathspeak",e9=(Q)=>!!Q&&typeof Q==="object"&&!Array.isArray(Q),Q6=(Q)=>typeof Q==="string"&&Q.trim()?Q.trim():void 0,z7=(Q)=>{if(!e9(Q))return;let Y=Q6(Q.domain),J=Q6(Q.style),G=e9(Q.engineOptions)?Q.engineOptions:void 0;if(!Y&&!J&&!G)return;return{...Y?{domain:Y}:{},...J?{style:J}:{},...G?{engineOptions:G}:{}}},D2=async(Q,Y,J,G)=>{let X=W2(Y),j=z7(G);await Q.setupEngine?.({...j?.engineOptions||{},locale:X,domain:j?.domain||B2(X),...j?.style?{style:j.style}:{},modality:"speech",markup:J}),await Q.engineReady?.()},V2=async(Q)=>{let Y=t9.then(Q,Q);return t9=Y.then(()=>{return},()=>{return}),Y},Y6=async(Q,Y,J,G,X)=>V2(async()=>{return await D2(Q,J,G,X),Q.toSpeech(Y)}),H2=(Q)=>Q.replace(/^\s*<\?xml[^>]*\?>\s*/i,""),_2=async(Q,Y,J,G)=>{try{let X=H2(await Y6(Q,Y,J,"ssml",G));return X.includes("<speak")?X:null}catch(X){return console.debug("[TTSService] Math SSML generation failed; using plain",{message:X instanceof Error?X.message:String(X)}),null}},D1=async(Q,Y={})=>{if(!Q.some((B)=>B.type==="math"))return{speechText:S(Q.map((B)=>B.type==="text"?B.text:B.fallbackText).join(" ")),usedMathSpeech:!1,usedFallback:!1};let J=null,G=!1,X=!1,j=Y.loadSre||U2,Z=[];for(let B of Q){if(B.type==="text"){Z.push(B.text);continue}try{if(!J)J=await j();let U=S(await Y6(J,B.mathml,Y.language,"none",Y.mathSpeech));if(U){Z.push(U),G=!0;continue}X=!0,Z.push(B.fallbackText)}catch(U){X=!0,console.debug("[TTSService] Math speech generation failed; using visible fallback",{message:U instanceof Error?U.message:String(U)}),Z.push(B.fallbackText)}}let q=S(Z.join(" ")),K;if(Y.produceSsml&&J&&G&&Q.length===1&&Q[0].type==="math")K=await _2(J,Q[0].mathml,Y.language,Y.mathSpeech)??void 0;return{speechText:q,usedMathSpeech:G,usedFallback:X,ssml:K}};var F2=(Q,Y)=>D1([Q],Y),A2=(Q)=>(Q||"en").split("-")[0].toLowerCase()||"en",M2=new Set(["H1","H2","H3","H4","H5","H6","LI","LABEL","BUTTON"]),N2=new Set(["heading","listitem","option","radio"]),z2=(Q)=>{if(Q.type!=="text"||!Q.sourceElement)return!1;let Y=Q.sourceElement.tagName.toUpperCase(),J=(Q.sourceElement.getAttribute("role")||"").toLowerCase();return M2.has(Y)||N2.has(J)},B8=async(Q)=>{let Y=Q.resolveMathSpeech??F2,{visibleText:J}=Q,G=[],X=0,j=(q)=>{let K=S(q),B=J.indexOf(K,X),U=B>=0?B:X,H=U+K.length;return X=H,{start:U,end:H}},Z=[];for(let q=0;q<Q.chunks.length;q++){let K=Q.chunks[q];if(K.type==="text"){let A=z2(K)?[{text:K.text,offset:0}]:w7(K.text,{locale:Q.language});for(let M of A){let O=S(M.text);if(!O)continue;let L=j(O);G.push({sourceChunkIndex:q,segment:{kind:"prose",spokenText:O,visibleText:O,visibleSpan:L}}),Z.push(O)}continue}let B=j(K.fallbackText),U=await Y(K,{language:Q.language,produceSsml:Q.produceSsml,mathSpeech:Q.mathSpeech}),H=!U.speechText,_=U.speechText||K.fallbackText;G.push({sourceChunkIndex:q,segment:{kind:"math",spokenText:_,mathml:K.mathml,fallbackText:K.fallbackText,visibleSpan:B,usedFallback:H,ssml:U.ssml}}),Z.push(_)}return{segments:G,locale:A2(Q.language),visibleText:J,plainSpeechText:S(Z.join(" "))}};var O2=(Q)=>(Q||"en").split("-")[0].toLowerCase()||"en",P2="sre-v1",L2=256,D8=(Q)=>{if(Array.isArray(Q))return`array:[${Q.map(D8).join(",")}]`;if(Q&&typeof Q==="object")return`object:{${Object.entries(Q).sort(([Y],[J])=>Y.localeCompare(J)).map(([Y,J])=>`${JSON.stringify(Y)}:${D8(J)}`).join(",")}}`;if(Q===null)return"null:null";if(typeof Q>"u")return"undefined:";if(typeof Q==="function")return`function:${Q.name||"anonymous"}`;if(typeof Q==="symbol")return`symbol:${String(Q)}`;if(typeof Q==="bigint")return`bigint:${Q.toString()}`;if(typeof Q==="number")return Number.isFinite(Q)?`number:${Q}`:`number:${String(Q)}`;return`${typeof Q}:${JSON.stringify(Q)}`},J6=(Q,Y,J,G)=>`${P2}\x00${O2(Q)}\x00${Y?"ssml":"plain"}\x00${D8(J??null)}\x00${G}`,V8=(Q={})=>{let Y=Math.max(1,Q.maxEntries??L2),J=Q.resolve??((j,Z)=>D1([j],Z)),G=new Map,X=(j,Z)=>{G.delete(j),G.set(j,Z);while(G.size>Y){let q=G.keys().next().value;if(q!==void 0)G.delete(q)}};return async(j,Z)=>{let q=z7(Z.mathSpeech),K=Z.produceSsml===!0,B=J6(Z.language,K,q,j.mathml),U=G.get(B);if(U)return G.delete(B),G.set(B,U),U;let H=await J(j,{...Z,mathSpeech:q});if(K&&H.ssml&&Y>1)X(J6(Z.language,!1,q,j.mathml),{speechText:H.speechText,usedMathSpeech:H.usedMathSpeech,usedFallback:H.usedFallback});return X(B,H),H}};var $2=(Q)=>{if(!Q||/^<[^>]+>$/.test(Q.trim()))return null;return A7({speechText:Q}).tokens[0]?.normalized||null},w2=(Q,Y)=>{let J=A7({speechText:Q.speechText});if(!Number.isFinite(Y.position))return{boundary:null,spokenText:J.spokenText};let G=W8({tokenization:J,position:Y.position,length:Y.length,boundaryWord:Y.word});return{boundary:G?{start:G.start,length:G.length}:null,spokenText:J.spokenText}},R2=(Q,Y,J)=>{if(!J)return!0;return A7({speechText:Q}).tokens.find((X)=>X.start<=Y&&Y<X.end)?.normalized===J},G6=(Q,Y)=>{let J=$2(Y.word);if(Q.id!==Y.chunkId)return{chunkId:Y.chunkId,normalizedWord:J,chunkSpokenStart:null,chunkSpokenEnd:null,confidence:0,reason:"boundary chunk id did not match highlight chunk"};if(Y.providerOffsetSpace==="unknown"||Q.offsetSpace==="unsupported")return{chunkId:Q.id,normalizedWord:J,chunkSpokenStart:null,chunkSpokenEnd:null,confidence:0,reason:"boundary offset space is unsupported"};let G,X;if(Q.catalogAlignment)G=T9(Q.catalogAlignment,Y.position,Y.length,Y.word),X=Q.catalogAlignment.spokenText;else{let j=w2(Q,Y);G=j.boundary,X=j.spokenText}if(!G)return{chunkId:Q.id,normalizedWord:J,chunkSpokenStart:null,chunkSpokenEnd:null,confidence:0,reason:"could not resolve provider boundary to chunk speech"};if(!R2(X,G.start,J))return{chunkId:Q.id,normalizedWord:J,chunkSpokenStart:null,chunkSpokenEnd:null,confidence:0,reason:"could not resolve provider boundary to matching word"};return{chunkId:Q.id,normalizedWord:J,chunkSpokenStart:G.start,chunkSpokenEnd:G.start+G.length,confidence:J?1:0.75,reason:Q.catalogAlignment?"resolved through catalog alignment":"resolved through speech tokenization"}};var O7=(Q)=>{if(Q.semanticTarget)return{activeTarget:Q.semanticTarget,regionTarget:Q.regionTarget,quality:Q.semanticTarget.quality==="exact-word"?"exact-word":Q.semanticTarget.quality==="expression"?"expression":"semantic-token",confidence:Q.confidence,reason:Q.reason};if(Q.expressionTarget)return{activeTarget:Q.expressionTarget,regionTarget:Q.regionTarget,quality:"expression",confidence:Q.confidence,reason:Q.reason};return{activeTarget:null,regionTarget:Q.regionTarget,quality:"region",confidence:Q.confidence,reason:Q.reason}};var Z6=new Map([["mi","mjx-mi"],["mn","mjx-mn"],["mo","mjx-mo"],["mtext","mjx-mtext"]]),H8="mi,mn,mo,mtext",j6="mjx-mi,mjx-mn,mjx-mo,mjx-mtext",q6=["mjx-mfrac","mjx-msqrt","mjx-mroot","mjx-mtable","mjx-munder","mjx-mover","mjx-munderover"].join(","),K6=(Q)=>{if(Q.type==="text-range")return Q.node.parentElement;return Q.element},V1=(Q)=>{let Y=Q;while(Y){if(Y.localName?.toLowerCase()==="mjx-container")return Y;Y=Y.parentElement}return null},X6=(Q)=>{if(!Q)return!1;if(V1(Q))return!1;return!j1(Q)},W6=(Q)=>{let Y=Q.getBoundingClientRect?.();return Boolean(Y&&Y.width>0&&Y.height>0)},_8=(Q)=>{let Y=Q;while(Y){if(Y.localName?.toLowerCase()==="math")return Y;Y=Y.parentElement}return null},U6=(Q,Y)=>{if(Q.length===0)return!1;if(Q.length!==Y.length)return!1;for(let J=0;J<Q.length;J+=1){let G=Z6.get(Q[J].localName.toLowerCase());if(!G)return!1;if(Y[J].localName.toLowerCase()!==G)return!1}return!0},E2=(Q,Y)=>{if(!Q)return null;if(!Z6.has(Q.localName.toLowerCase()))return null;if(Y.querySelector(q6))return null;let J=_8(Q),G=Y.querySelector("mjx-math");if(!J||!G)return null;let X=Array.from(J.querySelectorAll(H8)),j=X.indexOf(Q);if(j<0)return null;let Z=Array.from(G.querySelectorAll(j6));if(!U6(X,Z))return null;let q=Z[j];if(!q||!W6(q))return null;return q},B6=(Q)=>{let Y=V1(Q);if(Y){if(Y.querySelector(q6))return"expression";let X=_8(Q)??Q,j=Y.querySelector("mjx-math");if(!j)return"expression";let Z=Array.from(X.querySelectorAll(H8)),q=Array.from(j.querySelectorAll(j6));if(!U6(Z,q))return"expression";return q.some((K)=>W6(K))?"token":"expression"}let J=_8(Q)??Q;return Array.from(J.querySelectorAll(H8)).some((X)=>!j1(X))?"token":"expression"},F8=(Q)=>{let Y=K6(Q),J=V1(Y);if(J){let G=E2(Y,J);if(G)return{type:"element",quality:"semantic-token",element:G};return{type:"element",quality:"expression",element:J}}if(Q.type==="text-range"){if(!X6(Q.node.parentElement))return null;return{type:"text-range",quality:"semantic-token",node:Q.node,startOffset:Q.startOffset,endOffset:Q.endOffset}}if(!X6(Q.element))return null;return{type:"element",quality:Q.quality==="region-fallback"?"expression":"semantic-token",element:Q.element}},D6=F8,V6=()=>{let Q=new WeakMap;return(Y)=>{let J=K6(Y),G=V1(J);if(!J||!G)return F8(Y);if(Q.has(J))return Q.get(J)??null;let X=F8(Y);return Q.set(J,X),X}};var H6=(Q,Y,J,G=Q.mathAlignments,X=D6)=>{if(Y.chunkSpokenStart===null||Y.chunkSpokenEnd===null)return null;let j=null;for(let Z of G){let q=p9(Z.alignment,{position:Y.chunkSpokenStart,length:Math.max(1,Y.chunkSpokenEnd-Y.chunkSpokenStart),boundaryWord:J.word})||g9(Z.alignment,{boundaryWord:J.word});if(!q)continue;let K=X(q);if(!K)continue;if(K.quality==="semantic-token")return K;j??=K}return j};var H1=(Q,Y,J)=>{if(!Q||typeof document>"u")return null;if(J<=Y)return null;let G=Q.get(Y),X=Q.get(Math.max(Y,J-1));if(!G)return null;if(!X)X=G;try{let j=document.createRange();return j.setStart(G.node,G.offset),j.setEnd(X.node,X.offset+1),j}catch{return null}};var _6=(Q,Y)=>{if(!Q.catalogAlignment||Y.chunkSpokenStart===null)return null;let J=C9(Q.catalogAlignment,Y.chunkSpokenStart);if(!J)return null;let G=H1(Q.visibleMap,J.start,J.end);if(!G)return null;return{type:"range",quality:Q.catalogAlignment.playbackMode==="exact-word"?"exact-word":"semantic-token",range:G}};var b2=(Q)=>Q.regionRange?{type:"range",quality:"region",range:Q.regionRange}:Q.regionElement?{type:"element",quality:"region",element:Q.regionElement}:null,F6=(Q,Y=Q.chunk.mathAlignments)=>{if(Y.length!==1)return null;let J=Y[0]?.alignment.result.fallbackTarget;return J?Q.renderedMathTargetResolver(J):null},S2=(Q,Y)=>{if(!Q)return Y.mathAlignments;return Y.mathAlignments.filter(({element:J})=>{try{if(Q.type==="range")return Q.range.intersectsNode(J);if(Q.type==="element")return Q.element===J||Q.element.contains(J);return Q.node.parentElement?.contains(J)||!1}catch{return!1}})},A6=()=>({activeTarget:null,regionTarget:null,quality:"region",confidence:0,reason:"boundary chunk id was not found"}),M6=(Q)=>Q.length===1?Q[0].element:null,T2=(Q,Y)=>Y.length>0&&Y.every(({element:J})=>Q.mathCapabilityByElement.get(J)==="token"),C2=3,y2=(Q,Y,J)=>{if(!Y||Y.type!=="range")return!1;let{startContainer:G,endContainer:X}=Y.range;if(G===X&&G.nodeType===C2)return!1;return J.some(({element:Z})=>Q.mathCapabilityByElement.get(Z)==="token"&&Z.contains(G)&&Z.contains(X))},x2=(Q,Y)=>({chunk:Q,regionTarget:b2(Q),renderedMathTargetResolver:V6(),mathCapabilityByElement:new Map(Q.mathAlignments.map(({element:J})=>[J,Y?B6(J):"expression"])),heldTokenByElement:new Map}),N6=(Q)=>{let Y=Q.mathTokenHighlighting!==!1,J=new Map(Q.chunks.map((G)=>[G.id,x2(G,Y)]));return{chunks:Q.chunks,resolveInitial(G){let X=J.get(G);if(!X)return A6();let j=X.chunk.mathAlignments,Z=j.length===1?j[0].element:null,q=Z?X.mathCapabilityByElement.get(Z):null;if(q==="expression")return O7({semanticTarget:null,expressionTarget:F6(X),regionTarget:X.regionTarget,confidence:0.5,reason:"initial expression (sticky expression mode)"});return O7({semanticTarget:null,expressionTarget:null,regionTarget:X.regionTarget,confidence:0,reason:q==="token"?"initial region (sticky token mode, awaiting first token)":"initial region fallback"})},resolveBoundary(G){let X=J.get(G.chunkId);if(!X)return A6();let{chunk:j}=X,Z=G6(j,G),q=_6(j,Z),K=S2(q,j),B=(!q||K.length>0?H6(j,Z,G,K,X.renderedMathTargetResolver):null)||null,U=Y&&B&&B.quality!=="expression"?B:null,H=B&&B.quality==="expression"?B:null;if(U){let _=M6(K);if(_)X.heldTokenByElement.set(_,U);return O7({semanticTarget:U,expressionTarget:null,regionTarget:X.regionTarget,confidence:Z.confidence,reason:Z.reason})}if(q&&(Y?!y2(X,q,K):K.length===0))return O7({semanticTarget:q,expressionTarget:null,regionTarget:X.regionTarget,confidence:Z.confidence,reason:Z.reason});if(T2(X,K)){let _=M6(K),A=_?X.heldTokenByElement.get(_)??null:null;return O7({semanticTarget:A,expressionTarget:null,regionTarget:X.regionTarget,confidence:Z.confidence,reason:A?"hold last token (sticky token mode)":"region (sticky token mode, awaiting first token)"})}return O7({semanticTarget:null,expressionTarget:H??F6(X,K),regionTarget:X.regionTarget,confidence:Z.confidence,reason:Z.reason})}}};var f2=(Q)=>{if(Q.alignment?.boundaryOffsetMode)return Q.alignment.boundaryOffsetMode;let Y=Q.mathAlignment?.speech.boundaryOffsetSpace;if(Y)return Y;return"plain-spoken-text"},k2=(Q)=>{if(Q.mathAlignments?.length)return Q.mathAlignments;if(Q.mathAlignment&&Q.sourceElement)return[{element:Q.sourceElement,alignment:Q.mathAlignment}];return[]},z6=(Q)=>{return(Q.chunks&&Q.chunks.length?Q.chunks:[{speechText:Q.speechText||"",visibleText:Q.visibleText||Q.speechText||"",sourceElement:Q.sourceElement||Q.contentRoot,regionElement:Q.regionElement||Q.sourceElement||Q.contentRoot,regionRange:Q.regionRange,visibleMap:Q.visibleMap}]).map((J,G)=>({id:`tts-chunk-${G}`,speechText:J.speechText,visibleText:J.visibleText,sourceElement:J.sourceElement,contentRoot:Q.contentRoot,regionElement:J.regionElement??J.sourceElement,regionRange:J.regionRange,visibleMap:J.visibleMap,catalogAlignment:J.alignment,mathAlignments:k2(J),offsetSpace:f2(J)}))};var I2=["[data-pie-tts-region]","[data-catalog-region]","li","p","label","section","[role='group']","[role='region']","div"].join(","),_1=(Q,Y)=>{let J=Q.closest(I2);if(J&&Y.contains(J))return J;return Q};var v2=(Q,Y,J)=>{let G=new Map;for(let X=Y;X<J;X++){let j=Q.get(X);if(j)G.set(X-Y,j)}return G},A8=async(Q)=>{let Y=N7(Q.contentRoot,Q.textProcessingOptions),J=await B8({chunks:Y.chunks,visibleText:Y.visibleText,language:Q.language,mathSpeech:Q.mathSpeech,produceSsml:Q.produceSsml,resolveMathSpeech:Q.resolveMathSpeech});return{plan:{items:J.segments.map(({segment:X,sourceChunkIndex:j})=>{let Z=Y.chunks[j];if(X.kind==="prose"){let K=Z?.type==="text"?Z.sourceElement??Q.contentRoot:Q.contentRoot;return{segment:X,anchor:{sourceElement:K,regionElement:_1(K,Q.contentRoot),visibleMap:v2(Y.map,X.visibleSpan.start,X.visibleSpan.end)}}}let q=Z?.type==="math"?Z.sourceElement??null:null;return{segment:X,anchor:{sourceElement:q,regionElement:q}}}),locale:J.locale,visibleText:J.visibleText,plainSpeechText:J.plainSpeechText},containsMathMarkup:Y.containsMathMarkup,visibleText:Y.visibleText}};var h2=(Q,Y)=>{let J=U1({speechText:Q.spokenText,visibleText:Q.spokenText});return{speechText:Q.spokenText,visibleText:Q.visibleText,sourceElement:Y.sourceElement,regionElement:Y.regionElement,regionRange:H1(Y.visibleMap,0,Q.visibleText.length)??void 0,speechMatchesVisibleText:!0,playbackMode:J.playbackMode,alignment:J,visibleMap:Y.visibleMap}},O6=(Q,Y)=>{let J=Y.sourceElement;return{speechText:Q.spokenText,visibleText:Q.fallbackText,sourceElement:J,regionElement:Y.regionElement,speechMatchesVisibleText:Q.spokenText===Q.fallbackText,mathAlignment:J?S7({mathElement:J,speechText:Q.spokenText}):void 0}},m2=(Q,Y,J)=>{let G=Y.sourceElement;return{speechText:J,visibleText:Q.fallbackText,sourceElement:G,regionElement:Y.regionElement,speechMatchesVisibleText:!1,mathAlignment:G?S7({mathElement:G,speechText:J}):void 0,plainFallback:O6(Q,Y)}},M8=(Q,Y={})=>Q.items.map(({segment:J,anchor:G})=>{if(J.kind==="prose")return h2(J,G);if(Y.format==="ssml"&&J.ssml)return m2(J,G,J.ssml);return O6(J,G)});var P6="pie-tts-control-handoff";var E;(function(Q){Q.IDLE="idle",Q.LOADING="loading",Q.PLAYING="playing",Q.PAUSED="paused",Q.ERROR="error"})(E||(E={}));var L6=(Q,Y)=>Q===Y||Q.startContainer===Y.startContainer&&Q.startOffset===Y.startOffset&&Q.endContainer===Y.endContainer&&Q.endOffset===Y.endOffset,u2=(Q,Y)=>{if(Q===Y)return!0;if(!Q||!Y||Q.type!==Y.type||Q.quality!==Y.quality)return!1;if(Q.type==="range"&&Y.type==="range")return L6(Q.range,Y.range);if(Q.type==="element"&&Y.type==="element")return Q.element===Y.element;if(Q.type==="text-range"&&Y.type==="text-range")return Q.node===Y.node&&Q.startOffset===Y.startOffset&&Q.endOffset===Y.endOffset;return!1};class m7{currentProvider=null;provider=null;highlightCoordinator=null;highlightTargetResolverProvider=null;catalogResolver=null;state=E.IDLE;ttsConfig={};currentText=null;currentContentElement=null;normalizedToDOM=new Map;listeners=new Map;lastError=null;speakRunId=0;currentBoundaryOffset=0;activeWordBoundaryOffset=0;seekSegments=[];playbackChunks=[];activeRecordedAudio=null;sentenceHighlightSegments=[];currentSeekSegmentIndex=0;activeSentenceStartOffset=null;playbackStartDeferredRunId=null;pendingPlaybackStartHighlights=[];playbackStartBarrierCleanup=null;playbackRateWriteQueue=Promise.resolve();playbackRateRequestId=0;pendingPlaybackRateRequest=null;activePlaybackRate=null;activeHighlightMode="word";lastRenderedRegionTarget=null;telemetryReporter=null;generatedMathSpeechResolver=V8();static debugEnabled=(()=>{try{if(typeof process<"u"&&process.env?.PIE_TTS_DEBUG==="1")return!0}catch{}return globalThis.__PIE_TTS_DEBUG__===!0})();constructor(){}debugLog(Q,Y){if(!m7.debugEnabled)return;if(Y===void 0)console.debug(Q);else console.debug(Q,Y)}clearPlaybackStartBarrier(Q=this.playbackStartBarrierCleanup){if(Q?.(),this.playbackStartBarrierCleanup===Q)this.playbackStartBarrierCleanup=null}notifyPlaybackStarted(Q){if(this.playbackStartDeferredRunId!==Q||Q!==this.speakRunId)return;this.setState(E.PLAYING);let Y=this.pendingPlaybackStartHighlights.splice(0);for(let J of Y)J()}installPlaybackStartBarrier(Q,Y=!1){this.clearPlaybackStartBarrier();let J=this.provider,G=J&&"onPlaybackStart"in J?J:null;if(!G&&!Y)return null;let X=G?.onPlaybackStart,j=()=>{try{this.notifyPlaybackStarted(Q)}finally{X?.()}};if(G)G.onPlaybackStart=j;this.playbackStartDeferredRunId=Q;let Z=()=>{if(G?.onPlaybackStart===j)G.onPlaybackStart=X;if(this.playbackStartDeferredRunId===Q)this.playbackStartDeferredRunId=null,this.pendingPlaybackStartHighlights=[]};return this.playbackStartBarrierCleanup=Z,Z}runWhenPlaybackStarts(Q,Y){if(this.playbackStartDeferredRunId===Q){this.pendingPlaybackStartHighlights.push(Y);return}Y()}async emitTelemetry(Q,Y){try{await this.telemetryReporter?.(Q,Y)}catch(J){console.warn("[TTSService] telemetry callback failed:",J)}}async initialize(Q,Y={}){this.currentProvider=Q,this.ttsConfig={...Y};let J=Y.providerOptions&&typeof Y.providerOptions==="object"?Y.providerOptions:{};this.telemetryReporter=typeof J.__pieTelemetry==="function"?J.__pieTelemetry:null;try{this.provider=await Q.initialize(Y)}catch(G){if(Q.providerId.toLowerCase()==="browser")throw G;if(!this.isBrowserSpeechFallbackAvailable())throw G;if(!await this.switchProviderToBrowser(G,{operation:"tts-initialize"}))throw G}}async updateSettings(Q){if(!this.provider)throw Error("TTSService not initialized. Call initialize() first.");let Y=this.provider;if(typeof Y.updateSettings==="function"){let J={...Q,...Q.providerOptions?{providerOptions:{...this.ttsConfig.providerOptions||{},...Q.providerOptions}}:{}};await Y.updateSettings(J),this.ttsConfig={...this.ttsConfig,...J}}else console.warn("[TTSService] Provider does not support dynamic settings updates. Some settings may require reinitialization.")}setHighlightCoordinator(Q){this.highlightCoordinator=Q}setHighlightTargetResolverProvider(Q){return this.highlightTargetResolverProvider=Q,()=>{if(this.highlightTargetResolverProvider===Q)this.highlightTargetResolverProvider=null}}setCatalogResolver(Q){this.catalogResolver=Q}hasSpokenAlternate(Q,Y="en-US"){if(!Q||!this.catalogResolver)return!1;return this.catalogResolver.getAlternative(Q,{type:"spoken",language:Y,useFallback:!0,form:"content"})?.content!==void 0}getHighlightResolverRuntime(){let Q=null;try{Q=this.highlightTargetResolverProvider?.()??null}catch{Q=null}let Y=Q?.context??{},J=typeof HTMLElement<"u"&&this.currentContentElement instanceof HTMLElement?this.currentContentElement:null;return{context:{...Y,scopeElement:Y.scopeElement??J},resolver:Q?.resolver??null}}getNodeElement(Q){if(!Q)return null;return Q.nodeType===Node.ELEMENT_NODE?Q:Q.parentElement}isElementWithinScope(Q,Y){if(!Y)return!0;return Q===Y||Y.contains(Q)}isRangeWithinScope(Q,Y){let J=this.getNodeElement(Q.startContainer),G=this.getNodeElement(Q.endContainer);if(!J||!G)return!1;return this.isElementWithinScope(J,Y)&&this.isElementWithinScope(G,Y)}resolveWordHighlightRange(Q){let{context:Y,resolver:J}=this.getHighlightResolverRuntime(),G=Y.scopeElement??this.currentContentElement;try{let X=J?.resolveWordRange?.(Q,Y);if(X&&this.isRangeWithinScope(X,G))return{range:X,remapped:!L6(Q,X)}}catch{}return{range:Q,remapped:!1}}resolveSentenceHighlightTargets(Q){let{context:Y,resolver:J}=this.getHighlightResolverRuntime(),G=Y.scopeElement??this.currentContentElement;try{let X=J?.resolveSentenceRanges?.(Q,Y);if(!X)return{ranges:Q,elements:[]};let j=[],Z=[];for(let q of X){if(typeof Range<"u"&&q instanceof Range){if(!this.isRangeWithinScope(q,G))return{ranges:Q,elements:[]};j.push(q);continue}if(typeof Element<"u"&&q instanceof Element){if(!this.isElementWithinScope(q,G))return{ranges:Q,elements:[]};Z.push(q);continue}return{ranges:Q,elements:[]}}return{ranges:j,elements:Z}}catch{return{ranges:Q,elements:[]}}}createTextRange(Q,Y,J){if(typeof document>"u")return null;if(typeof document.createRange!=="function")return null;try{let G=document.createRange();if(G.setStart(Q,Y),G.setEnd(Q,J),G.startContainer!==Q||G.endContainer!==Q)return null;return G}catch{return null}}paintTTSWordRange(Q){if(!this.highlightCoordinator)return;try{if(Q.startContainer===Q.endContainer&&Q.startContainer.nodeType===Node.TEXT_NODE){this.highlightCoordinator.highlightTTSWord(Q.startContainer,Q.startOffset,Q.endOffset);return}}catch{}this.highlightCoordinator.highlightRange(Q,m.TTS_WORD,D7.YELLOW)}paintTTSSentenceRanges(Q){if(!this.highlightCoordinator)return;let{ranges:Y,elements:J}=this.resolveSentenceHighlightTargets(Q);if(J.length>0&&Y.length===0&&this.highlightCoordinator.highlightTTSSentenceElements){this.highlightCoordinator.highlightTTSSentenceElements(J);return}let G=[...Y];for(let X of J){let j=document.createRange();j.selectNodeContents(X),G.push(j)}this.highlightCoordinator.highlightTTSSentence(G)}getCapabilities(){return this.currentProvider?.getCapabilities()||null}getTextProcessingOptions(Q){let J=(this.ttsConfig.providerOptions||{}).textNormalization||{},G=J.boundarySpacingMode,X=G==="none"||G==="alnum"||G==="segmenterPreferred"?G:void 0;return{locale:Q||(typeof J.locale==="string"?J.locale:void 0),boundarySpacingMode:X}}getMathSpeechOptions(){let Y=(this.ttsConfig.providerOptions||{}).mathSpeech;return z7(Y)}buildPositionMap(Q,Y,J){this.normalizedToDOM.clear();let{text:G,map:X}=E7(Q,this.getTextProcessingOptions(J));if(this.normalizedToDOM=X,!m7.debugEnabled)return;this.debugLog("[TTSService] Text comparison:",{spokenLength:Y.length,normalizedDomLength:G.length,match:Y===G,spokenPreview:Y.substring(0,150),normalizedPreview:G.substring(0,150),differAtIndex:Y===G?null:(()=>{for(let j=0;j<Math.min(Y.length,G.length);j++)if(Y[j]!==G[j])return{index:j,spokenChar:Y[j],normalizedChar:G[j],spokenContext:Y.substring(Math.max(0,j-20),j+20),normalizedContext:G.substring(Math.max(0,j-20),j+20)};return null})()}),this.debugLog("[TTSService] Position map built:",{entries:this.normalizedToDOM.size,spokenTextLength:Y.length,normalizedDomLength:G.length,mapLengthMatchesSpoken:this.normalizedToDOM.size===Y.length,firstFewMappings:Array.from(this.normalizedToDOM.entries()).slice(0,10).map(([j,{node:Z,offset:q}])=>({pos:j,offset:q,char:Z.textContent?.[q],expected:Y[j]}))})}getStructuralPauseProfile(){let Y=(this.ttsConfig.providerOptions||{}).structuralPauses||{},J=Y.units||{},G=(X,j)=>{if(typeof X==="number"&&Number.isFinite(X))return X;if(typeof X==="string"&&X.trim()){let Z=Number(X);return Number.isFinite(Z)?Z:j}return j};return{baseMs:G(Y.baseMs,280),units:{minor:G(J.minor,0.65),section:G(J.section,1),major:G(J.major,1.35)},minMs:G(Y.minMs,120),maxMs:G(Y.maxMs,900)}}resolvePauseMsFromUnits(Q){let Y=this.getStructuralPauseProfile(),J=Math.max(0.25,Math.min(4,Number(this.ttsConfig.rate||1))),G=Y.baseMs*Math.max(0,Q)/J;return Math.max(Y.minMs,Math.min(Y.maxMs,Math.round(G)))}resolveHighlightMode(){let Y=(this.ttsConfig.providerOptions||{}).highlightMode;if(Y==="word"||Y==="sentence")return Y;if((this.currentProvider?.providerId||"").toLowerCase()==="browser")return"sentence";return this.currentProvider?.getCapabilities().supportsWordBoundary??!1?"word":"sentence"}hasExplicitBreakSemantics(Q){if(!Q.includes("<"))return!1;return/<\s*break\b|<\s*speak\b|<\s*prosody\b|<\s*p\b|<\s*s\b/i.test(Q)}isElementHidden(Q){return e1(Q)}getBoundaryStrength(Q){let Y=Number(Q.getAttribute("data-tts-break-ms"));if(Number.isFinite(Y)&&Y>0)return"major";let J=Q.tagName.toUpperCase();if(J.match(/^H[1-6]$/))return"major";let G=(Q.getAttribute("role")||"").toLowerCase();if(G==="heading")return"major";if(G==="listitem"||G==="row"||G==="option"||G==="radio"||J==="LI")return"section";if(typeof window<"u"){let X=window.getComputedStyle(Q).display;if(X==="block"||X==="list-item"||X.startsWith("table")||X==="flex"||X==="grid")return"minor"}return"minor"}getBoundaryAnchor(Q,Y){let J=Q.parentElement,G=null;while(J&&J!==Y){if(this.isElementHidden(J))return null;let j=Number(J.getAttribute("data-tts-break-ms"));if(Number.isFinite(j)&&j>0)return{anchor:J,units:j/this.getStructuralPauseProfile().baseMs};let Z=(J.getAttribute("role")||"").toLowerCase(),q=J.tagName.toUpperCase();if(q.match(/^H[1-6]$/)||Z==="heading"||Z==="listitem"||q==="LI"){G=J;break}if(!G){if(typeof window<"u"){let K=window.getComputedStyle(J).display;if(K==="block"||K==="list-item"||K.startsWith("table")||K==="flex"||K==="grid")G=J}}J=J.parentElement}if(!G)return null;let X=this.getBoundaryStrength(G);return{anchor:G,units:this.getStructuralPauseProfile().units[X]}}createSpeechPlan(Q,Y){let J=this.collectSpeechPlanBoundaries(Q,Y);return this.createSpeechPlanSegments(Y,J)}collectSpeechPlanBoundaries(Q,Y){let J=new Map,{map:G}=E7(Q,this.getTextProcessingOptions()),X=this.createNodeStartOffsets(G),j=document.createTreeWalker(Q,NodeFilter.SHOW_TEXT),Z=j.nextNode(),q=null;while(Z){let K=Z,B=K.parentElement;if(B&&!this.isElementHidden(B)&&!q1(K)){let U=this.getBoundaryAnchor(K,Q),H=X.get(K);if(U&&H!==void 0&&U.anchor!==q&&H>0)J.set(H,Math.max(J.get(H)||0,U.units)),q=U.anchor}Z=j.nextNode()}return J}createNodeStartOffsets(Q){let Y=new Map;for(let[J,G]of Q.entries())if(!Y.has(G.node))Y.set(G.node,J);return Y}createSpeechPlanSegments(Q,Y){let J=Array.from(Y.keys()).filter((K)=>K>0&&K<Q.length).sort((K,B)=>K-B),G=[],X=0;for(let K of J){let B=Q.substring(X,K),U=B.match(/^\s*/)?.[0].length||0,H=B.match(/\s*$/)?.[0].length||0,_=X+U,A=K-H;if(A>_){let M=Q.substring(_,A);G.push({text:M,startOffset:_,pauseMsAfter:this.resolvePauseMsFromUnits(Y.get(K)||0)})}X=K}let Z=Q.substring(X).match(/^\s*/)?.[0].length||0,q=X+Z;if(q<Q.length)G.push({text:Q.substring(q).trimEnd(),startOffset:q,pauseMsAfter:0});return G.filter((K)=>K.text.trim().length>0)}segmentSentences(Q){let Y=this.ttsConfig.providerOptions?.locale||void 0;return w7(Q,{locale:Y})}createSeekSegmentsFromText(Q){return this.segmentSentences(Q).map((Y)=>{let J=Y.text.match(/^\s*/)?.[0].length||0;return{text:Y.text.trim(),startOffset:Y.offset+J,pauseMsAfter:0}}).filter((Y)=>Y.text.length>0)}splitSegmentsAtBoundaries(Q,Y,J){if(Q.length===0||Y.length===0)return Q;let G=Array.from(new Set(Y)).filter((j)=>Number.isFinite(j)&&j>0).sort((j,Z)=>j-Z);if(G.length===0)return Q;let X=[];for(let j of Q){let Z=j.startOffset,q=j.startOffset+j.text.length,K=G.filter((U)=>U>Z&&U<q);if(K.length===0){X.push(j);continue}let B=Z;for(let U of[...K,q]){let H=J.substring(B,U),_=H.match(/^\s*/)?.[0].length||0,A=H.match(/\s*$/)?.[0].length||0,M=B+_,O=U-A;if(O>M)X.push({text:J.substring(M,O),startOffset:M,pauseMsAfter:0});B=U}}return X}createSentenceHighlightSegments(Q){let Y=this.createSeekSegmentsFromText(Q.contentToSpeak);if(!Q.shouldUsePlan||Q.playbackSegments.length===0)return Y;let J=Q.playbackSegments.map((G)=>G.startOffset).filter((G)=>G>0);return this.splitSegmentsAtBoundaries(Y,J,Q.contentToSpeak)}createSeekSegmentsFromSpeechChunks(Q){let Y=0;return Q.map((J)=>{let G=J.plainFallback?.speechText||(this.hasExplicitBreakSemantics(J.speechText)?J.visibleText:J.speechText)||J.visibleText,X=S(G)||J.visibleText||"",j={text:X,startOffset:Y,pauseMsAfter:0};return Y+=Math.max(1,X.length+1),j})}getCurrentSeekSegmentIndex(){if(this.seekSegments.length===0)return 0;let Q=0;for(let Y=0;Y<this.seekSegments.length;Y++)if(this.seekSegments[Y].startOffset<=this.currentBoundaryOffset)Q=Y;else break;return Q}async speakWithPlan(Q,Y,J){if(!this.provider||Q.length===0)return;let G=J?.highlightMode==="sentence",X=this.provider;if(!G&&typeof X.speakSegments==="function"){this.currentBoundaryOffset=0;let j=this.provider.onWordBoundary;this.provider.onWordBoundary=(Z,q,K)=>{if(j?.(Z,q,K),Number.isFinite(q))this.currentBoundaryOffset=q,this.currentSeekSegmentIndex=this.getCurrentSeekSegmentIndex()};try{await X.speakSegments(Q)}finally{if(Y===this.speakRunId&&this.provider===X)this.provider.onWordBoundary=j}return}this.configureWordBoundaryHighlighting({highlightMode:J?.highlightMode||"word",wordBoundaryOffset:this.activeWordBoundaryOffset});for(let j of Q){if(Y!==this.speakRunId)return;let Z=this.seekSegments.findIndex((K)=>K.startOffset===j.startOffset);if(Z>=0)this.currentSeekSegmentIndex=Z;if(this.currentBoundaryOffset=j.startOffset,G)this.runWhenPlaybackStarts(Y,()=>{this.highlightSentenceSegment(j.startOffset,j.text)});await this.provider.speak(j.text);let q=j.pauseMsAfter??0;if(q>0)await new Promise((K)=>setTimeout(K,q))}}highlightSentenceSegment(Q,Y){if(!this.highlightCoordinator||typeof document>"u")return;let J=Y.trimEnd().length;if(J<=0)return;let G=this.normalizedToDOM.get(Q),X=this.normalizedToDOM.get(Q+J-1);if(!G||!X)return;let j=document.createRange();j.setStart(G.node,G.offset),j.setEnd(X.node,X.offset+1),this.paintTTSSentenceRanges([j]),this.activeSentenceStartOffset=Q}getSegmentIndexForOffset(Q,Y){if(Q.length===0)return-1;let J=-1;for(let G=0;G<Q.length;G++)if(Q[G].startOffset<=Y)J=G;else break;return J}highlightSentenceForOffset(Q){let Y=this.sentenceHighlightSegments;if(!this.highlightCoordinator||Y.length===0)return;let J=this.getSegmentIndexForOffset(Y,Q);if(J<0)return;let G=Y[J];if(!G)return;if(this.activeSentenceStartOffset===G.startOffset)return;this.highlightSentenceSegment(G.startOffset,G.text)}findHighlightRange(Q,Y){let J=this.normalizedToDOM.get(Q);if(!J)return console.warn(`[TTSService] No mapping found for start position ${Q}`,{totalMappings:this.normalizedToDOM.size,nearbyMappings:Array.from(this.normalizedToDOM.entries()).filter(([j])=>Math.abs(j-Q)<5).map(([j,{offset:Z,node:q}])=>({pos:j,offset:Z,char:q.textContent?.[Z]}))}),null;let G=Q+Y-1,X=this.normalizedToDOM.get(G);if(!X)return console.warn(`[TTSService] No mapping found for end position ${G}`,{startChar:Q,length:Y,totalMappings:this.normalizedToDOM.size}),null;if(J.node!==X.node)return console.warn("[TTSService] Word spans multiple nodes, highlighting in first node only"),{node:J.node,start:J.offset,end:(J.node.textContent||"").length};return{node:J.node,start:J.offset,end:X.offset+1}}async speak(Q,Y){if(!this.provider)throw Error("TTS service not initialized");let J=++this.speakRunId;this.clearPlaybackStartBarrier();let G=null;try{if(await this.applyLanguageSettings(Y),J!==this.speakRunId)return;let X=await this.resolveSpeechContent(Q,Y);if(J!==this.speakRunId)return;let{contentToSpeak:j,speechText:Z,highlightText:q,normalizedText:K,usedCatalogSpoken:B,speechSource:U,speechMatchesVisibleText:H,speechChunks:_}=X;this.logResolvedSpeechContent({contentToSpeak:j,speechSource:U,catalogId:Y?.catalogId}),this.initializeSpeakTracking(q,Y);let A=Y?.highlightModeOverride||(H?this.resolveHighlightMode():"sentence");this.activeHighlightMode=A,this.activeWordBoundaryOffset=Y?.wordBoundaryOffset||0;let M=this.hasExplicitBreakSemantics(j),O=!!this.currentContentElement&&!B&&!M&&H;if(this.playbackChunks=_?.length?_:[],this.seekSegments=this.playbackChunks.length?this.createSeekSegmentsFromSpeechChunks(this.playbackChunks):M||!H?[]:O&&this.currentContentElement?this.createSpeechPlan(this.currentContentElement,K):this.createSeekSegmentsFromText(q),this.sentenceHighlightSegments=M?[]:this.createSentenceHighlightSegments({contentToSpeak:q,shouldUsePlan:O,playbackSegments:this.seekSegments}),this.setState(E.LOADING),G=this.installPlaybackStartBarrier(J,!!this.playbackChunks[0]?.audio),this.prepareHighlightsForSpeak({contentToSpeak:q,options:Y,highlightMode:A,shouldUsePlan:O,runId:J}),H)this.configureWordBoundaryHighlighting({highlightMode:A,wordBoundaryOffset:Y?.wordBoundaryOffset||0});else this.clearWordBoundaryHighlighting();if(!G)this.setState(E.PLAYING);if(this.activePlaybackRate=this.normalizePlaybackRate(Number(this.ttsConfig.rate??1)),await this.executeSpeakPlayback({shouldUsePlan:O,runId:J,highlightMode:A,contentToSpeak:Z,speechChunks:_}),J!==this.speakRunId)return;this.setState(E.IDLE),this.clearHighlightsAndTracking()}catch(X){let j=X;if(console.error("TTS error:",j),this.lastError=j instanceof Error?j.message:String(j),J!==this.speakRunId)return;throw this.setState(E.ERROR),this.clearHighlightsAndTracking(),j}finally{this.clearPlaybackStartBarrier(G)}}async switchProviderToBrowser(Q,Y){if(!this.currentProvider)return!1;let J=new R7,G=this.currentProvider.providerId,X={};if(this.ttsConfig.rate!==void 0)X.rate=this.ttsConfig.rate;if(this.ttsConfig.pitch!==void 0)X.pitch=this.ttsConfig.pitch;if(this.ttsConfig.mathTokenHighlighting!==void 0)X.mathTokenHighlighting=this.ttsConfig.mathTokenHighlighting;let j=Y?.operation||"tts-initialize",Z=Y?.contentToSpeak??"",q=Z.replace(/\s+/g," ").trim().slice(0,120),K=Z.length>0?{textLength:Z.length,textPreview:q.length<Z.length?`${q}…`:q}:{};try{return this.provider?.stop(),this.currentProvider.destroy(),this.currentProvider=J,this.provider=await J.initialize(X),this.ttsConfig=X,await this.emitTelemetry("pie-tool-runtime-fallback",{toolId:"textToSpeech",operation:j,fromProvider:G,toProvider:J.providerId,reason:Q instanceof Error?Q.message:String(Q),...K}),console.warn("[TTSService] TTS provider initialization failed; switched to browser fallback",{fromProvider:G,reason:Q,...K}),!0}catch(B){return await this.emitTelemetry("pie-tool-runtime-fallback-error",{toolId:"textToSpeech",operation:j,fromProvider:G,toProvider:"browser",errorType:"TTSRuntimeFallbackError",message:B instanceof Error?B.message:String(B)}),console.error("[TTSService] Failed to switch to browser fallback provider",B),!1}}isBrowserSpeechFallbackAvailable(){if(typeof window>"u")return!1;if(!("speechSynthesis"in window))return!1;return typeof globalThis.SpeechSynthesisUtterance==="function"}async applyLanguageSettings(Q){if(!Q?.language||!this.provider)return;let Y=this.ttsConfig.providerOptions||{},J=Y.textNormalization||{},G=Y.segmenter||{},X={...Y,locale:Q.language,textNormalization:{...J,locale:Q.language},segmenter:{...G,locale:Q.language}};if(this.ttsConfig={...this.ttsConfig,providerOptions:X},"updateSettings"in this.provider&&typeof this.provider.updateSettings==="function")await this.provider.updateSettings({providerOptions:X})}async resolveSpeechContent(Q,Y){let J=S(Q);if(Y?.ignoreCatalogs)return{contentToSpeak:J,speechText:J,visibleText:J,highlightText:J,usedCatalogSpoken:!1,speechSource:"dom-or-input",normalizedText:J,containsMathMarkup:!1,speechMatchesVisibleText:!0};if(Y?.catalogId&&this.catalogResolver){let j=this.catalogResolver.getAlternative(Y.catalogId,{type:"spoken",language:Y.language||"en-US",useFallback:!0,context:Y.catalogContext,form:"content"}),Z=j?.content;if(j&&Z!==void 0){let q=Y?.contentElement?N7(Y.contentElement,this.getTextProcessingOptions(Y.language)).visibleText||J:J,K=S(Z);return this.debugLog(`[TTSService] Using catalog content for "${Y.catalogId}" (${j.language})`),{contentToSpeak:Z,speechText:Z,visibleText:q,highlightText:q,usedCatalogSpoken:!0,speechSource:"catalog-spoken",normalizedText:q,containsMathMarkup:!1,speechMatchesVisibleText:K===q}}this.debugLog(`[TTSService] No catalog found for "${Y.catalogId}", falling back to generated TTS`)}let G=Y?.contentElement?this.resolveCatalogComposedSpeechContent(Y.contentElement,J,Y):null;if(G)return G;return{...Y?.contentElement?await this.resolveGeneratedSpeechContent(Y.contentElement,J,Y.language):{contentToSpeak:J,speechText:J,visibleText:J,highlightText:J,normalizedText:J,containsMathMarkup:!1,speechMatchesVisibleText:!0},usedCatalogSpoken:!1,speechSource:"dom-or-input"}}resolveCatalogComposedSpeechContent(Q,Y,J){if(!this.catalogResolver)return null;let G=this.collectCatalogSpeechChunks(Q,J);if(!G.some((Z)=>Z.sourceElement))return null;let X=S(G.map((Z)=>Z.speechText).join(" ")),j=N7(Q,this.getTextProcessingOptions(J.language)).visibleText||Y;return{contentToSpeak:X,speechText:X,visibleText:j,highlightText:j,usedCatalogSpoken:!0,speechSource:"catalog-spoken",normalizedText:j,containsMathMarkup:!1,speechMatchesVisibleText:G.every((Z)=>Z.speechMatchesVisibleText),speechChunks:G}}collectCatalogSpeechChunks(Q,Y){let J=[],G="",X=()=>{let B=S(G);if(G="",!B)return;J.push({speechText:B,visibleText:B,sourceElement:null,speechMatchesVisibleText:!0})},j=(B)=>{let U=B.getAttribute("data-catalog-idref");if(!U)return null;let H={type:"spoken",language:Y.language||"en-US",useFallback:!0,context:Y.catalogContext},_=this.catalogResolver.getAlternative(U,{...H,form:"payload"}),A=_?.payload?V9({payload:_.payload})??void 0:void 0,O=this.catalogResolver.getAlternative(U,{...H,form:"content"})?.content;if(A===void 0&&O===void 0)return null;return{script:O,audio:A}},Z=(B,U)=>{let H=q(B);if(H.length!==1)return null;let _=H[0],A=N7(_,this.getTextProcessingOptions(Y.language)).visibleText||S(_.textContent||""),M=(O)=>S(O).replace(/\s+/g,"");return M(A)===M(U)?_:null},q=(B)=>{let U=Array.from(B.querySelectorAll("math"));if(B.localName?.toLowerCase()==="math")return[B,...U];return U},K=(B)=>{if(V7(B,Q))return;if(B.nodeType===Node.TEXT_NODE){G+=` ${B.textContent||""}`;return}if(B.nodeType!==Node.ELEMENT_NODE)return;let U=B,H=j(U);if(H){X();let _=N7(U,this.getTextProcessingOptions(Y.language)),A=_.visibleText||S(U.textContent||""),M=_1(U,Q),O=H.script!==void 0?(()=>{let L=H.script,F=U1({speechText:L,visibleText:A}),$=Z(U,A),b=$?S7({mathElement:$,speechText:L}):void 0,v=b?void 0:q(U).map((k)=>({element:k,alignment:S7({mathElement:k,speechText:L})}));return{speechText:L,visibleText:A,sourceElement:U,regionElement:M,speechMatchesVisibleText:S(L)===A,playbackMode:F.playbackMode,alignment:F,mathAlignment:b,mathAlignments:v,visibleMap:_.map}})():null;if(H.audio){J.push(O?{...O,audio:H.audio,plainFallback:O}:{speechText:A,visibleText:A,sourceElement:U,regionElement:M,speechMatchesVisibleText:!1,visibleMap:_.map,audio:H.audio});return}if(O)J.push(O);return}for(let _ of Array.from(U.childNodes))K(_)};return K(Q),X(),J}resolveGeneratedPlaybackFormat(){let Q=this.currentProvider;if(!Q)return"plain";if(Q.providerId?.toLowerCase()==="browser")return"plain";return Q.getCapabilities?.().supportsSSML?"ssml":"plain"}async resolveGeneratedSpeechContent(Q,Y,J){let G=this.resolveGeneratedPlaybackFormat(),{plan:X,containsMathMarkup:j,visibleText:Z}=await A8({contentRoot:Q,language:J,mathSpeech:this.getMathSpeechOptions(),textProcessingOptions:this.getTextProcessingOptions(J),produceSsml:G==="ssml",resolveMathSpeech:this.generatedMathSpeechResolver}),q=Z||Y;if(!j)return{contentToSpeak:q,speechText:q,visibleText:q,highlightText:q,normalizedText:q,containsMathMarkup:!1,speechMatchesVisibleText:!0};let K=M8(X,{format:G}),B=X.plainSpeechText;return{contentToSpeak:B,speechText:B,visibleText:q,highlightText:q,normalizedText:q,containsMathMarkup:!0,speechMatchesVisibleText:B===q,speechChunks:K}}logResolvedSpeechContent(Q){let Y=Q.contentToSpeak.replace(/\s+/g," ").trim().slice(0,200);this.debugLog("[TTSService] Speak resolved content",{source:Q.speechSource,catalogId:Q.catalogId||null,length:Q.contentToSpeak.length,preview:Y})}initializeSpeakTracking(Q,Y){this.currentText=Q,this.currentContentElement=Y?.contentElement||null,this.lastError=null,this.currentBoundaryOffset=0,this.playbackChunks=[],this.currentSeekSegmentIndex=0,this.activeSentenceStartOffset=null}prepareHighlightsForSpeak(Q){if(!this.currentContentElement||!this.highlightCoordinator)return;if(this.buildPositionMap(this.currentContentElement,Q.contentToSpeak,Q.options?.language),Q.highlightMode==="sentence"&&Q.shouldUsePlan)return;let Y=this.sentenceHighlightSegments[0]||this.seekSegments[0];this.runWhenPlaybackStarts(Q.runId,()=>{if(Y)this.highlightSentenceSegment(Y.startOffset,Y.text),this.debugLog("[TTSService] Applied initial sentence highlighting");else try{let J=document.createRange();J.selectNodeContents(this.currentContentElement),this.paintTTSSentenceRanges([J])}catch{}})}configureWordBoundaryHighlighting(Q){if(!this.provider||Q.highlightMode!=="word"||!this.highlightCoordinator||!this.currentContentElement)return;this.provider.onWordBoundary=(Y,J,G)=>{let X=G||Y.length,j=J+this.currentBoundaryOffset+Q.wordBoundaryOffset;this.highlightSentenceForOffset(j);let Z=this.findHighlightRange(j,X);if(Z&&this.highlightCoordinator){let q=Z.node.textContent?.substring(Z.start,Z.end)||"";this.debugLog(`[TTSService] Highlighting "${q}" (word: "${Y}") at position ${j}`);let K=this.createTextRange(Z.node,Z.start,Z.end);if(K)this.paintTTSWordRange(this.resolveWordHighlightRange(K).range);else this.highlightCoordinator.highlightTTSWord(Z.node,Z.start,Z.end)}else console.warn(`[TTSService] Could not find highlight range for position ${j}, length ${X}`)}}clearWordBoundaryHighlighting(){if(this.provider)this.provider.onWordBoundary=void 0}highlightCatalogRegion(Q){let Y=Q.regionElement||Q.sourceElement;if(!Y&&!Q.regionRange||!this.highlightCoordinator)return;try{if(this.lastRenderedRegionTarget=null,Q.regionRange){this.highlightCoordinator.clearHighlights?.(m.TTS_WORD),this.paintTTSSentenceRanges([Q.regionRange]);return}if(!Y)return;let J=document.createRange();J.selectNodeContents(Y),this.highlightCoordinator.clearHighlights?.(m.TTS_WORD),this.paintTTSSentenceRanges([J])}catch{}}highlightCatalogActiveRange(Q){if(!this.highlightCoordinator)return;this.paintTTSWordRange(this.resolveWordHighlightRange(Q).range)}highlightRenderableRegionTarget(Q){if(!this.highlightCoordinator||!Q||typeof document>"u")return;if(!this.highlightTargetResolverProvider&&u2(this.lastRenderedRegionTarget,Q))return;try{let Y=document.createRange();if(Q.type==="element")Y.selectNodeContents(Q.element);else if(Q.type==="range"){this.paintTTSSentenceRanges([Q.range]),this.lastRenderedRegionTarget=Q;return}else Y.setStart(Q.node,Q.startOffset),Y.setEnd(Q.node,Q.endOffset);this.paintTTSSentenceRanges([Y]),this.lastRenderedRegionTarget=Q}catch{}}highlightRenderableActiveTarget(Q){if(!this.highlightCoordinator||typeof document>"u")return;if(!Q){this.highlightCoordinator.clearHighlights(m.TTS_WORD);return}if(Q.type==="text-range"){let X=this.createTextRange(Q.node,Q.startOffset,Q.endOffset);if(X)this.paintTTSWordRange(this.resolveWordHighlightRange(X).range);else this.highlightCoordinator.highlightTTSWord(Q.node,Q.startOffset,Q.endOffset);return}if(Q.type==="range"){this.highlightCatalogActiveRange(Q.range);return}let Y=document.createRange();Y.selectNodeContents(Q.element);let J=this.resolveWordHighlightRange(Y);if(J.remapped){this.paintTTSWordRange(J.range);return}let G=Q.element.childNodes.length===1?Q.element.firstChild:null;if(Q.quality==="semantic-token"&&G?.nodeType===Node.TEXT_NODE){this.highlightCoordinator.highlightTTSWord(G,0,G.textContent?.length||0);return}this.highlightCoordinator.highlightTTSWordElement?.(Q.element)}renderHighlightDecision(Q){this.highlightRenderableRegionTarget(Q.regionTarget),this.highlightRenderableActiveTarget(Q.activeTarget)}async speakCatalogChunk(Q,Y){try{await this.speakCatalogChunkOnce(Q,Y)}catch(J){if(Q.plainFallback&&Y===this.speakRunId){if(this.debugLog("[TTSService] SSML chunk speak failed; retrying plain text",{message:J instanceof Error?J.message:String(J)}),this.playbackStartDeferredRunId===Y&&this.provider&&!("onPlaybackStart"in this.provider))this.pendingPlaybackStartHighlights=[],this.clearPlaybackStartBarrier(),this.setState(E.PLAYING);await this.speakCatalogChunkOnce(Q.plainFallback,Y);return}throw J}}async playRecordedAudio(Q,Y){if(typeof document>"u")throw Error("[tts] no document available to play recorded audio");let J=Q.sources[0],G=document.createElement("audio");G.preload="auto",G.src=D9(J.src,Q.fragment),G.playbackRate=this.normalizePlaybackRate(Number(this.ttsConfig.rate||1)),await new Promise((X,j)=>{let Z,q=!1,K=!1,B=()=>{if(K||q)return;q=!0,Y?.()},U=()=>{if(G.removeEventListener("ended",H),G.removeEventListener("error",_),G.removeEventListener("playing",B),Z!==void 0)clearInterval(Z);if(this.activeRecordedAudio?.element===G)this.activeRecordedAudio=null},H=()=>{if(K)return;K=!0,U(),X()},_=()=>{if(K)return;K=!0,U(),j(Error(`[tts] recorded audio failed to play: ${J.src}`))};this.activeRecordedAudio={element:G,cancel:()=>{if(K)return;K=!0,U(),G.pause(),X()}},G.addEventListener("ended",H),G.addEventListener("error",_),G.addEventListener("playing",B);let A=Q.fragment?.endSeconds;if(A!==void 0)Z=setInterval(()=>{if(G.currentTime>=A)H()},100);Promise.resolve(G.play()).then(B).catch(_)}).finally(()=>{if(this.activeRecordedAudio?.element===G)this.activeRecordedAudio=null;G.pause(),G.removeAttribute("src")})}cancelRecordedAudio(){let Q=this.activeRecordedAudio;if(!Q)return;this.activeRecordedAudio=null,Q.cancel()}async speakCatalogChunkOnce(Q,Y){if(!this.provider)return;if(this.lastRenderedRegionTarget=null,Q.audio){this.runWhenPlaybackStarts(Y,()=>{this.highlightCatalogRegion(Q)}),await this.playRecordedAudio(Q.audio,()=>{this.notifyPlaybackStarted(Y)});return}let J=Q.regionElement||Q.sourceElement||this.currentContentElement,G=J?z6({contentRoot:J,chunks:[Q]})[0]:null,X=this.ttsConfig.mathTokenHighlighting!==!1,j=G?N6({chunks:[G],mathTokenHighlighting:X}):null;if(this.runWhenPlaybackStarts(Y,()=>{if(j&&G&&Q.mathAlignment)this.renderHighlightDecision(j.resolveInitial(G.id));else this.highlightCatalogRegion(Q)}),!(Q.sourceElement&&(Q.mathAlignment&&Q.mathAlignment.speech.tokens.length>0||Q.mathAlignments&&Q.mathAlignments.length>0||Q.alignment&&Q.visibleMap&&(Q.playbackMode==="exact-word"||Q.playbackMode==="anchor-span")))){let U=this.provider,H=U.onWordBoundary;U.onWordBoundary=void 0;try{await U.speak(Q.speechText)}finally{if(this.provider===U&&Y===this.speakRunId&&U.onWordBoundary===void 0)U.onWordBoundary=H}return}let q=this.provider,K=q.onWordBoundary,B=(U,H,_)=>{if(Y!==this.speakRunId)return;if(j&&G){let A=G.offsetSpace==="unsupported"?"unknown":G.offsetSpace;this.renderHighlightDecision(j.resolveBoundary({chunkId:G.id,word:U,position:H,length:_,providerOffsetSpace:A}));return}};q.onWordBoundary=B;try{await q.speak(Q.speechText)}finally{if(this.provider===q&&Y===this.speakRunId&&q.onWordBoundary===B)q.onWordBoundary=K}}async executeSpeakPlayback(Q){if(Q.speechChunks?.length&&this.provider){for(let Y=0;Y<Q.speechChunks.length;Y++){if(Q.runId!==this.speakRunId)return;this.currentSeekSegmentIndex=Y;let J=this.seekSegments[Y];if(J)this.currentBoundaryOffset=J.startOffset;let G=Q.speechChunks[Y];await this.speakCatalogChunk(G,Q.runId)}return}if(Q.shouldUsePlan&&this.currentContentElement){let Y=this.seekSegments;if(Y.length>0)await this.speakWithPlan(Y,Q.runId,{highlightMode:Q.highlightMode});else if(this.provider)await this.provider.speak(Q.contentToSpeak);return}if(this.provider)await this.provider.speak(Q.contentToSpeak)}clearHighlightsAndTracking(){if(this.pendingPlaybackStartHighlights=[],this.activePlaybackRate=null,this.highlightCoordinator)this.highlightCoordinator.clearTTS();this.lastRenderedRegionTarget=null,this.currentContentElement=null,this.normalizedToDOM.clear(),this.currentBoundaryOffset=0,this.activeWordBoundaryOffset=0,this.seekSegments=[],this.playbackChunks=[],this.sentenceHighlightSegments=[],this.currentSeekSegmentIndex=0,this.activeSentenceStartOffset=null}async speakRange(Q,Y){if(!this.provider)throw Error("TTS service not initialized");if(q1(Q.commonAncestorContainer)){console.warn("[tts] selection lies inside content marked not-to-be-spoken; nothing was spoken. Selecting a node and pressing read-aloud must not become a way around suppression.");return}let G=Y?.contentRoot||null;if(!G){let U=Q.commonAncestorContainer;G=U.nodeType===Node.ELEMENT_NODE?U:U.parentElement}if(!G)return;let X=Q8(Q,G),j=X.text.trim();if(!j){if(X.filtered)console.warn("[tts] every part of the selection is either hidden or marked not-to-be-spoken; nothing was spoken.");return}let Z=document.createRange();Z.selectNodeContents(G),Z.setEnd(Q.startContainer,Q.startOffset);let q=Q8(Z,G).text,K=S(q),B=K.length+(/\s$/.test(q)&&K?1:0);this.debugLog("[TTSService] speakRange offset calculation:",{selectedText:j,textBeforeRange:q.substring(0,100),offset:B,rootTag:G.tagName}),await this.speak(j,{contentElement:G,ignoreCatalogs:!0,wordBoundaryOffset:B})}pause(){if(!this.provider)return;if(this.state===E.PLAYING)this.activeRecordedAudio?.element.pause(),this.provider.pause(),this.setState(E.PAUSED)}resume(){if(!this.provider)return;if(this.state===E.PAUSED){let Q=this.activeRecordedAudio?.element;if(Q)Promise.resolve(Q.play()).catch(()=>{});this.provider.resume(),this.setState(E.PLAYING)}}normalizePlaybackRate(Q){if(!Number.isFinite(Q))return 1;return Math.max(0.25,Math.min(4,Q))}async restartFromSeekIndex(Q){if(!this.provider||this.seekSegments.length===0)return;let Y=Math.max(0,Math.min(this.seekSegments.length-1,Q)),J=this.playbackChunks.length?this.playbackChunks.slice(Y):null;this.speakRunId+=1,this.clearPlaybackStartBarrier(),this.cancelRecordedAudio(),this.provider.onWordBoundary=void 0,this.provider.stop(),this.currentSeekSegmentIndex=Y;let G=++this.speakRunId,X=this.seekSegments.slice(Y);this.highlightCoordinator?.clearTTS(),this.activeSentenceStartOffset=null,this.setState(E.LOADING);let j=this.installPlaybackStartBarrier(G,!!J?.[0]?.audio);if(!j)this.setState(E.PLAYING);this.activePlaybackRate=this.normalizePlaybackRate(Number(this.ttsConfig.rate??1));try{if(this.configureWordBoundaryHighlighting({highlightMode:this.activeHighlightMode,wordBoundaryOffset:this.activeWordBoundaryOffset}),J)for(let Z=0;Z<J.length;Z++){if(G!==this.speakRunId)return;let q=Y+Z;this.currentSeekSegmentIndex=q;let K=this.seekSegments[q];if(K)this.currentBoundaryOffset=K.startOffset;await this.speakCatalogChunk(J[Z],G)}else await this.speakWithPlan(X,G,{highlightMode:this.activeHighlightMode});if(G!==this.speakRunId)return;this.setState(E.IDLE),this.clearHighlightsAndTracking(),this.highlightTargetResolverProvider=null}catch(Z){if(G!==this.speakRunId)return;throw this.lastError=Z instanceof Error?Z.message:String(Z),this.setState(E.ERROR),this.clearHighlightsAndTracking(),this.highlightTargetResolverProvider=null,Z}finally{this.clearPlaybackStartBarrier(j)}}async setPlaybackRate(Q){if(!this.provider)throw Error("TTSService not initialized. Call initialize() first.");let Y=this.normalizePlaybackRate(Q),J=this.pendingPlaybackRateRequest;if(J?.rate===Y){await J.promise;return}let G=++this.playbackRateRequestId,X=this.playbackRateWriteQueue.then(async()=>{let q=this.speakRunId;if(G!==this.playbackRateRequestId)return{didUpdate:!1,playbackRunId:q};let K=this.normalizePlaybackRate(Number(this.ttsConfig.rate??1));if(Y===K)return{didUpdate:!1,playbackRunId:q};return await this.updateSettings({rate:Y}),{didUpdate:!0,playbackRunId:q}});this.playbackRateWriteQueue=X.then(()=>{return},()=>{return});let j=X.then(async(q)=>{if(G!==this.playbackRateRequestId||q.playbackRunId!==this.speakRunId)return;let K=this.activePlaybackRate!==null&&this.activePlaybackRate!==Y;if(!q.didUpdate&&!K)return;if(this.state!==E.PLAYING&&this.state!==E.LOADING||!this.currentText||this.seekSegments.length===0||this.hasExplicitBreakSemantics(this.currentText))return;await this.restartFromSeekIndex(this.getCurrentSeekSegmentIndex())}),Z;Z=j.finally(()=>{if(this.pendingPlaybackRateRequest?.promise===Z)this.pendingPlaybackRateRequest=null}),this.pendingPlaybackRateRequest={rate:Y,promise:Z},await Z}async seekBy(Q){if(!this.provider||!this.currentText)return;if(this.state!==E.PLAYING&&this.state!==E.PAUSED)return;if(this.hasExplicitBreakSemantics(this.currentText))return;if(this.seekSegments.length===0)return;let Y=Number.isFinite(Q)?Math.trunc(Q):0;if(Y===0)return;let J=this.getCurrentSeekSegmentIndex(),G=Math.max(0,Math.min(this.seekSegments.length-1,J+Y));if(G===J)return;await this.restartFromSeekIndex(G)}async seekForward(Q=1){let Y=Number.isFinite(Q)?Math.max(1,Math.trunc(Q)):1;await this.seekBy(Y)}async seekBackward(Q=1){let Y=Number.isFinite(Q)?Math.max(1,Math.trunc(Q)):1;await this.seekBy(-Y)}stop(){if(!this.provider)return;if(this.speakRunId+=1,this.clearPlaybackStartBarrier(),this.cancelRecordedAudio(),this.provider.onWordBoundary=void 0,this.provider.stop(),this.highlightTargetResolverProvider=null,this.setState(E.IDLE),this.currentText=null,this.highlightCoordinator)this.highlightCoordinator.clearTTS();this.lastRenderedRegionTarget=null,this.currentContentElement=null,this.normalizedToDOM.clear(),this.currentBoundaryOffset=0,this.activeWordBoundaryOffset=0,this.seekSegments=[],this.playbackChunks=[],this.sentenceHighlightSegments=[],this.currentSeekSegmentIndex=0,this.activeSentenceStartOffset=null,this.activePlaybackRate=null}requestControlHandoff(){if(typeof window>"u")return;let Q={source:"host"};window.dispatchEvent(new CustomEvent(P6,{detail:Q}))}isPlaying(){return this.state===E.PLAYING}isPaused(){return this.state===E.PAUSED}getState(){return this.state}getCurrentText(){return this.currentText}getLastError(){return this.lastError}onStateChange(Q,Y){if(!this.listeners.has(Q))this.listeners.set(Q,new Set);this.listeners.get(Q).add(Y)}offStateChange(Q,Y){let J=this.listeners.get(Q);if(J){if(J.delete(Y),J.size===0)this.listeners.delete(Q)}}setState(Q){if(this.state===Q)return;let Y=this.state;this.state=Q;for(let J of this.listeners.values())for(let G of J)G(Q);if(this.emitTelemetry("pie-tool-playback-state-changed",{toolId:"textToSpeech",providerId:"tts",previousState:Y,state:Q}),Q===E.PLAYING){let J=Y===E.PAUSED?"pie-tool-playback-resume":"pie-tool-playback-start";this.emitTelemetry(J,{toolId:"textToSpeech",providerId:"tts",previousState:Y,state:Q});return}if(Q===E.PAUSED){this.emitTelemetry("pie-tool-playback-pause",{toolId:"textToSpeech",providerId:"tts",previousState:Y,state:Q});return}if(Q===E.ERROR){this.emitTelemetry("pie-tool-playback-error",{toolId:"textToSpeech",providerId:"tts",previousState:Y,state:Q,message:this.lastError||void 0});return}if(Q===E.IDLE&&(Y===E.PLAYING||Y===E.PAUSED||Y===E.LOADING))this.emitTelemetry("pie-tool-playback-stop",{toolId:"textToSpeech",providerId:"tts",previousState:Y,state:Q})}}var p2=new Set(["reserved-row","expanding-row","floating-overlay","left-aligned"]),$6=(Q)=>Q&&typeof Q==="object"?Q:{},g2=(Q)=>Q==="polly"||Q==="google"||Q==="server",c=(Q,Y)=>Q===void 0?Y:Q,c2=(Q,Y="left-aligned")=>typeof Q==="string"&&p2.has(Q)?Q:Y,y4=Object.freeze([0.8,1.25]),x4=Object.freeze([{rate:0.8,label:"Slow",ariaLabel:"Slow speed"},{rate:1,label:"Normal",ariaLabel:"Normal speed",default:!0},{rate:1.25,label:"Fast",ariaLabel:"Fast speed"}]);var f4=Object.freeze([0.8,1,1.25]);var l2=(Q)=>{let Y={...Q,layoutMode:c2(Q.layoutMode)},J=Q.backend||"browser";if(!g2(J))return Y;let G={...Y,apiEndpoint:c(Y.apiEndpoint,"/api/tts"),transportMode:c(Y.transportMode,"pie"),endpointValidationMode:c(Y.endpointValidationMode,"voices"),validateEndpoint:c(Y.validateEndpoint,!0),includeAuthOnAssetFetch:c(Y.includeAuthOnAssetFetch,!1),rate:c(Y.rate,1),language:c(Y.language,"en-US")};if(J==="polly")return{...G,defaultVoice:c(G.defaultVoice,"Joanna"),engine:c(G.engine,"neural"),format:c(G.format,"mp3"),speechMarksMode:c(G.speechMarksMode,"word+sentence")};if(J==="google")return{...G,defaultVoice:c(G.defaultVoice,"en-US-Wavenet-A")};return G},w6=(Q)=>{let Y=$6(Q),J=$6(Y.settings);return l2({...Y,...J})},N8=(Q)=>Q.backend||"browser",d2=(Q,Y)=>{if(Y==="polly"||Y==="google")return Y;if(Y==="server")return Q.serverProvider||Q.provider;return Q.serverProvider||Q.provider},i2=(Q,Y)=>Q.transportMode||(Y==="custom"?"custom":"pie"),R6=(Q)=>{let Y=N8(Q),J=d2(Q,Y),G=i2(Q,J),X=z7(Q.mathSpeech);return{voice:Q.defaultVoice,rate:Q.rate,pitch:Q.pitch,providerOptions:{...Q.language?{locale:Q.language}:{},...Y==="polly"&&Q.engine?{engine:Q.engine}:{},...Y==="polly"&&typeof Q.sampleRate==="number"?{sampleRate:Q.sampleRate}:{},...Y==="polly"&&Q.format?{format:Q.format}:{},...Y==="polly"?{speechMarkTypes:Q.speechMarksMode==="word+sentence"?["word","sentence"]:["word"]}:{},...G==="custom"&&typeof Q.cache==="boolean"?{cache:Q.cache}:{},...G==="custom"&&Q.speedRate?{speedRate:Q.speedRate}:{},...G==="custom"&&Q.lang_id?{lang_id:Q.lang_id}:{},...X?{mathSpeech:X}:{}},apiEndpoint:Q.apiEndpoint,provider:J,language:Q.language,transportMode:G,endpointMode:Q.endpointMode,endpointValidationMode:Q.endpointValidationMode,includeAuthOnAssetFetch:Q.includeAuthOnAssetFetch,validateEndpoint:Q.validateEndpoint,...typeof Q.mathTokenHighlighting==="boolean"?{mathTokenHighlighting:Q.mathTokenHighlighting}:{}}};class F1{providers=new Map;configs=new Map;initialized=new Map;initializationPromises=new Map;async emitTelemetry(Q,Y,J){try{await Q.onTelemetry?.(Y,J)}catch(G){console.warn("[ToolProviderRegistry] Telemetry callback failed:",G)}}register(Q,Y){if(this.providers.has(Q)){console.warn(`[ToolProviderRegistry] Provider "${Q}" already registered, skipping`);return}if(this.providers.set(Q,Y.provider),this.configs.set(Q,Y),this.initialized.set(Q,!1),console.log(`[ToolProviderRegistry] Registered provider "${Q}" (${Y.provider.providerName})`),Y.lazy===!1)this.initialize(Q).catch((J)=>{console.error(`[ToolProviderRegistry] Failed to initialize provider "${Q}":`,J)})}async initialize(Q){if(this.initialized.get(Q))return;let Y=this.initializationPromises.get(Q);if(Y)return Y;let J=this._doInitialize(Q);this.initializationPromises.set(Q,J);try{await J}finally{this.initializationPromises.delete(Q)}}async _doInitialize(Q){let Y=this.providers.get(Q),J=this.configs.get(Q);if(!Y||!J)throw Error(`[ToolProviderRegistry] Provider "${Q}" not registered`);let G={...J.config},X=(Z)=>{if(!Z||typeof Z!=="object")return"unknown";let q=Z;return(typeof q.backend==="string"?q.backend:typeof q.provider==="string"?q.provider:typeof q.serverProvider==="string"?q.serverProvider:typeof q.providerId==="string"?q.providerId:"")||"unknown"},j=Date.now();if(await this.emitTelemetry(J,"pie-tool-init-start",{toolId:Q,providerId:Q,backend:X(G),operation:"provider-initialize"}),Y.requiresAuth&&J.authFetcher){let Z=Date.now();await this.emitTelemetry(J,"pie-tool-backend-call-start",{toolId:Q,providerId:Q,backend:X(G),operation:"auth-fetch"}),console.log(`[ToolProviderRegistry] Fetching auth for "${Q}"...`);try{let q=await J.authFetcher();G={...G,...q},await this.emitTelemetry(J,"pie-tool-backend-call-success",{toolId:Q,providerId:Q,backend:X(G),operation:"auth-fetch",duration:Date.now()-Z})}catch(q){throw await this.emitTelemetry(J,"pie-tool-backend-call-error",{toolId:Q,providerId:Q,backend:X(G),operation:"auth-fetch",duration:Date.now()-Z,errorType:"ProviderAuthFetchError",message:q instanceof Error?q.message:String(q)}),console.error(`[ToolProviderRegistry] Auth fetch failed for "${Q}":`,q),Error(`Failed to fetch auth credentials for provider "${Q}"`)}}try{await Y.initialize(G),this.initialized.set(Q,!0),await this.emitTelemetry(J,"pie-tool-init-success",{toolId:Q,providerId:Q,backend:X(G),operation:"provider-initialize",duration:Date.now()-j}),console.log(`[ToolProviderRegistry] Provider "${Q}" initialized`)}catch(Z){throw await this.emitTelemetry(J,"pie-tool-init-error",{toolId:Q,providerId:Q,backend:X(G),operation:"provider-initialize",duration:Date.now()-j,errorType:"ProviderInitializationError",message:Z instanceof Error?Z.message:String(Z)}),console.error(`[ToolProviderRegistry] Initialization failed for "${Q}":`,Z),Z}}async getProvider(Q,Y=!0){console.log("[ToolProviderRegistry] getProvider called",{providerId:Q,autoInitialize:Y,isRegistered:this.providers.has(Q),isInitialized:this.initialized.get(Q),allProviderIds:Array.from(this.providers.keys())});let J=this.providers.get(Q);if(!J)throw console.error("[ToolProviderRegistry] Provider not found:",{requestedId:Q,availableProviders:Array.from(this.providers.keys())}),Error(`[ToolProviderRegistry] Provider "${Q}" not registered`);if(Y&&!this.initialized.get(Q))console.log("[ToolProviderRegistry] Auto-initializing provider:",Q),await this.initialize(Q);return console.log("[ToolProviderRegistry] Returning provider:",{providerId:Q,providerName:J.providerName,isReady:J.isReady()}),J}getProvidersByCategory(Q){return Array.from(this.providers.entries()).filter(([Y,J])=>J.category===Q).map(([Y])=>Y)}getProviderIds(){return Array.from(this.providers.keys())}has(Q){return this.providers.has(Q)}isInitialized(Q){return this.initialized.get(Q)===!0}isInitializing(Q){return this.initializationPromises.has(Q)}async unregister(Q){let Y=this.providers.get(Q);if(Y){let J=this.initializationPromises.get(Q);if(J)try{await J}catch{}Y.destroy(),this.providers.delete(Q),this.configs.delete(Q),this.initialized.delete(Q),this.initializationPromises.delete(Q),console.log(`[ToolProviderRegistry] Unregistered provider "${Q}"`)}}async destroy(){let Q=Array.from(this.providers.keys());await Promise.all(Q.map((Y)=>this.unregister(Y))),console.log("[ToolProviderRegistry] Registry destroyed")}}var s2=(Q)=>`No assessment is bound, so no policy source could grant "${Q}"`;function E6(Q,Y,J){let G=Y.decisions[0],X=Array.from(Y.perToolFlags.values())[0],j=G?.action==="enable",Z=G?.reason??`Feature "${Q}" not configured`;return{featureId:Q,granted:j,action:G?.action??"skip",rule:G?.rule??"pnp-support",precedence:G?.precedence??6,sourceType:G?.sourceType??"system",reason:J.assessmentBound||j?Z:s2(Q),required:Boolean(X?.required),parameters:X?.settings,assessmentBound:J.assessmentBound}}class A1{provenance;stepCounter=0;constructor(Q){this.provenance={contextId:Q,resolvedAt:new Date,sources:{},features:new Map,decisionLog:[],summary:{totalFeatures:0,enabled:0,blocked:0,notConfigured:0,bySource:{},byRule:{}}}}addSource(Q,Y){let J={id:Y.id,name:Y.name??Y.id};switch(Q){case"organization":this.provenance.sources.organization={...J,pnpDefaults:Y.config};break;case"assessment":this.provenance.sources.assessment={...J,settings:Y.config};break;case"section":this.provenance.sources.section={...J,settings:Y.config};break;case"item":this.provenance.sources.item={...J,settings:Y.config};break;case"student":this.provenance.sources.student={id:Y.id,pnpProfile:Y.config};break;case"host":this.provenance.sources.host={id:Y.id,config:Y.config};break}return this}addDecision(Q){let Y={step:++this.stepCounter,precedence:Q.precedence,rule:Q.rule,featureId:Q.featureId,action:Q.action,source:{type:Q.sourceType,id:Q.sourceId,name:Q.sourceName},reason:Q.reason,value:Q.value,timestamp:new Date};this.provenance.decisionLog.push(Y);let J=this.provenance.features.get(Q.featureId);if(!J)J={featureId:Q.featureId,finalState:"not-configured",allDecisions:[],explanation:""},this.provenance.features.set(Q.featureId,J);if(J.allDecisions.push(Y),Q.action==="advisory"){if(J.finalState==="not-configured")J.finalState="advisory-only"}else if(Q.action!=="skip"){if(!J.winningDecision||Y.precedence<J.winningDecision.precedence)J.winningDecision=Y,J.finalState=Y.action==="enable"?"enabled":"blocked"}return this.provenance.summary.bySource[Q.sourceType]=(this.provenance.summary.bySource[Q.sourceType]||0)+1,this.provenance.summary.byRule[Q.rule]=(this.provenance.summary.byRule[Q.rule]||0)+1,this}reconcileFinalStates(Q){for(let Y of Q){let J=this.provenance.features.get(Y);if(!J){J={featureId:Y,finalState:"enabled",allDecisions:[],explanation:""},this.provenance.features.set(Y,J);continue}J.finalState="enabled"}for(let Y of this.provenance.features.values()){if(Q.has(Y.featureId))continue;let J=Y.allDecisions.some((X)=>X.action!=="skip"&&X.action!=="advisory"),G=Y.allDecisions.some((X)=>X.action==="advisory");if(J)Y.finalState="blocked";else if(G)Y.finalState="advisory-only";else Y.finalState="not-configured"}return this}build(){for(let Q of this.provenance.features.values())Q.explanation=n2(Q);for(let Q of this.provenance.features.values())if(this.provenance.summary.totalFeatures++,Q.finalState==="enabled")this.provenance.summary.enabled++;else if(Q.finalState==="blocked")this.provenance.summary.blocked++;else this.provenance.summary.notConfigured++;return this.provenance}}function n2(Q){if(!Q.winningDecision){if(Q.finalState==="advisory-only"){let j=Q.allDecisions.find((Z)=>Z.action==="advisory");return j?`Feature "${Q.featureId}" was kept in its host-decided state; ${j.reason}`:`Feature "${Q.featureId}" carries an advisory note.`}return`Feature "${Q.featureId}" was not configured at any level.`}let Y=Q.winningDecision,J=Y.source.name||Y.source.type,G=`Feature "${Q.featureId}" is ${Q.finalState}.
215
+ `,document.head.appendChild(Q)}highlightTTSWord(Q,Y,J){if(!this.ttsWordHighlight)return;this.applyAdaptiveTTSStyle(Q.parentElement),this.clearTTSWord();let G=document.createRange();G.setStart(Q,Y),G.setEnd(Q,J),this.ttsWordHighlight.add(G)}highlightTTSWordElement(Q){if(!this.ttsWordHighlight)return;this.applyAdaptiveTTSStyle(Q),this.clearTTSWord(),Q.setAttribute("data-pie-tts-word-element","true"),this.ttsWordElementHighlights.add(Q)}highlightTTSSentence(Q){if(!this.ttsSentenceHighlight)return;let Y=Q[0]?.startContainer,J=Y?.nodeType===Node.ELEMENT_NODE?Y:Y?.parentElement;this.applyAdaptiveTTSStyle(J),this.clearTTSSentence();for(let G of Q)this.ttsSentenceHighlight.add(G);this.highlightTTSElementFallbacks(Q)}highlightTTSSentenceElements(Q){if(!this.ttsSentenceHighlight)return;this.applyAdaptiveTTSStyle(Q[0]||null),this.clearTTSSentence();for(let Y of Q)Y.setAttribute("data-pie-tts-sentence-element","true"),this.ttsSentenceElementHighlights.add(Y)}static SENTENCE_FALLBACK_SELECTOR="math, mjx-container, svg, img, canvas, [role='img']";static WORD_FALLBACK_SELECTOR="svg, img, canvas, [role='img']";highlightTTSElementFallbacks(Q){if(typeof Element>"u")return;this.highlightElementFallbacks(Q,"data-pie-tts-sentence-element",this.ttsSentenceElementHighlights,m7.SENTENCE_FALLBACK_SELECTOR)}highlightTTSWordElementFallbacks(Q){if(typeof Element>"u")return;this.highlightElementFallbacks(Q,"data-pie-tts-word-element",this.ttsWordElementHighlights,m7.WORD_FALLBACK_SELECTOR)}highlightElementFallbacks(Q,Y,J,G){for(let X of Q){let j=X.commonAncestorContainer.nodeType===Node.ELEMENT_NODE?X.commonAncestorContainer:X.commonAncestorContainer.parentElement;if(!j)continue;let Z=[],q=X.startContainer.nodeType===Node.ELEMENT_NODE?X.startContainer:X.startContainer.parentElement,K=X.endContainer.nodeType===Node.ELEMENT_NODE?X.endContainer:X.endContainer.parentElement;for(let B of[q,K]){let U=B;while(U){if(U.matches?.(G))Z.push(U);U=U.parentElement}}if(j.matches?.(G))Z.push(j);Z.push(...Array.from(j.querySelectorAll(G)));for(let B of new Set(Z)){try{if(!X.intersectsNode(B)&&!B.contains(q)&&!B.contains(K))continue}catch{continue}B.setAttribute(Y,"true"),J.add(B)}}}clearTTSWord(){if(!this.ttsWordHighlight)return;this.ttsWordHighlight.clear();for(let Q of this.ttsWordElementHighlights)Q.removeAttribute("data-pie-tts-word-element");this.ttsWordElementHighlights.clear()}clearTTSSentence(){if(!this.ttsSentenceHighlight)return;this.ttsSentenceHighlight.clear();for(let Q of this.ttsSentenceElementHighlights)Q.removeAttribute("data-pie-tts-sentence-element");this.ttsSentenceElementHighlights.clear()}clearTTS(){this.clearTTSWord(),this.clearTTSSentence()}addAnnotation(Q,Y=D7.YELLOW){let J=`annotation-${this.nextAnnotationId++}`,G=Q.cloneRange(),X={id:J,range:G,type:m.ANNOTATION,color:Y,timestamp:Date.now()};this.annotations.set(J,X);let j=this.colorHighlights.get(Y);if(j)j.add(G);return J}removeAnnotation(Q){let Y=this.annotations.get(Q);if(!Y){console.warn(`[HighlightCoordinator] Annotation ${Q} not found`);return}console.log(`[HighlightCoordinator] Removing annotation ${Q} (color: ${Y.color})`);let J=this.colorHighlights.get(Y.color);if(J){let G=J.delete(Y.range);console.log("[HighlightCoordinator] Highlight.delete() returned:",G)}this.annotations.delete(Q),console.log(`[HighlightCoordinator] Annotation ${Q} removed from map. Remaining:`,this.annotations.size)}clearAnnotations(){for(let Q of this.colorHighlights.values())Q.clear();this.annotations.clear()}getAnnotations(){return Array.from(this.annotations.values())}getAnnotation(Q){return this.annotations.get(Q)??null}changeAnnotationColor(Q,Y){let J=this.annotations.get(Q);if(!J)return;let G=J.color;if(G===Y)return;let X=this.colorHighlights.get(G);if(X)X.delete(J.range);J.color=Y;let j=this.colorHighlights.get(Y);if(j)j.add(J.range)}exportAnnotations(Q=document.body){return this.getAnnotations().map((Y)=>({...this.rangeSerializer.serialize(Y.range,Q),id:Y.id,color:Y.color,timestamp:Y.timestamp}))}importAnnotations(Q,Y=document.body){let J=0;for(let G of Q){let X=this.rangeSerializer.deserialize(G,Y);if(X)this.addAnnotation(X,G.color),J++}return J}highlightRange(Q,Y,J=D7.YELLOW){if(!this.supported)return;switch(Y){case m.TTS_WORD:case m.TTS_SENTENCE:{let G=Y===m.TTS_WORD?this.ttsWordHighlight:this.ttsSentenceHighlight;if(G){if(G.clear(),G.add(Q),Y===m.TTS_WORD){for(let X of this.ttsWordElementHighlights)X.removeAttribute("data-pie-tts-word-element");this.ttsWordElementHighlights.clear(),this.highlightTTSWordElementFallbacks([Q])}}break}case m.ANNOTATION:this.addAnnotation(Q,J);break}}clearHighlights(Q){if(!this.supported)return;switch(Q){case m.TTS_WORD:this.clearTTSWord();break;case m.TTS_SENTENCE:this.clearTTSSentence();break;case m.ANNOTATION:this.clearAnnotations();break}}clearAll(){if(!this.supported)return;this.clearTTS(),this.clearAnnotations()}isSupported(){return this.supported}updateTTSHighlightStyle(Q,Y){if(!this.supported)return;if(typeof document>"u")return;if(!document.getElementById("pie-highlight-styles"))return;let X=((j)=>{let Z=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(j);return Z?{r:parseInt(Z[1],16),g:parseInt(Z[2],16),b:parseInt(Z[3],16)}:null})(Q);if(!X)return;this.explicitTTSColorOverride={color:`rgb(${X.r}, ${X.g}, ${X.b})`,opacity:Math.max(0.2,Math.min(0.95,Y))},this.applyAdaptiveTTSStyle()}destroy(){if(!this.supported)return;if(this.clearTTS(),this.clearAnnotations(),typeof document<"u"){let Q=document.getElementById("pie-highlight-styles");if(Q)Q.remove()}this.themeObserver?.disconnect(),this.themeObserver=null}}function W9(Q){return(...Y)=>{console.debug(`[${Q}]`,...Y)}}var o=W9("ToolCoordinator"),X7;(function(Q){Q[Q.BASE=0]="BASE",Q[Q.TOOL=1000]="TOOL",Q[Q.MODAL=2000]="MODAL",Q[Q.CONTROL=3000]="CONTROL",Q[Q.HIGHLIGHT=4000]="HIGHLIGHT"})(X7||(X7={}));class t1{config;tools=new Map;layerCounters=new Map;listeners=new Set;visibilityState=new Map;constructor(Q={}){this.config=Q,this.layerCounters.set(X7.BASE,0),this.layerCounters.set(X7.TOOL,0),this.layerCounters.set(X7.MODAL,0),this.layerCounters.set(X7.CONTROL,0),this.layerCounters.set(X7.HIGHLIGHT,0)}subscribe(Q){return this.listeners.add(Q),()=>{this.listeners.delete(Q)}}notifyListeners(){this.listeners.forEach((Q)=>Q())}registerTool(Q,Y,J,G=X7.MODAL){if(o("registerTool called:",{id:Q,name:Y,hasElement:!!J,layer:G}),this.tools.has(Q)){o(`Tool ${Q} is already registered`);return}let X=this.visibilityState.get(Q)??!1;if(!J){this.tools.set(Q,{id:Q,name:Y,element:null,layer:G,isVisible:X,baseZIndex:G}),o("Tool registered without element:",Q);return}let j=G+this.getNextLayerOffset(G);J.style.zIndex=String(j),J.style.display=X?"":"none";let Z=()=>this.bringToFront(J);if(J.addEventListener("mousedown",Z),this.tools.set(Q,{id:Q,name:Y,element:J,layer:G,isVisible:X,baseZIndex:j,mouseDownHandler:Z}),X)this.bringToFront(J);o("Tool registered with element:",Q)}unregisterTool(Q){let Y=this.tools.get(Q);if(!Y)return;if(Y.element&&Y.mouseDownHandler)Y.element.removeEventListener("mousedown",Y.mouseDownHandler);this.tools.delete(Q)}releaseTool(Q){this.unregisterTool(Q),this.visibilityState.delete(Q)}showTool(Q){let Y=this.tools.get(Q);if(!Y){o(`Tool ${Q} not found`);return}if(Y.element)Y.element.style.display="",this.bringToFront(Y.element);Y.isVisible=!0,this.visibilityState.set(Q,!0),this.notifyListeners()}hideTool(Q){let Y=this.tools.get(Q);if(!Y){o(`Tool ${Q} not found`);return}if(Y.element)Y.element.style.display="none";Y.isVisible=!1,this.visibilityState.set(Q,!1),this.notifyListeners()}toggleTool(Q){o("toggleTool called for:",Q);let Y=this.tools.get(Q);if(!Y){o(`Tool ${Q} not found. Registered tools:`,Array.from(this.tools.keys()));return}if(o("Tool found, current visibility:",Y.isVisible),Y.isVisible)this.hideTool(Q);else this.showTool(Q)}isToolVisible(Q){let Y=this.tools.get(Q);if(Y)return Y.isVisible;return this.visibilityState.get(Q)??!1}bringToFront(Q){let Y=Array.from(this.tools.values()).find((X)=>X.element===Q);if(!Y)return;let J=this.getMaxZIndexInLayer(Y.layer),G=Math.max(J+1,Y.layer+1);Q.style.zIndex=String(G),Y.baseZIndex=G}getRegisteredTools(){return Array.from(this.tools.keys())}getToolElement(Q){return this.tools.get(Q)?.element??null}getNextLayerOffset(Q){let Y=this.layerCounters.get(Q)??0;return this.layerCounters.set(Q,Y+1),Y}getMaxZIndexInLayer(Q){let Y=Q;for(let J of this.tools.values())if(J.layer===Q)Y=Math.max(Y,J.baseZIndex);return Y}resetZIndices(){for(let Q of this.tools.values())if(Q.element)Q.element.style.zIndex=String(Q.baseZIndex)}updateToolElement(Q,Y){let J=this.tools.get(Q);if(!J){o(`Tool ${Q} not found`);return}if(J.element&&J.mouseDownHandler)J.element.removeEventListener("mousedown",J.mouseDownHandler);let G=()=>this.bringToFront(Y);if(Y.addEventListener("mousedown",G),J.element=Y,J.mouseDownHandler=G,Y.style.zIndex=String(J.baseZIndex),J.isVisible)Y.style.display="";else Y.style.display="none"}hideAllTools(){for(let Q of this.tools.keys())this.hideTool(Q);this.notifyListeners()}getToolState(Q){let Y=this.tools.get(Q);if(!Y)return;return{id:Y.id,name:Y.name,isVisible:Y.isVisible,element:Y.element??null,layer:Y.layer}}getVisibleTools(){return Array.from(this.tools.values()).filter((Q)=>Q.isVisible).map((Q)=>({id:Q.id,name:Q.name,isVisible:Q.isVisible,element:Q.element??null,layer:Q.layer}))}}var q3=/^[a-z][a-z0-9+.-]*:/i,K3=new Set(["http:","https:","data:","blob:"]);function W3(Q){if(typeof Q!=="string")return!1;let Y=Q.trim();if(!Y)return!1;if(Y.startsWith("//")||!q3.test(Y))return!0;let J=Y.slice(0,Y.indexOf(":")+1).toLowerCase();return K3.has(J)}function U9(Q){if(!Array.isArray(Q))return[];let Y=[];for(let J of Q){if(!J||typeof J!=="object")continue;let G=J;if(!W3(G.src))continue;let X={src:G.src.trim()};if(typeof G.type==="string"&&G.type.trim())X.type=G.type.trim();if(Number.isFinite(G.width))X.width=G.width;if(Number.isFinite(G.height))X.height=G.height;if(Y.some((j)=>j.src===X.src))continue;Y.push(X)}return Y}function B9(Q){if(!Q||typeof Q!=="object")return;let Y=Q,J=Number(Y.startSeconds);if(!Number.isFinite(J)||J<0)return;let G=Number(Y.endSeconds);if(!Number.isFinite(G)||G<=J)return{startSeconds:J};return{startSeconds:J,endSeconds:G}}function D9(Q){if(typeof Q!=="string")return;return Q.trim()||void 0}function V9(Q,Y){if(!Y)return Q;if(Q.includes("#"))return Q;let J=Y.endSeconds!==void 0?`,${Y.endSeconds}`:"";return`${Q}#t=${Y.startSeconds}${J}`}function H9(Q){if(!Q)return null;let Y=Q.payload;if(!Y||typeof Y!=="object")return null;let J=Y.media;if(!J||typeof J!=="object")return console.warn("[spoken-audio] card carries a `payload` with no `media`; recorded speech needs `media.sources`, so this card is ignored and read-aloud falls back to the script or generated speech"),null;if(J.kind!==void 0&&J.kind!=="audio")return console.warn(`[spoken-audio] card's media is kind "${J.kind}", not "audio"; a spoken card carries recorded speech, so this card is ignored`),null;let G=U9(J.sources);if(G.length===0)return console.warn("[spoken-audio] card's `media.sources` yielded no usable URL; read-aloud falls back to the script or generated speech"),null;return{sources:G,fragment:B9(Y.fragment),label:D9(J.label)}}var R7=(Q,Y)=>{let J=Y?.useSentenceSegmenter!==!1;try{if(!J)throw Error("Segmenter disabled by policy");let q=globalThis.Intl?.Segmenter;if(typeof q==="function"){let K=new q(Y?.locale,{granularity:"sentence"}),B=Array.from(K.segment(Q)).map((U)=>({text:U.segment,offset:U.index})).filter((U)=>U.text.trim().length>0);if(B.length>0)return B}}catch{}let G=/[^.!?]+(?:[.!?]+|$)/g,X=Q.match(G)||[Q],j=[],Z=0;for(let q of X){let K=Q.indexOf(q,Z);if(K===-1)continue;j.push({text:q,offset:K}),Z=K+q.length}return j.length>0?j:[{text:Q,offset:0}]};var _9=5000,F9=2000,A9=(Q)=>String(Q||"").trim().toLowerCase(),U3=()=>{let Q=typeof navigator<"u"?navigator.language||navigator.languages?.[0]:"";return A9(Q||"en-US")},B3=(Q,Y)=>{if(Y)return Q.find((Z)=>Z.voiceURI===Y)||Q.find((Z)=>Z.name===Y)||null;let J=U3(),G=J.split("-")[0]||"en",X=(Z)=>{let q=A9(Z.lang);return q===J||q.startsWith(`${G}-`)},j=[(Z)=>Z.localService&&X(Z),(Z)=>Z.default&&X(Z),(Z)=>X(Z),(Z)=>Z.localService,(Z)=>Z.default];for(let Z of j){let q=Q.find(Z);if(q)return q}return Q[0]||null},D3=(Q)=>!Q.default;class E7{providerId="browser";providerName="Browser Speech Synthesis";version="1.0.0";async initialize(Q){if(typeof window>"u")throw Error("BrowserTTSProvider requires browser environment");if(!("speechSynthesis"in window))throw Error("Browser does not support Speech Synthesis API");return new M9(Q)}supportsFeature(Q){return!0}getCapabilities(){return{supportsPause:!0,supportsResume:!0,supportsWordBoundary:!0,supportsVoiceSelection:!0,supportsRateControl:!0,supportsPitchControl:!0,supportsSSML:!1}}destroy(){}}class M9{utterance=null;config=null;_isPlaying=!1;_isPaused=!1;speakRunId=0;settlePendingVoiceWait=null;settlePendingChunk=null;onPlaybackStart=void 0;constructor(Q){this.config=Q}waitForBrowserVoices(Q,Y){return new Promise((J,G)=>{let X=speechSynthesis,j=typeof X.addEventListener==="function"&&typeof X.removeEventListener==="function",Z=j?null:X.onvoiceschanged,q=!1,K=null,B=null,U=()=>{if(K!==null)clearTimeout(K),K=null;if(j)X.removeEventListener("voiceschanged",A);else if(X.onvoiceschanged===M)X.onvoiceschanged=Z;if(B&&this.settlePendingVoiceWait===B)this.settlePendingVoiceWait=null},H=(O,L)=>{if(q)return;if(q=!0,U(),L)G(L);else J(O)},_=()=>{if(Q!==this.speakRunId){H(!1);return}if(X.getVoices().length>0)H(!0)},A=()=>_(),M=(O)=>{try{Z?.call(X,O)}finally{_()}};if(B=()=>H(!1),this.settlePendingVoiceWait=B,K=setTimeout(()=>H(!1,Error(`Configured browser voice "${Y}" could not be resolved because the browser did not publish its voice inventory within ${F9/1000} seconds.`)),F9),j)X.addEventListener("voiceschanged",A);else X.onvoiceschanged=M;_()})}async resolveBrowserVoice(Q){let Y=typeof this.config?.voice==="string"?this.config.voice.trim():"",J=speechSynthesis.getVoices();if(Y&&J.length===0){if(!await this.waitForBrowserVoices(Q,Y)||Q!==this.speakRunId)return{shouldContinue:!1,voice:null};J=speechSynthesis.getVoices()}if(Q!==this.speakRunId)return{shouldContinue:!1,voice:null};let G=B3(J,Y||void 0);if(Y&&!G)throw Error(`Configured browser voice "${Y}" is unavailable. Select a voice exposed by this browser using its voiceURI or name.`);return{shouldContinue:!0,voice:G}}async speak(Q){if(!this.config)throw Error("TTS not initialized");this.stop();let Y=this.speakRunId,J=await this.resolveBrowserVoice(Y);if(!J.shouldContinue)return;let G=this.splitIntoChunks(Q);for(let X of G){if(Y!==this.speakRunId)break;if(!await this.speakChunk(X.text,X.offset,Y,J.voice))break}}async speakSegments(Q){if(!this.config)throw Error("TTS not initialized");this.stop();let Y=this.speakRunId,J=await this.resolveBrowserVoice(Y);if(!J.shouldContinue)return;for(let G of Q){if(Y!==this.speakRunId)break;let X=this.splitIntoChunks(G.text);for(let Z of X){if(Y!==this.speakRunId)break;if(!await this.speakChunk(Z.text,G.startOffset+Z.offset,Y,J.voice))break}let j=Math.max(0,Number(G.pauseMsAfter||0));if(j>0&&Y===this.speakRunId){if(!await this.waitForPause(j,Y))break}}}async waitForPause(Q,Y){return await new Promise((J)=>setTimeout(J,Q)),Y===this.speakRunId}splitIntoChunks(Q){if(Q.length<=260)return[{text:Q,offset:0}];let J=this.segmentSentences(Q),G=[],X="",j=0;for(let Z of J){let q=Z.text.trim();if(!q)continue;let K=Z.text.search(/\S/),B=Z.offset+(K===-1?0:K);if(!X){X=q,j=B;continue}let U=`${X} ${q}`;if(U.length<=260)X=U;else G.push({text:X,offset:j}),X=q,j=B}if(X)G.push({text:X,offset:j});return G.length?G:[{text:Q,offset:0}]}getHighlightMode(){return(this.config?.providerOptions||{}).highlightMode==="word"?"word":"sentence"}getSegmentationPolicy(){let Q=this.config?.providerOptions||{},Y=Q.segmenter||{},G=Y.mode!=="regexOnly",X=typeof Y.locale==="string"&&Y.locale.trim().length>0?Y.locale:typeof Q.locale==="string"&&Q.locale.trim().length>0?Q.locale:void 0;return{useSentenceSegmenter:G,useWordSegmenter:G,locale:X}}segmentSentences(Q){let Y=this.getSegmentationPolicy();return R7(Q,{locale:Y.locale,useSentenceSegmenter:Y.useSentenceSegmenter})}inferWordLength(Q,Y){let J=Math.max(0,Math.min(Y,Math.max(0,Q.length-1)));return Q.slice(J).match(/^\s*([^\s]+)/)?.[1]?.length||1}async speakChunk(Q,Y,J,G){return new Promise((X,j)=>{if(J!==this.speakRunId){X(!1);return}let Z=new SpeechSynthesisUtterance(Q);if(this.utterance=Z,G&&D3(G))Z.voice=G;if(this.config?.rate)Z.rate=this.config.rate;if(this.config?.pitch)Z.pitch=this.config.pitch;let q=!1,K=!1,B=null,U=null,H=()=>{if(this.utterance===Z)this.utterance=null},_=()=>{if(B!==null)clearTimeout(B),B=null},A=()=>{Z.onstart=null,Z.onend=null,Z.onerror=null,Z.onpause=null,Z.onresume=null,Z.onboundary=null},M=(L,F)=>{if(K)return;if(K=!0,_(),A(),H(),U&&this.settlePendingChunk===U)this.settlePendingChunk=null;if(J===this.speakRunId)this._isPlaying=!1,this._isPaused=!1;if(F)j(F);else X(L)},O=(L)=>Error(L==="ended"?"Browser speech synthesis ended before audio started. The browser speech engine may be unavailable or stuck; try another voice or restart the browser.":`Browser speech synthesis did not start within ${_9/1000} seconds. The browser speech engine may be unavailable or stuck; try another voice or restart the browser.`);U=()=>M(!1),this.settlePendingChunk=U,Z.onstart=()=>{if(J!==this.speakRunId){M(!1);return}q=!0,_(),this._isPlaying=!0,this._isPaused=!1;try{this.onPlaybackStart?.()}catch(L){console.error("Browser TTS playback-start callback failed",L)}},Z.onend=()=>{if(J!==this.speakRunId){M(!1);return}if(!q){M(!1,O("ended"));return}M(!0)},Z.onerror=(L)=>{if(J!==this.speakRunId){M(!1);return}if(L.error==="interrupted"||L.error==="canceled"){M(!1);return}M(!1,Error(`Speech synthesis error: ${L.error}`))},Z.onpause=()=>{if(J!==this.speakRunId)return;this._isPaused=!0},Z.onresume=()=>{if(J!==this.speakRunId)return;this._isPaused=!1},Z.onboundary=(L)=>{if(J!==this.speakRunId)return;if(console.log("[BrowserProvider] Boundary event:",L.name,"charIndex:",L.charIndex,"charLength:",L.charLength),L.name!=="word"||!this.onWordBoundary)return;if(this.getHighlightMode()==="sentence")return;let F=Math.max(0,Math.min(L.charIndex,Math.max(0,Q.length-1))),$=Number(L.charLength||0),b=this.inferWordLength(Q,F),v=Number.isFinite($)&&$>0&&$<=80&&F+$<=Q.length?$:b,k=Q.substring(F,Math.min(Q.length,F+v)).trim(),p=Y+F;console.log("[BrowserProvider] Calling onWordBoundary with word:",k,"at position:",p),this.onWordBoundary(k,p,v)},B=setTimeout(()=>{if(K||q||J!==this.speakRunId)return;M(!1,O("timedOut")),speechSynthesis.cancel()},_9);try{speechSynthesis.speak(Z)}catch(L){M(!1,L instanceof Error?L:Error("Browser speech synthesis failed to queue speech"))}})}pause(){if(this._isPlaying&&!this._isPaused)speechSynthesis.pause()}resume(){if(this._isPlaying&&this._isPaused)speechSynthesis.resume()}stop(){let Q=this.utterance,Y=this._isPlaying||Q!==null;if(this.speakRunId+=1,this.settlePendingVoiceWait?.(),this.settlePendingChunk?.(),Y)speechSynthesis.cancel();this.utterance=null,this._isPlaying=!1,this._isPaused=!1}isPlaying(){return this._isPlaying&&!this._isPaused}isPaused(){return this._isPaused}updateSettings(Q){if(!this.config)this.config={};if(Q.rate!==void 0)this.config.rate=Q.rate;if(Q.pitch!==void 0)this.config.pitch=Q.pitch;if(Q.voice!==void 0)this.config.voice=Q.voice;if(Q.providerOptions!==void 0)this.config.providerOptions={...this.config.providerOptions||{},...Q.providerOptions||{}}}onWordBoundary}var S=(Q)=>Q.trim().replace(/\s+/g," "),j1=()=>/[\p{L}]+|\d+(?:\.\d+)?|[±√=+\-*/()²³^×÷≤≥≠≈<>|%°'′\u2062]/gu,e1=(Q)=>{if(Q.hidden)return!0;if(Q.tagName?.toLowerCase()==="mjx-assistive-mml")return!0;if(Q.getAttribute("aria-hidden")==="true")return!0;if(Q.hasAttribute("inert"))return!0;let Y=Q.classList;if(Y?.contains("sr-only")||Y?.contains("pie-sr-only")||Y?.contains("visually-hidden"))return!0;if(typeof window<"u"){let J=window.getComputedStyle(Q);if(J.display==="none"||J.visibility==="hidden")return!0;let G=Number.parseFloat(J.width||"0"),X=Number.parseFloat(J.height||"0"),j=Number.isFinite(G)&&Number.isFinite(X)&&G<=1&&X<=1,Z=J.clipPath.includes("inset(50%")||J.clipPath.includes("inset(100%")||J.clip.includes("rect(0px, 0px, 0px, 0px)")||J.clip.includes("rect(0 0 0 0)");if((J.position==="absolute"||J.position==="fixed")&&j&&(J.overflow==="hidden"||Z))return!0;if(J.opacity==="0"&&j)return!0}return!1},q1=(Q,Y)=>{let J=Q.nodeType===1?Q:Q.parentElement;while(J){if(e1(J))return!0;if(Y&&J===Y)break;J=J.parentElement}return!1};var O9=new Set(["computer-read-aloud","all"]),N9=new Set([...O9,"screen-reader"]),z9=new Set,V3=(Q)=>{let Y=Q.getAttribute?.("data-tts-suppress");if(Y===null||Y===void 0)return!1;let J=Y.trim().toLowerCase();if(O9.has(J))return!0;if(N9.has(J))return!1;if(!z9.has(J))z9.add(J),console.warn(`[tts] data-tts-suppress="${Y}" is not one of ${Array.from(N9).join(", ")}; suppressing read-aloud for this content anyway, because a suppression attribute that fails open would leak the answer to items where reading is the construct. Correct the value to silence this.`);return!0},K1=(Q,Y)=>{let J=Q.nodeType===1?Q:Q.parentElement;while(J){if(V3(J))return!0;if(Y&&J===Y)break;J=J.parentElement}return!1},V7=(Q,Y)=>q1(Q,Y)||K1(Q),Q8=(Q,Y)=>{if(typeof document>"u"||typeof document.createTreeWalker!=="function"||typeof NodeFilter>"u"||typeof Q.intersectsNode!=="function")return{text:Q.toString(),filtered:!1};let J=[],G=!1,X=document.createTreeWalker(Y,NodeFilter.SHOW_TEXT),j=X.nextNode();while(j){let Z=j;if(Q.intersectsNode(Z))if(V7(Z,Y))G=!0;else{let q=Z.textContent||"",K=Z===Q.startContainer?Q.startOffset:0,B=Z===Q.endContainer?Q.endOffset:q.length;J.push(q.slice(K,B))}j=X.nextNode()}return{text:J.join(""),filtered:G}},Y8=(Q,Y,J)=>{if(!Q||!Y)return!1;if(/\s/.test(Q)||/\s/.test(Y))return!1;let G=J?.boundarySpacingMode??"segmenterPreferred";if(G==="none")return!1;if(G==="segmenterPreferred")try{let Z=globalThis.Intl?.Segmenter;if(typeof Z==="function"){let q=new Z(J?.locale,{granularity:"word"});if(Array.from(q.segment(`${Q}${Y}`)).filter((U)=>U.isWordLike!==!1&&U.segment.trim().length>0).length>=2)return!0}}catch{}let X=/[A-Za-z0-9]/.test(Q),j=/[A-Za-z0-9]/.test(Y);return X&&j},b7=(Q,Y)=>{let J=new Map;if(typeof document>"u"||typeof document.createTreeWalker!=="function"||typeof NodeFilter>"u")return{text:"",map:J};let G=[],X=0,j=!0,Z=!1,q=null,K=null,B=document.createTreeWalker(Q,NodeFilter.SHOW_TEXT),U=B.nextNode();while(U){let _=U;if(_.parentElement&&!V7(_,Q)){let M=_.textContent||"",O=M.match(/\S/),L=O?O[0]:null;if(!j&&!Z&&Y8(K,L,Y)){if(G.push(" "),q)J.set(X,q);X++,Z=!0}for(let F=0;F<M.length;F++){let $=M[F],b=/\s/.test($);if(j){if(!b)j=!1,G.push($),J.set(X,{node:_,offset:F}),q={node:_,offset:F},X++,Z=!1,K=$}else if(b){if(!Z)G.push(" "),J.set(X,{node:_,offset:F}),q={node:_,offset:F},X++;Z=!0}else G.push($),J.set(X,{node:_,offset:F}),q={node:_,offset:F},X++,Z=!1,K=$}}U=B.nextNode()}let H=G.join("").trimEnd();while(J.has(H.length))J.delete(H.length);return{text:H,map:J}};var H3=new Set(["speak","p","s","emphasis","prosody","say-as","voice","lang"]),P9=new Set(["audio","phoneme"]),$9=(Q)=>Q.replace(/&quot;/g,'"').replace(/&apos;/g,"'").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&nbsp;/g," ").replace(/&#160;/g," ").replace(/&amp;/g,"&"),W1=(Q,Y,J)=>{for(let G=0;G<Y.length;G++)Q.push({char:Y[G],rawOffset:J===null?null:J+G})},_3=(Q,Y,J)=>{let G=Y.slice(J).match(/^&(quot|apos|lt|gt|nbsp|amp|#160);/i);if(!G)return 0;return W1(Q,$9(G[0]),J),G[0].length},L9=(Q)=>{Q.push({char:" ",rawOffset:null})},F3=(Q)=>{let Y=new Map,J=[],G=!0;for(let X of Q){if(/\s/.test(X.char)){if(!G&&J.length>0){if(J.push(" "),X.rawOffset!==null)Y.set(X.rawOffset,J.length-1)}G=!0;continue}if(J.push(X.char),X.rawOffset!==null)Y.set(X.rawOffset,J.length-1);G=!1}while(J.length>0&&J[J.length-1]===" ")J.pop();for(let[X,j]of Y)if(j>=J.length)Y.delete(X);return{text:J.join(""),rawToSpokenOffsetMap:Y}},A3=(Q)=>{return Q.match(/^<\/?\s*([A-Za-z0-9:-]+)/)?.[1]?.toLowerCase()||""},M3=(Q,Y)=>{let J=new RegExp(`${Y}\\s*=\\s*("([^"]*)"|'([^']*)')`,"i"),G=Q.match(J);return $9(G?.[2]??G?.[3]??"")||null},U1=(Q)=>{let Y=[],J=!1,G=!1,X=0;while(X<Q.length){let Z=Q[X];if(Z!=="<"){if(Z==="&"){let _=_3(Y,Q,X);if(_>0){X+=_;continue}}W1(Y,Z,X),X++;continue}let q=Q.indexOf(">",X+1);if(q<0){W1(Y,Z,X),X++;continue}G=!0;let K=Q.slice(X,q+1),B=A3(K),U=/^<\s*\//.test(K),H=/\/\s*>$/.test(K);if(!U&&B==="sub"){let _=M3(K,"alias");if(!_){J=!0,X=q+1;continue}W1(Y,_,null);let A=Q.toLowerCase().indexOf("</sub>",q+1);X=A>=0?A+6:q+1;continue}if(!U&&B==="break"){L9(Y),X=q+1;continue}if(!U&&P9.has(B)){if(J=!0,H){X=q+1;continue}}if(B&&!H3.has(B)&&!P9.has(B)&&B!=="break"&&B!=="sub")J=!0;if(!U&&(B==="p"||B==="s"))L9(Y);X=q+1}let j=F3(Y);return{spokenText:S(j.text),rawToSpokenOffsetMap:j.rawToSpokenOffsetMap,unsupportedSemantic:J,hasMarkup:G}};var N3=j1(),S9=new Map([["zero","0"],["one","1"],["two","2"],["three","3"],["four","4"],["five","5"],["six","6"],["seven","7"],["eight","8"],["nine","9"],["ten","10"]]),z3=[{phrase:["plus","or","minus"],visible:"±",score:8},{phrase:["square","root"],visible:"√",score:8},{phrase:["divided","by"],visible:"/",score:7},{phrase:["all","over"],visible:"/",score:7},{phrase:["equals"],visible:"=",score:7},{phrase:["equal"],visible:"=",score:7},{phrase:["times"],visible:"⁢",score:7},{phrase:["multiplied","by"],visible:"⁢",score:7},{phrase:["over"],visible:"/",score:6},{phrase:["squared"],visible:"²",score:6},{phrase:["squared"],visible:"2",score:4},{phrase:["negative"],visible:"-",score:5},{phrase:["minus"],visible:"-",score:5},{phrase:["plus"],visible:"+",score:5}],J8=(Q)=>{let Y=[];for(let J of Q.matchAll(N3)){let G=J[0],X=J.index??0;Y.push({text:G,normalized:G.toLowerCase(),start:X,end:X+G.length})}return Y},G8=(Q)=>S9.get(Q.normalized)||Q.normalized,O3=(Q,Y)=>{let J=[];for(let G=0;G<Q.length;G++){for(let X=0;X<Y.length;X++){let j=G8(Q[G]),Z=G8(Y[X]);if(j===Z)J.push({spokenStartToken:G,spokenEndToken:G+1,visibleToken:X,score:10})}for(let X of z3){let j=Q.slice(G,G+X.phrase.length);if(j.length!==X.phrase.length)continue;if(!j.every((Z,q)=>Z.normalized===X.phrase[q]))continue;for(let Z=0;Z<Y.length;Z++){if(Y[Z].normalized!==X.visible)continue;J.push({spokenStartToken:G,spokenEndToken:G+X.phrase.length,visibleToken:Z,score:X.score})}}}return J},P3=(Q,Y)=>{let J=O3(Q,Y).sort((K,B)=>Q[K.spokenStartToken].start-Q[B.spokenStartToken].start||Y[K.visibleToken].start-Y[B.visibleToken].start),G=Array(J.length).fill(0),X=Array(J.length).fill(-1);for(let K=0;K<J.length;K++){let B=J[K];G[K]=B.score;for(let U=0;U<K;U++){let H=J[U];if(H.spokenEndToken<=B.spokenStartToken&&H.visibleToken<B.visibleToken){let _=B.spokenStartToken-H.spokenEndToken,A=B.visibleToken-H.visibleToken-1,M=Math.max(0,Math.abs(_-A)-2),O=G[U]+B.score-M;if(O>G[K])G[K]=O,X[K]=U}}}let j=-1;for(let K=0;K<G.length;K++)if(j<0||G[K]>G[j])j=K;if(j<0)return[];let Z=[],q=j;while(q>=0)Z.unshift(J[q]),q=X[q];return Z.map((K)=>{let B=Q[K.spokenStartToken],U=Q[K.spokenEndToken-1],H=Y[K.visibleToken];return{spokenStart:B.start,spokenEnd:U.end,visibleStart:H.start,visibleEnd:H.end,score:K.score}})},L3=(Q,Y,J)=>{if(Q.length===0)return 0;let G=Q.length/Math.max(1,Math.min(Y.length,J.length)),X=Q.reduce((j,Z)=>j+Z.score,0)/Q.length/10;return Math.min(1,G*X)},B1=(Q)=>{let Y=U1(Q.speechText),J=S(Q.visibleText),G=Y.spokenText,X=J8(G),j=J8(J),Z=Y.unsupportedSemantic?[]:P3(X,j),q=L3(Z,X,j),K=G===J&&G.length>0,B=Z.length===1&&Z[0].score===10&&X.length<=2&&j.length<=2,U=Y.unsupportedSemantic?"region-fallback":K?"exact-word":Z.length>=2||B?q>=0.12?"anchor-span":"region-fallback":"region-fallback",H=Y.unsupportedSemantic?"unsupported":Y.hasMarkup?"raw-ssml":"plain-spoken-text";return{speechText:Q.speechText,spokenText:G,visibleText:J,playbackMode:U,boundaryOffsetMode:H,anchors:Z,confidence:q,spokenTokens:X,visibleTokens:j,rawToSpokenOffsetMap:Y.rawToSpokenOffsetMap}},X8=(Q,Y)=>Q.find((J)=>J.start<=Y&&Y<J.end)||null,T9=(Q)=>{if(!Q)return null;if(/^<[^>]+>$/.test(Q.trim()))return null;let Y=J8(Q)[0];if(!Y)return null;return S9.get(Y.normalized)||Y.normalized},w9=(Q,Y,J)=>{let G=T9(J);if(!Y||!G)return!1;let X=X8(Q.spokenTokens,Y.start);if(!X)return!1;return G8(X)===G},R9=(Q,Y)=>{let J=Q.rawToSpokenOffsetMap.get(Y);if(J!==void 0)return J;for(let G=Y;G<Q.speechText.length;G++){let X=Q.rawToSpokenOffsetMap.get(G);if(X!==void 0)return X;if(Q.speechText[G]===">")break}return null},E9=(Q,Y,J)=>{let G=R9(Q,Y);if(G===null)return null;let X=R9(Q,Math.max(Y,Y+J-1)),j=X8(Q.spokenTokens,G),Z=X!==null&&X>=G?X-G+1:j?j.end-G:J;return{start:G,length:Math.max(1,Z)}},b9=(Q,Y,J)=>{if(Y<0||Y>=Q.spokenText.length)return null;let G=X8(Q.spokenTokens,Y);if(!G)return null;return{start:Y,length:Math.min(J,G.end-Y)}},C9=(Q,Y,J=1,G)=>{if(Q.boundaryOffsetMode==="unsupported"||!Number.isFinite(Y))return null;let X=Math.max(1,Number.isFinite(J)?J:1);if(G&&/^<[^>]+>$/.test(G.trim()))return null;if(Q.boundaryOffsetMode==="raw-ssml"){let j=E9(Q,Y,X),Z=b9(Q,Y,X);if(G){if(w9(Q,j,G))return j;if(w9(Q,Z,G))return Z;if(T9(G))return null}return j||Z}return b9(Q,Y,X)||E9(Q,Y,X)},y9=(Q,Y)=>{if(Q.playbackMode==="region-fallback")return null;let J=Q.anchors.find((j)=>j.spokenStart<=Y&&Y<j.spokenEnd);if(J)return{start:J.visibleStart,end:J.visibleEnd};let G=null,X=null;for(let j of Q.anchors){if(j.spokenEnd<=Y){G=j;continue}if(j.spokenStart>Y){X=j;break}}if(G&&X)return{start:Math.min(G.visibleStart,X.visibleStart),end:Math.max(G.visibleEnd,X.visibleEnd)};return null};var $3=new Map([["+",["plus"]],["-",["minus","negative"]],["−",["minus","negative"]],["×",["times","multiplied by"]],["÷",["divided by"]],["=",["equals","equal to"]],["≠",["is not equal to","not equal to"]],["≈",["approximately equals"]],["≤",["less than or equal to"]],["≥",["greater than or equal to"]],["<",["less than"]],[">",["greater than"]],["∠",["angle"]],["△",["triangle"]],["□",["box"]],["○",["circle"]],["°",["degrees","degree"]],["%",["percent"]],["'",["prime"]],["′",["prime"]],["•",["times"]],["·",["times"]],["⁢",["times","multiplied by"]]]),w3=new Map([["⁡","function-application"],["⁢","implicit-multiply"],["⁣","invisible-separator"],["⁤","invisible-plus"]]),x9=new Map([["2",["squared"]],["3",["cubed"]]]),R3=new Map([["msqrt","radical"],["mroot","radical"],["msub","subscript"],["msubsup","subsupscript"],["munder","underscript"],["mover","overscript"],["munderover","underoverscript"],["mmultiscripts","multiscript"],["menclose","enclosure"]]),E3=(Q)=>Q.replace(/\s+/g," ").trim(),H7=(Q)=>(Q.localName||Q.tagName||"").toLowerCase(),b3=(Q)=>Q.nodeType===Node.ELEMENT_NODE,S7=(Q)=>Array.from(Q.childNodes).filter(b3),Z8=(Q)=>E3(Q.textContent||""),e=(Q,Y)=>({type:"element-range",quality:Y,element:Q}),S3=(Q)=>{switch(Q){case"mi":return"identifier";case"mn":return"number";case"mo":return"operator";case"mtext":case"ms":return"text";case"mspace":return"space";default:return"unknown"}},T3=(Q,Y)=>{if(Y==="operator"){if(Q==="−")return"-";return Q}return Q.toLowerCase()},C3=(Q,Y,J)=>{if(J==="fraction")return["over","divided by"];if(J==="superscript")return x9.get(Q)??[];if(Q==="|")return["absolute value"];if(Y==="operator")return $3.get(Q)||[];return[]},_7=(Q)=>{let Y=Q.normalized??T3(Q.text,Q.kind||"unknown");return{id:`math-token-${Q.state.nextId++}`,kind:Q.kind,role:Q.role,text:Q.text,normalized:Y,spokenAliases:C3(Q.text,Q.kind,Q.role),sourceElement:Q.sourceElement,path:Q.path,target:Q.target||e(Q.sourceElement,"element-range"),optional:Q.optional}},F7=(Q,Y,J="tokens")=>{Q[J].push(Y)},f9=(Q,Y,J)=>{S7(Q).forEach((G,X)=>Q7(G,Y,`${J}/${H7(G)}[${X}]`))},y3=(Q,Y,J)=>{let G=S7(Q);if(G[0])Q7(G[0],Y,`${J}/numerator`);if(F7(Y,_7({state:Y,kind:"structure",role:"fraction",text:"/",sourceElement:Q,path:J,target:e(Q,"element-range")})),G[1])Q7(G[1],Y,`${J}/denominator`)},x3=(Q,Y,J)=>{let G=Q.getAttribute("open")||"(",X=Q.getAttribute("close")||")";F7(Y,_7({state:Y,kind:"operator",role:G==="|"?"absolute-value-fence":"open-fence",text:G,sourceElement:Q,path:`${J}/open`,target:e(Q,"element-range")})),f9(Q,Y,J),F7(Y,_7({state:Y,kind:"operator",role:X==="|"?"absolute-value-fence":"close-fence",text:X,sourceElement:Q,path:`${J}/close`,target:e(Q,"element-range")}))},f3=(Q,Y,J)=>{let G=S7(Q);if(G[0])Q7(G[0],Y,`${J}/base`);let X=G[1];if(!X)return;let j=Z8(X);if(x9.has(j)){F7(Y,_7({state:Y,kind:"structure",role:"superscript",text:j,normalized:j,sourceElement:X,path:`${J}/exponent`,target:e(Q,"element-range")}));return}Q7(X,Y,`${J}/exponent`)},k3=(Q,Y,J,G)=>{F7(Y,_7({state:Y,kind:"structure",role:G,text:Z8(Q)||G,normalized:`\x00${G}`,sourceElement:Q,path:J,target:e(Q,"element-range")}))},I3=(Q,Y,J)=>{let G=0;for(let X of S7(Q)){if(H7(X)==="mtr"||H7(X)==="mlabeledtr")G++,F7(Y,_7({state:Y,kind:"layout",role:"table-row",text:`row-${G}`,normalized:`row-${G}`,sourceElement:X,path:`${J}/row[${G}]`,target:e(X,"region-fallback")}),"layoutTargets");Q7(X,Y,`${J}/${H7(X)}[${G}]`)}},v3=(Q,Y,J)=>{let G=Z8(Q);if(!G)return;let X=S3(H7(Q)),j=X==="operator"?w3.get(G):void 0,Z=j??(X==="operator"&&(G==="("||G===")")?"grouping-fence":X);F7(Y,_7({state:Y,kind:X,role:Z,text:G,sourceElement:Q,path:J,target:j&&Q.parentElement?e(Q.parentElement,"region-fallback"):void 0,optional:Boolean(j)||Z==="grouping-fence"}))},Q7=(Q,Y,J)=>{let G=H7(Q);switch(G){case"annotation":case"annotation-xml":return;case"semantics":{let X=S7(Q).find((j)=>{let Z=H7(j);return Z!=="annotation"&&Z!=="annotation-xml"});if(X)Q7(X,Y,`${J}/presentation`);return}case"mi":case"mn":case"mo":case"mtext":case"ms":case"mspace":v3(Q,Y,J);return;case"mfrac":y3(Q,Y,J);return;case"msup":f3(Q,Y,J);return;case"mfenced":x3(Q,Y,J);return;case"mtable":I3(Q,Y,J);return;case"mphantom":return;case"maction":{let X=S7(Q)[0];if(X)Q7(X,Y,`${J}/action`);return}default:{let X=R3.get(G);if(X){k3(Q,Y,J,X);return}f9(Q,Y,J)}}},k9=(Q)=>{let Y={tokens:[],layoutTargets:[],nextId:0};return Q7(Q,Y,"/math"),{tokens:Y.tokens,layoutTargets:Y.layoutTargets,expressionTarget:e(Q,"region-fallback")}};var I9=(Q)=>{if(!Q.boundary)return null;return Q.alignment.segments.find((J)=>J.speechTokenIds.includes(Q.boundary.token.id))?.target||null};var h3=(Q)=>{let Y=[],J=new Set,G=(X)=>{let j=X.toLowerCase().trim().split(/\s+/).filter(Boolean);if(j.length===0)return;let Z=j.join(" ");if(J.has(Z))return;J.add(Z),Y.push(j)};G(Q.normalized);for(let X of Q.spokenAliases)G(X);return Y},v9=(Q,Y,J)=>{let G=0;for(let X of J){if(X.length<=G)continue;let j=!0;for(let Z=0;Z<X.length;Z++){let q=Q[Y+Z];if(!q||q.normalized.toLowerCase()!==X[Z]){j=!1;break}}if(j)G=X.length}return G},m3=(Q,Y)=>{let J=[],G=0;for(let X of Y){let j=h3(X);if(X.optional){let Z=v9(Q,G,j);if(Z>0)J.push({speechTokens:Q.slice(G,G+Z),math:X}),G+=Z;continue}while(G<Q.length){let Z=v9(Q,G,j);if(Z>0){J.push({speechTokens:Q.slice(G,G+Z),math:X}),G+=Z;break}G++}}return J},u3=(Q,Y,J)=>{let G=J.filter((Z)=>!Z.optional).length,X=Q.filter((Z)=>!Z.math.optional).length,j=Q.reduce((Z,q)=>Z+q.speechTokens.length,0);return G>0&&X===G&&j===Y.length},p3=(Q)=>Q.map(({speechTokens:Y,math:J})=>({speechTokenIds:Y.map((G)=>G.id),mathTokenIds:[J.id],score:1,confidence:1,target:J.target})),h9=(Q)=>{let Y=Q.minExactWordConfidence??0.95,J=m3(Q.speech.tokens,Q.math.tokens),G=u3(J,Q.speech.tokens,Q.math.tokens)?1:0;return{segments:G>=Y?p3(J):[],confidence:G,fallbackTarget:Q.math.expressionTarget}};var m9=j1(),g3=new Map([["zero","0"],["one","1"],["two","2"],["three","3"],["four","4"],["five","5"],["six","6"],["seven","7"],["eight","8"],["nine","9"],["ten","10"]]),u9=(Q)=>{let Y=Q.toLowerCase();return g3.get(Y)||Y},c3=(Q)=>{let Y=[];for(let J of Q.matchAll(m9)){let G=J[0],X=J.index??0;Y.push({id:`speech-token-${Y.length}`,text:G,normalized:u9(G),start:X,end:X+G.length,sourceStart:X,sourceEnd:X+G.length,coordinateSystem:"normalized-speech"})}return Y},A7=(Q)=>{let Y=U1(Q.speechText);return{speechText:Q.speechText,spokenText:Y.spokenText,tokens:c3(Y.spokenText),rawToSpokenOffsetMap:Y.rawToSpokenOffsetMap,boundaryOffsetSpace:Y.unsupportedSemantic?"unsupported":Y.hasMarkup?"raw-ssml":"plain-spoken-text",unsupportedSemantic:Y.unsupportedSemantic,hasMarkup:Y.hasMarkup}},K8=(Q)=>{if(!Q)return null;if(/^<[^>]+>$/.test(Q.trim()))return null;let Y=Q.match(m9);if(!Y?.[0])return null;return u9(Y[0])},l3=(Q,Y)=>Q.find((J)=>J.start<=Y&&Y<J.end)||null,d3=(Q,Y)=>{let J=Q.rawToSpokenOffsetMap.get(Y);if(J!==void 0)return J;for(let G=Y;G<Q.speechText.length;G++){let X=Q.rawToSpokenOffsetMap.get(G);if(X!==void 0)return X;if(Q.speechText[G]===">")break}return null},j8=(Q,Y,J)=>{if(Y===null)return null;let G=l3(Q.tokens,Y);if(!G)return null;return{token:G,start:Y,length:Math.max(1,Math.min(J,G.end-Y)),confidence:0.75}},q8=(Q,Y)=>{let J=K8(Y);return Boolean(Q&&J&&Q.token.normalized===J)},W8=(Q)=>{if(Q.tokenization.boundaryOffsetSpace==="unsupported"||!Number.isFinite(Q.position)||Q.boundaryWord&&/^<[^>]+>$/.test(Q.boundaryWord.trim()))return null;let Y=Math.max(1,Number.isFinite(Q.length)?Q.length:1),J=j8(Q.tokenization,d3(Q.tokenization,Q.position),Y),G=j8(Q.tokenization,Q.position>=0&&Q.position<Q.tokenization.spokenText.length?Q.position:null,Y);if(q8(J,Q.boundaryWord))return{...J,confidence:1};if(q8(G,Q.boundaryWord))return{...G,confidence:1};if(Q.boundaryWord&&K8(Q.boundaryWord))return null;return Q.tokenization.boundaryOffsetSpace==="raw-ssml"?J||G:G||J},p9=(Q)=>{if(Q.tokenization.boundaryOffsetSpace==="unsupported"||!Number.isFinite(Q.position)||Q.boundaryWord&&/^<[^>]+>$/.test(Q.boundaryWord.trim()))return null;let Y=Math.max(1,Number.isFinite(Q.length)?Q.length:1),J=j8(Q.tokenization,Q.position>=0&&Q.position<Q.tokenization.spokenText.length?Q.position:null,Y);if(q8(J,Q.boundaryWord))return{...J,confidence:1};if(Q.boundaryWord&&K8(Q.boundaryWord))return null;return J};var T7=(Q)=>{let Y=A7({speechText:Q.speechText}),J=k9(Q.mathElement);return{speech:Y,math:J,result:h9({speech:Y,math:J})}};var g9=(Q,Y)=>{let J=p9({tokenization:Q.speech,position:Y.position,length:Y.length,boundaryWord:Y.boundaryWord});return I9({alignment:Q.result,boundary:J})},c9=(Q,Y)=>{if(!Y.boundaryWord||/^<[^>]+>$/.test(Y.boundaryWord.trim()))return null;let J=A7({speechText:Y.boundaryWord}).tokens[0];if(!J)return null;let G=Q.math.tokens.filter((X)=>{let j=J.normalized.toLowerCase();return X.normalized.toLowerCase()===j||X.spokenAliases.some((Z)=>Z.toLowerCase()===j)});return G.length===1?G[0].target:null};var i3=new Set(["math","maction","menclose","merror","mfenced","mfrac","mi","mmultiscripts","mn","mo","mover","mpadded","mphantom","mprescripts","mroot","mrow","ms","mspace","msqrt","mstyle","msub","msubsup","msup","mtable","mtd","mtext","mtr","munder","munderover","none","semantics","annotation","annotation-xml"]),s3=new Set(["accent","accentunder","align","bevelled","class","close","columnalign","columnlines","columnspacing","columnspan","denomalign","depth","dir","display","encoding","fence","height","href","id","largeop","length","linethickness","lspace","mathbackground","mathcolor","mathsize","mathvariant","maxsize","minsize","movablelimits","notation","numalign","open","rowalign","rowlines","rowspacing","rowspan","rspace","scriptlevel","scriptminsize","scriptsizemultiplier","selection","separator","separators","stretchy","subscriptshift","supscriptshift","symmetric","width","xmlns","xml:lang"]),l9=(Q)=>Q.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),n3=(Q)=>l9(Q).replace(/"/g,"&quot;"),r3=(Q,Y)=>{let J=Q.toLowerCase(),G=Y.trim().toLowerCase();if(J.startsWith("on"))return!0;if(!s3.has(J))return!0;if(G.includes("javascript:"))return!0;if(G.includes("data:text/html"))return!0;return!1},o3=(Q)=>{let Y=Q.localName.toLowerCase();if(!i3.has(Y))return!1;let J=Q.namespaceURI;return!J||J==="http://www.w3.org/1998/Math/MathML"||J==="http://www.w3.org/1999/xhtml"},d9=(Q)=>{if(Q.nodeType===Node.TEXT_NODE)return l9(Q.textContent||"");if(Q.nodeType===Node.COMMENT_NODE)return"";if(Q.nodeType!==Node.ELEMENT_NODE)return null;let Y=Q;if(!o3(Y))return null;let J=Y.localName.toLowerCase(),G=[];for(let Z of Array.from(Y.attributes)){let q=Z.name.toLowerCase();if(r3(q,Z.value))continue;if(q==="xmlns"&&Z.value!=="http://www.w3.org/1998/Math/MathML")return null;G.push(`${q}="${n3(Z.value)}"`)}if(J==="math"&&!G.some((Z)=>Z.startsWith("xmlns=")))G.unshift('xmlns="http://www.w3.org/1998/Math/MathML"');let X=[];for(let Z of Array.from(Y.childNodes)){let q=d9(Z);if(q===null)return null;X.push(q)}let j=G.length>0?` ${G.join(" ")}`:"";return`<${J}${j}>${X.join("")}</${J}>`},a3=(Q)=>{if(typeof DOMParser<"u")return new DOMParser().parseFromString(Q,"application/xml");return null},D1=(Q)=>{let Y=String(Q||"").trim();if(!Y)return null;let J=a3(Y);if(!J)return null;if(J.getElementsByTagName("parsererror").length>0)return null;let G=J.documentElement;if(!G||G.localName.toLowerCase()!=="math")return null;return d9(G)};var i9=(Q)=>({chars:[],map:new Map,position:0,inLeadingWhitespace:!0,lastCharWasWhitespace:!1,lastMapped:null,options:Q}),s9=(Q)=>Q.classList?.contains("MathJax")||Q.tagName?.toLowerCase()==="mjx-container",n9=(Q)=>Q.tagName?.toLowerCase()==="mjx-assistive-mml",r9=(Q)=>{let Y=Q.tagName?.toLowerCase();return Y==="annotation"||Y==="annotation-xml"},t3=(Q)=>{let Y=Q.getAttribute("data-mathml");return Y&&Y.trim()?Y:null},e3=(Q)=>{return Q.querySelector("mjx-assistive-mml math")?.outerHTML||null},Q2=(Q)=>{if(Q.tagName.toLowerCase()==="math")return D1(Q.outerHTML);let Y=t3(Q);if(Y){let J=D1(Y);if(J)return J}if(s9(Q)){let J=e3(Q);if(J){let G=D1(J);if(G)return G}}return null};var Y2=new Set(["P","H1","H2","H3","H4","H5","H6","LI","TD","TH","DD","DT","FIGCAPTION","LABEL","BUTTON"]),J2=new Set(["heading","listitem","option","radio","row","cell","columnheader","rowheader"]),G2=(Q,Y)=>{let J=Q.parentElement,G=null;while(J&&J!==Y){let X=(J.getAttribute("role")||"").toLowerCase(),j=J.tagName.toUpperCase();if(Y2.has(j)||J2.has(X)){G=J;break}J=J.parentElement}return G||Y},X2=(Q)=>Boolean(typeof Q.querySelector==="function"&&Q.querySelector("math, [data-mathml], .MathJax, mjx-container, mjx-assistive-mml"))||Q.tagName?.toLowerCase()==="math"||Q.hasAttribute?.("data-mathml")||s9(Q),M7=(Q,Y,J)=>{if(/[.,;:!?]/.test(Y)&&Q.chars.length>0&&Q.chars[Q.chars.length-1]===" ")Q.chars.pop(),Q.position--,Q.map.delete(Q.position);if(Q.chars.push(Y),J)Q.map.set(Q.position,J),Q.lastMapped=J;else if(Q.lastMapped)Q.map.set(Q.position,Q.lastMapped);Q.position++},o9=(Q,Y)=>{if(Q.inLeadingWhitespace||Q.lastCharWasWhitespace||Q.chars.length===0)return!1;let J=Q.chars[Q.chars.length-1];return Y8(J,Y,Q.options)},a9=(Q,Y)=>{let J=Y.textContent||"",G=!1;for(let X=0;X<J.length;X++){let j=J[X],Z=/\s/.test(j);if(Q.inLeadingWhitespace){if(!Z)Q.inLeadingWhitespace=!1,M7(Q,j,{node:Y,offset:X}),G=!0,Q.lastCharWasWhitespace=!1;continue}if(Z){if(!Q.lastCharWasWhitespace)M7(Q," ",{node:Y,offset:X});Q.lastCharWasWhitespace=!0;continue}if(!G&&o9(Q,j))M7(Q," ",{node:Y,offset:X});M7(Q,j,{node:Y,offset:X}),G=!0,Q.lastCharWasWhitespace=!1}},Z2=(Q,Y)=>{for(let J=0;J<Y.text.length;J++){let G=Y.text[J],X=/\s/.test(G),j=Y.map.get(J)||null,Z=j?.node||Q.lastMapped?.node||null,q=j?.offset??Q.lastMapped?.offset??0,K=j?{node:j.node,offset:j.offset}:Z?{node:Z,offset:q}:null;if(Q.inLeadingWhitespace){if(X)continue;Q.inLeadingWhitespace=!1}if(X){if(!Q.lastCharWasWhitespace)M7(Q," ",K);Q.lastCharWasWhitespace=!0;continue}if(J===0&&o9(Q,G))M7(Q," ",K);if(M7(Q,G,K),Q.lastCharWasWhitespace=!1,j)Q.map.set(Q.position-1,{node:j.node,offset:j.offset}),Q.lastMapped={node:j.node,offset:j.offset};else if(Z)Q.map.set(Q.position-1,{node:Z,offset:q})}},j2=(Q)=>{if(typeof DOMParser>"u")return"";let Y=new DOMParser().parseFromString(Q,"application/xml");if(Y.getElementsByTagName("parsererror").length>0)return"";let J=[],G=(X)=>{if(X.nodeType===3){let Z=X.textContent||"";if(Z.trim())J.push(Z);return}if(X.nodeType!==1)return;let j=X;if(r9(j))return;for(let Z of Array.from(j.childNodes))G(Z)};return G(Y.documentElement),S(J.join(" "))},q2=(Q,Y,J)=>{let G=i9(J),X=(q)=>{if(V7(q,Q))return;if(q.nodeType===3){a9(G,q);return}if(q.nodeType!==1)return;let K=q;if(n9(K)||r9(K))return;for(let B of Array.from(K.childNodes))X(B)};X(Q),t9(G);let j=S(G.chars.join(""));if(j)return{text:j,map:G.map};let Z=j2(Y);if(!Z)return b7(Q,J);return{text:Z,map:new Map}},t9=(Q)=>{while(Q.chars.length>0&&/\s/.test(Q.chars[Q.chars.length-1]))Q.chars.pop(),Q.position--,Q.map.delete(Q.position)},K2=(Q,Y)=>{let J=i9(Y),G=[],X=0,j,Z=!1,q=()=>{let U=S(J.chars.slice(X,J.chars.length).join(""));if(U)G.push({type:"text",text:U,sourceElement:j});X=J.chars.length,j=void 0},K=(U)=>{if(V7(U,Q))return;if(U.nodeType===Node.TEXT_NODE){let A=G2(U,Q);if(j&&A!==j)q();j=A,a9(J,U);return}if(U.nodeType!==Node.ELEMENT_NODE)return;let H=U;if(n9(H))return;let _=Q2(H);if(_){q();let A=q2(H,_,Y);Z2(J,A);let M=S(A.text);G.push({type:"math",mathml:_,fallbackText:M,sourceElement:H}),X=J.chars.length,Z=!0;return}for(let A of Array.from(H.childNodes))K(A)};for(let U of Array.from(Q.childNodes))K(U);t9(J),q();let B=J.chars.join("");while(J.map.has(B.length))J.map.delete(B.length);return{visibleText:B,map:J.map,chunks:G,containsMathMarkup:Z}},N7=(Q,Y)=>{if(!X2(Q)){let{text:J,map:G}=b7(Q,Y);return{visibleText:J,map:G,chunks:J?[{type:"text",text:J}]:[],containsMathMarkup:!1}}return K2(Q,Y)};var U8=null,e9=Promise.resolve(),U2=(Q)=>(Q||"en").split("-")[0].toLowerCase()||"en",B2=async()=>{if(!U8)U8=import("speech-rule-engine").then((Q)=>{let Y=Q.default||Q;if(!Y||typeof Y.toSpeech!=="function")throw Error("speech-rule-engine did not expose toSpeech");return Y});return U8},D2=(Q)=>Q==="en"?"clearspeak":"mathspeak",Q6=(Q)=>!!Q&&typeof Q==="object"&&!Array.isArray(Q),Y6=(Q)=>typeof Q==="string"&&Q.trim()?Q.trim():void 0,z7=(Q)=>{if(!Q6(Q))return;let Y=Y6(Q.domain),J=Y6(Q.style),G=Q6(Q.engineOptions)?Q.engineOptions:void 0;if(!Y&&!J&&!G)return;return{...Y?{domain:Y}:{},...J?{style:J}:{},...G?{engineOptions:G}:{}}},V2=async(Q,Y,J,G)=>{let X=U2(Y),j=z7(G);await Q.setupEngine?.({...j?.engineOptions||{},locale:X,domain:j?.domain||D2(X),...j?.style?{style:j.style}:{},modality:"speech",markup:J}),await Q.engineReady?.()},H2=async(Q)=>{let Y=e9.then(Q,Q);return e9=Y.then(()=>{return},()=>{return}),Y},J6=async(Q,Y,J,G,X)=>H2(async()=>{return await V2(Q,J,G,X),Q.toSpeech(Y)}),_2=(Q)=>Q.replace(/^\s*<\?xml[^>]*\?>\s*/i,""),F2=async(Q,Y,J,G)=>{try{let X=_2(await J6(Q,Y,J,"ssml",G));return X.includes("<speak")?X:null}catch(X){return console.debug("[TTSService] Math SSML generation failed; using plain",{message:X instanceof Error?X.message:String(X)}),null}},V1=async(Q,Y={})=>{if(!Q.some((B)=>B.type==="math"))return{speechText:S(Q.map((B)=>B.type==="text"?B.text:B.fallbackText).join(" ")),usedMathSpeech:!1,usedFallback:!1};let J=null,G=!1,X=!1,j=Y.loadSre||B2,Z=[];for(let B of Q){if(B.type==="text"){Z.push(B.text);continue}try{if(!J)J=await j();let U=S(await J6(J,B.mathml,Y.language,"none",Y.mathSpeech));if(U){Z.push(U),G=!0;continue}X=!0,Z.push(B.fallbackText)}catch(U){X=!0,console.debug("[TTSService] Math speech generation failed; using visible fallback",{message:U instanceof Error?U.message:String(U)}),Z.push(B.fallbackText)}}let q=S(Z.join(" ")),K;if(Y.produceSsml&&J&&G&&Q.length===1&&Q[0].type==="math")K=await F2(J,Q[0].mathml,Y.language,Y.mathSpeech)??void 0;return{speechText:q,usedMathSpeech:G,usedFallback:X,ssml:K}};var A2=(Q,Y)=>V1([Q],Y),M2=(Q)=>(Q||"en").split("-")[0].toLowerCase()||"en",N2=new Set(["H1","H2","H3","H4","H5","H6","LI","LABEL","BUTTON"]),z2=new Set(["heading","listitem","option","radio"]),O2=(Q)=>{if(Q.type!=="text"||!Q.sourceElement)return!1;let Y=Q.sourceElement.tagName.toUpperCase(),J=(Q.sourceElement.getAttribute("role")||"").toLowerCase();return N2.has(Y)||z2.has(J)},B8=async(Q)=>{let Y=Q.resolveMathSpeech??A2,{visibleText:J}=Q,G=[],X=0,j=(q)=>{let K=S(q),B=J.indexOf(K,X),U=B>=0?B:X,H=U+K.length;return X=H,{start:U,end:H}},Z=[];for(let q=0;q<Q.chunks.length;q++){let K=Q.chunks[q];if(K.type==="text"){let A=O2(K)?[{text:K.text,offset:0}]:R7(K.text,{locale:Q.language});for(let M of A){let O=S(M.text);if(!O)continue;let L=j(O);G.push({sourceChunkIndex:q,segment:{kind:"prose",spokenText:O,visibleText:O,visibleSpan:L}}),Z.push(O)}continue}let B=j(K.fallbackText),U=await Y(K,{language:Q.language,produceSsml:Q.produceSsml,mathSpeech:Q.mathSpeech}),H=!U.speechText,_=U.speechText||K.fallbackText;G.push({sourceChunkIndex:q,segment:{kind:"math",spokenText:_,mathml:K.mathml,fallbackText:K.fallbackText,visibleSpan:B,usedFallback:H,ssml:U.ssml}}),Z.push(_)}return{segments:G,locale:M2(Q.language),visibleText:J,plainSpeechText:S(Z.join(" "))}};var P2=(Q)=>(Q||"en").split("-")[0].toLowerCase()||"en",L2="sre-v1",$2=256,D8=(Q)=>{if(Array.isArray(Q))return`array:[${Q.map(D8).join(",")}]`;if(Q&&typeof Q==="object")return`object:{${Object.entries(Q).sort(([Y],[J])=>Y.localeCompare(J)).map(([Y,J])=>`${JSON.stringify(Y)}:${D8(J)}`).join(",")}}`;if(Q===null)return"null:null";if(typeof Q>"u")return"undefined:";if(typeof Q==="function")return`function:${Q.name||"anonymous"}`;if(typeof Q==="symbol")return`symbol:${String(Q)}`;if(typeof Q==="bigint")return`bigint:${Q.toString()}`;if(typeof Q==="number")return Number.isFinite(Q)?`number:${Q}`:`number:${String(Q)}`;return`${typeof Q}:${JSON.stringify(Q)}`},G6=(Q,Y,J,G)=>`${L2}\x00${P2(Q)}\x00${Y?"ssml":"plain"}\x00${D8(J??null)}\x00${G}`,V8=(Q={})=>{let Y=Math.max(1,Q.maxEntries??$2),J=Q.resolve??((j,Z)=>V1([j],Z)),G=new Map,X=(j,Z)=>{G.delete(j),G.set(j,Z);while(G.size>Y){let q=G.keys().next().value;if(q!==void 0)G.delete(q)}};return async(j,Z)=>{let q=z7(Z.mathSpeech),K=Z.produceSsml===!0,B=G6(Z.language,K,q,j.mathml),U=G.get(B);if(U)return G.delete(B),G.set(B,U),U;let H=await J(j,{...Z,mathSpeech:q});if(K&&H.ssml&&Y>1)X(G6(Z.language,!1,q,j.mathml),{speechText:H.speechText,usedMathSpeech:H.usedMathSpeech,usedFallback:H.usedFallback});return X(B,H),H}};var w2=(Q)=>{if(!Q||/^<[^>]+>$/.test(Q.trim()))return null;return A7({speechText:Q}).tokens[0]?.normalized||null},R2=(Q,Y)=>{let J=A7({speechText:Q.speechText});if(!Number.isFinite(Y.position))return{boundary:null,spokenText:J.spokenText};let G=W8({tokenization:J,position:Y.position,length:Y.length,boundaryWord:Y.word});return{boundary:G?{start:G.start,length:G.length}:null,spokenText:J.spokenText}},E2=(Q,Y,J)=>{if(!J)return!0;return A7({speechText:Q}).tokens.find((X)=>X.start<=Y&&Y<X.end)?.normalized===J},X6=(Q,Y)=>{let J=w2(Y.word);if(Q.id!==Y.chunkId)return{chunkId:Y.chunkId,normalizedWord:J,chunkSpokenStart:null,chunkSpokenEnd:null,confidence:0,reason:"boundary chunk id did not match highlight chunk"};if(Y.providerOffsetSpace==="unknown"||Q.offsetSpace==="unsupported")return{chunkId:Q.id,normalizedWord:J,chunkSpokenStart:null,chunkSpokenEnd:null,confidence:0,reason:"boundary offset space is unsupported"};let G,X;if(Q.catalogAlignment)G=C9(Q.catalogAlignment,Y.position,Y.length,Y.word),X=Q.catalogAlignment.spokenText;else{let j=R2(Q,Y);G=j.boundary,X=j.spokenText}if(!G)return{chunkId:Q.id,normalizedWord:J,chunkSpokenStart:null,chunkSpokenEnd:null,confidence:0,reason:"could not resolve provider boundary to chunk speech"};if(!E2(X,G.start,J))return{chunkId:Q.id,normalizedWord:J,chunkSpokenStart:null,chunkSpokenEnd:null,confidence:0,reason:"could not resolve provider boundary to matching word"};return{chunkId:Q.id,normalizedWord:J,chunkSpokenStart:G.start,chunkSpokenEnd:G.start+G.length,confidence:J?1:0.75,reason:Q.catalogAlignment?"resolved through catalog alignment":"resolved through speech tokenization"}};var O7=(Q)=>{if(Q.semanticTarget)return{activeTarget:Q.semanticTarget,regionTarget:Q.regionTarget,quality:Q.semanticTarget.quality==="exact-word"?"exact-word":Q.semanticTarget.quality==="expression"?"expression":"semantic-token",confidence:Q.confidence,reason:Q.reason};if(Q.expressionTarget)return{activeTarget:Q.expressionTarget,regionTarget:Q.regionTarget,quality:"expression",confidence:Q.confidence,reason:Q.reason};return{activeTarget:null,regionTarget:Q.regionTarget,quality:"region",confidence:Q.confidence,reason:Q.reason}};var j6=new Map([["mi","mjx-mi"],["mn","mjx-mn"],["mo","mjx-mo"],["mtext","mjx-mtext"]]),H8="mi,mn,mo,mtext",q6="mjx-mi,mjx-mn,mjx-mo,mjx-mtext",K6=["mjx-mfrac","mjx-msqrt","mjx-mroot","mjx-mtable","mjx-munder","mjx-mover","mjx-munderover"].join(","),W6=(Q)=>{if(Q.type==="text-range")return Q.node.parentElement;return Q.element},H1=(Q)=>{let Y=Q;while(Y){if(Y.localName?.toLowerCase()==="mjx-container")return Y;Y=Y.parentElement}return null},Z6=(Q)=>{if(!Q)return!1;if(H1(Q))return!1;return!q1(Q)},U6=(Q)=>{let Y=Q.getBoundingClientRect?.();return Boolean(Y&&Y.width>0&&Y.height>0)},_8=(Q)=>{let Y=Q;while(Y){if(Y.localName?.toLowerCase()==="math")return Y;Y=Y.parentElement}return null},B6=(Q,Y)=>{if(Q.length===0)return!1;if(Q.length!==Y.length)return!1;for(let J=0;J<Q.length;J+=1){let G=j6.get(Q[J].localName.toLowerCase());if(!G)return!1;if(Y[J].localName.toLowerCase()!==G)return!1}return!0},b2=(Q,Y)=>{if(!Q)return null;if(!j6.has(Q.localName.toLowerCase()))return null;if(Y.querySelector(K6))return null;let J=_8(Q),G=Y.querySelector("mjx-math");if(!J||!G)return null;let X=Array.from(J.querySelectorAll(H8)),j=X.indexOf(Q);if(j<0)return null;let Z=Array.from(G.querySelectorAll(q6));if(!B6(X,Z))return null;let q=Z[j];if(!q||!U6(q))return null;return q},D6=(Q)=>{let Y=H1(Q);if(Y){if(Y.querySelector(K6))return"expression";let X=_8(Q)??Q,j=Y.querySelector("mjx-math");if(!j)return"expression";let Z=Array.from(X.querySelectorAll(H8)),q=Array.from(j.querySelectorAll(q6));if(!B6(Z,q))return"expression";return q.some((K)=>U6(K))?"token":"expression"}let J=_8(Q)??Q;return Array.from(J.querySelectorAll(H8)).some((X)=>!q1(X))?"token":"expression"},F8=(Q)=>{let Y=W6(Q),J=H1(Y);if(J){let G=b2(Y,J);if(G)return{type:"element",quality:"semantic-token",element:G};return{type:"element",quality:"expression",element:J}}if(Q.type==="text-range"){if(!Z6(Q.node.parentElement))return null;return{type:"text-range",quality:"semantic-token",node:Q.node,startOffset:Q.startOffset,endOffset:Q.endOffset}}if(!Z6(Q.element))return null;return{type:"element",quality:Q.quality==="region-fallback"?"expression":"semantic-token",element:Q.element}},V6=F8,H6=()=>{let Q=new WeakMap;return(Y)=>{let J=W6(Y),G=H1(J);if(!J||!G)return F8(Y);if(Q.has(J))return Q.get(J)??null;let X=F8(Y);return Q.set(J,X),X}};var _6=(Q,Y,J,G=Q.mathAlignments,X=V6)=>{if(Y.chunkSpokenStart===null||Y.chunkSpokenEnd===null)return null;let j=null;for(let Z of G){let q=g9(Z.alignment,{position:Y.chunkSpokenStart,length:Math.max(1,Y.chunkSpokenEnd-Y.chunkSpokenStart),boundaryWord:J.word})||c9(Z.alignment,{boundaryWord:J.word});if(!q)continue;let K=X(q);if(!K)continue;if(K.quality==="semantic-token")return K;j??=K}return j};var _1=(Q,Y,J)=>{if(!Q||typeof document>"u")return null;if(J<=Y)return null;let G=Q.get(Y),X=Q.get(Math.max(Y,J-1));if(!G)return null;if(!X)X=G;try{let j=document.createRange();return j.setStart(G.node,G.offset),j.setEnd(X.node,X.offset+1),j}catch{return null}};var F6=(Q,Y)=>{if(!Q.catalogAlignment||Y.chunkSpokenStart===null)return null;let J=y9(Q.catalogAlignment,Y.chunkSpokenStart);if(!J)return null;let G=_1(Q.visibleMap,J.start,J.end);if(!G)return null;return{type:"range",quality:Q.catalogAlignment.playbackMode==="exact-word"?"exact-word":"semantic-token",range:G}};var S2=(Q)=>Q.regionRange?{type:"range",quality:"region",range:Q.regionRange}:Q.regionElement?{type:"element",quality:"region",element:Q.regionElement}:null,A6=(Q,Y=Q.chunk.mathAlignments)=>{if(Y.length!==1)return null;let J=Y[0]?.alignment.result.fallbackTarget;return J?Q.renderedMathTargetResolver(J):null},T2=(Q,Y)=>{if(!Q)return Y.mathAlignments;return Y.mathAlignments.filter(({element:J})=>{try{if(Q.type==="range")return Q.range.intersectsNode(J);if(Q.type==="element")return Q.element===J||Q.element.contains(J);return Q.node.parentElement?.contains(J)||!1}catch{return!1}})},M6=()=>({activeTarget:null,regionTarget:null,quality:"region",confidence:0,reason:"boundary chunk id was not found"}),N6=(Q)=>Q.length===1?Q[0].element:null,C2=(Q,Y)=>Y.length>0&&Y.every(({element:J})=>Q.mathCapabilityByElement.get(J)==="token"),y2=3,x2=(Q,Y,J)=>{if(!Y||Y.type!=="range")return!1;let{startContainer:G,endContainer:X}=Y.range;if(G===X&&G.nodeType===y2)return!1;return J.some(({element:Z})=>Q.mathCapabilityByElement.get(Z)==="token"&&Z.contains(G)&&Z.contains(X))},f2=(Q,Y)=>({chunk:Q,regionTarget:S2(Q),renderedMathTargetResolver:H6(),mathCapabilityByElement:new Map(Q.mathAlignments.map(({element:J})=>[J,Y?D6(J):"expression"])),heldTokenByElement:new Map}),z6=(Q)=>{let Y=Q.mathTokenHighlighting!==!1,J=new Map(Q.chunks.map((G)=>[G.id,f2(G,Y)]));return{chunks:Q.chunks,resolveInitial(G){let X=J.get(G);if(!X)return M6();let j=X.chunk.mathAlignments,Z=j.length===1?j[0].element:null,q=Z?X.mathCapabilityByElement.get(Z):null;if(q==="expression")return O7({semanticTarget:null,expressionTarget:A6(X),regionTarget:X.regionTarget,confidence:0.5,reason:"initial expression (sticky expression mode)"});return O7({semanticTarget:null,expressionTarget:null,regionTarget:X.regionTarget,confidence:0,reason:q==="token"?"initial region (sticky token mode, awaiting first token)":"initial region fallback"})},resolveBoundary(G){let X=J.get(G.chunkId);if(!X)return M6();let{chunk:j}=X,Z=X6(j,G),q=F6(j,Z),K=T2(q,j),B=(!q||K.length>0?_6(j,Z,G,K,X.renderedMathTargetResolver):null)||null,U=Y&&B&&B.quality!=="expression"?B:null,H=B&&B.quality==="expression"?B:null;if(U){let _=N6(K);if(_)X.heldTokenByElement.set(_,U);return O7({semanticTarget:U,expressionTarget:null,regionTarget:X.regionTarget,confidence:Z.confidence,reason:Z.reason})}if(q&&(Y?!x2(X,q,K):K.length===0))return O7({semanticTarget:q,expressionTarget:null,regionTarget:X.regionTarget,confidence:Z.confidence,reason:Z.reason});if(C2(X,K)){let _=N6(K),A=_?X.heldTokenByElement.get(_)??null:null;return O7({semanticTarget:A,expressionTarget:null,regionTarget:X.regionTarget,confidence:Z.confidence,reason:A?"hold last token (sticky token mode)":"region (sticky token mode, awaiting first token)"})}return O7({semanticTarget:null,expressionTarget:H??A6(X,K),regionTarget:X.regionTarget,confidence:Z.confidence,reason:Z.reason})}}};var k2=(Q)=>{if(Q.alignment?.boundaryOffsetMode)return Q.alignment.boundaryOffsetMode;let Y=Q.mathAlignment?.speech.boundaryOffsetSpace;if(Y)return Y;return"plain-spoken-text"},I2=(Q)=>{if(Q.mathAlignments?.length)return Q.mathAlignments;if(Q.mathAlignment&&Q.sourceElement)return[{element:Q.sourceElement,alignment:Q.mathAlignment}];return[]},O6=(Q)=>{return(Q.chunks&&Q.chunks.length?Q.chunks:[{speechText:Q.speechText||"",visibleText:Q.visibleText||Q.speechText||"",sourceElement:Q.sourceElement||Q.contentRoot,regionElement:Q.regionElement||Q.sourceElement||Q.contentRoot,regionRange:Q.regionRange,visibleMap:Q.visibleMap}]).map((J,G)=>({id:`tts-chunk-${G}`,speechText:J.speechText,visibleText:J.visibleText,sourceElement:J.sourceElement,contentRoot:Q.contentRoot,regionElement:J.regionElement??J.sourceElement,regionRange:J.regionRange,visibleMap:J.visibleMap,catalogAlignment:J.alignment,mathAlignments:I2(J),offsetSpace:k2(J)}))};var v2=["[data-pie-tts-region]","[data-catalog-region]","li","p","label","section","[role='group']","[role='region']","div"].join(","),F1=(Q,Y)=>{let J=Q.closest(v2);if(J&&Y.contains(J))return J;return Q};var h2=(Q,Y,J)=>{let G=new Map;for(let X=Y;X<J;X++){let j=Q.get(X);if(j)G.set(X-Y,j)}return G},A8=async(Q)=>{let Y=N7(Q.contentRoot,Q.textProcessingOptions),J=await B8({chunks:Y.chunks,visibleText:Y.visibleText,language:Q.language,mathSpeech:Q.mathSpeech,produceSsml:Q.produceSsml,resolveMathSpeech:Q.resolveMathSpeech});return{plan:{items:J.segments.map(({segment:X,sourceChunkIndex:j})=>{let Z=Y.chunks[j];if(X.kind==="prose"){let K=Z?.type==="text"?Z.sourceElement??Q.contentRoot:Q.contentRoot;return{segment:X,anchor:{sourceElement:K,regionElement:F1(K,Q.contentRoot),visibleMap:h2(Y.map,X.visibleSpan.start,X.visibleSpan.end)}}}let q=Z?.type==="math"?Z.sourceElement??null:null;return{segment:X,anchor:{sourceElement:q,regionElement:q}}}),locale:J.locale,visibleText:J.visibleText,plainSpeechText:J.plainSpeechText},containsMathMarkup:Y.containsMathMarkup,visibleText:Y.visibleText}};var m2=(Q,Y)=>{let J=B1({speechText:Q.spokenText,visibleText:Q.spokenText});return{speechText:Q.spokenText,visibleText:Q.visibleText,sourceElement:Y.sourceElement,regionElement:Y.regionElement,regionRange:_1(Y.visibleMap,0,Q.visibleText.length)??void 0,speechMatchesVisibleText:!0,playbackMode:J.playbackMode,alignment:J,visibleMap:Y.visibleMap}},P6=(Q,Y)=>{let J=Y.sourceElement;return{speechText:Q.spokenText,visibleText:Q.fallbackText,sourceElement:J,regionElement:Y.regionElement,speechMatchesVisibleText:Q.spokenText===Q.fallbackText,mathAlignment:J?T7({mathElement:J,speechText:Q.spokenText}):void 0}},u2=(Q,Y,J)=>{let G=Y.sourceElement;return{speechText:J,visibleText:Q.fallbackText,sourceElement:G,regionElement:Y.regionElement,speechMatchesVisibleText:!1,mathAlignment:G?T7({mathElement:G,speechText:J}):void 0,plainFallback:P6(Q,Y)}},M8=(Q,Y={})=>Q.items.map(({segment:J,anchor:G})=>{if(J.kind==="prose")return m2(J,G);if(Y.format==="ssml"&&J.ssml)return u2(J,G,J.ssml);return P6(J,G)});var L6="pie-tts-control-handoff";var E;(function(Q){Q.IDLE="idle",Q.LOADING="loading",Q.PLAYING="playing",Q.PAUSED="paused",Q.ERROR="error"})(E||(E={}));var $6=(Q,Y)=>Q===Y||Q.startContainer===Y.startContainer&&Q.startOffset===Y.startOffset&&Q.endContainer===Y.endContainer&&Q.endOffset===Y.endOffset,p2=(Q,Y)=>{if(Q===Y)return!0;if(!Q||!Y||Q.type!==Y.type||Q.quality!==Y.quality)return!1;if(Q.type==="range"&&Y.type==="range")return $6(Q.range,Y.range);if(Q.type==="element"&&Y.type==="element")return Q.element===Y.element;if(Q.type==="text-range"&&Y.type==="text-range")return Q.node===Y.node&&Q.startOffset===Y.startOffset&&Q.endOffset===Y.endOffset;return!1};class u7{currentProvider=null;provider=null;highlightCoordinator=null;highlightTargetResolverProvider=null;catalogResolver=null;state=E.IDLE;ttsConfig={};currentText=null;currentContentElement=null;normalizedToDOM=new Map;listeners=new Map;lastError=null;speakRunId=0;currentBoundaryOffset=0;activeWordBoundaryOffset=0;seekSegments=[];playbackChunks=[];activeRecordedAudio=null;sentenceHighlightSegments=[];currentSeekSegmentIndex=0;activeSentenceStartOffset=null;playbackStartDeferredRunId=null;pendingPlaybackStartHighlights=[];playbackStartBarrierCleanup=null;playbackRateWriteQueue=Promise.resolve();playbackRateRequestId=0;pendingPlaybackRateRequest=null;activePlaybackRate=null;activeHighlightMode="word";lastRenderedRegionTarget=null;telemetryReporter=null;generatedMathSpeechResolver=V8();static debugEnabled=(()=>{try{if(typeof process<"u"&&process.env?.PIE_TTS_DEBUG==="1")return!0}catch{}return globalThis.__PIE_TTS_DEBUG__===!0})();constructor(){}debugLog(Q,Y){if(!u7.debugEnabled)return;if(Y===void 0)console.debug(Q);else console.debug(Q,Y)}clearPlaybackStartBarrier(Q=this.playbackStartBarrierCleanup){if(Q?.(),this.playbackStartBarrierCleanup===Q)this.playbackStartBarrierCleanup=null}notifyPlaybackStarted(Q){if(this.playbackStartDeferredRunId!==Q||Q!==this.speakRunId)return;this.setState(E.PLAYING);let Y=this.pendingPlaybackStartHighlights.splice(0);for(let J of Y)J()}installPlaybackStartBarrier(Q,Y=!1){this.clearPlaybackStartBarrier();let J=this.provider,G=J&&"onPlaybackStart"in J?J:null;if(!G&&!Y)return null;let X=G?.onPlaybackStart,j=()=>{try{this.notifyPlaybackStarted(Q)}finally{X?.()}};if(G)G.onPlaybackStart=j;this.playbackStartDeferredRunId=Q;let Z=()=>{if(G?.onPlaybackStart===j)G.onPlaybackStart=X;if(this.playbackStartDeferredRunId===Q)this.playbackStartDeferredRunId=null,this.pendingPlaybackStartHighlights=[]};return this.playbackStartBarrierCleanup=Z,Z}runWhenPlaybackStarts(Q,Y){if(this.playbackStartDeferredRunId===Q){this.pendingPlaybackStartHighlights.push(Y);return}Y()}async emitTelemetry(Q,Y){try{await this.telemetryReporter?.(Q,Y)}catch(J){console.warn("[TTSService] telemetry callback failed:",J)}}async initialize(Q,Y={}){this.currentProvider=Q,this.ttsConfig={...Y};let J=Y.providerOptions&&typeof Y.providerOptions==="object"?Y.providerOptions:{};this.telemetryReporter=typeof J.__pieTelemetry==="function"?J.__pieTelemetry:null;try{this.provider=await Q.initialize(Y)}catch(G){if(Q.providerId.toLowerCase()==="browser")throw G;if(!this.isBrowserSpeechFallbackAvailable())throw G;if(!await this.switchProviderToBrowser(G,{operation:"tts-initialize"}))throw G}}async updateSettings(Q){if(!this.provider)throw Error("TTSService not initialized. Call initialize() first.");let Y=this.provider;if(typeof Y.updateSettings==="function"){let J={...Q,...Q.providerOptions?{providerOptions:{...this.ttsConfig.providerOptions||{},...Q.providerOptions}}:{}};await Y.updateSettings(J),this.ttsConfig={...this.ttsConfig,...J}}else console.warn("[TTSService] Provider does not support dynamic settings updates. Some settings may require reinitialization.")}setHighlightCoordinator(Q){this.highlightCoordinator=Q}setHighlightTargetResolverProvider(Q){return this.highlightTargetResolverProvider=Q,()=>{if(this.highlightTargetResolverProvider===Q)this.highlightTargetResolverProvider=null}}setCatalogResolver(Q){this.catalogResolver=Q}hasSpokenAlternate(Q,Y="en-US"){if(!Q||!this.catalogResolver)return!1;return this.catalogResolver.getAlternative(Q,{type:"spoken",language:Y,useFallback:!0,form:"content"})?.content!==void 0}getHighlightResolverRuntime(){let Q=null;try{Q=this.highlightTargetResolverProvider?.()??null}catch{Q=null}let Y=Q?.context??{},J=typeof HTMLElement<"u"&&this.currentContentElement instanceof HTMLElement?this.currentContentElement:null;return{context:{...Y,scopeElement:Y.scopeElement??J},resolver:Q?.resolver??null}}getNodeElement(Q){if(!Q)return null;return Q.nodeType===Node.ELEMENT_NODE?Q:Q.parentElement}isElementWithinScope(Q,Y){if(!Y)return!0;return Q===Y||Y.contains(Q)}isRangeWithinScope(Q,Y){let J=this.getNodeElement(Q.startContainer),G=this.getNodeElement(Q.endContainer);if(!J||!G)return!1;return this.isElementWithinScope(J,Y)&&this.isElementWithinScope(G,Y)}resolveWordHighlightRange(Q){let{context:Y,resolver:J}=this.getHighlightResolverRuntime(),G=Y.scopeElement??this.currentContentElement;try{let X=J?.resolveWordRange?.(Q,Y);if(X&&this.isRangeWithinScope(X,G))return{range:X,remapped:!$6(Q,X)}}catch{}return{range:Q,remapped:!1}}resolveSentenceHighlightTargets(Q){let{context:Y,resolver:J}=this.getHighlightResolverRuntime(),G=Y.scopeElement??this.currentContentElement;try{let X=J?.resolveSentenceRanges?.(Q,Y);if(!X)return{ranges:Q,elements:[]};let j=[],Z=[];for(let q of X){if(typeof Range<"u"&&q instanceof Range){if(!this.isRangeWithinScope(q,G))return{ranges:Q,elements:[]};j.push(q);continue}if(typeof Element<"u"&&q instanceof Element){if(!this.isElementWithinScope(q,G))return{ranges:Q,elements:[]};Z.push(q);continue}return{ranges:Q,elements:[]}}return{ranges:j,elements:Z}}catch{return{ranges:Q,elements:[]}}}createTextRange(Q,Y,J){if(typeof document>"u")return null;if(typeof document.createRange!=="function")return null;try{let G=document.createRange();if(G.setStart(Q,Y),G.setEnd(Q,J),G.startContainer!==Q||G.endContainer!==Q)return null;return G}catch{return null}}paintTTSWordRange(Q){if(!this.highlightCoordinator)return;try{if(Q.startContainer===Q.endContainer&&Q.startContainer.nodeType===Node.TEXT_NODE){this.highlightCoordinator.highlightTTSWord(Q.startContainer,Q.startOffset,Q.endOffset);return}}catch{}this.highlightCoordinator.highlightRange(Q,m.TTS_WORD,D7.YELLOW)}paintTTSSentenceRanges(Q){if(!this.highlightCoordinator)return;let{ranges:Y,elements:J}=this.resolveSentenceHighlightTargets(Q);if(J.length>0&&Y.length===0&&this.highlightCoordinator.highlightTTSSentenceElements){this.highlightCoordinator.highlightTTSSentenceElements(J);return}let G=[...Y];for(let X of J){let j=document.createRange();j.selectNodeContents(X),G.push(j)}this.highlightCoordinator.highlightTTSSentence(G)}getCapabilities(){return this.currentProvider?.getCapabilities()||null}getTextProcessingOptions(Q){let J=(this.ttsConfig.providerOptions||{}).textNormalization||{},G=J.boundarySpacingMode,X=G==="none"||G==="alnum"||G==="segmenterPreferred"?G:void 0;return{locale:Q||(typeof J.locale==="string"?J.locale:void 0),boundarySpacingMode:X}}getMathSpeechOptions(){let Y=(this.ttsConfig.providerOptions||{}).mathSpeech;return z7(Y)}buildPositionMap(Q,Y,J){this.normalizedToDOM.clear();let{text:G,map:X}=b7(Q,this.getTextProcessingOptions(J));if(this.normalizedToDOM=X,!u7.debugEnabled)return;this.debugLog("[TTSService] Text comparison:",{spokenLength:Y.length,normalizedDomLength:G.length,match:Y===G,spokenPreview:Y.substring(0,150),normalizedPreview:G.substring(0,150),differAtIndex:Y===G?null:(()=>{for(let j=0;j<Math.min(Y.length,G.length);j++)if(Y[j]!==G[j])return{index:j,spokenChar:Y[j],normalizedChar:G[j],spokenContext:Y.substring(Math.max(0,j-20),j+20),normalizedContext:G.substring(Math.max(0,j-20),j+20)};return null})()}),this.debugLog("[TTSService] Position map built:",{entries:this.normalizedToDOM.size,spokenTextLength:Y.length,normalizedDomLength:G.length,mapLengthMatchesSpoken:this.normalizedToDOM.size===Y.length,firstFewMappings:Array.from(this.normalizedToDOM.entries()).slice(0,10).map(([j,{node:Z,offset:q}])=>({pos:j,offset:q,char:Z.textContent?.[q],expected:Y[j]}))})}getStructuralPauseProfile(){let Y=(this.ttsConfig.providerOptions||{}).structuralPauses||{},J=Y.units||{},G=(X,j)=>{if(typeof X==="number"&&Number.isFinite(X))return X;if(typeof X==="string"&&X.trim()){let Z=Number(X);return Number.isFinite(Z)?Z:j}return j};return{baseMs:G(Y.baseMs,280),units:{minor:G(J.minor,0.65),section:G(J.section,1),major:G(J.major,1.35)},minMs:G(Y.minMs,120),maxMs:G(Y.maxMs,900)}}resolvePauseMsFromUnits(Q){let Y=this.getStructuralPauseProfile(),J=Math.max(0.25,Math.min(4,Number(this.ttsConfig.rate||1))),G=Y.baseMs*Math.max(0,Q)/J;return Math.max(Y.minMs,Math.min(Y.maxMs,Math.round(G)))}resolveHighlightMode(){let Y=(this.ttsConfig.providerOptions||{}).highlightMode;if(Y==="word"||Y==="sentence")return Y;if((this.currentProvider?.providerId||"").toLowerCase()==="browser")return"sentence";return this.currentProvider?.getCapabilities().supportsWordBoundary??!1?"word":"sentence"}hasExplicitBreakSemantics(Q){if(!Q.includes("<"))return!1;return/<\s*break\b|<\s*speak\b|<\s*prosody\b|<\s*p\b|<\s*s\b/i.test(Q)}isElementHidden(Q){return e1(Q)}getBoundaryStrength(Q){let Y=Number(Q.getAttribute("data-tts-break-ms"));if(Number.isFinite(Y)&&Y>0)return"major";let J=Q.tagName.toUpperCase();if(J.match(/^H[1-6]$/))return"major";let G=(Q.getAttribute("role")||"").toLowerCase();if(G==="heading")return"major";if(G==="listitem"||G==="row"||G==="option"||G==="radio"||J==="LI")return"section";if(typeof window<"u"){let X=window.getComputedStyle(Q).display;if(X==="block"||X==="list-item"||X.startsWith("table")||X==="flex"||X==="grid")return"minor"}return"minor"}getBoundaryAnchor(Q,Y){let J=Q.parentElement,G=null;while(J&&J!==Y){if(this.isElementHidden(J))return null;let j=Number(J.getAttribute("data-tts-break-ms"));if(Number.isFinite(j)&&j>0)return{anchor:J,units:j/this.getStructuralPauseProfile().baseMs};let Z=(J.getAttribute("role")||"").toLowerCase(),q=J.tagName.toUpperCase();if(q.match(/^H[1-6]$/)||Z==="heading"||Z==="listitem"||q==="LI"){G=J;break}if(!G){if(typeof window<"u"){let K=window.getComputedStyle(J).display;if(K==="block"||K==="list-item"||K.startsWith("table")||K==="flex"||K==="grid")G=J}}J=J.parentElement}if(!G)return null;let X=this.getBoundaryStrength(G);return{anchor:G,units:this.getStructuralPauseProfile().units[X]}}createSpeechPlan(Q,Y){let J=this.collectSpeechPlanBoundaries(Q,Y);return this.createSpeechPlanSegments(Y,J)}collectSpeechPlanBoundaries(Q,Y){let J=new Map,{map:G}=b7(Q,this.getTextProcessingOptions()),X=this.createNodeStartOffsets(G),j=document.createTreeWalker(Q,NodeFilter.SHOW_TEXT),Z=j.nextNode(),q=null;while(Z){let K=Z,B=K.parentElement;if(B&&!this.isElementHidden(B)&&!K1(K)){let U=this.getBoundaryAnchor(K,Q),H=X.get(K);if(U&&H!==void 0&&U.anchor!==q&&H>0)J.set(H,Math.max(J.get(H)||0,U.units)),q=U.anchor}Z=j.nextNode()}return J}createNodeStartOffsets(Q){let Y=new Map;for(let[J,G]of Q.entries())if(!Y.has(G.node))Y.set(G.node,J);return Y}createSpeechPlanSegments(Q,Y){let J=Array.from(Y.keys()).filter((K)=>K>0&&K<Q.length).sort((K,B)=>K-B),G=[],X=0;for(let K of J){let B=Q.substring(X,K),U=B.match(/^\s*/)?.[0].length||0,H=B.match(/\s*$/)?.[0].length||0,_=X+U,A=K-H;if(A>_){let M=Q.substring(_,A);G.push({text:M,startOffset:_,pauseMsAfter:this.resolvePauseMsFromUnits(Y.get(K)||0)})}X=K}let Z=Q.substring(X).match(/^\s*/)?.[0].length||0,q=X+Z;if(q<Q.length)G.push({text:Q.substring(q).trimEnd(),startOffset:q,pauseMsAfter:0});return G.filter((K)=>K.text.trim().length>0)}segmentSentences(Q){let Y=this.ttsConfig.providerOptions?.locale||void 0;return R7(Q,{locale:Y})}createSeekSegmentsFromText(Q){return this.segmentSentences(Q).map((Y)=>{let J=Y.text.match(/^\s*/)?.[0].length||0;return{text:Y.text.trim(),startOffset:Y.offset+J,pauseMsAfter:0}}).filter((Y)=>Y.text.length>0)}splitSegmentsAtBoundaries(Q,Y,J){if(Q.length===0||Y.length===0)return Q;let G=Array.from(new Set(Y)).filter((j)=>Number.isFinite(j)&&j>0).sort((j,Z)=>j-Z);if(G.length===0)return Q;let X=[];for(let j of Q){let Z=j.startOffset,q=j.startOffset+j.text.length,K=G.filter((U)=>U>Z&&U<q);if(K.length===0){X.push(j);continue}let B=Z;for(let U of[...K,q]){let H=J.substring(B,U),_=H.match(/^\s*/)?.[0].length||0,A=H.match(/\s*$/)?.[0].length||0,M=B+_,O=U-A;if(O>M)X.push({text:J.substring(M,O),startOffset:M,pauseMsAfter:0});B=U}}return X}createSentenceHighlightSegments(Q){let Y=this.createSeekSegmentsFromText(Q.contentToSpeak);if(!Q.shouldUsePlan||Q.playbackSegments.length===0)return Y;let J=Q.playbackSegments.map((G)=>G.startOffset).filter((G)=>G>0);return this.splitSegmentsAtBoundaries(Y,J,Q.contentToSpeak)}createSeekSegmentsFromSpeechChunks(Q){let Y=0;return Q.map((J)=>{let G=J.plainFallback?.speechText||(this.hasExplicitBreakSemantics(J.speechText)?J.visibleText:J.speechText)||J.visibleText,X=S(G)||J.visibleText||"",j={text:X,startOffset:Y,pauseMsAfter:0};return Y+=Math.max(1,X.length+1),j})}getCurrentSeekSegmentIndex(){if(this.seekSegments.length===0)return 0;let Q=0;for(let Y=0;Y<this.seekSegments.length;Y++)if(this.seekSegments[Y].startOffset<=this.currentBoundaryOffset)Q=Y;else break;return Q}async speakWithPlan(Q,Y,J){if(!this.provider||Q.length===0)return;let G=J?.highlightMode==="sentence",X=this.provider;if(!G&&typeof X.speakSegments==="function"){this.currentBoundaryOffset=0;let j=this.provider.onWordBoundary;this.provider.onWordBoundary=(Z,q,K)=>{if(j?.(Z,q,K),Number.isFinite(q))this.currentBoundaryOffset=q,this.currentSeekSegmentIndex=this.getCurrentSeekSegmentIndex()};try{await X.speakSegments(Q)}finally{if(Y===this.speakRunId&&this.provider===X)this.provider.onWordBoundary=j}return}this.configureWordBoundaryHighlighting({highlightMode:J?.highlightMode||"word",wordBoundaryOffset:this.activeWordBoundaryOffset});for(let j of Q){if(Y!==this.speakRunId)return;let Z=this.seekSegments.findIndex((K)=>K.startOffset===j.startOffset);if(Z>=0)this.currentSeekSegmentIndex=Z;if(this.currentBoundaryOffset=j.startOffset,G)this.runWhenPlaybackStarts(Y,()=>{this.highlightSentenceSegment(j.startOffset,j.text)});await this.provider.speak(j.text);let q=j.pauseMsAfter??0;if(q>0)await new Promise((K)=>setTimeout(K,q))}}highlightSentenceSegment(Q,Y){if(!this.highlightCoordinator||typeof document>"u")return;let J=Y.trimEnd().length;if(J<=0)return;let G=this.normalizedToDOM.get(Q),X=this.normalizedToDOM.get(Q+J-1);if(!G||!X)return;let j=document.createRange();j.setStart(G.node,G.offset),j.setEnd(X.node,X.offset+1),this.paintTTSSentenceRanges([j]),this.activeSentenceStartOffset=Q}getSegmentIndexForOffset(Q,Y){if(Q.length===0)return-1;let J=-1;for(let G=0;G<Q.length;G++)if(Q[G].startOffset<=Y)J=G;else break;return J}highlightSentenceForOffset(Q){let Y=this.sentenceHighlightSegments;if(!this.highlightCoordinator||Y.length===0)return;let J=this.getSegmentIndexForOffset(Y,Q);if(J<0)return;let G=Y[J];if(!G)return;if(this.activeSentenceStartOffset===G.startOffset)return;this.highlightSentenceSegment(G.startOffset,G.text)}findHighlightRange(Q,Y){let J=this.normalizedToDOM.get(Q);if(!J)return console.warn(`[TTSService] No mapping found for start position ${Q}`,{totalMappings:this.normalizedToDOM.size,nearbyMappings:Array.from(this.normalizedToDOM.entries()).filter(([j])=>Math.abs(j-Q)<5).map(([j,{offset:Z,node:q}])=>({pos:j,offset:Z,char:q.textContent?.[Z]}))}),null;let G=Q+Y-1,X=this.normalizedToDOM.get(G);if(!X)return console.warn(`[TTSService] No mapping found for end position ${G}`,{startChar:Q,length:Y,totalMappings:this.normalizedToDOM.size}),null;if(J.node!==X.node)return console.warn("[TTSService] Word spans multiple nodes, highlighting in first node only"),{node:J.node,start:J.offset,end:(J.node.textContent||"").length};return{node:J.node,start:J.offset,end:X.offset+1}}async speak(Q,Y){if(!this.provider)throw Error("TTS service not initialized");let J=++this.speakRunId;this.clearPlaybackStartBarrier();let G=null;try{if(await this.applyLanguageSettings(Y),J!==this.speakRunId)return;let X=await this.resolveSpeechContent(Q,Y);if(J!==this.speakRunId)return;let{contentToSpeak:j,speechText:Z,highlightText:q,normalizedText:K,usedCatalogSpoken:B,speechSource:U,speechMatchesVisibleText:H,speechChunks:_}=X;this.logResolvedSpeechContent({contentToSpeak:j,speechSource:U,catalogId:Y?.catalogId}),this.initializeSpeakTracking(q,Y);let A=Y?.highlightModeOverride||(H?this.resolveHighlightMode():"sentence");this.activeHighlightMode=A,this.activeWordBoundaryOffset=Y?.wordBoundaryOffset||0;let M=this.hasExplicitBreakSemantics(j),O=!!this.currentContentElement&&!B&&!M&&H;if(this.playbackChunks=_?.length?_:[],this.seekSegments=this.playbackChunks.length?this.createSeekSegmentsFromSpeechChunks(this.playbackChunks):M||!H?[]:O&&this.currentContentElement?this.createSpeechPlan(this.currentContentElement,K):this.createSeekSegmentsFromText(q),this.sentenceHighlightSegments=M?[]:this.createSentenceHighlightSegments({contentToSpeak:q,shouldUsePlan:O,playbackSegments:this.seekSegments}),this.setState(E.LOADING),G=this.installPlaybackStartBarrier(J,!!this.playbackChunks[0]?.audio),this.prepareHighlightsForSpeak({contentToSpeak:q,options:Y,highlightMode:A,shouldUsePlan:O,runId:J}),H)this.configureWordBoundaryHighlighting({highlightMode:A,wordBoundaryOffset:Y?.wordBoundaryOffset||0});else this.clearWordBoundaryHighlighting();if(!G)this.setState(E.PLAYING);if(this.activePlaybackRate=this.normalizePlaybackRate(Number(this.ttsConfig.rate??1)),await this.executeSpeakPlayback({shouldUsePlan:O,runId:J,highlightMode:A,contentToSpeak:Z,speechChunks:_}),J!==this.speakRunId)return;this.setState(E.IDLE),this.clearHighlightsAndTracking()}catch(X){let j=X;if(console.error("TTS error:",j),this.lastError=j instanceof Error?j.message:String(j),J!==this.speakRunId)return;throw this.setState(E.ERROR),this.clearHighlightsAndTracking(),j}finally{this.clearPlaybackStartBarrier(G)}}async switchProviderToBrowser(Q,Y){if(!this.currentProvider)return!1;let J=new E7,G=this.currentProvider.providerId,X={};if(this.ttsConfig.rate!==void 0)X.rate=this.ttsConfig.rate;if(this.ttsConfig.pitch!==void 0)X.pitch=this.ttsConfig.pitch;if(this.ttsConfig.mathTokenHighlighting!==void 0)X.mathTokenHighlighting=this.ttsConfig.mathTokenHighlighting;let j=Y?.operation||"tts-initialize",Z=Y?.contentToSpeak??"",q=Z.replace(/\s+/g," ").trim().slice(0,120),K=Z.length>0?{textLength:Z.length,textPreview:q.length<Z.length?`${q}…`:q}:{};try{return this.provider?.stop(),this.currentProvider.destroy(),this.currentProvider=J,this.provider=await J.initialize(X),this.ttsConfig=X,await this.emitTelemetry("pie-tool-runtime-fallback",{toolId:"textToSpeech",operation:j,fromProvider:G,toProvider:J.providerId,reason:Q instanceof Error?Q.message:String(Q),...K}),console.warn("[TTSService] TTS provider initialization failed; switched to browser fallback",{fromProvider:G,reason:Q,...K}),!0}catch(B){return await this.emitTelemetry("pie-tool-runtime-fallback-error",{toolId:"textToSpeech",operation:j,fromProvider:G,toProvider:"browser",errorType:"TTSRuntimeFallbackError",message:B instanceof Error?B.message:String(B)}),console.error("[TTSService] Failed to switch to browser fallback provider",B),!1}}isBrowserSpeechFallbackAvailable(){if(typeof window>"u")return!1;if(!("speechSynthesis"in window))return!1;return typeof globalThis.SpeechSynthesisUtterance==="function"}async applyLanguageSettings(Q){if(!Q?.language||!this.provider)return;let Y=this.ttsConfig.providerOptions||{},J=Y.textNormalization||{},G=Y.segmenter||{},X={...Y,locale:Q.language,textNormalization:{...J,locale:Q.language},segmenter:{...G,locale:Q.language}};if(this.ttsConfig={...this.ttsConfig,providerOptions:X},"updateSettings"in this.provider&&typeof this.provider.updateSettings==="function")await this.provider.updateSettings({providerOptions:X})}async resolveSpeechContent(Q,Y){let J=S(Q);if(Y?.ignoreCatalogs)return{contentToSpeak:J,speechText:J,visibleText:J,highlightText:J,usedCatalogSpoken:!1,speechSource:"dom-or-input",normalizedText:J,containsMathMarkup:!1,speechMatchesVisibleText:!0};if(Y?.catalogId&&this.catalogResolver){let j=this.catalogResolver.getAlternative(Y.catalogId,{type:"spoken",language:Y.language||"en-US",useFallback:!0,context:Y.catalogContext,form:"content"}),Z=j?.content;if(j&&Z!==void 0){let q=Y?.contentElement?N7(Y.contentElement,this.getTextProcessingOptions(Y.language)).visibleText||J:J,K=S(Z);return this.debugLog(`[TTSService] Using catalog content for "${Y.catalogId}" (${j.language})`),{contentToSpeak:Z,speechText:Z,visibleText:q,highlightText:q,usedCatalogSpoken:!0,speechSource:"catalog-spoken",normalizedText:q,containsMathMarkup:!1,speechMatchesVisibleText:K===q}}this.debugLog(`[TTSService] No catalog found for "${Y.catalogId}", falling back to generated TTS`)}let G=Y?.contentElement?this.resolveCatalogComposedSpeechContent(Y.contentElement,J,Y):null;if(G)return G;return{...Y?.contentElement?await this.resolveGeneratedSpeechContent(Y.contentElement,J,Y.language):{contentToSpeak:J,speechText:J,visibleText:J,highlightText:J,normalizedText:J,containsMathMarkup:!1,speechMatchesVisibleText:!0},usedCatalogSpoken:!1,speechSource:"dom-or-input"}}resolveCatalogComposedSpeechContent(Q,Y,J){if(!this.catalogResolver)return null;let G=this.collectCatalogSpeechChunks(Q,J);if(!G.some((Z)=>Z.sourceElement))return null;let X=S(G.map((Z)=>Z.speechText).join(" ")),j=N7(Q,this.getTextProcessingOptions(J.language)).visibleText||Y;return{contentToSpeak:X,speechText:X,visibleText:j,highlightText:j,usedCatalogSpoken:!0,speechSource:"catalog-spoken",normalizedText:j,containsMathMarkup:!1,speechMatchesVisibleText:G.every((Z)=>Z.speechMatchesVisibleText),speechChunks:G}}collectCatalogSpeechChunks(Q,Y){let J=[],G="",X=()=>{let B=S(G);if(G="",!B)return;J.push({speechText:B,visibleText:B,sourceElement:null,speechMatchesVisibleText:!0})},j=(B)=>{let U=B.getAttribute("data-catalog-idref");if(!U)return null;let H={type:"spoken",language:Y.language||"en-US",useFallback:!0,context:Y.catalogContext},_=this.catalogResolver.getAlternative(U,{...H,form:"payload"}),A=_?.payload?H9({payload:_.payload})??void 0:void 0,O=this.catalogResolver.getAlternative(U,{...H,form:"content"})?.content;if(A===void 0&&O===void 0)return null;return{script:O,audio:A}},Z=(B,U)=>{let H=q(B);if(H.length!==1)return null;let _=H[0],A=N7(_,this.getTextProcessingOptions(Y.language)).visibleText||S(_.textContent||""),M=(O)=>S(O).replace(/\s+/g,"");return M(A)===M(U)?_:null},q=(B)=>{let U=Array.from(B.querySelectorAll("math"));if(B.localName?.toLowerCase()==="math")return[B,...U];return U},K=(B)=>{if(V7(B,Q))return;if(B.nodeType===Node.TEXT_NODE){G+=` ${B.textContent||""}`;return}if(B.nodeType!==Node.ELEMENT_NODE)return;let U=B,H=j(U);if(H){X();let _=N7(U,this.getTextProcessingOptions(Y.language)),A=_.visibleText||S(U.textContent||""),M=F1(U,Q),O=H.script!==void 0?(()=>{let L=H.script,F=B1({speechText:L,visibleText:A}),$=Z(U,A),b=$?T7({mathElement:$,speechText:L}):void 0,v=b?void 0:q(U).map((k)=>({element:k,alignment:T7({mathElement:k,speechText:L})}));return{speechText:L,visibleText:A,sourceElement:U,regionElement:M,speechMatchesVisibleText:S(L)===A,playbackMode:F.playbackMode,alignment:F,mathAlignment:b,mathAlignments:v,visibleMap:_.map}})():null;if(H.audio){J.push(O?{...O,audio:H.audio,plainFallback:O}:{speechText:A,visibleText:A,sourceElement:U,regionElement:M,speechMatchesVisibleText:!1,visibleMap:_.map,audio:H.audio});return}if(O)J.push(O);return}for(let _ of Array.from(U.childNodes))K(_)};return K(Q),X(),J}resolveGeneratedPlaybackFormat(){let Q=this.currentProvider;if(!Q)return"plain";if(Q.providerId?.toLowerCase()==="browser")return"plain";return Q.getCapabilities?.().supportsSSML?"ssml":"plain"}async resolveGeneratedSpeechContent(Q,Y,J){let G=this.resolveGeneratedPlaybackFormat(),{plan:X,containsMathMarkup:j,visibleText:Z}=await A8({contentRoot:Q,language:J,mathSpeech:this.getMathSpeechOptions(),textProcessingOptions:this.getTextProcessingOptions(J),produceSsml:G==="ssml",resolveMathSpeech:this.generatedMathSpeechResolver}),q=Z||Y;if(!j)return{contentToSpeak:q,speechText:q,visibleText:q,highlightText:q,normalizedText:q,containsMathMarkup:!1,speechMatchesVisibleText:!0};let K=M8(X,{format:G}),B=X.plainSpeechText;return{contentToSpeak:B,speechText:B,visibleText:q,highlightText:q,normalizedText:q,containsMathMarkup:!0,speechMatchesVisibleText:B===q,speechChunks:K}}logResolvedSpeechContent(Q){let Y=Q.contentToSpeak.replace(/\s+/g," ").trim().slice(0,200);this.debugLog("[TTSService] Speak resolved content",{source:Q.speechSource,catalogId:Q.catalogId||null,length:Q.contentToSpeak.length,preview:Y})}initializeSpeakTracking(Q,Y){this.currentText=Q,this.currentContentElement=Y?.contentElement||null,this.lastError=null,this.currentBoundaryOffset=0,this.playbackChunks=[],this.currentSeekSegmentIndex=0,this.activeSentenceStartOffset=null}prepareHighlightsForSpeak(Q){if(!this.currentContentElement||!this.highlightCoordinator)return;if(this.buildPositionMap(this.currentContentElement,Q.contentToSpeak,Q.options?.language),Q.highlightMode==="sentence"&&Q.shouldUsePlan)return;let Y=this.sentenceHighlightSegments[0]||this.seekSegments[0];this.runWhenPlaybackStarts(Q.runId,()=>{if(Y)this.highlightSentenceSegment(Y.startOffset,Y.text),this.debugLog("[TTSService] Applied initial sentence highlighting");else try{let J=document.createRange();J.selectNodeContents(this.currentContentElement),this.paintTTSSentenceRanges([J])}catch{}})}configureWordBoundaryHighlighting(Q){if(!this.provider||Q.highlightMode!=="word"||!this.highlightCoordinator||!this.currentContentElement)return;this.provider.onWordBoundary=(Y,J,G)=>{let X=G||Y.length,j=J+this.currentBoundaryOffset+Q.wordBoundaryOffset;this.highlightSentenceForOffset(j);let Z=this.findHighlightRange(j,X);if(Z&&this.highlightCoordinator){let q=Z.node.textContent?.substring(Z.start,Z.end)||"";this.debugLog(`[TTSService] Highlighting "${q}" (word: "${Y}") at position ${j}`);let K=this.createTextRange(Z.node,Z.start,Z.end);if(K)this.paintTTSWordRange(this.resolveWordHighlightRange(K).range);else this.highlightCoordinator.highlightTTSWord(Z.node,Z.start,Z.end)}else console.warn(`[TTSService] Could not find highlight range for position ${j}, length ${X}`)}}clearWordBoundaryHighlighting(){if(this.provider)this.provider.onWordBoundary=void 0}highlightCatalogRegion(Q){let Y=Q.regionElement||Q.sourceElement;if(!Y&&!Q.regionRange||!this.highlightCoordinator)return;try{if(this.lastRenderedRegionTarget=null,Q.regionRange){this.highlightCoordinator.clearHighlights?.(m.TTS_WORD),this.paintTTSSentenceRanges([Q.regionRange]);return}if(!Y)return;let J=document.createRange();J.selectNodeContents(Y),this.highlightCoordinator.clearHighlights?.(m.TTS_WORD),this.paintTTSSentenceRanges([J])}catch{}}highlightCatalogActiveRange(Q){if(!this.highlightCoordinator)return;this.paintTTSWordRange(this.resolveWordHighlightRange(Q).range)}highlightRenderableRegionTarget(Q){if(!this.highlightCoordinator||!Q||typeof document>"u")return;if(!this.highlightTargetResolverProvider&&p2(this.lastRenderedRegionTarget,Q))return;try{let Y=document.createRange();if(Q.type==="element")Y.selectNodeContents(Q.element);else if(Q.type==="range"){this.paintTTSSentenceRanges([Q.range]),this.lastRenderedRegionTarget=Q;return}else Y.setStart(Q.node,Q.startOffset),Y.setEnd(Q.node,Q.endOffset);this.paintTTSSentenceRanges([Y]),this.lastRenderedRegionTarget=Q}catch{}}highlightRenderableActiveTarget(Q){if(!this.highlightCoordinator||typeof document>"u")return;if(!Q){this.highlightCoordinator.clearHighlights(m.TTS_WORD);return}if(Q.type==="text-range"){let X=this.createTextRange(Q.node,Q.startOffset,Q.endOffset);if(X)this.paintTTSWordRange(this.resolveWordHighlightRange(X).range);else this.highlightCoordinator.highlightTTSWord(Q.node,Q.startOffset,Q.endOffset);return}if(Q.type==="range"){this.highlightCatalogActiveRange(Q.range);return}let Y=document.createRange();Y.selectNodeContents(Q.element);let J=this.resolveWordHighlightRange(Y);if(J.remapped){this.paintTTSWordRange(J.range);return}let G=Q.element.childNodes.length===1?Q.element.firstChild:null;if(Q.quality==="semantic-token"&&G?.nodeType===Node.TEXT_NODE){this.highlightCoordinator.highlightTTSWord(G,0,G.textContent?.length||0);return}this.highlightCoordinator.highlightTTSWordElement?.(Q.element)}renderHighlightDecision(Q){this.highlightRenderableRegionTarget(Q.regionTarget),this.highlightRenderableActiveTarget(Q.activeTarget)}async speakCatalogChunk(Q,Y){try{await this.speakCatalogChunkOnce(Q,Y)}catch(J){if(Q.plainFallback&&Y===this.speakRunId){if(this.debugLog("[TTSService] SSML chunk speak failed; retrying plain text",{message:J instanceof Error?J.message:String(J)}),this.playbackStartDeferredRunId===Y&&this.provider&&!("onPlaybackStart"in this.provider))this.pendingPlaybackStartHighlights=[],this.clearPlaybackStartBarrier(),this.setState(E.PLAYING);await this.speakCatalogChunkOnce(Q.plainFallback,Y);return}throw J}}async playRecordedAudio(Q,Y){if(typeof document>"u")throw Error("[tts] no document available to play recorded audio");let J=Q.sources[0],G=document.createElement("audio");G.preload="auto",G.src=V9(J.src,Q.fragment),G.playbackRate=this.normalizePlaybackRate(Number(this.ttsConfig.rate||1)),await new Promise((X,j)=>{let Z,q=!1,K=!1,B=()=>{if(K||q)return;q=!0,Y?.()},U=()=>{if(G.removeEventListener("ended",H),G.removeEventListener("error",_),G.removeEventListener("playing",B),Z!==void 0)clearInterval(Z);if(this.activeRecordedAudio?.element===G)this.activeRecordedAudio=null},H=()=>{if(K)return;K=!0,U(),X()},_=()=>{if(K)return;K=!0,U(),j(Error(`[tts] recorded audio failed to play: ${J.src}`))};this.activeRecordedAudio={element:G,cancel:()=>{if(K)return;K=!0,U(),G.pause(),X()}},G.addEventListener("ended",H),G.addEventListener("error",_),G.addEventListener("playing",B);let A=Q.fragment?.endSeconds;if(A!==void 0)Z=setInterval(()=>{if(G.currentTime>=A)H()},100);Promise.resolve(G.play()).then(B).catch(_)}).finally(()=>{if(this.activeRecordedAudio?.element===G)this.activeRecordedAudio=null;G.pause(),G.removeAttribute("src")})}cancelRecordedAudio(){let Q=this.activeRecordedAudio;if(!Q)return;this.activeRecordedAudio=null,Q.cancel()}async speakCatalogChunkOnce(Q,Y){if(!this.provider)return;if(this.lastRenderedRegionTarget=null,Q.audio){this.runWhenPlaybackStarts(Y,()=>{this.highlightCatalogRegion(Q)}),await this.playRecordedAudio(Q.audio,()=>{this.notifyPlaybackStarted(Y)});return}let J=Q.regionElement||Q.sourceElement||this.currentContentElement,G=J?O6({contentRoot:J,chunks:[Q]})[0]:null,X=this.ttsConfig.mathTokenHighlighting!==!1,j=G?z6({chunks:[G],mathTokenHighlighting:X}):null;if(this.runWhenPlaybackStarts(Y,()=>{if(j&&G&&Q.mathAlignment)this.renderHighlightDecision(j.resolveInitial(G.id));else this.highlightCatalogRegion(Q)}),!(Q.sourceElement&&(Q.mathAlignment&&Q.mathAlignment.speech.tokens.length>0||Q.mathAlignments&&Q.mathAlignments.length>0||Q.alignment&&Q.visibleMap&&(Q.playbackMode==="exact-word"||Q.playbackMode==="anchor-span")))){let U=this.provider,H=U.onWordBoundary;U.onWordBoundary=void 0;try{await U.speak(Q.speechText)}finally{if(this.provider===U&&Y===this.speakRunId&&U.onWordBoundary===void 0)U.onWordBoundary=H}return}let q=this.provider,K=q.onWordBoundary,B=(U,H,_)=>{if(Y!==this.speakRunId)return;if(j&&G){let A=G.offsetSpace==="unsupported"?"unknown":G.offsetSpace;this.renderHighlightDecision(j.resolveBoundary({chunkId:G.id,word:U,position:H,length:_,providerOffsetSpace:A}));return}};q.onWordBoundary=B;try{await q.speak(Q.speechText)}finally{if(this.provider===q&&Y===this.speakRunId&&q.onWordBoundary===B)q.onWordBoundary=K}}async executeSpeakPlayback(Q){if(Q.speechChunks?.length&&this.provider){for(let Y=0;Y<Q.speechChunks.length;Y++){if(Q.runId!==this.speakRunId)return;this.currentSeekSegmentIndex=Y;let J=this.seekSegments[Y];if(J)this.currentBoundaryOffset=J.startOffset;let G=Q.speechChunks[Y];await this.speakCatalogChunk(G,Q.runId)}return}if(Q.shouldUsePlan&&this.currentContentElement){let Y=this.seekSegments;if(Y.length>0)await this.speakWithPlan(Y,Q.runId,{highlightMode:Q.highlightMode});else if(this.provider)await this.provider.speak(Q.contentToSpeak);return}if(this.provider)await this.provider.speak(Q.contentToSpeak)}clearHighlightsAndTracking(){if(this.pendingPlaybackStartHighlights=[],this.activePlaybackRate=null,this.highlightCoordinator)this.highlightCoordinator.clearTTS();this.lastRenderedRegionTarget=null,this.currentContentElement=null,this.normalizedToDOM.clear(),this.currentBoundaryOffset=0,this.activeWordBoundaryOffset=0,this.seekSegments=[],this.playbackChunks=[],this.sentenceHighlightSegments=[],this.currentSeekSegmentIndex=0,this.activeSentenceStartOffset=null}async speakRange(Q,Y){if(!this.provider)throw Error("TTS service not initialized");if(K1(Q.commonAncestorContainer)){console.warn("[tts] selection lies inside content marked not-to-be-spoken; nothing was spoken. Selecting a node and pressing read-aloud must not become a way around suppression.");return}let G=Y?.contentRoot||null;if(!G){let U=Q.commonAncestorContainer;G=U.nodeType===Node.ELEMENT_NODE?U:U.parentElement}if(!G)return;let X=Q8(Q,G),j=X.text.trim();if(!j){if(X.filtered)console.warn("[tts] every part of the selection is either hidden or marked not-to-be-spoken; nothing was spoken.");return}let Z=document.createRange();Z.selectNodeContents(G),Z.setEnd(Q.startContainer,Q.startOffset);let q=Q8(Z,G).text,K=S(q),B=K.length+(/\s$/.test(q)&&K?1:0);this.debugLog("[TTSService] speakRange offset calculation:",{selectedText:j,textBeforeRange:q.substring(0,100),offset:B,rootTag:G.tagName}),await this.speak(j,{contentElement:G,ignoreCatalogs:!0,wordBoundaryOffset:B})}pause(){if(!this.provider)return;if(this.state===E.PLAYING)this.activeRecordedAudio?.element.pause(),this.provider.pause(),this.setState(E.PAUSED)}resume(){if(!this.provider)return;if(this.state===E.PAUSED){let Q=this.activeRecordedAudio?.element;if(Q)Promise.resolve(Q.play()).catch(()=>{});this.provider.resume(),this.setState(E.PLAYING)}}normalizePlaybackRate(Q){if(!Number.isFinite(Q))return 1;return Math.max(0.25,Math.min(4,Q))}async restartFromSeekIndex(Q){if(!this.provider||this.seekSegments.length===0)return;let Y=Math.max(0,Math.min(this.seekSegments.length-1,Q)),J=this.playbackChunks.length?this.playbackChunks.slice(Y):null;this.speakRunId+=1,this.clearPlaybackStartBarrier(),this.cancelRecordedAudio(),this.provider.onWordBoundary=void 0,this.provider.stop(),this.currentSeekSegmentIndex=Y;let G=++this.speakRunId,X=this.seekSegments.slice(Y);this.highlightCoordinator?.clearTTS(),this.activeSentenceStartOffset=null,this.setState(E.LOADING);let j=this.installPlaybackStartBarrier(G,!!J?.[0]?.audio);if(!j)this.setState(E.PLAYING);this.activePlaybackRate=this.normalizePlaybackRate(Number(this.ttsConfig.rate??1));try{if(this.configureWordBoundaryHighlighting({highlightMode:this.activeHighlightMode,wordBoundaryOffset:this.activeWordBoundaryOffset}),J)for(let Z=0;Z<J.length;Z++){if(G!==this.speakRunId)return;let q=Y+Z;this.currentSeekSegmentIndex=q;let K=this.seekSegments[q];if(K)this.currentBoundaryOffset=K.startOffset;await this.speakCatalogChunk(J[Z],G)}else await this.speakWithPlan(X,G,{highlightMode:this.activeHighlightMode});if(G!==this.speakRunId)return;this.setState(E.IDLE),this.clearHighlightsAndTracking(),this.highlightTargetResolverProvider=null}catch(Z){if(G!==this.speakRunId)return;throw this.lastError=Z instanceof Error?Z.message:String(Z),this.setState(E.ERROR),this.clearHighlightsAndTracking(),this.highlightTargetResolverProvider=null,Z}finally{this.clearPlaybackStartBarrier(j)}}async setPlaybackRate(Q){if(!this.provider)throw Error("TTSService not initialized. Call initialize() first.");let Y=this.normalizePlaybackRate(Q),J=this.pendingPlaybackRateRequest;if(J?.rate===Y){await J.promise;return}let G=++this.playbackRateRequestId,X=this.playbackRateWriteQueue.then(async()=>{let q=this.speakRunId;if(G!==this.playbackRateRequestId)return{didUpdate:!1,playbackRunId:q};let K=this.normalizePlaybackRate(Number(this.ttsConfig.rate??1));if(Y===K)return{didUpdate:!1,playbackRunId:q};return await this.updateSettings({rate:Y}),{didUpdate:!0,playbackRunId:q}});this.playbackRateWriteQueue=X.then(()=>{return},()=>{return});let j=X.then(async(q)=>{if(G!==this.playbackRateRequestId||q.playbackRunId!==this.speakRunId)return;let K=this.activePlaybackRate!==null&&this.activePlaybackRate!==Y;if(!q.didUpdate&&!K)return;if(this.state!==E.PLAYING&&this.state!==E.LOADING||!this.currentText||this.seekSegments.length===0||this.hasExplicitBreakSemantics(this.currentText))return;await this.restartFromSeekIndex(this.getCurrentSeekSegmentIndex())}),Z;Z=j.finally(()=>{if(this.pendingPlaybackRateRequest?.promise===Z)this.pendingPlaybackRateRequest=null}),this.pendingPlaybackRateRequest={rate:Y,promise:Z},await Z}async seekBy(Q){if(!this.provider||!this.currentText)return;if(this.state!==E.PLAYING&&this.state!==E.PAUSED)return;if(this.hasExplicitBreakSemantics(this.currentText))return;if(this.seekSegments.length===0)return;let Y=Number.isFinite(Q)?Math.trunc(Q):0;if(Y===0)return;let J=this.getCurrentSeekSegmentIndex(),G=Math.max(0,Math.min(this.seekSegments.length-1,J+Y));if(G===J)return;await this.restartFromSeekIndex(G)}async seekForward(Q=1){let Y=Number.isFinite(Q)?Math.max(1,Math.trunc(Q)):1;await this.seekBy(Y)}async seekBackward(Q=1){let Y=Number.isFinite(Q)?Math.max(1,Math.trunc(Q)):1;await this.seekBy(-Y)}stop(){if(!this.provider)return;if(this.speakRunId+=1,this.clearPlaybackStartBarrier(),this.cancelRecordedAudio(),this.provider.onWordBoundary=void 0,this.provider.stop(),this.highlightTargetResolverProvider=null,this.setState(E.IDLE),this.currentText=null,this.highlightCoordinator)this.highlightCoordinator.clearTTS();this.lastRenderedRegionTarget=null,this.currentContentElement=null,this.normalizedToDOM.clear(),this.currentBoundaryOffset=0,this.activeWordBoundaryOffset=0,this.seekSegments=[],this.playbackChunks=[],this.sentenceHighlightSegments=[],this.currentSeekSegmentIndex=0,this.activeSentenceStartOffset=null,this.activePlaybackRate=null}requestControlHandoff(){if(typeof window>"u")return;let Q={source:"host"};window.dispatchEvent(new CustomEvent(L6,{detail:Q}))}isPlaying(){return this.state===E.PLAYING}isPaused(){return this.state===E.PAUSED}getState(){return this.state}getCurrentText(){return this.currentText}getLastError(){return this.lastError}onStateChange(Q,Y){if(!this.listeners.has(Q))this.listeners.set(Q,new Set);this.listeners.get(Q).add(Y)}offStateChange(Q,Y){let J=this.listeners.get(Q);if(J){if(J.delete(Y),J.size===0)this.listeners.delete(Q)}}setState(Q){if(this.state===Q)return;let Y=this.state;this.state=Q;for(let J of this.listeners.values())for(let G of J)G(Q);if(this.emitTelemetry("pie-tool-playback-state-changed",{toolId:"textToSpeech",providerId:"tts",previousState:Y,state:Q}),Q===E.PLAYING){let J=Y===E.PAUSED?"pie-tool-playback-resume":"pie-tool-playback-start";this.emitTelemetry(J,{toolId:"textToSpeech",providerId:"tts",previousState:Y,state:Q});return}if(Q===E.PAUSED){this.emitTelemetry("pie-tool-playback-pause",{toolId:"textToSpeech",providerId:"tts",previousState:Y,state:Q});return}if(Q===E.ERROR){this.emitTelemetry("pie-tool-playback-error",{toolId:"textToSpeech",providerId:"tts",previousState:Y,state:Q,message:this.lastError||void 0});return}if(Q===E.IDLE&&(Y===E.PLAYING||Y===E.PAUSED||Y===E.LOADING))this.emitTelemetry("pie-tool-playback-stop",{toolId:"textToSpeech",providerId:"tts",previousState:Y,state:Q})}}var g2=new Set(["reserved-row","expanding-row","floating-overlay","left-aligned"]),w6=(Q)=>Q&&typeof Q==="object"?Q:{},c2=(Q)=>Q==="polly"||Q==="google"||Q==="server",c=(Q,Y)=>Q===void 0?Y:Q,l2=(Q,Y="left-aligned")=>typeof Q==="string"&&g2.has(Q)?Q:Y,x4=Object.freeze([0.8,1.25]),f4=Object.freeze([{rate:0.8,label:"Slow",ariaLabel:"Slow speed"},{rate:1,label:"Normal",ariaLabel:"Normal speed",default:!0},{rate:1.25,label:"Fast",ariaLabel:"Fast speed"}]);var k4=Object.freeze([0.8,1,1.25]);var d2=(Q)=>{let Y={...Q,layoutMode:l2(Q.layoutMode)},J=Q.backend||"browser";if(!c2(J))return Y;let G={...Y,apiEndpoint:c(Y.apiEndpoint,"/api/tts"),transportMode:c(Y.transportMode,"pie"),endpointValidationMode:c(Y.endpointValidationMode,"voices"),validateEndpoint:c(Y.validateEndpoint,!0),includeAuthOnAssetFetch:c(Y.includeAuthOnAssetFetch,!1),rate:c(Y.rate,1),language:c(Y.language,"en-US")};if(J==="polly")return{...G,defaultVoice:c(G.defaultVoice,"Joanna"),engine:c(G.engine,"neural"),format:c(G.format,"mp3"),speechMarksMode:c(G.speechMarksMode,"word+sentence")};if(J==="google")return{...G,defaultVoice:c(G.defaultVoice,"en-US-Wavenet-A")};return G},R6=(Q)=>{let Y=w6(Q),J=w6(Y.settings);return d2({...Y,...J})},N8=(Q)=>Q.backend||"browser",i2=(Q,Y)=>{if(Y==="polly"||Y==="google")return Y;if(Y==="server")return Q.serverProvider||Q.provider;return Q.serverProvider||Q.provider},s2=(Q,Y)=>Q.transportMode||(Y==="custom"?"custom":"pie"),E6=(Q)=>{let Y=N8(Q),J=i2(Q,Y),G=s2(Q,J),X=z7(Q.mathSpeech);return{voice:Q.defaultVoice,rate:Q.rate,pitch:Q.pitch,providerOptions:{...Q.language?{locale:Q.language}:{},...Y==="polly"&&Q.engine?{engine:Q.engine}:{},...Y==="polly"&&typeof Q.sampleRate==="number"?{sampleRate:Q.sampleRate}:{},...Y==="polly"&&Q.format?{format:Q.format}:{},...Y==="polly"?{speechMarkTypes:Q.speechMarksMode==="word+sentence"?["word","sentence"]:["word"]}:{},...G==="custom"&&typeof Q.cache==="boolean"?{cache:Q.cache}:{},...G==="custom"&&Q.speedRate?{speedRate:Q.speedRate}:{},...G==="custom"&&Q.lang_id?{lang_id:Q.lang_id}:{},...X?{mathSpeech:X}:{}},apiEndpoint:Q.apiEndpoint,provider:J,language:Q.language,transportMode:G,endpointMode:Q.endpointMode,endpointValidationMode:Q.endpointValidationMode,includeAuthOnAssetFetch:Q.includeAuthOnAssetFetch,validateEndpoint:Q.validateEndpoint,...typeof Q.mathTokenHighlighting==="boolean"?{mathTokenHighlighting:Q.mathTokenHighlighting}:{}}};class A1{providers=new Map;configs=new Map;initialized=new Map;initializationPromises=new Map;async emitTelemetry(Q,Y,J){try{await Q.onTelemetry?.(Y,J)}catch(G){console.warn("[ToolProviderRegistry] Telemetry callback failed:",G)}}register(Q,Y){if(this.providers.has(Q)){console.warn(`[ToolProviderRegistry] Provider "${Q}" already registered, skipping`);return}if(this.providers.set(Q,Y.provider),this.configs.set(Q,Y),this.initialized.set(Q,!1),console.log(`[ToolProviderRegistry] Registered provider "${Q}" (${Y.provider.providerName})`),Y.lazy===!1)this.initialize(Q).catch((J)=>{console.error(`[ToolProviderRegistry] Failed to initialize provider "${Q}":`,J)})}async initialize(Q){if(this.initialized.get(Q))return;let Y=this.initializationPromises.get(Q);if(Y)return Y;let J=this._doInitialize(Q);this.initializationPromises.set(Q,J);try{await J}finally{this.initializationPromises.delete(Q)}}async _doInitialize(Q){let Y=this.providers.get(Q),J=this.configs.get(Q);if(!Y||!J)throw Error(`[ToolProviderRegistry] Provider "${Q}" not registered`);let G={...J.config},X=(Z)=>{if(!Z||typeof Z!=="object")return"unknown";let q=Z;return(typeof q.backend==="string"?q.backend:typeof q.provider==="string"?q.provider:typeof q.serverProvider==="string"?q.serverProvider:typeof q.providerId==="string"?q.providerId:"")||"unknown"},j=Date.now();if(await this.emitTelemetry(J,"pie-tool-init-start",{toolId:Q,providerId:Q,backend:X(G),operation:"provider-initialize"}),Y.requiresAuth&&J.authFetcher){let Z=Date.now();await this.emitTelemetry(J,"pie-tool-backend-call-start",{toolId:Q,providerId:Q,backend:X(G),operation:"auth-fetch"}),console.log(`[ToolProviderRegistry] Fetching auth for "${Q}"...`);try{let q=await J.authFetcher();G={...G,...q},await this.emitTelemetry(J,"pie-tool-backend-call-success",{toolId:Q,providerId:Q,backend:X(G),operation:"auth-fetch",duration:Date.now()-Z})}catch(q){throw await this.emitTelemetry(J,"pie-tool-backend-call-error",{toolId:Q,providerId:Q,backend:X(G),operation:"auth-fetch",duration:Date.now()-Z,errorType:"ProviderAuthFetchError",message:q instanceof Error?q.message:String(q)}),console.error(`[ToolProviderRegistry] Auth fetch failed for "${Q}":`,q),Error(`Failed to fetch auth credentials for provider "${Q}"`)}}try{await Y.initialize(G),this.initialized.set(Q,!0),await this.emitTelemetry(J,"pie-tool-init-success",{toolId:Q,providerId:Q,backend:X(G),operation:"provider-initialize",duration:Date.now()-j}),console.log(`[ToolProviderRegistry] Provider "${Q}" initialized`)}catch(Z){throw await this.emitTelemetry(J,"pie-tool-init-error",{toolId:Q,providerId:Q,backend:X(G),operation:"provider-initialize",duration:Date.now()-j,errorType:"ProviderInitializationError",message:Z instanceof Error?Z.message:String(Z)}),console.error(`[ToolProviderRegistry] Initialization failed for "${Q}":`,Z),Z}}async getProvider(Q,Y=!0){console.log("[ToolProviderRegistry] getProvider called",{providerId:Q,autoInitialize:Y,isRegistered:this.providers.has(Q),isInitialized:this.initialized.get(Q),allProviderIds:Array.from(this.providers.keys())});let J=this.providers.get(Q);if(!J)throw console.error("[ToolProviderRegistry] Provider not found:",{requestedId:Q,availableProviders:Array.from(this.providers.keys())}),Error(`[ToolProviderRegistry] Provider "${Q}" not registered`);if(Y&&!this.initialized.get(Q))console.log("[ToolProviderRegistry] Auto-initializing provider:",Q),await this.initialize(Q);return console.log("[ToolProviderRegistry] Returning provider:",{providerId:Q,providerName:J.providerName,isReady:J.isReady()}),J}getProvidersByCategory(Q){return Array.from(this.providers.entries()).filter(([Y,J])=>J.category===Q).map(([Y])=>Y)}getProviderIds(){return Array.from(this.providers.keys())}has(Q){return this.providers.has(Q)}isInitialized(Q){return this.initialized.get(Q)===!0}isInitializing(Q){return this.initializationPromises.has(Q)}async unregister(Q){let Y=this.providers.get(Q);if(Y){let J=this.initializationPromises.get(Q);if(J)try{await J}catch{}Y.destroy(),this.providers.delete(Q),this.configs.delete(Q),this.initialized.delete(Q),this.initializationPromises.delete(Q),console.log(`[ToolProviderRegistry] Unregistered provider "${Q}"`)}}async destroy(){let Q=Array.from(this.providers.keys());await Promise.all(Q.map((Y)=>this.unregister(Y))),console.log("[ToolProviderRegistry] Registry destroyed")}}var n2=(Q)=>`No assessment is bound, so no policy source could grant "${Q}"`;function z8(Q,Y,J,G){return{featureId:Q,granted:!1,action:"block",rule:Y,precedence:0,sourceType:"host",reason:Y==="host-blocked"?"Listed in tools.policy.blocked":`Not listed in tools.policy.allowed (${J.join(", ")})`,required:!1,assessmentBound:G.assessmentBound}}function b6(Q,Y,J){let G=Y.decisions[0],X=Array.from(Y.perToolFlags.values())[0],j=G?.action==="enable",Z=G?.reason??`Feature "${Q}" not configured`;return{featureId:Q,granted:j,action:G?.action??"skip",rule:G?.rule??"pnp-support",precedence:G?.precedence??6,sourceType:G?.sourceType??"system",reason:J.assessmentBound||j?Z:n2(Q),required:Boolean(X?.required),parameters:X?.settings,assessmentBound:J.assessmentBound}}class M1{provenance;stepCounter=0;constructor(Q){this.provenance={contextId:Q,resolvedAt:new Date,sources:{},features:new Map,decisionLog:[],summary:{totalFeatures:0,enabled:0,blocked:0,notConfigured:0,bySource:{},byRule:{}}}}addSource(Q,Y){let J={id:Y.id,name:Y.name??Y.id};switch(Q){case"organization":this.provenance.sources.organization={...J,pnpDefaults:Y.config};break;case"assessment":this.provenance.sources.assessment={...J,settings:Y.config};break;case"section":this.provenance.sources.section={...J,settings:Y.config};break;case"item":this.provenance.sources.item={...J,settings:Y.config};break;case"student":this.provenance.sources.student={id:Y.id,pnpProfile:Y.config};break;case"host":this.provenance.sources.host={id:Y.id,config:Y.config};break}return this}addDecision(Q){let Y={step:++this.stepCounter,precedence:Q.precedence,rule:Q.rule,featureId:Q.featureId,action:Q.action,source:{type:Q.sourceType,id:Q.sourceId,name:Q.sourceName},reason:Q.reason,value:Q.value,timestamp:new Date};this.provenance.decisionLog.push(Y);let J=this.provenance.features.get(Q.featureId);if(!J)J={featureId:Q.featureId,finalState:"not-configured",allDecisions:[],explanation:""},this.provenance.features.set(Q.featureId,J);if(J.allDecisions.push(Y),Q.action==="advisory"){if(J.finalState==="not-configured")J.finalState="advisory-only"}else if(Q.action!=="skip"){if(!J.winningDecision||Y.precedence<J.winningDecision.precedence)J.winningDecision=Y,J.finalState=Y.action==="enable"?"enabled":"blocked"}return this.provenance.summary.bySource[Q.sourceType]=(this.provenance.summary.bySource[Q.sourceType]||0)+1,this.provenance.summary.byRule[Q.rule]=(this.provenance.summary.byRule[Q.rule]||0)+1,this}reconcileFinalStates(Q){for(let Y of Q){let J=this.provenance.features.get(Y);if(!J){J={featureId:Y,finalState:"enabled",allDecisions:[],explanation:""},this.provenance.features.set(Y,J);continue}J.finalState="enabled"}for(let Y of this.provenance.features.values()){if(Q.has(Y.featureId))continue;let J=Y.allDecisions.some((X)=>X.action!=="skip"&&X.action!=="advisory"),G=Y.allDecisions.some((X)=>X.action==="advisory");if(J)Y.finalState="blocked";else if(G)Y.finalState="advisory-only";else Y.finalState="not-configured"}return this}build(){for(let Q of this.provenance.features.values())Q.explanation=r2(Q);for(let Q of this.provenance.features.values())if(this.provenance.summary.totalFeatures++,Q.finalState==="enabled")this.provenance.summary.enabled++;else if(Q.finalState==="blocked")this.provenance.summary.blocked++;else this.provenance.summary.notConfigured++;return this.provenance}}function r2(Q){if(!Q.winningDecision){if(Q.finalState==="advisory-only"){let j=Q.allDecisions.find((Z)=>Z.action==="advisory");return j?`Feature "${Q.featureId}" was kept in its host-decided state; ${j.reason}`:`Feature "${Q.featureId}" carries an advisory note.`}return`Feature "${Q.featureId}" was not configured at any level.`}let Y=Q.winningDecision,J=Y.source.name||Y.source.type,G=`Feature "${Q.featureId}" is ${Q.finalState}.
216
216
 
217
217
  `;G+=`**Primary Reason** (${Y.rule}):
218
218
  `,G+=`${Y.reason}
@@ -220,6 +220,6 @@ ${J}`)}function G7(Q,Y={}){let J=u1(Y.strictness),G=Y.source??"tools",X=o0(Y.too
220
220
  `;let X=Q.allDecisions.filter((j)=>j.step!==Y.step&&j.action!=="skip"&&j.action!=="advisory"&&j.precedence>Y.precedence);if(X.length>0){G+=`
221
221
  **Overridden Rules**:
222
222
  `;for(let j of X)G+=`- ${j.rule}: ${j.reason}
223
- `}return G}function z8(Q){let{request:Y,tools:J,pnpPolicy:G,customSources:X,contextId:j}=Q,Z=new A1(j);Z.addSource("host",{id:Y.scope.scopeId,name:`${Y.level}:${Y.scope.scopeId}`,config:{placement:J.placement,policy:J.policy}});let q=M1(J.placement[Y.level]),K=M1(J.policy.allowed),B=new Set(M1(J.policy.blocked)),U=[];for(let F of q)U.push(F),Z.addDecision({precedence:0,rule:"placement-membership",featureId:F,action:"skip",sourceType:"host",reason:`Listed in tools.placement.${Y.level}`});if(U=U.filter((F)=>{if(J.providers?.[F]?.enabled===!1)return Z.addDecision({precedence:0,rule:"provider-disabled",featureId:F,action:"block",sourceType:"host",reason:`tools.providers.${F}.enabled === false`,value:!1}),!1;return!0}),K.length>0){let F=new Set(K);U=U.filter(($)=>{if(!F.has($))return Z.addDecision({precedence:0,rule:"host-allowlist",featureId:$,action:"block",sourceType:"host",reason:"Not present in tools.policy.allowed",value:K}),!1;return!0})}U=U.filter((F)=>{if(B.has(F))return Z.addDecision({precedence:0,rule:"host-blocked",featureId:F,action:"block",sourceType:"host",reason:"Listed in tools.policy.blocked",value:J.policy.blocked}),!1;return!0});let H=[],_=new Map;for(let F of U)_.set(F,["placement"]);let A=new Set(U),M=null;if(G.enforcement==="on"&&G.source&&(G.assessment||G.currentItemRef)){if(M=G.source.apply({assessment:G.assessment,currentItemRef:G.currentItemRef}),M.sources.assessment)Z.addSource("assessment",M.sources.assessment);if(M.sources.student)Z.addSource("student",M.sources.student);if(M.sources.item)Z.addSource("item",M.sources.item);for(let F of M.decisions)Z.addDecision({precedence:F.precedence,rule:F.rule,featureId:F.featureId,action:F.action,sourceType:F.sourceType,reason:F.reason,value:F.value});U=U.filter((F)=>{return!M.blockedToolIds.has(F)});for(let F of Array.from(_.keys()))if(M.blockedToolIds.has(F))_.delete(F);for(let F of M.mandatedToolIds){if(!!A.has(F))continue;let v=M.perToolFlags.get(F)?.rule??"required-tool",k=r2(F,{placement:q,allowed:K,blocked:B,providers:J.providers}),p={rule:v,hostRule:k.hostRule,hostValue:k.hostValue};H.push({code:"tool-policy.requiredToolBlocked",level:Y.level,toolId:F,message:`Profile policy mandates "${F}" (${v}) but host policy removed it from level "${Y.level}" via ${k.hostRule}.`,details:p}),Z.addDecision({precedence:0,rule:"required-tool-blocked",featureId:F,action:"advisory",sourceType:"host",reason:`Host removed required tool "${F}" via ${k.hostRule}`,value:p})}for(let F of U){let $=M.perToolFlags.get(F);if($){let b=_.get(F)??[];b.push(`pnp.${$.rule}`),_.set(F,b)}}}for(let F=0;F<X.length;F++){let $=X[F],b=U.slice(),v=$.refine({request:Y,candidates:b}),k=new Set(v.refinedCandidates);for(let w of v.refinedCandidates)if(!b.includes(w))H.push({code:"tool-policy.placementMissing",level:Y.level,toolId:w,message:`Custom source "${$.id}" tried to add tool "${w}" that was not in candidates; ignored.`,source:`custom.${$.id}`}),k.delete(w);U=b.filter((w)=>k.has(w));let p=new Set;if(v.decisions){for(let w of v.decisions)if(Z.addDecision({precedence:w.precedence??100+F,rule:w.rule,featureId:w.featureId,action:w.action,sourceType:w.sourceType,reason:w.reason,value:w.value}),w.action==="block")p.add(w.featureId)}for(let w of b){if(k.has(w))continue;if(p.has(w))continue;Z.addDecision({precedence:100+F,rule:"custom-source",featureId:w,action:"block",sourceType:"custom",reason:`Custom policy source "${$.id}" removed tool "${w}" from candidates without emitting a decision; auto-logged for trail completeness.`,value:{customSourceId:$.id}})}for(let w of U){let l=_.get(w)??["placement"];l.push(`custom.${$.id}`),_.set(w,l)}for(let w of b)if(!k.has(w))_.delete(w)}let O=new Set(U),L=U.map((F)=>{let $=M?.perToolFlags.get(F);return{toolId:F,required:$?.required??!1,alwaysAvailable:$?.alwaysAvailable??!1,settings:$?.settings,sources:_.get(F)??["placement"]}});return Z.reconcileFinalStates(O),{visibleTools:L,diagnostics:H,provenance:Z.build()}}function r2(Q,Y){if(!Y.placement.includes(Q))return{hostRule:"placement-missing",hostValue:Y.placement};if(Y.providers?.[Q]?.enabled===!1)return{hostRule:"provider-disabled",hostValue:!1};if(Y.allowed.length>0&&!Y.allowed.includes(Q))return{hostRule:"host-allowlist",hostValue:Y.allowed};if(Y.blocked.has(Q))return{hostRule:"host-blocked",hostValue:Array.from(Y.blocked)};return{hostRule:"placement-missing",hostValue:Y.placement}}function b6(Q){if(!Q)return!1;let Y=Q.personalNeedsProfile;if(Y){if(Array.isArray(Y.supports)&&Y.supports.length>0)return!0;if(Array.isArray(Y.prohibitedSupports)&&Y.prohibitedSupports.length>0)return!0;if(Array.isArray(Y.activateAtInit)&&Y.activateAtInit.length>0)return!0}let J=Q.settings;if(J){let G=J.districtPolicy;if(G){if(Array.isArray(G.blockedTools)&&G.blockedTools.length>0)return!0;if(Array.isArray(G.requiredTools)&&G.requiredTools.length>0)return!0;if(G.policies&&typeof G.policies==="object"&&Object.keys(G.policies).length>0)return!0}let X=J.testAdministration;if(X&&typeof X==="object")for(let j of Object.keys(X)){let Z=X[j];if(Z===void 0||Z===null)continue;if(Array.isArray(Z)&&Z.length===0)continue;if(typeof Z==="object"&&!Array.isArray(Z)&&Object.keys(Z).length===0)continue;return!0}}return!1}function S6(Q){let Y=Q?.settings;if(!Y)return!1;if(Array.isArray(Y.requiredTools)&&Y.requiredTools.length>0)return!0;if(Array.isArray(Y.restrictedTools)&&Y.restrictedTools.length>0)return!0;if(Y.toolParameters&&typeof Y.toolParameters==="object"&&Object.keys(Y.toolParameters).length>0)return!0;return!1}function u7(Q){if(b6(Q.assessment))return"on";if(S6(Q.currentItemRef))return"on";return"off"}class N1{id="pnp";toolRegistry;constructor(Q){this.toolRegistry=Q}apply(Q){let{ctx:Y,result:J}=this.prepare(Q),{pnp:G,districtPolicy:X,itemSettings:j}=Y,Z=new Set;G?.supports?.forEach((q)=>Z.add(q)),G?.prohibitedSupports?.forEach((q)=>Z.add(q)),X?.blockedTools?.forEach((q)=>Z.add(q)),X?.requiredTools?.forEach((q)=>Z.add(q)),j?.requiredTools?.forEach((q)=>Z.add(q)),j?.restrictedTools?.forEach((q)=>Z.add(q));for(let q of Z)this.resolveSupport(q,Y,J);return J}resolveFeature(Q,Y){let{ctx:J,result:G}=this.prepare(Y);return this.resolveSupport(Q,J,G),G}prepare(Q){let{assessment:Y,currentItemRef:J}=Q,G=Y?.personalNeedsProfile,X=Y?.settings,j=J?.settings,Z={blockedToolIds:new Set,mandatedToolIds:new Set,perToolFlags:new Map,decisions:[],sources:{}};if(X?.districtPolicy||X?.testAdministration)Z.sources.assessment={id:Y?.id||"unknown",name:Y?.name||Y?.id||"Assessment",config:X};if(G)Z.sources.student={id:"student",name:"Student PNP Profile",config:G};if(J&&j)Z.sources.item={id:J.identifier,name:J.identifier,config:j};return{ctx:{pnp:G,districtPolicy:X?.districtPolicy,testAdmin:X?.testAdministration,itemSettings:j,toolConfigs:X?.toolConfigs},result:Z}}resolveSupport(Q,Y,J){if(Y.districtPolicy?.blockedTools?.includes(Q)){let X=this.mapSupportToToolId(Q);J.blockedToolIds.add(X),J.decisions.push({precedence:1,rule:"district-block",featureId:X,action:"block",sourceType:"assessment",reason:`District policy blocks "${Q}" for all assessments`,value:Y.districtPolicy.blockedTools});return}if(Y.testAdmin?.toolOverrides?.[Q]===!1){let X=this.mapSupportToToolId(Q);J.blockedToolIds.add(X),J.decisions.push({precedence:2,rule:"test-admin-override",featureId:X,action:"block",sourceType:"assessment",reason:`Test administrator disabled "${Q}" for this session`,value:Y.testAdmin.toolOverrides});return}if(Y.itemSettings?.restrictedTools?.includes(Q)){let X=this.mapSupportToToolId(Q);J.blockedToolIds.add(X),J.decisions.push({precedence:3,rule:"item-restriction",featureId:X,action:"block",sourceType:"item",reason:`Item restricts "${Q}" (e.g., mental math question blocks calculator)`,value:Y.itemSettings.restrictedTools});return}if(Y.itemSettings?.requiredTools?.includes(Q)){let X=this.mapSupportToToolId(Q);J.mandatedToolIds.add(X),J.perToolFlags.set(X,{required:!0,alwaysAvailable:!1,settings:this.resolveToolSettings(Q,Y),rule:"item-requirement",sourceType:"item"}),J.decisions.push({precedence:4,rule:"item-requirement",featureId:X,action:"enable",sourceType:"item",reason:`Item requires "${Q}" for this question`,value:Y.itemSettings.requiredTools});return}if(Y.districtPolicy?.requiredTools?.includes(Q)){let X=this.mapSupportToToolId(Q);J.mandatedToolIds.add(X),J.perToolFlags.set(X,{required:!0,alwaysAvailable:!1,settings:this.resolveToolSettings(Q,Y),rule:"district-requirement",sourceType:"assessment"}),J.decisions.push({precedence:5,rule:"district-requirement",featureId:X,action:"enable",sourceType:"assessment",reason:`District policy requires "${Q}" for all assessments`,value:Y.districtPolicy.requiredTools});return}if(Y.pnp?.prohibitedSupports?.includes(Q)){let X=this.mapSupportToToolId(Q);J.blockedToolIds.add(X),J.decisions.push({precedence:6,rule:"pnp-prohibited",featureId:X,action:"block",sourceType:"student",reason:`Student PNP profile prohibits "${Q}"`,value:Y.pnp.prohibitedSupports});return}if(Y.pnp?.supports?.includes(Q)){let X=this.mapSupportToToolId(Q);J.perToolFlags.set(X,{required:!1,alwaysAvailable:!0,settings:this.resolveToolSettings(Q,Y),rule:"pnp-support",sourceType:"student"}),J.decisions.push({precedence:6,rule:"pnp-support",featureId:X,action:"enable",sourceType:"student",reason:`Student PNP profile requests "${Q}"`,value:Y.pnp.supports});return}let G=this.mapSupportToToolId(Q);J.decisions.push({precedence:6,rule:"pnp-support",featureId:G,action:"skip",sourceType:"system",reason:`Feature "${Q}" not configured at any level`,value:{supportId:Q}})}mapSupportToToolId(Q){let Y=this.toolRegistry.getToolsByPNPSupport(Q);if(Y.size===0)return Q;return Array.from(Y)[0]}resolveToolSettings(Q,Y){return Y.itemSettings?.toolParameters?.[Q]??Y.toolConfigs?.[Q]}}var T6=$7({policy:{allowed:[],blocked:[]},placement:{section:[],item:[],passage:[]},providers:{}});class z1{toolRegistry;contextId;pnpPolicySource;customSources;listeners=new Set;tools;assessment;currentItemRef;pnpEnforcement;disposed=!1;constructor(Q){this.toolRegistry=Q.toolRegistry,this.contextId=Q.contextId??"tool-policy",this.pnpPolicySource=new N1(this.toolRegistry),this.customSources=Q.customSources?[...Q.customSources]:[];let Y=Q.inputs??{};this.tools=Y.tools??T6,this.assessment=Y.assessment??null,this.currentItemRef=Y.currentItemRef??null,this.pnpEnforcement=Y.pnpEnforcement??u7({assessment:this.assessment,currentItemRef:this.currentItemRef})}decide(Q){this.assertNotDisposed();let Y=Q.scope.scopeId?`${this.contextId}:${Q.level}:${Q.scope.scopeId}`:`${this.contextId}:${Q.level}`;return z8({request:Q,tools:this.tools,pnpPolicy:{source:this.pnpPolicySource,assessment:this.assessment??void 0,currentItemRef:this.currentItemRef??void 0,enforcement:this.pnpEnforcement},customSources:this.customSources,contextId:Y})}decideFeature(Q){return this.assertNotDisposed(),E6(Q,this.pnpPolicySource.resolveFeature(Q,{assessment:this.assessment??void 0,currentItemRef:this.currentItemRef??void 0}),{assessmentBound:this.assessment!==null})}getVisibleToolIds(Q,Y){return this.decide({level:Q,scope:{level:Q,scopeId:Y}}).visibleTools.map((J)=>J.toolId)}updateInputs(Q){this.assertNotDisposed();let Y=!1,J=!1;if("tools"in Q){let G=Q.tools??T6;if(!Object.is(this.tools,G))this.tools=G,Y=!0}if("assessment"in Q){let G=Q.assessment??null;if(!Object.is(this.assessment,G))this.assessment=G,Y=!0}if("currentItemRef"in Q){let G=Q.currentItemRef??null;if(!Object.is(this.currentItemRef,G))this.currentItemRef=G,Y=!0}if("pnpEnforcement"in Q&&Q.pnpEnforcement){if(this.pnpEnforcement!==Q.pnpEnforcement)this.pnpEnforcement=Q.pnpEnforcement,J=!0}if(Y||J)this.emit({reason:J&&!Y?"pnp-enforcement":"inputs",inputs:this.snapshotInputs()})}registerPolicySource(Q){return this.assertNotDisposed(),this.customSources.push(Q),this.emit({reason:"policy-source-added",inputs:this.snapshotInputs()}),()=>{let Y=this.customSources.indexOf(Q);if(Y!==-1){if(this.customSources.splice(Y,1),!this.disposed)this.emit({reason:"policy-source-removed",inputs:this.snapshotInputs()})}}}onPolicyChange(Q){return this.listeners.add(Q),()=>{this.listeners.delete(Q)}}getInputs(){return this.snapshotInputs()}dispose(){if(this.disposed)return;this.disposed=!0,this.emit({reason:"disposed",inputs:this.snapshotInputs()}),this.listeners.clear(),this.customSources.length=0}snapshotInputs(){return Object.freeze({tools:this.tools,assessment:this.assessment,currentItemRef:this.currentItemRef,pnpEnforcement:this.pnpEnforcement})}emit(Q){for(let Y of Array.from(this.listeners))try{Y(Q)}catch{}}assertNotDisposed(){if(this.disposed)throw Error("ToolPolicyEngine has been disposed.")}}var o2=Symbol("@pie-players/tool-policy-engine");var O1=(Q)=>!!Q&&typeof Q==="object"&&!Array.isArray(Q),a2=(Q,Y,J)=>{let G={...Y,...J};if(Q==="textToSpeech"&&O1(Y.settings)&&O1(J.settings)){if(G.settings={...Y.settings,...J.settings},O1(Y.settings.mathSpeech)&&O1(J.settings.mathSpeech))G.settings.mathSpeech={...Y.settings.mathSpeech,...J.settings.mathSpeech}}return G},t2=["item-selected","item-session-data-changed","item-session-meta-changed","item-complete-changed","content-loaded","item-player-error"],e2=["section-navigation-change","section-session-applied","section-loading-complete","section-items-complete-changed","section-error"];class P1{assessmentId;config;ttsService;toolCoordinator;highlightCoordinator;elementToolStateStore;catalogResolver;toolProviderRegistry;hooks;lazyInit;ttsInitialized=!1;ttsInitPromise;ttsReconfigurePromise;stateLoaded=!1;stateLoadPromise;coordinatorReadyPromise;coordinatorReadyNotified=!1;providerInitPromises=new Map;toolRegistry;toolContextResolvers=new Map;toolContextResolverChangeListeners=new Set;sectionControllers=new Map;sectionControllerKeys=new Map;sectionControllerInitPromises=new Map;sectionPersistenceStrategies=new Map;sectionControllerLifecycleListeners=new Set;activeSubscriptions=new Map;activeCohortMapKey=null;latestRequestedActiveCohortMapKey=null;telemetryListeners=new Set;frameworkErrorBus;ownsFrameworkErrorBus;policyEngine;pnpEnforcementOverride=null;boundAssessment=null;boundCurrentItemRef=null;reportedUnboundFeaturePolicy=!1;static resolveConfig(Q){let Y=u1(Q.toolConfigStrictness),J=Q.toolRegistry??new O8,G=Q.deferToolConfigValidation===!0?$7(Q.tools):G7(Q.tools,{strictness:Y,source:"ToolkitCoordinator.init",toolRegistry:J}).config;return{...Q,toolConfigStrictness:Y,toolRegistry:J,tools:{...G,providers:{...{textToSpeech:{enabled:!0,backend:"browser"},annotationToolbar:{enabled:!0}},...G.providers}},accessibility:{language:"en-US",...Q.accessibility??{},catalogs:Q.accessibility?.catalogs??[]}}}constructor(Q){if(!Q.assessmentId)throw Error("ToolkitCoordinator requires assessmentId in config");let Y=P1.resolveConfig(Q);if(this.assessmentId=Y.assessmentId,this.config=Y,this.toolRegistry=Y.toolRegistry??new O8,this.installToolContextResolvers(Y.toolContextResolvers),this.hooks=Y.hooks??{},this.lazyInit=Q.lazyInit===!0,this.pnpEnforcementOverride=this.resolveConfiguredPnpEnforcement(),this.frameworkErrorBus=Q.frameworkErrorBus??new v7,this.ownsFrameworkErrorBus=!Q.frameworkErrorBus,this.subscribeFrameworkErrorHookAdapters(),this.toolCoordinator=new t1,this.highlightCoordinator=new h7,this.elementToolStateStore=new o1,this.catalogResolver=new r1(Y.accessibility?.catalogs||[],Y.accessibility?.language||"en-US"),this.toolProviderRegistry=new F1,this._registerToolProviders(),this.ttsService=new m7,this.setupStatePersistenceHooks(),this.policyEngine=new z1({toolRegistry:this.toolRegistry,contextId:`toolkit-coordinator:${this.assessmentId}`,inputs:{tools:this.config.tools,assessment:null,currentItemRef:null,pnpEnforcement:this.resolveEffectivePnpEnforcement()}}),!this.lazyInit)this.waitUntilReady().catch((J)=>{console.error("[ToolkitCoordinator] Failed eager initialization:",J),this.handleError(J,{phase:"coordinator-ready"})})}subscribeFrameworkErrorHookAdapters(){this.frameworkErrorBus.subscribeFrameworkErrors((Q)=>{let Y=this.hooks.onFrameworkError;if(!Y)return;try{Y(Q)}catch(J){console.warn("[ToolkitCoordinator] onFrameworkError hook failed:",J)}})}async emitTelemetry(Q,Y){try{await this.hooks.onTelemetry?.(Q,Y)}catch(G){console.warn("[ToolkitCoordinator] telemetry hook failed:",G)}let J=Y?{...Y}:void 0;for(let G of this.telemetryListeners)try{G({eventName:Q,payload:J?{...J}:void 0})}catch(X){console.warn("[ToolkitCoordinator] telemetry listener failed:",X)}}emitSectionControllerLifecycle(Q){for(let Y of this.sectionControllerLifecycleListeners)try{Y(Q)}catch(J){console.warn("[ToolkitCoordinator] section controller lifecycle listener failed:",J)}}handleError(Q,Y){let J=r8({error:Q,context:Y});this.frameworkErrorBus.reportFrameworkError(J)}subscribeFrameworkErrors(Q){return this.frameworkErrorBus.subscribeFrameworkErrors(Q)}reportFrameworkError(Q){this.frameworkErrorBus.reportFrameworkError(Q)}getSectionControllerMapKey(Q){return`${Q.assessmentId}::${Q.sectionId}::${Q.attemptId||""}`}createDefaultSectionPersistence(){let Q=(()=>{try{if(typeof window>"u")return null;return window.localStorage}catch{return null}})(),Y=(J)=>{let{assessmentId:G,sectionId:X,attemptId:j}=J.key;return`pie:section-controller:v1:${G}:${X}:${j||"default"}`};return{async loadSession(J){if(!Q)return null;let G=Q.getItem(Y(J));if(!G)return null;try{return JSON.parse(G)}catch{return null}},async saveSession(J,G){if(!Q)return;Q.setItem(Y(J),JSON.stringify(G))},async clearSession(J){if(!Q)return;Q.removeItem(Y(J))}}}async resolveSectionPersistence(Q){let Y=this.getSectionControllerMapKey(Q.key),J=this.sectionPersistenceStrategies.get(Y);if(J)return J;let G={createDefaultPersistence:()=>this.createDefaultSectionPersistence()},X=await this.hooks.createSectionSessionPersistence?.(Q,G)??await G.createDefaultPersistence();return this.sectionPersistenceStrategies.set(Y,X),X}setupStatePersistenceHooks(){this.elementToolStateStore.setOnStateChange((Q)=>{if(!this.hooks.saveToolState)return;Promise.resolve(this.hooks.saveToolState(Q)).catch((Y)=>{this.handleError(Y,{phase:"state-save"})})})}async ensureStateLoaded(){if(this.stateLoaded)return;if(this.stateLoadPromise)return this.stateLoadPromise;return this.stateLoadPromise=(async()=>{let Q=this.hooks.loadToolState;if(!Q)return;try{let Y=await Q();if(Y&&typeof Y==="object")this.elementToolStateStore.loadState(Y);this.stateLoaded=!0,await this.emitTelemetry("pie-toolkit-tool-state-loaded",{hasState:Boolean(Y)})}catch(Y){this.handleError(Y,{phase:"state-load"})}})().finally(()=>{this.stateLoadPromise=void 0}),this.stateLoadPromise}_registerToolProviders(){let Q=this.getProviderDescriptorTools();for(let Y of Q)this.registerProviderFromTool(Y)}getProviderDescriptorTools(){return this.toolRegistry.getAllTools().filter((Q)=>!!Q.provider)}async registerProviderFromTool(Q){let Y=Q.provider;if(!Y)return;let J=this.getToolConfig(Q.toolId)||void 0;if(J?.enabled===!1)return;let G=Y.getProviderId?.(J)??J?.provider?.id??Q.toolId;if(this.toolProviderRegistry.has(G))return;let X=Y.createProvider(J),j=Y.getInitConfig?.(J)??J?.provider?.init??{},Z=this.addToolTelemetryReporter({toolId:Q.toolId,providerId:G,initConfig:j}),q=this.createToolTelemetryForwarder({toolId:Q.toolId,providerId:G}),K=Y.getAuthFetcher?.(J)??J?.provider?.runtime?.authFetcher;await this.registerProvider(G,{provider:X,config:Z,lazy:Y.lazy??!0,authFetcher:K,onTelemetry:q})}createToolTelemetryForwarder(Q){return async(Y,J)=>{await this.emitTelemetry(Y,{...J||{},toolId:Q.toolId,providerId:Q.providerId})}}addToolTelemetryReporter(Q){let Y=Q.initConfig&&typeof Q.initConfig==="object"?{...Q.initConfig}:{},J=typeof Y.onTelemetry==="function"?Y.onTelemetry:null,G=this.createToolTelemetryForwarder({toolId:Q.toolId,providerId:Q.providerId});return Y.onTelemetry=async(X,j)=>{if(J)await J(X,j);await G(X,j)},Y}async registerProvider(Q,Y){try{this.toolProviderRegistry.register(Q,Y);let J={providerId:Q,providerName:Y.provider.providerName};await this.hooks.onProviderRegistered?.(Q,J),await this.emitTelemetry("pie-toolkit-provider-registered",{providerId:Q,providerName:Y.provider.providerName})}catch(J){console.warn(`[ToolkitCoordinator] Failed to register provider "${Q}":`,J),this.handleError(J,{phase:"provider-register",providerId:Q})}}async ensureProviderReady(Q){let Y=this.providerInitPromises.get(Q);if(Y)return Y;let J=(async()=>{let G=await this.toolProviderRegistry.getProvider(Q,!1),X={providerId:Q,providerName:G.providerName};try{return await this.hooks.onProviderInitStart?.(Q,X),await this.toolProviderRegistry.initialize(Q),await this.hooks.onProviderReady?.(Q,X),await this.emitTelemetry("pie-toolkit-provider-ready",{providerId:Q}),G}catch(j){let Z=j instanceof Error?j:Error(String(j));throw this.handleError(Z,{phase:"provider-init",providerId:Q}),Z}})().finally(()=>{this.providerInitPromises.delete(Q)});return this.providerInitPromises.set(Q,J),J}setHooks(Q){if(Object.assign(this.hooks,Q),this.setupStatePersistenceHooks(),Q.onCoordinatorReady&&this.isReady())Promise.resolve(Q.onCoordinatorReady(this)).catch((Y)=>{this.handleError(Y,{phase:"coordinator-ready"})})}subscribeTelemetry(Q){return this.telemetryListeners.add(Q),()=>{this.telemetryListeners.delete(Q)}}getSectionController(Q){let Y={assessmentId:this.assessmentId,sectionId:Q.sectionId,attemptId:Q.attemptId};return this.sectionControllers.get(this.getSectionControllerMapKey(Y))}subscribeSectionEvents(Q){if(this.activeCohortMapKey===null)throw Error("[ToolkitCoordinator] subscribeSectionEvents requires an active section cohort; call getOrCreateSectionController first.");let Y=this.activeSubscriptions.get(Q.listener);if(Y)Y.unsubscribeCurrent?.(),Y.unsubscribeCurrent=null;let J={listener:Q.listener,eventTypes:Q.eventTypes,itemIds:Q.itemIds,unsubscribeCurrent:null};this.activeSubscriptions.set(Q.listener,J);let G=this.sectionControllers.get(this.activeCohortMapKey);if(G)this.bindSubscriptionToController(J,G);let X=!1;return()=>{if(X)return;if(X=!0,J.unsubscribeCurrent?.(),J.unsubscribeCurrent=null,this.activeSubscriptions.get(Q.listener)===J)this.activeSubscriptions.delete(Q.listener)}}bindSubscriptionToController(Q,Y){Q.unsubscribeCurrent?.(),Q.unsubscribeCurrent=null;let J=Y.subscribe;if(typeof J!=="function")return;let G=this.buildSectionEventPredicate(Q);Q.unsubscribeCurrent=J.call(Y,(Z)=>{if(!G(Z))return;this.deliverSectionEventSafely(Q.listener,Z)});let X=this.buildContentLoadedReplayEvents(Y);for(let Z of X)if(G(Z))this.deliverSectionEventSafely(Q.listener,Z);let j=this.buildLoadingCompleteReplayEvent(Y);if(j&&G(j))this.deliverSectionEventSafely(Q.listener,j)}deliverSectionEventSafely(Q,Y){try{Q(Y)}catch(J){console.warn("[ToolkitCoordinator] section-event listener failed:",J)}}setActiveCohort(Q){if(this.activeCohortMapKey===Q)return;this.activeCohortMapKey=Q;let Y=this.sectionControllers.get(Q);if(!Y)return;for(let J of Array.from(this.activeSubscriptions.values()))this.bindSubscriptionToController(J,Y)}setActiveCohortIfLatestRequest(Q){if(this.latestRequestedActiveCohortMapKey!==Q)return;this.setActiveCohort(Q)}suspendActiveCohortIfSuperseded(Q){if(this.activeCohortMapKey===null)return;if(this.activeCohortMapKey===Q)return;this.activeCohortMapKey=null;for(let Y of Array.from(this.activeSubscriptions.values()))Y.unsubscribeCurrent?.(),Y.unsubscribeCurrent=null}clearActiveCohortIfMatches(Q){if(this.activeCohortMapKey!==Q)return;this.activeCohortMapKey=null;for(let Y of Array.from(this.activeSubscriptions.values()))Y.unsubscribeCurrent?.(),Y.unsubscribeCurrent=null}buildSectionEventPredicate(Q){let Y=Q.eventTypes?new Set(Q.eventTypes):null,J=Q.itemIds?new Set(Q.itemIds):null;return(G)=>{if(Y||J){let X=G?.type||null;if(Y&&(!X||!Y.has(X)))return!1;if(J){if(!Array.from(this.collectEventItemIds(G)).some((Z)=>J.has(Z)))return!1}}return!0}}collectEventItemIds(Q){let Y=new Set;if("itemId"in Q&&typeof Q.itemId==="string")Y.add(Q.itemId);if("canonicalItemId"in Q&&typeof Q.canonicalItemId==="string")Y.add(Q.canonicalItemId);if("currentItemId"in Q&&typeof Q.currentItemId==="string")Y.add(Q.currentItemId);if("previousItemId"in Q&&typeof Q.previousItemId==="string")Y.add(Q.previousItemId);return Y}buildContentLoadedReplayEvents(Q){let Y=Q.getRuntimeState?.(),J=Y?.loadedRenderables;if(!Array.isArray(J)||J.length===0)return[];let G=typeof Y?.currentItemIndex==="number"&&Number.isFinite(Y.currentItemIndex)?Y.currentItemIndex:0,X=Date.now(),j=[];for(let Z of J){if(!Z)continue;let q=Z.itemId,K=typeof Z.canonicalItemId==="string"&&Z.canonicalItemId?Z.canonicalItemId:q;if(typeof q!=="string"||!q)continue;j.push({type:"content-loaded",contentKind:Z.contentKind??"unknown",itemId:q,canonicalItemId:K,currentItemIndex:G,timestamp:X})}return j}buildLoadingCompleteReplayEvent(Q){let Y=Q.getRuntimeState?.();if(Y?.loadingComplete!==!0)return null;let J=typeof Y.totalRegistered==="number"&&Number.isFinite(Y.totalRegistered)?Math.max(0,Y.totalRegistered):0,G=typeof Y.totalLoaded==="number"&&Number.isFinite(Y.totalLoaded)?Math.max(0,Y.totalLoaded):J;return{type:"section-loading-complete",totalRegistered:J,totalLoaded:G,currentItemIndex:Y.currentItemIndex,timestamp:Date.now()}}subscribeItemEvents(Q){return this.subscribeSectionEvents({eventTypes:Q.eventTypes||t2,itemIds:Q.itemIds,listener:Q.listener})}subscribeSectionLifecycleEvents(Q){return this.subscribeSectionEvents({eventTypes:Q.eventTypes||e2,listener:Q.listener})}onSectionControllerLifecycle(Q){return this.sectionControllerLifecycleListeners.add(Q),()=>{this.sectionControllerLifecycleListeners.delete(Q)}}async getOrCreateSectionController(Q){let Y={assessmentId:this.assessmentId,sectionId:Q.sectionId,attemptId:Q.attemptId},J=this.getSectionControllerMapKey(Y);this.latestRequestedActiveCohortMapKey=J,this.suspendActiveCohortIfSuperseded(J);let G=await this.resolveExistingSectionController({mapKey:J,key:Y,input:Q.input,updateExisting:Q.updateExisting});if(G)return G;let X=this.sectionControllerInitPromises.get(J);if(X)return X;let j=this.initializeNewSectionController({args:Q,key:Y,mapKey:J}).catch((Z)=>{throw this.handleSectionControllerInitError(Z,Q),Z}).finally(()=>{this.sectionControllerInitPromises.delete(J)});return this.sectionControllerInitPromises.set(J,j),j}async resolveExistingSectionController(Q){let Y=this.sectionControllers.get(Q.mapKey);if(!Y)return;if(this.sectionControllerKeys.set(Q.mapKey,Q.key),Q.updateExisting!==!1)await Y.updateInput?.(Q.input);return this.setActiveCohortIfLatestRequest(Q.mapKey),Y}createSectionControllerContext(Q){return{key:Q.key,coordinator:this,input:Q.input}}async initializeNewSectionController(Q){let Y=this.createSectionControllerContext({key:Q.key,input:Q.args.input}),J=await this.resolveSectionPersistence(Y),G={createDefaultController:Q.args.createDefaultController},X=await this.hooks.createSectionController?.(Y,G)??await G.createDefaultController();return await X.configureSessionPersistence?.({strategy:J,context:Y}),await X.initialize?.(Q.args.input),await X.hydrate?.(),await this.finalizeSectionControllerReady({mapKey:Q.mapKey,key:Q.key,context:Y,controller:X}),X}async finalizeSectionControllerReady(Q){this.sectionControllers.set(Q.mapKey,Q.controller),this.sectionControllerKeys.set(Q.mapKey,Q.key),this.setActiveCohortIfLatestRequest(Q.mapKey),this.emitSectionControllerLifecycle({type:"ready",key:Q.key,controller:Q.controller}),await this.hooks.onSectionControllerReady?.(Q.context,Q.controller),await this.emitTelemetry("pie-toolkit-section-controller-ready",{assessmentId:Q.key.assessmentId,sectionId:Q.key.sectionId,attemptId:Q.key.attemptId})}handleSectionControllerInitError(Q,Y){this.handleError(Q,{phase:"section-controller-init",details:{sectionId:Y.sectionId,attemptId:Y.attemptId}})}async disposeSectionController(Q){let Y={assessmentId:this.assessmentId,sectionId:Q.sectionId,attemptId:Q.attemptId},J=this.getSectionControllerMapKey(Y),G=this.sectionControllers.get(J);if(!G)return;this.clearActiveCohortIfMatches(J);let X=this.createSectionControllerContext({key:Y,input:void 0});try{await this.runSectionControllerDisposePipeline({key:Y,context:X,controller:G,persistBeforeDispose:Q.persistBeforeDispose})}catch(j){this.handleError(j,{phase:"section-controller-dispose",details:{sectionId:Q.sectionId,attemptId:Q.attemptId}})}finally{await this.finalizeSectionControllerDispose({mapKey:J,key:Y,context:X,clearPersistence:Q.clearPersistence})}}async runSectionControllerDisposePipeline(Q){if(Q.persistBeforeDispose!==!1)await Q.controller.persist?.();await Q.controller.dispose?.(),await this.hooks.onSectionControllerDispose?.(Q.context,Q.controller),await this.emitTelemetry("pie-toolkit-section-controller-disposed",{assessmentId:Q.key.assessmentId,sectionId:Q.key.sectionId,attemptId:Q.key.attemptId})}async finalizeSectionControllerDispose(Q){if(this.sectionControllers.delete(Q.mapKey),this.sectionControllerKeys.delete(Q.mapKey),this.emitSectionControllerLifecycle({type:"disposed",key:Q.key}),Q.clearPersistence)await this.sectionPersistenceStrategies.get(Q.mapKey)?.clearSession?.(Q.context);this.sectionPersistenceStrategies.delete(Q.mapKey)}async ensureTTSReady(Q){if(await this.waitForPendingTTSReconfigure(),this.ttsInitialized)return;if(this.ttsInitPromise)return this.ttsInitPromise;return this.ttsInitPromise=this._initializeTTS(Q).finally(()=>{this.ttsInitPromise=void 0}),this.ttsInitPromise}async waitForPendingTTSReconfigure(){let Q=this.ttsReconfigurePromise;while(Q)await Q,Q=this.ttsReconfigurePromise}async _initializeTTS(Q){if(this.ttsInitialized)return;let Y=this.resolveTTSToolConfig(Q),J=w6(Y),G=N8(J),X=R6(J);if(await this.hooks.onBeforeTTSInit?.({phase:"tts-init",details:{backend:G}}),await this.emitTelemetry("pie-toolkit-tts-init-start",{backend:G}),await this.emitTelemetry("pie-tool-init-start",{toolId:"textToSpeech",operation:"tts-init",backend:G}),this.toolProviderRegistry.has("tts"))try{let q=await(await this.ensureProviderReady("tts")).createInstance();await this.initializeTTSService(q,X),await this.emitTelemetry("pie-toolkit-tts-init-success",{provider:"registry"}),await this.emitTelemetry("pie-tool-init-success",{toolId:"textToSpeech",operation:"tts-init",backend:G,provider:"registry"}),console.log("[ToolkitCoordinator] TTS initialized via ToolProviderRegistry");return}catch(Z){let q=Z instanceof Error?Z:Error(String(Z));await this.emitTelemetry("pie-tool-init-error",{toolId:"textToSpeech",providerId:"tts",operation:"tts-init",backend:G,errorType:"TTSRegistryInitError",message:q.message,recovered:!0}),await this.emitTelemetry("pie-tool-init-fallback",{toolId:"textToSpeech",providerId:"tts",operation:"tts-init",backend:G,fromProvider:"registry",toProvider:"browser",reason:q.message}),console.warn("[ToolkitCoordinator] Failed to initialize TTS via registry, falling back to browser provider:",q)}let j=new R7;try{await this.initializeTTSService(j,X),await this.emitTelemetry("pie-toolkit-tts-init-success",{provider:"browser-fallback"}),await this.emitTelemetry("pie-tool-init-success",{toolId:"textToSpeech",operation:"tts-init",backend:G,provider:"browser-fallback"})}catch(Z){let q=Z instanceof Error?Z:Error(String(Z));throw this.handleError(q,{phase:"tts-init"}),await this.emitTelemetry("pie-toolkit-tts-init-error",{message:q.message}),await this.emitTelemetry("pie-tool-init-error",{toolId:"textToSpeech",operation:"tts-init",backend:G,errorType:"TTSInitError",message:q.message}),q}}resolveTTSToolConfig(Q){return Q||this.getTTSConfigFromProviders()||{}}async initializeTTSService(Q,Y){let J={...Y.providerOptions||{},__pieTelemetry:async(X,j)=>{await this.emitTelemetry(X,{toolId:"textToSpeech",...j||{}})}},G={...Y,providerOptions:J};await this.ttsService.initialize(Q,G),await this.ensureBrowserVoicesReady(Q),this.ttsService.setCatalogResolver(this.catalogResolver),this.ttsInitialized=!0,await this.hooks.onTTSReady?.()}async ensureBrowserVoicesReady(Q,Y=1200){if(Q.providerId!=="browser")return;if(typeof window>"u")return;if(!("speechSynthesis"in window))return;let J=window.speechSynthesis;if(J.getVoices().length>0)return;await new Promise((j)=>{let Z=!1,q=typeof J.addEventListener==="function"&&typeof J.removeEventListener==="function",K=!q&&"onvoiceschanged"in J,B=K?J.onvoiceschanged:null,U=!1,H=()=>{if(Z)return;if(Z=!0,window.clearTimeout(A),q)J.removeEventListener("voiceschanged",_);else if(U&&J.onvoiceschanged===_)J.onvoiceschanged=B;j()},_=(M)=>{if(!q&&typeof B==="function"&&M)B.call(J,M);H()},A=window.setTimeout(H,Y);if(q)J.addEventListener("voiceschanged",_,{once:!0});else if(K)J.onvoiceschanged=_,U=!0});let X=J.getVoices();await this.emitTelemetry("pie-toolkit-tts-browser-voices-ready",{voiceCount:X.length,timedOut:X.length===0})}getServiceBundle(){return{ttsService:this.ttsService,toolCoordinator:this.toolCoordinator,highlightCoordinator:this.highlightCoordinator,elementToolStateStore:this.elementToolStateStore,catalogResolver:this.catalogResolver,toolProviderRegistry:this.toolProviderRegistry}}async getToolProvider(Q){return this.ensureProviderReady(Q)}async waitUntilReady(){if(this.isReady())return;if(this.coordinatorReadyPromise)return this.coordinatorReadyPromise;return this.coordinatorReadyPromise=(async()=>{await this.ensureStateLoaded();let Q=this.getTTSConfigFromProviders();if(Q?.enabled!==!1)await this.ensureTTSReady(Q);if(!this.coordinatorReadyNotified)this.coordinatorReadyNotified=!0,await this.hooks.onCoordinatorReady?.(this),await this.emitTelemetry("pie-toolkit-coordinator-ready",{assessmentId:this.assessmentId})})().finally(()=>{this.coordinatorReadyPromise=void 0}),this.coordinatorReadyPromise}isReady(){return this.getInitStatus().coordinator}getInitStatus(){let Q={};for(let J of this.toolProviderRegistry.getProviderIds())Q[J]=this.toolProviderRegistry.isInitialized(J);let Y=this.getTTSConfigFromProviders();return{tts:this.ttsInitialized,stateLoaded:this.stateLoaded||!this.hooks.loadToolState,coordinator:(this.stateLoaded||!this.hooks.loadToolState)&&(this.ttsInitialized||Y?.enabled===!1),providers:Q}}getTTSConfigFromProviders(){return(this.config.tools?.providers||{}).textToSpeech}assertCanonicalToolId(Q){if(typeof Q!=="string"||Q.trim().length===0)throw Error("Tool id must be a non-empty string.");if(Q==="tts")throw Error('Tool id "tts" is no longer supported. Use "textToSpeech".');if(this.toolRegistry.getAllToolIds().length===0)return;if(!this.toolRegistry.get(Q))throw Error(`Unknown tool id "${Q}".`)}installToolContextResolvers(Q){if(!Q)return;for(let[Y,J]of Object.entries(Q)){if(J==null)continue;if(this.assertCanonicalToolId(Y),typeof J!=="function")throw Error(`Invalid tool context resolver for "${Y}": expected a function.`);this.toolContextResolvers.set(Y,J)}}setToolContextResolvers(Q){this.toolContextResolvers.clear(),this.installToolContextResolvers(Q??void 0),this.notifyToolContextResolverChange()}notifyToolContextResolverChange(){for(let Q of this.toolContextResolverChangeListeners)try{Q()}catch(Y){console.warn("[ToolkitCoordinator] Tool context resolver listener threw:",Y)}}isToolEnabled(Q){return this.assertCanonicalToolId(Q),this.config.tools?.providers?.[Q]?.enabled!==!1}getToolConfig(Q){return this.assertCanonicalToolId(Q),this.config.tools?.providers?.[Q]||null}updateToolConfig(Q,Y){this.assertCanonicalToolId(Q);let J=this.getToolConfig(Q)||{};if(!this.config.tools)this.config.tools=G7(void 0,{strictness:this.config.toolConfigStrictness??"error",source:"ToolkitCoordinator.updateToolConfig",toolRegistry:this.toolRegistry}).config;if(!this.config.tools.providers)this.config.tools.providers={};let G={...this.config.tools.providers||{},[Q]:a2(Q,J,Y)},X=G7({...this.config.tools,providers:G},{strictness:this.config.toolConfigStrictness??"error",source:"ToolkitCoordinator.updateToolConfig",toolRegistry:this.toolRegistry});this.config.tools=X.config,this.policyEngine.updateInputs({tools:this.config.tools}),this.emitTelemetry("pie-toolkit-tool-config-updated",{toolId:Q}),this._applyToolConfigChange(Q,Y)}updateToolPlacement(Q,Y){this.updateToolsPlacement({[Q]:[...Y]})}updateToolsPlacement(Q){if(!this.config.tools)this.config.tools=G7(void 0,{strictness:this.config.toolConfigStrictness??"error",source:"ToolkitCoordinator.updateToolsPlacement",toolRegistry:this.toolRegistry}).config;let Y=this.config.tools?.placement??{section:[],item:[],passage:[]},J={section:[...Q.section??Y.section??[]],item:[...Q.item??Y.item??[]],passage:[...Q.passage??Y.passage??[]]},G=G7({...this.config.tools,placement:J},{strictness:this.config.toolConfigStrictness??"error",source:"ToolkitCoordinator.updateToolsPlacement",toolRegistry:this.toolRegistry});G.config.placement=J,this.config.tools=G.config,this.policyEngine.updateInputs({tools:this.config.tools})}decideToolPolicy(Q){return this.policyEngine.decide(Q)}decideFeaturePolicy(Q){let Y=this.policyEngine.decideFeature(Q);if(!Y.assessmentBound&&!this.reportedUnboundFeaturePolicy)this.reportedUnboundFeaturePolicy=!0,console.warn(`[ToolkitCoordinator] Feature policy was asked about "${Q}" with no assessment bound, so every capability will be declined for want of a profile to read. Call updateAssessment(...) with the assessment (its personalNeedsProfile, settings.districtPolicy and settings.testAdministration are what policy reads) before relying on any accommodation. Reported once per coordinator.`);return Y}onPolicyChange(Q){return this.policyEngine.onPolicyChange(Q)}onCatalogsChange(Q){return this.catalogResolver.onCatalogsChange(Q)}updateAssessment(Q){this.boundAssessment=Q,this.policyEngine.updateInputs({assessment:Q,pnpEnforcement:this.resolveEffectivePnpEnforcement()})}updateCurrentItemRef(Q){this.boundCurrentItemRef=Q,this.policyEngine.updateInputs({currentItemRef:Q,pnpEnforcement:this.resolveEffectivePnpEnforcement()})}setPnpEnforcement(Q){this.pnpEnforcementOverride=Q,this.policyEngine.updateInputs({pnpEnforcement:this.resolveEffectivePnpEnforcement()})}getPolicyInputs(){return this.policyEngine.getInputs()}registerPolicySource(Q){return this.policyEngine.registerPolicySource(Q)}registerToolContextResolver(Q,Y){if(this.assertCanonicalToolId(Q),typeof Y!=="function")throw Error(`Invalid tool context resolver for "${Q}": expected a function.`);return this.toolContextResolvers.set(Q,Y),this.notifyToolContextResolverChange(),()=>{if(this.toolContextResolvers.get(Q)!==Y)return;this.toolContextResolvers.delete(Q),this.notifyToolContextResolverChange()}}hasToolContextResolver(Q){return this.assertCanonicalToolId(Q),this.toolContextResolvers.has(Q)}resolveToolContext(Q){this.assertCanonicalToolId(Q.toolId);let Y=this.toolContextResolvers.get(Q.toolId);if(!Y)return null;let J;try{J=Y(Q)}catch(X){return console.error(`[ToolkitCoordinator] Tool context resolver for "${Q.toolId}" threw:`,X),{toolId:Q.toolId,visible:!1,params:{},reason:"Tool context resolver threw."}}if(!J)return{toolId:Q.toolId,visible:!0,params:{}};let G=J.params&&typeof J.params==="object"&&!Array.isArray(J.params)?J.params:{};return{toolId:Q.toolId,visible:J.visible!==!1,params:G,reason:typeof J.reason==="string"?J.reason:void 0}}onToolContextResolverChange(Q){return this.toolContextResolverChangeListeners.add(Q),()=>{this.toolContextResolverChangeListeners.delete(Q)}}resolveEffectivePnpEnforcement(){if(this.pnpEnforcementOverride!==null)return this.pnpEnforcementOverride;return u7({assessment:this.boundAssessment,currentItemRef:this.boundCurrentItemRef})}resolveConfiguredPnpEnforcement(){return this.config.tools?.pnpEnforcement??null}_applyToolConfigChange(Q,Y){switch(Q){case"textToSpeech":{let J=this._reconfigureTTSProvider();this.ttsReconfigurePromise=J,J.finally(()=>{if(this.ttsReconfigurePromise===J)this.ttsReconfigurePromise=void 0}),J.then(async()=>{let G=this.getTTSConfigFromProviders();if(!this.lazyInit&&G?.enabled!==!1)await this.ensureTTSReady(G)});break}case"answerEliminator":break}}async _reconfigureTTSProvider(){this.ttsInitialized=!1,this.ttsInitPromise=void 0;try{this.ttsService.stop()}catch{}if(this.toolProviderRegistry.has("tts"))await this.toolProviderRegistry.unregister("tts");let Q=this.getProviderDescriptorTools().find((Y)=>Y.toolId==="textToSpeech");if(!Q)return;await this.registerProviderFromTool(Q)}}var C6="pie-register",y6="pie-unregister",x6="pie-item-session-changed";var f6="pie-content-loaded",k6="pie-item-player-error";var Q5={bubbles:!0,composed:!0,cancelable:!1};function Y5(Q,Y,J={}){return new CustomEvent(Q,{detail:Y,...Q5,...J})}function P8(Q,Y,J,G={}){return Q.dispatchEvent(Y5(Y,J,G))}function T7(){return{phase:"idle",cohort:null,controllerResolved:!1,readinessSignals:{sectionReady:!1,interactionReady:!1,allLoadingComplete:!1,runtimeError:!1},effectiveRuntime:null,effectiveToolsConfig:null,loadingCompleteEmitted:!1,lastFrameworkError:null,itemCount:0,loadedCount:0}}function L8(Q,Y){if(Q===Y)return!0;if(!Q||!Y)return!1;return Q.sectionId===Y.sectionId&&Q.attemptId===Y.attemptId}function J5(Q){if(Q.runtimeError)return"error";if(Q.allLoadingComplete)return"ready";if(Q.interactionReady)return"interaction-ready";if(Q.sectionReady)return"loading";return"bootstrapping"}function I6(Q){let Y=Q.signals.sectionReady&&Q.signals.allLoadingComplete,J=Q.mode==="strict"?Y:Q.signals.interactionReady;return{phase:J5({...Q.signals,allLoadingComplete:Y,interactionReady:J}),interactionReady:J,allLoadingComplete:Y,reason:Q.reason}}function v6(Q){switch(Q){case"idle":return null;case"booting-section":return"composed";case"engine-ready":return"engine-ready";case"interactive":return"interactive";case"disposed":return"disposed"}}function L1(Q,Y,J,G="entered"){let X=v6(Y);if(!X)return;Q.push({kind:"stage-change",stage:X,status:G,cohort:J})}function h6(Q){let Y={...T7(),phase:"booting-section",cohort:Q.cohort,effectiveRuntime:Q.effectiveRuntime,effectiveToolsConfig:Q.effectiveToolsConfig,itemCount:Q.itemCount},J=[];return L1(J,"booting-section",Q.cohort),{state:Y,outputs:J}}function G5(Q,Y){if(Q.phase==="idle"||Q.phase==="disposed")return{state:Q,outputs:[]};let J=I6({mode:Y.mode,signals:Y.signals}),G=[],X=Q.phase,j=Q.loadingCompleteEmitted;if(X==="engine-ready"&&J.interactionReady)X="interactive",L1(G,X,Q.cohort);if(J.allLoadingComplete&&Q.cohort&&!j)j=!0,G.push({kind:"loading-complete",cohort:Q.cohort,itemCount:Y.itemCount,loadedCount:Y.loadedCount});return{state:{...Q,phase:X,readinessSignals:Y.signals,loadedCount:Y.loadedCount,itemCount:Y.itemCount,loadingCompleteEmitted:j},outputs:G}}function p7(Q,Y){switch(Y.kind){case"initialize":{if(Q.phase==="disposed")return{state:Q,outputs:[]};if(Q.phase!=="idle"){if(L8(Q.cohort,Y.cohort))return p7(Q,{kind:"update-runtime",effectiveRuntime:Y.effectiveRuntime,effectiveToolsConfig:Y.effectiveToolsConfig});return p7(Q,{kind:"cohort-change",cohort:Y.cohort,effectiveRuntime:Y.effectiveRuntime,effectiveToolsConfig:Y.effectiveToolsConfig,itemCount:Y.itemCount})}return h6({state:Q,cohort:Y.cohort,effectiveRuntime:Y.effectiveRuntime,effectiveToolsConfig:Y.effectiveToolsConfig,itemCount:Y.itemCount})}case"update-runtime":{if(Q.phase==="idle"||Q.phase==="disposed")return{state:Q,outputs:[]};return{state:{...Q,effectiveRuntime:Y.effectiveRuntime,effectiveToolsConfig:Y.effectiveToolsConfig},outputs:[]}}case"cohort-change":{if(Q.phase==="disposed")return{state:Q,outputs:[]};if(L8(Q.cohort,Y.cohort))return p7(Q,{kind:"update-runtime",effectiveRuntime:Y.effectiveRuntime,effectiveToolsConfig:Y.effectiveToolsConfig});let J=[];if(Q.phase!=="idle")J.push({kind:"stage-change",stage:"disposed",status:"entered",cohort:Q.cohort});let G=h6({state:Q,cohort:Y.cohort,effectiveRuntime:Y.effectiveRuntime,effectiveToolsConfig:Y.effectiveToolsConfig,itemCount:Y.itemCount});return{state:G.state,outputs:[...J,...G.outputs]}}case"section-controller-resolved":{if(Q.phase!=="booting-section")return{state:{...Q,controllerResolved:!0},outputs:[]};let J=[];return L1(J,"engine-ready",Q.cohort),{state:{...Q,phase:"engine-ready",controllerResolved:!0},outputs:J}}case"update-readiness-signals":return G5(Q,{signals:Y.signals,mode:Y.mode,loadedCount:Y.loadedCount,itemCount:Y.itemCount});case"framework-error":return{state:{...Q,lastFrameworkError:Y.error,readinessSignals:{...Q.readinessSignals,runtimeError:Y.error.recoverable===!0?Q.readinessSignals.runtimeError:!0}},outputs:[{kind:"framework-error",error:Y.error}]};case"dispose":{if(Q.phase==="disposed")return{state:Q,outputs:[]};let J=[];if(Q.phase!=="idle")L1(J,"disposed",Q.cohort);return{state:{...Q,phase:"disposed"},outputs:J}}default:{let J=Y;return{state:Q,outputs:[]}}}}class $8{state=T7();listeners=new Set;getState(){return this.state}dispatch(Q){let Y=p7(this.state,Q);if(this.state=Y.state,Y.outputs.length>0)this.fanOut(Y.outputs);return Y.outputs}subscribe(Q){this.listeners.add(Q);let Y=!0;return()=>{if(!Y)return;Y=!1,this.listeners.delete(Q)}}disposeListeners(){this.listeners.clear()}fanOut(Q){let Y=Array.from(this.listeners),J=Object.freeze(Q.slice());for(let G of Y)try{G(J)}catch(X){console.warn("[SectionEngineCore] listener failed:",X)}}}function m6(Q){let{coordinator:Y,dispatchCoreInput:J}=Q,G=0,X=null,j=null,Z=!1,q=Y.subscribeFrameworkErrors((H)=>{try{J({kind:"framework-error",error:H})}catch(_){console.warn("[CoordinatorBridge] framework-error dispatch failed:",_)}});function K(){if(!j)return;try{j()}catch(H){console.warn("[CoordinatorBridge] controller unsubscribe failed:",H)}j=null}async function B(H){if(Z)return;G+=1;let _=G;X=H.cohort;let A=await Y.getOrCreateSectionController({sectionId:H.cohort.sectionId,attemptId:H.cohort.attemptId||void 0,input:{section:H.section,sectionId:H.cohort.sectionId,assessmentId:H.assessmentId,view:H.view},updateExisting:!0,createDefaultController:H.createDefaultController});if(_!==G||Z)return;K(),H.onControllerResolved?.(A);let M=A.getCompositionModel;if(H.onCompositionChanged?.(M?.()),typeof A.subscribe==="function")j=A.subscribe((O)=>{if(_!==G||Z)return;H.onCompositionChanged?.(M?.())});J({kind:"section-controller-resolved"})}async function U(){if(Z)return;Z=!0,G+=1,K();try{q()}catch(_){console.warn("[CoordinatorBridge] framework-error unsubscribe failed:",_)}let H=X;if(X=null,H)try{await Y.disposeSectionController({sectionId:H.sectionId,attemptId:H.attemptId||void 0})}catch(_){console.warn("[CoordinatorBridge] section-controller dispose failed:",_)}}return{resolveSectionController:B,dispose:U}}function u6(Q){let{runtimeId:Y,sourceCe:J}=Q,G=Q.host,X=Q.now??(()=>new Date().toISOString());function j(U){let H={stage:U.stage,status:U.status,runtimeId:Y,sectionId:U.cohort?.sectionId,attemptId:U.cohort?.attemptId?U.cohort.attemptId:void 0,timestamp:X(),sourceCe:J};G.dispatchEvent(new CustomEvent("pie-stage-change",{detail:H}))}function Z(U){let H={runtimeId:Y,sectionId:U.cohort.sectionId,attemptId:U.cohort.attemptId?U.cohort.attemptId:void 0,itemCount:U.itemCount,loadedCount:U.loadedCount,timestamp:X(),sourceCe:J};G.dispatchEvent(new CustomEvent("pie-loading-complete",{detail:H}))}function q(U){G.dispatchEvent(new CustomEvent("framework-error",{detail:U.error}))}function K(U){switch(U.kind){case"stage-change":j(U);return;case"loading-complete":Z(U);return;case"framework-error":q(U);return;default:{let H=U;return}}}function B(U){G=U}return{dispatch:K,setHost:B}}function p6(Q){let{bus:Y}=Q;function J(G){switch(G.kind){case"framework-error":Y.reportFrameworkError(G.error);return;case"stage-change":case"loading-complete":return;default:{let X=G;return}}}return{dispatch:J}}function g6(Q={}){let Y=Q.hook;function J(X){if(!Y)return;try{Y(X)}catch(j){console.warn("[InstrumentationBridge] hook failed:",j)}}function G(X){Y=X}return{dispatch:J,setHook:G}}function c6(){let Q=new Set;function Y(j){if(j.length===0)return;let Z=Array.from(Q),q=Object.freeze(j.slice());for(let K of Z)try{K(q)}catch(B){console.warn("[SubscriberFanout] listener failed:",B)}}function J(j){Q.add(j);let Z=!0;return()=>{if(!Z)return;Z=!1,Q.delete(j)}}function G(){Q.clear()}function X(){return Q.size}return{emit:Y,subscribe:J,dispose:G,getListenerCount:X}}class w8{core;domEventBridge;frameworkErrorBridge;instrumentationBridge;subscriberFanout;coordinatorBridge;unsubscribeCore;disposed=!1;constructor(Q){this.core=Q.core??new $8,this.domEventBridge=u6({host:Q.host,runtimeId:Q.runtimeId,sourceCe:Q.sourceCe,now:Q.now}),this.frameworkErrorBridge=p6({bus:Q.frameworkErrorBus}),this.instrumentationBridge=g6({hook:Q.instrumentationHook}),this.subscriberFanout=c6(),this.coordinatorBridge=Q.coordinator?m6({coordinator:Q.coordinator,dispatchCoreInput:(Y)=>this.dispatchInput(Y)}):null,this.unsubscribeCore=this.core.subscribe((Y)=>{this.routeOutputs(Y)})}getState(){return this.core.getState()}dispatchInput(Q){if(this.disposed)return[];return this.core.dispatch(Q)}subscribe(Q){return this.subscriberFanout.subscribe(Q)}setHost(Q){this.domEventBridge.setHost(Q)}setInstrumentationHook(Q){this.instrumentationBridge.setHook(Q)}resolveSectionController(Q){if(!this.coordinatorBridge)throw Error("[SectionEngineAdapter] resolveSectionController called without a coordinator.");return this.coordinatorBridge.resolveSectionController(Q)}async dispose(){if(this.disposed)return;if(this.disposed=!0,this.core.dispatch({kind:"dispose"}),this.unsubscribeCore(),this.subscriberFanout.dispose(),this.coordinatorBridge)await this.coordinatorBridge.dispose()}routeOutputs(Q){for(let Y of Q)this.routeOne(Y);this.subscriberFanout.emit(Q)}routeOne(Q){switch(Q.kind){case"stage-change":case"loading-complete":this.domEventBridge.dispatch(Q);break;case"framework-error":this.domEventBridge.dispatch(Q),this.frameworkErrorBridge.dispatch(Q);break;default:{let Y=Q;return}}this.instrumentationBridge.dispatch(Q)}}var X5={mode:"gather",role:"student"};function $1(Q,Y){return Q!==void 0?Q:Y}function Z5(Q){let Y=Q.runtime??{};if(Y.onFrameworkError!==void 0)return Y.onFrameworkError;return Q.onFrameworkError}function j5(Q){let Y=Q.runtime?.tools||{},J=Y.placement||{};return{...Y,placement:{...J}}}function q5(Q){let Y=Q.runtime||{},J=Y.player?{...Y.player}:null;return{...Y,assessmentId:$1(Y.assessmentId,Q.assessmentId),playerType:Y.playerType??"iife",player:J,lazyInit:Y.lazyInit??!0,accessibility:Y.accessibility??null,coordinator:Y.coordinator??null,createSectionController:Y.createSectionController,isolation:Y.isolation??"inherit",env:Y.env??X5,toolConfigStrictness:$1(Y.toolConfigStrictness,Q.toolConfigStrictness)??"error",onFrameworkError:Z5({runtime:Q.runtime,onFrameworkError:Q.onFrameworkError}),onStageChange:$1(Y.onStageChange,Q.onStageChange),onLoadingComplete:$1(Y.onLoadingComplete,Q.onLoadingComplete),tools:Q.effectiveToolsConfig}}function l6(Q,Y){let J=Q.assessmentId??"section-demo-direct",G=j5({runtime:Q.runtime}),X=q5({assessmentId:J,runtime:Q.runtime,effectiveToolsConfig:G,toolConfigStrictness:Q.toolConfigStrictness,onFrameworkError:Q.onFrameworkError,onStageChange:Q.onStageChange,onLoadingComplete:Q.onLoadingComplete}),j=Y.resolvePlayerRuntime({effectiveRuntime:X,playerType:String(X.playerType??"iife"),env:X.env??null});return{effectiveToolsConfig:G,effectiveRuntime:X,playerRuntime:j}}function K5(Q,Y){if(Q===Y)return 0;let J=Q.compareDocumentPosition(Y);if(J&Node.DOCUMENT_POSITION_PRECEDING)return 1;if(J&Node.DOCUMENT_POSITION_FOLLOWING)return-1;return 0}class R8{shellsByElement=new Map;register(Q){let Y=this.shellsByElement.get(Q.element),J={...Q,sortKey:Date.now()};if(Y&&Y.kind===J.kind&&Y.itemId===J.itemId&&Y.canonicalItemId===J.canonicalItemId)return!1;return this.shellsByElement.set(Q.element,J),!0}unregister(Q){return this.shellsByElement.delete(Q)}getOrderedShells(Q){let Y=Array.from(this.shellsByElement.values()).filter((J)=>!Q||J.kind===Q);return Y.sort((J,G)=>K5(J.element,G.element)),Y}getCanonicalIdMap(){let Q={};for(let Y of this.getOrderedShells("item")){if(!Y.itemId)continue;Q[Y.itemId]=Y.canonicalItemId||Y.itemId}return Q}clear(){this.shellsByElement.clear()}}function w1(Q="runtime"){return`${Q}-${Math.random().toString(16).slice(2)}-${Date.now()}`}class E8{registry=new R8;runtimeId=w1("section-engine");adapter=null;controller=null;coordinator=null;sectionId="";attemptId;unsubscribeController=null;activeInitToken=0;loadedRenderableKeys=new Set;attachHost(Q){if(this.adapter){if(this.adapter.setHost(Q.host),Q.instrumentationHook!==void 0)this.adapter.setInstrumentationHook(Q.instrumentationHook);return}this.adapter=new w8({host:Q.host,runtimeId:this.runtimeId,sourceCe:Q.sourceCe,frameworkErrorBus:Q.frameworkErrorBus,coordinator:Q.coordinator,instrumentationHook:Q.instrumentationHook,now:Q.now})}dispatchInput(Q){return this.adapter?.dispatchInput(Q)??[]}subscribe(Q){return this.adapter?.subscribe(Q)??W5}getState(){return this.adapter?.getState()??T7()}getEffectiveRuntime(Q,Y){return l6(Q,Y).effectiveRuntime}setInstrumentationHook(Q){this.adapter?.setInstrumentationHook(Q)}getRuntimeId(){return this.runtimeId}async initialize(Q){this.activeInitToken+=1;let Y=this.activeInitToken;this.coordinator=Q.coordinator,this.sectionId=Q.sectionId,this.attemptId=Q.attemptId;let J=await Q.coordinator.getOrCreateSectionController({sectionId:Q.sectionId,attemptId:Q.attemptId,input:{section:Q.section,sectionId:Q.sectionId,assessmentId:Q.assessmentId,view:Q.view},updateExisting:!0,createDefaultController:Q.createDefaultController});if(Y!==this.activeInitToken)return;this.unsubscribeController?.(),this.controller=J,this.replayRegisteredShellsIntoController(J),Q.onCompositionChanged?.(J.getCompositionModel?.()),this.unsubscribeController=J.subscribe?.(()=>{Q.onCompositionChanged?.(J.getCompositionModel?.())})||null}replayRegisteredShellsIntoController(Q){if(!Q.handleContentRegistered)return;let Y=this.registry.getOrderedShells();if(Y.length===0)return;for(let G of Y){let X=G.canonicalItemId||G.itemId;Q.handleContentRegistered({itemId:G.itemId,canonicalItemId:X,contentKind:G.contentKind||G.kind})}let J=Date.now();for(let G of Y){let X=G.canonicalItemId||G.itemId,j=this.getLoadedKey(X,G.contentKind);if(this.loadedRenderableKeys.has(j))Q.handleContentLoaded?.({itemId:G.itemId,canonicalItemId:X,contentKind:G.contentKind||G.kind,timestamp:J})}}getLoadedKey(Q,Y){return`${Y??""}:${Q}`}register(Q){return this.registry.register(Q)}unregister(Q){return this.registry.unregister(Q)}getCompositionModel(){return this.controller?.getCompositionModel?.()??null}getCanonicalItemId(Q){return this.registry.getCanonicalIdMap()[Q]||this.controller?.getCanonicalItemId?.(Q)||Q}handleContentRegistered(Q){this.controller?.handleContentRegistered?.({itemId:Q.itemId,canonicalItemId:Q.canonicalItemId||Q.itemId,contentKind:Q.contentKind||Q.kind})}handleContentUnregistered(Q){let Y=Q.canonicalItemId||Q.itemId;this.loadedRenderableKeys.delete(this.getLoadedKey(Y,Q.contentKind)),this.controller?.handleContentUnregistered?.({itemId:Q.itemId,canonicalItemId:Y,contentKind:Q.contentKind||Q.kind})}handleContentLoaded(Q){let Y=Q.canonicalItemId||Q.itemId;this.loadedRenderableKeys.add(this.getLoadedKey(Y,Q.contentKind)),this.controller?.handleContentLoaded?.(Q)}handleItemPlayerError(Q){this.controller?.handleItemPlayerError?.(Q)}reportSectionError(Q){this.controller?.reportSectionError?.(Q)}updateItemSession(Q,Y){let J=this.getCanonicalItemId(Q);return this.controller?.updateItemSession?.(J,Y)??null}navigateToItem(Q){return this.controller?.navigateToItem?.(Q)??null}async persist(){await this.controller?.persist?.()}async hydrate(){await this.controller?.hydrate?.()}getRegistry(){return this.registry}async dispose(){if(this.activeInitToken+=1,this.unsubscribeController?.(),this.unsubscribeController=null,this.coordinator&&this.sectionId)await this.coordinator.disposeSectionController({sectionId:this.sectionId,attemptId:this.attemptId});if(this.registry.clear(),this.loadedRenderableKeys.clear(),this.controller=null,this.coordinator=null,this.adapter){let Q=this.adapter;this.adapter=null,await Q.dispose()}}}var W5=()=>{};import{ContextConsumer as U5,createContext as B5}from"@pie-players/pie-context";var d6=B5(Symbol.for("pie.sectionRuntimeEngineHostContext"));function i6(Q,Y){let J=!1,G=new U5(Q,{context:d6,subscribe:!0,onValue:(K)=>{J=!0,Y(K)}});G.connect();let X=(K)=>{if(K.context!==d6)return;G.requestValue()};Q.addEventListener("context-provider",X);let j=0,Z=200,q=globalThis.setInterval(()=>{if(J||j>=Z){globalThis.clearInterval(q);return}j+=1,G.requestValue()},50);return()=>{globalThis.clearInterval(q),Q.removeEventListener("context-provider",X),G.disconnect()}}var D5=(Q)=>{console.error("[pie-assessment-toolkit] onStageChange handler threw",Q)};function s6(Q,Y){if(Q.isSuppressed())return!1;Q.dispatchDomEvent(Y);let J=Q.getOnStageChange();if(J)try{J(Y)}catch(G){(Q.logHandlerError??D5)(G)}return!0}function g7(Q,Y){if(typeof Q==="function")return Q;if(Q===null)return null;return typeof Y==="function"?Y:null}function n6(Q={}){let Y=Q.frameDeadlineMs??100,J=!1,G=null,X=null,j=null,Z=null,q=null;function K(){if(J=!1,X!==null)Z?.(X),X=null;if(j!==null)q?.(j),j=null;Z=null,q=null}function B(_){if(!J)return;if(_==="frame")X=null;if(_==="timer")j=null;let A=G;G=null,K(),A?.()}function U(_){if(G=_,J)return;J=!0;let A=globalThis,M=g7(Q.requestFrame,A.requestAnimationFrame);Z=g7(Q.cancelFrame,A.cancelAnimationFrame);let O=g7(Q.setTimer,A.setTimeout);if(q=g7(Q.clearTimer,A.clearTimeout),M){let F=M(()=>B("frame"));if(!J)return;if(X=F,O){let $=O(()=>B("timer"),Y);if(J)j=$}return}let L=g7(Q.queueMicrotaskFn,A.queueMicrotask);if(L){L(()=>B("microtask"));return}if(O){let F=O(()=>B("timer"),0);if(J)j=F;return}B("microtask")}function H(){if(!J)return;G=null,K()}return{schedule:U,cancel:H,isPending:()=>J}}function r6(){return{lastSessionEventSignatureByItemId:new Map,lastMetadataSignatureByItemId:new Map}}function o6(Q){Q.lastSessionEventSignatureByItemId.clear(),Q.lastMetadataSignatureByItemId.clear()}function a6(Q){let{state:Y,itemId:J,payload:G}=Q;if(H5(G)){let Z=_5(G);if(Y.lastMetadataSignatureByItemId.get(J)===Z)return!1;Y.lastMetadataSignatureByItemId.set(J,Z)}let X=V5(G);if(Y.lastSessionEventSignatureByItemId.get(J)===X)return!1;return Y.lastSessionEventSignatureByItemId.set(J,X),!0}function V5(Q){let Y={...Q};delete Y.timestamp,delete Y.sourceRuntimeId;try{return JSON.stringify(Y)}catch{return String(Y.itemId||"")}}function H5(Q){return Q.intent==="metadata-only"}function _5(Q){try{return JSON.stringify({itemId:Q.itemId,canonicalItemId:Q.canonicalItemId,intent:Q.intent,complete:Q.complete??null,component:Q.component??null})}catch{return String(Q.itemId||"")}}var F5=(Q,Y)=>{if(customElements.get(Q))return;try{customElements.define(Q,Y)}catch(J){if(!(J instanceof DOMException&&J.name==="NotSupportedError"||J&&typeof J==="object"&&J.name==="NotSupportedError")||!customElements.get(Q))throw J}},L5=C8('<div class="pie-assessment-toolkit-error svelte-vpe4u2" role="alert" aria-live="assertive"><div class="pie-assessment-toolkit-error-title svelte-vpe4u2"> </div> <div class="pie-assessment-toolkit-error-message svelte-vpe4u2"> </div> <pre class="pie-assessment-toolkit-error-details svelte-vpe4u2"> </pre></div>'),$5=C8('<div class="pie-assessment-toolkit-anchor svelte-vpe4u2" aria-hidden="true"></div> <!>',1),w5={hash:"svelte-vpe4u2",code:`.pie-assessment-toolkit-anchor.svelte-vpe4u2 {display:none;}.pie-assessment-toolkit-error.svelte-vpe4u2 {margin:0.75rem;padding:0.75rem 1rem;border-radius:0.5rem;border:1px solid
224
- color-mix(in srgb, var(--pie-incorrect-icon, #dc2626) 40%, transparent);background:color-mix(in srgb, var(--pie-incorrect-icon, #dc2626) 12%, transparent);color:var(--pie-incorrect, #7f1d1d);font-size:0.9rem;}.pie-assessment-toolkit-error-title.svelte-vpe4u2 {font-weight:600;margin-bottom:0.25rem;}.pie-assessment-toolkit-error-message.svelte-vpe4u2 {margin-bottom:0.5rem;}.pie-assessment-toolkit-error-details.svelte-vpe4u2 {margin:0;white-space:pre-wrap;word-break:break-word;}`};function D0(Q,Y){Q0(Y,!0),j0(Q,w5);let J=w1("toolkit"),G=new E8,X=h(null),j=new v7,Z={mode:"gather",role:"student"},q={iife:"pie-item-player",esm:"pie-item-player",preloaded:"pie-item-player",custom:""},K=y(Y,"assessmentId",7,""),B=y(Y,"section",7,null),U=y(Y,"sectionId",7,""),H=y(Y,"attemptId",7,""),_=y(Y,"env",23,()=>({})),A=y(Y,"ndsIcons",7,!1),M=y(Y,"lazyInit",7,!0),O=y(Y,"toolConfigStrictness",7,"error"),L=y(Y,"tools",23,()=>({})),F=y(Y,"toolContextResolvers",7,null),$=y(Y,"enabledTools",7,""),b=y(Y,"toolRegistry",7,null),v=y(Y,"accessibility",23,()=>({})),k=y(Y,"player",7,null),p=y(Y,"playerType",7,""),w=y(Y,"coordinator",7,null),l=y(Y,"createSectionController",7,null),Z7=y(Y,"onFrameworkError",7,null),j7=y(Y,"errorRenderer",7,null),P7=y(Y,"onStageChange",7,null),q7=y(Y,"assessment",7,null),d7=y(Y,"currentItemRef",7,null),i7=y(Y,"pnpEnforcement",7,null),K7=y(Y,"isolation",7,"inherit"),C7=h(null),d=h(null),Y7=h(null),y8=null,y7=null,x7=null,s7=null,f7=null,n7=null,r7=h(0),S1=h(null),o7=h(null),n=h(null),T1=h("Unable to initialize assessment toolkit."),C1=h(b8([])),x8="",y1="",f8=h(""),k8=null,I8=n6(),W7=[],a7=new Map,x1=new WeakMap,v8=r6(),i=N5({sourceCe:"pie-assessment-toolkit",sourceCeShape:"toolkit",runtimeId:J,sectionId:u(()=>U()||void 0),attemptId:u(()=>H()||void 0),emit:(W)=>{s6({isSuppressed:()=>V(X)!==null,dispatchDomEvent:(D)=>U7("pie-stage-change",D),getOnStageChange:()=>P7()},W)}}),h8=h(b8(u(()=>`${U()}|${H()}`))),t7=h(!1),a=h(!1),f1=h(!1),k1=h(!1);function V0(){if(!V(C7))return null;let W=V(C7).getRootNode();if(W&&"host"in W)return W.host;return V(C7).parentElement}let x=s(()=>V0());function U7(W,D){if(!V(x)){W7=[...W7,{name:W,detail:D}];return}P8(V(x),W,D)}T(()=>{if(!V(x))return;if(W7.length===0)return;let W=W7;W7=[],queueMicrotask(()=>{let D=V(x);if(!D){W7=[...W,...W7];return}for(let N of W)P8(D,N.name,N.detail)})});function H0(W){if(!j7())return{title:"Unable to initialize assessment toolkit.",details:W.details.length>0?W.details:[W.message]};try{let D=j7()(W)||{};return{title:typeof D.title==="string"&&D.title.trim().length>0?D.title:"Unable to initialize assessment toolkit.",details:Array.isArray(D.details)&&D.details.length>0?D.details.map((N)=>String(N)):W.details.length>0?W.details:[W.message]}}catch(D){let N=D instanceof Error&&D.message.trim().length>0?D.message:String(D||"Unknown renderer error");return{title:"Unable to initialize assessment toolkit.",details:[...W.details,`Error renderer failed: ${N}`]}}}function e7(W){let D=G1({kind:W.kind,source:W.source,error:W.error,recoverable:W.recoverable});return j.reportFrameworkError(D),D}function _0(W){return W==="coordinator-init"||W==="runtime-init"||W==="tool-config"}function m8(W){if(!Z7())return;try{Z7()(W),x8=`${W.kind}|${W.source}|${W.message}`}catch(D){console.error(`[pie-framework:${W.kind}:${W.source}] framework error hook failed`,D)}}T(()=>{let W=j.subscribeFrameworkErrors((D)=>{if(console.error(o8(D),D.cause),_0(D.kind)){let N=H0(D);R(n,D,!0),R(T1,N.title,!0),R(C1,N.details,!0)}U7("framework-error",D),m8(D)});return()=>{W()}}),T(()=>{if(!V(n))return;let W=`${V(n).kind}|${V(n).source}|${V(n).message}`;if(x8===W)return;m8(V(n))});function F0(W){let D=5381;for(let N=0;N<W.length;N+=1)D=(D<<5)+D^W.charCodeAt(N);return(D>>>0).toString(36)}function B7(W){return W&&typeof W==="object"?W:{}}function A0(W){let D=B7(W.section),N=typeof D.identifier==="string"?D.identifier:"",P=typeof W.sectionId==="string"?W.sectionId:"";return N||P}function M0(W){return typeof W.currentItemIndex==="number"?W.currentItemIndex:-1}function N0(W){return(Array.isArray(W.renderables)?W.renderables:[]).map((N,P)=>{let z=B7(N),I=B7(z.entity),r=typeof I.id==="string"&&I.id||`renderable-${P}`,J1=B7(I.config),m1=typeof I.version==="string"&&I.version||(typeof I.version==="number"?String(I.version):"")||(typeof J1.version==="string"?J1.version:"");return{id:r,version:m1}})}function z0(W){let D=B7(W.itemSessionsByItemId);return Object.keys(D).sort((N,P)=>N.localeCompare(P)).map((N)=>{let P=B7(D[N]),z=typeof P.id==="string"?P.id:"",I=Array.isArray(P.data)?P.data:[],r="";try{r=F0(JSON.stringify(I))}catch{r=String(I.length)}return{itemId:N,sessionId:z,payloadSignature:r}})}function O0(W){let D=B7(W),N=N0(D).map((z)=>`${z.id}:${z.version}`).join("|"),P=z0(D).map((z)=>`${z.itemId}:${z.sessionId}:${z.payloadSignature}`).join("|");return{sectionId:A0(D),currentItemIndex:M0(D),renderableSignature:N,itemSessionSignature:P}}function P0(W){let D=O0(W);return`${D.sectionId}|${D.currentItemIndex}|${D.renderableSignature}|${D.itemSessionSignature}`}function u8(W){return W==="iife"||W==="esm"||W==="preloaded"||W==="custom"}function L0(W,D){let N=W?.type,P=u8(N)?N:u8(D)?D:W?.tagName?"custom":"iife",z=W?.tagName?.trim();if(P==="custom"&&!z)return{type:"iife",tagName:q.iife,version:void 0,source:void 0,isDefault:!0};return{type:P,tagName:z||q[P],version:W?.version,source:W?.source,loaderConfig:W?.loaderConfig,loaderOptions:W?.loaderOptions,isDefault:!W&&!D}}function p8(W){let D=W||{},N=typeof D.mode==="string"&&D.mode.trim()?D.mode.trim():Z.mode,P=typeof D.role==="string"&&D.role.trim()?D.role.trim():Z.role;return{mode:N,role:P}}function $0(W){let D=p8(W);if(D.mode==="author")return"author";if(D.role==="instructor")return"scorer";return"candidate"}async function w0(){if(l())return l()();throw Error("pie-assessment-toolkit requires createSectionController when no coordinator hook provides one")}function g8(){let W=L()||{},D=B0($());if(D.length===0)return W;let N=W.placement||{},P=Array.isArray(N.section)?N.section:null;if(P&&P.length>0)return W;return{...W,placement:{...N,section:D}}}function R0(){return G7(g8(),{strictness:O(),source:"pie-assessment-toolkit.bootstrap",toolRegistry:b()}).config}function E0(){let W="",D="";try{W=JSON.stringify(g8())}catch{W="[unserializable-tools]"}try{D=JSON.stringify(Object.entries(F()??{}).map(([N,P])=>[N,typeof P]))}catch{D="[unserializable-resolvers]"}return[K()||"",String(O()||"error"),W,D].join("|")}function c8(W){return W==="on"||W==="off"?W:null}function b0(W,D){let N=c8(W);if(N)return N;if(D&&typeof D==="object"){let z=D.pnpEnforcement;return c8(typeof z==="string"?z:null)}return null}function S0(W){let D=K()||B()?.identifier||`assessment-${Math.random().toString(16).slice(2)}`;return new P1({assessmentId:D,lazyInit:M(),toolConfigStrictness:O(),deferToolConfigValidation:!0,tools:W,toolRegistry:b(),toolContextResolvers:F(),accessibility:v(),frameworkErrorBus:j})}let f=s(()=>{if(K7()!=="force"&&V(Y7)?.coordinator)return V(Y7).coordinator;return w()||V(d)});T(()=>{V(x),w(),K7(),V(Y7),F(),u(()=>{if(!V(x))return;if(w()){if(V(d))R(d,null);y7=null;return}if(K7()!=="force"&&V(Y7)?.coordinator){if(V(d))R(d,null);y7=null;return}if(V(d)&&y7!==F()){try{V(d).setToolContextResolvers(F()),y7=F()}catch(W){R(o7,W,!0),e7({kind:"coordinator-init",phase:"coordinator-ready",error:W})}return}if(!V(d)){let W=E0();if(y1===W)return;try{let D=R0();R(d,S0(D),!0),y7=F(),y1="",R(n,null),R(T1,"Unable to initialize assessment toolkit."),R(C1,[],!0)}catch(D){R(o7,D,!0),R(d,null),y1=W,e7({kind:"coordinator-init",source:"pie-assessment-toolkit",error:D})}}})});let J7=s(()=>K()||V(f)?.assessmentId||""),t=s(()=>U()||B()?.identifier||`section-${V(J7)||"default"}`),I1=s(()=>p8(_())),T0=s(()=>$0(V(I1))),L7=s(()=>L0(k(),p())),k7=s(()=>z5({player:V(L7),component:"pie-assessment-toolkit"})),Q1=s(()=>{if(!V(f))return null;let W=V(f).getServiceBundle();return{toolkitCoordinator:V(f),toolCoordinator:V(f).toolCoordinator,ttsService:W.ttsService,highlightCoordinator:W.highlightCoordinator,catalogResolver:W.catalogResolver,elementToolStateStore:W.elementToolStateStore,assessmentId:V(J7),sectionId:V(t),itemPlayer:V(L7),ndsIcons:A()===!0,reportSessionChanged:(D,N)=>{let P=G.updateItemSession(D,N);i8({itemId:D,result:P,fallbackSession:N})}}}),Y1=s(()=>{if(!V(f))return null;return{runtimeId:J,coordinator:V(f)}});function C0(W){let D=P0(W);if(D===V(f8))return;R(f8,D,!0),R(r7,V(r7)+1),R(S1,W,!0),U7("composition-changed",{composition:V(S1),version:V(r7)})}function v1(W){k8=W??G.getCompositionModel(),I8.schedule(()=>{C0(k8)})}function h1(W){if(!W)return;let D=x1.get(W);if(!D)return;for(let N of D)N();x1.delete(W)}function l8(){for(let W of a7.values())h1(W.element)}function d8(W){if(h1(W.element),!V(f))return;let D=V(f).getServiceBundle().catalogResolver;x1.set(W.element,[D.registerOwner({owner:{kind:W.kind,itemId:W.itemId,canonicalItemId:W.canonicalItemId,assessmentId:V(J7),sectionId:V(t)},entity:W.item})])}function y0(){l8();for(let W of a7.values())d8(W)}function i8(W){let N={...W.result?.eventDetail||W.fallbackSession,itemId:W.itemId,canonicalItemId:W.canonicalItemId||W.itemId,sourceRuntimeId:J};if(!a6({state:v8,itemId:W.itemId,payload:N}))return;U7("session-changed",N)}function x0(W){if(!(W instanceof HTMLElement))return!1;return A5(W,T8)?.runtimeId===J}function I7(W){return W.detail??null}function f0(W,D){for(let N of D)W.addEventListener(N.name,N.handler);return()=>{for(let N of D)W.removeEventListener(N.name,N.handler)}}T(()=>{if(!V(x))return;if(K7()==="force"){R(Y7,null);return}return U0(V(x),(W)=>{if(W.runtimeId===J)return;R(Y7,W,!0)})}),T(()=>{let W=V(x);return u(()=>{if(!W){R(X,null);return}let D=i6(W,(N)=>{if(N.engine===V(X))return;R(X,N.engine,!0)});return()=>{D(),R(X,null)}})}),T(()=>{let W=K7()!=="force"&&V(Y7)?V(Y7).runtimeId:null,D=W?"inherited":"owned";if(D!==y8)y8=D,U7(D==="inherited"?"runtime-inherited":"runtime-owned",{runtimeId:J,parentRuntimeId:W})}),T(()=>{let W=V(t),D=H()||"";o6(v8)}),T(()=>{if(!V(x)||!V(Y1))return;return f7=new t6(V(x),{context:T8,initialValue:V(Y1)}),f7.connect(),n7=new e6(V(x)),n7.attach(),()=>{n7?.detach(),n7=null,f7?.disconnect(),f7=null}}),T(()=>{if(!V(Y1))return;f7?.setValue(V(Y1))}),T(()=>{if(!V(x))return;V(x).setAttribute("data-item-player-type",V(L7).type),V(x).setAttribute("data-item-player-tag",V(L7).tagName),V(x).setAttribute("data-env-mode",String(V(I1)?.mode||"")),V(x).setAttribute("data-env-role",String(V(I1)?.role||""))}),T(()=>{if(!V(x)||!V(Q1))return;return x7=new t6(V(x),{context:W0,initialValue:V(Q1)}),x7.connect(),s7=new e6(V(x)),s7.attach(),()=>{s7?.detach(),s7=null,x7?.disconnect(),x7=null}}),T(()=>{if(V(Q1))x7?.setValue(V(Q1))}),T(()=>{return V(f),V(J7),V(t),y0(),()=>{l8()}}),T(()=>{if(!V(x))return;return M5({host:V(x),instrumentationProvider:V(k7),component:"pie-assessment-toolkit",eventMap:O5,staticAttributes:{instrumentationLayer:"toolkit",assessmentId:V(J7),sectionId:V(t),attemptId:H()||void 0}})}),T(()=>{q7(),d7(),i7(),L();let W=V(f);if(!W)return;if(W!==V(d))return;u(()=>{W.setPnpEnforcement(b0(i7(),L())),W.updateAssessment(q7()),W.updateCurrentItemRef(d7())})}),T(()=>{if(!V(f))return;return V(f).subscribeTelemetry(({eventName:W,payload:D})=>{if(!P5(V(k7)))return;if(!V(k7).isReady())return;let N=W,P=new Date().toISOString(),z={...D||{},instrumentationLayer:"toolkit",assessmentId:V(J7),sectionId:V(t),attemptId:H()||void 0,component:"pie-assessment-toolkit",sourceEventName:W,timestamp:P};V(k7).trackEvent(N,z);let I=D&&typeof D.errorType==="string"?D.errorType:void 0;if(!W.endsWith("-error")&&!I)return;let r=D&&typeof D.message==="string"?D.message:`Toolkit telemetry error: ${W}`;V(k7).trackError(Error(r),{component:"pie-assessment-toolkit",errorType:I||"ToolkitTelemetryError",...z})})}),T(()=>{if(!B()||!V(f))return;let W=!1;return G.initialize({coordinator:V(f),section:B(),sectionId:V(t),assessmentId:V(J7),attemptId:H()||void 0,view:V(T0),createDefaultController:w0,onCompositionChanged:(D)=>{if(W)return;v1(D)}}).then(()=>{if(W)return;U7("toolkit-ready",{runtimeId:J,assessmentId:V(J7),sectionId:V(t),itemPlayer:V(L7),coordinator:V(f)}),U7("section-ready",{sectionId:V(t)}),u(()=>{R(k1,!0)})}).catch((D)=>{u(()=>{if(!V(a))R(a,!0),i.enter("engine-ready","skipped");i.enter("interactive","failed")}),R(o7,D,!0),G.reportSectionError({source:"section-runtime",error:D,timestamp:Date.now()}),e7({kind:"runtime-init",source:"pie-assessment-toolkit",error:D})}),()=>{W=!0}}),T(()=>{if(!V(x))return;let W=V(x),D=(P)=>x0(P.target);return f0(W,[{name:C6,handler:(P)=>{if(!D(P))return;let z=I7(P);if(!z?.element||!z?.itemId)return;let I=G.register(z);if(a7.set(z.element,z),d8(z),G.handleContentRegistered(z),I)v1()}},{name:y6,handler:(P)=>{if(!D(P))return;let z=I7(P);if(!z?.itemId)return;let I=z?.element?G.unregister(z.element):!1;if(h1(z.element),z.element)a7.delete(z.element);if(G.handleContentUnregistered(z),I)v1()}},{name:x6,handler:(P)=>{if(!D(P))return;let z=I7(P);if(!z?.itemId)return;let I=G.updateItemSession(z.itemId,z.session);i8({itemId:z.itemId,canonicalItemId:G.getCanonicalItemId(z.itemId),result:I,fallbackSession:z.session})}},{name:f6,handler:(P)=>{if(!D(P))return;let z=I7(P);if(!z?.itemId)return;G.handleContentLoaded({itemId:z.itemId,canonicalItemId:z.canonicalItemId,contentKind:z.contentKind,detail:z.detail,timestamp:Date.now()})}},{name:k6,handler:(P)=>{if(!D(P))return;let z=I7(P);if(!z?.itemId)return;G.handleItemPlayerError({itemId:z.itemId,canonicalItemId:z.canonicalItemId,contentKind:z.contentKind,error:z.error,timestamp:Date.now()})}}])});async function k0(){if(!V(f))throw Error("Coordinator not initialized");await V(f).waitUntilReady()}function I0(){if(!V(f))throw Error("Coordinator not initialized");return V(f).getServiceBundle()}function v0(W){if(!V(f))throw Error("Coordinator not initialized");V(f).setHooks(W)}function h0(W){return G.navigateToItem(W)}function m0(){return G.getCompositionModel()}function u0(){return V(L7)}async function p0(){await G.persist()}async function g0(){await G.hydrate()}T(()=>{return()=>{u(()=>{if(i.getCurrent()!==null)i.enter("disposed")})}}),T(()=>{let W=`${U()}|${H()}`;u(()=>{if(W===V(h8))return;if(i.getCurrent()!==null)i.enter("disposed");i.reset({sectionId:U()||void 0,attemptId:H()||void 0}),R(h8,W),R(t7,!1),R(a,!1),R(f1,!1),R(k1,!1)})}),T(()=>{let W=V(a)&&V(k1);u(()=>{if(!W)return;if(V(f1))return;R(f1,!0),i.enter("interactive")})}),T(()=>{let W=V(r7)>0||V(S1)!==null;u(()=>{if(!V(t7)&&W)R(t7,!0),i.enter("composed")})}),T(()=>{if(!V(f))return;if(!V(t7))return;if(V(a))return;let W=V(f),D=!1;return W.waitUntilReady().then(()=>{if(D)return;u(()=>{if(V(a))return;R(a,!0),i.enter("engine-ready")})}).catch(()=>{if(D)return;u(()=>{if(V(a))return;R(a,!0),i.enter("engine-ready","failed")})}),()=>{D=!0}}),T(()=>{return()=>{I8.cancel(),G.dispose().catch((W)=>{R(o7,W,!0),e7({kind:"runtime-dispose",source:"pie-assessment-toolkit",error:W,recoverable:!0})}).finally(()=>{j.dispose()})}});var c0={waitUntilReady:k0,getServiceBundle:I0,setHooks:v0,navigateToItem:h0,getCompositionModel:m0,getItemPlayerConfig:u0,persist:p0,hydrate:g0,get assessmentId(){return K()},set assessmentId(W){K(W),C()},get section(){return B()},set section(W){B(W),C()},get sectionId(){return U()},set sectionId(W){U(W),C()},get attemptId(){return H()},set attemptId(W){H(W),C()},get env(){return _()},set env(W){_(W),C()},get ndsIcons(){return A()},set ndsIcons(W){A(W),C()},get lazyInit(){return M()},set lazyInit(W){M(W),C()},get toolConfigStrictness(){return O()},set toolConfigStrictness(W){O(W),C()},get tools(){return L()},set tools(W){L(W),C()},get toolContextResolvers(){return F()},set toolContextResolvers(W){F(W),C()},get enabledTools(){return $()},set enabledTools(W){$(W),C()},get toolRegistry(){return b()},set toolRegistry(W){b(W),C()},get accessibility(){return v()},set accessibility(W){v(W),C()},get player(){return k()},set player(W){k(W),C()},get playerType(){return p()},set playerType(W){p(W),C()},get coordinator(){return w()},set coordinator(W){w(W),C()},get createSectionController(){return l()},set createSectionController(W){l(W),C()},get onFrameworkError(){return Z7()},set onFrameworkError(W){Z7(W),C()},get errorRenderer(){return j7()},set errorRenderer(W){j7(W),C()},get onStageChange(){return P7()},set onStageChange(W){P7(W),C()},get assessment(){return q7()},set assessment(W){q7(W),C()},get currentItemRef(){return d7()},set currentItemRef(W){d7(W),C()},get pnpEnforcement(){return i7()},set pnpEnforcement(W){i7(W),C()},get isolation(){return K7()},set isolation(W){K7(W),C()}},s8=$5(),n8=S8(s8);q0(n8,(W)=>R(C7,W),()=>V(C7));var l0=R1(n8,2);{var d0=(W)=>{var D=L5(),N=l7(D),P=l7(N,!0);c7(N);var z=R1(N,2),I=l7(z,!0);c7(z);var r=R1(z,2),J1=l7(r,!0);c7(r),c7(D),J0((m1)=>{b1(P,V(T1)),b1(I,V(n).message),b1(J1,m1)},[()=>V(C1).join(`
225
- `)]),E1(W,D)},i0=(W)=>{var D=G0(),N=S8(D);Z0(N,Y,"default",{},null),E1(W,D)};X0(l0,(W)=>{if(V(n)&&!V(n).recoverable)W(d0);else W(i0,-1)})}return E1(Q,s8),Y0(c0)}F5("pie-assessment-toolkit",K0(D0,{assessmentId:{attribute:"assessment-id",type:"String"},section:{attribute:"section",type:"Object"},sectionId:{attribute:"section-id",type:"String"},attemptId:{attribute:"attempt-id",type:"String"},env:{attribute:"env",type:"Object"},ndsIcons:{attribute:"nds-icons",type:"Boolean"},lazyInit:{attribute:"lazy-init",type:"Boolean"},toolConfigStrictness:{attribute:"tool-config-strictness",type:"String"},tools:{attribute:"tools",type:"Object"},toolContextResolvers:{type:"Object"},enabledTools:{attribute:"enabled-tools",type:"String"},toolRegistry:{type:"Object"},accessibility:{type:"Object"},player:{attribute:"player",type:"Object"},playerType:{attribute:"player-type",type:"String"},coordinator:{type:"Object"},createSectionController:{type:"Object"},onFrameworkError:{type:"Object"},errorRenderer:{type:"Object"},onStageChange:{type:"Object"},assessment:{type:"Object"},currentItemRef:{type:"Object"},pnpEnforcement:{attribute:"pnp-enforcement",type:"String"},isolation:{type:"Object"}},["default"],["waitUntilReady","getServiceBundle","setHooks","navigateToItem","getCompositionModel","getItemPlayerConfig","persist","hydrate"],{mode:"open"}));export{D0 as default};
223
+ `}return G}function O8(Q){let{request:Y,tools:J,pnpPolicy:G,customSources:X,contextId:j}=Q,Z=new M1(j);Z.addSource("host",{id:Y.scope.scopeId,name:`${Y.level}:${Y.scope.scopeId}`,config:{placement:J.placement,policy:J.policy}});let q=P7(J.placement[Y.level]),K=P7(J.policy.allowed),B=new Set(P7(J.policy.blocked)),U=[];for(let F of q)U.push(F),Z.addDecision({precedence:0,rule:"placement-membership",featureId:F,action:"skip",sourceType:"host",reason:`Listed in tools.placement.${Y.level}`});if(U=U.filter((F)=>{if(J.providers?.[F]?.enabled===!1)return Z.addDecision({precedence:0,rule:"provider-disabled",featureId:F,action:"block",sourceType:"host",reason:`tools.providers.${F}.enabled === false`,value:!1}),!1;return!0}),K.length>0){let F=new Set(K);U=U.filter(($)=>{if(!F.has($))return Z.addDecision({precedence:0,rule:"host-allowlist",featureId:$,action:"block",sourceType:"host",reason:"Not present in tools.policy.allowed",value:K}),!1;return!0})}U=U.filter((F)=>{if(B.has(F))return Z.addDecision({precedence:0,rule:"host-blocked",featureId:F,action:"block",sourceType:"host",reason:"Listed in tools.policy.blocked",value:J.policy.blocked}),!1;return!0});let H=[],_=new Map;for(let F of U)_.set(F,["placement"]);let A=new Set(U),M=null;if(G.enforcement==="on"&&G.source&&(G.assessment||G.currentItemRef)){if(M=G.source.apply({assessment:G.assessment,currentItemRef:G.currentItemRef}),M.sources.assessment)Z.addSource("assessment",M.sources.assessment);if(M.sources.student)Z.addSource("student",M.sources.student);if(M.sources.item)Z.addSource("item",M.sources.item);for(let F of M.decisions)Z.addDecision({precedence:F.precedence,rule:F.rule,featureId:F.featureId,action:F.action,sourceType:F.sourceType,reason:F.reason,value:F.value});U=U.filter((F)=>{return!M.blockedToolIds.has(F)});for(let F of Array.from(_.keys()))if(M.blockedToolIds.has(F))_.delete(F);for(let F of M.mandatedToolIds){if(!!A.has(F))continue;let v=M.perToolFlags.get(F)?.rule??"required-tool",k=o2(F,{placement:q,allowed:K,blocked:B,providers:J.providers}),p={rule:v,hostRule:k.hostRule,hostValue:k.hostValue};H.push({code:"tool-policy.requiredToolBlocked",level:Y.level,toolId:F,message:`Profile policy mandates "${F}" (${v}) but host policy removed it from level "${Y.level}" via ${k.hostRule}.`,details:p}),Z.addDecision({precedence:0,rule:"required-tool-blocked",featureId:F,action:"advisory",sourceType:"host",reason:`Host removed required tool "${F}" via ${k.hostRule}`,value:p})}for(let F of U){let $=M.perToolFlags.get(F);if($){let b=_.get(F)??[];b.push(`pnp.${$.rule}`),_.set(F,b)}}}for(let F=0;F<X.length;F++){let $=X[F],b=U.slice(),v=$.refine({request:Y,candidates:b}),k=new Set(v.refinedCandidates);for(let w of v.refinedCandidates)if(!b.includes(w))H.push({code:"tool-policy.placementMissing",level:Y.level,toolId:w,message:`Custom source "${$.id}" tried to add tool "${w}" that was not in candidates; ignored.`,source:`custom.${$.id}`}),k.delete(w);U=b.filter((w)=>k.has(w));let p=new Set;if(v.decisions){for(let w of v.decisions)if(Z.addDecision({precedence:w.precedence??100+F,rule:w.rule,featureId:w.featureId,action:w.action,sourceType:w.sourceType,reason:w.reason,value:w.value}),w.action==="block")p.add(w.featureId)}for(let w of b){if(k.has(w))continue;if(p.has(w))continue;Z.addDecision({precedence:100+F,rule:"custom-source",featureId:w,action:"block",sourceType:"custom",reason:`Custom policy source "${$.id}" removed tool "${w}" from candidates without emitting a decision; auto-logged for trail completeness.`,value:{customSourceId:$.id}})}for(let w of U){let l=_.get(w)??["placement"];l.push(`custom.${$.id}`),_.set(w,l)}for(let w of b)if(!k.has(w))_.delete(w)}let O=new Set(U),L=U.map((F)=>{let $=M?.perToolFlags.get(F);return{toolId:F,required:$?.required??!1,alwaysAvailable:$?.alwaysAvailable??!1,settings:$?.settings,sources:_.get(F)??["placement"]}});return Z.reconcileFinalStates(O),{visibleTools:L,diagnostics:H,provenance:Z.build()}}function o2(Q,Y){if(!Y.placement.includes(Q))return{hostRule:"placement-missing",hostValue:Y.placement};if(Y.providers?.[Q]?.enabled===!1)return{hostRule:"provider-disabled",hostValue:!1};if(Y.allowed.length>0&&!Y.allowed.includes(Q))return{hostRule:"host-allowlist",hostValue:Y.allowed};if(Y.blocked.has(Q))return{hostRule:"host-blocked",hostValue:Array.from(Y.blocked)};return{hostRule:"placement-missing",hostValue:Y.placement}}function S6(Q){if(!Q)return!1;let Y=Q.personalNeedsProfile;if(Y){if(Array.isArray(Y.supports)&&Y.supports.length>0)return!0;if(Array.isArray(Y.prohibitedSupports)&&Y.prohibitedSupports.length>0)return!0;if(Array.isArray(Y.activateAtInit)&&Y.activateAtInit.length>0)return!0}let J=Q.settings;if(J){let G=J.districtPolicy;if(G){if(Array.isArray(G.blockedTools)&&G.blockedTools.length>0)return!0;if(Array.isArray(G.requiredTools)&&G.requiredTools.length>0)return!0;if(G.policies&&typeof G.policies==="object"&&Object.keys(G.policies).length>0)return!0}let X=J.testAdministration;if(X&&typeof X==="object")for(let j of Object.keys(X)){let Z=X[j];if(Z===void 0||Z===null)continue;if(Array.isArray(Z)&&Z.length===0)continue;if(typeof Z==="object"&&!Array.isArray(Z)&&Object.keys(Z).length===0)continue;return!0}}return!1}function T6(Q){let Y=Q?.settings;if(!Y)return!1;if(Array.isArray(Y.requiredTools)&&Y.requiredTools.length>0)return!0;if(Array.isArray(Y.restrictedTools)&&Y.restrictedTools.length>0)return!0;if(Y.toolParameters&&typeof Y.toolParameters==="object"&&Object.keys(Y.toolParameters).length>0)return!0;return!1}function p7(Q){if(S6(Q.assessment))return"on";if(T6(Q.currentItemRef))return"on";return"off"}class N1{id="pnp";toolRegistry;constructor(Q){this.toolRegistry=Q}apply(Q){let{ctx:Y,result:J}=this.prepare(Q),{pnp:G,districtPolicy:X,itemSettings:j}=Y,Z=new Set;G?.supports?.forEach((q)=>Z.add(q)),G?.prohibitedSupports?.forEach((q)=>Z.add(q)),X?.blockedTools?.forEach((q)=>Z.add(q)),X?.requiredTools?.forEach((q)=>Z.add(q)),j?.requiredTools?.forEach((q)=>Z.add(q)),j?.restrictedTools?.forEach((q)=>Z.add(q));for(let q of Z)this.resolveSupport(q,Y,J);return J}resolveFeature(Q,Y){let{ctx:J,result:G}=this.prepare(Y);return this.resolveSupport(Q,J,G),G}prepare(Q){let{assessment:Y,currentItemRef:J}=Q,G=Y?.personalNeedsProfile,X=Y?.settings,j=J?.settings,Z={blockedToolIds:new Set,mandatedToolIds:new Set,perToolFlags:new Map,decisions:[],sources:{}};if(X?.districtPolicy||X?.testAdministration)Z.sources.assessment={id:Y?.id||"unknown",name:Y?.name||Y?.id||"Assessment",config:X};if(G)Z.sources.student={id:"student",name:"Student PNP Profile",config:G};if(J&&j)Z.sources.item={id:J.identifier,name:J.identifier,config:j};return{ctx:{pnp:G,districtPolicy:X?.districtPolicy,testAdmin:X?.testAdministration,itemSettings:j,toolConfigs:X?.toolConfigs},result:Z}}resolveSupport(Q,Y,J){if(Y.districtPolicy?.blockedTools?.includes(Q)){let X=this.mapSupportToToolId(Q);J.blockedToolIds.add(X),J.decisions.push({precedence:1,rule:"district-block",featureId:X,action:"block",sourceType:"assessment",reason:`District policy blocks "${Q}" for all assessments`,value:Y.districtPolicy.blockedTools});return}if(Y.testAdmin?.toolOverrides?.[Q]===!1){let X=this.mapSupportToToolId(Q);J.blockedToolIds.add(X),J.decisions.push({precedence:2,rule:"test-admin-override",featureId:X,action:"block",sourceType:"assessment",reason:`Test administrator disabled "${Q}" for this session`,value:Y.testAdmin.toolOverrides});return}if(Y.itemSettings?.restrictedTools?.includes(Q)){let X=this.mapSupportToToolId(Q);J.blockedToolIds.add(X),J.decisions.push({precedence:3,rule:"item-restriction",featureId:X,action:"block",sourceType:"item",reason:`Item restricts "${Q}" (e.g., mental math question blocks calculator)`,value:Y.itemSettings.restrictedTools});return}if(Y.itemSettings?.requiredTools?.includes(Q)){let X=this.mapSupportToToolId(Q);J.mandatedToolIds.add(X),J.perToolFlags.set(X,{required:!0,alwaysAvailable:!1,settings:this.resolveToolSettings(Q,Y),rule:"item-requirement",sourceType:"item"}),J.decisions.push({precedence:4,rule:"item-requirement",featureId:X,action:"enable",sourceType:"item",reason:`Item requires "${Q}" for this question`,value:Y.itemSettings.requiredTools});return}if(Y.districtPolicy?.requiredTools?.includes(Q)){let X=this.mapSupportToToolId(Q);J.mandatedToolIds.add(X),J.perToolFlags.set(X,{required:!0,alwaysAvailable:!1,settings:this.resolveToolSettings(Q,Y),rule:"district-requirement",sourceType:"assessment"}),J.decisions.push({precedence:5,rule:"district-requirement",featureId:X,action:"enable",sourceType:"assessment",reason:`District policy requires "${Q}" for all assessments`,value:Y.districtPolicy.requiredTools});return}if(Y.pnp?.prohibitedSupports?.includes(Q)){let X=this.mapSupportToToolId(Q);J.blockedToolIds.add(X),J.decisions.push({precedence:6,rule:"pnp-prohibited",featureId:X,action:"block",sourceType:"student",reason:`Student PNP profile prohibits "${Q}"`,value:Y.pnp.prohibitedSupports});return}if(Y.pnp?.supports?.includes(Q)){let X=this.mapSupportToToolId(Q);J.perToolFlags.set(X,{required:!1,alwaysAvailable:!0,settings:this.resolveToolSettings(Q,Y),rule:"pnp-support",sourceType:"student"}),J.decisions.push({precedence:6,rule:"pnp-support",featureId:X,action:"enable",sourceType:"student",reason:`Student PNP profile requests "${Q}"`,value:Y.pnp.supports});return}let G=this.mapSupportToToolId(Q);J.decisions.push({precedence:6,rule:"pnp-support",featureId:G,action:"skip",sourceType:"system",reason:`Feature "${Q}" not configured at any level`,value:{supportId:Q}})}mapSupportToToolId(Q){let Y=this.toolRegistry.getToolsByPNPSupport(Q);if(Y.size===0)return Q;return Array.from(Y)[0]}resolveToolSettings(Q,Y){return Y.itemSettings?.toolParameters?.[Q]??Y.toolConfigs?.[Q]}}var C6=w7({policy:{allowed:[],blocked:[]},placement:{section:[],item:[],passage:[]},providers:{}});class z1{toolRegistry;contextId;pnpPolicySource;customSources;listeners=new Set;tools;assessment;currentItemRef;pnpEnforcement;disposed=!1;constructor(Q){this.toolRegistry=Q.toolRegistry,this.contextId=Q.contextId??"tool-policy",this.pnpPolicySource=new N1(this.toolRegistry),this.customSources=Q.customSources?[...Q.customSources]:[];let Y=Q.inputs??{};this.tools=Y.tools??C6,this.assessment=Y.assessment??null,this.currentItemRef=Y.currentItemRef??null,this.pnpEnforcement=Y.pnpEnforcement??p7({assessment:this.assessment,currentItemRef:this.currentItemRef})}decide(Q){this.assertNotDisposed();let Y=Q.scope.scopeId?`${this.contextId}:${Q.level}:${Q.scope.scopeId}`:`${this.contextId}:${Q.level}`;return O8({request:Q,tools:this.tools,pnpPolicy:{source:this.pnpPolicySource,assessment:this.assessment??void 0,currentItemRef:this.currentItemRef??void 0,enforcement:this.pnpEnforcement},customSources:this.customSources,contextId:Y})}decideFeature(Q){this.assertNotDisposed();let Y=this.hostFeatureGate(Q);if(Y)return Y;return b6(Q,this.pnpPolicySource.resolveFeature(Q,{assessment:this.assessment??void 0,currentItemRef:this.currentItemRef??void 0}),{assessmentBound:this.assessment!==null})}hostFeatureGate(Q){let Y={assessmentBound:this.assessment!==null},J=P7(this.tools.policy.blocked);if(J.includes(Q))return z8(Q,"host-blocked",J,Y);let G=P7(this.tools.policy.allowed);if(G.length>0&&!G.includes(Q))return z8(Q,"host-allowlist",G,Y);return null}getVisibleToolIds(Q,Y){return this.decide({level:Q,scope:{level:Q,scopeId:Y}}).visibleTools.map((J)=>J.toolId)}updateInputs(Q){this.assertNotDisposed();let Y=!1,J=!1;if("tools"in Q){let G=Q.tools??C6;if(!Object.is(this.tools,G))this.tools=G,Y=!0}if("assessment"in Q){let G=Q.assessment??null;if(!Object.is(this.assessment,G))this.assessment=G,Y=!0}if("currentItemRef"in Q){let G=Q.currentItemRef??null;if(!Object.is(this.currentItemRef,G))this.currentItemRef=G,Y=!0}if("pnpEnforcement"in Q&&Q.pnpEnforcement){if(this.pnpEnforcement!==Q.pnpEnforcement)this.pnpEnforcement=Q.pnpEnforcement,J=!0}if(Y||J)this.emit({reason:J&&!Y?"pnp-enforcement":"inputs",inputs:this.snapshotInputs()})}registerPolicySource(Q){return this.assertNotDisposed(),this.customSources.push(Q),this.emit({reason:"policy-source-added",inputs:this.snapshotInputs()}),()=>{let Y=this.customSources.indexOf(Q);if(Y!==-1){if(this.customSources.splice(Y,1),!this.disposed)this.emit({reason:"policy-source-removed",inputs:this.snapshotInputs()})}}}onPolicyChange(Q){return this.listeners.add(Q),()=>{this.listeners.delete(Q)}}getInputs(){return this.snapshotInputs()}dispose(){if(this.disposed)return;this.disposed=!0,this.emit({reason:"disposed",inputs:this.snapshotInputs()}),this.listeners.clear(),this.customSources.length=0}snapshotInputs(){return Object.freeze({tools:this.tools,assessment:this.assessment,currentItemRef:this.currentItemRef,pnpEnforcement:this.pnpEnforcement})}emit(Q){for(let Y of Array.from(this.listeners))try{Y(Q)}catch{}}assertNotDisposed(){if(this.disposed)throw Error("ToolPolicyEngine has been disposed.")}}var a2=Symbol("@pie-players/tool-policy-engine");var O1=(Q)=>!!Q&&typeof Q==="object"&&!Array.isArray(Q),t2=(Q,Y,J)=>{let G={...Y,...J};if(Q==="textToSpeech"&&O1(Y.settings)&&O1(J.settings)){if(G.settings={...Y.settings,...J.settings},O1(Y.settings.mathSpeech)&&O1(J.settings.mathSpeech))G.settings.mathSpeech={...Y.settings.mathSpeech,...J.settings.mathSpeech}}return G},e2=["item-selected","item-session-data-changed","item-session-meta-changed","item-complete-changed","content-loaded","item-player-error"],Q5=["section-navigation-change","section-session-applied","section-loading-complete","section-items-complete-changed","section-error"];class P1{assessmentId;config;ttsService;toolCoordinator;highlightCoordinator;elementToolStateStore;catalogResolver;toolProviderRegistry;hooks;lazyInit;ttsInitialized=!1;ttsInitPromise;ttsReconfigurePromise;stateLoaded=!1;stateLoadPromise;coordinatorReadyPromise;coordinatorReadyNotified=!1;providerInitPromises=new Map;toolRegistry;toolContextResolvers=new Map;toolContextResolverChangeListeners=new Set;sectionControllers=new Map;sectionControllerKeys=new Map;sectionControllerInitPromises=new Map;sectionPersistenceStrategies=new Map;sectionControllerLifecycleListeners=new Set;activeSubscriptions=new Map;activeCohortMapKey=null;latestRequestedActiveCohortMapKey=null;telemetryListeners=new Set;frameworkErrorBus;ownsFrameworkErrorBus;policyEngine;pnpEnforcementOverride=null;boundAssessment=null;boundCurrentItemRef=null;reportedUnboundFeaturePolicy=!1;static resolveConfig(Q){let Y=u1(Q.toolConfigStrictness),J=Q.toolRegistry??new P8,G=Q.deferToolConfigValidation===!0?w7(Q.tools):G7(Q.tools,{strictness:Y,source:"ToolkitCoordinator.init",toolRegistry:J}).config;return{...Q,toolConfigStrictness:Y,toolRegistry:J,tools:{...G,providers:{...{textToSpeech:{enabled:!0,backend:"browser"},annotationToolbar:{enabled:!0}},...G.providers}},accessibility:{language:"en-US",...Q.accessibility??{},catalogs:Q.accessibility?.catalogs??[]}}}constructor(Q){if(!Q.assessmentId)throw Error("ToolkitCoordinator requires assessmentId in config");let Y=P1.resolveConfig(Q);if(this.assessmentId=Y.assessmentId,this.config=Y,this.toolRegistry=Y.toolRegistry??new P8,this.installToolContextResolvers(Y.toolContextResolvers),this.hooks=Y.hooks??{},this.lazyInit=Q.lazyInit===!0,this.pnpEnforcementOverride=this.resolveConfiguredPnpEnforcement(),this.frameworkErrorBus=Q.frameworkErrorBus??new h7,this.ownsFrameworkErrorBus=!Q.frameworkErrorBus,this.subscribeFrameworkErrorHookAdapters(),this.toolCoordinator=new t1,this.highlightCoordinator=new m7,this.elementToolStateStore=new o1,this.catalogResolver=new r1(Y.accessibility?.catalogs||[],Y.accessibility?.language||"en-US"),this.toolProviderRegistry=new A1,this._registerToolProviders(),this.ttsService=new u7,this.setupStatePersistenceHooks(),this.policyEngine=new z1({toolRegistry:this.toolRegistry,contextId:`toolkit-coordinator:${this.assessmentId}`,inputs:{tools:this.config.tools,assessment:null,currentItemRef:null,pnpEnforcement:this.resolveEffectivePnpEnforcement()}}),!this.lazyInit)this.waitUntilReady().catch((J)=>{console.error("[ToolkitCoordinator] Failed eager initialization:",J),this.handleError(J,{phase:"coordinator-ready"})})}subscribeFrameworkErrorHookAdapters(){this.frameworkErrorBus.subscribeFrameworkErrors((Q)=>{let Y=this.hooks.onFrameworkError;if(!Y)return;try{Y(Q)}catch(J){console.warn("[ToolkitCoordinator] onFrameworkError hook failed:",J)}})}async emitTelemetry(Q,Y){try{await this.hooks.onTelemetry?.(Q,Y)}catch(G){console.warn("[ToolkitCoordinator] telemetry hook failed:",G)}let J=Y?{...Y}:void 0;for(let G of this.telemetryListeners)try{G({eventName:Q,payload:J?{...J}:void 0})}catch(X){console.warn("[ToolkitCoordinator] telemetry listener failed:",X)}}emitSectionControllerLifecycle(Q){for(let Y of this.sectionControllerLifecycleListeners)try{Y(Q)}catch(J){console.warn("[ToolkitCoordinator] section controller lifecycle listener failed:",J)}}handleError(Q,Y){let J=o8({error:Q,context:Y});this.frameworkErrorBus.reportFrameworkError(J)}subscribeFrameworkErrors(Q){return this.frameworkErrorBus.subscribeFrameworkErrors(Q)}reportFrameworkError(Q){this.frameworkErrorBus.reportFrameworkError(Q)}getSectionControllerMapKey(Q){return`${Q.assessmentId}::${Q.sectionId}::${Q.attemptId||""}`}createDefaultSectionPersistence(){let Q=(()=>{try{if(typeof window>"u")return null;return window.localStorage}catch{return null}})(),Y=(J)=>{let{assessmentId:G,sectionId:X,attemptId:j}=J.key;return`pie:section-controller:v1:${G}:${X}:${j||"default"}`};return{async loadSession(J){if(!Q)return null;let G=Q.getItem(Y(J));if(!G)return null;try{return JSON.parse(G)}catch{return null}},async saveSession(J,G){if(!Q)return;Q.setItem(Y(J),JSON.stringify(G))},async clearSession(J){if(!Q)return;Q.removeItem(Y(J))}}}async resolveSectionPersistence(Q){let Y=this.getSectionControllerMapKey(Q.key),J=this.sectionPersistenceStrategies.get(Y);if(J)return J;let G={createDefaultPersistence:()=>this.createDefaultSectionPersistence()},X=await this.hooks.createSectionSessionPersistence?.(Q,G)??await G.createDefaultPersistence();return this.sectionPersistenceStrategies.set(Y,X),X}setupStatePersistenceHooks(){this.elementToolStateStore.setOnStateChange((Q)=>{if(!this.hooks.saveToolState)return;Promise.resolve(this.hooks.saveToolState(Q)).catch((Y)=>{this.handleError(Y,{phase:"state-save"})})})}async ensureStateLoaded(){if(this.stateLoaded)return;if(this.stateLoadPromise)return this.stateLoadPromise;return this.stateLoadPromise=(async()=>{let Q=this.hooks.loadToolState;if(!Q)return;try{let Y=await Q();if(Y&&typeof Y==="object")this.elementToolStateStore.loadState(Y);this.stateLoaded=!0,await this.emitTelemetry("pie-toolkit-tool-state-loaded",{hasState:Boolean(Y)})}catch(Y){this.handleError(Y,{phase:"state-load"})}})().finally(()=>{this.stateLoadPromise=void 0}),this.stateLoadPromise}_registerToolProviders(){let Q=this.getProviderDescriptorTools();for(let Y of Q)this.registerProviderFromTool(Y)}getProviderDescriptorTools(){return this.toolRegistry.getAllTools().filter((Q)=>!!Q.provider)}async registerProviderFromTool(Q){let Y=Q.provider;if(!Y)return;let J=this.getToolConfig(Q.toolId)||void 0;if(J?.enabled===!1)return;let G=Y.getProviderId?.(J)??J?.provider?.id??Q.toolId;if(this.toolProviderRegistry.has(G))return;let X=Y.createProvider(J),j=Y.getInitConfig?.(J)??J?.provider?.init??{},Z=this.addToolTelemetryReporter({toolId:Q.toolId,providerId:G,initConfig:j}),q=this.createToolTelemetryForwarder({toolId:Q.toolId,providerId:G}),K=Y.getAuthFetcher?.(J)??J?.provider?.runtime?.authFetcher;await this.registerProvider(G,{provider:X,config:Z,lazy:Y.lazy??!0,authFetcher:K,onTelemetry:q})}createToolTelemetryForwarder(Q){return async(Y,J)=>{await this.emitTelemetry(Y,{...J||{},toolId:Q.toolId,providerId:Q.providerId})}}addToolTelemetryReporter(Q){let Y=Q.initConfig&&typeof Q.initConfig==="object"?{...Q.initConfig}:{},J=typeof Y.onTelemetry==="function"?Y.onTelemetry:null,G=this.createToolTelemetryForwarder({toolId:Q.toolId,providerId:Q.providerId});return Y.onTelemetry=async(X,j)=>{if(J)await J(X,j);await G(X,j)},Y}async registerProvider(Q,Y){try{this.toolProviderRegistry.register(Q,Y);let J={providerId:Q,providerName:Y.provider.providerName};await this.hooks.onProviderRegistered?.(Q,J),await this.emitTelemetry("pie-toolkit-provider-registered",{providerId:Q,providerName:Y.provider.providerName})}catch(J){console.warn(`[ToolkitCoordinator] Failed to register provider "${Q}":`,J),this.handleError(J,{phase:"provider-register",providerId:Q})}}async ensureProviderReady(Q){let Y=this.providerInitPromises.get(Q);if(Y)return Y;let J=(async()=>{let G=await this.toolProviderRegistry.getProvider(Q,!1),X={providerId:Q,providerName:G.providerName};try{return await this.hooks.onProviderInitStart?.(Q,X),await this.toolProviderRegistry.initialize(Q),await this.hooks.onProviderReady?.(Q,X),await this.emitTelemetry("pie-toolkit-provider-ready",{providerId:Q}),G}catch(j){let Z=j instanceof Error?j:Error(String(j));throw this.handleError(Z,{phase:"provider-init",providerId:Q}),Z}})().finally(()=>{this.providerInitPromises.delete(Q)});return this.providerInitPromises.set(Q,J),J}setHooks(Q){if(Object.assign(this.hooks,Q),this.setupStatePersistenceHooks(),Q.onCoordinatorReady&&this.isReady())Promise.resolve(Q.onCoordinatorReady(this)).catch((Y)=>{this.handleError(Y,{phase:"coordinator-ready"})})}subscribeTelemetry(Q){return this.telemetryListeners.add(Q),()=>{this.telemetryListeners.delete(Q)}}getSectionController(Q){let Y={assessmentId:this.assessmentId,sectionId:Q.sectionId,attemptId:Q.attemptId};return this.sectionControllers.get(this.getSectionControllerMapKey(Y))}subscribeSectionEvents(Q){if(this.activeCohortMapKey===null)throw Error("[ToolkitCoordinator] subscribeSectionEvents requires an active section cohort; call getOrCreateSectionController first.");let Y=this.activeSubscriptions.get(Q.listener);if(Y)Y.unsubscribeCurrent?.(),Y.unsubscribeCurrent=null;let J={listener:Q.listener,eventTypes:Q.eventTypes,itemIds:Q.itemIds,unsubscribeCurrent:null};this.activeSubscriptions.set(Q.listener,J);let G=this.sectionControllers.get(this.activeCohortMapKey);if(G)this.bindSubscriptionToController(J,G);let X=!1;return()=>{if(X)return;if(X=!0,J.unsubscribeCurrent?.(),J.unsubscribeCurrent=null,this.activeSubscriptions.get(Q.listener)===J)this.activeSubscriptions.delete(Q.listener)}}bindSubscriptionToController(Q,Y){Q.unsubscribeCurrent?.(),Q.unsubscribeCurrent=null;let J=Y.subscribe;if(typeof J!=="function")return;let G=this.buildSectionEventPredicate(Q);Q.unsubscribeCurrent=J.call(Y,(Z)=>{if(!G(Z))return;this.deliverSectionEventSafely(Q.listener,Z)});let X=this.buildContentLoadedReplayEvents(Y);for(let Z of X)if(G(Z))this.deliverSectionEventSafely(Q.listener,Z);let j=this.buildLoadingCompleteReplayEvent(Y);if(j&&G(j))this.deliverSectionEventSafely(Q.listener,j)}deliverSectionEventSafely(Q,Y){try{Q(Y)}catch(J){console.warn("[ToolkitCoordinator] section-event listener failed:",J)}}setActiveCohort(Q){if(this.activeCohortMapKey===Q)return;this.activeCohortMapKey=Q;let Y=this.sectionControllers.get(Q);if(!Y)return;for(let J of Array.from(this.activeSubscriptions.values()))this.bindSubscriptionToController(J,Y)}setActiveCohortIfLatestRequest(Q){if(this.latestRequestedActiveCohortMapKey!==Q)return;this.setActiveCohort(Q)}suspendActiveCohortIfSuperseded(Q){if(this.activeCohortMapKey===null)return;if(this.activeCohortMapKey===Q)return;this.activeCohortMapKey=null;for(let Y of Array.from(this.activeSubscriptions.values()))Y.unsubscribeCurrent?.(),Y.unsubscribeCurrent=null}clearActiveCohortIfMatches(Q){if(this.activeCohortMapKey!==Q)return;this.activeCohortMapKey=null;for(let Y of Array.from(this.activeSubscriptions.values()))Y.unsubscribeCurrent?.(),Y.unsubscribeCurrent=null}buildSectionEventPredicate(Q){let Y=Q.eventTypes?new Set(Q.eventTypes):null,J=Q.itemIds?new Set(Q.itemIds):null;return(G)=>{if(Y||J){let X=G?.type||null;if(Y&&(!X||!Y.has(X)))return!1;if(J){if(!Array.from(this.collectEventItemIds(G)).some((Z)=>J.has(Z)))return!1}}return!0}}collectEventItemIds(Q){let Y=new Set;if("itemId"in Q&&typeof Q.itemId==="string")Y.add(Q.itemId);if("canonicalItemId"in Q&&typeof Q.canonicalItemId==="string")Y.add(Q.canonicalItemId);if("currentItemId"in Q&&typeof Q.currentItemId==="string")Y.add(Q.currentItemId);if("previousItemId"in Q&&typeof Q.previousItemId==="string")Y.add(Q.previousItemId);return Y}buildContentLoadedReplayEvents(Q){let Y=Q.getRuntimeState?.(),J=Y?.loadedRenderables;if(!Array.isArray(J)||J.length===0)return[];let G=typeof Y?.currentItemIndex==="number"&&Number.isFinite(Y.currentItemIndex)?Y.currentItemIndex:0,X=Date.now(),j=[];for(let Z of J){if(!Z)continue;let q=Z.itemId,K=typeof Z.canonicalItemId==="string"&&Z.canonicalItemId?Z.canonicalItemId:q;if(typeof q!=="string"||!q)continue;j.push({type:"content-loaded",contentKind:Z.contentKind??"unknown",itemId:q,canonicalItemId:K,currentItemIndex:G,timestamp:X})}return j}buildLoadingCompleteReplayEvent(Q){let Y=Q.getRuntimeState?.();if(Y?.loadingComplete!==!0)return null;let J=typeof Y.totalRegistered==="number"&&Number.isFinite(Y.totalRegistered)?Math.max(0,Y.totalRegistered):0,G=typeof Y.totalLoaded==="number"&&Number.isFinite(Y.totalLoaded)?Math.max(0,Y.totalLoaded):J;return{type:"section-loading-complete",totalRegistered:J,totalLoaded:G,currentItemIndex:Y.currentItemIndex,timestamp:Date.now()}}subscribeItemEvents(Q){return this.subscribeSectionEvents({eventTypes:Q.eventTypes||e2,itemIds:Q.itemIds,listener:Q.listener})}subscribeSectionLifecycleEvents(Q){return this.subscribeSectionEvents({eventTypes:Q.eventTypes||Q5,listener:Q.listener})}onSectionControllerLifecycle(Q){return this.sectionControllerLifecycleListeners.add(Q),()=>{this.sectionControllerLifecycleListeners.delete(Q)}}async getOrCreateSectionController(Q){let Y={assessmentId:this.assessmentId,sectionId:Q.sectionId,attemptId:Q.attemptId},J=this.getSectionControllerMapKey(Y);this.latestRequestedActiveCohortMapKey=J,this.suspendActiveCohortIfSuperseded(J);let G=await this.resolveExistingSectionController({mapKey:J,key:Y,input:Q.input,updateExisting:Q.updateExisting});if(G)return G;let X=this.sectionControllerInitPromises.get(J);if(X)return X;let j=this.initializeNewSectionController({args:Q,key:Y,mapKey:J}).catch((Z)=>{throw this.handleSectionControllerInitError(Z,Q),Z}).finally(()=>{this.sectionControllerInitPromises.delete(J)});return this.sectionControllerInitPromises.set(J,j),j}async resolveExistingSectionController(Q){let Y=this.sectionControllers.get(Q.mapKey);if(!Y)return;if(this.sectionControllerKeys.set(Q.mapKey,Q.key),Q.updateExisting!==!1)await Y.updateInput?.(Q.input);return this.setActiveCohortIfLatestRequest(Q.mapKey),Y}createSectionControllerContext(Q){return{key:Q.key,coordinator:this,input:Q.input}}async initializeNewSectionController(Q){let Y=this.createSectionControllerContext({key:Q.key,input:Q.args.input}),J=await this.resolveSectionPersistence(Y),G={createDefaultController:Q.args.createDefaultController},X=await this.hooks.createSectionController?.(Y,G)??await G.createDefaultController();return await X.configureSessionPersistence?.({strategy:J,context:Y}),await X.initialize?.(Q.args.input),await X.hydrate?.(),await this.finalizeSectionControllerReady({mapKey:Q.mapKey,key:Q.key,context:Y,controller:X}),X}async finalizeSectionControllerReady(Q){this.sectionControllers.set(Q.mapKey,Q.controller),this.sectionControllerKeys.set(Q.mapKey,Q.key),this.setActiveCohortIfLatestRequest(Q.mapKey),this.emitSectionControllerLifecycle({type:"ready",key:Q.key,controller:Q.controller}),await this.hooks.onSectionControllerReady?.(Q.context,Q.controller),await this.emitTelemetry("pie-toolkit-section-controller-ready",{assessmentId:Q.key.assessmentId,sectionId:Q.key.sectionId,attemptId:Q.key.attemptId})}handleSectionControllerInitError(Q,Y){this.handleError(Q,{phase:"section-controller-init",details:{sectionId:Y.sectionId,attemptId:Y.attemptId}})}async disposeSectionController(Q){let Y={assessmentId:this.assessmentId,sectionId:Q.sectionId,attemptId:Q.attemptId},J=this.getSectionControllerMapKey(Y),G=this.sectionControllers.get(J);if(!G)return;this.clearActiveCohortIfMatches(J);let X=this.createSectionControllerContext({key:Y,input:void 0});try{await this.runSectionControllerDisposePipeline({key:Y,context:X,controller:G,persistBeforeDispose:Q.persistBeforeDispose})}catch(j){this.handleError(j,{phase:"section-controller-dispose",details:{sectionId:Q.sectionId,attemptId:Q.attemptId}})}finally{await this.finalizeSectionControllerDispose({mapKey:J,key:Y,context:X,clearPersistence:Q.clearPersistence})}}async runSectionControllerDisposePipeline(Q){if(Q.persistBeforeDispose!==!1)await Q.controller.persist?.();await Q.controller.dispose?.(),await this.hooks.onSectionControllerDispose?.(Q.context,Q.controller),await this.emitTelemetry("pie-toolkit-section-controller-disposed",{assessmentId:Q.key.assessmentId,sectionId:Q.key.sectionId,attemptId:Q.key.attemptId})}async finalizeSectionControllerDispose(Q){if(this.sectionControllers.delete(Q.mapKey),this.sectionControllerKeys.delete(Q.mapKey),this.emitSectionControllerLifecycle({type:"disposed",key:Q.key}),Q.clearPersistence)await this.sectionPersistenceStrategies.get(Q.mapKey)?.clearSession?.(Q.context);this.sectionPersistenceStrategies.delete(Q.mapKey)}async ensureTTSReady(Q){if(await this.waitForPendingTTSReconfigure(),this.ttsInitialized)return;if(this.ttsInitPromise)return this.ttsInitPromise;return this.ttsInitPromise=this._initializeTTS(Q).finally(()=>{this.ttsInitPromise=void 0}),this.ttsInitPromise}async waitForPendingTTSReconfigure(){let Q=this.ttsReconfigurePromise;while(Q)await Q,Q=this.ttsReconfigurePromise}async _initializeTTS(Q){if(this.ttsInitialized)return;let Y=this.resolveTTSToolConfig(Q),J=R6(Y),G=N8(J),X=E6(J);if(await this.hooks.onBeforeTTSInit?.({phase:"tts-init",details:{backend:G}}),await this.emitTelemetry("pie-toolkit-tts-init-start",{backend:G}),await this.emitTelemetry("pie-tool-init-start",{toolId:"textToSpeech",operation:"tts-init",backend:G}),this.toolProviderRegistry.has("tts"))try{let q=await(await this.ensureProviderReady("tts")).createInstance();await this.initializeTTSService(q,X),await this.emitTelemetry("pie-toolkit-tts-init-success",{provider:"registry"}),await this.emitTelemetry("pie-tool-init-success",{toolId:"textToSpeech",operation:"tts-init",backend:G,provider:"registry"}),console.log("[ToolkitCoordinator] TTS initialized via ToolProviderRegistry");return}catch(Z){let q=Z instanceof Error?Z:Error(String(Z));await this.emitTelemetry("pie-tool-init-error",{toolId:"textToSpeech",providerId:"tts",operation:"tts-init",backend:G,errorType:"TTSRegistryInitError",message:q.message,recovered:!0}),await this.emitTelemetry("pie-tool-init-fallback",{toolId:"textToSpeech",providerId:"tts",operation:"tts-init",backend:G,fromProvider:"registry",toProvider:"browser",reason:q.message}),console.warn("[ToolkitCoordinator] Failed to initialize TTS via registry, falling back to browser provider:",q)}let j=new E7;try{await this.initializeTTSService(j,X),await this.emitTelemetry("pie-toolkit-tts-init-success",{provider:"browser-fallback"}),await this.emitTelemetry("pie-tool-init-success",{toolId:"textToSpeech",operation:"tts-init",backend:G,provider:"browser-fallback"})}catch(Z){let q=Z instanceof Error?Z:Error(String(Z));throw this.handleError(q,{phase:"tts-init"}),await this.emitTelemetry("pie-toolkit-tts-init-error",{message:q.message}),await this.emitTelemetry("pie-tool-init-error",{toolId:"textToSpeech",operation:"tts-init",backend:G,errorType:"TTSInitError",message:q.message}),q}}resolveTTSToolConfig(Q){return Q||this.getTTSConfigFromProviders()||{}}async initializeTTSService(Q,Y){let J={...Y.providerOptions||{},__pieTelemetry:async(X,j)=>{await this.emitTelemetry(X,{toolId:"textToSpeech",...j||{}})}},G={...Y,providerOptions:J};await this.ttsService.initialize(Q,G),await this.ensureBrowserVoicesReady(Q),this.ttsService.setCatalogResolver(this.catalogResolver),this.ttsInitialized=!0,await this.hooks.onTTSReady?.()}async ensureBrowserVoicesReady(Q,Y=1200){if(Q.providerId!=="browser")return;if(typeof window>"u")return;if(!("speechSynthesis"in window))return;let J=window.speechSynthesis;if(J.getVoices().length>0)return;await new Promise((j)=>{let Z=!1,q=typeof J.addEventListener==="function"&&typeof J.removeEventListener==="function",K=!q&&"onvoiceschanged"in J,B=K?J.onvoiceschanged:null,U=!1,H=()=>{if(Z)return;if(Z=!0,window.clearTimeout(A),q)J.removeEventListener("voiceschanged",_);else if(U&&J.onvoiceschanged===_)J.onvoiceschanged=B;j()},_=(M)=>{if(!q&&typeof B==="function"&&M)B.call(J,M);H()},A=window.setTimeout(H,Y);if(q)J.addEventListener("voiceschanged",_,{once:!0});else if(K)J.onvoiceschanged=_,U=!0});let X=J.getVoices();await this.emitTelemetry("pie-toolkit-tts-browser-voices-ready",{voiceCount:X.length,timedOut:X.length===0})}getServiceBundle(){return{ttsService:this.ttsService,toolCoordinator:this.toolCoordinator,highlightCoordinator:this.highlightCoordinator,elementToolStateStore:this.elementToolStateStore,catalogResolver:this.catalogResolver,toolProviderRegistry:this.toolProviderRegistry}}async getToolProvider(Q){return this.ensureProviderReady(Q)}async waitUntilReady(){if(this.isReady())return;if(this.coordinatorReadyPromise)return this.coordinatorReadyPromise;return this.coordinatorReadyPromise=(async()=>{await this.ensureStateLoaded();let Q=this.getTTSConfigFromProviders();if(Q?.enabled!==!1)await this.ensureTTSReady(Q);if(!this.coordinatorReadyNotified)this.coordinatorReadyNotified=!0,await this.hooks.onCoordinatorReady?.(this),await this.emitTelemetry("pie-toolkit-coordinator-ready",{assessmentId:this.assessmentId})})().finally(()=>{this.coordinatorReadyPromise=void 0}),this.coordinatorReadyPromise}isReady(){return this.getInitStatus().coordinator}getInitStatus(){let Q={};for(let J of this.toolProviderRegistry.getProviderIds())Q[J]=this.toolProviderRegistry.isInitialized(J);let Y=this.getTTSConfigFromProviders();return{tts:this.ttsInitialized,stateLoaded:this.stateLoaded||!this.hooks.loadToolState,coordinator:(this.stateLoaded||!this.hooks.loadToolState)&&(this.ttsInitialized||Y?.enabled===!1),providers:Q}}getTTSConfigFromProviders(){return(this.config.tools?.providers||{}).textToSpeech}assertCanonicalToolId(Q){if(typeof Q!=="string"||Q.trim().length===0)throw Error("Tool id must be a non-empty string.");if(Q==="tts")throw Error('Tool id "tts" is no longer supported. Use "textToSpeech".');if(this.toolRegistry.getAllToolIds().length===0)return;if(!this.toolRegistry.get(Q))throw Error(`Unknown tool id "${Q}".`)}installToolContextResolvers(Q){if(!Q)return;for(let[Y,J]of Object.entries(Q)){if(J==null)continue;if(this.assertCanonicalToolId(Y),typeof J!=="function")throw Error(`Invalid tool context resolver for "${Y}": expected a function.`);this.toolContextResolvers.set(Y,J)}}setToolContextResolvers(Q){this.toolContextResolvers.clear(),this.installToolContextResolvers(Q??void 0),this.notifyToolContextResolverChange()}notifyToolContextResolverChange(){for(let Q of this.toolContextResolverChangeListeners)try{Q()}catch(Y){console.warn("[ToolkitCoordinator] Tool context resolver listener threw:",Y)}}isToolEnabled(Q){return this.assertCanonicalToolId(Q),this.config.tools?.providers?.[Q]?.enabled!==!1}getToolConfig(Q){return this.assertCanonicalToolId(Q),this.config.tools?.providers?.[Q]||null}updateToolConfig(Q,Y){this.assertCanonicalToolId(Q);let J=this.getToolConfig(Q)||{};if(!this.config.tools)this.config.tools=G7(void 0,{strictness:this.config.toolConfigStrictness??"error",source:"ToolkitCoordinator.updateToolConfig",toolRegistry:this.toolRegistry}).config;if(!this.config.tools.providers)this.config.tools.providers={};let G={...this.config.tools.providers||{},[Q]:t2(Q,J,Y)},X=G7({...this.config.tools,providers:G},{strictness:this.config.toolConfigStrictness??"error",source:"ToolkitCoordinator.updateToolConfig",toolRegistry:this.toolRegistry});this.config.tools=X.config,this.policyEngine.updateInputs({tools:this.config.tools}),this.emitTelemetry("pie-toolkit-tool-config-updated",{toolId:Q}),this._applyToolConfigChange(Q,Y)}updateToolPlacement(Q,Y){this.updateToolsPlacement({[Q]:[...Y]})}updateToolsPlacement(Q){if(!this.config.tools)this.config.tools=G7(void 0,{strictness:this.config.toolConfigStrictness??"error",source:"ToolkitCoordinator.updateToolsPlacement",toolRegistry:this.toolRegistry}).config;let Y=this.config.tools?.placement??{section:[],item:[],passage:[]},J={section:[...Q.section??Y.section??[]],item:[...Q.item??Y.item??[]],passage:[...Q.passage??Y.passage??[]]},G=G7({...this.config.tools,placement:J},{strictness:this.config.toolConfigStrictness??"error",source:"ToolkitCoordinator.updateToolsPlacement",toolRegistry:this.toolRegistry});G.config.placement=J,this.config.tools=G.config,this.policyEngine.updateInputs({tools:this.config.tools})}decideToolPolicy(Q){return this.policyEngine.decide(Q)}decideFeaturePolicy(Q){let Y=this.policyEngine.decideFeature(Q);if(!Y.assessmentBound&&!this.reportedUnboundFeaturePolicy)this.reportedUnboundFeaturePolicy=!0,console.warn(`[ToolkitCoordinator] Feature policy was asked about "${Q}" with no assessment bound, so every capability will be declined for want of a profile to read. Call updateAssessment(...) with the assessment (its personalNeedsProfile, settings.districtPolicy and settings.testAdministration are what policy reads) before relying on any accommodation. Reported once per coordinator.`);return Y}onPolicyChange(Q){return this.policyEngine.onPolicyChange(Q)}onCatalogsChange(Q){return this.catalogResolver.onCatalogsChange(Q)}updateAssessment(Q){this.boundAssessment=Q,this.policyEngine.updateInputs({assessment:Q,pnpEnforcement:this.resolveEffectivePnpEnforcement()})}updateCurrentItemRef(Q){this.boundCurrentItemRef=Q,this.policyEngine.updateInputs({currentItemRef:Q,pnpEnforcement:this.resolveEffectivePnpEnforcement()})}setPnpEnforcement(Q){this.pnpEnforcementOverride=Q,this.policyEngine.updateInputs({pnpEnforcement:this.resolveEffectivePnpEnforcement()})}getPolicyInputs(){return this.policyEngine.getInputs()}registerPolicySource(Q){return this.policyEngine.registerPolicySource(Q)}registerToolContextResolver(Q,Y){if(this.assertCanonicalToolId(Q),typeof Y!=="function")throw Error(`Invalid tool context resolver for "${Q}": expected a function.`);return this.toolContextResolvers.set(Q,Y),this.notifyToolContextResolverChange(),()=>{if(this.toolContextResolvers.get(Q)!==Y)return;this.toolContextResolvers.delete(Q),this.notifyToolContextResolverChange()}}hasToolContextResolver(Q){return this.assertCanonicalToolId(Q),this.toolContextResolvers.has(Q)}resolveToolContext(Q){this.assertCanonicalToolId(Q.toolId);let Y=this.toolContextResolvers.get(Q.toolId);if(!Y)return null;let J;try{J=Y(Q)}catch(X){return console.error(`[ToolkitCoordinator] Tool context resolver for "${Q.toolId}" threw:`,X),{toolId:Q.toolId,visible:!1,params:{},reason:"Tool context resolver threw."}}if(!J)return{toolId:Q.toolId,visible:!0,params:{}};let G=J.params&&typeof J.params==="object"&&!Array.isArray(J.params)?J.params:{};return{toolId:Q.toolId,visible:J.visible!==!1,params:G,reason:typeof J.reason==="string"?J.reason:void 0}}onToolContextResolverChange(Q){return this.toolContextResolverChangeListeners.add(Q),()=>{this.toolContextResolverChangeListeners.delete(Q)}}resolveEffectivePnpEnforcement(){if(this.pnpEnforcementOverride!==null)return this.pnpEnforcementOverride;return p7({assessment:this.boundAssessment,currentItemRef:this.boundCurrentItemRef})}resolveConfiguredPnpEnforcement(){return this.config.tools?.pnpEnforcement??null}_applyToolConfigChange(Q,Y){switch(Q){case"textToSpeech":{let J=this._reconfigureTTSProvider();this.ttsReconfigurePromise=J,J.finally(()=>{if(this.ttsReconfigurePromise===J)this.ttsReconfigurePromise=void 0}),J.then(async()=>{let G=this.getTTSConfigFromProviders();if(!this.lazyInit&&G?.enabled!==!1)await this.ensureTTSReady(G)});break}case"answerEliminator":break}}async _reconfigureTTSProvider(){this.ttsInitialized=!1,this.ttsInitPromise=void 0;try{this.ttsService.stop()}catch{}if(this.toolProviderRegistry.has("tts"))await this.toolProviderRegistry.unregister("tts");let Q=this.getProviderDescriptorTools().find((Y)=>Y.toolId==="textToSpeech");if(!Q)return;await this.registerProviderFromTool(Q)}}var y6="pie-register",x6="pie-unregister",f6="pie-item-session-changed";var k6="pie-content-loaded",I6="pie-item-player-error";var Y5={bubbles:!0,composed:!0,cancelable:!1};function J5(Q,Y,J={}){return new CustomEvent(Q,{detail:Y,...Y5,...J})}function L8(Q,Y,J,G={}){return Q.dispatchEvent(J5(Y,J,G))}function C7(){return{phase:"idle",cohort:null,controllerResolved:!1,readinessSignals:{sectionReady:!1,interactionReady:!1,allLoadingComplete:!1,runtimeError:!1},effectiveRuntime:null,effectiveToolsConfig:null,loadingCompleteEmitted:!1,lastFrameworkError:null,itemCount:0,loadedCount:0}}function $8(Q,Y){if(Q===Y)return!0;if(!Q||!Y)return!1;return Q.sectionId===Y.sectionId&&Q.attemptId===Y.attemptId}function G5(Q){if(Q.runtimeError)return"error";if(Q.allLoadingComplete)return"ready";if(Q.interactionReady)return"interaction-ready";if(Q.sectionReady)return"loading";return"bootstrapping"}function v6(Q){let Y=Q.signals.sectionReady&&Q.signals.allLoadingComplete,J=Q.mode==="strict"?Y:Q.signals.interactionReady;return{phase:G5({...Q.signals,allLoadingComplete:Y,interactionReady:J}),interactionReady:J,allLoadingComplete:Y,reason:Q.reason}}function h6(Q){switch(Q){case"idle":return null;case"booting-section":return"composed";case"engine-ready":return"engine-ready";case"interactive":return"interactive";case"disposed":return"disposed"}}function L1(Q,Y,J,G="entered"){let X=h6(Y);if(!X)return;Q.push({kind:"stage-change",stage:X,status:G,cohort:J})}function m6(Q){let Y={...C7(),phase:"booting-section",cohort:Q.cohort,effectiveRuntime:Q.effectiveRuntime,effectiveToolsConfig:Q.effectiveToolsConfig,itemCount:Q.itemCount},J=[];return L1(J,"booting-section",Q.cohort),{state:Y,outputs:J}}function X5(Q,Y){if(Q.phase==="idle"||Q.phase==="disposed")return{state:Q,outputs:[]};let J=v6({mode:Y.mode,signals:Y.signals}),G=[],X=Q.phase,j=Q.loadingCompleteEmitted;if(X==="engine-ready"&&J.interactionReady)X="interactive",L1(G,X,Q.cohort);if(J.allLoadingComplete&&Q.cohort&&!j)j=!0,G.push({kind:"loading-complete",cohort:Q.cohort,itemCount:Y.itemCount,loadedCount:Y.loadedCount});return{state:{...Q,phase:X,readinessSignals:Y.signals,loadedCount:Y.loadedCount,itemCount:Y.itemCount,loadingCompleteEmitted:j},outputs:G}}function g7(Q,Y){switch(Y.kind){case"initialize":{if(Q.phase==="disposed")return{state:Q,outputs:[]};if(Q.phase!=="idle"){if($8(Q.cohort,Y.cohort))return g7(Q,{kind:"update-runtime",effectiveRuntime:Y.effectiveRuntime,effectiveToolsConfig:Y.effectiveToolsConfig});return g7(Q,{kind:"cohort-change",cohort:Y.cohort,effectiveRuntime:Y.effectiveRuntime,effectiveToolsConfig:Y.effectiveToolsConfig,itemCount:Y.itemCount})}return m6({state:Q,cohort:Y.cohort,effectiveRuntime:Y.effectiveRuntime,effectiveToolsConfig:Y.effectiveToolsConfig,itemCount:Y.itemCount})}case"update-runtime":{if(Q.phase==="idle"||Q.phase==="disposed")return{state:Q,outputs:[]};return{state:{...Q,effectiveRuntime:Y.effectiveRuntime,effectiveToolsConfig:Y.effectiveToolsConfig},outputs:[]}}case"cohort-change":{if(Q.phase==="disposed")return{state:Q,outputs:[]};if($8(Q.cohort,Y.cohort))return g7(Q,{kind:"update-runtime",effectiveRuntime:Y.effectiveRuntime,effectiveToolsConfig:Y.effectiveToolsConfig});let J=[];if(Q.phase!=="idle")J.push({kind:"stage-change",stage:"disposed",status:"entered",cohort:Q.cohort});let G=m6({state:Q,cohort:Y.cohort,effectiveRuntime:Y.effectiveRuntime,effectiveToolsConfig:Y.effectiveToolsConfig,itemCount:Y.itemCount});return{state:G.state,outputs:[...J,...G.outputs]}}case"section-controller-resolved":{if(Q.phase!=="booting-section")return{state:{...Q,controllerResolved:!0},outputs:[]};let J=[];return L1(J,"engine-ready",Q.cohort),{state:{...Q,phase:"engine-ready",controllerResolved:!0},outputs:J}}case"update-readiness-signals":return X5(Q,{signals:Y.signals,mode:Y.mode,loadedCount:Y.loadedCount,itemCount:Y.itemCount});case"framework-error":return{state:{...Q,lastFrameworkError:Y.error,readinessSignals:{...Q.readinessSignals,runtimeError:Y.error.recoverable===!0?Q.readinessSignals.runtimeError:!0}},outputs:[{kind:"framework-error",error:Y.error}]};case"dispose":{if(Q.phase==="disposed")return{state:Q,outputs:[]};let J=[];if(Q.phase!=="idle")L1(J,"disposed",Q.cohort);return{state:{...Q,phase:"disposed"},outputs:J}}default:{let J=Y;return{state:Q,outputs:[]}}}}class w8{state=C7();listeners=new Set;getState(){return this.state}dispatch(Q){let Y=g7(this.state,Q);if(this.state=Y.state,Y.outputs.length>0)this.fanOut(Y.outputs);return Y.outputs}subscribe(Q){this.listeners.add(Q);let Y=!0;return()=>{if(!Y)return;Y=!1,this.listeners.delete(Q)}}disposeListeners(){this.listeners.clear()}fanOut(Q){let Y=Array.from(this.listeners),J=Object.freeze(Q.slice());for(let G of Y)try{G(J)}catch(X){console.warn("[SectionEngineCore] listener failed:",X)}}}function u6(Q){let{coordinator:Y,dispatchCoreInput:J}=Q,G=0,X=null,j=null,Z=!1,q=Y.subscribeFrameworkErrors((H)=>{try{J({kind:"framework-error",error:H})}catch(_){console.warn("[CoordinatorBridge] framework-error dispatch failed:",_)}});function K(){if(!j)return;try{j()}catch(H){console.warn("[CoordinatorBridge] controller unsubscribe failed:",H)}j=null}async function B(H){if(Z)return;G+=1;let _=G;X=H.cohort;let A=await Y.getOrCreateSectionController({sectionId:H.cohort.sectionId,attemptId:H.cohort.attemptId||void 0,input:{section:H.section,sectionId:H.cohort.sectionId,assessmentId:H.assessmentId,view:H.view},updateExisting:!0,createDefaultController:H.createDefaultController});if(_!==G||Z)return;K(),H.onControllerResolved?.(A);let M=A.getCompositionModel;if(H.onCompositionChanged?.(M?.()),typeof A.subscribe==="function")j=A.subscribe((O)=>{if(_!==G||Z)return;H.onCompositionChanged?.(M?.())});J({kind:"section-controller-resolved"})}async function U(){if(Z)return;Z=!0,G+=1,K();try{q()}catch(_){console.warn("[CoordinatorBridge] framework-error unsubscribe failed:",_)}let H=X;if(X=null,H)try{await Y.disposeSectionController({sectionId:H.sectionId,attemptId:H.attemptId||void 0})}catch(_){console.warn("[CoordinatorBridge] section-controller dispose failed:",_)}}return{resolveSectionController:B,dispose:U}}function p6(Q){let{runtimeId:Y,sourceCe:J}=Q,G=Q.host,X=Q.now??(()=>new Date().toISOString());function j(U){let H={stage:U.stage,status:U.status,runtimeId:Y,sectionId:U.cohort?.sectionId,attemptId:U.cohort?.attemptId?U.cohort.attemptId:void 0,timestamp:X(),sourceCe:J};G.dispatchEvent(new CustomEvent("pie-stage-change",{detail:H}))}function Z(U){let H={runtimeId:Y,sectionId:U.cohort.sectionId,attemptId:U.cohort.attemptId?U.cohort.attemptId:void 0,itemCount:U.itemCount,loadedCount:U.loadedCount,timestamp:X(),sourceCe:J};G.dispatchEvent(new CustomEvent("pie-loading-complete",{detail:H}))}function q(U){G.dispatchEvent(new CustomEvent("framework-error",{detail:U.error}))}function K(U){switch(U.kind){case"stage-change":j(U);return;case"loading-complete":Z(U);return;case"framework-error":q(U);return;default:{let H=U;return}}}function B(U){G=U}return{dispatch:K,setHost:B}}function g6(Q){let{bus:Y}=Q;function J(G){switch(G.kind){case"framework-error":Y.reportFrameworkError(G.error);return;case"stage-change":case"loading-complete":return;default:{let X=G;return}}}return{dispatch:J}}function c6(Q={}){let Y=Q.hook;function J(X){if(!Y)return;try{Y(X)}catch(j){console.warn("[InstrumentationBridge] hook failed:",j)}}function G(X){Y=X}return{dispatch:J,setHook:G}}function l6(){let Q=new Set;function Y(j){if(j.length===0)return;let Z=Array.from(Q),q=Object.freeze(j.slice());for(let K of Z)try{K(q)}catch(B){console.warn("[SubscriberFanout] listener failed:",B)}}function J(j){Q.add(j);let Z=!0;return()=>{if(!Z)return;Z=!1,Q.delete(j)}}function G(){Q.clear()}function X(){return Q.size}return{emit:Y,subscribe:J,dispose:G,getListenerCount:X}}class R8{core;domEventBridge;frameworkErrorBridge;instrumentationBridge;subscriberFanout;coordinatorBridge;unsubscribeCore;disposed=!1;constructor(Q){this.core=Q.core??new w8,this.domEventBridge=p6({host:Q.host,runtimeId:Q.runtimeId,sourceCe:Q.sourceCe,now:Q.now}),this.frameworkErrorBridge=g6({bus:Q.frameworkErrorBus}),this.instrumentationBridge=c6({hook:Q.instrumentationHook}),this.subscriberFanout=l6(),this.coordinatorBridge=Q.coordinator?u6({coordinator:Q.coordinator,dispatchCoreInput:(Y)=>this.dispatchInput(Y)}):null,this.unsubscribeCore=this.core.subscribe((Y)=>{this.routeOutputs(Y)})}getState(){return this.core.getState()}dispatchInput(Q){if(this.disposed)return[];return this.core.dispatch(Q)}subscribe(Q){return this.subscriberFanout.subscribe(Q)}setHost(Q){this.domEventBridge.setHost(Q)}setInstrumentationHook(Q){this.instrumentationBridge.setHook(Q)}resolveSectionController(Q){if(!this.coordinatorBridge)throw Error("[SectionEngineAdapter] resolveSectionController called without a coordinator.");return this.coordinatorBridge.resolveSectionController(Q)}async dispose(){if(this.disposed)return;if(this.disposed=!0,this.core.dispatch({kind:"dispose"}),this.unsubscribeCore(),this.subscriberFanout.dispose(),this.coordinatorBridge)await this.coordinatorBridge.dispose()}routeOutputs(Q){for(let Y of Q)this.routeOne(Y);this.subscriberFanout.emit(Q)}routeOne(Q){switch(Q.kind){case"stage-change":case"loading-complete":this.domEventBridge.dispatch(Q);break;case"framework-error":this.domEventBridge.dispatch(Q),this.frameworkErrorBridge.dispatch(Q);break;default:{let Y=Q;return}}this.instrumentationBridge.dispatch(Q)}}var Z5={mode:"gather",role:"student"};function $1(Q,Y){return Q!==void 0?Q:Y}function j5(Q){let Y=Q.runtime??{};if(Y.onFrameworkError!==void 0)return Y.onFrameworkError;return Q.onFrameworkError}function q5(Q){let Y=Q.runtime?.tools||{},J=Y.placement||{};return{...Y,placement:{...J}}}function K5(Q){let Y=Q.runtime||{},J=Y.player?{...Y.player}:null;return{...Y,assessmentId:$1(Y.assessmentId,Q.assessmentId),playerType:Y.playerType??"iife",player:J,lazyInit:Y.lazyInit??!0,accessibility:Y.accessibility??null,coordinator:Y.coordinator??null,createSectionController:Y.createSectionController,isolation:Y.isolation??"inherit",env:Y.env??Z5,toolConfigStrictness:$1(Y.toolConfigStrictness,Q.toolConfigStrictness)??"error",onFrameworkError:j5({runtime:Q.runtime,onFrameworkError:Q.onFrameworkError}),onStageChange:$1(Y.onStageChange,Q.onStageChange),onLoadingComplete:$1(Y.onLoadingComplete,Q.onLoadingComplete),tools:Q.effectiveToolsConfig}}function d6(Q,Y){let J=Q.assessmentId??"section-demo-direct",G=q5({runtime:Q.runtime}),X=K5({assessmentId:J,runtime:Q.runtime,effectiveToolsConfig:G,toolConfigStrictness:Q.toolConfigStrictness,onFrameworkError:Q.onFrameworkError,onStageChange:Q.onStageChange,onLoadingComplete:Q.onLoadingComplete}),j=Y.resolvePlayerRuntime({effectiveRuntime:X,playerType:String(X.playerType??"iife"),env:X.env??null});return{effectiveToolsConfig:G,effectiveRuntime:X,playerRuntime:j}}function W5(Q,Y){if(Q===Y)return 0;let J=Q.compareDocumentPosition(Y);if(J&Node.DOCUMENT_POSITION_PRECEDING)return 1;if(J&Node.DOCUMENT_POSITION_FOLLOWING)return-1;return 0}class E8{shellsByElement=new Map;register(Q){let Y=this.shellsByElement.get(Q.element),J={...Q,sortKey:Date.now()};if(Y&&Y.kind===J.kind&&Y.itemId===J.itemId&&Y.canonicalItemId===J.canonicalItemId)return!1;return this.shellsByElement.set(Q.element,J),!0}unregister(Q){return this.shellsByElement.delete(Q)}getOrderedShells(Q){let Y=Array.from(this.shellsByElement.values()).filter((J)=>!Q||J.kind===Q);return Y.sort((J,G)=>W5(J.element,G.element)),Y}getCanonicalIdMap(){let Q={};for(let Y of this.getOrderedShells("item")){if(!Y.itemId)continue;Q[Y.itemId]=Y.canonicalItemId||Y.itemId}return Q}clear(){this.shellsByElement.clear()}}function w1(Q="runtime"){return`${Q}-${Math.random().toString(16).slice(2)}-${Date.now()}`}class b8{registry=new E8;runtimeId=w1("section-engine");adapter=null;controller=null;coordinator=null;sectionId="";attemptId;unsubscribeController=null;activeInitToken=0;loadedRenderableKeys=new Set;attachHost(Q){if(this.adapter){if(this.adapter.setHost(Q.host),Q.instrumentationHook!==void 0)this.adapter.setInstrumentationHook(Q.instrumentationHook);return}this.adapter=new R8({host:Q.host,runtimeId:this.runtimeId,sourceCe:Q.sourceCe,frameworkErrorBus:Q.frameworkErrorBus,coordinator:Q.coordinator,instrumentationHook:Q.instrumentationHook,now:Q.now})}dispatchInput(Q){return this.adapter?.dispatchInput(Q)??[]}subscribe(Q){return this.adapter?.subscribe(Q)??U5}getState(){return this.adapter?.getState()??C7()}getEffectiveRuntime(Q,Y){return d6(Q,Y).effectiveRuntime}setInstrumentationHook(Q){this.adapter?.setInstrumentationHook(Q)}getRuntimeId(){return this.runtimeId}async initialize(Q){this.activeInitToken+=1;let Y=this.activeInitToken;this.coordinator=Q.coordinator,this.sectionId=Q.sectionId,this.attemptId=Q.attemptId;let J=await Q.coordinator.getOrCreateSectionController({sectionId:Q.sectionId,attemptId:Q.attemptId,input:{section:Q.section,sectionId:Q.sectionId,assessmentId:Q.assessmentId,view:Q.view},updateExisting:!0,createDefaultController:Q.createDefaultController});if(Y!==this.activeInitToken)return;this.unsubscribeController?.(),this.controller=J,this.replayRegisteredShellsIntoController(J),Q.onCompositionChanged?.(J.getCompositionModel?.()),this.unsubscribeController=J.subscribe?.(()=>{Q.onCompositionChanged?.(J.getCompositionModel?.())})||null}replayRegisteredShellsIntoController(Q){if(!Q.handleContentRegistered)return;let Y=this.registry.getOrderedShells();if(Y.length===0)return;for(let G of Y){let X=G.canonicalItemId||G.itemId;Q.handleContentRegistered({itemId:G.itemId,canonicalItemId:X,contentKind:G.contentKind||G.kind})}let J=Date.now();for(let G of Y){let X=G.canonicalItemId||G.itemId,j=this.getLoadedKey(X,G.contentKind);if(this.loadedRenderableKeys.has(j))Q.handleContentLoaded?.({itemId:G.itemId,canonicalItemId:X,contentKind:G.contentKind||G.kind,timestamp:J})}}getLoadedKey(Q,Y){return`${Y??""}:${Q}`}register(Q){return this.registry.register(Q)}unregister(Q){return this.registry.unregister(Q)}getCompositionModel(){return this.controller?.getCompositionModel?.()??null}getCanonicalItemId(Q){return this.registry.getCanonicalIdMap()[Q]||this.controller?.getCanonicalItemId?.(Q)||Q}handleContentRegistered(Q){this.controller?.handleContentRegistered?.({itemId:Q.itemId,canonicalItemId:Q.canonicalItemId||Q.itemId,contentKind:Q.contentKind||Q.kind})}handleContentUnregistered(Q){let Y=Q.canonicalItemId||Q.itemId;this.loadedRenderableKeys.delete(this.getLoadedKey(Y,Q.contentKind)),this.controller?.handleContentUnregistered?.({itemId:Q.itemId,canonicalItemId:Y,contentKind:Q.contentKind||Q.kind})}handleContentLoaded(Q){let Y=Q.canonicalItemId||Q.itemId;this.loadedRenderableKeys.add(this.getLoadedKey(Y,Q.contentKind)),this.controller?.handleContentLoaded?.(Q)}handleItemPlayerError(Q){this.controller?.handleItemPlayerError?.(Q)}reportSectionError(Q){this.controller?.reportSectionError?.(Q)}updateItemSession(Q,Y){let J=this.getCanonicalItemId(Q);return this.controller?.updateItemSession?.(J,Y)??null}navigateToItem(Q){return this.controller?.navigateToItem?.(Q)??null}async persist(){await this.controller?.persist?.()}async hydrate(){await this.controller?.hydrate?.()}getRegistry(){return this.registry}async dispose(){if(this.activeInitToken+=1,this.unsubscribeController?.(),this.unsubscribeController=null,this.coordinator&&this.sectionId)await this.coordinator.disposeSectionController({sectionId:this.sectionId,attemptId:this.attemptId});if(this.registry.clear(),this.loadedRenderableKeys.clear(),this.controller=null,this.coordinator=null,this.adapter){let Q=this.adapter;this.adapter=null,await Q.dispose()}}}var U5=()=>{};import{ContextConsumer as B5,createContext as D5}from"@pie-players/pie-context";var i6=D5(Symbol.for("pie.sectionRuntimeEngineHostContext"));function s6(Q,Y){let J=!1,G=new B5(Q,{context:i6,subscribe:!0,onValue:(K)=>{J=!0,Y(K)}});G.connect();let X=(K)=>{if(K.context!==i6)return;G.requestValue()};Q.addEventListener("context-provider",X);let j=0,Z=200,q=globalThis.setInterval(()=>{if(J||j>=Z){globalThis.clearInterval(q);return}j+=1,G.requestValue()},50);return()=>{globalThis.clearInterval(q),Q.removeEventListener("context-provider",X),G.disconnect()}}var V5=(Q)=>{console.error("[pie-assessment-toolkit] onStageChange handler threw",Q)};function n6(Q,Y){if(Q.isSuppressed())return!1;Q.dispatchDomEvent(Y);let J=Q.getOnStageChange();if(J)try{J(Y)}catch(G){(Q.logHandlerError??V5)(G)}return!0}function c7(Q,Y){if(typeof Q==="function")return Q;if(Q===null)return null;return typeof Y==="function"?Y:null}function r6(Q={}){let Y=Q.frameDeadlineMs??100,J=!1,G=null,X=null,j=null,Z=null,q=null;function K(){if(J=!1,X!==null)Z?.(X),X=null;if(j!==null)q?.(j),j=null;Z=null,q=null}function B(_){if(!J)return;if(_==="frame")X=null;if(_==="timer")j=null;let A=G;G=null,K(),A?.()}function U(_){if(G=_,J)return;J=!0;let A=globalThis,M=c7(Q.requestFrame,A.requestAnimationFrame);Z=c7(Q.cancelFrame,A.cancelAnimationFrame);let O=c7(Q.setTimer,A.setTimeout);if(q=c7(Q.clearTimer,A.clearTimeout),M){let F=M(()=>B("frame"));if(!J)return;if(X=F,O){let $=O(()=>B("timer"),Y);if(J)j=$}return}let L=c7(Q.queueMicrotaskFn,A.queueMicrotask);if(L){L(()=>B("microtask"));return}if(O){let F=O(()=>B("timer"),0);if(J)j=F;return}B("microtask")}function H(){if(!J)return;G=null,K()}return{schedule:U,cancel:H,isPending:()=>J}}function o6(){return{lastSessionEventSignatureByItemId:new Map,lastMetadataSignatureByItemId:new Map}}function a6(Q){Q.lastSessionEventSignatureByItemId.clear(),Q.lastMetadataSignatureByItemId.clear()}function t6(Q){let{state:Y,itemId:J,payload:G}=Q;if(_5(G)){let Z=F5(G);if(Y.lastMetadataSignatureByItemId.get(J)===Z)return!1;Y.lastMetadataSignatureByItemId.set(J,Z)}let X=H5(G);if(Y.lastSessionEventSignatureByItemId.get(J)===X)return!1;return Y.lastSessionEventSignatureByItemId.set(J,X),!0}function H5(Q){let Y={...Q};delete Y.timestamp,delete Y.sourceRuntimeId;try{return JSON.stringify(Y)}catch{return String(Y.itemId||"")}}function _5(Q){return Q.intent==="metadata-only"}function F5(Q){try{return JSON.stringify({itemId:Q.itemId,canonicalItemId:Q.canonicalItemId,intent:Q.intent,complete:Q.complete??null,component:Q.component??null})}catch{return String(Q.itemId||"")}}var A5=(Q,Y)=>{if(customElements.get(Q))return;try{customElements.define(Q,Y)}catch(J){if(!(J instanceof DOMException&&J.name==="NotSupportedError"||J&&typeof J==="object"&&J.name==="NotSupportedError")||!customElements.get(Q))throw J}},$5=y8('<div class="pie-assessment-toolkit-error svelte-vpe4u2" role="alert" aria-live="assertive"><div class="pie-assessment-toolkit-error-title svelte-vpe4u2"> </div> <div class="pie-assessment-toolkit-error-message svelte-vpe4u2"> </div> <pre class="pie-assessment-toolkit-error-details svelte-vpe4u2"> </pre></div>'),w5=y8('<div class="pie-assessment-toolkit-anchor svelte-vpe4u2" aria-hidden="true"></div> <!>',1),R5={hash:"svelte-vpe4u2",code:`.pie-assessment-toolkit-anchor.svelte-vpe4u2 {display:none;}.pie-assessment-toolkit-error.svelte-vpe4u2 {margin:0.75rem;padding:0.75rem 1rem;border-radius:0.5rem;border:1px solid
224
+ color-mix(in srgb, var(--pie-incorrect-icon, #dc2626) 40%, transparent);background:color-mix(in srgb, var(--pie-incorrect-icon, #dc2626) 12%, transparent);color:var(--pie-incorrect, #7f1d1d);font-size:0.9rem;}.pie-assessment-toolkit-error-title.svelte-vpe4u2 {font-weight:600;margin-bottom:0.25rem;}.pie-assessment-toolkit-error-message.svelte-vpe4u2 {margin-bottom:0.5rem;}.pie-assessment-toolkit-error-details.svelte-vpe4u2 {margin:0;white-space:pre-wrap;word-break:break-word;}`};function V0(Q,Y){Y0(Y,!0),q0(Q,R5);let J=w1("toolkit"),G=new b8,X=h(null),j=new h7,Z={mode:"gather",role:"student"},q={iife:"pie-item-player",esm:"pie-item-player",preloaded:"pie-item-player",custom:""},K=y(Y,"assessmentId",7,""),B=y(Y,"section",7,null),U=y(Y,"sectionId",7,""),H=y(Y,"attemptId",7,""),_=y(Y,"env",23,()=>({})),A=y(Y,"ndsIcons",7,!1),M=y(Y,"lazyInit",7,!0),O=y(Y,"toolConfigStrictness",7,"error"),L=y(Y,"tools",23,()=>({})),F=y(Y,"toolContextResolvers",7,null),$=y(Y,"enabledTools",7,""),b=y(Y,"toolRegistry",7,null),v=y(Y,"accessibility",23,()=>({})),k=y(Y,"player",7,null),p=y(Y,"playerType",7,""),w=y(Y,"coordinator",7,null),l=y(Y,"createSectionController",7,null),Z7=y(Y,"onFrameworkError",7,null),j7=y(Y,"errorRenderer",7,null),L7=y(Y,"onStageChange",7,null),q7=y(Y,"assessment",7,null),i7=y(Y,"currentItemRef",7,null),s7=y(Y,"pnpEnforcement",7,null),K7=y(Y,"isolation",7,"inherit"),y7=h(null),d=h(null),Y7=h(null),x8=null,x7=null,f7=null,n7=null,k7=null,r7=null,o7=h(0),S1=h(null),a7=h(null),n=h(null),T1=h("Unable to initialize assessment toolkit."),C1=h(S8([])),f8="",y1="",k8=h(""),I8=null,v8=r6(),W7=[],t7=new Map,x1=new WeakMap,h8=o6(),i=z5({sourceCe:"pie-assessment-toolkit",sourceCeShape:"toolkit",runtimeId:J,sectionId:u(()=>U()||void 0),attemptId:u(()=>H()||void 0),emit:(W)=>{n6({isSuppressed:()=>V(X)!==null,dispatchDomEvent:(D)=>U7("pie-stage-change",D),getOnStageChange:()=>L7()},W)}}),m8=h(S8(u(()=>`${U()}|${H()}`))),e7=h(!1),a=h(!1),f1=h(!1),k1=h(!1);function H0(){if(!V(y7))return null;let W=V(y7).getRootNode();if(W&&"host"in W)return W.host;return V(y7).parentElement}let x=s(()=>H0());function U7(W,D){if(!V(x)){W7=[...W7,{name:W,detail:D}];return}L8(V(x),W,D)}T(()=>{if(!V(x))return;if(W7.length===0)return;let W=W7;W7=[],queueMicrotask(()=>{let D=V(x);if(!D){W7=[...W,...W7];return}for(let N of W)L8(D,N.name,N.detail)})});function _0(W){if(!j7())return{title:"Unable to initialize assessment toolkit.",details:W.details.length>0?W.details:[W.message]};try{let D=j7()(W)||{};return{title:typeof D.title==="string"&&D.title.trim().length>0?D.title:"Unable to initialize assessment toolkit.",details:Array.isArray(D.details)&&D.details.length>0?D.details.map((N)=>String(N)):W.details.length>0?W.details:[W.message]}}catch(D){let N=D instanceof Error&&D.message.trim().length>0?D.message:String(D||"Unknown renderer error");return{title:"Unable to initialize assessment toolkit.",details:[...W.details,`Error renderer failed: ${N}`]}}}function Q1(W){let D=X1({kind:W.kind,source:W.source,error:W.error,recoverable:W.recoverable});return j.reportFrameworkError(D),D}function F0(W){return W==="coordinator-init"||W==="runtime-init"||W==="tool-config"}function u8(W){if(!Z7())return;try{Z7()(W),f8=`${W.kind}|${W.source}|${W.message}`}catch(D){console.error(`[pie-framework:${W.kind}:${W.source}] framework error hook failed`,D)}}T(()=>{let W=j.subscribeFrameworkErrors((D)=>{if(console.error(a8(D),D.cause),F0(D.kind)){let N=_0(D);R(n,D,!0),R(T1,N.title,!0),R(C1,N.details,!0)}U7("framework-error",D),u8(D)});return()=>{W()}}),T(()=>{if(!V(n))return;let W=`${V(n).kind}|${V(n).source}|${V(n).message}`;if(f8===W)return;u8(V(n))});function A0(W){let D=5381;for(let N=0;N<W.length;N+=1)D=(D<<5)+D^W.charCodeAt(N);return(D>>>0).toString(36)}function B7(W){return W&&typeof W==="object"?W:{}}function M0(W){let D=B7(W.section),N=typeof D.identifier==="string"?D.identifier:"",P=typeof W.sectionId==="string"?W.sectionId:"";return N||P}function N0(W){return typeof W.currentItemIndex==="number"?W.currentItemIndex:-1}function z0(W){return(Array.isArray(W.renderables)?W.renderables:[]).map((N,P)=>{let z=B7(N),I=B7(z.entity),r=typeof I.id==="string"&&I.id||`renderable-${P}`,G1=B7(I.config),m1=typeof I.version==="string"&&I.version||(typeof I.version==="number"?String(I.version):"")||(typeof G1.version==="string"?G1.version:"");return{id:r,version:m1}})}function O0(W){let D=B7(W.itemSessionsByItemId);return Object.keys(D).sort((N,P)=>N.localeCompare(P)).map((N)=>{let P=B7(D[N]),z=typeof P.id==="string"?P.id:"",I=Array.isArray(P.data)?P.data:[],r="";try{r=A0(JSON.stringify(I))}catch{r=String(I.length)}return{itemId:N,sessionId:z,payloadSignature:r}})}function P0(W){let D=B7(W),N=z0(D).map((z)=>`${z.id}:${z.version}`).join("|"),P=O0(D).map((z)=>`${z.itemId}:${z.sessionId}:${z.payloadSignature}`).join("|");return{sectionId:M0(D),currentItemIndex:N0(D),renderableSignature:N,itemSessionSignature:P}}function L0(W){let D=P0(W);return`${D.sectionId}|${D.currentItemIndex}|${D.renderableSignature}|${D.itemSessionSignature}`}function p8(W){return W==="iife"||W==="esm"||W==="preloaded"||W==="custom"}function $0(W,D){let N=W?.type,P=p8(N)?N:p8(D)?D:W?.tagName?"custom":"iife",z=W?.tagName?.trim();if(P==="custom"&&!z)return{type:"iife",tagName:q.iife,version:void 0,source:void 0,isDefault:!0};return{type:P,tagName:z||q[P],version:W?.version,source:W?.source,loaderConfig:W?.loaderConfig,loaderOptions:W?.loaderOptions,isDefault:!W&&!D}}function g8(W){let D=W||{},N=typeof D.mode==="string"&&D.mode.trim()?D.mode.trim():Z.mode,P=typeof D.role==="string"&&D.role.trim()?D.role.trim():Z.role;return{mode:N,role:P}}function w0(W){let D=g8(W);if(D.mode==="author")return"author";if(D.role==="instructor")return"scorer";return"candidate"}async function R0(){if(l())return l()();throw Error("pie-assessment-toolkit requires createSectionController when no coordinator hook provides one")}function c8(){let W=L()||{},D=D0($());if(D.length===0)return W;let N=W.placement||{},P=Array.isArray(N.section)?N.section:null;if(P&&P.length>0)return W;return{...W,placement:{...N,section:D}}}function E0(){return G7(c8(),{strictness:O(),source:"pie-assessment-toolkit.bootstrap",toolRegistry:b()}).config}function b0(){let W="",D="";try{W=JSON.stringify(c8())}catch{W="[unserializable-tools]"}try{D=JSON.stringify(Object.entries(F()??{}).map(([N,P])=>[N,typeof P]))}catch{D="[unserializable-resolvers]"}return[K()||"",String(O()||"error"),W,D].join("|")}function l8(W){return W==="on"||W==="off"?W:null}function S0(W,D){let N=l8(W);if(N)return N;if(D&&typeof D==="object"){let z=D.pnpEnforcement;return l8(typeof z==="string"?z:null)}return null}function T0(W){let D=K()||B()?.identifier||`assessment-${Math.random().toString(16).slice(2)}`;return new P1({assessmentId:D,lazyInit:M(),toolConfigStrictness:O(),deferToolConfigValidation:!0,tools:W,toolRegistry:b(),toolContextResolvers:F(),accessibility:v(),frameworkErrorBus:j})}let f=s(()=>{if(K7()!=="force"&&V(Y7)?.coordinator)return V(Y7).coordinator;return w()||V(d)});T(()=>{V(x),w(),K7(),V(Y7),F(),u(()=>{if(!V(x))return;if(w()){if(V(d))R(d,null);x7=null;return}if(K7()!=="force"&&V(Y7)?.coordinator){if(V(d))R(d,null);x7=null;return}if(V(d)&&x7!==F()){try{V(d).setToolContextResolvers(F()),x7=F()}catch(W){R(a7,W,!0),Q1({kind:"coordinator-init",phase:"coordinator-ready",error:W})}return}if(!V(d)){let W=b0();if(y1===W)return;try{let D=E0();R(d,T0(D),!0),x7=F(),y1="",R(n,null),R(T1,"Unable to initialize assessment toolkit."),R(C1,[],!0)}catch(D){R(a7,D,!0),R(d,null),y1=W,Q1({kind:"coordinator-init",source:"pie-assessment-toolkit",error:D})}}})});let J7=s(()=>K()||V(f)?.assessmentId||""),t=s(()=>U()||B()?.identifier||`section-${V(J7)||"default"}`),I1=s(()=>g8(_())),C0=s(()=>w0(V(I1))),$7=s(()=>$0(k(),p())),I7=s(()=>O5({player:V($7),component:"pie-assessment-toolkit"})),Y1=s(()=>{if(!V(f))return null;let W=V(f).getServiceBundle();return{toolkitCoordinator:V(f),toolCoordinator:V(f).toolCoordinator,ttsService:W.ttsService,highlightCoordinator:W.highlightCoordinator,catalogResolver:W.catalogResolver,elementToolStateStore:W.elementToolStateStore,assessmentId:V(J7),sectionId:V(t),itemPlayer:V($7),ndsIcons:A()===!0,reportSessionChanged:(D,N)=>{let P=G.updateItemSession(D,N);s8({itemId:D,result:P,fallbackSession:N})}}}),J1=s(()=>{if(!V(f))return null;return{runtimeId:J,coordinator:V(f)}});function y0(W){let D=L0(W);if(D===V(k8))return;R(k8,D,!0),R(o7,V(o7)+1),R(S1,W,!0),U7("composition-changed",{composition:V(S1),version:V(o7)})}function v1(W){I8=W??G.getCompositionModel(),v8.schedule(()=>{y0(I8)})}function h1(W){if(!W)return;let D=x1.get(W);if(!D)return;for(let N of D)N();x1.delete(W)}function d8(){for(let W of t7.values())h1(W.element)}function i8(W){if(h1(W.element),!V(f))return;let D=V(f).getServiceBundle().catalogResolver;x1.set(W.element,[D.registerOwner({owner:{kind:W.kind,itemId:W.itemId,canonicalItemId:W.canonicalItemId,assessmentId:V(J7),sectionId:V(t)},entity:W.item})])}function x0(){d8();for(let W of t7.values())i8(W)}function s8(W){let N={...W.result?.eventDetail||W.fallbackSession,itemId:W.itemId,canonicalItemId:W.canonicalItemId||W.itemId,sourceRuntimeId:J};if(!t6({state:h8,itemId:W.itemId,payload:N}))return;U7("session-changed",N)}function f0(W){if(!(W instanceof HTMLElement))return!1;return M5(W,C8)?.runtimeId===J}function v7(W){return W.detail??null}function k0(W,D){for(let N of D)W.addEventListener(N.name,N.handler);return()=>{for(let N of D)W.removeEventListener(N.name,N.handler)}}T(()=>{if(!V(x))return;if(K7()==="force"){R(Y7,null);return}return B0(V(x),(W)=>{if(W.runtimeId===J)return;R(Y7,W,!0)})}),T(()=>{let W=V(x);return u(()=>{if(!W){R(X,null);return}let D=s6(W,(N)=>{if(N.engine===V(X))return;R(X,N.engine,!0)});return()=>{D(),R(X,null)}})}),T(()=>{let W=K7()!=="force"&&V(Y7)?V(Y7).runtimeId:null,D=W?"inherited":"owned";if(D!==x8)x8=D,U7(D==="inherited"?"runtime-inherited":"runtime-owned",{runtimeId:J,parentRuntimeId:W})}),T(()=>{let W=V(t),D=H()||"";a6(h8)}),T(()=>{if(!V(x)||!V(J1))return;return k7=new e6(V(x),{context:C8,initialValue:V(J1)}),k7.connect(),r7=new Q0(V(x)),r7.attach(),()=>{r7?.detach(),r7=null,k7?.disconnect(),k7=null}}),T(()=>{if(!V(J1))return;k7?.setValue(V(J1))}),T(()=>{if(!V(x))return;V(x).setAttribute("data-item-player-type",V($7).type),V(x).setAttribute("data-item-player-tag",V($7).tagName),V(x).setAttribute("data-env-mode",String(V(I1)?.mode||"")),V(x).setAttribute("data-env-role",String(V(I1)?.role||""))}),T(()=>{if(!V(x)||!V(Y1))return;return f7=new e6(V(x),{context:U0,initialValue:V(Y1)}),f7.connect(),n7=new Q0(V(x)),n7.attach(),()=>{n7?.detach(),n7=null,f7?.disconnect(),f7=null}}),T(()=>{if(V(Y1))f7?.setValue(V(Y1))}),T(()=>{return V(f),V(J7),V(t),x0(),()=>{d8()}}),T(()=>{if(!V(x))return;return N5({host:V(x),instrumentationProvider:V(I7),component:"pie-assessment-toolkit",eventMap:P5,staticAttributes:{instrumentationLayer:"toolkit",assessmentId:V(J7),sectionId:V(t),attemptId:H()||void 0}})}),T(()=>{q7(),i7(),s7(),L();let W=V(f);if(!W)return;if(W!==V(d))return;u(()=>{W.setPnpEnforcement(S0(s7(),L())),W.updateAssessment(q7()),W.updateCurrentItemRef(i7())})}),T(()=>{if(!V(f))return;return V(f).subscribeTelemetry(({eventName:W,payload:D})=>{if(!L5(V(I7)))return;if(!V(I7).isReady())return;let N=W,P=new Date().toISOString(),z={...D||{},instrumentationLayer:"toolkit",assessmentId:V(J7),sectionId:V(t),attemptId:H()||void 0,component:"pie-assessment-toolkit",sourceEventName:W,timestamp:P};V(I7).trackEvent(N,z);let I=D&&typeof D.errorType==="string"?D.errorType:void 0;if(!W.endsWith("-error")&&!I)return;let r=D&&typeof D.message==="string"?D.message:`Toolkit telemetry error: ${W}`;V(I7).trackError(Error(r),{component:"pie-assessment-toolkit",errorType:I||"ToolkitTelemetryError",...z})})}),T(()=>{if(!B()||!V(f))return;let W=!1;return G.initialize({coordinator:V(f),section:B(),sectionId:V(t),assessmentId:V(J7),attemptId:H()||void 0,view:V(C0),createDefaultController:R0,onCompositionChanged:(D)=>{if(W)return;v1(D)}}).then(()=>{if(W)return;U7("toolkit-ready",{runtimeId:J,assessmentId:V(J7),sectionId:V(t),itemPlayer:V($7),coordinator:V(f)}),U7("section-ready",{sectionId:V(t)}),u(()=>{R(k1,!0)})}).catch((D)=>{u(()=>{if(!V(a))R(a,!0),i.enter("engine-ready","skipped");i.enter("interactive","failed")}),R(a7,D,!0),G.reportSectionError({source:"section-runtime",error:D,timestamp:Date.now()}),Q1({kind:"runtime-init",source:"pie-assessment-toolkit",error:D})}),()=>{W=!0}}),T(()=>{if(!V(x))return;let W=V(x),D=(P)=>f0(P.target);return k0(W,[{name:y6,handler:(P)=>{if(!D(P))return;let z=v7(P);if(!z?.element||!z?.itemId)return;let I=G.register(z);if(t7.set(z.element,z),i8(z),G.handleContentRegistered(z),I)v1()}},{name:x6,handler:(P)=>{if(!D(P))return;let z=v7(P);if(!z?.itemId)return;let I=z?.element?G.unregister(z.element):!1;if(h1(z.element),z.element)t7.delete(z.element);if(G.handleContentUnregistered(z),I)v1()}},{name:f6,handler:(P)=>{if(!D(P))return;let z=v7(P);if(!z?.itemId)return;let I=G.updateItemSession(z.itemId,z.session);s8({itemId:z.itemId,canonicalItemId:G.getCanonicalItemId(z.itemId),result:I,fallbackSession:z.session})}},{name:k6,handler:(P)=>{if(!D(P))return;let z=v7(P);if(!z?.itemId)return;G.handleContentLoaded({itemId:z.itemId,canonicalItemId:z.canonicalItemId,contentKind:z.contentKind,detail:z.detail,timestamp:Date.now()})}},{name:I6,handler:(P)=>{if(!D(P))return;let z=v7(P);if(!z?.itemId)return;G.handleItemPlayerError({itemId:z.itemId,canonicalItemId:z.canonicalItemId,contentKind:z.contentKind,error:z.error,timestamp:Date.now()})}}])});async function I0(){if(!V(f))throw Error("Coordinator not initialized");await V(f).waitUntilReady()}function v0(){if(!V(f))throw Error("Coordinator not initialized");return V(f).getServiceBundle()}function h0(W){if(!V(f))throw Error("Coordinator not initialized");V(f).setHooks(W)}function m0(W){return G.navigateToItem(W)}function u0(){return G.getCompositionModel()}function p0(){return V($7)}async function g0(){await G.persist()}async function c0(){await G.hydrate()}T(()=>{return()=>{u(()=>{if(i.getCurrent()!==null)i.enter("disposed")})}}),T(()=>{let W=`${U()}|${H()}`;u(()=>{if(W===V(m8))return;if(i.getCurrent()!==null)i.enter("disposed");i.reset({sectionId:U()||void 0,attemptId:H()||void 0}),R(m8,W),R(e7,!1),R(a,!1),R(f1,!1),R(k1,!1)})}),T(()=>{let W=V(a)&&V(k1);u(()=>{if(!W)return;if(V(f1))return;R(f1,!0),i.enter("interactive")})}),T(()=>{let W=V(o7)>0||V(S1)!==null;u(()=>{if(!V(e7)&&W)R(e7,!0),i.enter("composed")})}),T(()=>{if(!V(f))return;if(!V(e7))return;if(V(a))return;let W=V(f),D=!1;return W.waitUntilReady().then(()=>{if(D)return;u(()=>{if(V(a))return;R(a,!0),i.enter("engine-ready")})}).catch(()=>{if(D)return;u(()=>{if(V(a))return;R(a,!0),i.enter("engine-ready","failed")})}),()=>{D=!0}}),T(()=>{return()=>{v8.cancel(),G.dispose().catch((W)=>{R(a7,W,!0),Q1({kind:"runtime-dispose",source:"pie-assessment-toolkit",error:W,recoverable:!0})}).finally(()=>{j.dispose()})}});var l0={waitUntilReady:I0,getServiceBundle:v0,setHooks:h0,navigateToItem:m0,getCompositionModel:u0,getItemPlayerConfig:p0,persist:g0,hydrate:c0,get assessmentId(){return K()},set assessmentId(W){K(W),C()},get section(){return B()},set section(W){B(W),C()},get sectionId(){return U()},set sectionId(W){U(W),C()},get attemptId(){return H()},set attemptId(W){H(W),C()},get env(){return _()},set env(W){_(W),C()},get ndsIcons(){return A()},set ndsIcons(W){A(W),C()},get lazyInit(){return M()},set lazyInit(W){M(W),C()},get toolConfigStrictness(){return O()},set toolConfigStrictness(W){O(W),C()},get tools(){return L()},set tools(W){L(W),C()},get toolContextResolvers(){return F()},set toolContextResolvers(W){F(W),C()},get enabledTools(){return $()},set enabledTools(W){$(W),C()},get toolRegistry(){return b()},set toolRegistry(W){b(W),C()},get accessibility(){return v()},set accessibility(W){v(W),C()},get player(){return k()},set player(W){k(W),C()},get playerType(){return p()},set playerType(W){p(W),C()},get coordinator(){return w()},set coordinator(W){w(W),C()},get createSectionController(){return l()},set createSectionController(W){l(W),C()},get onFrameworkError(){return Z7()},set onFrameworkError(W){Z7(W),C()},get errorRenderer(){return j7()},set errorRenderer(W){j7(W),C()},get onStageChange(){return L7()},set onStageChange(W){L7(W),C()},get assessment(){return q7()},set assessment(W){q7(W),C()},get currentItemRef(){return i7()},set currentItemRef(W){i7(W),C()},get pnpEnforcement(){return s7()},set pnpEnforcement(W){s7(W),C()},get isolation(){return K7()},set isolation(W){K7(W),C()}},n8=w5(),r8=T8(n8);K0(r8,(W)=>R(y7,W),()=>V(y7));var d0=R1(r8,2);{var i0=(W)=>{var D=$5(),N=d7(D),P=d7(N,!0);l7(N);var z=R1(N,2),I=d7(z,!0);l7(z);var r=R1(z,2),G1=d7(r,!0);l7(r),l7(D),G0((m1)=>{b1(P,V(T1)),b1(I,V(n).message),b1(G1,m1)},[()=>V(C1).join(`
225
+ `)]),E1(W,D)},s0=(W)=>{var D=X0(),N=T8(D);j0(N,Y,"default",{},null),E1(W,D)};Z0(d0,(W)=>{if(V(n)&&!V(n).recoverable)W(i0);else W(s0,-1)})}return E1(Q,n8),J0(l0)}A5("pie-assessment-toolkit",W0(V0,{assessmentId:{attribute:"assessment-id",type:"String"},section:{attribute:"section",type:"Object"},sectionId:{attribute:"section-id",type:"String"},attemptId:{attribute:"attempt-id",type:"String"},env:{attribute:"env",type:"Object"},ndsIcons:{attribute:"nds-icons",type:"Boolean"},lazyInit:{attribute:"lazy-init",type:"Boolean"},toolConfigStrictness:{attribute:"tool-config-strictness",type:"String"},tools:{attribute:"tools",type:"Object"},toolContextResolvers:{type:"Object"},enabledTools:{attribute:"enabled-tools",type:"String"},toolRegistry:{type:"Object"},accessibility:{type:"Object"},player:{attribute:"player",type:"Object"},playerType:{attribute:"player-type",type:"String"},coordinator:{type:"Object"},createSectionController:{type:"Object"},onFrameworkError:{type:"Object"},errorRenderer:{type:"Object"},onStageChange:{type:"Object"},assessment:{type:"Object"},currentItemRef:{type:"Object"},pnpEnforcement:{attribute:"pnp-enforcement",type:"String"},isolation:{type:"Object"}},["default"],["waitUntilReady","getServiceBundle","setHooks","navigateToItem","getCompositionModel","getItemPlayerConfig","persist","hydrate"],{mode:"open"}));export{V0 as default};