@pie-players/pie-assessment-toolkit 0.3.64 → 0.3.65
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +45 -17
- package/dist/components/ItemToolBar.custom-element.js +1 -1
- package/dist/components/PieAssessmentToolkit.custom-element.js +6 -6
- package/dist/components/SectionToolBar.custom-element.js +1 -1
- package/dist/components/chunks/ItemToolBar-cckwpz6c.js +51 -0
- package/dist/components/chunks/ItemToolBar-pryf0rtz.js +22 -0
- package/dist/index.d.ts +5 -6
- package/dist/index.js +9 -4
- package/dist/runtime/composition-emit-scheduler.d.ts +78 -0
- package/dist/runtime/composition-emit-scheduler.js +154 -0
- package/dist/runtime/core/engine-resolver.d.ts +1 -1
- package/dist/services/ToolRegistry.d.ts +218 -8
- package/dist/services/ToolRegistry.js +124 -8
- package/dist/services/ToolkitCoordinator.d.ts +2 -1
- package/dist/services/ToolkitCoordinator.js +23 -6
- package/dist/services/createDefaultToolRegistry.d.ts +25 -58
- package/dist/services/createDefaultToolRegistry.js +24 -104
- package/dist/services/defaultPersonalNeedsProfile.d.ts +16 -14
- package/dist/services/defaultPersonalNeedsProfile.js +17 -38
- package/dist/services/pnp-standard-features.d.ts +1 -1
- package/dist/services/tool-config-defaults.d.ts +7 -23
- package/dist/services/tool-config-defaults.js +7 -46
- package/dist/services/tool-config-validation.d.ts +1 -1
- package/dist/services/tool-config-validation.js +44 -4
- package/dist/services/tts/browser-provider.js +2 -1
- package/dist/services/tts-runtime-config.js +7 -2
- package/dist/tools/internal.d.ts +34 -0
- package/dist/tools/internal.js +33 -0
- package/dist/tools/tool-tag-map.d.ts +15 -3
- package/dist/tools/tool-tag-map.js +21 -18
- package/package.json +14 -10
- package/dist/components/chunks/ItemToolBar-3cppre9r.js +0 -51
- package/dist/components/chunks/ItemToolBar-7rq2gj8b.js +0 -22
- package/dist/services/sign-language-cards.d.ts +0 -82
- package/dist/services/sign-language-cards.js +0 -133
- package/dist/tools/registrations/accessibility-tools.d.ts +0 -34
- package/dist/tools/registrations/accessibility-tools.js +0 -217
- package/dist/tools/registrations/calculator.d.ts +0 -20
- package/dist/tools/registrations/calculator.js +0 -228
- package/dist/tools/registrations/interaction-tools.d.ts +0 -27
- package/dist/tools/registrations/interaction-tools.js +0 -143
- package/dist/tools/registrations/measurement-tools.d.ts +0 -24
- package/dist/tools/registrations/measurement-tools.js +0 -130
- package/dist/tools/registrations/subject-specific-tools.d.ts +0 -27
- package/dist/tools/registrations/subject-specific-tools.js +0 -158
- package/dist/tools/registrations/tts.d.ts +0 -21
- package/dist/tools/registrations/tts.js +0 -184
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{B as Y0,C as J0,I as G0,J as C,K as X0,L as Z0,M as E8,O as j0,Q as M1,R as q0,S as $7,T as M8,b as X2,c as c7,d as o6,e as a6,f as s,g as T,h as v,i as w,j as R8,k as l7,l as b8,m as R1,n as S,o as t6,p as D,q as u,t as S8,u as e6,v as b1,w as E1,x as Q0}from"./chunks/ItemToolBar-cckwpz6c.js";import{ContextProvider as n6,ContextRoot as r6,requestContext as _5}from"@pie-players/pie-context";import{attachInstrumentationEventBridge as H5,createStageTracker as A5,resolveInstrumentationProvider as F5,TOOLKIT_INSTRUMENTATION_EVENT_MAP as M5}from"@pie-players/pie-players-shared/pie";import{isInstrumentationProvider as N5}from"@pie-players/pie-players-shared";function c0(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 c0({kind:Q.kind,source:Q.source,message:Y,recoverable:Q.recoverable,cause:Q.error})}var l0={"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 s8(Q){let Y=l0[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 n8(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
|
|
3
|
+
- `)}`}var d0="error";function u1(Q){if(Q==="off"||Q==="warn"||Q==="error")return Q;return d0}function p(Q){return Q}function i0(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 s0(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(p({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(p({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 n0(Q,Y,J,G){if(!Y||!J?.provider?.validateConfig)return;try{let X=J.provider.validateConfig(Y);if(!Array.isArray(X)){G.push(p({code:"tools.invalidProviderValidation",severity:"error",path:`providers.${Q}`,message:`Provider validator for "${Q}" must return an array.`,providerId:Q,toolId:Q}));return}for(let Z of X)G.push({...Z,path:Z.path||`providers.${Q}`,providerId:Z.providerId||Q,toolId:Z.toolId||Q})}catch(X){G.push(p({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 r0(Q,Y,J){if(Y.size===0)return;let G=["section","item","passage"];for(let X of G)for(let Z of Q.placement[X]){let j=Y.get(Z);if(!j){J.push(p({code:"tools.unknownToolId",severity:"error",path:`placement.${X}`,message:`Unknown tool id "${Z}" in placement.${X}.`,toolId:Z}));continue}if(j.activation==="region"){J.push(p({code:"tools.unplaceableActivation",severity:"error",path:`placement.${X}`,message:`Tool "${Z}" 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:Z}));continue}let q=j.supportedLevels.includes(X),W=X==="item"&&j.supportedLevels.includes("section");if(!q&&!W)J.push(p({code:"tools.unsupportedLevel",severity:"error",path:`placement.${X}`,message:`Tool "${Z}" does not support level "${X}".`,toolId:Z}))}}function o0(Q,Y,J){if(Y.size===0)return;for(let G of Q.policy.allowed||[]){if(Y.has(G))continue;J.push(p({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(p({code:"tools.unknownToolId",severity:"error",path:"policy.blocked",message:`Unknown tool id "${G}" in policy.blocked.`,toolId:G}))}}function a0(Q,Y,J,G){if(J)G.push(p({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(p({code:"tools.unknownProviderKey",severity:"error",path:`providers.${X}`,message:`Unknown provider key "${X}".`,providerId:X,toolId:X}))}}function r8(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 o8(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 J7(Q,Y={}){let J=h1(Y.strictness),G=Y.source??"tools",X=y0(Y.toolRegistry??f7()),Z=z7(Q),j=[],q=Object.hasOwn(Z.providers,"tts"),U={...Z.providers||{}};for(let D of Object.keys(U).sort()){if(D==="tts"){delete U.tts;continue}let _=X.get(D);U[D]=f0(D,U[D],_,j),x0(D,U[D],_,j)}let V={...Z,providers:U};if(I0(V,X,j),k0(V,X,j),v0(V,X,q,j),q)c8(j.filter((D)=>D.code==="tools.removedProviderKey"),G);if(J==="warn")h0(j,G);if(J==="error"&&j.length>0)c8(j,G);return{config:V,diagnostics:j}}var p1=new Set(["speak","break","prosody","emphasis","say-as","sub","mark","phoneme","lang","p","s","voice","audio","lexicon"]),d8=new Set(["script","style","iframe","object","embed","foreignobject","noscript","template"]),l8=new Set(["alphabet","ph","time","strength","rate","pitch","volume","name","interpret-as","format","detail","language","xml:lang","lang","gender","src"]),i8=new Set(["break","mark","lexicon"]);function u0(Q){let Y=Q;for(let J of i8){let G=new RegExp(`<${J}\\b([^>/]*?)\\s*/>`,"gi");Y=Y.replace(G,(X,Z)=>{let j=Z?Z.replace(/\s+$/,""):"";return`<${J}${j}></${J}>`})}return Y}var m0=[/^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 p0(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!m0.some((G)=>G.test(J))}function u1(Q){let Y=Array.from(Q.children);for(let G of Y){let X=G.tagName.toLowerCase();if(d8.has(X)){G.remove();continue}if(u1(G),!p1.has(X)){let Z=Q.ownerDocument.createTextNode(G.textContent??"");G.replaceWith(Z)}}let J=Array.from(Q.attributes).map((G)=>G.name);for(let G of J)if(!l8.has(G.toLowerCase()))Q.removeAttribute(G);if(Q.tagName.toLowerCase()==="audio"){let G=Q.getAttribute("src");if(G!==null&&!p0(G))Q.removeAttribute("src")}}function m1(Q){let Y=Q.tagName.toLowerCase(),J=Array.from(Q.attributes).filter((X)=>l8.has(X.name.toLowerCase())).map((X)=>` ${X.name}="${g0(X.value)}"`).join("");if(i8.has(Y))return`<${Y}${J}/>`;let G=[];for(let X of Array.from(Q.childNodes))if(X.nodeType===3)G.push(J1(X.nodeValue??""));else if(X.nodeType===1){let Z=X,j=Z.tagName.toLowerCase();if(d8.has(j))continue;if(p1.has(j))G.push(m1(Z));else G.push(J1(Z.textContent??""))}return`<${Y}${J}>${G.join("")}</${Y}>`}function g1(Q){let Y=String(Q||"").trim();if(!Y||!Y.includes("<"))return Q;if(typeof DOMParser>"u")return Q;let G=new DOMParser().parseFromString(u0(Y),"text/html"),X=G.querySelector("speak");if(X)return u1(X),m1(X);let Z=G.createElement("speak");for(let j of Array.from(G.body.childNodes))Z.appendChild(j);return u1(Z),Array.from(Z.childNodes).map((j)=>{if(j.nodeType===3)return J1(j.nodeValue??"");if(j.nodeType===1){let q=j;if(p1.has(q.tagName.toLowerCase()))return m1(q);return J1(q.textContent??"")}return""}).join("")}function J1(Q){return Q.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}function g0(Q){return Q.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}var a8=new Set(["spoken","sign-language","transcript","braille","tactile","simplified-language","audio-description","extended-description"]),c1="ext:";function s8(Q){if(a8.has(Q))return!0;return Q.startsWith(c1)&&Q.length>c1.length}var n8=new Set;function r8(Q,Y,J){let G=`${Y}|${Q}`;if(n8.has(G))return;n8.add(G);let X=`${Array.from(a8).join(", ")}, or an "${c1}" 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 o8=(Q)=>Q.payload!==void 0?"payload":"content";class d1{assessmentCatalogs=new Map;itemCatalogs=new Map;scopedCatalogs=new Map;defaultLanguage="en-US";sanitizedSpokenCache=new Map;catalogChangeListeners=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)}}registerCatalogs(Q,Y){if(!Y||Y.length===0)return()=>{};let J=this.getOwnerKey(Q),G=this.scopedCatalogs.get(J),X=G?.catalogs??new Map,Z=[];for(let j of this.sanitizeCatalogs(Y)){if(X.has(j.identifier)){console.warn(`[AccessibilityCatalogResolver] Duplicate scoped catalog "${j.identifier}" ignored for ${J}`);continue}X.set(j.identifier,j),Z.push(j.identifier)}if(!G)this.scopedCatalogs.set(J,{context:{...Q},catalogs:X});if(Z.length>0)this.emitCatalogsChange({reason:"scoped-registered",context:Q});return()=>{let j=this.scopedCatalogs.get(J);if(j?.catalogs!==X)return;for(let q of Z)j.catalogs.delete(q);if(j.catalogs.size===0)this.scopedCatalogs.delete(J);if(Z.length>0)this.emitCatalogsChange({reason:"scoped-removed",context:Q})}}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(!s8(Y.type))r8(Y.type,"lookup",Q);let J=Y.context?this.scopedCatalogs.get(this.getOwnerKey(Y.context))?.catalogs.get(Q):null;if(J){let Z=this.findMatchingCard(J,Y);if(Z)return this.resolveCard(Q,Z,"item")}if(Y.context){let Z=this.findScopedCandidates(Q,Y.context);if(Z.length===1){let j=this.findMatchingCard(Z[0],Y);if(j)return this.resolveCard(Q,j,"item")}else if(Z.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 Z=this.findMatchingCard(G,Y);if(Z)return this.resolveCard(Q,Z,"item")}let X=this.assessmentCatalogs.get(Q);if(X){let Z=this.findMatchingCard(X,Y);if(Z)return this.resolveCard(Q,Z,"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=g1(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}sanitizeCatalogs(Q){return Q.map((Y)=>({...Y,cards:Y.cards.map((J)=>{if(!s8(J.catalog))r8(J.catalog,"card",Y.identifier);return{...J,content:J.catalog==="spoken"&&J.content!==void 0?g1(J.content):J.content}})}))}findMatchingCard(Q,Y){let{type:J,language:G,useFallback:X=!0,form:Z}=Y,j=[];if(G)j.push((q)=>q.language===G);if(X)j.push((q)=>q.language===this.defaultLanguage),j.push(()=>!0);for(let q of j){let U=Q.cards.filter((V)=>V.catalog===J&&q(V));if(U.length===0)continue;if(Z){let V=U.find((D)=>o8(D)===Z);if(V)return V}return U[0]}return null}getAllAlternatives(Q){let Y=[],J=new Set,G=(j,q)=>{let U=`${j.catalog}|${j.language??""}|${o8(j)}`;if(J.has(U))return;J.add(U),Y.push(this.resolveCard(Q,j,q))},X=this.itemCatalogs.get(Q);if(X)for(let j of X.cards)G(j,"item");let Z=this.assessmentCatalogs.get(Q);if(Z)for(let j of Z.cards)G(j,"assessment");for(let[j,q]of this.scopedCatalogEntries()){if(j!==Q)continue;for(let U of q.cards)G(U,"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);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()}destroy(){this.reset()}}class l1{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 x7{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 i1{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((j)=>j.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 Z=Array.from(X.children).filter((U)=>U.tagName===G.tagName),j=Z.indexOf(G),q=Z.length>1?`${G.tagName.toLowerCase()}:nth-of-type(${j+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),Z=J?Y.querySelector(J):Y;if(!Z)return null;return Array.from(Z.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 h;(function(Q){Q.TTS_WORD="tts-word",Q.TTS_SENTENCE="tts-sentence",Q.ANNOTATION="annotation"})(h||(h={}));var K7;(function(Q){Q.YELLOW="yellow",Q.GREEN="green",Q.BLUE="blue",Q.PINK="pink",Q.ORANGE="orange",Q.UNDERLINE="underline"})(K7||(K7={}));class I7{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 i1,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 Z=G[1].replace(/\//g,",").split(/[,\s]+/).map((V)=>V.trim()).filter(Boolean),j=Number(Z[0]),q=Number(Z[1]),U=Number(Z[2]);if(Number.isFinite(j)&&Number.isFinite(q)&&Number.isFinite(U))return[j,q,U]}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 Z=typeof getComputedStyle==="function"?getComputedStyle(X).color:"";X.remove();let j=Z.trim();if(j&&j!==Y)return this.parseColor(Z)}}return null}relativeLuminance([Q,Y,J]){let G=(q)=>{let U=q/255;return U<=0.03928?U/12.92:((U+0.055)/1.055)**2.4},X=G(Q),Z=G(Y),j=G(J);return 0.2126*X+0.7152*Z+0.0722*j}contrastRatio(Q,Y){let J=this.relativeLuminance(Q),G=this.relativeLuminance(Y),X=Math.max(J,G),Z=Math.min(J,G);return(X+0.05)/(Z+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),Z=X&&typeof getComputedStyle==="function"?getComputedStyle(X):null,j=this.parseColor(Z?.getPropertyValue("--pie-background")||Z?.backgroundColor)||G,q=this.parseColor(Z?.getPropertyValue("--pie-text"))||J,U=this.explicitTTSColorOverride?this.parseColor(this.explicitTTSColorOverride.color)||Y:this.parseColor(Z?.getPropertyValue("--pie-missing"))||Y,V=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],D=V[V.length-1],_=-1/0;for(let g of V){let X7=this.blend(U,j,g),Z7=this.contrastRatio(X7,j),N7=this.contrastRatio(X7,q),j7=Z7*1.2+N7*0.8;if(Z7>=1.25&&N7>=2.4){D=g;break}if(j7>_)_=j7,D=g}let F=Math.max(0.24,Math.min(0.85,D*0.55)),N=Math.max(0.55,Math.min(0.95,D+0.2)),O=Math.max(0.22,Math.min(0.6,D*0.45)),w=q,k=this.blend(w,j,N),H=this.contrastRatio(k,j),b=this.relativeLuminance(j)>0.45?[0,0,0]:[255,255,255],T=H>=1.35?w:b,u=`rgba(${U[0]}, ${U[1]}, ${U[2]}, ${D})`,I=`rgba(${U[0]}, ${U[1]}, ${U[2]}, ${F})`,p=`rgba(${T[0]}, ${T[1]}, ${T[2]}, ${N})`,L=`rgba(${T[0]}, ${T[1]}, ${T[2]}, ${O})`;return{wordHighlight:u,sentenceHighlight:I,wordUnderline:p,wordShadow:L}}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(K7)){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=i0(Y.toolRegistry),Z=$7(Q),j=[],q=Object.values(Z.placement).some((H)=>H.length>0)||Object.keys(Z.providers).length>0||(Z.policy.allowed?.length??0)>0||(Z.policy.blocked?.length??0)>0;if(X.size===0&&q)j.push(p({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 W=Object.hasOwn(Z.providers,"tts"),V={...Z.providers||{}};for(let H of Object.keys(V).sort()){if(H==="tts"){delete V.tts;continue}let F=X.get(H);V[H]=s0(H,V[H],F,j),n0(H,V[H],F,j)}let U={...Z,providers:V};if(r0(U,X,j),o0(U,X,j),a0(U,X,W,j),W)o8(j.filter((H)=>H.code==="tools.removedProviderKey"),G);if(J==="warn")r8(j,G);let _=j.filter((H)=>H.severity==="error");if(J==="error"&&_.length>0)o8(_,G);if(J==="error"&&_.length===0)r8(j,G);return{config:U,diagnostics:j}}var c1=new Set(["speak","break","prosody","emphasis","say-as","sub","mark","phoneme","lang","p","s","voice","audio","lexicon"]),a8=new Set(["script","style","iframe","object","embed","foreignobject","noscript","template"]),t8=new Set(["alphabet","ph","time","strength","rate","pitch","volume","name","interpret-as","format","detail","language","xml:lang","lang","gender","src"]),e8=new Set(["break","mark","lexicon"]);function t0(Q){let Y=Q;for(let J of e8){let G=new RegExp(`<${J}\\b([^>/]*?)\\s*/>`,"gi");Y=Y.replace(G,(X,Z)=>{let j=Z?Z.replace(/\s+$/,""):"";return`<${J}${j}></${J}>`})}return Y}var e0=[/^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 Q3(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!e0.some((G)=>G.test(J))}function p1(Q){let Y=Array.from(Q.children);for(let G of Y){let X=G.tagName.toLowerCase();if(a8.has(X)){G.remove();continue}if(p1(G),!c1.has(X)){let Z=Q.ownerDocument.createTextNode(G.textContent??"");G.replaceWith(Z)}}let J=Array.from(Q.attributes).map((G)=>G.name);for(let G of J)if(!t8.has(G.toLowerCase()))Q.removeAttribute(G);if(Q.tagName.toLowerCase()==="audio"){let G=Q.getAttribute("src");if(G!==null&&!Q3(G))Q.removeAttribute("src")}}function g1(Q){let Y=Q.tagName.toLowerCase(),J=Array.from(Q.attributes).filter((X)=>t8.has(X.name.toLowerCase())).map((X)=>` ${X.name}="${Y3(X.value)}"`).join("");if(e8.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 Z=X,j=Z.tagName.toLowerCase();if(a8.has(j))continue;if(c1.has(j))G.push(g1(Z));else G.push(X1(Z.textContent??""))}return`<${Y}${J}>${G.join("")}</${Y}>`}function l1(Q){let Y=String(Q||"").trim();if(!Y||!Y.includes("<"))return Q;if(typeof DOMParser>"u")return Q;let G=new DOMParser().parseFromString(t0(Y),"text/html"),X=G.querySelector("speak");if(X)return p1(X),g1(X);let Z=G.createElement("speak");for(let j of Array.from(G.body.childNodes))Z.appendChild(j);return p1(Z),Array.from(Z.childNodes).map((j)=>{if(j.nodeType===3)return X1(j.nodeValue??"");if(j.nodeType===1){let q=j;if(c1.has(q.tagName.toLowerCase()))return g1(q);return X1(q.textContent??"")}return""}).join("")}function X1(Q){return Q.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}function Y3(Q){return Q.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}var X9=new Set(["spoken","sign-language","transcript","braille","tactile","simplified-language","audio-description","extended-description"]),d1="ext:";function Q9(Q){if(X9.has(Q))return!0;return Q.startsWith(d1)&&Q.length>d1.length}var Y9=new Set;function J9(Q,Y,J){let G=`${Y}|${Q}`;if(Y9.has(G))return;Y9.add(G);let X=`${Array.from(X9).join(", ")}, or an "${d1}" 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 G9=(Q)=>Q.payload!==void 0?"payload":"content";class i1{assessmentCatalogs=new Map;itemCatalogs=new Map;scopedCatalogs=new Map;defaultLanguage="en-US";sanitizedSpokenCache=new Map;catalogChangeListeners=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)}}registerCatalogs(Q,Y){if(!Y||Y.length===0)return()=>{};let J=this.getOwnerKey(Q),G=this.scopedCatalogs.get(J),X=G?.catalogs??new Map,Z=[];for(let j of this.sanitizeCatalogs(Y)){if(X.has(j.identifier)){console.warn(`[AccessibilityCatalogResolver] Duplicate scoped catalog "${j.identifier}" ignored for ${J}`);continue}X.set(j.identifier,j),Z.push(j.identifier)}if(!G)this.scopedCatalogs.set(J,{context:{...Q},catalogs:X});if(Z.length>0)this.emitCatalogsChange({reason:"scoped-registered",context:Q});return()=>{let j=this.scopedCatalogs.get(J);if(j?.catalogs!==X)return;for(let q of Z)j.catalogs.delete(q);if(j.catalogs.size===0)this.scopedCatalogs.delete(J);if(Z.length>0)this.emitCatalogsChange({reason:"scoped-removed",context:Q})}}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(!Q9(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 Z=this.findMatchingCard(J,Y);if(Z)return this.resolveCard(Q,Z,"item")}if(Y.context){let Z=this.findScopedCandidates(Q,Y.context);if(Z.length===1){let j=this.findMatchingCard(Z[0],Y);if(j)return this.resolveCard(Q,j,"item")}else if(Z.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 Z=this.findMatchingCard(G,Y);if(Z)return this.resolveCard(Q,Z,"item")}let X=this.assessmentCatalogs.get(Q);if(X){let Z=this.findMatchingCard(X,Y);if(Z)return this.resolveCard(Q,Z,"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=l1(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}sanitizeCatalogs(Q){return Q.map((Y)=>({...Y,cards:Y.cards.map((J)=>{if(!Q9(J.catalog))J9(J.catalog,"card",Y.identifier);return{...J,content:J.catalog==="spoken"&&J.content!==void 0?l1(J.content):J.content}})}))}findMatchingCard(Q,Y){let{type:J,language:G,useFallback:X=!0,form:Z}=Y,j=[];if(G)j.push((q)=>q.language===G);if(X)j.push((q)=>q.language===this.defaultLanguage),j.push(()=>!0);for(let q of j){let W=Q.cards.filter((V)=>V.catalog===J&&q(V));if(W.length===0)continue;if(Z){let V=W.find((U)=>G9(U)===Z);if(V)return V}return W[0]}return null}getAllAlternatives(Q){let Y=[],J=new Set,G=(j,q)=>{let W=`${j.catalog}|${j.language??""}|${G9(j)}`;if(J.has(W))return;J.add(W),Y.push(this.resolveCard(Q,j,q))},X=this.itemCatalogs.get(Q);if(X)for(let j of X.cards)G(j,"item");let Z=this.assessmentCatalogs.get(Q);if(Z)for(let j of Z.cards)G(j,"assessment");for(let[j,q]of this.scopedCatalogEntries()){if(j!==Q)continue;for(let W of q.cards)G(W,"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);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()}destroy(){this.reset()}}class s1{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 n1{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((j)=>j.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 Z=Array.from(X.children).filter((W)=>W.tagName===G.tagName),j=Z.indexOf(G),q=Z.length>1?`${G.tagName.toLowerCase()}:nth-of-type(${j+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),Z=J?Y.querySelector(J):Y;if(!Z)return null;return Array.from(Z.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 h;(function(Q){Q.TTS_WORD="tts-word",Q.TTS_SENTENCE="tts-sentence",Q.ANNOTATION="annotation"})(h||(h={}));var B7;(function(Q){Q.YELLOW="yellow",Q.GREEN="green",Q.BLUE="blue",Q.PINK="pink",Q.ORANGE="orange",Q.UNDERLINE="underline"})(B7||(B7={}));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 n1,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 Z=G[1].replace(/\//g,",").split(/[,\s]+/).map((V)=>V.trim()).filter(Boolean),j=Number(Z[0]),q=Number(Z[1]),W=Number(Z[2]);if(Number.isFinite(j)&&Number.isFinite(q)&&Number.isFinite(W))return[j,q,W]}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 Z=typeof getComputedStyle==="function"?getComputedStyle(X).color:"";X.remove();let j=Z.trim();if(j&&j!==Y)return this.parseColor(Z)}}return null}relativeLuminance([Q,Y,J]){let G=(q)=>{let W=q/255;return W<=0.03928?W/12.92:((W+0.055)/1.055)**2.4},X=G(Q),Z=G(Y),j=G(J);return 0.2126*X+0.7152*Z+0.0722*j}contrastRatio(Q,Y){let J=this.relativeLuminance(Q),G=this.relativeLuminance(Y),X=Math.max(J,G),Z=Math.min(J,G);return(X+0.05)/(Z+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),Z=X&&typeof getComputedStyle==="function"?getComputedStyle(X):null,j=this.parseColor(Z?.getPropertyValue("--pie-background")||Z?.backgroundColor)||G,q=this.parseColor(Z?.getPropertyValue("--pie-text"))||J,W=this.explicitTTSColorOverride?this.parseColor(this.explicitTTSColorOverride.color)||Y:this.parseColor(Z?.getPropertyValue("--pie-missing"))||Y,V=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=V[V.length-1],_=-1/0;for(let l of V){let Z7=this.blend(W,j,l),j7=this.contrastRatio(Z7,j),P7=this.contrastRatio(Z7,q),q7=j7*1.2+P7*0.8;if(j7>=1.25&&P7>=2.4){U=l;break}if(q7>_)_=q7,U=l}let H=Math.max(0.24,Math.min(0.85,U*0.55)),F=Math.max(0.55,Math.min(0.95,U+0.2)),N=Math.max(0.22,Math.min(0.6,U*0.45)),P=q,f=this.blend(P,j,F),A=this.contrastRatio(f,j),L=this.relativeLuminance(j)>0.45?[0,0,0]:[255,255,255],E=A>=1.35?P:L,m=`rgba(${W[0]}, ${W[1]}, ${W[2]}, ${U})`,I=`rgba(${W[0]}, ${W[1]}, ${W[2]}, ${H})`,c=`rgba(${E[0]}, ${E[1]}, ${E[2]}, ${F})`,$=`rgba(${E[0]}, ${E[1]}, ${E[2]}, ${N})`;return{wordHighlight:m,sentenceHighlight:I,wordUnderline:c,wordShadow:$}}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(B7)){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 J7(Q,Y={}){let J=h1(Y.strictness),G=Y.source??"tools",X=y0(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,I7.SENTENCE_FALLBACK_SELECTOR)}highlightTTSWordElementFallbacks(Q){if(typeof Element>"u")return;this.highlightElementFallbacks(Q,"data-pie-tts-word-element",this.ttsWordElementHighlights,I7.WORD_FALLBACK_SELECTOR)}highlightElementFallbacks(Q,Y,J,G){for(let X of Q){let Z=X.commonAncestorContainer.nodeType===Node.ELEMENT_NODE?X.commonAncestorContainer:X.commonAncestorContainer.parentElement;if(!Z)continue;let j=[],q=X.startContainer.nodeType===Node.ELEMENT_NODE?X.startContainer:X.startContainer.parentElement,U=X.endContainer.nodeType===Node.ELEMENT_NODE?X.endContainer:X.endContainer.parentElement;for(let V of[q,U]){let D=V;while(D){if(D.matches?.(G))j.push(D);D=D.parentElement}}if(Z.matches?.(G))j.push(Z);j.push(...Array.from(Z.querySelectorAll(G)));for(let V of new Set(j)){try{if(!X.intersectsNode(V)&&!V.contains(q)&&!V.contains(U))continue}catch{continue}V.setAttribute(Y,"true"),J.add(V)}}}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=K7.YELLOW){let J=`annotation-${this.nextAnnotationId++}`,G=Q.cloneRange(),X={id:J,range:G,type:h.ANNOTATION,color:Y,timestamp:Date.now()};this.annotations.set(J,X);let Z=this.colorHighlights.get(Y);if(Z)Z.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 Z=this.colorHighlights.get(Y);if(Z)Z.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=K7.YELLOW){if(!this.supported)return;switch(Y){case h.TTS_WORD:case h.TTS_SENTENCE:{let G=Y===h.TTS_WORD?this.ttsWordHighlight:this.ttsSentenceHighlight;if(G){if(G.clear(),G.add(Q),Y===h.TTS_WORD){for(let X of this.ttsWordElementHighlights)X.removeAttribute("data-pie-tts-word-element");this.ttsWordElementHighlights.clear(),this.highlightTTSWordElementFallbacks([Q])}}break}case h.ANNOTATION:this.addAnnotation(Q,J);break}}clearHighlights(Q){if(!this.supported)return;switch(Q){case h.TTS_WORD:this.clearTTSWord();break;case h.TTS_SENTENCE:this.clearTTSSentence();break;case h.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=((Z)=>{let j=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(Z);return j?{r:parseInt(j[1],16),g:parseInt(j[2],16),b:parseInt(j[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 t8(Q){return(...Y)=>{console.debug(`[${Q}]`,...Y)}}var r=t8("ToolCoordinator"),G7;(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"})(G7||(G7={}));class s1{config;tools=new Map;layerCounters=new Map;listeners=new Set;visibilityState=new Map;constructor(Q={}){this.config=Q,this.layerCounters.set(G7.BASE,0),this.layerCounters.set(G7.TOOL,0),this.layerCounters.set(G7.MODAL,0),this.layerCounters.set(G7.CONTROL,0),this.layerCounters.set(G7.HIGHLIGHT,0)}subscribe(Q){return this.listeners.add(Q),()=>{this.listeners.delete(Q)}}notifyListeners(){this.listeners.forEach((Q)=>Q())}registerTool(Q,Y,J,G=G7.MODAL){if(r("registerTool called:",{id:Q,name:Y,hasElement:!!J,layer:G}),this.tools.has(Q)){r(`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}),r("Tool registered without element:",Q);return}let Z=G+this.getNextLayerOffset(G);J.style.zIndex=String(Z),J.style.display=X?"":"none";let j=()=>this.bringToFront(J);if(J.addEventListener("mousedown",j),this.tools.set(Q,{id:Q,name:Y,element:J,layer:G,isVisible:X,baseZIndex:Z,mouseDownHandler:j}),X)this.bringToFront(J);r("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){r(`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){r(`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){r("toggleTool called for:",Q);let Y=this.tools.get(Q);if(!Y){r(`Tool ${Q} not found. Registered tools:`,Array.from(this.tools.keys()));return}if(r("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){r(`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 c0=/^[a-z][a-z0-9+.-]*:/i,d0=new Set(["http:","https:","data:","blob:"]);function l0(Q){if(typeof Q!=="string")return!1;let Y=Q.trim();if(!Y)return!1;if(Y.startsWith("//")||!c0.test(Y))return!0;let J=Y.slice(0,Y.indexOf(":")+1).toLowerCase();return d0.has(J)}function e8(Q){if(!Array.isArray(Q))return[];let Y=[];for(let J of Q){if(!J||typeof J!=="object")continue;let G=J;if(!l0(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((Z)=>Z.src===X.src))continue;Y.push(X)}return Y}function Q9(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 Y9(Q){if(typeof Q!=="string")return;return Q.trim()||void 0}function J9(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 G9(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=e8(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:Q9(Y.fragment),label:Y9(J.label)}}var i0=new Set(["speak","p","s","emphasis","prosody","say-as","voice","lang"]),X9=new Set(["audio","phoneme"]),j9=(Q)=>Q.replace(/"/g,'"').replace(/'/g,"'").replace(/</g,"<").replace(/>/g,">").replace(/ /g," ").replace(/ /g," ").replace(/&/g,"&"),G1=(Q,Y,J)=>{for(let G=0;G<Y.length;G++)Q.push({char:Y[G],rawOffset:J===null?null:J+G})},s0=(Q,Y,J)=>{let G=Y.slice(J).match(/^&(quot|apos|lt|gt|nbsp|amp|#160);/i);if(!G)return 0;return G1(Q,j9(G[0]),J),G[0].length},Z9=(Q)=>{Q.push({char:" ",rawOffset:null})},n0=(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,Z]of Y)if(Z>=J.length)Y.delete(X);return{text:J.join(""),rawToSpokenOffsetMap:Y}},r0=(Q)=>{return Q.match(/^<\/?\s*([A-Za-z0-9:-]+)/)?.[1]?.toLowerCase()||""},o0=(Q,Y)=>{let J=new RegExp(`${Y}\\s*=\\s*("([^"]*)"|'([^']*)')`,"i"),G=Q.match(J);return j9(G?.[2]??G?.[3]??"")||null},X1=(Q)=>{let Y=[],J=!1,G=!1,X=0;while(X<Q.length){let j=Q[X];if(j!=="<"){if(j==="&"){let F=s0(Y,Q,X);if(F>0){X+=F;continue}}G1(Y,j,X),X++;continue}let q=Q.indexOf(">",X+1);if(q<0){G1(Y,j,X),X++;continue}G=!0;let U=Q.slice(X,q+1),V=r0(U),D=/^<\s*\//.test(U),_=/\/\s*>$/.test(U);if(!D&&V==="sub"){let F=o0(U,"alias");if(!F){J=!0,X=q+1;continue}G1(Y,F,null);let N=Q.toLowerCase().indexOf("</sub>",q+1);X=N>=0?N+6:q+1;continue}if(!D&&V==="break"){Z9(Y),X=q+1;continue}if(!D&&X9.has(V)){if(J=!0,_){X=q+1;continue}}if(V&&!i0.has(V)&&!X9.has(V)&&V!=="break"&&V!=="sub")J=!0;if(!D&&(V==="p"||V==="s"))Z9(Y);X=q+1}let Z=n0(Y);return{spokenText:f(Z.text),rawToSpokenOffsetMap:Z.rawToSpokenOffsetMap,unsupportedSemantic:J,hasMarkup:G}};var a0=Z1(),K9=new Map([["zero","0"],["one","1"],["two","2"],["three","3"],["four","4"],["five","5"],["six","6"],["seven","7"],["eight","8"],["nine","9"],["ten","10"]]),t0=[{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}],n1=(Q)=>{let Y=[];for(let J of Q.matchAll(a0)){let G=J[0],X=J.index??0;Y.push({text:G,normalized:G.toLowerCase(),start:X,end:X+G.length})}return Y},r1=(Q)=>K9.get(Q.normalized)||Q.normalized,e0=(Q,Y)=>{let J=[];for(let G=0;G<Q.length;G++){for(let X=0;X<Y.length;X++){let Z=r1(Q[G]),j=r1(Y[X]);if(Z===j)J.push({spokenStartToken:G,spokenEndToken:G+1,visibleToken:X,score:10})}for(let X of t0){let Z=Q.slice(G,G+X.phrase.length);if(Z.length!==X.phrase.length)continue;if(!Z.every((j,q)=>j.normalized===X.phrase[q]))continue;for(let j=0;j<Y.length;j++){if(Y[j].normalized!==X.visible)continue;J.push({spokenStartToken:G,spokenEndToken:G+X.phrase.length,visibleToken:j,score:X.score})}}}return J},QQ=(Q,Y)=>{let J=e0(Q,Y).sort((U,V)=>Q[U.spokenStartToken].start-Q[V.spokenStartToken].start||Y[U.visibleToken].start-Y[V.visibleToken].start),G=Array(J.length).fill(0),X=Array(J.length).fill(-1);for(let U=0;U<J.length;U++){let V=J[U];G[U]=V.score;for(let D=0;D<U;D++){let _=J[D];if(_.spokenEndToken<=V.spokenStartToken&&_.visibleToken<V.visibleToken){let F=V.spokenStartToken-_.spokenEndToken,N=V.visibleToken-_.visibleToken-1,O=Math.max(0,Math.abs(F-N)-2),w=G[D]+V.score-O;if(w>G[U])G[U]=w,X[U]=D}}}let Z=-1;for(let U=0;U<G.length;U++)if(Z<0||G[U]>G[Z])Z=U;if(Z<0)return[];let j=[],q=Z;while(q>=0)j.unshift(J[q]),q=X[q];return j.map((U)=>{let V=Q[U.spokenStartToken],D=Q[U.spokenEndToken-1],_=Y[U.visibleToken];return{spokenStart:V.start,spokenEnd:D.end,visibleStart:_.start,visibleEnd:_.end,score:U.score}})},YQ=(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((Z,j)=>Z+j.score,0)/Q.length/10;return Math.min(1,G*X)},j1=(Q)=>{let Y=X1(Q.speechText),J=f(Q.visibleText),G=Y.spokenText,X=n1(G),Z=n1(J),j=Y.unsupportedSemantic?[]:QQ(X,Z),q=YQ(j,X,Z),U=G===J&&G.length>0,V=j.length===1&&j[0].score===10&&X.length<=2&&Z.length<=2,D=Y.unsupportedSemantic?"region-fallback":U?"exact-word":j.length>=2||V?q>=0.12?"anchor-span":"region-fallback":"region-fallback",_=Y.unsupportedSemantic?"unsupported":Y.hasMarkup?"raw-ssml":"plain-spoken-text";return{speechText:Q.speechText,spokenText:G,visibleText:J,playbackMode:D,boundaryOffsetMode:_,anchors:j,confidence:q,spokenTokens:X,visibleTokens:Z,rawToSpokenOffsetMap:Y.rawToSpokenOffsetMap}},o1=(Q,Y)=>Q.find((J)=>J.start<=Y&&Y<J.end)||null,V9=(Q)=>{if(!Q)return null;if(/^<[^>]+>$/.test(Q.trim()))return null;let Y=n1(Q)[0];if(!Y)return null;return K9.get(Y.normalized)||Y.normalized},q9=(Q,Y,J)=>{let G=V9(J);if(!Y||!G)return!1;let X=o1(Q.spokenTokens,Y.start);if(!X)return!1;return r1(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},U9=(Q,Y,J)=>{let G=W9(Q,Y);if(G===null)return null;let X=W9(Q,Math.max(Y,Y+J-1)),Z=o1(Q.spokenTokens,G),j=X!==null&&X>=G?X-G+1:Z?Z.end-G:J;return{start:G,length:Math.max(1,j)}},D9=(Q,Y,J)=>{if(Y<0||Y>=Q.spokenText.length)return null;let G=o1(Q.spokenTokens,Y);if(!G)return null;return{start:Y,length:Math.min(J,G.end-Y)}},B9=(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 Z=U9(Q,Y,X),j=D9(Q,Y,X);if(G){if(q9(Q,Z,G))return Z;if(q9(Q,j,G))return j;if(V9(G))return null}return Z||j}return D9(Q,Y,X)||U9(Q,Y,X)},_9=(Q,Y)=>{if(Q.playbackMode==="region-fallback")return null;let J=Q.anchors.find((Z)=>Z.spokenStart<=Y&&Y<Z.spokenEnd);if(J)return{start:J.visibleStart,end:J.visibleEnd};let G=null,X=null;for(let Z of Q.anchors){if(Z.spokenEnd<=Y){G=Z;continue}if(Z.spokenStart>Y){X=Z;break}}if(G&&X)return{start:Math.min(G.visibleStart,X.visibleStart),end:Math.max(G.visibleEnd,X.visibleEnd)};return null};var JQ=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"]]]),GQ=new Map([["","function-application"],["","implicit-multiply"],["","invisible-separator"],["","invisible-plus"]]),F9=new Map([["2",["squared"]],["3",["cubed"]]]),XQ=new Map([["msqrt","radical"],["mroot","radical"],["msub","subscript"],["msubsup","subsupscript"],["munder","underscript"],["mover","overscript"],["munderover","underoverscript"],["mmultiscripts","multiscript"],["menclose","enclosure"]]),ZQ=(Q)=>Q.replace(/\s+/g," ").trim(),V7=(Q)=>(Q.localName||Q.tagName||"").toLowerCase(),jQ=(Q)=>Q.nodeType===Node.ELEMENT_NODE,L7=(Q)=>Array.from(Q.childNodes).filter(jQ),a1=(Q)=>ZQ(Q.textContent||""),t=(Q,Y)=>({type:"element-range",quality:Y,element:Q}),qQ=(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"}},WQ=(Q,Y)=>{if(Y==="operator"){if(Q==="−")return"-";return Q}return Q.toLowerCase()},UQ=(Q,Y,J)=>{if(J==="fraction")return["over","divided by"];if(J==="superscript")return F9.get(Q)??[];if(Q==="|")return["absolute value"];if(Y==="operator")return JQ.get(Q)||[];return[]},B7=(Q)=>{let Y=Q.normalized??WQ(Q.text,Q.kind||"unknown");return{id:`math-token-${Q.state.nextId++}`,kind:Q.kind,role:Q.role,text:Q.text,normalized:Y,spokenAliases:UQ(Q.text,Q.kind,Q.role),sourceElement:Q.sourceElement,path:Q.path,target:Q.target||t(Q.sourceElement,"element-range"),optional:Q.optional}},_7=(Q,Y,J="tokens")=>{Q[J].push(Y)},A9=(Q,Y,J)=>{L7(Q).forEach((G,X)=>e(G,Y,`${J}/${V7(G)}[${X}]`))},DQ=(Q,Y,J)=>{let G=L7(Q);if(G[0])e(G[0],Y,`${J}/numerator`);if(_7(Y,B7({state:Y,kind:"structure",role:"fraction",text:"/",sourceElement:Q,path:J,target:t(Q,"element-range")})),G[1])e(G[1],Y,`${J}/denominator`)},KQ=(Q,Y,J)=>{let G=Q.getAttribute("open")||"(",X=Q.getAttribute("close")||")";_7(Y,B7({state:Y,kind:"operator",role:G==="|"?"absolute-value-fence":"open-fence",text:G,sourceElement:Q,path:`${J}/open`,target:t(Q,"element-range")})),A9(Q,Y,J),_7(Y,B7({state:Y,kind:"operator",role:X==="|"?"absolute-value-fence":"close-fence",text:X,sourceElement:Q,path:`${J}/close`,target:t(Q,"element-range")}))},VQ=(Q,Y,J)=>{let G=L7(Q);if(G[0])e(G[0],Y,`${J}/base`);let X=G[1];if(!X)return;let Z=a1(X);if(F9.has(Z)){_7(Y,B7({state:Y,kind:"structure",role:"superscript",text:Z,normalized:Z,sourceElement:X,path:`${J}/exponent`,target:t(Q,"element-range")}));return}e(X,Y,`${J}/exponent`)},BQ=(Q,Y,J,G)=>{_7(Y,B7({state:Y,kind:"structure",role:G,text:a1(Q)||G,normalized:`\x00${G}`,sourceElement:Q,path:J,target:t(Q,"element-range")}))},_Q=(Q,Y,J)=>{let G=0;for(let X of L7(Q)){if(V7(X)==="mtr"||V7(X)==="mlabeledtr")G++,_7(Y,B7({state:Y,kind:"layout",role:"table-row",text:`row-${G}`,normalized:`row-${G}`,sourceElement:X,path:`${J}/row[${G}]`,target:t(X,"region-fallback")}),"layoutTargets");e(X,Y,`${J}/${V7(X)}[${G}]`)}},FQ=(Q,Y,J)=>{let G=a1(Q);if(!G)return;let X=qQ(V7(Q)),Z=X==="operator"?GQ.get(G):void 0,j=Z??(X==="operator"&&(G==="("||G===")")?"grouping-fence":X);_7(Y,B7({state:Y,kind:X,role:j,text:G,sourceElement:Q,path:J,target:Z&&Q.parentElement?t(Q.parentElement,"region-fallback"):void 0,optional:Boolean(Z)||j==="grouping-fence"}))},e=(Q,Y,J)=>{let G=V7(Q);switch(G){case"annotation":case"annotation-xml":return;case"semantics":{let X=L7(Q).find((Z)=>{let j=V7(Z);return j!=="annotation"&&j!=="annotation-xml"});if(X)e(X,Y,`${J}/presentation`);return}case"mi":case"mn":case"mo":case"mtext":case"ms":case"mspace":FQ(Q,Y,J);return;case"mfrac":DQ(Q,Y,J);return;case"msup":VQ(Q,Y,J);return;case"mfenced":KQ(Q,Y,J);return;case"mtable":_Q(Q,Y,J);return;case"mphantom":return;case"maction":{let X=L7(Q)[0];if(X)e(X,Y,`${J}/action`);return}default:{let X=XQ.get(G);if(X){BQ(Q,Y,J,X);return}A9(Q,Y,J)}}},H9=(Q)=>{let Y={tokens:[],layoutTargets:[],nextId:0};return e(Q,Y,"/math"),{tokens:Y.tokens,layoutTargets:Y.layoutTargets,expressionTarget:t(Q,"region-fallback")}};var M9=(Q)=>{if(!Q.boundary)return null;return Q.alignment.segments.find((J)=>J.speechTokenIds.includes(Q.boundary.token.id))?.target||null};var AQ=(Q)=>{let Y=[],J=new Set,G=(X)=>{let Z=X.toLowerCase().trim().split(/\s+/).filter(Boolean);if(Z.length===0)return;let j=Z.join(" ");if(J.has(j))return;J.add(j),Y.push(Z)};G(Q.normalized);for(let X of Q.spokenAliases)G(X);return Y},N9=(Q,Y,J)=>{let G=0;for(let X of J){if(X.length<=G)continue;let Z=!0;for(let j=0;j<X.length;j++){let q=Q[Y+j];if(!q||q.normalized.toLowerCase()!==X[j]){Z=!1;break}}if(Z)G=X.length}return G},HQ=(Q,Y)=>{let J=[],G=0;for(let X of Y){let Z=AQ(X);if(X.optional){let j=N9(Q,G,Z);if(j>0)J.push({speechTokens:Q.slice(G,G+j),math:X}),G+=j;continue}while(G<Q.length){let j=N9(Q,G,Z);if(j>0){J.push({speechTokens:Q.slice(G,G+j),math:X}),G+=j;break}G++}}return J},MQ=(Q,Y,J)=>{let G=J.filter((j)=>!j.optional).length,X=Q.filter((j)=>!j.math.optional).length,Z=Q.reduce((j,q)=>j+q.speechTokens.length,0);return G>0&&X===G&&Z===Y.length},NQ=(Q)=>Q.map(({speechTokens:Y,math:J})=>({speechTokenIds:Y.map((G)=>G.id),mathTokenIds:[J.id],score:1,confidence:1,target:J.target})),O9=(Q)=>{let Y=Q.minExactWordConfidence??0.95,J=HQ(Q.speech.tokens,Q.math.tokens),G=MQ(J,Q.speech.tokens,Q.math.tokens)?1:0;return{segments:G>=Y?NQ(J):[],confidence:G,fallbackTarget:Q.math.expressionTarget}};var z9=Z1(),OQ=new Map([["zero","0"],["one","1"],["two","2"],["three","3"],["four","4"],["five","5"],["six","6"],["seven","7"],["eight","8"],["nine","9"],["ten","10"]]),L9=(Q)=>{let Y=Q.toLowerCase();return OQ.get(Y)||Y},zQ=(Q)=>{let Y=[];for(let J of Q.matchAll(z9)){let G=J[0],X=J.index??0;Y.push({id:`speech-token-${Y.length}`,text:G,normalized:L9(G),start:X,end:X+G.length,sourceStart:X,sourceEnd:X+G.length,coordinateSystem:"normalized-speech"})}return Y},F7=(Q)=>{let Y=X1(Q.speechText);return{speechText:Q.speechText,spokenText:Y.spokenText,tokens:zQ(Y.spokenText),rawToSpokenOffsetMap:Y.rawToSpokenOffsetMap,boundaryOffsetSpace:Y.unsupportedSemantic?"unsupported":Y.hasMarkup?"raw-ssml":"plain-spoken-text",unsupportedSemantic:Y.unsupportedSemantic,hasMarkup:Y.hasMarkup}},Q8=(Q)=>{if(!Q)return null;if(/^<[^>]+>$/.test(Q.trim()))return null;let Y=Q.match(z9);if(!Y?.[0])return null;return L9(Y[0])},LQ=(Q,Y)=>Q.find((J)=>J.start<=Y&&Y<J.end)||null,PQ=(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},t1=(Q,Y,J)=>{if(Y===null)return null;let G=LQ(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}},e1=(Q,Y)=>{let J=Q8(Y);return Boolean(Q&&J&&Q.token.normalized===J)},Y8=(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=t1(Q.tokenization,PQ(Q.tokenization,Q.position),Y),G=t1(Q.tokenization,Q.position>=0&&Q.position<Q.tokenization.spokenText.length?Q.position:null,Y);if(e1(J,Q.boundaryWord))return{...J,confidence:1};if(e1(G,Q.boundaryWord))return{...G,confidence:1};if(Q.boundaryWord&&Q8(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=t1(Q.tokenization,Q.position>=0&&Q.position<Q.tokenization.spokenText.length?Q.position:null,Y);if(e1(J,Q.boundaryWord))return{...J,confidence:1};if(Q.boundaryWord&&Q8(Q.boundaryWord))return null;return J};var P7=(Q)=>{let Y=F7({speechText:Q.speechText}),J=H9(Q.mathElement);return{speech:Y,math:J,result:O9({speech:Y,math:J})}};var w9=(Q,Y)=>{let J=P9({tokenization:Q.speech,position:Y.position,length:Y.length,boundaryWord:Y.boundaryWord});return M9({alignment:Q.result,boundary:J})},$9=(Q,Y)=>{if(!Y.boundaryWord||/^<[^>]+>$/.test(Y.boundaryWord.trim()))return null;let J=F7({speechText:Y.boundaryWord}).tokens[0];if(!J)return null;let G=Q.math.tokens.filter((X)=>{let Z=J.normalized.toLowerCase();return X.normalized.toLowerCase()===Z||X.spokenAliases.some((j)=>j.toLowerCase()===Z)});return G.length===1?G[0].target:null};var wQ=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"]),$Q=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"]),b9=(Q)=>Q.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">"),bQ=(Q)=>b9(Q).replace(/"/g,"""),RQ=(Q,Y)=>{let J=Q.toLowerCase(),G=Y.trim().toLowerCase();if(J.startsWith("on"))return!0;if(!$Q.has(J))return!0;if(G.includes("javascript:"))return!0;if(G.includes("data:text/html"))return!0;return!1},EQ=(Q)=>{let Y=Q.localName.toLowerCase();if(!wQ.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"},R9=(Q)=>{if(Q.nodeType===Node.TEXT_NODE)return b9(Q.textContent||"");if(Q.nodeType===Node.COMMENT_NODE)return"";if(Q.nodeType!==Node.ELEMENT_NODE)return null;let Y=Q;if(!EQ(Y))return null;let J=Y.localName.toLowerCase(),G=[];for(let j of Array.from(Y.attributes)){let q=j.name.toLowerCase();if(RQ(q,j.value))continue;if(q==="xmlns"&&j.value!=="http://www.w3.org/1998/Math/MathML")return null;G.push(`${q}="${bQ(j.value)}"`)}if(J==="math"&&!G.some((j)=>j.startsWith("xmlns=")))G.unshift('xmlns="http://www.w3.org/1998/Math/MathML"');let X=[];for(let j of Array.from(Y.childNodes)){let q=R9(j);if(q===null)return null;X.push(q)}let Z=G.length>0?` ${G.join(" ")}`:"";return`<${J}${Z}>${X.join("")}</${J}>`},SQ=(Q)=>{if(typeof DOMParser<"u")return new DOMParser().parseFromString(Q,"application/xml");return null},q1=(Q)=>{let Y=String(Q||"").trim();if(!Y)return null;let J=SQ(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 R9(G)};var S9=(Q)=>({chars:[],map:new Map,position:0,inLeadingWhitespace:!0,lastCharWasWhitespace:!1,lastMapped:null,options:Q}),T9=(Q)=>Q.classList?.contains("MathJax")||Q.tagName?.toLowerCase()==="mjx-container",C9=(Q)=>Q.tagName?.toLowerCase()==="mjx-assistive-mml",y9=(Q)=>{let Y=Q.tagName?.toLowerCase();return Y==="annotation"||Y==="annotation-xml"},TQ=(Q)=>{let Y=Q.getAttribute("data-mathml");return Y&&Y.trim()?Y:null},CQ=(Q)=>{return Q.querySelector("mjx-assistive-mml math")?.outerHTML||null},yQ=(Q)=>{if(Q.tagName.toLowerCase()==="math")return q1(Q.outerHTML);let Y=TQ(Q);if(Y){let J=q1(Y);if(J)return J}if(T9(Q)){let J=CQ(Q);if(J){let G=q1(J);if(G)return G}}return null};var fQ=new Set(["P","H1","H2","H3","H4","H5","H6","LI","TD","TH","DD","DT","FIGCAPTION","LABEL","BUTTON"]),xQ=new Set(["heading","listitem","option","radio","row","cell","columnheader","rowheader"]),IQ=(Q,Y)=>{let J=Q.parentElement,G=null;while(J&&J!==Y){let X=(J.getAttribute("role")||"").toLowerCase(),Z=J.tagName.toUpperCase();if(fQ.has(Z)||xQ.has(X)){G=J;break}J=J.parentElement}return G||Y},kQ=(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")||T9(Q),A7=(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++},f9=(Q,Y)=>{if(Q.inLeadingWhitespace||Q.lastCharWasWhitespace||Q.chars.length===0)return!1;let J=Q.chars[Q.chars.length-1];return E9(J,Y,Q.options)},x9=(Q,Y)=>{let J=Y.textContent||"",G=!1;for(let X=0;X<J.length;X++){let Z=J[X],j=/\s/.test(Z);if(Q.inLeadingWhitespace){if(!j)Q.inLeadingWhitespace=!1,A7(Q,Z,{node:Y,offset:X}),G=!0,Q.lastCharWasWhitespace=!1;continue}if(j){if(!Q.lastCharWasWhitespace)A7(Q," ",{node:Y,offset:X});Q.lastCharWasWhitespace=!0;continue}if(!G&&f9(Q,Z))A7(Q," ",{node:Y,offset:X});A7(Q,Z,{node:Y,offset:X}),G=!0,Q.lastCharWasWhitespace=!1}},vQ=(Q,Y)=>{for(let J=0;J<Y.text.length;J++){let G=Y.text[J],X=/\s/.test(G),Z=Y.map.get(J)||null,j=Z?.node||Q.lastMapped?.node||null,q=Z?.offset??Q.lastMapped?.offset??0,U=Z?{node:Z.node,offset:Z.offset}:j?{node:j,offset:q}:null;if(Q.inLeadingWhitespace){if(X)continue;Q.inLeadingWhitespace=!1}if(X){if(!Q.lastCharWasWhitespace)A7(Q," ",U);Q.lastCharWasWhitespace=!0;continue}if(J===0&&f9(Q,G))A7(Q," ",U);if(A7(Q,G,U),Q.lastCharWasWhitespace=!1,Z)Q.map.set(Q.position-1,{node:Z.node,offset:Z.offset}),Q.lastMapped={node:Z.node,offset:Z.offset};else if(j)Q.map.set(Q.position-1,{node:j,offset:q})}},hQ=(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 j=X.textContent||"";if(j.trim())J.push(j);return}if(X.nodeType!==1)return;let Z=X;if(y9(Z))return;for(let j of Array.from(Z.childNodes))G(j)};return G(Y.documentElement),f(J.join(" "))},uQ=(Q,Y,J)=>{let G=S9(J),X=(q)=>{if(k7(q,Q))return;if(q.nodeType===3){x9(G,q);return}if(q.nodeType!==1)return;let U=q;if(C9(U)||y9(U))return;for(let V of Array.from(U.childNodes))X(V)};X(Q),I9(G);let Z=f(G.chars.join(""));if(Z)return{text:Z,map:G.map};let j=hQ(Y);if(!j)return w7(Q,J);return{text:j,map:new Map}},I9=(Q)=>{while(Q.chars.length>0&&/\s/.test(Q.chars[Q.chars.length-1]))Q.chars.pop(),Q.position--,Q.map.delete(Q.position)},mQ=(Q,Y)=>{let J=S9(Y),G=[],X=0,Z,j=!1,q=()=>{let D=f(J.chars.slice(X,J.chars.length).join(""));if(D)G.push({type:"text",text:D,sourceElement:Z});X=J.chars.length,Z=void 0},U=(D)=>{if(k7(D,Q))return;if(D.nodeType===Node.TEXT_NODE){let N=IQ(D,Q);if(Z&&N!==Z)q();Z=N,x9(J,D);return}if(D.nodeType!==Node.ELEMENT_NODE)return;let _=D;if(C9(_))return;let F=yQ(_);if(F){q();let N=uQ(_,F,Y);vQ(J,N);let O=f(N.text);G.push({type:"math",mathml:F,fallbackText:O,sourceElement:_}),X=J.chars.length,j=!0;return}for(let N of Array.from(_.childNodes))U(N)};for(let D of Array.from(Q.childNodes))U(D);I9(J),q();let V=J.chars.join("");while(J.map.has(V.length))J.map.delete(V.length);return{visibleText:V,map:J.map,chunks:G,containsMathMarkup:j}},H7=(Q,Y)=>{if(!kQ(Q)){let{text:J,map:G}=w7(Q,Y);return{visibleText:J,map:G,chunks:J?[{type:"text",text:J}]:[],containsMathMarkup:!1}}return mQ(Q,Y)};var pQ=(Q,Y)=>U1([Q],Y),gQ=(Q)=>(Q||"en").split("-")[0].toLowerCase()||"en",cQ=new Set(["H1","H2","H3","H4","H5","H6","LI","LABEL","BUTTON"]),dQ=new Set(["heading","listitem","option","radio"]),lQ=(Q)=>{if(Q.type!=="text"||!Q.sourceElement)return!1;let Y=Q.sourceElement.tagName.toUpperCase(),J=(Q.sourceElement.getAttribute("role")||"").toLowerCase();return cQ.has(Y)||dQ.has(J)},J8=async(Q)=>{let Y=Q.resolveMathSpeech??pQ,{visibleText:J}=Q,G=[],X=0,Z=(q)=>{let U=f(q),V=J.indexOf(U,X),D=V>=0?V:X,_=D+U.length;return X=_,{start:D,end:_}},j=[];for(let q=0;q<Q.chunks.length;q++){let U=Q.chunks[q];if(U.type==="text"){let N=lQ(U)?[{text:U.text,offset:0}]:W1(U.text,{locale:Q.language});for(let O of N){let w=f(O.text);if(!w)continue;let k=Z(w);G.push({sourceChunkIndex:q,segment:{kind:"prose",spokenText:w,visibleText:w,visibleSpan:k}}),j.push(w)}continue}let V=Z(U.fallbackText),D=await Y(U,{language:Q.language,produceSsml:Q.produceSsml,mathSpeech:Q.mathSpeech}),_=!D.speechText,F=D.speechText||U.fallbackText;G.push({sourceChunkIndex:q,segment:{kind:"math",spokenText:F,mathml:U.mathml,fallbackText:U.fallbackText,visibleSpan:V,usedFallback:_,ssml:D.ssml}}),j.push(F)}return{segments:G,locale:gQ(Q.language),visibleText:J,plainSpeechText:f(j.join(" "))}};var iQ=(Q)=>(Q||"en").split("-")[0].toLowerCase()||"en",sQ="sre-v1",nQ=256,G8=(Q)=>{if(Array.isArray(Q))return`array:[${Q.map(G8).join(",")}]`;if(Q&&typeof Q==="object")return`object:{${Object.entries(Q).sort(([Y],[J])=>Y.localeCompare(J)).map(([Y,J])=>`${JSON.stringify(Y)}:${G8(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)}`},k9=(Q,Y,J,G)=>`${sQ}\x00${iQ(Q)}\x00${Y?"ssml":"plain"}\x00${G8(J??null)}\x00${G}`,X8=(Q={})=>{let Y=Math.max(1,Q.maxEntries??nQ),J=Q.resolve??((Z,j)=>U1([Z],j)),G=new Map,X=(Z,j)=>{G.delete(Z),G.set(Z,j);while(G.size>Y){let q=G.keys().next().value;if(q!==void 0)G.delete(q)}};return async(Z,j)=>{let q=D1(j.mathSpeech),U=j.produceSsml===!0,V=k9(j.language,U,q,Z.mathml),D=G.get(V);if(D)return G.delete(V),G.set(V,D),D;let _=await J(Z,{...j,mathSpeech:q});if(U&&_.ssml&&Y>1)X(k9(j.language,!1,q,Z.mathml),{speechText:_.speechText,usedMathSpeech:_.usedMathSpeech,usedFallback:_.usedFallback});return X(V,_),_}};var rQ=(Q)=>{if(!Q||/^<[^>]+>$/.test(Q.trim()))return null;return F7({speechText:Q}).tokens[0]?.normalized||null},oQ=(Q,Y)=>{let J=F7({speechText:Q.speechText});if(!Number.isFinite(Y.position))return{boundary:null,spokenText:J.spokenText};let G=Y8({tokenization:J,position:Y.position,length:Y.length,boundaryWord:Y.word});return{boundary:G?{start:G.start,length:G.length}:null,spokenText:J.spokenText}},aQ=(Q,Y,J)=>{if(!J)return!0;return F7({speechText:Q}).tokens.find((X)=>X.start<=Y&&Y<X.end)?.normalized===J},v9=(Q,Y)=>{let J=rQ(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=B9(Q.catalogAlignment,Y.position,Y.length,Y.word),X=Q.catalogAlignment.spokenText;else{let Z=oQ(Q,Y);G=Z.boundary,X=Z.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(!aQ(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 M7=(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 u9=new Map([["mi","mjx-mi"],["mn","mjx-mn"],["mo","mjx-mo"],["mtext","mjx-mtext"]]),Z8="mi,mn,mo,mtext",m9="mjx-mi,mjx-mn,mjx-mo,mjx-mtext",p9=["mjx-mfrac","mjx-msqrt","mjx-mroot","mjx-mtable","mjx-munder","mjx-mover","mjx-munderover"].join(","),g9=(Q)=>{if(Q.type==="text-range")return Q.node.parentElement;return Q.element},K1=(Q)=>{let Y=Q;while(Y){if(Y.localName?.toLowerCase()==="mjx-container")return Y;Y=Y.parentElement}return null},h9=(Q)=>{if(!Q)return!1;if(K1(Q))return!1;return!W8(Q)},c9=(Q)=>{let Y=Q.getBoundingClientRect?.();return Boolean(Y&&Y.width>0&&Y.height>0)},j8=(Q)=>{let Y=Q;while(Y){if(Y.localName?.toLowerCase()==="math")return Y;Y=Y.parentElement}return null},d9=(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=u9.get(Q[J].localName.toLowerCase());if(!G)return!1;if(Y[J].localName.toLowerCase()!==G)return!1}return!0},tQ=(Q,Y)=>{if(!Q)return null;if(!u9.has(Q.localName.toLowerCase()))return null;if(Y.querySelector(p9))return null;let J=j8(Q),G=Y.querySelector("mjx-math");if(!J||!G)return null;let X=Array.from(J.querySelectorAll(Z8)),Z=X.indexOf(Q);if(Z<0)return null;let j=Array.from(G.querySelectorAll(m9));if(!d9(X,j))return null;let q=j[Z];if(!q||!c9(q))return null;return q},l9=(Q)=>{let Y=K1(Q);if(Y){if(Y.querySelector(p9))return"expression";let X=j8(Q)??Q,Z=Y.querySelector("mjx-math");if(!Z)return"expression";let j=Array.from(X.querySelectorAll(Z8)),q=Array.from(Z.querySelectorAll(m9));if(!d9(j,q))return"expression";return q.some((U)=>c9(U))?"token":"expression"}let J=j8(Q)??Q;return Array.from(J.querySelectorAll(Z8)).some((X)=>!W8(X))?"token":"expression"},q8=(Q)=>{let Y=g9(Q),J=K1(Y);if(J){let G=tQ(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(!h9(Q.node.parentElement))return null;return{type:"text-range",quality:"semantic-token",node:Q.node,startOffset:Q.startOffset,endOffset:Q.endOffset}}if(!h9(Q.element))return null;return{type:"element",quality:Q.quality==="region-fallback"?"expression":"semantic-token",element:Q.element}},i9=q8,s9=()=>{let Q=new WeakMap;return(Y)=>{let J=g9(Y),G=K1(J);if(!J||!G)return q8(Y);if(Q.has(J))return Q.get(J)??null;let X=q8(Y);return Q.set(J,X),X}};var n9=(Q,Y,J,G=Q.mathAlignments,X=i9)=>{if(Y.chunkSpokenStart===null||Y.chunkSpokenEnd===null)return null;let Z=null;for(let j of G){let q=w9(j.alignment,{position:Y.chunkSpokenStart,length:Math.max(1,Y.chunkSpokenEnd-Y.chunkSpokenStart),boundaryWord:J.word})||$9(j.alignment,{boundaryWord:J.word});if(!q)continue;let U=X(q);if(!U)continue;if(U.quality==="semantic-token")return U;Z??=U}return Z};var V1=(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 Z=document.createRange();return Z.setStart(G.node,G.offset),Z.setEnd(X.node,X.offset+1),Z}catch{return null}};var r9=(Q,Y)=>{if(!Q.catalogAlignment||Y.chunkSpokenStart===null)return null;let J=_9(Q.catalogAlignment,Y.chunkSpokenStart);if(!J)return null;let G=V1(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 eQ=(Q)=>Q.regionRange?{type:"range",quality:"region",range:Q.regionRange}:Q.regionElement?{type:"element",quality:"region",element:Q.regionElement}:null,o9=(Q,Y=Q.chunk.mathAlignments)=>{if(Y.length!==1)return null;let J=Y[0]?.alignment.result.fallbackTarget;return J?Q.renderedMathTargetResolver(J):null},Q3=(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}})},a9=()=>({activeTarget:null,regionTarget:null,quality:"region",confidence:0,reason:"boundary chunk id was not found"}),t9=(Q)=>Q.length===1?Q[0].element:null,Y3=(Q,Y)=>Y.length>0&&Y.every(({element:J})=>Q.mathCapabilityByElement.get(J)==="token"),J3=3,G3=(Q,Y,J)=>{if(!Y||Y.type!=="range")return!1;let{startContainer:G,endContainer:X}=Y.range;if(G===X&&G.nodeType===J3)return!1;return J.some(({element:j})=>Q.mathCapabilityByElement.get(j)==="token"&&j.contains(G)&&j.contains(X))},X3=(Q,Y)=>({chunk:Q,regionTarget:eQ(Q),renderedMathTargetResolver:s9(),mathCapabilityByElement:new Map(Q.mathAlignments.map(({element:J})=>[J,Y?l9(J):"expression"])),heldTokenByElement:new Map}),e9=(Q)=>{let Y=Q.mathTokenHighlighting!==!1,J=new Map(Q.chunks.map((G)=>[G.id,X3(G,Y)]));return{chunks:Q.chunks,resolveInitial(G){let X=J.get(G);if(!X)return a9();let Z=X.chunk.mathAlignments,j=Z.length===1?Z[0].element:null,q=j?X.mathCapabilityByElement.get(j):null;if(q==="expression")return M7({semanticTarget:null,expressionTarget:o9(X),regionTarget:X.regionTarget,confidence:0.5,reason:"initial expression (sticky expression mode)"});return M7({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 a9();let{chunk:Z}=X,j=v9(Z,G),q=r9(Z,j),U=Q3(q,Z),V=(!q||U.length>0?n9(Z,j,G,U,X.renderedMathTargetResolver):null)||null,D=Y&&V&&V.quality!=="expression"?V:null,_=V&&V.quality==="expression"?V:null;if(D){let F=t9(U);if(F)X.heldTokenByElement.set(F,D);return M7({semanticTarget:D,expressionTarget:null,regionTarget:X.regionTarget,confidence:j.confidence,reason:j.reason})}if(q&&(Y?!G3(X,q,U):U.length===0))return M7({semanticTarget:q,expressionTarget:null,regionTarget:X.regionTarget,confidence:j.confidence,reason:j.reason});if(Y3(X,U)){let F=t9(U),N=F?X.heldTokenByElement.get(F)??null:null;return M7({semanticTarget:N,expressionTarget:null,regionTarget:X.regionTarget,confidence:j.confidence,reason:N?"hold last token (sticky token mode)":"region (sticky token mode, awaiting first token)"})}return M7({semanticTarget:null,expressionTarget:_??o9(X,U),regionTarget:X.regionTarget,confidence:j.confidence,reason:j.reason})}}};var Z3=(Q)=>{if(Q.alignment?.boundaryOffsetMode)return Q.alignment.boundaryOffsetMode;let Y=Q.mathAlignment?.speech.boundaryOffsetSpace;if(Y)return Y;return"plain-spoken-text"},j3=(Q)=>{if(Q.mathAlignments?.length)return Q.mathAlignments;if(Q.mathAlignment&&Q.sourceElement)return[{element:Q.sourceElement,alignment:Q.mathAlignment}];return[]},Q6=(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:j3(J),offsetSpace:Z3(J)}))};var q3=["[data-pie-tts-region]","[data-catalog-region]","li","p","label","section","[role='group']","[role='region']","div"].join(","),B1=(Q,Y)=>{let J=Q.closest(q3);if(J&&Y.contains(J))return J;return Q};var W3=(Q,Y,J)=>{let G=new Map;for(let X=Y;X<J;X++){let Z=Q.get(X);if(Z)G.set(X-Y,Z)}return G},U8=async(Q)=>{let Y=H7(Q.contentRoot,Q.textProcessingOptions),J=await J8({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:Z})=>{let j=Y.chunks[Z];if(X.kind==="prose"){let U=j?.type==="text"?j.sourceElement??Q.contentRoot:Q.contentRoot;return{segment:X,anchor:{sourceElement:U,regionElement:B1(U,Q.contentRoot),visibleMap:W3(Y.map,X.visibleSpan.start,X.visibleSpan.end)}}}let q=j?.type==="math"?j.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 U3=(Q,Y)=>{let J=j1({speechText:Q.spokenText,visibleText:Q.spokenText});return{speechText:Q.spokenText,visibleText:Q.visibleText,sourceElement:Y.sourceElement,regionElement:Y.regionElement,regionRange:V1(Y.visibleMap,0,Q.visibleText.length)??void 0,speechMatchesVisibleText:!0,playbackMode:J.playbackMode,alignment:J,visibleMap:Y.visibleMap}},Y6=(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?P7({mathElement:J,speechText:Q.spokenText}):void 0}},D3=(Q,Y,J)=>{let G=Y.sourceElement;return{speechText:J,visibleText:Q.fallbackText,sourceElement:G,regionElement:Y.regionElement,speechMatchesVisibleText:!1,mathAlignment:G?P7({mathElement:G,speechText:J}):void 0,plainFallback:Y6(Q,Y)}},D8=(Q,Y={})=>Q.items.map(({segment:J,anchor:G})=>{if(J.kind==="prose")return U3(J,G);if(Y.format==="ssml"&&J.ssml)return D3(J,G,J.ssml);return Y6(J,G)});var J6="pie-tts-control-handoff";var $;(function(Q){Q.IDLE="idle",Q.LOADING="loading",Q.PLAYING="playing",Q.PAUSED="paused",Q.ERROR="error"})($||($={}));var X6=(Q,Y)=>Q===Y||Q.startContainer===Y.startContainer&&Q.startOffset===Y.startOffset&&Q.endContainer===Y.endContainer&&Q.endOffset===Y.endOffset,K3=(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 X6(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 v7{currentProvider=null;provider=null;highlightCoordinator=null;highlightTargetResolverProvider=null;catalogResolver=null;state=$.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;activeHighlightMode="word";lastRenderedRegionTarget=null;telemetryReporter=null;generatedMathSpeechResolver=X8();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(!v7.debugEnabled)return;if(Y===void 0)console.debug(Q);else console.debug(Q,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:!X6(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 Z=[],j=[];for(let q of X){if(typeof Range<"u"&&q instanceof Range){if(!this.isRangeWithinScope(q,G))return{ranges:Q,elements:[]};Z.push(q);continue}if(typeof Element<"u"&&q instanceof Element){if(!this.isElementWithinScope(q,G))return{ranges:Q,elements:[]};j.push(q);continue}return{ranges:Q,elements:[]}}return{ranges:Z,elements:j}}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,h.TTS_WORD,K7.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 Z=document.createRange();Z.selectNodeContents(X),G.push(Z)}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 D1(Y)}buildPositionMap(Q,Y,J){this.normalizedToDOM.clear();let{text:G,map:X}=w7(Q,this.getTextProcessingOptions(J));if(this.normalizedToDOM=X,!v7.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 Z=0;Z<Math.min(Y.length,G.length);Z++)if(Y[Z]!==G[Z])return{index:Z,spokenChar:Y[Z],normalizedChar:G[Z],spokenContext:Y.substring(Math.max(0,Z-20),Z+20),normalizedContext:G.substring(Math.max(0,Z-20),Z+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(([Z,{node:j,offset:q}])=>({pos:Z,offset:q,char:j.textContent?.[q],expected:Y[Z]}))})}getStructuralPauseProfile(){let Y=(this.ttsConfig.providerOptions||{}).structuralPauses||{},J=Y.units||{},G=(X,Z)=>{if(typeof X==="number"&&Number.isFinite(X))return X;if(typeof X==="string"&&X.trim()){let j=Number(X);return Number.isFinite(j)?j:Z}return Z};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 G6(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 Z=Number(J.getAttribute("data-tts-break-ms"));if(Number.isFinite(Z)&&Z>0)return{anchor:J,units:Z/this.getStructuralPauseProfile().baseMs};let j=(J.getAttribute("role")||"").toLowerCase(),q=J.tagName.toUpperCase();if(q.match(/^H[1-6]$/)||j==="heading"||j==="listitem"||q==="LI"){G=J;break}if(!G){if(typeof window<"u"){let U=window.getComputedStyle(J).display;if(U==="block"||U==="list-item"||U.startsWith("table")||U==="flex"||U==="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}=w7(Q,this.getTextProcessingOptions()),X=this.createNodeStartOffsets(G),Z=document.createTreeWalker(Q,NodeFilter.SHOW_TEXT),j=Z.nextNode(),q=null;while(j){let U=j,V=U.parentElement;if(V&&!this.isElementHidden(V)&&!K8(U)){let D=this.getBoundaryAnchor(U,Q),_=X.get(U);if(D&&_!==void 0&&D.anchor!==q&&_>0)J.set(_,Math.max(J.get(_)||0,D.units)),q=D.anchor}j=Z.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((U)=>U>0&&U<Q.length).sort((U,V)=>U-V),G=[],X=0;for(let U of J){let V=Q.substring(X,U),D=V.match(/^\s*/)?.[0].length||0,_=V.match(/\s*$/)?.[0].length||0,F=X+D,N=U-_;if(N>F){let O=Q.substring(F,N);G.push({text:O,startOffset:F,pauseMsAfter:this.resolvePauseMsFromUnits(Y.get(U)||0)})}X=U}let j=Q.substring(X).match(/^\s*/)?.[0].length||0,q=X+j;if(q<Q.length)G.push({text:Q.substring(q).trimEnd(),startOffset:q,pauseMsAfter:0});return G.filter((U)=>U.text.trim().length>0)}segmentSentences(Q){let Y=this.ttsConfig.providerOptions?.locale||void 0;return W1(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((Z)=>Number.isFinite(Z)&&Z>0).sort((Z,j)=>Z-j);if(G.length===0)return Q;let X=[];for(let Z of Q){let j=Z.startOffset,q=Z.startOffset+Z.text.length,U=G.filter((D)=>D>j&&D<q);if(U.length===0){X.push(Z);continue}let V=j;for(let D of[...U,q]){let _=J.substring(V,D),F=_.match(/^\s*/)?.[0].length||0,N=_.match(/\s*$/)?.[0].length||0,O=V+F,w=D-N;if(w>O)X.push({text:J.substring(O,w),startOffset:O,pauseMsAfter:0});V=D}}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=f(G)||J.visibleText||"",Z={text:X,startOffset:Y,pauseMsAfter:0};return Y+=Math.max(1,X.length+1),Z})}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 Z=this.provider.onWordBoundary;this.provider.onWordBoundary=(j,q,U)=>{if(Z?.(j,q,U),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=Z}return}this.configureWordBoundaryHighlighting({highlightMode:J?.highlightMode||"word",wordBoundaryOffset:this.activeWordBoundaryOffset});for(let Z of Q){if(Y!==this.speakRunId)return;let j=this.seekSegments.findIndex((U)=>U.startOffset===Z.startOffset);if(j>=0)this.currentSeekSegmentIndex=j;if(this.currentBoundaryOffset=Z.startOffset,G)this.highlightSentenceSegment(Z.startOffset,Z.text);await this.provider.speak(Z.text);let q=Z.pauseMsAfter??0;if(q>0)await new Promise((U)=>setTimeout(U,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 Z=document.createRange();Z.setStart(G.node,G.offset),Z.setEnd(X.node,X.offset+1),this.paintTTSSentenceRanges([Z]),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(([Z])=>Math.abs(Z-Q)<5).map(([Z,{offset:j,node:q}])=>({pos:Z,offset:j,char:q.textContent?.[j]}))}),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;try{if(await this.applyLanguageSettings(Y),J!==this.speakRunId)return;let G=await this.resolveSpeechContent(Q,Y);if(J!==this.speakRunId)return;let{contentToSpeak:X,speechText:Z,highlightText:j,normalizedText:q,usedCatalogSpoken:U,speechSource:V,speechMatchesVisibleText:D,speechChunks:_}=G;this.logResolvedSpeechContent({contentToSpeak:X,speechSource:V,catalogId:Y?.catalogId}),this.initializeSpeakTracking(j,Y);let F=Y?.highlightModeOverride||(D?this.resolveHighlightMode():"sentence");this.activeHighlightMode=F,this.activeWordBoundaryOffset=Y?.wordBoundaryOffset||0;let N=this.hasExplicitBreakSemantics(X),O=!!this.currentContentElement&&!U&&!N&&D;if(this.playbackChunks=_?.length?_:[],this.seekSegments=this.playbackChunks.length?this.createSeekSegmentsFromSpeechChunks(this.playbackChunks):N||!D?[]:O&&this.currentContentElement?this.createSpeechPlan(this.currentContentElement,q):this.createSeekSegmentsFromText(j),this.sentenceHighlightSegments=N?[]:this.createSentenceHighlightSegments({contentToSpeak:j,shouldUsePlan:O,playbackSegments:this.seekSegments}),this.setState($.LOADING),this.prepareHighlightsForSpeak({contentToSpeak:j,options:Y,highlightMode:F,shouldUsePlan:O}),D)this.configureWordBoundaryHighlighting({highlightMode:F,wordBoundaryOffset:Y?.wordBoundaryOffset||0});else this.clearWordBoundaryHighlighting();if(this.setState($.PLAYING),await this.executeSpeakPlayback({shouldUsePlan:O,runId:J,highlightMode:F,contentToSpeak:Z,speechChunks:_}),J!==this.speakRunId)return;this.setState($.IDLE),this.clearHighlightsAndTracking()}catch(G){let X=G;if(console.error("TTS error:",X),this.lastError=X instanceof Error?X.message:String(X),J!==this.speakRunId)return;throw this.setState($.ERROR),this.clearHighlightsAndTracking(),X}}async switchProviderToBrowser(Q,Y){if(!this.currentProvider)return!1;let J=new _1,G=this.currentProvider.providerId,X={...this.ttsConfig},Z=Y?.operation||"tts-initialize",j=Y?.contentToSpeak??"",q=j.replace(/\s+/g," ").trim().slice(0,120),U=j.length>0?{textLength:j.length,textPreview:q.length<j.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:Z,fromProvider:G,toProvider:J.providerId,reason:Q instanceof Error?Q.message:String(Q),...U}),console.warn("[TTSService] TTS provider initialization failed; switched to browser fallback",{fromProvider:G,reason:Q,...U}),!0}catch(V){return await this.emitTelemetry("pie-tool-runtime-fallback-error",{toolId:"textToSpeech",operation:Z,fromProvider:G,toProvider:"browser",errorType:"TTSRuntimeFallbackError",message:V instanceof Error?V.message:String(V)}),console.error("[TTSService] Failed to switch to browser fallback provider",V),!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=f(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 Z=this.catalogResolver.getAlternative(Y.catalogId,{type:"spoken",language:Y.language||"en-US",useFallback:!0,context:Y.catalogContext,form:"content"}),j=Z?.content;if(Z&&j!==void 0){let q=Y?.contentElement?H7(Y.contentElement,this.getTextProcessingOptions(Y.language)).visibleText||J:J,U=f(j);return this.debugLog(`[TTSService] Using catalog content for "${Y.catalogId}" (${Z.language})`),{contentToSpeak:j,speechText:j,visibleText:q,highlightText:q,usedCatalogSpoken:!0,speechSource:"catalog-spoken",normalizedText:q,containsMathMarkup:!1,speechMatchesVisibleText:U===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((j)=>j.sourceElement))return null;let X=f(G.map((j)=>j.speechText).join(" ")),Z=H7(Q,this.getTextProcessingOptions(J.language)).visibleText||Y;return{contentToSpeak:X,speechText:X,visibleText:Z,highlightText:Z,usedCatalogSpoken:!0,speechSource:"catalog-spoken",normalizedText:Z,containsMathMarkup:!1,speechMatchesVisibleText:G.every((j)=>j.speechMatchesVisibleText),speechChunks:G}}collectCatalogSpeechChunks(Q,Y){let J=[],G="",X=()=>{let V=f(G);if(G="",!V)return;J.push({speechText:V,visibleText:V,sourceElement:null,speechMatchesVisibleText:!0})},Z=(V)=>{let D=V.getAttribute("data-catalog-idref");if(!D)return null;let _={type:"spoken",language:Y.language||"en-US",useFallback:!0,context:Y.catalogContext},F=this.catalogResolver.getAlternative(D,{..._,form:"payload"}),N=F?.payload?G9({payload:F.payload})??void 0:void 0,w=this.catalogResolver.getAlternative(D,{..._,form:"content"})?.content;if(N===void 0&&w===void 0)return null;return{script:w,audio:N}},j=(V,D)=>{let _=q(V);if(_.length!==1)return null;let F=_[0],N=H7(F,this.getTextProcessingOptions(Y.language)).visibleText||f(F.textContent||""),O=(w)=>f(w).replace(/\s+/g,"");return O(N)===O(D)?F:null},q=(V)=>{let D=Array.from(V.querySelectorAll("math"));if(V.localName?.toLowerCase()==="math")return[V,...D];return D},U=(V)=>{if(k7(V,Q))return;if(V.nodeType===Node.TEXT_NODE){G+=` ${V.textContent||""}`;return}if(V.nodeType!==Node.ELEMENT_NODE)return;let D=V,_=Z(D);if(_){X();let F=H7(D,this.getTextProcessingOptions(Y.language)),N=F.visibleText||f(D.textContent||""),O=B1(D,Q),w=_.script!==void 0?(()=>{let k=_.script,H=j1({speechText:k,visibleText:N}),b=j(D,N),T=b?P7({mathElement:b,speechText:k}):void 0,u=T?void 0:q(D).map((I)=>({element:I,alignment:P7({mathElement:I,speechText:k})}));return{speechText:k,visibleText:N,sourceElement:D,regionElement:O,speechMatchesVisibleText:f(k)===N,playbackMode:H.playbackMode,alignment:H,mathAlignment:T,mathAlignments:u,visibleMap:F.map}})():null;if(_.audio){J.push(w?{...w,audio:_.audio,plainFallback:w}:{speechText:N,visibleText:N,sourceElement:D,regionElement:O,speechMatchesVisibleText:!1,visibleMap:F.map,audio:_.audio});return}if(w)J.push(w);return}for(let F of Array.from(D.childNodes))U(F)};return U(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:Z,visibleText:j}=await U8({contentRoot:Q,language:J,mathSpeech:this.getMathSpeechOptions(),textProcessingOptions:this.getTextProcessingOptions(J),produceSsml:G==="ssml",resolveMathSpeech:this.generatedMathSpeechResolver}),q=j||Y;if(!Z)return{contentToSpeak:q,speechText:q,visibleText:q,highlightText:q,normalizedText:q,containsMathMarkup:!1,speechMatchesVisibleText:!0};let U=D8(X,{format:G}),V=X.plainSpeechText;return{contentToSpeak:V,speechText:V,visibleText:q,highlightText:q,normalizedText:q,containsMathMarkup:!0,speechMatchesVisibleText:V===q,speechChunks:U}}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];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,Z=J+this.currentBoundaryOffset+Q.wordBoundaryOffset;this.highlightSentenceForOffset(Z);let j=this.findHighlightRange(Z,X);if(j&&this.highlightCoordinator){let q=j.node.textContent?.substring(j.start,j.end)||"";this.debugLog(`[TTSService] Highlighting "${q}" (word: "${Y}") at position ${Z}`);let U=this.createTextRange(j.node,j.start,j.end);if(U)this.paintTTSWordRange(this.resolveWordHighlightRange(U).range);else this.highlightCoordinator.highlightTTSWord(j.node,j.start,j.end)}else console.warn(`[TTSService] Could not find highlight range for position ${Z}, 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?.(h.TTS_WORD),this.paintTTSSentenceRanges([Q.regionRange]);return}if(!Y)return;let J=document.createRange();J.selectNodeContents(Y),this.highlightCoordinator.clearHighlights?.(h.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&&K3(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(h.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){this.debugLog("[TTSService] SSML chunk speak failed; retrying plain text",{message:J instanceof Error?J.message:String(J)}),await this.speakCatalogChunkOnce(Q.plainFallback,Y);return}throw J}}async playRecordedAudio(Q){if(typeof document>"u")throw Error("[tts] no document available to play recorded audio");let Y=Q.sources[0],J=document.createElement("audio");J.preload="auto",J.src=J9(Y.src,Q.fragment),J.playbackRate=this.normalizePlaybackRate(Number(this.ttsConfig.rate||1)),await new Promise((G,X)=>{let Z,j=()=>{if(J.removeEventListener("ended",q),J.removeEventListener("error",U),Z!==void 0)clearInterval(Z);if(this.activeRecordedAudio?.element===J)this.activeRecordedAudio=null},q=()=>{j(),G()},U=()=>{j(),X(Error(`[tts] recorded audio failed to play: ${Y.src}`))};this.activeRecordedAudio={element:J,cancel:()=>{j(),J.pause(),G()}},J.addEventListener("ended",q),J.addEventListener("error",U);let V=Q.fragment?.endSeconds;if(V!==void 0)Z=setInterval(()=>{if(J.currentTime>=V)q()},100);Promise.resolve(J.play()).catch(U)}).finally(()=>{if(this.activeRecordedAudio?.element===J)this.activeRecordedAudio=null;J.pause(),J.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.highlightCatalogRegion(Q),await this.playRecordedAudio(Q.audio);return}let J=Q.regionElement||Q.sourceElement||this.currentContentElement,G=J?Q6({contentRoot:J,chunks:[Q]})[0]:null,X=this.ttsConfig.mathTokenHighlighting!==!1,Z=G?e9({chunks:[G],mathTokenHighlighting:X}):null;if(Z&&G&&Q.mathAlignment)this.renderHighlightDecision(Z.resolveInitial(G.id));else this.highlightCatalogRegion(Q);if(!(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 D=this.provider,_=D.onWordBoundary;D.onWordBoundary=void 0;try{await D.speak(Q.speechText)}finally{if(this.provider===D&&Y===this.speakRunId&&D.onWordBoundary===void 0)D.onWordBoundary=_}return}let q=this.provider,U=q.onWordBoundary,V=(D,_,F)=>{if(Y!==this.speakRunId)return;if(Z&&G){let N=G.offsetSpace==="unsupported"?"unknown":G.offsetSpace;this.renderHighlightDecision(Z.resolveBoundary({chunkId:G.id,word:D,position:_,length:F,providerOffsetSpace:N}));return}};q.onWordBoundary=V;try{await q.speak(Q.speechText)}finally{if(this.provider===q&&Y===this.speakRunId&&q.onWordBoundary===V)q.onWordBoundary=U}}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.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(K8(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 D=Q.commonAncestorContainer;G=D.nodeType===Node.ELEMENT_NODE?D:D.parentElement}if(!G)return;let X=V8(Q,G),Z=X.text.trim();if(!Z){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 j=document.createRange();j.selectNodeContents(G),j.setEnd(Q.startContainer,Q.startOffset);let q=V8(j,G).text,U=f(q),V=U.length+(/\s$/.test(q)&&U?1:0);this.debugLog("[TTSService] speakRange offset calculation:",{selectedText:Z,textBeforeRange:q.substring(0,100),offset:V,rootTag:G.tagName}),await this.speak(Z,{contentElement:G,ignoreCatalogs:!0,wordBoundaryOffset:V})}pause(){if(!this.provider)return;if(this.state===$.PLAYING)this.activeRecordedAudio?.element.pause(),this.provider.pause(),this.setState($.PAUSED)}resume(){if(!this.provider)return;if(this.state===$.PAUSED){let Q=this.activeRecordedAudio?.element;if(Q)Promise.resolve(Q.play()).catch(()=>{});this.provider.resume(),this.setState($.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.cancelRecordedAudio(),this.provider.onWordBoundary=void 0,this.provider.stop(),this.currentSeekSegmentIndex=Y;let G=++this.speakRunId,X=this.seekSegments.slice(Y);this.setState($.PLAYING);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 j=Y+Z;this.currentSeekSegmentIndex=j;let q=this.seekSegments[j];if(q)this.currentBoundaryOffset=q.startOffset;await this.speakCatalogChunk(J[Z],G)}else await this.speakWithPlan(X,G,{highlightMode:this.activeHighlightMode});if(G!==this.speakRunId)return;this.setState($.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($.ERROR),this.clearHighlightsAndTracking(),this.highlightTargetResolverProvider=null,Z}}async setPlaybackRate(Q){let Y=this.normalizePlaybackRate(Q);if(await this.updateSettings({rate:Y}),this.state!==$.PLAYING||!this.currentText||this.seekSegments.length===0||this.hasExplicitBreakSemantics(this.currentText))return;await this.restartFromSeekIndex(this.getCurrentSeekSegmentIndex())}async seekBy(Q){if(!this.provider||!this.currentText)return;if(this.state!==$.PLAYING&&this.state!==$.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.cancelRecordedAudio(),this.provider.onWordBoundary=void 0,this.provider.stop(),this.highlightTargetResolverProvider=null,this.setState($.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}requestControlHandoff(){if(typeof window>"u")return;let Q={source:"host"};window.dispatchEvent(new CustomEvent(J6,{detail:Q}))}isPlaying(){return this.state===$.PLAYING}isPaused(){return this.state===$.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===$.PLAYING){let J=Y===$.PAUSED?"pie-tool-playback-resume":"pie-tool-playback-start";this.emitTelemetry(J,{toolId:"textToSpeech",providerId:"tts",previousState:Y,state:Q});return}if(Q===$.PAUSED){this.emitTelemetry("pie-tool-playback-pause",{toolId:"textToSpeech",providerId:"tts",previousState:Y,state:Q});return}if(Q===$.ERROR){this.emitTelemetry("pie-tool-playback-error",{toolId:"textToSpeech",providerId:"tts",previousState:Y,state:Q,message:this.lastError||void 0});return}if(Q===$.IDLE&&(Y===$.PLAYING||Y===$.PAUSED||Y===$.LOADING))this.emitTelemetry("pie-tool-playback-stop",{toolId:"textToSpeech",providerId:"tts",previousState:Y,state:Q})}}function Z6(Q,Y){let J=Y.decisions[0],G=Array.from(Y.perToolFlags.values())[0];return{featureId:Q,granted:J?.action==="enable",action:J?.action??"skip",rule:J?.rule??"pnp-support",precedence:J?.precedence??6,sourceType:J?.sourceType??"system",reason:J?.reason??`Feature "${Q}" not configured`,required:Boolean(G?.required),parameters:G?.settings}}class F1{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=V3(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 V3(Q){if(!Q.winningDecision){if(Q.finalState==="advisory-only"){let Z=Q.allDecisions.find((j)=>j.action==="advisory");return Z?`Feature "${Q.featureId}" was kept in its host-decided state; ${Z.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,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 Z=X.commonAncestorContainer.nodeType===Node.ELEMENT_NODE?X.commonAncestorContainer:X.commonAncestorContainer.parentElement;if(!Z)continue;let j=[],q=X.startContainer.nodeType===Node.ELEMENT_NODE?X.startContainer:X.startContainer.parentElement,W=X.endContainer.nodeType===Node.ELEMENT_NODE?X.endContainer:X.endContainer.parentElement;for(let V of[q,W]){let U=V;while(U){if(U.matches?.(G))j.push(U);U=U.parentElement}}if(Z.matches?.(G))j.push(Z);j.push(...Array.from(Z.querySelectorAll(G)));for(let V of new Set(j)){try{if(!X.intersectsNode(V)&&!V.contains(q)&&!V.contains(W))continue}catch{continue}V.setAttribute(Y,"true"),J.add(V)}}}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=B7.YELLOW){let J=`annotation-${this.nextAnnotationId++}`,G=Q.cloneRange(),X={id:J,range:G,type:h.ANNOTATION,color:Y,timestamp:Date.now()};this.annotations.set(J,X);let Z=this.colorHighlights.get(Y);if(Z)Z.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 Z=this.colorHighlights.get(Y);if(Z)Z.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=B7.YELLOW){if(!this.supported)return;switch(Y){case h.TTS_WORD:case h.TTS_SENTENCE:{let G=Y===h.TTS_WORD?this.ttsWordHighlight:this.ttsSentenceHighlight;if(G){if(G.clear(),G.add(Q),Y===h.TTS_WORD){for(let X of this.ttsWordElementHighlights)X.removeAttribute("data-pie-tts-word-element");this.ttsWordElementHighlights.clear(),this.highlightTTSWordElementFallbacks([Q])}}break}case h.ANNOTATION:this.addAnnotation(Q,J);break}}clearHighlights(Q){if(!this.supported)return;switch(Q){case h.TTS_WORD:this.clearTTSWord();break;case h.TTS_SENTENCE:this.clearTTSSentence();break;case h.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=((Z)=>{let j=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(Z);return j?{r:parseInt(j[1],16),g:parseInt(j[2],16),b:parseInt(j[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 Z9(Q){return(...Y)=>{console.debug(`[${Q}]`,...Y)}}var o=Z9("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 r1{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 Z=G+this.getNextLayerOffset(G);J.style.zIndex=String(Z),J.style.display=X?"":"none";let j=()=>this.bringToFront(J);if(J.addEventListener("mousedown",j),this.tools.set(Q,{id:Q,name:Y,element:J,layer:G,isVisible:X,baseZIndex:Z,mouseDownHandler:j}),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,G3=new Set(["http:","https:","data:","blob:"]);function X3(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 G3.has(J)}function j9(Q){if(!Array.isArray(Q))return[];let Y=[];for(let J of Q){if(!J||typeof J!=="object")continue;let G=J;if(!X3(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((Z)=>Z.src===X.src))continue;Y.push(X)}return Y}function q9(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 K9(Q){if(typeof Q!=="string")return;return Q.trim()||void 0}function W9(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 U9(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=j9(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:q9(Y.fragment),label:K9(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 W=new q(Y?.locale,{granularity:"sentence"}),V=Array.from(W.segment(Q)).map((U)=>({text:U.segment,offset:U.index})).filter((U)=>U.text.trim().length>0);if(V.length>0)return V}}catch{}let G=/[^.!?]+(?:[.!?]+|$)/g,X=Q.match(G)||[Q],Z=[],j=0;for(let q of X){let W=Q.indexOf(q,j);if(W===-1)continue;Z.push({text:q,offset:W}),j=W+q.length}return Z.length>0?Z:[{text:Q,offset:0}]};var V9=(Q)=>String(Q||"").trim().toLowerCase(),Z3=()=>{let Q=typeof navigator<"u"?navigator.language||navigator.languages?.[0]:"";return V9(Q||"en-US")},j3=(Q,Y)=>{if(Y){let j=Q.find((q)=>q.name===Y);if(j)return j}let J=Z3(),G=J.split("-")[0]||"en",X=(j)=>{let q=V9(j.lang);return q===J||q.startsWith(`${G}-`)},Z=[(j)=>j.localService&&X(j),(j)=>j.default&&X(j),(j)=>X(j),(j)=>j.localService,(j)=>j.default];for(let j of Z){let q=Q.find(j);if(q)return q}return Q[0]||null},q3=(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 B9(Q)}supportsFeature(Q){return!0}getCapabilities(){return{supportsPause:!0,supportsResume:!0,supportsWordBoundary:!0,supportsVoiceSelection:!0,supportsRateControl:!0,supportsPitchControl:!0,supportsSSML:!1}}destroy(){}}class B9{utterance=null;config=null;_isPlaying=!1;_isPaused=!1;speakRunId=0;constructor(Q){this.config=Q}async speak(Q){if(!this.config)throw Error("TTS not initialized");this.stop();let Y=this.speakRunId,J=this.splitIntoChunks(Q);for(let G of J){if(Y!==this.speakRunId)break;if(!await this.speakChunk(G.text,G.offset,Y))break}}async speakSegments(Q){if(!this.config)throw Error("TTS not initialized");this.stop();let Y=this.speakRunId;for(let J of Q){if(Y!==this.speakRunId)break;let G=this.splitIntoChunks(J.text);for(let Z of G){if(Y!==this.speakRunId)break;if(!await this.speakChunk(Z.text,J.startOffset+Z.offset,Y))break}let X=Math.max(0,Number(J.pauseMsAfter||0));if(X>0&&Y===this.speakRunId){if(!await this.waitForPause(X,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="",Z=0;for(let j of J){let q=j.text.trim();if(!q)continue;let W=j.text.search(/\S/),V=j.offset+(W===-1?0:W);if(!X){X=q,Z=V;continue}let U=`${X} ${q}`;if(U.length<=260)X=U;else G.push({text:X,offset:Z}),X=q,Z=V}if(X)G.push({text:X,offset:Z});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){return new Promise((G,X)=>{if(J!==this.speakRunId){G(!1);return}let Z=new SpeechSynthesisUtterance(Q);this.utterance=Z;let j=j3(speechSynthesis.getVoices(),this.config?.voice);if(j&&q3(j))Z.voice=j;if(this.config?.rate)Z.rate=this.config.rate;if(this.config?.pitch)Z.pitch=this.config.pitch;let q=()=>{if(this.utterance===Z)this.utterance=null};Z.onstart=()=>{if(J!==this.speakRunId)return;this._isPlaying=!0,this._isPaused=!1},Z.onend=()=>{if(q(),J!==this.speakRunId){G(!1);return}this._isPlaying=!1,this._isPaused=!1,G(!0)},Z.onerror=(W)=>{if(q(),J!==this.speakRunId){G(!1);return}if(this._isPlaying=!1,this._isPaused=!1,W.error==="interrupted"||W.error==="canceled"){G(!1);return}X(Error(`Speech synthesis error: ${W.error}`))},Z.onpause=()=>{if(J!==this.speakRunId)return;this._isPaused=!0},Z.onresume=()=>{if(J!==this.speakRunId)return;this._isPaused=!1},Z.onboundary=(W)=>{if(J!==this.speakRunId)return;if(console.log("[BrowserProvider] Boundary event:",W.name,"charIndex:",W.charIndex,"charLength:",W.charLength),W.name!=="word"||!this.onWordBoundary)return;if(this.getHighlightMode()==="sentence")return;let V=Math.max(0,Math.min(W.charIndex,Math.max(0,Q.length-1))),U=Number(W.charLength||0),_=this.inferWordLength(Q,V),H=Number.isFinite(U)&&U>0&&U<=80&&V+U<=Q.length?U:_,F=Q.substring(V,Math.min(Q.length,V+H)).trim(),N=Y+V;console.log("[BrowserProvider] Calling onWordBoundary with word:",F,"at position:",N),this.onWordBoundary(F,N,H)},speechSynthesis.speak(Z)})}pause(){if(this._isPlaying&&!this._isPaused)speechSynthesis.pause()}resume(){if(this._isPlaying&&this._isPaused)speechSynthesis.resume()}stop(){if(this.speakRunId+=1,this._isPlaying||this.utterance)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 R=(Q)=>Q.trim().replace(/\s+/g," "),Z1=()=>/[\p{L}]+|\d+(?:\.\d+)?|[±√=+\-*/()²³^×÷≤≥≠≈<>|%°'′\u2062]/gu,o1=(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"),Z=Number.isFinite(G)&&Number.isFinite(X)&&G<=1&&X<=1,j=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")&&Z&&(J.overflow==="hidden"||j))return!0;if(J.opacity==="0"&&Z)return!0}return!1},j1=(Q,Y)=>{let J=Q.nodeType===1?Q:Q.parentElement;while(J){if(o1(J))return!0;if(Y&&J===Y)break;J=J.parentElement}return!1};var H9=new Set(["computer-read-aloud","all"]),D9=new Set([...H9,"screen-reader"]),_9=new Set,K3=(Q)=>{let Y=Q.getAttribute?.("data-tts-suppress");if(Y===null||Y===void 0)return!1;let J=Y.trim().toLowerCase();if(H9.has(J))return!0;if(D9.has(J))return!1;if(!_9.has(J))_9.add(J),console.warn(`[tts] data-tts-suppress="${Y}" is not one of ${Array.from(D9).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(K3(J))return!0;if(Y&&J===Y)break;J=J.parentElement}return!1},D7=(Q,Y)=>j1(Q,Y)||q1(Q),a1=(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),Z=X.nextNode();while(Z){let j=Z;if(Q.intersectsNode(j))if(D7(j,Y))G=!0;else{let q=j.textContent||"",W=j===Q.startContainer?Q.startOffset:0,V=j===Q.endContainer?Q.endOffset:q.length;J.push(q.slice(W,V))}Z=X.nextNode()}return{text:J.join(""),filtered:G}},t1=(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 j=globalThis.Intl?.Segmenter;if(typeof j==="function"){let q=new j(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),Z=/[A-Za-z0-9]/.test(Y);return X&&Z},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,Z=!0,j=!1,q=null,W=null,V=document.createTreeWalker(Q,NodeFilter.SHOW_TEXT),U=V.nextNode();while(U){let H=U;if(H.parentElement&&!D7(H,Q)){let N=H.textContent||"",P=N.match(/\S/),f=P?P[0]:null;if(!Z&&!j&&t1(W,f,Y)){if(G.push(" "),q)J.set(X,q);X++,j=!0}for(let A=0;A<N.length;A++){let L=N[A],E=/\s/.test(L);if(Z){if(!E)Z=!1,G.push(L),J.set(X,{node:H,offset:A}),q={node:H,offset:A},X++,j=!1,W=L}else if(E){if(!j)G.push(" "),J.set(X,{node:H,offset:A}),q={node:H,offset:A},X++;j=!0}else G.push(L),J.set(X,{node:H,offset:A}),q={node:H,offset:A},X++,j=!1,W=L}}U=V.nextNode()}let _=G.join("").trimEnd();while(J.has(_.length))J.delete(_.length);return{text:_,map:J}};var W3=new Set(["speak","p","s","emphasis","prosody","say-as","voice","lang"]),A9=new Set(["audio","phoneme"]),M9=(Q)=>Q.replace(/"/g,'"').replace(/'/g,"'").replace(/</g,"<").replace(/>/g,">").replace(/ /g," ").replace(/ /g," ").replace(/&/g,"&"),K1=(Q,Y,J)=>{for(let G=0;G<Y.length;G++)Q.push({char:Y[G],rawOffset:J===null?null:J+G})},U3=(Q,Y,J)=>{let G=Y.slice(J).match(/^&(quot|apos|lt|gt|nbsp|amp|#160);/i);if(!G)return 0;return K1(Q,M9(G[0]),J),G[0].length},F9=(Q)=>{Q.push({char:" ",rawOffset:null})},V3=(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,Z]of Y)if(Z>=J.length)Y.delete(X);return{text:J.join(""),rawToSpokenOffsetMap:Y}},B3=(Q)=>{return Q.match(/^<\/?\s*([A-Za-z0-9:-]+)/)?.[1]?.toLowerCase()||""},D3=(Q,Y)=>{let J=new RegExp(`${Y}\\s*=\\s*("([^"]*)"|'([^']*)')`,"i"),G=Q.match(J);return M9(G?.[2]??G?.[3]??"")||null},W1=(Q)=>{let Y=[],J=!1,G=!1,X=0;while(X<Q.length){let j=Q[X];if(j!=="<"){if(j==="&"){let H=U3(Y,Q,X);if(H>0){X+=H;continue}}K1(Y,j,X),X++;continue}let q=Q.indexOf(">",X+1);if(q<0){K1(Y,j,X),X++;continue}G=!0;let W=Q.slice(X,q+1),V=B3(W),U=/^<\s*\//.test(W),_=/\/\s*>$/.test(W);if(!U&&V==="sub"){let H=D3(W,"alias");if(!H){J=!0,X=q+1;continue}K1(Y,H,null);let F=Q.toLowerCase().indexOf("</sub>",q+1);X=F>=0?F+6:q+1;continue}if(!U&&V==="break"){F9(Y),X=q+1;continue}if(!U&&A9.has(V)){if(J=!0,_){X=q+1;continue}}if(V&&!W3.has(V)&&!A9.has(V)&&V!=="break"&&V!=="sub")J=!0;if(!U&&(V==="p"||V==="s"))F9(Y);X=q+1}let Z=V3(Y);return{spokenText:R(Z.text),rawToSpokenOffsetMap:Z.rawToSpokenOffsetMap,unsupportedSemantic:J,hasMarkup:G}};var _3=Z1(),L9=new Map([["zero","0"],["one","1"],["two","2"],["three","3"],["four","4"],["five","5"],["six","6"],["seven","7"],["eight","8"],["nine","9"],["ten","10"]]),H3=[{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}],e1=(Q)=>{let Y=[];for(let J of Q.matchAll(_3)){let G=J[0],X=J.index??0;Y.push({text:G,normalized:G.toLowerCase(),start:X,end:X+G.length})}return Y},Q8=(Q)=>L9.get(Q.normalized)||Q.normalized,A3=(Q,Y)=>{let J=[];for(let G=0;G<Q.length;G++){for(let X=0;X<Y.length;X++){let Z=Q8(Q[G]),j=Q8(Y[X]);if(Z===j)J.push({spokenStartToken:G,spokenEndToken:G+1,visibleToken:X,score:10})}for(let X of H3){let Z=Q.slice(G,G+X.phrase.length);if(Z.length!==X.phrase.length)continue;if(!Z.every((j,q)=>j.normalized===X.phrase[q]))continue;for(let j=0;j<Y.length;j++){if(Y[j].normalized!==X.visible)continue;J.push({spokenStartToken:G,spokenEndToken:G+X.phrase.length,visibleToken:j,score:X.score})}}}return J},F3=(Q,Y)=>{let J=A3(Q,Y).sort((W,V)=>Q[W.spokenStartToken].start-Q[V.spokenStartToken].start||Y[W.visibleToken].start-Y[V.visibleToken].start),G=Array(J.length).fill(0),X=Array(J.length).fill(-1);for(let W=0;W<J.length;W++){let V=J[W];G[W]=V.score;for(let U=0;U<W;U++){let _=J[U];if(_.spokenEndToken<=V.spokenStartToken&&_.visibleToken<V.visibleToken){let H=V.spokenStartToken-_.spokenEndToken,F=V.visibleToken-_.visibleToken-1,N=Math.max(0,Math.abs(H-F)-2),P=G[U]+V.score-N;if(P>G[W])G[W]=P,X[W]=U}}}let Z=-1;for(let W=0;W<G.length;W++)if(Z<0||G[W]>G[Z])Z=W;if(Z<0)return[];let j=[],q=Z;while(q>=0)j.unshift(J[q]),q=X[q];return j.map((W)=>{let V=Q[W.spokenStartToken],U=Q[W.spokenEndToken-1],_=Y[W.visibleToken];return{spokenStart:V.start,spokenEnd:U.end,visibleStart:_.start,visibleEnd:_.end,score:W.score}})},M3=(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((Z,j)=>Z+j.score,0)/Q.length/10;return Math.min(1,G*X)},U1=(Q)=>{let Y=W1(Q.speechText),J=R(Q.visibleText),G=Y.spokenText,X=e1(G),Z=e1(J),j=Y.unsupportedSemantic?[]:F3(X,Z),q=M3(j,X,Z),W=G===J&&G.length>0,V=j.length===1&&j[0].score===10&&X.length<=2&&Z.length<=2,U=Y.unsupportedSemantic?"region-fallback":W?"exact-word":j.length>=2||V?q>=0.12?"anchor-span":"region-fallback":"region-fallback",_=Y.unsupportedSemantic?"unsupported":Y.hasMarkup?"raw-ssml":"plain-spoken-text";return{speechText:Q.speechText,spokenText:G,visibleText:J,playbackMode:U,boundaryOffsetMode:_,anchors:j,confidence:q,spokenTokens:X,visibleTokens:Z,rawToSpokenOffsetMap:Y.rawToSpokenOffsetMap}},Y8=(Q,Y)=>Q.find((J)=>J.start<=Y&&Y<J.end)||null,$9=(Q)=>{if(!Q)return null;if(/^<[^>]+>$/.test(Q.trim()))return null;let Y=e1(Q)[0];if(!Y)return null;return L9.get(Y.normalized)||Y.normalized},N9=(Q,Y,J)=>{let G=$9(J);if(!Y||!G)return!1;let X=Y8(Q.spokenTokens,Y.start);if(!X)return!1;return Q8(X)===G},O9=(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},z9=(Q,Y,J)=>{let G=O9(Q,Y);if(G===null)return null;let X=O9(Q,Math.max(Y,Y+J-1)),Z=Y8(Q.spokenTokens,G),j=X!==null&&X>=G?X-G+1:Z?Z.end-G:J;return{start:G,length:Math.max(1,j)}},P9=(Q,Y,J)=>{if(Y<0||Y>=Q.spokenText.length)return null;let G=Y8(Q.spokenTokens,Y);if(!G)return null;return{start:Y,length:Math.min(J,G.end-Y)}},w9=(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 Z=z9(Q,Y,X),j=P9(Q,Y,X);if(G){if(N9(Q,Z,G))return Z;if(N9(Q,j,G))return j;if($9(G))return null}return Z||j}return P9(Q,Y,X)||z9(Q,Y,X)},R9=(Q,Y)=>{if(Q.playbackMode==="region-fallback")return null;let J=Q.anchors.find((Z)=>Z.spokenStart<=Y&&Y<Z.spokenEnd);if(J)return{start:J.visibleStart,end:J.visibleEnd};let G=null,X=null;for(let Z of Q.anchors){if(Z.spokenEnd<=Y){G=Z;continue}if(Z.spokenStart>Y){X=Z;break}}if(G&&X)return{start:Math.min(G.visibleStart,X.visibleStart),end:Math.max(G.visibleEnd,X.visibleEnd)};return null};var N3=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"]]]),O3=new Map([["","function-application"],["","implicit-multiply"],["","invisible-separator"],["","invisible-plus"]]),b9=new Map([["2",["squared"]],["3",["cubed"]]]),z3=new Map([["msqrt","radical"],["mroot","radical"],["msub","subscript"],["msubsup","subsupscript"],["munder","underscript"],["mover","overscript"],["munderover","underoverscript"],["mmultiscripts","multiscript"],["menclose","enclosure"]]),P3=(Q)=>Q.replace(/\s+/g," ").trim(),_7=(Q)=>(Q.localName||Q.tagName||"").toLowerCase(),L3=(Q)=>Q.nodeType===Node.ELEMENT_NODE,E7=(Q)=>Array.from(Q.childNodes).filter(L3),J8=(Q)=>P3(Q.textContent||""),e=(Q,Y)=>({type:"element-range",quality:Y,element:Q}),$3=(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"}},w3=(Q,Y)=>{if(Y==="operator"){if(Q==="−")return"-";return Q}return Q.toLowerCase()},R3=(Q,Y,J)=>{if(J==="fraction")return["over","divided by"];if(J==="superscript")return b9.get(Q)??[];if(Q==="|")return["absolute value"];if(Y==="operator")return N3.get(Q)||[];return[]},H7=(Q)=>{let Y=Q.normalized??w3(Q.text,Q.kind||"unknown");return{id:`math-token-${Q.state.nextId++}`,kind:Q.kind,role:Q.role,text:Q.text,normalized:Y,spokenAliases:R3(Q.text,Q.kind,Q.role),sourceElement:Q.sourceElement,path:Q.path,target:Q.target||e(Q.sourceElement,"element-range"),optional:Q.optional}},A7=(Q,Y,J="tokens")=>{Q[J].push(Y)},E9=(Q,Y,J)=>{E7(Q).forEach((G,X)=>Q7(G,Y,`${J}/${_7(G)}[${X}]`))},b3=(Q,Y,J)=>{let G=E7(Q);if(G[0])Q7(G[0],Y,`${J}/numerator`);if(A7(Y,H7({state:Y,kind:"structure",role:"fraction",text:"/",sourceElement:Q,path:J,target:e(Q,"element-range")})),G[1])Q7(G[1],Y,`${J}/denominator`)},E3=(Q,Y,J)=>{let G=Q.getAttribute("open")||"(",X=Q.getAttribute("close")||")";A7(Y,H7({state:Y,kind:"operator",role:G==="|"?"absolute-value-fence":"open-fence",text:G,sourceElement:Q,path:`${J}/open`,target:e(Q,"element-range")})),E9(Q,Y,J),A7(Y,H7({state:Y,kind:"operator",role:X==="|"?"absolute-value-fence":"close-fence",text:X,sourceElement:Q,path:`${J}/close`,target:e(Q,"element-range")}))},S3=(Q,Y,J)=>{let G=E7(Q);if(G[0])Q7(G[0],Y,`${J}/base`);let X=G[1];if(!X)return;let Z=J8(X);if(b9.has(Z)){A7(Y,H7({state:Y,kind:"structure",role:"superscript",text:Z,normalized:Z,sourceElement:X,path:`${J}/exponent`,target:e(Q,"element-range")}));return}Q7(X,Y,`${J}/exponent`)},T3=(Q,Y,J,G)=>{A7(Y,H7({state:Y,kind:"structure",role:G,text:J8(Q)||G,normalized:`\x00${G}`,sourceElement:Q,path:J,target:e(Q,"element-range")}))},C3=(Q,Y,J)=>{let G=0;for(let X of E7(Q)){if(_7(X)==="mtr"||_7(X)==="mlabeledtr")G++,A7(Y,H7({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}/${_7(X)}[${G}]`)}},y3=(Q,Y,J)=>{let G=J8(Q);if(!G)return;let X=$3(_7(Q)),Z=X==="operator"?O3.get(G):void 0,j=Z??(X==="operator"&&(G==="("||G===")")?"grouping-fence":X);A7(Y,H7({state:Y,kind:X,role:j,text:G,sourceElement:Q,path:J,target:Z&&Q.parentElement?e(Q.parentElement,"region-fallback"):void 0,optional:Boolean(Z)||j==="grouping-fence"}))},Q7=(Q,Y,J)=>{let G=_7(Q);switch(G){case"annotation":case"annotation-xml":return;case"semantics":{let X=E7(Q).find((Z)=>{let j=_7(Z);return j!=="annotation"&&j!=="annotation-xml"});if(X)Q7(X,Y,`${J}/presentation`);return}case"mi":case"mn":case"mo":case"mtext":case"ms":case"mspace":y3(Q,Y,J);return;case"mfrac":b3(Q,Y,J);return;case"msup":S3(Q,Y,J);return;case"mfenced":E3(Q,Y,J);return;case"mtable":C3(Q,Y,J);return;case"mphantom":return;case"maction":{let X=E7(Q)[0];if(X)Q7(X,Y,`${J}/action`);return}default:{let X=z3.get(G);if(X){T3(Q,Y,J,X);return}E9(Q,Y,J)}}},S9=(Q)=>{let Y={tokens:[],layoutTargets:[],nextId:0};return Q7(Q,Y,"/math"),{tokens:Y.tokens,layoutTargets:Y.layoutTargets,expressionTarget:e(Q,"region-fallback")}};var T9=(Q)=>{if(!Q.boundary)return null;return Q.alignment.segments.find((J)=>J.speechTokenIds.includes(Q.boundary.token.id))?.target||null};var x3=(Q)=>{let Y=[],J=new Set,G=(X)=>{let Z=X.toLowerCase().trim().split(/\s+/).filter(Boolean);if(Z.length===0)return;let j=Z.join(" ");if(J.has(j))return;J.add(j),Y.push(Z)};G(Q.normalized);for(let X of Q.spokenAliases)G(X);return Y},C9=(Q,Y,J)=>{let G=0;for(let X of J){if(X.length<=G)continue;let Z=!0;for(let j=0;j<X.length;j++){let q=Q[Y+j];if(!q||q.normalized.toLowerCase()!==X[j]){Z=!1;break}}if(Z)G=X.length}return G},f3=(Q,Y)=>{let J=[],G=0;for(let X of Y){let Z=x3(X);if(X.optional){let j=C9(Q,G,Z);if(j>0)J.push({speechTokens:Q.slice(G,G+j),math:X}),G+=j;continue}while(G<Q.length){let j=C9(Q,G,Z);if(j>0){J.push({speechTokens:Q.slice(G,G+j),math:X}),G+=j;break}G++}}return J},k3=(Q,Y,J)=>{let G=J.filter((j)=>!j.optional).length,X=Q.filter((j)=>!j.math.optional).length,Z=Q.reduce((j,q)=>j+q.speechTokens.length,0);return G>0&&X===G&&Z===Y.length},I3=(Q)=>Q.map(({speechTokens:Y,math:J})=>({speechTokenIds:Y.map((G)=>G.id),mathTokenIds:[J.id],score:1,confidence:1,target:J.target})),y9=(Q)=>{let Y=Q.minExactWordConfidence??0.95,J=f3(Q.speech.tokens,Q.math.tokens),G=k3(J,Q.speech.tokens,Q.math.tokens)?1:0;return{segments:G>=Y?I3(J):[],confidence:G,fallbackTarget:Q.math.expressionTarget}};var x9=Z1(),v3=new Map([["zero","0"],["one","1"],["two","2"],["three","3"],["four","4"],["five","5"],["six","6"],["seven","7"],["eight","8"],["nine","9"],["ten","10"]]),f9=(Q)=>{let Y=Q.toLowerCase();return v3.get(Y)||Y},h3=(Q)=>{let Y=[];for(let J of Q.matchAll(x9)){let G=J[0],X=J.index??0;Y.push({id:`speech-token-${Y.length}`,text:G,normalized:f9(G),start:X,end:X+G.length,sourceStart:X,sourceEnd:X+G.length,coordinateSystem:"normalized-speech"})}return Y},F7=(Q)=>{let Y=W1(Q.speechText);return{speechText:Q.speechText,spokenText:Y.spokenText,tokens:h3(Y.spokenText),rawToSpokenOffsetMap:Y.rawToSpokenOffsetMap,boundaryOffsetSpace:Y.unsupportedSemantic?"unsupported":Y.hasMarkup?"raw-ssml":"plain-spoken-text",unsupportedSemantic:Y.unsupportedSemantic,hasMarkup:Y.hasMarkup}},Z8=(Q)=>{if(!Q)return null;if(/^<[^>]+>$/.test(Q.trim()))return null;let Y=Q.match(x9);if(!Y?.[0])return null;return f9(Y[0])},m3=(Q,Y)=>Q.find((J)=>J.start<=Y&&Y<J.end)||null,u3=(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},G8=(Q,Y,J)=>{if(Y===null)return null;let G=m3(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}},X8=(Q,Y)=>{let J=Z8(Y);return Boolean(Q&&J&&Q.token.normalized===J)},j8=(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=G8(Q.tokenization,u3(Q.tokenization,Q.position),Y),G=G8(Q.tokenization,Q.position>=0&&Q.position<Q.tokenization.spokenText.length?Q.position:null,Y);if(X8(J,Q.boundaryWord))return{...J,confidence:1};if(X8(G,Q.boundaryWord))return{...G,confidence:1};if(Q.boundaryWord&&Z8(Q.boundaryWord))return null;return Q.tokenization.boundaryOffsetSpace==="raw-ssml"?J||G:G||J},k9=(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=G8(Q.tokenization,Q.position>=0&&Q.position<Q.tokenization.spokenText.length?Q.position:null,Y);if(X8(J,Q.boundaryWord))return{...J,confidence:1};if(Q.boundaryWord&&Z8(Q.boundaryWord))return null;return J};var S7=(Q)=>{let Y=F7({speechText:Q.speechText}),J=S9(Q.mathElement);return{speech:Y,math:J,result:y9({speech:Y,math:J})}};var I9=(Q,Y)=>{let J=k9({tokenization:Q.speech,position:Y.position,length:Y.length,boundaryWord:Y.boundaryWord});return T9({alignment:Q.result,boundary:J})},v9=(Q,Y)=>{if(!Y.boundaryWord||/^<[^>]+>$/.test(Y.boundaryWord.trim()))return null;let J=F7({speechText:Y.boundaryWord}).tokens[0];if(!J)return null;let G=Q.math.tokens.filter((X)=>{let Z=J.normalized.toLowerCase();return X.normalized.toLowerCase()===Z||X.spokenAliases.some((j)=>j.toLowerCase()===Z)});return G.length===1?G[0].target:null};var p3=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"]),g3=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"]),h9=(Q)=>Q.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">"),c3=(Q)=>h9(Q).replace(/"/g,"""),l3=(Q,Y)=>{let J=Q.toLowerCase(),G=Y.trim().toLowerCase();if(J.startsWith("on"))return!0;if(!g3.has(J))return!0;if(G.includes("javascript:"))return!0;if(G.includes("data:text/html"))return!0;return!1},d3=(Q)=>{let Y=Q.localName.toLowerCase();if(!p3.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"},m9=(Q)=>{if(Q.nodeType===Node.TEXT_NODE)return h9(Q.textContent||"");if(Q.nodeType===Node.COMMENT_NODE)return"";if(Q.nodeType!==Node.ELEMENT_NODE)return null;let Y=Q;if(!d3(Y))return null;let J=Y.localName.toLowerCase(),G=[];for(let j of Array.from(Y.attributes)){let q=j.name.toLowerCase();if(l3(q,j.value))continue;if(q==="xmlns"&&j.value!=="http://www.w3.org/1998/Math/MathML")return null;G.push(`${q}="${c3(j.value)}"`)}if(J==="math"&&!G.some((j)=>j.startsWith("xmlns=")))G.unshift('xmlns="http://www.w3.org/1998/Math/MathML"');let X=[];for(let j of Array.from(Y.childNodes)){let q=m9(j);if(q===null)return null;X.push(q)}let Z=G.length>0?` ${G.join(" ")}`:"";return`<${J}${Z}>${X.join("")}</${J}>`},i3=(Q)=>{if(typeof DOMParser<"u")return new DOMParser().parseFromString(Q,"application/xml");return null},V1=(Q)=>{let Y=String(Q||"").trim();if(!Y)return null;let J=i3(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 m9(G)};var u9=(Q)=>({chars:[],map:new Map,position:0,inLeadingWhitespace:!0,lastCharWasWhitespace:!1,lastMapped:null,options:Q}),p9=(Q)=>Q.classList?.contains("MathJax")||Q.tagName?.toLowerCase()==="mjx-container",g9=(Q)=>Q.tagName?.toLowerCase()==="mjx-assistive-mml",c9=(Q)=>{let Y=Q.tagName?.toLowerCase();return Y==="annotation"||Y==="annotation-xml"},s3=(Q)=>{let Y=Q.getAttribute("data-mathml");return Y&&Y.trim()?Y:null},n3=(Q)=>{return Q.querySelector("mjx-assistive-mml math")?.outerHTML||null},r3=(Q)=>{if(Q.tagName.toLowerCase()==="math")return V1(Q.outerHTML);let Y=s3(Q);if(Y){let J=V1(Y);if(J)return J}if(p9(Q)){let J=n3(Q);if(J){let G=V1(J);if(G)return G}}return null};var o3=new Set(["P","H1","H2","H3","H4","H5","H6","LI","TD","TH","DD","DT","FIGCAPTION","LABEL","BUTTON"]),a3=new Set(["heading","listitem","option","radio","row","cell","columnheader","rowheader"]),t3=(Q,Y)=>{let J=Q.parentElement,G=null;while(J&&J!==Y){let X=(J.getAttribute("role")||"").toLowerCase(),Z=J.tagName.toUpperCase();if(o3.has(Z)||a3.has(X)){G=J;break}J=J.parentElement}return G||Y},e3=(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")||p9(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++},l9=(Q,Y)=>{if(Q.inLeadingWhitespace||Q.lastCharWasWhitespace||Q.chars.length===0)return!1;let J=Q.chars[Q.chars.length-1];return t1(J,Y,Q.options)},d9=(Q,Y)=>{let J=Y.textContent||"",G=!1;for(let X=0;X<J.length;X++){let Z=J[X],j=/\s/.test(Z);if(Q.inLeadingWhitespace){if(!j)Q.inLeadingWhitespace=!1,M7(Q,Z,{node:Y,offset:X}),G=!0,Q.lastCharWasWhitespace=!1;continue}if(j){if(!Q.lastCharWasWhitespace)M7(Q," ",{node:Y,offset:X});Q.lastCharWasWhitespace=!0;continue}if(!G&&l9(Q,Z))M7(Q," ",{node:Y,offset:X});M7(Q,Z,{node:Y,offset:X}),G=!0,Q.lastCharWasWhitespace=!1}},Q2=(Q,Y)=>{for(let J=0;J<Y.text.length;J++){let G=Y.text[J],X=/\s/.test(G),Z=Y.map.get(J)||null,j=Z?.node||Q.lastMapped?.node||null,q=Z?.offset??Q.lastMapped?.offset??0,W=Z?{node:Z.node,offset:Z.offset}:j?{node:j,offset:q}:null;if(Q.inLeadingWhitespace){if(X)continue;Q.inLeadingWhitespace=!1}if(X){if(!Q.lastCharWasWhitespace)M7(Q," ",W);Q.lastCharWasWhitespace=!0;continue}if(J===0&&l9(Q,G))M7(Q," ",W);if(M7(Q,G,W),Q.lastCharWasWhitespace=!1,Z)Q.map.set(Q.position-1,{node:Z.node,offset:Z.offset}),Q.lastMapped={node:Z.node,offset:Z.offset};else if(j)Q.map.set(Q.position-1,{node:j,offset:q})}},Y2=(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 j=X.textContent||"";if(j.trim())J.push(j);return}if(X.nodeType!==1)return;let Z=X;if(c9(Z))return;for(let j of Array.from(Z.childNodes))G(j)};return G(Y.documentElement),R(J.join(" "))},J2=(Q,Y,J)=>{let G=u9(J),X=(q)=>{if(D7(q,Q))return;if(q.nodeType===3){d9(G,q);return}if(q.nodeType!==1)return;let W=q;if(g9(W)||c9(W))return;for(let V of Array.from(W.childNodes))X(V)};X(Q),i9(G);let Z=R(G.chars.join(""));if(Z)return{text:Z,map:G.map};let j=Y2(Y);if(!j)return b7(Q,J);return{text:j,map:new Map}},i9=(Q)=>{while(Q.chars.length>0&&/\s/.test(Q.chars[Q.chars.length-1]))Q.chars.pop(),Q.position--,Q.map.delete(Q.position)},G2=(Q,Y)=>{let J=u9(Y),G=[],X=0,Z,j=!1,q=()=>{let U=R(J.chars.slice(X,J.chars.length).join(""));if(U)G.push({type:"text",text:U,sourceElement:Z});X=J.chars.length,Z=void 0},W=(U)=>{if(D7(U,Q))return;if(U.nodeType===Node.TEXT_NODE){let F=t3(U,Q);if(Z&&F!==Z)q();Z=F,d9(J,U);return}if(U.nodeType!==Node.ELEMENT_NODE)return;let _=U;if(g9(_))return;let H=r3(_);if(H){q();let F=J2(_,H,Y);Q2(J,F);let N=R(F.text);G.push({type:"math",mathml:H,fallbackText:N,sourceElement:_}),X=J.chars.length,j=!0;return}for(let F of Array.from(_.childNodes))W(F)};for(let U of Array.from(Q.childNodes))W(U);i9(J),q();let V=J.chars.join("");while(J.map.has(V.length))J.map.delete(V.length);return{visibleText:V,map:J.map,chunks:G,containsMathMarkup:j}},N7=(Q,Y)=>{if(!e3(Q)){let{text:J,map:G}=b7(Q,Y);return{visibleText:J,map:G,chunks:J?[{type:"text",text:J}]:[],containsMathMarkup:!1}}return G2(Q,Y)};var q8=null,s9=Promise.resolve(),Z2=(Q)=>(Q||"en").split("-")[0].toLowerCase()||"en",j2=async()=>{if(!q8)q8=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 q8},q2=(Q)=>Q==="en"?"clearspeak":"mathspeak",n9=(Q)=>!!Q&&typeof Q==="object"&&!Array.isArray(Q),r9=(Q)=>typeof Q==="string"&&Q.trim()?Q.trim():void 0,O7=(Q)=>{if(!n9(Q))return;let Y=r9(Q.domain),J=r9(Q.style),G=n9(Q.engineOptions)?Q.engineOptions:void 0;if(!Y&&!J&&!G)return;return{...Y?{domain:Y}:{},...J?{style:J}:{},...G?{engineOptions:G}:{}}},K2=async(Q,Y,J,G)=>{let X=Z2(Y),Z=O7(G);await Q.setupEngine?.({...Z?.engineOptions||{},locale:X,domain:Z?.domain||q2(X),...Z?.style?{style:Z.style}:{},modality:"speech",markup:J}),await Q.engineReady?.()},W2=async(Q)=>{let Y=s9.then(Q,Q);return s9=Y.then(()=>{return},()=>{return}),Y},o9=async(Q,Y,J,G,X)=>W2(async()=>{return await K2(Q,J,G,X),Q.toSpeech(Y)}),U2=(Q)=>Q.replace(/^\s*<\?xml[^>]*\?>\s*/i,""),V2=async(Q,Y,J,G)=>{try{let X=U2(await o9(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}},B1=async(Q,Y={})=>{if(!Q.some((V)=>V.type==="math"))return{speechText:R(Q.map((V)=>V.type==="text"?V.text:V.fallbackText).join(" ")),usedMathSpeech:!1,usedFallback:!1};let J=null,G=!1,X=!1,Z=Y.loadSre||j2,j=[];for(let V of Q){if(V.type==="text"){j.push(V.text);continue}try{if(!J)J=await Z();let U=R(await o9(J,V.mathml,Y.language,"none",Y.mathSpeech));if(U){j.push(U),G=!0;continue}X=!0,j.push(V.fallbackText)}catch(U){X=!0,console.debug("[TTSService] Math speech generation failed; using visible fallback",{message:U instanceof Error?U.message:String(U)}),j.push(V.fallbackText)}}let q=R(j.join(" ")),W;if(Y.produceSsml&&J&&G&&Q.length===1&&Q[0].type==="math")W=await V2(J,Q[0].mathml,Y.language,Y.mathSpeech)??void 0;return{speechText:q,usedMathSpeech:G,usedFallback:X,ssml:W}};var B2=(Q,Y)=>B1([Q],Y),D2=(Q)=>(Q||"en").split("-")[0].toLowerCase()||"en",_2=new Set(["H1","H2","H3","H4","H5","H6","LI","LABEL","BUTTON"]),H2=new Set(["heading","listitem","option","radio"]),A2=(Q)=>{if(Q.type!=="text"||!Q.sourceElement)return!1;let Y=Q.sourceElement.tagName.toUpperCase(),J=(Q.sourceElement.getAttribute("role")||"").toLowerCase();return _2.has(Y)||H2.has(J)},K8=async(Q)=>{let Y=Q.resolveMathSpeech??B2,{visibleText:J}=Q,G=[],X=0,Z=(q)=>{let W=R(q),V=J.indexOf(W,X),U=V>=0?V:X,_=U+W.length;return X=_,{start:U,end:_}},j=[];for(let q=0;q<Q.chunks.length;q++){let W=Q.chunks[q];if(W.type==="text"){let F=A2(W)?[{text:W.text,offset:0}]:w7(W.text,{locale:Q.language});for(let N of F){let P=R(N.text);if(!P)continue;let f=Z(P);G.push({sourceChunkIndex:q,segment:{kind:"prose",spokenText:P,visibleText:P,visibleSpan:f}}),j.push(P)}continue}let V=Z(W.fallbackText),U=await Y(W,{language:Q.language,produceSsml:Q.produceSsml,mathSpeech:Q.mathSpeech}),_=!U.speechText,H=U.speechText||W.fallbackText;G.push({sourceChunkIndex:q,segment:{kind:"math",spokenText:H,mathml:W.mathml,fallbackText:W.fallbackText,visibleSpan:V,usedFallback:_,ssml:U.ssml}}),j.push(H)}return{segments:G,locale:D2(Q.language),visibleText:J,plainSpeechText:R(j.join(" "))}};var F2=(Q)=>(Q||"en").split("-")[0].toLowerCase()||"en",M2="sre-v1",N2=256,W8=(Q)=>{if(Array.isArray(Q))return`array:[${Q.map(W8).join(",")}]`;if(Q&&typeof Q==="object")return`object:{${Object.entries(Q).sort(([Y],[J])=>Y.localeCompare(J)).map(([Y,J])=>`${JSON.stringify(Y)}:${W8(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)}`},a9=(Q,Y,J,G)=>`${M2}\x00${F2(Q)}\x00${Y?"ssml":"plain"}\x00${W8(J??null)}\x00${G}`,U8=(Q={})=>{let Y=Math.max(1,Q.maxEntries??N2),J=Q.resolve??((Z,j)=>B1([Z],j)),G=new Map,X=(Z,j)=>{G.delete(Z),G.set(Z,j);while(G.size>Y){let q=G.keys().next().value;if(q!==void 0)G.delete(q)}};return async(Z,j)=>{let q=O7(j.mathSpeech),W=j.produceSsml===!0,V=a9(j.language,W,q,Z.mathml),U=G.get(V);if(U)return G.delete(V),G.set(V,U),U;let _=await J(Z,{...j,mathSpeech:q});if(W&&_.ssml&&Y>1)X(a9(j.language,!1,q,Z.mathml),{speechText:_.speechText,usedMathSpeech:_.usedMathSpeech,usedFallback:_.usedFallback});return X(V,_),_}};var O2=(Q)=>{if(!Q||/^<[^>]+>$/.test(Q.trim()))return null;return F7({speechText:Q}).tokens[0]?.normalized||null},z2=(Q,Y)=>{let J=F7({speechText:Q.speechText});if(!Number.isFinite(Y.position))return{boundary:null,spokenText:J.spokenText};let G=j8({tokenization:J,position:Y.position,length:Y.length,boundaryWord:Y.word});return{boundary:G?{start:G.start,length:G.length}:null,spokenText:J.spokenText}},P2=(Q,Y,J)=>{if(!J)return!0;return F7({speechText:Q}).tokens.find((X)=>X.start<=Y&&Y<X.end)?.normalized===J},t9=(Q,Y)=>{let J=O2(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=w9(Q.catalogAlignment,Y.position,Y.length,Y.word),X=Q.catalogAlignment.spokenText;else{let Z=z2(Q,Y);G=Z.boundary,X=Z.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(!P2(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 z7=(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 Q6=new Map([["mi","mjx-mi"],["mn","mjx-mn"],["mo","mjx-mo"],["mtext","mjx-mtext"]]),V8="mi,mn,mo,mtext",Y6="mjx-mi,mjx-mn,mjx-mo,mjx-mtext",J6=["mjx-mfrac","mjx-msqrt","mjx-mroot","mjx-mtable","mjx-munder","mjx-mover","mjx-munderover"].join(","),G6=(Q)=>{if(Q.type==="text-range")return Q.node.parentElement;return Q.element},D1=(Q)=>{let Y=Q;while(Y){if(Y.localName?.toLowerCase()==="mjx-container")return Y;Y=Y.parentElement}return null},e9=(Q)=>{if(!Q)return!1;if(D1(Q))return!1;return!j1(Q)},X6=(Q)=>{let Y=Q.getBoundingClientRect?.();return Boolean(Y&&Y.width>0&&Y.height>0)},B8=(Q)=>{let Y=Q;while(Y){if(Y.localName?.toLowerCase()==="math")return Y;Y=Y.parentElement}return null},Z6=(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=Q6.get(Q[J].localName.toLowerCase());if(!G)return!1;if(Y[J].localName.toLowerCase()!==G)return!1}return!0},L2=(Q,Y)=>{if(!Q)return null;if(!Q6.has(Q.localName.toLowerCase()))return null;if(Y.querySelector(J6))return null;let J=B8(Q),G=Y.querySelector("mjx-math");if(!J||!G)return null;let X=Array.from(J.querySelectorAll(V8)),Z=X.indexOf(Q);if(Z<0)return null;let j=Array.from(G.querySelectorAll(Y6));if(!Z6(X,j))return null;let q=j[Z];if(!q||!X6(q))return null;return q},j6=(Q)=>{let Y=D1(Q);if(Y){if(Y.querySelector(J6))return"expression";let X=B8(Q)??Q,Z=Y.querySelector("mjx-math");if(!Z)return"expression";let j=Array.from(X.querySelectorAll(V8)),q=Array.from(Z.querySelectorAll(Y6));if(!Z6(j,q))return"expression";return q.some((W)=>X6(W))?"token":"expression"}let J=B8(Q)??Q;return Array.from(J.querySelectorAll(V8)).some((X)=>!j1(X))?"token":"expression"},D8=(Q)=>{let Y=G6(Q),J=D1(Y);if(J){let G=L2(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(!e9(Q.node.parentElement))return null;return{type:"text-range",quality:"semantic-token",node:Q.node,startOffset:Q.startOffset,endOffset:Q.endOffset}}if(!e9(Q.element))return null;return{type:"element",quality:Q.quality==="region-fallback"?"expression":"semantic-token",element:Q.element}},q6=D8,K6=()=>{let Q=new WeakMap;return(Y)=>{let J=G6(Y),G=D1(J);if(!J||!G)return D8(Y);if(Q.has(J))return Q.get(J)??null;let X=D8(Y);return Q.set(J,X),X}};var W6=(Q,Y,J,G=Q.mathAlignments,X=q6)=>{if(Y.chunkSpokenStart===null||Y.chunkSpokenEnd===null)return null;let Z=null;for(let j of G){let q=I9(j.alignment,{position:Y.chunkSpokenStart,length:Math.max(1,Y.chunkSpokenEnd-Y.chunkSpokenStart),boundaryWord:J.word})||v9(j.alignment,{boundaryWord:J.word});if(!q)continue;let W=X(q);if(!W)continue;if(W.quality==="semantic-token")return W;Z??=W}return Z};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 Z=document.createRange();return Z.setStart(G.node,G.offset),Z.setEnd(X.node,X.offset+1),Z}catch{return null}};var U6=(Q,Y)=>{if(!Q.catalogAlignment||Y.chunkSpokenStart===null)return null;let J=R9(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 $2=(Q)=>Q.regionRange?{type:"range",quality:"region",range:Q.regionRange}:Q.regionElement?{type:"element",quality:"region",element:Q.regionElement}:null,V6=(Q,Y=Q.chunk.mathAlignments)=>{if(Y.length!==1)return null;let J=Y[0]?.alignment.result.fallbackTarget;return J?Q.renderedMathTargetResolver(J):null},w2=(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}})},B6=()=>({activeTarget:null,regionTarget:null,quality:"region",confidence:0,reason:"boundary chunk id was not found"}),D6=(Q)=>Q.length===1?Q[0].element:null,R2=(Q,Y)=>Y.length>0&&Y.every(({element:J})=>Q.mathCapabilityByElement.get(J)==="token"),b2=3,E2=(Q,Y,J)=>{if(!Y||Y.type!=="range")return!1;let{startContainer:G,endContainer:X}=Y.range;if(G===X&&G.nodeType===b2)return!1;return J.some(({element:j})=>Q.mathCapabilityByElement.get(j)==="token"&&j.contains(G)&&j.contains(X))},S2=(Q,Y)=>({chunk:Q,regionTarget:$2(Q),renderedMathTargetResolver:K6(),mathCapabilityByElement:new Map(Q.mathAlignments.map(({element:J})=>[J,Y?j6(J):"expression"])),heldTokenByElement:new Map}),_6=(Q)=>{let Y=Q.mathTokenHighlighting!==!1,J=new Map(Q.chunks.map((G)=>[G.id,S2(G,Y)]));return{chunks:Q.chunks,resolveInitial(G){let X=J.get(G);if(!X)return B6();let Z=X.chunk.mathAlignments,j=Z.length===1?Z[0].element:null,q=j?X.mathCapabilityByElement.get(j):null;if(q==="expression")return z7({semanticTarget:null,expressionTarget:V6(X),regionTarget:X.regionTarget,confidence:0.5,reason:"initial expression (sticky expression mode)"});return z7({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 B6();let{chunk:Z}=X,j=t9(Z,G),q=U6(Z,j),W=w2(q,Z),V=(!q||W.length>0?W6(Z,j,G,W,X.renderedMathTargetResolver):null)||null,U=Y&&V&&V.quality!=="expression"?V:null,_=V&&V.quality==="expression"?V:null;if(U){let H=D6(W);if(H)X.heldTokenByElement.set(H,U);return z7({semanticTarget:U,expressionTarget:null,regionTarget:X.regionTarget,confidence:j.confidence,reason:j.reason})}if(q&&(Y?!E2(X,q,W):W.length===0))return z7({semanticTarget:q,expressionTarget:null,regionTarget:X.regionTarget,confidence:j.confidence,reason:j.reason});if(R2(X,W)){let H=D6(W),F=H?X.heldTokenByElement.get(H)??null:null;return z7({semanticTarget:F,expressionTarget:null,regionTarget:X.regionTarget,confidence:j.confidence,reason:F?"hold last token (sticky token mode)":"region (sticky token mode, awaiting first token)"})}return z7({semanticTarget:null,expressionTarget:_??V6(X,W),regionTarget:X.regionTarget,confidence:j.confidence,reason:j.reason})}}};var T2=(Q)=>{if(Q.alignment?.boundaryOffsetMode)return Q.alignment.boundaryOffsetMode;let Y=Q.mathAlignment?.speech.boundaryOffsetSpace;if(Y)return Y;return"plain-spoken-text"},C2=(Q)=>{if(Q.mathAlignments?.length)return Q.mathAlignments;if(Q.mathAlignment&&Q.sourceElement)return[{element:Q.sourceElement,alignment:Q.mathAlignment}];return[]},H6=(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:C2(J),offsetSpace:T2(J)}))};var y2=["[data-pie-tts-region]","[data-catalog-region]","li","p","label","section","[role='group']","[role='region']","div"].join(","),H1=(Q,Y)=>{let J=Q.closest(y2);if(J&&Y.contains(J))return J;return Q};var x2=(Q,Y,J)=>{let G=new Map;for(let X=Y;X<J;X++){let Z=Q.get(X);if(Z)G.set(X-Y,Z)}return G},_8=async(Q)=>{let Y=N7(Q.contentRoot,Q.textProcessingOptions),J=await K8({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:Z})=>{let j=Y.chunks[Z];if(X.kind==="prose"){let W=j?.type==="text"?j.sourceElement??Q.contentRoot:Q.contentRoot;return{segment:X,anchor:{sourceElement:W,regionElement:H1(W,Q.contentRoot),visibleMap:x2(Y.map,X.visibleSpan.start,X.visibleSpan.end)}}}let q=j?.type==="math"?j.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 f2=(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:_1(Y.visibleMap,0,Q.visibleText.length)??void 0,speechMatchesVisibleText:!0,playbackMode:J.playbackMode,alignment:J,visibleMap:Y.visibleMap}},A6=(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}},k2=(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:A6(Q,Y)}},H8=(Q,Y={})=>Q.items.map(({segment:J,anchor:G})=>{if(J.kind==="prose")return f2(J,G);if(Y.format==="ssml"&&J.ssml)return k2(J,G,J.ssml);return A6(J,G)});var F6="pie-tts-control-handoff";var b;(function(Q){Q.IDLE="idle",Q.LOADING="loading",Q.PLAYING="playing",Q.PAUSED="paused",Q.ERROR="error"})(b||(b={}));var M6=(Q,Y)=>Q===Y||Q.startContainer===Y.startContainer&&Q.startOffset===Y.startOffset&&Q.endContainer===Y.endContainer&&Q.endOffset===Y.endOffset,I2=(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 M6(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=b.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;activeHighlightMode="word";lastRenderedRegionTarget=null;telemetryReporter=null;generatedMathSpeechResolver=U8();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)}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:!M6(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 Z=[],j=[];for(let q of X){if(typeof Range<"u"&&q instanceof Range){if(!this.isRangeWithinScope(q,G))return{ranges:Q,elements:[]};Z.push(q);continue}if(typeof Element<"u"&&q instanceof Element){if(!this.isElementWithinScope(q,G))return{ranges:Q,elements:[]};j.push(q);continue}return{ranges:Q,elements:[]}}return{ranges:Z,elements:j}}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,h.TTS_WORD,B7.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 Z=document.createRange();Z.selectNodeContents(X),G.push(Z)}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 O7(Y)}buildPositionMap(Q,Y,J){this.normalizedToDOM.clear();let{text:G,map:X}=b7(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 Z=0;Z<Math.min(Y.length,G.length);Z++)if(Y[Z]!==G[Z])return{index:Z,spokenChar:Y[Z],normalizedChar:G[Z],spokenContext:Y.substring(Math.max(0,Z-20),Z+20),normalizedContext:G.substring(Math.max(0,Z-20),Z+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(([Z,{node:j,offset:q}])=>({pos:Z,offset:q,char:j.textContent?.[q],expected:Y[Z]}))})}getStructuralPauseProfile(){let Y=(this.ttsConfig.providerOptions||{}).structuralPauses||{},J=Y.units||{},G=(X,Z)=>{if(typeof X==="number"&&Number.isFinite(X))return X;if(typeof X==="string"&&X.trim()){let j=Number(X);return Number.isFinite(j)?j:Z}return Z};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 o1(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 Z=Number(J.getAttribute("data-tts-break-ms"));if(Number.isFinite(Z)&&Z>0)return{anchor:J,units:Z/this.getStructuralPauseProfile().baseMs};let j=(J.getAttribute("role")||"").toLowerCase(),q=J.tagName.toUpperCase();if(q.match(/^H[1-6]$/)||j==="heading"||j==="listitem"||q==="LI"){G=J;break}if(!G){if(typeof window<"u"){let W=window.getComputedStyle(J).display;if(W==="block"||W==="list-item"||W.startsWith("table")||W==="flex"||W==="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),Z=document.createTreeWalker(Q,NodeFilter.SHOW_TEXT),j=Z.nextNode(),q=null;while(j){let W=j,V=W.parentElement;if(V&&!this.isElementHidden(V)&&!q1(W)){let U=this.getBoundaryAnchor(W,Q),_=X.get(W);if(U&&_!==void 0&&U.anchor!==q&&_>0)J.set(_,Math.max(J.get(_)||0,U.units)),q=U.anchor}j=Z.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((W)=>W>0&&W<Q.length).sort((W,V)=>W-V),G=[],X=0;for(let W of J){let V=Q.substring(X,W),U=V.match(/^\s*/)?.[0].length||0,_=V.match(/\s*$/)?.[0].length||0,H=X+U,F=W-_;if(F>H){let N=Q.substring(H,F);G.push({text:N,startOffset:H,pauseMsAfter:this.resolvePauseMsFromUnits(Y.get(W)||0)})}X=W}let j=Q.substring(X).match(/^\s*/)?.[0].length||0,q=X+j;if(q<Q.length)G.push({text:Q.substring(q).trimEnd(),startOffset:q,pauseMsAfter:0});return G.filter((W)=>W.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((Z)=>Number.isFinite(Z)&&Z>0).sort((Z,j)=>Z-j);if(G.length===0)return Q;let X=[];for(let Z of Q){let j=Z.startOffset,q=Z.startOffset+Z.text.length,W=G.filter((U)=>U>j&&U<q);if(W.length===0){X.push(Z);continue}let V=j;for(let U of[...W,q]){let _=J.substring(V,U),H=_.match(/^\s*/)?.[0].length||0,F=_.match(/\s*$/)?.[0].length||0,N=V+H,P=U-F;if(P>N)X.push({text:J.substring(N,P),startOffset:N,pauseMsAfter:0});V=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=R(G)||J.visibleText||"",Z={text:X,startOffset:Y,pauseMsAfter:0};return Y+=Math.max(1,X.length+1),Z})}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 Z=this.provider.onWordBoundary;this.provider.onWordBoundary=(j,q,W)=>{if(Z?.(j,q,W),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=Z}return}this.configureWordBoundaryHighlighting({highlightMode:J?.highlightMode||"word",wordBoundaryOffset:this.activeWordBoundaryOffset});for(let Z of Q){if(Y!==this.speakRunId)return;let j=this.seekSegments.findIndex((W)=>W.startOffset===Z.startOffset);if(j>=0)this.currentSeekSegmentIndex=j;if(this.currentBoundaryOffset=Z.startOffset,G)this.highlightSentenceSegment(Z.startOffset,Z.text);await this.provider.speak(Z.text);let q=Z.pauseMsAfter??0;if(q>0)await new Promise((W)=>setTimeout(W,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 Z=document.createRange();Z.setStart(G.node,G.offset),Z.setEnd(X.node,X.offset+1),this.paintTTSSentenceRanges([Z]),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(([Z])=>Math.abs(Z-Q)<5).map(([Z,{offset:j,node:q}])=>({pos:Z,offset:j,char:q.textContent?.[j]}))}),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;try{if(await this.applyLanguageSettings(Y),J!==this.speakRunId)return;let G=await this.resolveSpeechContent(Q,Y);if(J!==this.speakRunId)return;let{contentToSpeak:X,speechText:Z,highlightText:j,normalizedText:q,usedCatalogSpoken:W,speechSource:V,speechMatchesVisibleText:U,speechChunks:_}=G;this.logResolvedSpeechContent({contentToSpeak:X,speechSource:V,catalogId:Y?.catalogId}),this.initializeSpeakTracking(j,Y);let H=Y?.highlightModeOverride||(U?this.resolveHighlightMode():"sentence");this.activeHighlightMode=H,this.activeWordBoundaryOffset=Y?.wordBoundaryOffset||0;let F=this.hasExplicitBreakSemantics(X),N=!!this.currentContentElement&&!W&&!F&&U;if(this.playbackChunks=_?.length?_:[],this.seekSegments=this.playbackChunks.length?this.createSeekSegmentsFromSpeechChunks(this.playbackChunks):F||!U?[]:N&&this.currentContentElement?this.createSpeechPlan(this.currentContentElement,q):this.createSeekSegmentsFromText(j),this.sentenceHighlightSegments=F?[]:this.createSentenceHighlightSegments({contentToSpeak:j,shouldUsePlan:N,playbackSegments:this.seekSegments}),this.setState(b.LOADING),this.prepareHighlightsForSpeak({contentToSpeak:j,options:Y,highlightMode:H,shouldUsePlan:N}),U)this.configureWordBoundaryHighlighting({highlightMode:H,wordBoundaryOffset:Y?.wordBoundaryOffset||0});else this.clearWordBoundaryHighlighting();if(this.setState(b.PLAYING),await this.executeSpeakPlayback({shouldUsePlan:N,runId:J,highlightMode:H,contentToSpeak:Z,speechChunks:_}),J!==this.speakRunId)return;this.setState(b.IDLE),this.clearHighlightsAndTracking()}catch(G){let X=G;if(console.error("TTS error:",X),this.lastError=X instanceof Error?X.message:String(X),J!==this.speakRunId)return;throw this.setState(b.ERROR),this.clearHighlightsAndTracking(),X}}async switchProviderToBrowser(Q,Y){if(!this.currentProvider)return!1;let J=new R7,G=this.currentProvider.providerId,X={...this.ttsConfig},Z=Y?.operation||"tts-initialize",j=Y?.contentToSpeak??"",q=j.replace(/\s+/g," ").trim().slice(0,120),W=j.length>0?{textLength:j.length,textPreview:q.length<j.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:Z,fromProvider:G,toProvider:J.providerId,reason:Q instanceof Error?Q.message:String(Q),...W}),console.warn("[TTSService] TTS provider initialization failed; switched to browser fallback",{fromProvider:G,reason:Q,...W}),!0}catch(V){return await this.emitTelemetry("pie-tool-runtime-fallback-error",{toolId:"textToSpeech",operation:Z,fromProvider:G,toProvider:"browser",errorType:"TTSRuntimeFallbackError",message:V instanceof Error?V.message:String(V)}),console.error("[TTSService] Failed to switch to browser fallback provider",V),!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=R(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 Z=this.catalogResolver.getAlternative(Y.catalogId,{type:"spoken",language:Y.language||"en-US",useFallback:!0,context:Y.catalogContext,form:"content"}),j=Z?.content;if(Z&&j!==void 0){let q=Y?.contentElement?N7(Y.contentElement,this.getTextProcessingOptions(Y.language)).visibleText||J:J,W=R(j);return this.debugLog(`[TTSService] Using catalog content for "${Y.catalogId}" (${Z.language})`),{contentToSpeak:j,speechText:j,visibleText:q,highlightText:q,usedCatalogSpoken:!0,speechSource:"catalog-spoken",normalizedText:q,containsMathMarkup:!1,speechMatchesVisibleText:W===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((j)=>j.sourceElement))return null;let X=R(G.map((j)=>j.speechText).join(" ")),Z=N7(Q,this.getTextProcessingOptions(J.language)).visibleText||Y;return{contentToSpeak:X,speechText:X,visibleText:Z,highlightText:Z,usedCatalogSpoken:!0,speechSource:"catalog-spoken",normalizedText:Z,containsMathMarkup:!1,speechMatchesVisibleText:G.every((j)=>j.speechMatchesVisibleText),speechChunks:G}}collectCatalogSpeechChunks(Q,Y){let J=[],G="",X=()=>{let V=R(G);if(G="",!V)return;J.push({speechText:V,visibleText:V,sourceElement:null,speechMatchesVisibleText:!0})},Z=(V)=>{let U=V.getAttribute("data-catalog-idref");if(!U)return null;let _={type:"spoken",language:Y.language||"en-US",useFallback:!0,context:Y.catalogContext},H=this.catalogResolver.getAlternative(U,{..._,form:"payload"}),F=H?.payload?U9({payload:H.payload})??void 0:void 0,P=this.catalogResolver.getAlternative(U,{..._,form:"content"})?.content;if(F===void 0&&P===void 0)return null;return{script:P,audio:F}},j=(V,U)=>{let _=q(V);if(_.length!==1)return null;let H=_[0],F=N7(H,this.getTextProcessingOptions(Y.language)).visibleText||R(H.textContent||""),N=(P)=>R(P).replace(/\s+/g,"");return N(F)===N(U)?H:null},q=(V)=>{let U=Array.from(V.querySelectorAll("math"));if(V.localName?.toLowerCase()==="math")return[V,...U];return U},W=(V)=>{if(D7(V,Q))return;if(V.nodeType===Node.TEXT_NODE){G+=` ${V.textContent||""}`;return}if(V.nodeType!==Node.ELEMENT_NODE)return;let U=V,_=Z(U);if(_){X();let H=N7(U,this.getTextProcessingOptions(Y.language)),F=H.visibleText||R(U.textContent||""),N=H1(U,Q),P=_.script!==void 0?(()=>{let f=_.script,A=U1({speechText:f,visibleText:F}),L=j(U,F),E=L?S7({mathElement:L,speechText:f}):void 0,m=E?void 0:q(U).map((I)=>({element:I,alignment:S7({mathElement:I,speechText:f})}));return{speechText:f,visibleText:F,sourceElement:U,regionElement:N,speechMatchesVisibleText:R(f)===F,playbackMode:A.playbackMode,alignment:A,mathAlignment:E,mathAlignments:m,visibleMap:H.map}})():null;if(_.audio){J.push(P?{...P,audio:_.audio,plainFallback:P}:{speechText:F,visibleText:F,sourceElement:U,regionElement:N,speechMatchesVisibleText:!1,visibleMap:H.map,audio:_.audio});return}if(P)J.push(P);return}for(let H of Array.from(U.childNodes))W(H)};return W(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:Z,visibleText:j}=await _8({contentRoot:Q,language:J,mathSpeech:this.getMathSpeechOptions(),textProcessingOptions:this.getTextProcessingOptions(J),produceSsml:G==="ssml",resolveMathSpeech:this.generatedMathSpeechResolver}),q=j||Y;if(!Z)return{contentToSpeak:q,speechText:q,visibleText:q,highlightText:q,normalizedText:q,containsMathMarkup:!1,speechMatchesVisibleText:!0};let W=H8(X,{format:G}),V=X.plainSpeechText;return{contentToSpeak:V,speechText:V,visibleText:q,highlightText:q,normalizedText:q,containsMathMarkup:!0,speechMatchesVisibleText:V===q,speechChunks:W}}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];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,Z=J+this.currentBoundaryOffset+Q.wordBoundaryOffset;this.highlightSentenceForOffset(Z);let j=this.findHighlightRange(Z,X);if(j&&this.highlightCoordinator){let q=j.node.textContent?.substring(j.start,j.end)||"";this.debugLog(`[TTSService] Highlighting "${q}" (word: "${Y}") at position ${Z}`);let W=this.createTextRange(j.node,j.start,j.end);if(W)this.paintTTSWordRange(this.resolveWordHighlightRange(W).range);else this.highlightCoordinator.highlightTTSWord(j.node,j.start,j.end)}else console.warn(`[TTSService] Could not find highlight range for position ${Z}, 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?.(h.TTS_WORD),this.paintTTSSentenceRanges([Q.regionRange]);return}if(!Y)return;let J=document.createRange();J.selectNodeContents(Y),this.highlightCoordinator.clearHighlights?.(h.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&&I2(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(h.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){this.debugLog("[TTSService] SSML chunk speak failed; retrying plain text",{message:J instanceof Error?J.message:String(J)}),await this.speakCatalogChunkOnce(Q.plainFallback,Y);return}throw J}}async playRecordedAudio(Q){if(typeof document>"u")throw Error("[tts] no document available to play recorded audio");let Y=Q.sources[0],J=document.createElement("audio");J.preload="auto",J.src=W9(Y.src,Q.fragment),J.playbackRate=this.normalizePlaybackRate(Number(this.ttsConfig.rate||1)),await new Promise((G,X)=>{let Z,j=()=>{if(J.removeEventListener("ended",q),J.removeEventListener("error",W),Z!==void 0)clearInterval(Z);if(this.activeRecordedAudio?.element===J)this.activeRecordedAudio=null},q=()=>{j(),G()},W=()=>{j(),X(Error(`[tts] recorded audio failed to play: ${Y.src}`))};this.activeRecordedAudio={element:J,cancel:()=>{j(),J.pause(),G()}},J.addEventListener("ended",q),J.addEventListener("error",W);let V=Q.fragment?.endSeconds;if(V!==void 0)Z=setInterval(()=>{if(J.currentTime>=V)q()},100);Promise.resolve(J.play()).catch(W)}).finally(()=>{if(this.activeRecordedAudio?.element===J)this.activeRecordedAudio=null;J.pause(),J.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.highlightCatalogRegion(Q),await this.playRecordedAudio(Q.audio);return}let J=Q.regionElement||Q.sourceElement||this.currentContentElement,G=J?H6({contentRoot:J,chunks:[Q]})[0]:null,X=this.ttsConfig.mathTokenHighlighting!==!1,Z=G?_6({chunks:[G],mathTokenHighlighting:X}):null;if(Z&&G&&Q.mathAlignment)this.renderHighlightDecision(Z.resolveInitial(G.id));else this.highlightCatalogRegion(Q);if(!(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,_=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=_}return}let q=this.provider,W=q.onWordBoundary,V=(U,_,H)=>{if(Y!==this.speakRunId)return;if(Z&&G){let F=G.offsetSpace==="unsupported"?"unknown":G.offsetSpace;this.renderHighlightDecision(Z.resolveBoundary({chunkId:G.id,word:U,position:_,length:H,providerOffsetSpace:F}));return}};q.onWordBoundary=V;try{await q.speak(Q.speechText)}finally{if(this.provider===q&&Y===this.speakRunId&&q.onWordBoundary===V)q.onWordBoundary=W}}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.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=a1(Q,G),Z=X.text.trim();if(!Z){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 j=document.createRange();j.selectNodeContents(G),j.setEnd(Q.startContainer,Q.startOffset);let q=a1(j,G).text,W=R(q),V=W.length+(/\s$/.test(q)&&W?1:0);this.debugLog("[TTSService] speakRange offset calculation:",{selectedText:Z,textBeforeRange:q.substring(0,100),offset:V,rootTag:G.tagName}),await this.speak(Z,{contentElement:G,ignoreCatalogs:!0,wordBoundaryOffset:V})}pause(){if(!this.provider)return;if(this.state===b.PLAYING)this.activeRecordedAudio?.element.pause(),this.provider.pause(),this.setState(b.PAUSED)}resume(){if(!this.provider)return;if(this.state===b.PAUSED){let Q=this.activeRecordedAudio?.element;if(Q)Promise.resolve(Q.play()).catch(()=>{});this.provider.resume(),this.setState(b.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.cancelRecordedAudio(),this.provider.onWordBoundary=void 0,this.provider.stop(),this.currentSeekSegmentIndex=Y;let G=++this.speakRunId,X=this.seekSegments.slice(Y);this.setState(b.PLAYING);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 j=Y+Z;this.currentSeekSegmentIndex=j;let q=this.seekSegments[j];if(q)this.currentBoundaryOffset=q.startOffset;await this.speakCatalogChunk(J[Z],G)}else await this.speakWithPlan(X,G,{highlightMode:this.activeHighlightMode});if(G!==this.speakRunId)return;this.setState(b.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(b.ERROR),this.clearHighlightsAndTracking(),this.highlightTargetResolverProvider=null,Z}}async setPlaybackRate(Q){let Y=this.normalizePlaybackRate(Q);if(await this.updateSettings({rate:Y}),this.state!==b.PLAYING||!this.currentText||this.seekSegments.length===0||this.hasExplicitBreakSemantics(this.currentText))return;await this.restartFromSeekIndex(this.getCurrentSeekSegmentIndex())}async seekBy(Q){if(!this.provider||!this.currentText)return;if(this.state!==b.PLAYING&&this.state!==b.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.cancelRecordedAudio(),this.provider.onWordBoundary=void 0,this.provider.stop(),this.highlightTargetResolverProvider=null,this.setState(b.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}requestControlHandoff(){if(typeof window>"u")return;let Q={source:"host"};window.dispatchEvent(new CustomEvent(F6,{detail:Q}))}isPlaying(){return this.state===b.PLAYING}isPaused(){return this.state===b.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===b.PLAYING){let J=Y===b.PAUSED?"pie-tool-playback-resume":"pie-tool-playback-start";this.emitTelemetry(J,{toolId:"textToSpeech",providerId:"tts",previousState:Y,state:Q});return}if(Q===b.PAUSED){this.emitTelemetry("pie-tool-playback-pause",{toolId:"textToSpeech",providerId:"tts",previousState:Y,state:Q});return}if(Q===b.ERROR){this.emitTelemetry("pie-tool-playback-error",{toolId:"textToSpeech",providerId:"tts",previousState:Y,state:Q,message:this.lastError||void 0});return}if(Q===b.IDLE&&(Y===b.PLAYING||Y===b.PAUSED||Y===b.LOADING))this.emitTelemetry("pie-tool-playback-stop",{toolId:"textToSpeech",providerId:"tts",previousState:Y,state:Q})}}var v2=new Set(["reserved-row","expanding-row","floating-overlay","left-aligned"]),N6=(Q)=>Q&&typeof Q==="object"?Q:{},h2=(Q)=>Q==="polly"||Q==="google"||Q==="server",g=(Q,Y)=>Q===void 0?Y:Q,m2=(Q,Y="left-aligned")=>typeof Q==="string"&&v2.has(Q)?Q:Y,b4=Object.freeze([0.8,1.25]),E4=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 S4=Object.freeze([0.8,1,1.25]);var u2=(Q)=>{let Y={...Q,layoutMode:m2(Q.layoutMode)},J=Q.backend||"browser";if(!h2(J))return Y;let G={...Y,apiEndpoint:g(Y.apiEndpoint,"/api/tts"),transportMode:g(Y.transportMode,"pie"),endpointValidationMode:g(Y.endpointValidationMode,"voices"),validateEndpoint:g(Y.validateEndpoint,!0),includeAuthOnAssetFetch:g(Y.includeAuthOnAssetFetch,!1),rate:g(Y.rate,1),language:g(Y.language,"en-US")};if(J==="polly")return{...G,defaultVoice:g(G.defaultVoice,"Joanna"),engine:g(G.engine,"neural"),format:g(G.format,"mp3"),speechMarksMode:g(G.speechMarksMode,"word+sentence")};if(J==="google")return{...G,defaultVoice:g(G.defaultVoice,"en-US-Wavenet-A")};return G},O6=(Q)=>{let Y=N6(Q),J=N6(Y.settings);return u2({...Y,...J})},A8=(Q)=>Q.backend||"browser",p2=(Q,Y)=>{if(Y==="polly"||Y==="google")return Y;if(Y==="server")return Q.serverProvider||Q.provider;return Q.serverProvider||Q.provider},g2=(Q,Y)=>Q.transportMode||(Y==="custom"?"custom":"pie"),z6=(Q)=>{let Y=A8(Q),J=p2(Q,Y),G=g2(Q,J),X=O7(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=(j)=>{if(!j||typeof j!=="object")return"unknown";let q=j;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"},Z=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 j=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()-j})}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()-j,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()-Z}),console.log(`[ToolProviderRegistry] Provider "${Q}" initialized`)}catch(j){throw await this.emitTelemetry(J,"pie-tool-init-error",{toolId:Q,providerId:Q,backend:X(G),operation:"provider-initialize",duration:Date.now()-Z,errorType:"ProviderInitializationError",message:j instanceof Error?j.message:String(j)}),console.error(`[ToolProviderRegistry] Initialization failed for "${Q}":`,j),j}}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")}}function P6(Q,Y){let J=Y.decisions[0],G=Array.from(Y.perToolFlags.values())[0];return{featureId:Q,granted:J?.action==="enable",action:J?.action??"skip",rule:J?.rule??"pnp-support",precedence:J?.precedence??6,sourceType:J?.sourceType??"system",reason:J?.reason??`Feature "${Q}" not configured`,required:Boolean(G?.required),parameters:G?.settings}}class F1{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=c2(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 c2(Q){if(!Q.winningDecision){if(Q.finalState==="advisory-only"){let Z=Q.allDecisions.find((j)=>j.action==="advisory");return Z?`Feature "${Q.featureId}" was kept in its host-decided state; ${Z.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,5 +220,5 @@ ${J}`)}function J7(Q,Y={}){let J=h1(Y.strictness),G=Y.source??"tools",X=y0(Y.too
|
|
|
220
220
|
`;let X=Q.allDecisions.filter((Z)=>Z.step!==Y.step&&Z.action!=="skip"&&Z.action!=="advisory"&&Z.precedence>Y.precedence);if(X.length>0){G+=`
|
|
221
221
|
**Overridden Rules**:
|
|
222
222
|
`;for(let Z of X)G+=`- ${Z.rule}: ${Z.reason}
|
|
223
|
-
`}return G}function B8(Q){let{request:Y,tools:J,pnpPolicy:G,customSources:X,contextId:Z}=Q,j=new F1(Z);j.addSource("host",{id:Y.scope.scopeId,name:`${Y.level}:${Y.scope.scopeId}`,config:{placement:J.placement,policy:J.policy}});let q=A1(J.placement[Y.level]),U=A1(J.policy.allowed),V=new Set(A1(J.policy.blocked)),D=[];for(let H of q)D.push(H),j.addDecision({precedence:0,rule:"placement-membership",featureId:H,action:"skip",sourceType:"host",reason:`Listed in tools.placement.${Y.level}`});if(D=D.filter((H)=>{if(J.providers?.[H]?.enabled===!1)return j.addDecision({precedence:0,rule:"provider-disabled",featureId:H,action:"block",sourceType:"host",reason:`tools.providers.${H}.enabled === false`,value:!1}),!1;return!0}),U.length>0){let H=new Set(U);D=D.filter((b)=>{if(!H.has(b))return j.addDecision({precedence:0,rule:"host-allowlist",featureId:b,action:"block",sourceType:"host",reason:"Not present in tools.policy.allowed",value:U}),!1;return!0})}D=D.filter((H)=>{if(V.has(H))return j.addDecision({precedence:0,rule:"host-blocked",featureId:H,action:"block",sourceType:"host",reason:"Listed in tools.policy.blocked",value:J.policy.blocked}),!1;return!0});let _=[],F=new Map;for(let H of D)F.set(H,["placement"]);let N=new Set(D),O=null;if(G.enforcement==="on"&&G.source&&(G.assessment||G.currentItemRef)){if(O=G.source.apply({assessment:G.assessment,currentItemRef:G.currentItemRef}),O.sources.assessment)j.addSource("assessment",O.sources.assessment);if(O.sources.student)j.addSource("student",O.sources.student);if(O.sources.item)j.addSource("item",O.sources.item);for(let H of O.decisions)j.addDecision({precedence:H.precedence,rule:H.rule,featureId:H.featureId,action:H.action,sourceType:H.sourceType,reason:H.reason,value:H.value});D=D.filter((H)=>{return!O.blockedToolIds.has(H)});for(let H of Array.from(F.keys()))if(O.blockedToolIds.has(H))F.delete(H);for(let H of O.mandatedToolIds){if(!!N.has(H))continue;let u=O.perToolFlags.get(H)?.rule??"required-tool",I=B3(H,{placement:q,allowed:U,blocked:V,providers:J.providers}),p={rule:u,hostRule:I.hostRule,hostValue:I.hostValue};_.push({code:"tool-policy.requiredToolBlocked",level:Y.level,toolId:H,message:`Profile policy mandates "${H}" (${u}) but host policy removed it from level "${Y.level}" via ${I.hostRule}.`,details:p}),j.addDecision({precedence:0,rule:"required-tool-blocked",featureId:H,action:"advisory",sourceType:"host",reason:`Host removed required tool "${H}" via ${I.hostRule}`,value:p})}for(let H of D){let b=O.perToolFlags.get(H);if(b){let T=F.get(H)??[];T.push(`pnp.${b.rule}`),F.set(H,T)}}}for(let H=0;H<X.length;H++){let b=X[H],T=D.slice(),u=b.refine({request:Y,candidates:T}),I=new Set(u.refinedCandidates);for(let L of u.refinedCandidates)if(!T.includes(L))_.push({code:"tool-policy.placementMissing",level:Y.level,toolId:L,message:`Custom source "${b.id}" tried to add tool "${L}" that was not in candidates; ignored.`,source:`custom.${b.id}`}),I.delete(L);D=T.filter((L)=>I.has(L));let p=new Set;if(u.decisions){for(let L of u.decisions)if(j.addDecision({precedence:L.precedence??100+H,rule:L.rule,featureId:L.featureId,action:L.action,sourceType:L.sourceType,reason:L.reason,value:L.value}),L.action==="block")p.add(L.featureId)}for(let L of T){if(I.has(L))continue;if(p.has(L))continue;j.addDecision({precedence:100+H,rule:"custom-source",featureId:L,action:"block",sourceType:"custom",reason:`Custom policy source "${b.id}" removed tool "${L}" from candidates without emitting a decision; auto-logged for trail completeness.`,value:{customSourceId:b.id}})}for(let L of D){let g=F.get(L)??["placement"];g.push(`custom.${b.id}`),F.set(L,g)}for(let L of T)if(!I.has(L))F.delete(L)}let w=new Set(D),k=D.map((H)=>{let b=O?.perToolFlags.get(H);return{toolId:H,required:b?.required??!1,alwaysAvailable:b?.alwaysAvailable??!1,settings:b?.settings,sources:F.get(H)??["placement"]}});return j.reconcileFinalStates(w),{visibleTools:k,diagnostics:_,provenance:j.build()}}function B3(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 j6(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 Z of Object.keys(X)){let j=X[Z];if(j===void 0||j===null)continue;if(Array.isArray(j)&&j.length===0)continue;if(typeof j==="object"&&!Array.isArray(j)&&Object.keys(j).length===0)continue;return!0}}return!1}function q6(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 h7(Q){if(j6(Q.assessment))return"on";if(q6(Q.currentItemRef))return"on";return"off"}class H1{id="pnp";toolRegistry;constructor(Q){this.toolRegistry=Q}apply(Q){let{ctx:Y,result:J}=this.prepare(Q),{pnp:G,districtPolicy:X,itemSettings:Z}=Y,j=new Set;G?.supports?.forEach((q)=>j.add(q)),G?.prohibitedSupports?.forEach((q)=>j.add(q)),X?.blockedTools?.forEach((q)=>j.add(q)),X?.requiredTools?.forEach((q)=>j.add(q)),Z?.requiredTools?.forEach((q)=>j.add(q)),Z?.restrictedTools?.forEach((q)=>j.add(q));for(let q of j)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,Z=J?.settings,j={blockedToolIds:new Set,mandatedToolIds:new Set,perToolFlags:new Map,decisions:[],sources:{}};if(X?.districtPolicy||X?.testAdministration)j.sources.assessment={id:Y?.id||"unknown",name:Y?.name||Y?.id||"Assessment",config:X};if(G)j.sources.student={id:"student",name:"Student PNP Profile",config:G};if(J&&Z)j.sources.item={id:J.identifier,name:J.identifier,config:Z};return{ctx:{pnp:G,districtPolicy:X?.districtPolicy,testAdmin:X?.testAdministration,itemSettings:Z,toolConfigs:X?.toolConfigs},result:j}}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 W6=z7({policy:{allowed:[],blocked:[]},placement:{section:[],item:[],passage:[]},providers:{}});class M1{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 H1(this.toolRegistry),this.customSources=Q.customSources?[...Q.customSources]:[];let Y=Q.inputs??{};this.tools=Y.tools??W6,this.assessment=Y.assessment??null,this.currentItemRef=Y.currentItemRef??null,this.pnpEnforcement=Y.pnpEnforcement??h7({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 B8({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(),Z6(Q,this.pnpPolicySource.resolveFeature(Q,{assessment:this.assessment??void 0,currentItemRef:this.currentItemRef??void 0}))}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??W6;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 _3=Symbol("@pie-players/tool-policy-engine");var N1=(Q)=>!!Q&&typeof Q==="object"&&!Array.isArray(Q),F3=(Q,Y,J)=>{let G={...Y,...J};if(Q==="textToSpeech"&&N1(Y.settings)&&N1(J.settings)){if(G.settings={...Y.settings,...J.settings},N1(Y.settings.mathSpeech)&&N1(J.settings.mathSpeech))G.settings.mathSpeech={...Y.settings.mathSpeech,...J.settings.mathSpeech}}return G},A3=["item-selected","item-session-data-changed","item-session-meta-changed","item-complete-changed","content-loaded","item-player-error"],H3=["section-navigation-change","section-session-applied","section-loading-complete","section-items-complete-changed","section-error"];class O1{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;static resolveConfig(Q){let Y=h1(Q.toolConfigStrictness),J=Q.toolRegistry??f7(),G=Q.deferToolConfigValidation===!0?z7(Q.tools):J7(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=O1.resolveConfig(Q);if(this.assessmentId=Y.assessmentId,this.config=Y,this.toolRegistry=Y.toolRegistry??f7(),this.installToolContextResolvers(Y.toolContextResolvers),this.hooks=Y.hooks??{},this.lazyInit=Q.lazyInit===!0,this.pnpEnforcementOverride=this.resolveConfiguredPnpEnforcement(),this.frameworkErrorBus=Q.frameworkErrorBus??new x7,this.ownsFrameworkErrorBus=!Q.frameworkErrorBus,this.subscribeFrameworkErrorHookAdapters(),this.toolCoordinator=new s1,this.highlightCoordinator=new I7,this.elementToolStateStore=new l1,this.catalogResolver=new d1(Y.accessibility?.catalogs||[],Y.accessibility?.language||"en-US"),this.toolProviderRegistry=new U6,this._registerToolProviders(),this.ttsService=new v7,this.setupStatePersistenceHooks(),this.policyEngine=new M1({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=p8({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:Z}=J.key;return`pie:section-controller:v1:${G}:${X}:${Z||"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),Z=Y.getInitConfig?.(J)??J?.provider?.init??{},j=this.addToolTelemetryReporter({toolId:Q.toolId,providerId:G,initConfig:Z}),q=this.createToolTelemetryForwarder({toolId:Q.toolId,providerId:G}),U=Y.getAuthFetcher?.(J)??J?.provider?.runtime?.authFetcher;await this.registerProvider(G,{provider:X,config:j,lazy:Y.lazy??!0,authFetcher:U,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,Z)=>{if(J)await J(X,Z);await G(X,Z)},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(Z){let j=Z instanceof Error?Z:Error(String(Z));throw this.handleError(j,{phase:"provider-init",providerId:Q}),j}})().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,(j)=>{if(!G(j))return;this.deliverSectionEventSafely(Q.listener,j)});let X=this.buildContentLoadedReplayEvents(Y);for(let j of X)if(G(j))this.deliverSectionEventSafely(Q.listener,j);let Z=this.buildLoadingCompleteReplayEvent(Y);if(Z&&G(Z))this.deliverSectionEventSafely(Q.listener,Z)}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((j)=>J.has(j)))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(),Z=[];for(let j of J){if(!j)continue;let q=j.itemId,U=typeof j.canonicalItemId==="string"&&j.canonicalItemId?j.canonicalItemId:q;if(typeof q!=="string"||!q)continue;Z.push({type:"content-loaded",contentKind:j.contentKind??"unknown",itemId:q,canonicalItemId:U,currentItemIndex:G,timestamp:X})}return Z}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||A3,itemIds:Q.itemIds,listener:Q.listener})}subscribeSectionLifecycleEvents(Q){return this.subscribeSectionEvents({eventTypes:Q.eventTypes||H3,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 Z=this.initializeNewSectionController({args:Q,key:Y,mapKey:J}).catch((j)=>{throw this.handleSectionControllerInitError(j,Q),j}).finally(()=>{this.sectionControllerInitPromises.delete(J)});return this.sectionControllerInitPromises.set(J,Z),Z}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(Z){this.handleError(Z,{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=D6(Y),G=K6(J),X=V6(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(j){let q=j instanceof Error?j:Error(String(j));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 Z=new _1;try{await this.initializeTTSService(Z,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(j){let q=j instanceof Error?j:Error(String(j));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,Z)=>{await this.emitTelemetry(X,{toolId:"textToSpeech",...Z||{}})}},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((Z)=>{let j=!1,q=typeof J.addEventListener==="function"&&typeof J.removeEventListener==="function",U=!q&&"onvoiceschanged"in J,V=U?J.onvoiceschanged:null,D=!1,_=()=>{if(j)return;if(j=!0,window.clearTimeout(N),q)J.removeEventListener("voiceschanged",F);else if(D&&J.onvoiceschanged===F)J.onvoiceschanged=V;Z()},F=(O)=>{if(!q&&typeof V==="function"&&O)V.call(J,O);_()},N=window.setTimeout(_,Y);if(q)J.addEventListener("voiceschanged",F,{once:!0});else if(U)J.onvoiceschanged=F,D=!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.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=J7(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]:F3(Q,J,Y)},X=J7({...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=J7(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=J7({...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){return this.policyEngine.decideFeature(Q)}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 h7({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 B6="pie-register",_6="pie-unregister",F6="pie-item-session-changed";var A6="pie-content-loaded",H6="pie-item-player-error";var M3={bubbles:!0,composed:!0,cancelable:!1};function N3(Q,Y,J={}){return new CustomEvent(Q,{detail:Y,...M3,...J})}function _8(Q,Y,J,G={}){return Q.dispatchEvent(N3(Y,J,G))}var F8=(Q)=>Array.isArray(Q)&&Q.length>0;function O3(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 z3(Q,Y){if(!Q)return[];let J=O3(Y),G=[];if(F8(Q.accessibilityCatalogs))G.push({context:J,catalogs:Q.accessibilityCatalogs});if(F8(Q.config?.extractedCatalogs))G.push({context:J,catalogs:Q.config.extractedCatalogs});if(Y.kind==="passage")return G;for(let X of Q.config?.models??[]){if(!F8(X.accessibilityCatalogs))continue;G.push({context:{...J,modelId:X.id},catalogs:X.accessibilityCatalogs})}return G}function M6(Q,Y={}){return z3(Q.item,{kind:Q.kind,itemId:Q.itemId,canonicalItemId:Q.canonicalItemId,assessmentId:Y.assessmentId,sectionId:Y.sectionId})}function $7(){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 A8(Q,Y){if(Q===Y)return!0;if(!Q||!Y)return!1;return Q.sectionId===Y.sectionId&&Q.attemptId===Y.attemptId}function L3(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 N6(Q){let Y=Q.signals.sectionReady&&Q.signals.allLoadingComplete,J=Q.mode==="strict"?Y:Q.signals.interactionReady;return{phase:L3({...Q.signals,allLoadingComplete:Y,interactionReady:J}),interactionReady:J,allLoadingComplete:Y,reason:Q.reason}}function O6(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 z1(Q,Y,J,G="entered"){let X=O6(Y);if(!X)return;Q.push({kind:"stage-change",stage:X,status:G,cohort:J})}function z6(Q){let Y={...$7(),phase:"booting-section",cohort:Q.cohort,effectiveRuntime:Q.effectiveRuntime,effectiveToolsConfig:Q.effectiveToolsConfig,itemCount:Q.itemCount},J=[];return z1(J,"booting-section",Q.cohort),{state:Y,outputs:J}}function P3(Q,Y){if(Q.phase==="idle"||Q.phase==="disposed")return{state:Q,outputs:[]};let J=N6({mode:Y.mode,signals:Y.signals}),G=[],X=Q.phase,Z=Q.loadingCompleteEmitted;if(X==="engine-ready"&&J.interactionReady)X="interactive",z1(G,X,Q.cohort);if(J.allLoadingComplete&&Q.cohort&&!Z)Z=!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:Z},outputs:G}}function u7(Q,Y){switch(Y.kind){case"initialize":{if(Q.phase==="disposed")return{state:Q,outputs:[]};if(Q.phase!=="idle"){if(A8(Q.cohort,Y.cohort))return u7(Q,{kind:"update-runtime",effectiveRuntime:Y.effectiveRuntime,effectiveToolsConfig:Y.effectiveToolsConfig});return u7(Q,{kind:"cohort-change",cohort:Y.cohort,effectiveRuntime:Y.effectiveRuntime,effectiveToolsConfig:Y.effectiveToolsConfig,itemCount:Y.itemCount})}return z6({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(A8(Q.cohort,Y.cohort))return u7(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=z6({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 z1(J,"engine-ready",Q.cohort),{state:{...Q,phase:"engine-ready",controllerResolved:!0},outputs:J}}case"update-readiness-signals":return P3(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:!0}},outputs:[{kind:"framework-error",error:Y.error}]};case"dispose":{if(Q.phase==="disposed")return{state:Q,outputs:[]};let J=[];if(Q.phase!=="idle")z1(J,"disposed",Q.cohort);return{state:{...Q,phase:"disposed"},outputs:J}}default:{let J=Y;return{state:Q,outputs:[]}}}}class H8{state=$7();listeners=new Set;getState(){return this.state}dispatch(Q){let Y=u7(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 L6(Q){let{coordinator:Y,dispatchCoreInput:J}=Q,G=0,X=null,Z=null,j=!1,q=Y.subscribeFrameworkErrors((_)=>{try{J({kind:"framework-error",error:_})}catch(F){console.warn("[CoordinatorBridge] framework-error dispatch failed:",F)}});function U(){if(!Z)return;try{Z()}catch(_){console.warn("[CoordinatorBridge] controller unsubscribe failed:",_)}Z=null}async function V(_){if(j)return;G+=1;let F=G;X=_.cohort;let N=await Y.getOrCreateSectionController({sectionId:_.cohort.sectionId,attemptId:_.cohort.attemptId||void 0,input:{section:_.section,sectionId:_.cohort.sectionId,assessmentId:_.assessmentId,view:_.view},updateExisting:!0,createDefaultController:_.createDefaultController});if(F!==G||j)return;U(),_.onControllerResolved?.(N);let O=N.getCompositionModel;if(_.onCompositionChanged?.(O?.()),typeof N.subscribe==="function")Z=N.subscribe((w)=>{if(F!==G||j)return;_.onCompositionChanged?.(O?.())});J({kind:"section-controller-resolved"})}async function D(){if(j)return;j=!0,G+=1,U();try{q()}catch(F){console.warn("[CoordinatorBridge] framework-error unsubscribe failed:",F)}let _=X;if(X=null,_)try{await Y.disposeSectionController({sectionId:_.sectionId,attemptId:_.attemptId||void 0})}catch(F){console.warn("[CoordinatorBridge] section-controller dispose failed:",F)}}return{resolveSectionController:V,dispose:D}}function P6(Q){let{runtimeId:Y,sourceCe:J}=Q,G=Q.host,X=Q.now??(()=>new Date().toISOString());function Z(D){let _={stage:D.stage,status:D.status,runtimeId:Y,sectionId:D.cohort?.sectionId,attemptId:D.cohort?.attemptId?D.cohort.attemptId:void 0,timestamp:X(),sourceCe:J};G.dispatchEvent(new CustomEvent("pie-stage-change",{detail:_}))}function j(D){let _={runtimeId:Y,sectionId:D.cohort.sectionId,attemptId:D.cohort.attemptId?D.cohort.attemptId:void 0,itemCount:D.itemCount,loadedCount:D.loadedCount,timestamp:X(),sourceCe:J};G.dispatchEvent(new CustomEvent("pie-loading-complete",{detail:_}))}function q(D){G.dispatchEvent(new CustomEvent("framework-error",{detail:D.error}))}function U(D){switch(D.kind){case"stage-change":Z(D);return;case"loading-complete":j(D);return;case"framework-error":q(D);return;default:{let _=D;return}}}function V(D){G=D}return{dispatch:U,setHost:V}}function w6(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 $6(Q={}){let Y=Q.hook;function J(X){if(!Y)return;try{Y(X)}catch(Z){console.warn("[InstrumentationBridge] hook failed:",Z)}}function G(X){Y=X}return{dispatch:J,setHook:G}}function b6(){let Q=new Set;function Y(Z){if(Z.length===0)return;let j=Array.from(Q),q=Object.freeze(Z.slice());for(let U of j)try{U(q)}catch(V){console.warn("[SubscriberFanout] listener failed:",V)}}function J(Z){Q.add(Z);let j=!0;return()=>{if(!j)return;j=!1,Q.delete(Z)}}function G(){Q.clear()}function X(){return Q.size}return{emit:Y,subscribe:J,dispose:G,getListenerCount:X}}class M8{core;domEventBridge;frameworkErrorBridge;instrumentationBridge;subscriberFanout;coordinatorBridge;unsubscribeCore;disposed=!1;constructor(Q){this.core=Q.core??new H8,this.domEventBridge=P6({host:Q.host,runtimeId:Q.runtimeId,sourceCe:Q.sourceCe,now:Q.now}),this.frameworkErrorBridge=w6({bus:Q.frameworkErrorBus}),this.instrumentationBridge=$6({hook:Q.instrumentationHook}),this.subscriberFanout=b6(),this.coordinatorBridge=Q.coordinator?L6({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 w3={mode:"gather",role:"student"};function L1(Q,Y){return Q!==void 0?Q:Y}function $3(Q){let Y=Q.runtime??{};if(Y.onFrameworkError!==void 0)return Y.onFrameworkError;return Q.onFrameworkError}function b3(Q){let Y=Q.runtime?.tools||{},J=Y.placement||{};return{...Y,placement:{...J}}}function R3(Q){let Y=Q.runtime||{},J=Y.player?{...Y.player}:null;return{...Y,assessmentId:L1(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??w3,toolConfigStrictness:L1(Y.toolConfigStrictness,Q.toolConfigStrictness)??"error",onFrameworkError:$3({runtime:Q.runtime,onFrameworkError:Q.onFrameworkError}),onStageChange:L1(Y.onStageChange,Q.onStageChange),onLoadingComplete:L1(Y.onLoadingComplete,Q.onLoadingComplete),tools:Q.effectiveToolsConfig}}function R6(Q,Y){let J=Q.assessmentId??"section-demo-direct",G=b3({runtime:Q.runtime}),X=R3({assessmentId:J,runtime:Q.runtime,effectiveToolsConfig:G,toolConfigStrictness:Q.toolConfigStrictness,onFrameworkError:Q.onFrameworkError,onStageChange:Q.onStageChange,onLoadingComplete:Q.onLoadingComplete}),Z=Y.resolvePlayerRuntime({effectiveRuntime:X,playerType:String(X.playerType??"iife"),env:X.env??null});return{effectiveToolsConfig:G,effectiveRuntime:X,playerRuntime:Z}}function E3(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 N8{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)=>E3(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 P1(Q="runtime"){return`${Q}-${Math.random().toString(16).slice(2)}-${Date.now()}`}class O8{registry=new N8;runtimeId=P1("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 M8({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)??S3}getState(){return this.adapter?.getState()??$7()}getEffectiveRuntime(Q,Y){return R6(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,Z=this.getLoadedKey(X,G.contentKind);if(this.loadedRenderableKeys.has(Z))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 S3=()=>{};import{ContextConsumer as T3,createContext as C3}from"@pie-players/pie-context";var E6=C3(Symbol.for("pie.sectionRuntimeEngineHostContext"));function S6(Q,Y){let J=!1,G=new T3(Q,{context:E6,subscribe:!0,onValue:(U)=>{J=!0,Y(U)}});G.connect();let X=(U)=>{if(U.context!==E6)return;G.requestValue()};Q.addEventListener("context-provider",X);let Z=0,j=200,q=globalThis.setInterval(()=>{if(J||Z>=j){globalThis.clearInterval(q);return}Z+=1,G.requestValue()},50);return()=>{globalThis.clearInterval(q),Q.removeEventListener("context-provider",X),G.disconnect()}}var y3=(Q)=>{console.error("[pie-assessment-toolkit] onStageChange handler threw",Q)};function T6(Q,Y){if(Q.isSuppressed())return!1;Q.dispatchDomEvent(Y);let J=Q.getOnStageChange();if(J)try{J(Y)}catch(G){(Q.logHandlerError??y3)(G)}return!0}function C6(){return{lastSessionEventSignatureByItemId:new Map,lastMetadataSignatureByItemId:new Map}}function y6(Q){Q.lastSessionEventSignatureByItemId.clear(),Q.lastMetadataSignatureByItemId.clear()}function f6(Q){let{state:Y,itemId:J,payload:G}=Q;if(x3(G)){let j=I3(G);if(Y.lastMetadataSignatureByItemId.get(J)===j)return!1;Y.lastMetadataSignatureByItemId.set(J,j)}let X=f3(G);if(Y.lastSessionEventSignatureByItemId.get(J)===X)return!1;return Y.lastSessionEventSignatureByItemId.set(J,X),!0}function f3(Q){let Y={...Q};delete Y.timestamp,delete Y.sourceRuntimeId;try{return JSON.stringify(Y)}catch{return String(Y.itemId||"")}}function x3(Q){return Q.intent==="metadata-only"}function I3(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 k3=(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}},c3=w8('<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>'),d3=w8('<div class="pie-assessment-toolkit-anchor svelte-vpe4u2" aria-hidden="true"></div> <!>',1),l3={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 color-mix(in srgb, #dc2626 40%, transparent);background:color-mix(in srgb, #dc2626 12%, transparent);color:#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 n6(Q,Y){k6(Y,!0),g6(Q,l3);let J=P1("toolkit"),G=new O8,X=v(null),Z=new x7,j={mode:"gather",role:"student"},q={iife:"pie-item-player",esm:"pie-item-player",preloaded:"pie-item-player",custom:""},U=S(Y,"assessmentId",7,""),V=S(Y,"section",7,null),D=S(Y,"sectionId",7,""),_=S(Y,"attemptId",7,""),F=S(Y,"env",23,()=>({})),N=S(Y,"ndsIcons",7,!1),O=S(Y,"lazyInit",7,!0),w=S(Y,"toolConfigStrictness",7,"error"),k=S(Y,"tools",23,()=>({})),H=S(Y,"toolContextResolvers",7,null),b=S(Y,"enabledTools",7,""),T=S(Y,"toolRegistry",7,null),u=S(Y,"accessibility",23,()=>({})),I=S(Y,"player",7,null),p=S(Y,"playerType",7,""),L=S(Y,"coordinator",7,null),g=S(Y,"createSectionController",7,null),X7=S(Y,"onFrameworkError",7,null),Z7=S(Y,"errorRenderer",7,null),N7=S(Y,"onStageChange",7,null),j7=S(Y,"assessment",7,null),g7=S(Y,"currentItemRef",7,null),c7=S(Y,"pnpEnforcement",7,null),q7=S(Y,"isolation",7,"inherit"),b7=v(null),c=v(null),Q7=v(null),$8=null,R7=null,E7=null,d7=null,S7=null,l7=null,i7=v(0),R1=v(null),s7=v(null),i=v(null),E1=v("Unable to initialize assessment toolkit."),S1=v(z8([])),b8="",T1="",R8=v(""),E8=null,n7=!1,T7=null,W7=[],r7=new Map,C1=new WeakMap,S8=C6(),d=u3({sourceCe:"pie-assessment-toolkit",sourceCeShape:"toolkit",runtimeId:J,sectionId:m(()=>D()||void 0),attemptId:m(()=>_()||void 0),emit:(W)=>{T6({isSuppressed:()=>B(X)!==null,dispatchDomEvent:(K)=>U7("pie-stage-change",K),getOnStageChange:()=>N7()},W)}}),T8=v(z8(m(()=>`${D()}|${_()}`))),o7=v(!1),o=v(!1),y1=v(!1),f1=v(!1);function r6(){if(!B(b7))return null;let W=B(b7).getRootNode();if(W&&"host"in W)return W.host;return B(b7).parentElement}let C=l(()=>r6());function U7(W,K){if(!B(C)){W7=[...W7,{name:W,detail:K}];return}_8(B(C),W,K)}R(()=>{if(!B(C))return;if(W7.length===0)return;let W=W7;W7=[],queueMicrotask(()=>{let K=B(C);if(!K){W7=[...W,...W7];return}for(let A of W)_8(K,A.name,A.detail)})});function o6(W){if(!Z7())return{title:"Unable to initialize assessment toolkit.",details:W.details.length>0?W.details:[W.message]};try{let K=Z7()(W)||{};return{title:typeof K.title==="string"&&K.title.trim().length>0?K.title:"Unable to initialize assessment toolkit.",details:Array.isArray(K.details)&&K.details.length>0?K.details.map((A)=>String(A)):W.details.length>0?W.details:[W.message]}}catch(K){let A=K instanceof Error&&K.message.trim().length>0?K.message:String(K||"Unknown renderer error");return{title:"Unable to initialize assessment toolkit.",details:[...W.details,`Error renderer failed: ${A}`]}}}function a7(W){let K=Y1({kind:W.kind,source:W.source,error:W.error,recoverable:W.recoverable});return Z.reportFrameworkError(K),K}function a6(W){return W==="coordinator-init"||W==="runtime-init"||W==="tool-config"}function C8(W){if(!X7())return;try{X7()(W),b8=`${W.kind}|${W.source}|${W.message}`}catch(K){console.error(`[pie-framework:${W.kind}:${W.source}] framework error hook failed`,K)}}R(()=>{let W=Z.subscribeFrameworkErrors((K)=>{if(console.error(g8(K),K.cause),a6(K.kind)){let A=o6(K);P(i,K,!0),P(E1,A.title,!0),P(S1,A.details,!0)}U7("framework-error",K),C8(K)});return()=>{W()}}),R(()=>{if(!B(i))return;let W=`${B(i).kind}|${B(i).source}|${B(i).message}`;if(b8===W)return;C8(B(i))});function t6(W){let K=5381;for(let A=0;A<W.length;A+=1)K=(K<<5)+K^W.charCodeAt(A);return(K>>>0).toString(36)}function D7(W){return W&&typeof W==="object"?W:{}}function e6(W){let K=D7(W.section),A=typeof K.identifier==="string"?K.identifier:"",z=typeof W.sectionId==="string"?W.sectionId:"";return A||z}function Q0(W){return typeof W.currentItemIndex==="number"?W.currentItemIndex:-1}function Y0(W){return(Array.isArray(W.renderables)?W.renderables:[]).map((A,z)=>{let M=D7(A),x=D7(M.entity),s=typeof x.id==="string"&&x.id||`renderable-${z}`,Q1=D7(x.config),v1=typeof x.version==="string"&&x.version||(typeof x.version==="number"?String(x.version):"")||(typeof Q1.version==="string"?Q1.version:"");return{id:s,version:v1}})}function J0(W){let K=D7(W.itemSessionsByItemId);return Object.keys(K).sort((A,z)=>A.localeCompare(z)).map((A)=>{let z=D7(K[A]),M=typeof z.id==="string"?z.id:"",x=Array.isArray(z.data)?z.data:[],s="";try{s=t6(JSON.stringify(x))}catch{s=String(x.length)}return{itemId:A,sessionId:M,payloadSignature:s}})}function G0(W){let K=D7(W),A=Y0(K).map((M)=>`${M.id}:${M.version}`).join("|"),z=J0(K).map((M)=>`${M.itemId}:${M.sessionId}:${M.payloadSignature}`).join("|");return{sectionId:e6(K),currentItemIndex:Q0(K),renderableSignature:A,itemSessionSignature:z}}function X0(W){let K=G0(W);return`${K.sectionId}|${K.currentItemIndex}|${K.renderableSignature}|${K.itemSessionSignature}`}function y8(W){return W==="iife"||W==="esm"||W==="preloaded"||W==="custom"}function Z0(W,K){let A=W?.type,z=y8(A)?A:y8(K)?K:W?.tagName?"custom":"iife",M=W?.tagName?.trim();if(z==="custom"&&!M)return{type:"iife",tagName:q.iife,version:void 0,source:void 0,isDefault:!0};return{type:z,tagName:M||q[z],version:W?.version,source:W?.source,loaderConfig:W?.loaderConfig,loaderOptions:W?.loaderOptions,isDefault:!W&&!K}}function f8(W){let K=W||{},A=typeof K.mode==="string"&&K.mode.trim()?K.mode.trim():j.mode,z=typeof K.role==="string"&&K.role.trim()?K.role.trim():j.role;return{mode:A,role:z}}function j0(W){let K=f8(W);if(K.mode==="author")return"author";if(K.role==="instructor")return"scorer";return"candidate"}async function q0(){if(g())return g()();throw Error("pie-assessment-toolkit requires createSectionController when no coordinator hook provides one")}function x8(){let W=k()||{},K=s6(b());if(K.length===0)return W;let A=W.placement||{},z=Array.isArray(A.section)?A.section:null;if(z&&z.length>0)return W;return{...W,placement:{...A,section:K}}}function W0(){return J7(x8(),{strictness:w(),source:"pie-assessment-toolkit.bootstrap",toolRegistry:T()}).config}function U0(){let W="",K="";try{W=JSON.stringify(x8())}catch{W="[unserializable-tools]"}try{K=JSON.stringify(Object.entries(H()??{}).map(([A,z])=>[A,typeof z]))}catch{K="[unserializable-resolvers]"}return[U()||"",String(w()||"error"),W,K].join("|")}function I8(W){return W==="on"||W==="off"?W:null}function D0(W,K){let A=I8(W);if(A)return A;if(K&&typeof K==="object"){let M=K.pnpEnforcement;return I8(typeof M==="string"?M:null)}return null}function K0(W){let K=U()||V()?.identifier||`assessment-${Math.random().toString(16).slice(2)}`;return new O1({assessmentId:K,lazyInit:O(),toolConfigStrictness:w(),deferToolConfigValidation:!0,tools:W,toolRegistry:T(),toolContextResolvers:H(),accessibility:u(),frameworkErrorBus:Z})}let y=l(()=>{if(q7()!=="force"&&B(Q7)?.coordinator)return B(Q7).coordinator;return L()||B(c)});R(()=>{B(C),L(),q7(),B(Q7),H(),m(()=>{if(!B(C))return;if(L()){if(B(c))P(c,null);R7=null;return}if(q7()!=="force"&&B(Q7)?.coordinator){if(B(c))P(c,null);R7=null;return}if(B(c)&&R7!==H()){try{B(c).setToolContextResolvers(H()),R7=H()}catch(W){P(s7,W,!0),a7({kind:"coordinator-init",phase:"coordinator-ready",error:W})}return}if(!B(c)){let W=U0();if(T1===W)return;try{let K=W0();P(c,K0(K),!0),R7=H(),T1="",P(i,null),P(E1,"Unable to initialize assessment toolkit."),P(S1,[],!0)}catch(K){P(s7,K,!0),P(c,null),T1=W,a7({kind:"coordinator-init",source:"pie-assessment-toolkit",error:K})}}})});let Y7=l(()=>U()||B(y)?.assessmentId||""),a=l(()=>D()||V()?.identifier||`section-${B(Y7)||"default"}`),x1=l(()=>f8(F())),V0=l(()=>j0(B(x1))),O7=l(()=>Z0(I(),p())),C7=l(()=>m3({player:B(O7),component:"pie-assessment-toolkit"})),t7=l(()=>{if(!B(y))return null;let W=B(y).getServiceBundle();return{toolkitCoordinator:B(y),toolCoordinator:B(y).toolCoordinator,ttsService:W.ttsService,highlightCoordinator:W.highlightCoordinator,catalogResolver:W.catalogResolver,elementToolStateStore:W.elementToolStateStore,assessmentId:B(Y7),sectionId:B(a),itemPlayer:B(O7),ndsIcons:N()===!0,reportSessionChanged:(K,A)=>{let z=G.updateItemSession(K,A);h8({itemId:K,result:z,fallbackSession:A})}}}),e7=l(()=>{if(!B(y))return null;return{runtimeId:J,coordinator:B(y)}});function B0(W){let K=X0(W);if(K===B(R8))return;P(R8,K,!0),P(i7,B(i7)+1),P(R1,W,!0),U7("composition-changed",{composition:B(R1),version:B(i7)})}function I1(W){if(E8=W??G.getCompositionModel(),n7)return;n7=!0;let K=()=>{n7=!1,T7=null,B0(E8)};if(typeof window<"u"&&typeof window.requestAnimationFrame==="function"){T7=window.requestAnimationFrame(K);return}queueMicrotask(K)}function k1(W){if(!W)return;let K=C1.get(W);if(!K)return;for(let A of K)A();C1.delete(W)}function k8(){for(let W of r7.values())k1(W.element)}function v8(W){if(k1(W.element),!B(y))return;let K=B(y).getServiceBundle().catalogResolver;if(typeof K.registerCatalogs!=="function")return;let A=M6(W,{assessmentId:B(Y7),sectionId:B(a)});if(A.length===0)return;C1.set(W.element,A.map((z)=>K.registerCatalogs(z.context,z.catalogs)))}function _0(){k8();for(let W of r7.values())v8(W)}function h8(W){let A={...W.result?.eventDetail||W.fallbackSession,itemId:W.itemId,canonicalItemId:W.canonicalItemId||W.itemId,sourceRuntimeId:J};if(!f6({state:S8,itemId:W.itemId,payload:A}))return;U7("session-changed",A)}function F0(W){if(!(W instanceof HTMLElement))return!1;return v3(W,P8)?.runtimeId===J}function y7(W){return W.detail??null}function A0(W,K){for(let A of K)W.addEventListener(A.name,A.handler);return()=>{for(let A of K)W.removeEventListener(A.name,A.handler)}}R(()=>{if(!B(C))return;if(q7()==="force"){P(Q7,null);return}return i6(B(C),(W)=>{if(W.runtimeId===J)return;P(Q7,W,!0)})}),R(()=>{let W=B(C);return m(()=>{if(!W){P(X,null);return}let K=S6(W,(A)=>{if(A.engine===B(X))return;P(X,A.engine,!0)});return()=>{K(),P(X,null)}})}),R(()=>{let W=q7()!=="force"&&B(Q7)?B(Q7).runtimeId:null,K=W?"inherited":"owned";if(K!==$8)$8=K,U7(K==="inherited"?"runtime-inherited":"runtime-owned",{runtimeId:J,parentRuntimeId:W})}),R(()=>{let W=B(a),K=_()||"";y6(S8)}),R(()=>{if(!B(C)||!B(e7))return;return S7=new x6(B(C),{context:P8,initialValue:B(e7)}),S7.connect(),l7=new I6(B(C)),l7.attach(),()=>{l7?.detach(),l7=null,S7?.disconnect(),S7=null}}),R(()=>{if(!B(e7))return;S7?.setValue(B(e7))}),R(()=>{if(!B(C))return;B(C).setAttribute("data-item-player-type",B(O7).type),B(C).setAttribute("data-item-player-tag",B(O7).tagName),B(C).setAttribute("data-env-mode",String(B(x1)?.mode||"")),B(C).setAttribute("data-env-role",String(B(x1)?.role||""))}),R(()=>{if(!B(C)||!B(t7))return;return E7=new x6(B(C),{context:l6,initialValue:B(t7)}),E7.connect(),d7=new I6(B(C)),d7.attach(),()=>{d7?.detach(),d7=null,E7?.disconnect(),E7=null}}),R(()=>{if(B(t7))E7?.setValue(B(t7))}),R(()=>{return B(y),B(Y7),B(a),_0(),()=>{k8()}}),R(()=>{if(!B(C))return;return h3({host:B(C),instrumentationProvider:B(C7),component:"pie-assessment-toolkit",eventMap:p3,staticAttributes:{instrumentationLayer:"toolkit",assessmentId:B(Y7),sectionId:B(a),attemptId:_()||void 0}})}),R(()=>{j7(),g7(),c7(),k();let W=B(y);if(!W)return;if(W!==B(c))return;m(()=>{W.setPnpEnforcement(D0(c7(),k())),W.updateAssessment(j7()),W.updateCurrentItemRef(g7())})}),R(()=>{if(!B(y))return;return B(y).subscribeTelemetry(({eventName:W,payload:K})=>{if(!g3(B(C7)))return;if(!B(C7).isReady())return;let A=W,z=new Date().toISOString(),M={...K||{},instrumentationLayer:"toolkit",assessmentId:B(Y7),sectionId:B(a),attemptId:_()||void 0,component:"pie-assessment-toolkit",sourceEventName:W,timestamp:z};B(C7).trackEvent(A,M);let x=K&&typeof K.errorType==="string"?K.errorType:void 0;if(!W.endsWith("-error")&&!x)return;let s=K&&typeof K.message==="string"?K.message:`Toolkit telemetry error: ${W}`;B(C7).trackError(Error(s),{component:"pie-assessment-toolkit",errorType:x||"ToolkitTelemetryError",...M})})}),R(()=>{if(!V()||!B(y))return;let W=!1;return G.initialize({coordinator:B(y),section:V(),sectionId:B(a),assessmentId:B(Y7),attemptId:_()||void 0,view:B(V0),createDefaultController:q0,onCompositionChanged:(K)=>{if(W)return;I1(K)}}).then(()=>{if(W)return;U7("toolkit-ready",{runtimeId:J,assessmentId:B(Y7),sectionId:B(a),itemPlayer:B(O7),coordinator:B(y)}),U7("section-ready",{sectionId:B(a)}),m(()=>{P(f1,!0)})}).catch((K)=>{m(()=>{if(!B(o))P(o,!0),d.enter("engine-ready","skipped");d.enter("interactive","failed")}),P(s7,K,!0),G.reportSectionError({source:"section-runtime",error:K,timestamp:Date.now()}),a7({kind:"runtime-init",source:"pie-assessment-toolkit",error:K})}),()=>{W=!0}}),R(()=>{if(!B(C))return;let W=B(C),K=(z)=>F0(z.target);return A0(W,[{name:B6,handler:(z)=>{if(!K(z))return;let M=y7(z);if(!M?.element||!M?.itemId)return;let x=G.register(M);if(r7.set(M.element,M),v8(M),G.handleContentRegistered(M),x)I1()}},{name:_6,handler:(z)=>{if(!K(z))return;let M=y7(z);if(!M?.itemId)return;let x=M?.element?G.unregister(M.element):!1;if(k1(M.element),M.element)r7.delete(M.element);if(G.handleContentUnregistered(M),x)I1()}},{name:F6,handler:(z)=>{if(!K(z))return;let M=y7(z);if(!M?.itemId)return;let x=G.updateItemSession(M.itemId,M.session);h8({itemId:M.itemId,canonicalItemId:G.getCanonicalItemId(M.itemId),result:x,fallbackSession:M.session})}},{name:A6,handler:(z)=>{if(!K(z))return;let M=y7(z);if(!M?.itemId)return;G.handleContentLoaded({itemId:M.itemId,canonicalItemId:M.canonicalItemId,contentKind:M.contentKind,detail:M.detail,timestamp:Date.now()})}},{name:H6,handler:(z)=>{if(!K(z))return;let M=y7(z);if(!M?.itemId)return;G.handleItemPlayerError({itemId:M.itemId,canonicalItemId:M.canonicalItemId,contentKind:M.contentKind,error:M.error,timestamp:Date.now()})}}])});async function H0(){if(!B(y))throw Error("Coordinator not initialized");await B(y).waitUntilReady()}function M0(){if(!B(y))throw Error("Coordinator not initialized");return B(y).getServiceBundle()}function N0(W){if(!B(y))throw Error("Coordinator not initialized");B(y).setHooks(W)}function O0(W){return G.navigateToItem(W)}function z0(){return G.getCompositionModel()}function L0(){return B(O7)}async function P0(){await G.persist()}async function w0(){await G.hydrate()}R(()=>{return()=>{m(()=>{if(d.getCurrent()!==null)d.enter("disposed")})}}),R(()=>{let W=`${D()}|${_()}`;m(()=>{if(W===B(T8))return;if(d.getCurrent()!==null)d.enter("disposed");d.reset({sectionId:D()||void 0,attemptId:_()||void 0}),P(T8,W),P(o7,!1),P(o,!1),P(y1,!1),P(f1,!1)})}),R(()=>{let W=B(o)&&B(f1);m(()=>{if(!W)return;if(B(y1))return;P(y1,!0),d.enter("interactive")})}),R(()=>{let W=B(i7)>0||B(R1)!==null;m(()=>{if(!B(o7)&&W)P(o7,!0),d.enter("composed")})}),R(()=>{if(!B(y))return;if(!B(o7))return;if(B(o))return;let W=B(y),K=!1;return W.waitUntilReady().then(()=>{if(K)return;m(()=>{if(B(o))return;P(o,!0),d.enter("engine-ready")})}).catch(()=>{if(K)return;m(()=>{if(B(o))return;P(o,!0),d.enter("engine-ready","failed")})}),()=>{K=!0}}),R(()=>{return()=>{if(T7!==null&&typeof window<"u")window.cancelAnimationFrame(T7),T7=null;n7=!1,G.dispose().catch((W)=>{P(s7,W,!0),a7({kind:"runtime-dispose",source:"pie-assessment-toolkit",error:W,recoverable:!0})}).finally(()=>{Z.dispose()})}});var $0={waitUntilReady:H0,getServiceBundle:M0,setHooks:N0,navigateToItem:O0,getCompositionModel:z0,getItemPlayerConfig:L0,persist:P0,hydrate:w0,get assessmentId(){return U()},set assessmentId(W){U(W),E()},get section(){return V()},set section(W){V(W),E()},get sectionId(){return D()},set sectionId(W){D(W),E()},get attemptId(){return _()},set attemptId(W){_(W),E()},get env(){return F()},set env(W){F(W),E()},get ndsIcons(){return N()},set ndsIcons(W){N(W),E()},get lazyInit(){return O()},set lazyInit(W){O(W),E()},get toolConfigStrictness(){return w()},set toolConfigStrictness(W){w(W),E()},get tools(){return k()},set tools(W){k(W),E()},get toolContextResolvers(){return H()},set toolContextResolvers(W){H(W),E()},get enabledTools(){return b()},set enabledTools(W){b(W),E()},get toolRegistry(){return T()},set toolRegistry(W){T(W),E()},get accessibility(){return u()},set accessibility(W){u(W),E()},get player(){return I()},set player(W){I(W),E()},get playerType(){return p()},set playerType(W){p(W),E()},get coordinator(){return L()},set coordinator(W){L(W),E()},get createSectionController(){return g()},set createSectionController(W){g(W),E()},get onFrameworkError(){return X7()},set onFrameworkError(W){X7(W),E()},get errorRenderer(){return Z7()},set errorRenderer(W){Z7(W),E()},get onStageChange(){return N7()},set onStageChange(W){N7(W),E()},get assessment(){return j7()},set assessment(W){j7(W),E()},get currentItemRef(){return g7()},set currentItemRef(W){g7(W),E()},get pnpEnforcement(){return c7()},set pnpEnforcement(W){c7(W),E()},get isolation(){return q7()},set isolation(W){q7(W),E()}},u8=d3(),m8=L8(u8);c6(m8,(W)=>P(b7,W),()=>B(b7));var b0=w1(m8,2);{var R0=(W)=>{var K=c3(),A=p7(K),z=p7(A,!0);m7(A);var M=w1(A,2),x=p7(M,!0);m7(M);var s=w1(M,2),Q1=p7(s,!0);m7(s),m7(K),h6((v1)=>{b1(z,B(E1)),b1(x,B(i).message),b1(Q1,v1)},[()=>B(S1).join(`
|
|
224
|
-
`)])
|
|
223
|
+
`}return G}function F8(Q){let{request:Y,tools:J,pnpPolicy:G,customSources:X,contextId:Z}=Q,j=new F1(Z);j.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]),W=M1(J.policy.allowed),V=new Set(M1(J.policy.blocked)),U=[];for(let A of q)U.push(A),j.addDecision({precedence:0,rule:"placement-membership",featureId:A,action:"skip",sourceType:"host",reason:`Listed in tools.placement.${Y.level}`});if(U=U.filter((A)=>{if(J.providers?.[A]?.enabled===!1)return j.addDecision({precedence:0,rule:"provider-disabled",featureId:A,action:"block",sourceType:"host",reason:`tools.providers.${A}.enabled === false`,value:!1}),!1;return!0}),W.length>0){let A=new Set(W);U=U.filter((L)=>{if(!A.has(L))return j.addDecision({precedence:0,rule:"host-allowlist",featureId:L,action:"block",sourceType:"host",reason:"Not present in tools.policy.allowed",value:W}),!1;return!0})}U=U.filter((A)=>{if(V.has(A))return j.addDecision({precedence:0,rule:"host-blocked",featureId:A,action:"block",sourceType:"host",reason:"Listed in tools.policy.blocked",value:J.policy.blocked}),!1;return!0});let _=[],H=new Map;for(let A of U)H.set(A,["placement"]);let F=new Set(U),N=null;if(G.enforcement==="on"&&G.source&&(G.assessment||G.currentItemRef)){if(N=G.source.apply({assessment:G.assessment,currentItemRef:G.currentItemRef}),N.sources.assessment)j.addSource("assessment",N.sources.assessment);if(N.sources.student)j.addSource("student",N.sources.student);if(N.sources.item)j.addSource("item",N.sources.item);for(let A of N.decisions)j.addDecision({precedence:A.precedence,rule:A.rule,featureId:A.featureId,action:A.action,sourceType:A.sourceType,reason:A.reason,value:A.value});U=U.filter((A)=>{return!N.blockedToolIds.has(A)});for(let A of Array.from(H.keys()))if(N.blockedToolIds.has(A))H.delete(A);for(let A of N.mandatedToolIds){if(!!F.has(A))continue;let m=N.perToolFlags.get(A)?.rule??"required-tool",I=l2(A,{placement:q,allowed:W,blocked:V,providers:J.providers}),c={rule:m,hostRule:I.hostRule,hostValue:I.hostValue};_.push({code:"tool-policy.requiredToolBlocked",level:Y.level,toolId:A,message:`Profile policy mandates "${A}" (${m}) but host policy removed it from level "${Y.level}" via ${I.hostRule}.`,details:c}),j.addDecision({precedence:0,rule:"required-tool-blocked",featureId:A,action:"advisory",sourceType:"host",reason:`Host removed required tool "${A}" via ${I.hostRule}`,value:c})}for(let A of U){let L=N.perToolFlags.get(A);if(L){let E=H.get(A)??[];E.push(`pnp.${L.rule}`),H.set(A,E)}}}for(let A=0;A<X.length;A++){let L=X[A],E=U.slice(),m=L.refine({request:Y,candidates:E}),I=new Set(m.refinedCandidates);for(let $ of m.refinedCandidates)if(!E.includes($))_.push({code:"tool-policy.placementMissing",level:Y.level,toolId:$,message:`Custom source "${L.id}" tried to add tool "${$}" that was not in candidates; ignored.`,source:`custom.${L.id}`}),I.delete($);U=E.filter(($)=>I.has($));let c=new Set;if(m.decisions){for(let $ of m.decisions)if(j.addDecision({precedence:$.precedence??100+A,rule:$.rule,featureId:$.featureId,action:$.action,sourceType:$.sourceType,reason:$.reason,value:$.value}),$.action==="block")c.add($.featureId)}for(let $ of E){if(I.has($))continue;if(c.has($))continue;j.addDecision({precedence:100+A,rule:"custom-source",featureId:$,action:"block",sourceType:"custom",reason:`Custom policy source "${L.id}" removed tool "${$}" from candidates without emitting a decision; auto-logged for trail completeness.`,value:{customSourceId:L.id}})}for(let $ of U){let l=H.get($)??["placement"];l.push(`custom.${L.id}`),H.set($,l)}for(let $ of E)if(!I.has($))H.delete($)}let P=new Set(U),f=U.map((A)=>{let L=N?.perToolFlags.get(A);return{toolId:A,required:L?.required??!1,alwaysAvailable:L?.alwaysAvailable??!1,settings:L?.settings,sources:H.get(A)??["placement"]}});return j.reconcileFinalStates(P),{visibleTools:f,diagnostics:_,provenance:j.build()}}function l2(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 L6(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 Z of Object.keys(X)){let j=X[Z];if(j===void 0||j===null)continue;if(Array.isArray(j)&&j.length===0)continue;if(typeof j==="object"&&!Array.isArray(j)&&Object.keys(j).length===0)continue;return!0}}return!1}function $6(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(L6(Q.assessment))return"on";if($6(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:Z}=Y,j=new Set;G?.supports?.forEach((q)=>j.add(q)),G?.prohibitedSupports?.forEach((q)=>j.add(q)),X?.blockedTools?.forEach((q)=>j.add(q)),X?.requiredTools?.forEach((q)=>j.add(q)),Z?.requiredTools?.forEach((q)=>j.add(q)),Z?.restrictedTools?.forEach((q)=>j.add(q));for(let q of j)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,Z=J?.settings,j={blockedToolIds:new Set,mandatedToolIds:new Set,perToolFlags:new Map,decisions:[],sources:{}};if(X?.districtPolicy||X?.testAdministration)j.sources.assessment={id:Y?.id||"unknown",name:Y?.name||Y?.id||"Assessment",config:X};if(G)j.sources.student={id:"student",name:"Student PNP Profile",config:G};if(J&&Z)j.sources.item={id:J.identifier,name:J.identifier,config:Z};return{ctx:{pnp:G,districtPolicy:X?.districtPolicy,testAdmin:X?.testAdministration,itemSettings:Z,toolConfigs:X?.toolConfigs},result:j}}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 w6=$7({policy:{allowed:[],blocked:[]},placement:{section:[],item:[],passage:[]},providers:{}});class O1{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??w6,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 F8({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(),P6(Q,this.pnpPolicySource.resolveFeature(Q,{assessment:this.assessment??void 0,currentItemRef:this.currentItemRef??void 0}))}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??w6;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 d2=Symbol("@pie-players/tool-policy-engine");var z1=(Q)=>!!Q&&typeof Q==="object"&&!Array.isArray(Q),i2=(Q,Y,J)=>{let G={...Y,...J};if(Q==="textToSpeech"&&z1(Y.settings)&&z1(J.settings)){if(G.settings={...Y.settings,...J.settings},z1(Y.settings.mathSpeech)&&z1(J.settings.mathSpeech))G.settings.mathSpeech={...Y.settings.mathSpeech,...J.settings.mathSpeech}}return G},s2=["item-selected","item-session-data-changed","item-session-meta-changed","item-complete-changed","content-loaded","item-player-error"],n2=["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;static resolveConfig(Q){let Y=u1(Q.toolConfigStrictness),J=Q.toolRegistry??new M8,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 M8,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 r1,this.highlightCoordinator=new h7,this.elementToolStateStore=new s1,this.catalogResolver=new i1(Y.accessibility?.catalogs||[],Y.accessibility?.language||"en-US"),this.toolProviderRegistry=new A1,this._registerToolProviders(),this.ttsService=new m7,this.setupStatePersistenceHooks(),this.policyEngine=new O1({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=s8({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:Z}=J.key;return`pie:section-controller:v1:${G}:${X}:${Z||"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),Z=Y.getInitConfig?.(J)??J?.provider?.init??{},j=this.addToolTelemetryReporter({toolId:Q.toolId,providerId:G,initConfig:Z}),q=this.createToolTelemetryForwarder({toolId:Q.toolId,providerId:G}),W=Y.getAuthFetcher?.(J)??J?.provider?.runtime?.authFetcher;await this.registerProvider(G,{provider:X,config:j,lazy:Y.lazy??!0,authFetcher:W,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,Z)=>{if(J)await J(X,Z);await G(X,Z)},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(Z){let j=Z instanceof Error?Z:Error(String(Z));throw this.handleError(j,{phase:"provider-init",providerId:Q}),j}})().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,(j)=>{if(!G(j))return;this.deliverSectionEventSafely(Q.listener,j)});let X=this.buildContentLoadedReplayEvents(Y);for(let j of X)if(G(j))this.deliverSectionEventSafely(Q.listener,j);let Z=this.buildLoadingCompleteReplayEvent(Y);if(Z&&G(Z))this.deliverSectionEventSafely(Q.listener,Z)}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((j)=>J.has(j)))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(),Z=[];for(let j of J){if(!j)continue;let q=j.itemId,W=typeof j.canonicalItemId==="string"&&j.canonicalItemId?j.canonicalItemId:q;if(typeof q!=="string"||!q)continue;Z.push({type:"content-loaded",contentKind:j.contentKind??"unknown",itemId:q,canonicalItemId:W,currentItemIndex:G,timestamp:X})}return Z}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||s2,itemIds:Q.itemIds,listener:Q.listener})}subscribeSectionLifecycleEvents(Q){return this.subscribeSectionEvents({eventTypes:Q.eventTypes||n2,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 Z=this.initializeNewSectionController({args:Q,key:Y,mapKey:J}).catch((j)=>{throw this.handleSectionControllerInitError(j,Q),j}).finally(()=>{this.sectionControllerInitPromises.delete(J)});return this.sectionControllerInitPromises.set(J,Z),Z}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(Z){this.handleError(Z,{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=O6(Y),G=A8(J),X=z6(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(j){let q=j instanceof Error?j:Error(String(j));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 Z=new R7;try{await this.initializeTTSService(Z,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(j){let q=j instanceof Error?j:Error(String(j));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,Z)=>{await this.emitTelemetry(X,{toolId:"textToSpeech",...Z||{}})}},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((Z)=>{let j=!1,q=typeof J.addEventListener==="function"&&typeof J.removeEventListener==="function",W=!q&&"onvoiceschanged"in J,V=W?J.onvoiceschanged:null,U=!1,_=()=>{if(j)return;if(j=!0,window.clearTimeout(F),q)J.removeEventListener("voiceschanged",H);else if(U&&J.onvoiceschanged===H)J.onvoiceschanged=V;Z()},H=(N)=>{if(!q&&typeof V==="function"&&N)V.call(J,N);_()},F=window.setTimeout(_,Y);if(q)J.addEventListener("voiceschanged",H,{once:!0});else if(W)J.onvoiceschanged=H,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]:i2(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){return this.policyEngine.decideFeature(Q)}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 R6="pie-register",b6="pie-unregister",E6="pie-item-session-changed";var S6="pie-content-loaded",T6="pie-item-player-error";var r2={bubbles:!0,composed:!0,cancelable:!1};function o2(Q,Y,J={}){return new CustomEvent(Q,{detail:Y,...r2,...J})}function N8(Q,Y,J,G={}){return Q.dispatchEvent(o2(Y,J,G))}var O8=(Q)=>Array.isArray(Q)&&Q.length>0;function a2(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 t2(Q,Y){if(!Q)return[];let J=a2(Y),G=[];if(O8(Q.accessibilityCatalogs))G.push({context:J,catalogs:Q.accessibilityCatalogs});if(O8(Q.config?.extractedCatalogs))G.push({context:J,catalogs:Q.config.extractedCatalogs});if(Y.kind==="passage")return G;for(let X of Q.config?.models??[]){if(!O8(X.accessibilityCatalogs))continue;G.push({context:{...J,modelId:X.id},catalogs:X.accessibilityCatalogs})}return G}function C6(Q,Y={}){return t2(Q.item,{kind:Q.kind,itemId:Q.itemId,canonicalItemId:Q.canonicalItemId,assessmentId:Y.assessmentId,sectionId:Y.sectionId})}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 z8(Q,Y){if(Q===Y)return!0;if(!Q||!Y)return!1;return Q.sectionId===Y.sectionId&&Q.attemptId===Y.attemptId}function e2(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 y6(Q){let Y=Q.signals.sectionReady&&Q.signals.allLoadingComplete,J=Q.mode==="strict"?Y:Q.signals.interactionReady;return{phase:e2({...Q.signals,allLoadingComplete:Y,interactionReady:J}),interactionReady:J,allLoadingComplete:Y,reason:Q.reason}}function x6(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=x6(Y);if(!X)return;Q.push({kind:"stage-change",stage:X,status:G,cohort:J})}function f6(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 Q5(Q,Y){if(Q.phase==="idle"||Q.phase==="disposed")return{state:Q,outputs:[]};let J=y6({mode:Y.mode,signals:Y.signals}),G=[],X=Q.phase,Z=Q.loadingCompleteEmitted;if(X==="engine-ready"&&J.interactionReady)X="interactive",L1(G,X,Q.cohort);if(J.allLoadingComplete&&Q.cohort&&!Z)Z=!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:Z},outputs:G}}function p7(Q,Y){switch(Y.kind){case"initialize":{if(Q.phase==="disposed")return{state:Q,outputs:[]};if(Q.phase!=="idle"){if(z8(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 f6({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(z8(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=f6({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 Q5(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:!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 P8{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 k6(Q){let{coordinator:Y,dispatchCoreInput:J}=Q,G=0,X=null,Z=null,j=!1,q=Y.subscribeFrameworkErrors((_)=>{try{J({kind:"framework-error",error:_})}catch(H){console.warn("[CoordinatorBridge] framework-error dispatch failed:",H)}});function W(){if(!Z)return;try{Z()}catch(_){console.warn("[CoordinatorBridge] controller unsubscribe failed:",_)}Z=null}async function V(_){if(j)return;G+=1;let H=G;X=_.cohort;let F=await Y.getOrCreateSectionController({sectionId:_.cohort.sectionId,attemptId:_.cohort.attemptId||void 0,input:{section:_.section,sectionId:_.cohort.sectionId,assessmentId:_.assessmentId,view:_.view},updateExisting:!0,createDefaultController:_.createDefaultController});if(H!==G||j)return;W(),_.onControllerResolved?.(F);let N=F.getCompositionModel;if(_.onCompositionChanged?.(N?.()),typeof F.subscribe==="function")Z=F.subscribe((P)=>{if(H!==G||j)return;_.onCompositionChanged?.(N?.())});J({kind:"section-controller-resolved"})}async function U(){if(j)return;j=!0,G+=1,W();try{q()}catch(H){console.warn("[CoordinatorBridge] framework-error unsubscribe failed:",H)}let _=X;if(X=null,_)try{await Y.disposeSectionController({sectionId:_.sectionId,attemptId:_.attemptId||void 0})}catch(H){console.warn("[CoordinatorBridge] section-controller dispose failed:",H)}}return{resolveSectionController:V,dispose:U}}function I6(Q){let{runtimeId:Y,sourceCe:J}=Q,G=Q.host,X=Q.now??(()=>new Date().toISOString());function Z(U){let _={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:_}))}function j(U){let _={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:_}))}function q(U){G.dispatchEvent(new CustomEvent("framework-error",{detail:U.error}))}function W(U){switch(U.kind){case"stage-change":Z(U);return;case"loading-complete":j(U);return;case"framework-error":q(U);return;default:{let _=U;return}}}function V(U){G=U}return{dispatch:W,setHost:V}}function v6(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 h6(Q={}){let Y=Q.hook;function J(X){if(!Y)return;try{Y(X)}catch(Z){console.warn("[InstrumentationBridge] hook failed:",Z)}}function G(X){Y=X}return{dispatch:J,setHook:G}}function m6(){let Q=new Set;function Y(Z){if(Z.length===0)return;let j=Array.from(Q),q=Object.freeze(Z.slice());for(let W of j)try{W(q)}catch(V){console.warn("[SubscriberFanout] listener failed:",V)}}function J(Z){Q.add(Z);let j=!0;return()=>{if(!j)return;j=!1,Q.delete(Z)}}function G(){Q.clear()}function X(){return Q.size}return{emit:Y,subscribe:J,dispose:G,getListenerCount:X}}class L8{core;domEventBridge;frameworkErrorBridge;instrumentationBridge;subscriberFanout;coordinatorBridge;unsubscribeCore;disposed=!1;constructor(Q){this.core=Q.core??new P8,this.domEventBridge=I6({host:Q.host,runtimeId:Q.runtimeId,sourceCe:Q.sourceCe,now:Q.now}),this.frameworkErrorBridge=v6({bus:Q.frameworkErrorBus}),this.instrumentationBridge=h6({hook:Q.instrumentationHook}),this.subscriberFanout=m6(),this.coordinatorBridge=Q.coordinator?k6({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 Y5={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 G5(Q){let Y=Q.runtime?.tools||{},J=Y.placement||{};return{...Y,placement:{...J}}}function X5(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??Y5,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 u6(Q,Y){let J=Q.assessmentId??"section-demo-direct",G=G5({runtime:Q.runtime}),X=X5({assessmentId:J,runtime:Q.runtime,effectiveToolsConfig:G,toolConfigStrictness:Q.toolConfigStrictness,onFrameworkError:Q.onFrameworkError,onStageChange:Q.onStageChange,onLoadingComplete:Q.onLoadingComplete}),Z=Y.resolvePlayerRuntime({effectiveRuntime:X,playerType:String(X.playerType??"iife"),env:X.env??null});return{effectiveToolsConfig:G,effectiveRuntime:X,playerRuntime:Z}}function Z5(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 $8{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)=>Z5(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 w8{registry=new $8;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 L8({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)??j5}getState(){return this.adapter?.getState()??T7()}getEffectiveRuntime(Q,Y){return u6(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,Z=this.getLoadedKey(X,G.contentKind);if(this.loadedRenderableKeys.has(Z))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 j5=()=>{};import{ContextConsumer as q5,createContext as K5}from"@pie-players/pie-context";var p6=K5(Symbol.for("pie.sectionRuntimeEngineHostContext"));function g6(Q,Y){let J=!1,G=new q5(Q,{context:p6,subscribe:!0,onValue:(W)=>{J=!0,Y(W)}});G.connect();let X=(W)=>{if(W.context!==p6)return;G.requestValue()};Q.addEventListener("context-provider",X);let Z=0,j=200,q=globalThis.setInterval(()=>{if(J||Z>=j){globalThis.clearInterval(q);return}Z+=1,G.requestValue()},50);return()=>{globalThis.clearInterval(q),Q.removeEventListener("context-provider",X),G.disconnect()}}var W5=(Q)=>{console.error("[pie-assessment-toolkit] onStageChange handler threw",Q)};function c6(Q,Y){if(Q.isSuppressed())return!1;Q.dispatchDomEvent(Y);let J=Q.getOnStageChange();if(J)try{J(Y)}catch(G){(Q.logHandlerError??W5)(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 l6(Q={}){let Y=Q.frameDeadlineMs??100,J=!1,G=null,X=null,Z=null,j=null,q=null;function W(){if(J=!1,X!==null)j?.(X),X=null;if(Z!==null)q?.(Z),Z=null;j=null,q=null}function V(H){if(!J)return;if(H==="frame")X=null;if(H==="timer")Z=null;let F=G;G=null,W(),F?.()}function U(H){if(G=H,J)return;J=!0;let F=globalThis,N=g7(Q.requestFrame,F.requestAnimationFrame);j=g7(Q.cancelFrame,F.cancelAnimationFrame);let P=g7(Q.setTimer,F.setTimeout);if(q=g7(Q.clearTimer,F.clearTimeout),N){let A=N(()=>V("frame"));if(!J)return;if(X=A,P){let L=P(()=>V("timer"),Y);if(J)Z=L}return}let f=g7(Q.queueMicrotaskFn,F.queueMicrotask);if(f){f(()=>V("microtask"));return}if(P){let A=P(()=>V("timer"),0);if(J)Z=A;return}V("microtask")}function _(){if(!J)return;G=null,W()}return{schedule:U,cancel:_,isPending:()=>J}}function d6(){return{lastSessionEventSignatureByItemId:new Map,lastMetadataSignatureByItemId:new Map}}function i6(Q){Q.lastSessionEventSignatureByItemId.clear(),Q.lastMetadataSignatureByItemId.clear()}function s6(Q){let{state:Y,itemId:J,payload:G}=Q;if(V5(G)){let j=B5(G);if(Y.lastMetadataSignatureByItemId.get(J)===j)return!1;Y.lastMetadataSignatureByItemId.set(J,j)}let X=U5(G);if(Y.lastSessionEventSignatureByItemId.get(J)===X)return!1;return Y.lastSessionEventSignatureByItemId.set(J,X),!0}function U5(Q){let Y={...Q};delete Y.timestamp,delete Y.sourceRuntimeId;try{return JSON.stringify(Y)}catch{return String(Y.itemId||"")}}function V5(Q){return Q.intent==="metadata-only"}function B5(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 D5=(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}},O5=S8('<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>'),z5=S8('<div class="pie-assessment-toolkit-anchor svelte-vpe4u2" aria-hidden="true"></div> <!>',1),P5={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 color-mix(in srgb, #dc2626 40%, transparent);background:color-mix(in srgb, #dc2626 12%, transparent);color:#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 K0(Q,Y){o6(Y,!0),J0(Q,P5);let J=w1("toolkit"),G=new w8,X=v(null),Z=new v7,j={mode:"gather",role:"student"},q={iife:"pie-item-player",esm:"pie-item-player",preloaded:"pie-item-player",custom:""},W=C(Y,"assessmentId",7,""),V=C(Y,"section",7,null),U=C(Y,"sectionId",7,""),_=C(Y,"attemptId",7,""),H=C(Y,"env",23,()=>({})),F=C(Y,"ndsIcons",7,!1),N=C(Y,"lazyInit",7,!0),P=C(Y,"toolConfigStrictness",7,"error"),f=C(Y,"tools",23,()=>({})),A=C(Y,"toolContextResolvers",7,null),L=C(Y,"enabledTools",7,""),E=C(Y,"toolRegistry",7,null),m=C(Y,"accessibility",23,()=>({})),I=C(Y,"player",7,null),c=C(Y,"playerType",7,""),$=C(Y,"coordinator",7,null),l=C(Y,"createSectionController",7,null),Z7=C(Y,"onFrameworkError",7,null),j7=C(Y,"errorRenderer",7,null),P7=C(Y,"onStageChange",7,null),q7=C(Y,"assessment",7,null),d7=C(Y,"currentItemRef",7,null),i7=C(Y,"pnpEnforcement",7,null),K7=C(Y,"isolation",7,"inherit"),C7=v(null),d=v(null),Y7=v(null),T8=null,y7=null,x7=null,s7=null,f7=null,n7=null,r7=v(0),S1=v(null),o7=v(null),n=v(null),T1=v("Unable to initialize assessment toolkit."),C1=v(R8([])),C8="",y1="",y8=v(""),x8=null,f8=l6(),W7=[],a7=new Map,x1=new WeakMap,k8=d6(),i=A5({sourceCe:"pie-assessment-toolkit",sourceCeShape:"toolkit",runtimeId:J,sectionId:u(()=>U()||void 0),attemptId:u(()=>_()||void 0),emit:(K)=>{c6({isSuppressed:()=>D(X)!==null,dispatchDomEvent:(B)=>U7("pie-stage-change",B),getOnStageChange:()=>P7()},K)}}),I8=v(R8(u(()=>`${U()}|${_()}`))),t7=v(!1),a=v(!1),f1=v(!1),k1=v(!1);function W0(){if(!D(C7))return null;let K=D(C7).getRootNode();if(K&&"host"in K)return K.host;return D(C7).parentElement}let y=s(()=>W0());function U7(K,B){if(!D(y)){W7=[...W7,{name:K,detail:B}];return}N8(D(y),K,B)}S(()=>{if(!D(y))return;if(W7.length===0)return;let K=W7;W7=[],queueMicrotask(()=>{let B=D(y);if(!B){W7=[...K,...W7];return}for(let M of K)N8(B,M.name,M.detail)})});function U0(K){if(!j7())return{title:"Unable to initialize assessment toolkit.",details:K.details.length>0?K.details:[K.message]};try{let B=j7()(K)||{};return{title:typeof B.title==="string"&&B.title.trim().length>0?B.title:"Unable to initialize assessment toolkit.",details:Array.isArray(B.details)&&B.details.length>0?B.details.map((M)=>String(M)):K.details.length>0?K.details:[K.message]}}catch(B){let M=B instanceof Error&&B.message.trim().length>0?B.message:String(B||"Unknown renderer error");return{title:"Unable to initialize assessment toolkit.",details:[...K.details,`Error renderer failed: ${M}`]}}}function e7(K){let B=G1({kind:K.kind,source:K.source,error:K.error,recoverable:K.recoverable});return Z.reportFrameworkError(B),B}function V0(K){return K==="coordinator-init"||K==="runtime-init"||K==="tool-config"}function v8(K){if(!Z7())return;try{Z7()(K),C8=`${K.kind}|${K.source}|${K.message}`}catch(B){console.error(`[pie-framework:${K.kind}:${K.source}] framework error hook failed`,B)}}S(()=>{let K=Z.subscribeFrameworkErrors((B)=>{if(console.error(n8(B),B.cause),V0(B.kind)){let M=U0(B);w(n,B,!0),w(T1,M.title,!0),w(C1,M.details,!0)}U7("framework-error",B),v8(B)});return()=>{K()}}),S(()=>{if(!D(n))return;let K=`${D(n).kind}|${D(n).source}|${D(n).message}`;if(C8===K)return;v8(D(n))});function B0(K){let B=5381;for(let M=0;M<K.length;M+=1)B=(B<<5)+B^K.charCodeAt(M);return(B>>>0).toString(36)}function V7(K){return K&&typeof K==="object"?K:{}}function D0(K){let B=V7(K.section),M=typeof B.identifier==="string"?B.identifier:"",z=typeof K.sectionId==="string"?K.sectionId:"";return M||z}function _0(K){return typeof K.currentItemIndex==="number"?K.currentItemIndex:-1}function H0(K){return(Array.isArray(K.renderables)?K.renderables:[]).map((M,z)=>{let O=V7(M),k=V7(O.entity),r=typeof k.id==="string"&&k.id||`renderable-${z}`,J1=V7(k.config),m1=typeof k.version==="string"&&k.version||(typeof k.version==="number"?String(k.version):"")||(typeof J1.version==="string"?J1.version:"");return{id:r,version:m1}})}function A0(K){let B=V7(K.itemSessionsByItemId);return Object.keys(B).sort((M,z)=>M.localeCompare(z)).map((M)=>{let z=V7(B[M]),O=typeof z.id==="string"?z.id:"",k=Array.isArray(z.data)?z.data:[],r="";try{r=B0(JSON.stringify(k))}catch{r=String(k.length)}return{itemId:M,sessionId:O,payloadSignature:r}})}function F0(K){let B=V7(K),M=H0(B).map((O)=>`${O.id}:${O.version}`).join("|"),z=A0(B).map((O)=>`${O.itemId}:${O.sessionId}:${O.payloadSignature}`).join("|");return{sectionId:D0(B),currentItemIndex:_0(B),renderableSignature:M,itemSessionSignature:z}}function M0(K){let B=F0(K);return`${B.sectionId}|${B.currentItemIndex}|${B.renderableSignature}|${B.itemSessionSignature}`}function h8(K){return K==="iife"||K==="esm"||K==="preloaded"||K==="custom"}function N0(K,B){let M=K?.type,z=h8(M)?M:h8(B)?B:K?.tagName?"custom":"iife",O=K?.tagName?.trim();if(z==="custom"&&!O)return{type:"iife",tagName:q.iife,version:void 0,source:void 0,isDefault:!0};return{type:z,tagName:O||q[z],version:K?.version,source:K?.source,loaderConfig:K?.loaderConfig,loaderOptions:K?.loaderOptions,isDefault:!K&&!B}}function m8(K){let B=K||{},M=typeof B.mode==="string"&&B.mode.trim()?B.mode.trim():j.mode,z=typeof B.role==="string"&&B.role.trim()?B.role.trim():j.role;return{mode:M,role:z}}function O0(K){let B=m8(K);if(B.mode==="author")return"author";if(B.role==="instructor")return"scorer";return"candidate"}async function z0(){if(l())return l()();throw Error("pie-assessment-toolkit requires createSectionController when no coordinator hook provides one")}function u8(){let K=f()||{},B=q0(L());if(B.length===0)return K;let M=K.placement||{},z=Array.isArray(M.section)?M.section:null;if(z&&z.length>0)return K;return{...K,placement:{...M,section:B}}}function P0(){return G7(u8(),{strictness:P(),source:"pie-assessment-toolkit.bootstrap",toolRegistry:E()}).config}function L0(){let K="",B="";try{K=JSON.stringify(u8())}catch{K="[unserializable-tools]"}try{B=JSON.stringify(Object.entries(A()??{}).map(([M,z])=>[M,typeof z]))}catch{B="[unserializable-resolvers]"}return[W()||"",String(P()||"error"),K,B].join("|")}function p8(K){return K==="on"||K==="off"?K:null}function $0(K,B){let M=p8(K);if(M)return M;if(B&&typeof B==="object"){let O=B.pnpEnforcement;return p8(typeof O==="string"?O:null)}return null}function w0(K){let B=W()||V()?.identifier||`assessment-${Math.random().toString(16).slice(2)}`;return new P1({assessmentId:B,lazyInit:N(),toolConfigStrictness:P(),deferToolConfigValidation:!0,tools:K,toolRegistry:E(),toolContextResolvers:A(),accessibility:m(),frameworkErrorBus:Z})}let x=s(()=>{if(K7()!=="force"&&D(Y7)?.coordinator)return D(Y7).coordinator;return $()||D(d)});S(()=>{D(y),$(),K7(),D(Y7),A(),u(()=>{if(!D(y))return;if($()){if(D(d))w(d,null);y7=null;return}if(K7()!=="force"&&D(Y7)?.coordinator){if(D(d))w(d,null);y7=null;return}if(D(d)&&y7!==A()){try{D(d).setToolContextResolvers(A()),y7=A()}catch(K){w(o7,K,!0),e7({kind:"coordinator-init",phase:"coordinator-ready",error:K})}return}if(!D(d)){let K=L0();if(y1===K)return;try{let B=P0();w(d,w0(B),!0),y7=A(),y1="",w(n,null),w(T1,"Unable to initialize assessment toolkit."),w(C1,[],!0)}catch(B){w(o7,B,!0),w(d,null),y1=K,e7({kind:"coordinator-init",source:"pie-assessment-toolkit",error:B})}}})});let J7=s(()=>W()||D(x)?.assessmentId||""),t=s(()=>U()||V()?.identifier||`section-${D(J7)||"default"}`),I1=s(()=>m8(H())),R0=s(()=>O0(D(I1))),L7=s(()=>N0(I(),c())),k7=s(()=>F5({player:D(L7),component:"pie-assessment-toolkit"})),Q1=s(()=>{if(!D(x))return null;let K=D(x).getServiceBundle();return{toolkitCoordinator:D(x),toolCoordinator:D(x).toolCoordinator,ttsService:K.ttsService,highlightCoordinator:K.highlightCoordinator,catalogResolver:K.catalogResolver,elementToolStateStore:K.elementToolStateStore,assessmentId:D(J7),sectionId:D(t),itemPlayer:D(L7),ndsIcons:F()===!0,reportSessionChanged:(B,M)=>{let z=G.updateItemSession(B,M);l8({itemId:B,result:z,fallbackSession:M})}}}),Y1=s(()=>{if(!D(x))return null;return{runtimeId:J,coordinator:D(x)}});function b0(K){let B=M0(K);if(B===D(y8))return;w(y8,B,!0),w(r7,D(r7)+1),w(S1,K,!0),U7("composition-changed",{composition:D(S1),version:D(r7)})}function v1(K){x8=K??G.getCompositionModel(),f8.schedule(()=>{b0(x8)})}function h1(K){if(!K)return;let B=x1.get(K);if(!B)return;for(let M of B)M();x1.delete(K)}function g8(){for(let K of a7.values())h1(K.element)}function c8(K){if(h1(K.element),!D(x))return;let B=D(x).getServiceBundle().catalogResolver;if(typeof B.registerCatalogs!=="function")return;let M=C6(K,{assessmentId:D(J7),sectionId:D(t)});if(M.length===0)return;x1.set(K.element,M.map((z)=>B.registerCatalogs(z.context,z.catalogs)))}function E0(){g8();for(let K of a7.values())c8(K)}function l8(K){let M={...K.result?.eventDetail||K.fallbackSession,itemId:K.itemId,canonicalItemId:K.canonicalItemId||K.itemId,sourceRuntimeId:J};if(!s6({state:k8,itemId:K.itemId,payload:M}))return;U7("session-changed",M)}function S0(K){if(!(K instanceof HTMLElement))return!1;return _5(K,E8)?.runtimeId===J}function I7(K){return K.detail??null}function T0(K,B){for(let M of B)K.addEventListener(M.name,M.handler);return()=>{for(let M of B)K.removeEventListener(M.name,M.handler)}}S(()=>{if(!D(y))return;if(K7()==="force"){w(Y7,null);return}return j0(D(y),(K)=>{if(K.runtimeId===J)return;w(Y7,K,!0)})}),S(()=>{let K=D(y);return u(()=>{if(!K){w(X,null);return}let B=g6(K,(M)=>{if(M.engine===D(X))return;w(X,M.engine,!0)});return()=>{B(),w(X,null)}})}),S(()=>{let K=K7()!=="force"&&D(Y7)?D(Y7).runtimeId:null,B=K?"inherited":"owned";if(B!==T8)T8=B,U7(B==="inherited"?"runtime-inherited":"runtime-owned",{runtimeId:J,parentRuntimeId:K})}),S(()=>{let K=D(t),B=_()||"";i6(k8)}),S(()=>{if(!D(y)||!D(Y1))return;return f7=new n6(D(y),{context:E8,initialValue:D(Y1)}),f7.connect(),n7=new r6(D(y)),n7.attach(),()=>{n7?.detach(),n7=null,f7?.disconnect(),f7=null}}),S(()=>{if(!D(Y1))return;f7?.setValue(D(Y1))}),S(()=>{if(!D(y))return;D(y).setAttribute("data-item-player-type",D(L7).type),D(y).setAttribute("data-item-player-tag",D(L7).tagName),D(y).setAttribute("data-env-mode",String(D(I1)?.mode||"")),D(y).setAttribute("data-env-role",String(D(I1)?.role||""))}),S(()=>{if(!D(y)||!D(Q1))return;return x7=new n6(D(y),{context:Z0,initialValue:D(Q1)}),x7.connect(),s7=new r6(D(y)),s7.attach(),()=>{s7?.detach(),s7=null,x7?.disconnect(),x7=null}}),S(()=>{if(D(Q1))x7?.setValue(D(Q1))}),S(()=>{return D(x),D(J7),D(t),E0(),()=>{g8()}}),S(()=>{if(!D(y))return;return H5({host:D(y),instrumentationProvider:D(k7),component:"pie-assessment-toolkit",eventMap:M5,staticAttributes:{instrumentationLayer:"toolkit",assessmentId:D(J7),sectionId:D(t),attemptId:_()||void 0}})}),S(()=>{q7(),d7(),i7(),f();let K=D(x);if(!K)return;if(K!==D(d))return;u(()=>{K.setPnpEnforcement($0(i7(),f())),K.updateAssessment(q7()),K.updateCurrentItemRef(d7())})}),S(()=>{if(!D(x))return;return D(x).subscribeTelemetry(({eventName:K,payload:B})=>{if(!N5(D(k7)))return;if(!D(k7).isReady())return;let M=K,z=new Date().toISOString(),O={...B||{},instrumentationLayer:"toolkit",assessmentId:D(J7),sectionId:D(t),attemptId:_()||void 0,component:"pie-assessment-toolkit",sourceEventName:K,timestamp:z};D(k7).trackEvent(M,O);let k=B&&typeof B.errorType==="string"?B.errorType:void 0;if(!K.endsWith("-error")&&!k)return;let r=B&&typeof B.message==="string"?B.message:`Toolkit telemetry error: ${K}`;D(k7).trackError(Error(r),{component:"pie-assessment-toolkit",errorType:k||"ToolkitTelemetryError",...O})})}),S(()=>{if(!V()||!D(x))return;let K=!1;return G.initialize({coordinator:D(x),section:V(),sectionId:D(t),assessmentId:D(J7),attemptId:_()||void 0,view:D(R0),createDefaultController:z0,onCompositionChanged:(B)=>{if(K)return;v1(B)}}).then(()=>{if(K)return;U7("toolkit-ready",{runtimeId:J,assessmentId:D(J7),sectionId:D(t),itemPlayer:D(L7),coordinator:D(x)}),U7("section-ready",{sectionId:D(t)}),u(()=>{w(k1,!0)})}).catch((B)=>{u(()=>{if(!D(a))w(a,!0),i.enter("engine-ready","skipped");i.enter("interactive","failed")}),w(o7,B,!0),G.reportSectionError({source:"section-runtime",error:B,timestamp:Date.now()}),e7({kind:"runtime-init",source:"pie-assessment-toolkit",error:B})}),()=>{K=!0}}),S(()=>{if(!D(y))return;let K=D(y),B=(z)=>S0(z.target);return T0(K,[{name:R6,handler:(z)=>{if(!B(z))return;let O=I7(z);if(!O?.element||!O?.itemId)return;let k=G.register(O);if(a7.set(O.element,O),c8(O),G.handleContentRegistered(O),k)v1()}},{name:b6,handler:(z)=>{if(!B(z))return;let O=I7(z);if(!O?.itemId)return;let k=O?.element?G.unregister(O.element):!1;if(h1(O.element),O.element)a7.delete(O.element);if(G.handleContentUnregistered(O),k)v1()}},{name:E6,handler:(z)=>{if(!B(z))return;let O=I7(z);if(!O?.itemId)return;let k=G.updateItemSession(O.itemId,O.session);l8({itemId:O.itemId,canonicalItemId:G.getCanonicalItemId(O.itemId),result:k,fallbackSession:O.session})}},{name:S6,handler:(z)=>{if(!B(z))return;let O=I7(z);if(!O?.itemId)return;G.handleContentLoaded({itemId:O.itemId,canonicalItemId:O.canonicalItemId,contentKind:O.contentKind,detail:O.detail,timestamp:Date.now()})}},{name:T6,handler:(z)=>{if(!B(z))return;let O=I7(z);if(!O?.itemId)return;G.handleItemPlayerError({itemId:O.itemId,canonicalItemId:O.canonicalItemId,contentKind:O.contentKind,error:O.error,timestamp:Date.now()})}}])});async function C0(){if(!D(x))throw Error("Coordinator not initialized");await D(x).waitUntilReady()}function y0(){if(!D(x))throw Error("Coordinator not initialized");return D(x).getServiceBundle()}function x0(K){if(!D(x))throw Error("Coordinator not initialized");D(x).setHooks(K)}function f0(K){return G.navigateToItem(K)}function k0(){return G.getCompositionModel()}function I0(){return D(L7)}async function v0(){await G.persist()}async function h0(){await G.hydrate()}S(()=>{return()=>{u(()=>{if(i.getCurrent()!==null)i.enter("disposed")})}}),S(()=>{let K=`${U()}|${_()}`;u(()=>{if(K===D(I8))return;if(i.getCurrent()!==null)i.enter("disposed");i.reset({sectionId:U()||void 0,attemptId:_()||void 0}),w(I8,K),w(t7,!1),w(a,!1),w(f1,!1),w(k1,!1)})}),S(()=>{let K=D(a)&&D(k1);u(()=>{if(!K)return;if(D(f1))return;w(f1,!0),i.enter("interactive")})}),S(()=>{let K=D(r7)>0||D(S1)!==null;u(()=>{if(!D(t7)&&K)w(t7,!0),i.enter("composed")})}),S(()=>{if(!D(x))return;if(!D(t7))return;if(D(a))return;let K=D(x),B=!1;return K.waitUntilReady().then(()=>{if(B)return;u(()=>{if(D(a))return;w(a,!0),i.enter("engine-ready")})}).catch(()=>{if(B)return;u(()=>{if(D(a))return;w(a,!0),i.enter("engine-ready","failed")})}),()=>{B=!0}}),S(()=>{return()=>{f8.cancel(),G.dispose().catch((K)=>{w(o7,K,!0),e7({kind:"runtime-dispose",source:"pie-assessment-toolkit",error:K,recoverable:!0})}).finally(()=>{Z.dispose()})}});var m0={waitUntilReady:C0,getServiceBundle:y0,setHooks:x0,navigateToItem:f0,getCompositionModel:k0,getItemPlayerConfig:I0,persist:v0,hydrate:h0,get assessmentId(){return W()},set assessmentId(K){W(K),T()},get section(){return V()},set section(K){V(K),T()},get sectionId(){return U()},set sectionId(K){U(K),T()},get attemptId(){return _()},set attemptId(K){_(K),T()},get env(){return H()},set env(K){H(K),T()},get ndsIcons(){return F()},set ndsIcons(K){F(K),T()},get lazyInit(){return N()},set lazyInit(K){N(K),T()},get toolConfigStrictness(){return P()},set toolConfigStrictness(K){P(K),T()},get tools(){return f()},set tools(K){f(K),T()},get toolContextResolvers(){return A()},set toolContextResolvers(K){A(K),T()},get enabledTools(){return L()},set enabledTools(K){L(K),T()},get toolRegistry(){return E()},set toolRegistry(K){E(K),T()},get accessibility(){return m()},set accessibility(K){m(K),T()},get player(){return I()},set player(K){I(K),T()},get playerType(){return c()},set playerType(K){c(K),T()},get coordinator(){return $()},set coordinator(K){$(K),T()},get createSectionController(){return l()},set createSectionController(K){l(K),T()},get onFrameworkError(){return Z7()},set onFrameworkError(K){Z7(K),T()},get errorRenderer(){return j7()},set errorRenderer(K){j7(K),T()},get onStageChange(){return P7()},set onStageChange(K){P7(K),T()},get assessment(){return q7()},set assessment(K){q7(K),T()},get currentItemRef(){return d7()},set currentItemRef(K){d7(K),T()},get pnpEnforcement(){return i7()},set pnpEnforcement(K){i7(K),T()},get isolation(){return K7()},set isolation(K){K7(K),T()}},d8=z5(),i8=b8(d8);G0(i8,(K)=>w(C7,K),()=>D(C7));var u0=R1(i8,2);{var p0=(K)=>{var B=O5(),M=l7(B),z=l7(M,!0);c7(M);var O=R1(M,2),k=l7(O,!0);c7(O);var r=R1(O,2),J1=l7(r,!0);c7(r),c7(B),t6((m1)=>{E1(z,D(T1)),E1(k,D(n).message),E1(J1,m1)},[()=>D(C1).join(`
|
|
224
|
+
`)]),b1(K,B)},g0=(K)=>{var B=e6(),M=b8(B);Y0(M,Y,"default",{},null),b1(K,B)};Q0(u0,(K)=>{if(D(n)&&!D(n).recoverable)K(p0);else K(g0,-1)})}return b1(Q,d8),a6(m0)}D5("pie-assessment-toolkit",X0(K0,{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{K0 as default};
|