@pie-players/pie-assessment-toolkit 1.0.0-beta.8 → 1.0.0-beta.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/components/ItemScope.custom-element.js +1 -1
- package/dist/components/PieAssessmentToolkit.custom-element.js +3 -3
- package/dist/components/chunks/{ItemToolBar-x998kkvy.js → ItemToolBar-eg8jarh0.js} +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/runtime/SectionControllerBinding.d.ts +5 -5
- package/dist/runtime/SectionControllerBinding.js +6 -6
- package/dist/runtime/registration-events.d.ts +3 -3
- package/dist/runtime/registration-events.js +1 -1
- package/dist/services/section-controller-types.d.ts +34 -23
- package/package.json +6 -6
|
@@ -1 +1 @@
|
|
|
1
|
-
import{b as wJ,c as g,d as o,e as u,f as p,g as m,h as E,i as T,j as S,k as c,p as _}from"./chunks/ItemToolBar-
|
|
1
|
+
import{b as wJ,c as g,d as o,e as u,f as p,g as m,h as E,i as T,j as S,k as c,p as _}from"./chunks/ItemToolBar-eg8jarh0.js";import{A as JJ,B as QJ,C as ZJ,D as f,E as XJ,F as qJ,I as WJ,K as UJ,L as y,N as C,R as YJ,T as MJ,Z as jJ,_ as zJ,ea as KJ,fa as k,ga as xJ,ja as i,ka as t,la as P,oa as b,pa as v,qa as OJ,ra as d}from"./chunks/ItemToolBar-bsww9e8f.js";import"./chunks/ItemToolBar-wcw4yxjy.js";import{commitPendingSessions as AJ,createPieLogger as FJ,normalizeItemSessionChange as LJ}from"@pie-players/pie-players-shared";function VJ(Q){let J=Q&&typeof Q==="object"?{...Q}:Q;if(J&&typeof J==="object")delete J.timestamp,delete J.sourceRuntimeId;try{return JSON.stringify(J)}catch{return String(J)}}var fJ=(Q)=>Boolean(Q&&typeof Q==="object"&&Q.sessionSource==="correct-response"),kJ=(Q)=>Boolean(Q&&typeof Q==="object"&&Q.sessionCommitReason);function l(Q){let{host:J,kind:Z,identity:U,mode:z,send:Y}=Q,M=FJ(J.localName||"pie-shell",()=>!1),x="",O=(j)=>{let{itemId:W,canonicalItemId:K}=U();if(!W)return;Y(u,{itemId:W,session:j});let X=LJ({itemId:W,sessionDetail:j});if(X.intent==="metadata-only"||!X.session)return;let L={itemId:W,canonicalItemId:K||W,session:X.session,...X.sessionCommitReason?{sessionCommitReason:X.sessionCommitReason}:{}};P(J,p,L)},w=(j)=>{if(z()!=="section")return;if(j.stopPropagation(),Z!=="item")return;let W=j.detail;if(fJ(W))return;let K=VJ(W);if(!kJ(W)&&K===x)return;x=K,O(W)},A=(j)=>{if(z()==="section")j.stopPropagation();let{itemId:W,canonicalItemId:K,contentKind:q}=U();if(!W)return;let X={itemId:W,canonicalItemId:K||W,contentKind:q,detail:j.detail};Y(T,X)},F=(j)=>{if(z()!=="section"||Z!=="item")return;let W=j.detail;if(W?.scope!=="delivery")return;let{itemId:K,canonicalItemId:q}=U();if(!K)return;let X={itemId:K,canonicalItemId:q||K,...W.identity?{identity:W.identity}:{}};Y(S,X)},V=(j)=>{if(z()==="section")j.stopPropagation();let{itemId:W,canonicalItemId:K,contentKind:q}=U();if(!W)return;let X={itemId:W,canonicalItemId:K||W,contentKind:q,error:j.detail};Y(c,X)},B=(j)=>{if(z()!=="section"||Z!=="item")return;let{itemId:W,canonicalItemId:K}=U();if(!W)return;let q={itemId:W,canonicalItemId:K||W,type:j.type,detail:j.detail};P(J,m,q)};J.addEventListener("session-changed",w),J.addEventListener("load-complete",A),J.addEventListener("backend-load-complete",F),J.addEventListener("player-error",V);for(let j of E)J.addEventListener(j,B);return{disconnect:()=>{try{if(Z==="item"&&z()==="section")AJ(J,{reason:"teardown",logger:M})}finally{J.removeEventListener("session-changed",w),J.removeEventListener("load-complete",A),J.removeEventListener("backend-load-complete",F),J.removeEventListener("player-error",V);for(let j of E)J.removeEventListener(j,B)}}}}import{ContextProvider as CJ}from"@pie-players/pie-context";function HJ(Q,J){return Q.kind===J.kind&&Q.host===J.host&&Q.itemId===J.itemId&&Q.canonicalItemId===J.canonicalItemId&&Q.contentKind===J.contentKind&&d(Q.settings,J.settings)}function r(Q){return _(Q.item,Q.kind)}function $(Q,J){return Q.isConnected||!J?Q:J.eventTarget}function I(Q,J,Z){let U={kind:J.kind,itemId:J.itemId,canonicalItemId:J.canonicalItemId,contentKind:J.contentKind,item:J.item,...J.settings?{settings:J.settings}:{},element:J.host,...Z?{runtimeId:Z.runtimeId}:{}};P($(J.host,Z),Q,U)}function s(){let Q=null,J=null,Z;function U(){let Y=Q;if(!Y)return;let M=Z;Q=null,J=null,Z=void 0,I(o,Y,M)}function z(Y,M){if(!Y){U();return}if(Q&&Z?.runtimeId!==M?.runtimeId)U();if(Q&&HJ(Q,Y)){if(Q.item===Y.item)return;let x=r(Y);if(x!==null&&x===J){Q=Y;return}Q=Y,J=x,I(g,Y,M);return}Q=Y,J=r(Y),Z=M,I(g,Y,M)}return{sync:z,retire:U}}var PJ=50;function n(Q,J,Z){let U=new CJ(Q,{context:J,initialValue:Z});return U.connect(),{provider:U,value:Z}}function a(Q,J,Z){if(Z(Q.value,J))return;Q.value=J,Q.provider.setValue(J)}var DJ=(Q,J,Z)=>{if(Q===J)return!0;if(!Q||!J)return!1;if(Q.id!==J.id)return!1;let U=_(Q,Z);return U!==null&&U===_(J,Z)},TJ=(Q,J)=>Q.kind===J.kind&&Q.itemId===J.itemId&&Q.canonicalItemId===J.canonicalItemId&&Q.contentKind===J.contentKind&&Q.regionPolicy===J.regionPolicy&&Q.scopeElement===J.scopeElement&&DJ(Q.item,J.item,Q.kind),SJ=(Q,J)=>Q.scopeElement===J.scopeElement&&Q.ttsHighlightTargetResolver===J.ttsHighlightTargetResolver,N=(Q,J,Z)=>{if(Q.getAttribute(J)!==Z)Q.setAttribute(J,Z)};function e(){let Q=s(),J=Date.now(),Z=null,U=null,z=null,Y=null,M=null,x=null,O=[],w=null,A=null,F=()=>{if(M!==null)Q.sync(x,M)},V=(q,X)=>q.isConnected&&X.eventTarget.isConnected===!1;function B(q,X){if(q===T)w=X;if(q===S)A=X;if(Z&&M!==null&&!V(Z,M)){P($(Z,M),q,{...X,runtimeId:M.runtimeId});return}if(O.push({type:q,detail:X}),O.length>PJ)O.shift()}function j(q){let X=M!==null&&q.runtimeId!==M.runtimeId;if(q.runtimeId!==M?.runtimeId)M={runtimeId:q.runtimeId,eventTarget:q.eventTarget},F();let L=O;O=[];for(let G of L)B(G.type,G.detail);if(!X)return;let H=(G)=>L.some((D)=>D.type===G);if(A&&!H(S))B(S,A);if(w&&!H(T))B(T,w)}function W(){for(let q of[U,z])q?.provider.disconnect();Y?.(),Y=null,M=null,O=[],w=null,A=null,x=null,U=null,z=null,Z=null}function K(q){if(!q){Q.sync(null),W();return}if(q.host!==Z)W();Z=q.host;let X=q.canonicalItemId||q.itemId,L=q.regionPolicy||"default",H=q.scopeElement||q.host,G={kind:q.kind,itemId:q.itemId,canonicalItemId:X,contentKind:q.contentKind,regionPolicy:L,scopeElement:H,item:q.item??null,contextVersion:J};if(U)a(U,G,TJ);else U=n(Z,i,G);let D={scopeElement:H,ttsHighlightTargetResolver:q.ttsHighlightTargetResolver??null};if(z)a(z,D,SJ);else z=n(Z,t,D);N(Z,"data-item-id",q.itemId),N(Z,"data-canonical-item-id",X),N(Z,"data-pie-shell-root",q.kind),N(Z,"data-region-policy",L);let R=x;if(x=q.itemId?{kind:q.kind,host:Z,itemId:q.itemId,canonicalItemId:X,contentKind:q.contentKind,item:q.item??null,settings:q.settings??null}:null,R&&(R.itemId!==x?.itemId||R.canonicalItemId!==x?.canonicalItemId))w=null;Y??=b(Z,j),F()}return{publish:K,retire:Q.retire,disconnect:W,send:B}}var RJ=(Q,J)=>{if(customElements.get(Q))return;try{customElements.define(Q,J)}catch(Z){if(!(Z instanceof DOMException&&Z.name==="NotSupportedError"||Z&&typeof Z==="object"&&Z.name==="NotSupportedError")||!customElements.get(Q))throw Z}},_J=YJ('<div class="pie-item-scope-anchor svelte-980v5l" aria-hidden="true"></div> <!>',1),NJ={hash:"svelte-980v5l",code:".pie-item-scope-anchor.svelte-980v5l {display:none;}"};function BJ(Q,J){JJ(J,!0),zJ(Q,NJ);let Z=k(J,"itemId",7,""),U=k(J,"canonicalItemId",7,""),z=k(J,"contentKind",7,"assessment-item"),Y=k(J,"regionPolicy",7,"default"),M=k(J,"scopeElement",7,null),x=k(J,"ttsHighlightTargetResolver",7,null),O=k(J,"item",7,null),w=k(J,"settings",7,null),A=XJ(null),F=ZJ(()=>{let X=C(A)?.getRootNode();return X instanceof ShadowRoot?X.host:null}),V=e(),B=null;y(()=>{if(!C(F))return;let X=C(F),L=!1,H=!1,G=wJ(X);B=G;let D=b(X,(h)=>{H=!0,L=h.sectionBound===!0,G.setCoordinator(h.coordinator??null)}),R=setTimeout(()=>{if(H||!X.isConnected)return;OJ(X.ownerDocument,"itemScopeWithoutToolkit",`[pie-item-scope] No <pie-assessment-toolkit> has answered item "${Z()}" after ${v/1000} s, so the item is not registered and the tools inside the scope have no runtime. Place the scope inside the toolkit element; it keeps waiting for one. Reported once per page.`)},v),GJ=l({host:X,kind:"item",identity:()=>({itemId:Z(),canonicalItemId:U(),contentKind:z()}),mode:()=>L?"section":"plain",send:V.send});return()=>{clearTimeout(R);try{GJ.disconnect()}finally{if(D(),V.retire(),V.disconnect(),G.disconnect(),B===G)B=null}}}),y(()=>{V.publish(C(F)?{host:C(F),kind:"item",itemId:Z(),canonicalItemId:U(),contentKind:z(),regionPolicy:Y(),scopeElement:M(),ttsHighlightTargetResolver:x(),item:O(),settings:w()}:null),B?.setItem(C(F)?{itemId:Z(),canonicalItemId:U()}:null)});var j={get itemId(){return Z()},set itemId(X){Z(X),f()},get canonicalItemId(){return U()},set canonicalItemId(X){U(X),f()},get contentKind(){return z()},set contentKind(X){z(X),f()},get regionPolicy(){return Y()},set regionPolicy(X){Y(X),f()},get scopeElement(){return M()},set scopeElement(X){M(X),f()},get ttsHighlightTargetResolver(){return x()},set ttsHighlightTargetResolver(X){x(X),f()},get item(){return O()},set item(X){O(X),f()},get settings(){return w()},set settings(X){w(X),f()}},W=_J(),K=WJ(W);KJ(K,(X)=>qJ(A,X),()=>C(A));var q=UJ(K,2);return jJ(q,J,"default",{},null),MJ(Q,W),QJ(j)}RJ("pie-item-scope",xJ(BJ,{itemId:{attribute:"item-id",type:"String"},canonicalItemId:{attribute:"canonical-item-id",type:"String"},contentKind:{attribute:"content-kind",type:"String"},regionPolicy:{attribute:"region-policy",type:"String"},scopeElement:{type:"Object"},ttsHighlightTargetResolver:{type:"Object"},item:{type:"Object"},settings:{type:"Object"}},["default"],[],{mode:"open"}));export{BJ as default};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as F8,c as Y5,d as Z4,e as Q4,i as J4,j as Y4,k as X4,l as G4,m as j4,n as N8,o as P8}from"./chunks/ItemToolBar-
|
|
1
|
+
import{a as F8,c as Y5,d as Z4,e as Q4,i as J4,j as Y4,k as X4,l as G4,m as j4,n as N8,o as P8}from"./chunks/ItemToolBar-eg8jarh0.js";import{t as A1,u as C7,v as _0,w as e1,x as s0}from"./chunks/ItemToolBar-na4e5vwt.js";import{A as u1,B as p1,C as d,D as k,E as n,F as m,G as g1,H as c1,I as T7,J as X5,K as G5,L as y,M as d1,N as F,O as I,R as k7,S as i1,T as j5,U as B5,V as l1,Z as s1,_ as n1,ea as r1,fa as f,ga as a1,ha as o1,ia as W5,la as x7,oa as t1,qa as S1,ra as p0,z as m1}from"./chunks/ItemToolBar-bsww9e8f.js";import{sa as D9,ta as _9}from"./chunks/ItemToolBar-gsb96731.js";import{va as b3}from"./chunks/ItemToolBar-wcw4yxjy.js";import{coerceBooleanAttributes as JQ}from"@pie-players/pie-players-shared/ui/attribute-coercion";import{ContextProvider as y7,interfaceLocaleContext as YQ,requestContext as v1}from"@pie-players/pie-context";import{attachInstrumentationEventBridge as XQ,resolveInstrumentationProvider as GQ,TOOLKIT_INSTRUMENTATION_EVENT_MAP as jQ}from"@pie-players/pie-players-shared/pie";import{commitPendingSessions as h1,createPieLogger as BQ,isGlobalDebugEnabled as WQ,isInstrumentationProvider as VQ}from"@pie-players/pie-players-shared";import{createPieI18n as KQ,DEFAULT_LOCALE as qQ,defaultContentLanguage as UQ,stampInterfaceLocale as $Q}from"@pie-players/pie-players-shared/i18n";import{settleAll as MZ}from"@pie-players/pie-players-shared/promise";var Z6="error";function P5(Z){if(Z==="off"||Z==="warn"||Z==="error")return Z;return Z6}function o(Z){return Z}function Q6(Z){if(!Z)return new Map;return new Map(Z.getAllTools().slice().sort((Q,J)=>Q.toolId.localeCompare(J.toolId)).map((Q)=>[Q.toolId,Q]))}function J6(Z,Q,J,Y){if(!Q||!J?.sanitizeConfig)return Q;try{let X=J.sanitizeConfig(Q);if(!X||typeof X!=="object"||Array.isArray(X))return Y.push(o({code:"tools.providerSanitizeFailed",severity:"error",path:`providers.${Z}`,message:`Config sanitizer of tool "${Z}" must return an object.`,toolId:Z})),Q;return X}catch(X){return Y.push(o({code:"tools.providerSanitizeFailed",severity:"error",path:`providers.${Z}`,message:`Config sanitizer of tool "${Z}" failed: ${X instanceof Error?X.message:String(X)}`,toolId:Z})),Q}}function Y6(Z,Q,J,Y){if(!Q||!J?.validateConfig)return;try{let X=J.validateConfig(Q);if(!Array.isArray(X)){Y.push(o({code:"tools.invalidProviderValidation",severity:"error",path:`providers.${Z}`,message:`Config validator of tool "${Z}" must return an array.`,toolId:Z}));return}for(let G of X)Y.push({...G,path:G.path||`providers.${Z}`,toolId:G.toolId||Z})}catch(X){Y.push(o({code:"tools.providerValidateFailed",severity:"error",path:`providers.${Z}`,message:`Config validator of tool "${Z}" failed: ${X instanceof Error?X.message:String(X)}`,toolId:Z}))}}function X6(Z,Q,J){if(Q.size===0)return;let Y=["section","item","passage"];for(let X of Y)for(let G of Z.placement[X]){let j=Q.get(G);if(!j){J.push(o({code:"tools.unknownToolId",severity:"error",path:`placement.${X}`,message:`Unknown tool id "${G}" in placement.${X}.`,toolId:G}));continue}if(j.activation==="region"){J.push(o({code:"tools.unplaceableActivation",severity:"error",path:`placement.${X}`,message:`Tool "${G}" 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:G}));continue}let B=j.supportedLevels.includes(X),V=X==="item"&&j.supportedLevels.includes("section");if(!B&&!V)J.push(o({code:"tools.unsupportedLevel",severity:"error",path:`placement.${X}`,message:`Tool "${G}" does not support level "${X}".`,toolId:G}))}}var U8=new Set(F8);function G6(Z,Q,J){if(Q.size===0)return;for(let Y of Z.policy.allowed||[]){if(Q.has(Y)||U8.has(Y))continue;J.push(o({code:"tools.unknownToolId",severity:"error",path:"policy.allowed",message:`Unknown tool id "${Y}" in policy.allowed.`,toolId:Y}))}for(let Y of Z.policy.blocked||[]){if(Q.has(Y)||U8.has(Y))continue;J.push(o({code:"tools.unknownToolId",severity:"error",path:"policy.blocked",message:`Unknown tool id "${Y}" in policy.blocked.`,toolId:Y}))}}function j6(Z,Q,J){for(let Y of Object.keys(Z.providers).sort()){if(Q.size===0||Q.has(Y))continue;J.push(o({code:"tools.unknownProviderKey",severity:"error",path:`providers.${Y}`,message:`Unknown provider key "${Y}".`,toolId:Y}))}}function $8(Z,Q){if(Z.length===0)return;for(let J of Z){let Y=`[tool-config-validation:${Q}]`;console.warn(`${Y} ${J.path} - ${J.message}`)}}function B6(Z,Q){let J=Z.map((Y)=>`- ${Y.path}: ${Y.message}`).join(`
|
|
2
2
|
`);throw Error(`[tool-config-validation:${Q}] Invalid tools config:
|
|
3
3
|
${J}`)}function z8(Z,Q={}){let J=w5(Z,Q.toolRegistry);return R5(J.diagnostics,Q),J}function w5(Z,Q){let J=Q6(Q),Y=s0(Z),X=[],G=Object.values(Y.placement).some((V)=>V.length>0)||Object.keys(Y.providers).length>0||(Y.policy.allowed?.length??0)>0||(Y.policy.blocked?.length??0)>0;if(J.size===0&&G)X.push(o({code:"tools.registryUnavailable",severity:"warning",path:"tools",message:'No tool registry was supplied, so tool ids, placement levels and provider config were not validated, and a coordinator without one registers no tool providers. Pass `toolRegistry` to the coordinator or the toolkit it is bound to — for the packaged capability set, `createPackagedToolRegistry()` from "@pie-players/pie-default-tool-loaders".'}));let j={...Y.providers||{}};for(let V of Object.keys(j).sort()){let K=J.get(V);j[V]=J6(V,j[V],K,X),Y6(V,j[V],K,X)}let B={...Y,providers:j};return X6(B,J,X),G6(B,J,X),j6(B,J,X),{config:B,diagnostics:X}}function R5(Z,Q={}){let J=P5(Q.strictness),Y=Q.source??"tools";if(J==="warn")$8(Z,Y);let X=Z.filter((G)=>G.severity==="error");if(J==="error"&&X.length>0)B6(X,Y);if(J==="error"&&X.length===0)$8(Z,Y)}import{languageTagScriptLookupSequence as $6,languageTagScriptsMatch as F6,normalizeLanguageTag as y5}from"@pie-players/pie-players-shared/i18n/language-tags";import{isCloudMetadataHostname as W6,isPrivateHostname as V6}from"@pie-players/pie-players-shared/security/private-hosts";var E5=new Set(["speak","break","prosody","emphasis","say-as","sub","mark","phoneme","lang","p","s","voice","audio","lexicon"]),H8=new Set(["script","style","iframe","object","embed","foreignobject","noscript","template"]),A8=new Set(["alphabet","ph","time","strength","rate","pitch","volume","name","interpret-as","format","detail","language","xml:lang","lang","gender","src"]),D8=new Set(["break","mark","lexicon"]);function K6(Z){let Q=Z;for(let J of D8){let Y=new RegExp(`<${J}\\b([^>/]*?)\\s*/>`,"gi");Q=Q.replace(Y,(X,G)=>{let j=G?G.replace(/\s+$/,""):"";return`<${J}${j}></${J}>`})}return Q}function q6(Z){if(typeof Z!=="string"||Z.length===0)return!1;let Q;try{Q=new URL(Z)}catch{return!1}if(Q.protocol!=="http:"&&Q.protocol!=="https:")return!1;return!W6(Q.hostname)&&!V6(Q.hostname)}function C5(Z){let Q=Array.from(Z.children);for(let Y of Q){let X=Y.tagName.toLowerCase();if(H8.has(X)){Y.remove();continue}if(C5(Y),!E5.has(X)){let G=Z.ownerDocument.createTextNode(Y.textContent??"");Y.replaceWith(G)}}let J=Array.from(Z.attributes).map((Y)=>Y.name);for(let Y of J)if(!A8.has(Y.toLowerCase()))Z.removeAttribute(Y);if(Z.tagName.toLowerCase()==="audio"){let Y=Z.getAttribute("src");if(Y!==null&&!q6(Y))Z.removeAttribute("src")}}function b5(Z){let Q=Z.tagName.toLowerCase(),J=Array.from(Z.attributes).filter((X)=>A8.has(X.name.toLowerCase())).map((X)=>` ${X.name}="${U6(X.value)}"`).join("");if(D8.has(Q))return`<${Q}${J}/>`;let Y=[];for(let X of Array.from(Z.childNodes))if(X.nodeType===3)Y.push(kZ(X.nodeValue??""));else if(X.nodeType===1){let G=X,j=G.tagName.toLowerCase();if(H8.has(j))continue;if(E5.has(j))Y.push(b5(G));else Y.push(kZ(G.textContent??""))}return`<${Q}${J}>${Y.join("")}</${Q}>`}function S5(Z){let Q=String(Z||"").trim();if(!Q||!Q.includes("<"))return Z;if(typeof DOMParser>"u")return Z;let Y=new DOMParser().parseFromString(K6(Q),"text/html"),X=Y.querySelector("speak");if(X)return C5(X),b5(X);let G=Y.createElement("speak");for(let j of Array.from(Y.body.childNodes))G.appendChild(j);return C5(G),Array.from(G.childNodes).map((j)=>{if(j.nodeType===3)return kZ(j.nodeValue??"");if(j.nodeType===1){let B=j;if(E5.has(B.tagName.toLowerCase()))return b5(B);return kZ(B.textContent??"")}return""}).join("")}function kZ(Z){return Z.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}function U6(Z){return Z.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}var w8=new Set(["spoken","sign-language","transcript","braille","tactile","simplified-language","audio-description","extended-description"]),T5="ext:";function _8(Z){if(w8.has(Z))return!0;return Z.startsWith(T5)&&Z.length>T5.length}var M8=new Set;function x5(Z,Q=new Set){if(Z===null||typeof Z==="string"||typeof Z==="number"||typeof Z==="boolean"||typeof Z>"u")return Z;if(typeof Z!=="object")throw TypeError("catalog cards must contain JSON-compatible values");if(Q.has(Z))throw TypeError("catalog cards must not contain cycles");Q.add(Z);try{if(Array.isArray(Z))return Object.freeze(Z.map((X)=>x5(X,Q)));let J=Object.getPrototypeOf(Z);if(J!==Object.prototype&&J!==null)throw TypeError("catalog cards must contain only plain objects and arrays");let Y={};for(let[X,G]of Object.entries(Z))Y[X]=x5(G,Q);return Object.freeze(Y)}finally{Q.delete(Z)}}function O8(Z,Q,J){let Y=`${Q}|${Z}`;if(M8.has(Y))return;M8.add(Y);let X=`${Array.from(w8).join(", ")}, or an "${T5}" prefixed vendor extension`;if(Q==="card"){console.warn(`[AccessibilityCatalogResolver] catalog "${J}" has a card of unknown type "${Z}"; 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 "${Z}" on "${J}" cannot match any card. Expected one of: ${X}.`)}var L8=(Z)=>Z.payload!==void 0?"payload":"content";class k5{assessmentCatalogs=new Map;itemCatalogs=new Map;scopedCatalogs=new Map;defaultLanguage="en-US";sanitizedSpokenCache=new Map;catalogChangeListeners=new Set;reportedSnapshotProblems=new Set;constructor(Z,Q="en-US"){this.defaultLanguage=Q,this.indexCatalogs(Z??[],"assessment")}setDefaultLanguage(Z){this.defaultLanguage=Z}onCatalogsChange(Z){return this.catalogChangeListeners.add(Z),()=>{this.catalogChangeListeners.delete(Z)}}emitCatalogsChange(Z){for(let Q of Array.from(this.catalogChangeListeners))try{Q(Z)}catch{}}getDefaultLanguage(){return this.defaultLanguage}indexCatalogs(Z,Q){let J=Q==="assessment"?this.assessmentCatalogs:this.itemCatalogs;for(let Y of this.sanitizeCatalogs(Z)){if(J.has(Y.identifier)){console.warn(`[AccessibilityCatalogResolver] Duplicate ${Q} catalog "${Y.identifier}" ignored`);continue}J.set(Y.identifier,Y)}}insertScopedCatalogs(Z,Q){if(!Q||Q.length===0)return null;let J=this.getOwnerKey(Z),Y=this.scopedCatalogs.get(J),X=Y?.catalogs??new Map,G=[];for(let j of this.sanitizeCatalogs(Q)){if(X.has(j.identifier)){console.warn(`[AccessibilityCatalogResolver] Duplicate scoped catalog "${j.identifier}" ignored for ${J}`);continue}X.set(j.identifier,j),G.push(j.identifier)}if(!Y&&G.length>0)this.scopedCatalogs.set(J,{context:{...Z},catalogs:X});return{key:J,context:{...Z},catalogs:X,insertedIds:G}}removeScopedInsertion(Z){let Q=this.scopedCatalogs.get(Z.key);if(Q?.catalogs!==Z.catalogs)return!1;let J=!1;for(let Y of Z.insertedIds)J=Q.catalogs.delete(Y)||J;if(Q.catalogs.size===0)this.scopedCatalogs.delete(Z.key);return J}registerCatalogs(Z,Q){let J=this.insertScopedCatalogs(Z,Q);if(J&&J.insertedIds.length>0)this.emitCatalogsChange({reason:"scoped-registered",context:Z});let Y=!0;return()=>{if(!Y)return;if(Y=!1,J&&this.removeScopedInsertion(J))this.emitCatalogsChange({reason:"scoped-removed",context:Z})}}registerOwner(Z){let{owner:Q,entity:J}=Z,Y=N8(Q),X=[],G=[];try{G=P8(J,Q)}catch(V){console.warn("[AccessibilityCatalogResolver] A mounted content owner could not be traversed for catalogs; the primary content remains available.",V)}for(let V of G)try{let K=this.insertScopedCatalogs(V.context,V.catalogs);if(K)X.push(K)}catch(K){console.warn("[AccessibilityCatalogResolver] Invalid catalogs on a mounted content owner were ignored; the primary content and other valid catalogs remain available.",K)}if(X.some((V)=>V.insertedIds.length>0))this.emitCatalogsChange({reason:"scoped-registered",context:Y});let B=!0;return()=>{if(!B)return;B=!1;let V=!1;for(let K of X)V=this.removeScopedInsertion(K)||V;if(V)this.emitCatalogsChange({reason:"scoped-removed",context:Y})}}forOwner(Z){let Q={...Z};return Object.freeze({snapshot:()=>this.createOwnerSnapshot(Q),onChange:(J)=>this.onCatalogsChange((Y)=>{if(this.catalogChangeAffectsOwner(Y,Q))J()})})}addItemCatalogs(Z){if(!Z||Z.length===0)return;this.indexCatalogs(Z,"item"),this.emitCatalogsChange({reason:"item-added"})}clearItemCatalogs(){if(this.itemCatalogs.size===0)return;this.itemCatalogs.clear(),this.emitCatalogsChange({reason:"item-cleared"})}hasCatalog(Z){return this.itemCatalogs.has(Z)||this.assessmentCatalogs.has(Z)||Array.from(this.scopedCatalogs.values()).some((Q)=>Q.catalogs.has(Z))}getAlternative(Z,Q){if(!_8(Q.type))O8(Q.type,"lookup",Z);let J=Q.context?this.scopedCatalogs.get(this.getOwnerKey(Q.context))?.catalogs.get(Z):null;if(J){let G=this.findMatchingCard(J,Q);if(G)return this.resolveCard(Z,G,"item")}if(Q.context){let G=this.findScopedCandidates(Z,Q.context);if(G.length===1){let j=this.findMatchingCard(G[0],Q);if(j)return this.resolveCard(Z,j,"item")}else if(G.length>1)return console.warn(`[AccessibilityCatalogResolver] Ambiguous scoped catalog "${Z}" for owner context`,Q.context),null}let Y=this.itemCatalogs.get(Z);if(Y){let G=this.findMatchingCard(Y,Q);if(G)return this.resolveCard(Z,G,"item")}let X=this.assessmentCatalogs.get(Z);if(X){let G=this.findMatchingCard(X,Q);if(G)return this.resolveCard(Z,G,"assessment")}return null}resolveCard(Z,Q,J){return{catalogId:Z,type:Q.catalog,language:Q.language,content:Q.catalog==="spoken"&&Q.content!==void 0?this.ensureSpokenSanitized(Q.content):Q.content,payload:Q.payload,source:J}}ensureSpokenSanitized(Z){let Q=this.sanitizedSpokenCache.get(Z);if(Q!==void 0)return Q;let J=S5(Z);return this.sanitizedSpokenCache.set(Z,J),J}getOwnerKey(Z){return[Z.ownerKind,Z.assessmentId||"",Z.sectionId||"",Z.canonicalItemId||"",Z.itemId||"",Z.passageId||"",Z.modelId||""].join("|")}scopedCatalogEntries(){let Z=[];for(let Q of this.scopedCatalogs.values())for(let J of Q.catalogs.entries())Z.push(J);return Z}findScopedCandidates(Z,Q){return Array.from(this.scopedCatalogs.values()).filter((J)=>this.isCompatibleOwnerContext(J.context,Q)).map((J)=>J.catalogs.get(Z)).filter((J)=>Boolean(J))}isCompatibleOwnerContext(Z,Q){if(Z.ownerKind!==Q.ownerKind)return!1;if(Q.assessmentId&&Z.assessmentId!==Q.assessmentId)return!1;if(Q.sectionId&&Z.sectionId!==Q.sectionId)return!1;if(Q.canonicalItemId&&Z.canonicalItemId!==Q.canonicalItemId)return!1;if(Q.itemId&&Z.itemId!==Q.itemId)return!1;if(Q.passageId&&Z.passageId!==Q.passageId)return!1;if(Q.modelId&&Z.modelId!==Q.modelId)return!1;return!0}ownerScopedCatalogEntries(Z){let Q=[],J=this.scopedCatalogs.get(this.getOwnerKey(Z));if(J)Q.push(...J.catalogs.entries());for(let Y of this.scopedCatalogs.values()){if(Y===J)continue;if(!this.isCompatibleOwnerContext(Y.context,Z))continue;Q.push(...Y.catalogs.entries())}return Q}createOwnerSnapshot(Z){let Q=[],J=this.ownerScopedCatalogEntries(Z);if(Z.ownerKind==="global")J.push(...this.assessmentCatalogs.entries());for(let[Y,X]of J)for(let G of X.cards)try{Q.push(Object.freeze({catalogId:Y,card:x5(G)}))}catch(j){let B=`${this.getOwnerKey(Z)}\x00${Y}`;if(!this.reportedSnapshotProblems.has(B))this.reportedSnapshotProblems.add(B),console.warn(`[AccessibilityCatalogResolver] Catalog "${Y}" contains a card that cannot be exposed in an owner snapshot; that card was ignored.`,j)}return Object.freeze({cards:Object.freeze(Q)})}catalogChangeAffectsOwner(Z,Q){if(!Z.context)return!1;if(this.isCompatibleOwnerContext(Z.context,Q))return!0;if(Q.ownerKind==="itemModel"&&Q.modelId&&Z.context.ownerKind==="itemModel"&&!Z.context.modelId)return this.isCompatibleOwnerContext({...Z.context,modelId:Q.modelId},Q);return!1}sanitizeCatalogs(Z){return Z.map((Q)=>({...Q,cards:Q.cards.map((J)=>{if(!_8(J.catalog))O8(J.catalog,"card",Q.identifier);return{...J,content:J.catalog==="spoken"&&J.content!==void 0?S5(J.content):J.content}})}))}findMatchingCard(Z,Q){let{type:J,language:Y,useFallback:X=!0,form:G}=Q,j=[],B=(V)=>{let K=y5(V);for(let U of $6(V))j.push(($)=>y5($.language)===U&&(U===K||F6(V,$.language)))};if(Y)B(Y);if(X)B(this.defaultLanguage),j.push(()=>!0);for(let V of j){let K=Z.cards.filter((U)=>U.catalog===J&&V(U));if(K.length===0)continue;if(G){let U=K.find(($)=>L8($)===G);if(U)return U}return K[0]}return null}getAllAlternatives(Z){let Q=[],J=new Set,Y=(j,B)=>{let V=`${j.catalog}|${y5(j.language)}|${L8(j)}`;if(J.has(V))return;J.add(V),Q.push(this.resolveCard(Z,j,B))},X=this.itemCatalogs.get(Z);if(X)for(let j of X.cards)Y(j,"item");let G=this.assessmentCatalogs.get(Z);if(G)for(let j of G.cards)Y(j,"assessment");for(let[j,B]of this.scopedCatalogEntries()){if(j!==Z)continue;for(let V of B.cards)Y(V,"item")}return Q}getAllCatalogIds(){let Z=this.scopedCatalogEntries().map(([Q])=>Q);return Array.from(new Set([...this.itemCatalogs.keys(),...this.assessmentCatalogs.keys(),...Z]))}getStatistics(){let Z=new Set,Q=new Set;for(let J of this.assessmentCatalogs.values())for(let Y of J.cards)if(Z.add(Y.catalog),Y.language)Q.add(Y.language);for(let J of this.itemCatalogs.values())for(let Y of J.cards)if(Z.add(Y.catalog),Y.language)Q.add(Y.language);for(let J of this.scopedCatalogs.values())for(let Y of J.catalogs.values())for(let X of Y.cards)if(Z.add(X.catalog),X.language)Q.add(X.language);return{totalCatalogs:this.assessmentCatalogs.size+this.itemCatalogs.size+Array.from(this.scopedCatalogs.values()).reduce((J,Y)=>J+Y.catalogs.size,0),assessmentCatalogs:this.assessmentCatalogs.size,itemCatalogs:this.itemCatalogs.size+Array.from(this.scopedCatalogs.values()).reduce((J,Y)=>J+Y.catalogs.size,0),availableTypes:Z,availableLanguages:Q}}hasAlternativeType(Z,Q){return this.getAllAlternatives(Z).some((Y)=>Y.type===Q)}getCatalogsByType(Z){let Q=new Set;for(let[J,Y]of this.assessmentCatalogs.entries())if(Y.cards.some((X)=>X.catalog===Z))Q.add(J);for(let[J,Y]of this.itemCatalogs.entries())if(Y.cards.some((X)=>X.catalog===Z))Q.add(J);for(let[J,Y]of this.scopedCatalogEntries())if(Y.cards.some((X)=>X.catalog===Z))Q.add(J);return Array.from(Q)}reset(){this.assessmentCatalogs.clear(),this.itemCatalogs.clear(),this.scopedCatalogs.clear(),this.sanitizedSpokenCache.clear(),this.reportedSnapshotProblems.clear()}destroy(){this.reset()}}var R8=["assessmentId","sectionId","attemptId","itemId","elementId"];function f5(Z){return Z.replace(/%/g,"%25").replace(/:/g,"%3A")}function z6(Z){return Z.replace(/%(25|3A)/g,(Q,J)=>J==="25"?"%":":")}class I5{elementStates=new Map;listeners=new Set;onStateChange=null;getGlobalElementId(Z){return R8.map((Q)=>f5(Z[Q])).join(":")}parseGlobalElementId(Z){let Q=Z.split(":");if(Q.length!==R8.length)return null;let[J,Y,X,G,j]=Q.map(z6);return{assessmentId:J,sectionId:Y,attemptId:X,itemId:G,elementId:j}}setState(Z,Q,J){let Y=this.elementStates.get(Z);if(!Y)Y=new Map,this.elementStates.set(Z,Y);Y.set(Q,J),this._notifyListeners(),this._notifyStateChange()}getState(Z,Q){return this.elementStates.get(Z)?.get(Q)}getElementState(Z){let Q=this.elementStates.get(Z);if(!Q)return{};return Object.fromEntries(Q.entries())}getAllState(){let Z={};for(let[Q,J]of this.elementStates.entries())Z[Q]=Object.fromEntries(J.entries());return Z}subscribe(Z){return this.listeners.add(Z),()=>this.listeners.delete(Z)}_notifyListeners(){if(this.listeners.size===0)return;let Z=new Map([...this.elementStates].map(([Q,J])=>[Q,new Map(J)]));for(let Q of this.listeners)try{Q(Z)}catch(J){console.warn("[ElementToolStateStore] listener failed:",J)}}setOnStateChange(Z){this.onStateChange=Z}_notifyStateChange(){if(!this.onStateChange)return;try{this.onStateChange(this.getAllState())}catch(Z){console.warn("[ElementToolStateStore] state-change callback failed:",Z)}}loadState(Z){this.elementStates.clear();for(let[Q,J]of Object.entries(Z)){let Y=new Map(Object.entries(J));this.elementStates.set(Q,Y)}this._notifyListeners()}clearElement(Z){this.elementStates.delete(Z),this._notifyListeners(),this._notifyStateChange()}clearTool(Z){for(let Q of this.elementStates.values())Q.delete(Z);this._notifyListeners(),this._notifyStateChange()}clearSection(Z,Q){let J=`${f5(Z)}:${f5(Q)}:`,Y=[];for(let X of this.elementStates.keys())if(X.startsWith(J))Y.push(X);for(let X of Y)this.elementStates.delete(X);this._notifyListeners(),this._notifyStateChange()}clearAll(){this.elementStates.clear(),this._notifyListeners(),this._notifyStateChange()}}function fZ(Z){return{kind:Z.kind,severity:Z.severity??"error",source:Z.source,message:Z.message,details:[...Z.details||[]],recoverable:Z.recoverable===!0,scope:Z.scope??"runtime",...Z.cohort?{cohort:{...Z.cohort}}:{},cause:Z.cause}}function v5(Z){let Q=Z.error instanceof Error&&Z.error.message.trim().length>0?Z.error.message:String(Z.error||"Unknown framework error");return fZ({kind:Z.kind,source:Z.source,message:Q,recoverable:Z.recoverable,scope:Z.scope,cohort:Z.cohort,cause:Z.error})}var H6={"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","tool-module-load":"tool-module-load","tool-request-open":"tool-request","tool-request-host-check":"tool-request","tool-visibility":"tool-registration","tool-applicability":"tool-registration","tool-state-load":"tool-state-load","tool-state-save":"tool-state-save","tool-playback":"tool-playback"};function C8(Z){let Q=H6[Z.context.phase],J=Z.context.toolId?`pie-toolkit-coordinator/${Z.context.toolId}`:`pie-toolkit-coordinator:${Z.context.phase}`;return v5({kind:Q,source:J,error:Z.error,recoverable:Z.recoverable,scope:Z.scope,cohort:Z.cohort})}function b8(Z){let Q=`[pie-framework:${Z.kind}:${Z.source}]`;if(Z.details.length===0)return`${Q} ${Z.message}`;return`${Q} ${Z.message}
|
|
4
4
|
- ${Z.details.join(`
|
|
@@ -220,6 +220,6 @@ ${J}`)}function z8(Z,Q={}){let J=w5(Z,Q.toolRegistry);return R5(J.diagnostics,Q)
|
|
|
220
220
|
`;let X=Z.allDecisions.filter((G)=>G.step!==Q.step&&G.action!=="skip"&&G.action!=="advisory"&&G.precedence>Q.precedence);if(X.length>0){Y+=`
|
|
221
221
|
**Overridden Rules**:
|
|
222
222
|
`;for(let G of X)Y+=`- ${G.rule}: ${G.reason}
|
|
223
|
-
`}return Y}function K1(Z){let{request:Q,tools:J,pnpPolicy:Y,customSources:X,contextId:G}=Z,j=new L7(G);j.addSource("host",{id:Q.scope.scopeId,name:`${Q.level}:${Q.scope.scopeId}`,config:{placement:J.placement,policy:J.policy}});let B=_0(J.placement[Q.level]),V=_0(J.policy.allowed),K=new Set(_0(J.policy.blocked)),U=[];for(let D of B)U.push(D),j.addDecision({precedence:0,rule:"placement-membership",featureId:D,action:"skip",sourceType:"host",reason:`Listed in tools.placement.${Q.level}`});if(U=U.filter((D)=>{if(J.providers?.[D]?.enabled===!1)return j.addDecision({precedence:0,rule:"provider-disabled",featureId:D,action:"block",sourceType:"host",reason:`tools.providers.${D}.enabled === false`,value:!1}),!1;return!0}),V.length>0){let D=new Set(V);U=U.filter((P)=>{if(!D.has(P))return j.addDecision({precedence:0,rule:"host-allowlist",featureId:P,action:"block",sourceType:"host",reason:"Not present in tools.policy.allowed",value:V}),!1;return!0})}U=U.filter((D)=>{if(K.has(D))return j.addDecision({precedence:0,rule:"host-blocked",featureId:D,action:"block",sourceType:"host",reason:"Listed in tools.policy.blocked",value:J.policy.blocked}),!1;return!0});let $=[],z=new Set(U),H=null;if(Y.enforcement==="on"&&Y.source&&(Y.assessment||Y.item)){if(H=Y.source.apply({assessment:Y.assessment,item:Y.item}),H.sources.assessment)j.addSource("assessment",H.sources.assessment);if(H.sources.student)j.addSource("student",H.sources.student);if(H.sources.item)j.addSource("item",H.sources.item);for(let M of H.decisions)j.addDecision({precedence:M.precedence,rule:M.rule,featureId:M.featureId,action:M.action,sourceType:M.sourceType,reason:M.reason,value:M.value});for(let[M,C]of H.blockedOverrides)$.push(P7(M,C,Q.level));for(let[M,C]of H.supportConflicts){if(!z.has(M))continue;$.push(_Z(M,C.support,C.grant??"placement",Q.level))}let{blockedToolIds:D}=H;U=U.filter((M)=>!D.has(M));let P=new Set(Object.values(J.placement).flatMap(_0));for(let[M,C]of H.mandates){if(z.has(M))continue;if(!B.includes(M)&&P.has(M))continue;let E=y2(M,{placedAtAnyLevel:P,allTools:J.placement,allowed:V,blocked:K,providers:J.providers}),v={rule:C,hostRule:E.hostRule,hostValue:E.hostValue};$.push({code:"tool-policy.requiredToolBlocked",level:Q.level,toolId:M,message:E.hostRule==="placement-missing"?`Profile policy mandates "${M}" (${C}), but no level of tools.placement lists it.`:`Profile policy mandates "${M}" (${C}), but host policy removes it via ${E.hostRule}.`,details:v}),j.addDecision({precedence:0,rule:"required-tool-blocked",featureId:M,action:"advisory",sourceType:"host",reason:`Host removed required tool "${M}" via ${E.hostRule}`,value:v})}}for(let D=0;D<X.length;D++){let P=X[D],M=U.slice(),C=P.refine({request:Q,candidates:M}),E=new Set(C.refinedCandidates);for(let S of C.refinedCandidates)if(!M.includes(S))$.push({code:"tool-policy.placementMissing",level:Q.level,toolId:S,message:`Custom source "${P.id}" tried to add tool "${S}" that was not in candidates; ignored.`,details:{customSourceId:P.id}}),E.delete(S);U=M.filter((S)=>E.has(S));let v=new Set;if(C.decisions){for(let S of C.decisions)if(j.addDecision({precedence:S.precedence??100+D,rule:S.rule,featureId:S.featureId,action:S.action,sourceType:S.sourceType,reason:S.reason,value:S.value}),S.action==="block")v.add(S.featureId)}for(let S of M){if(E.has(S))continue;if(v.has(S))continue;j.addDecision({precedence:100+D,rule:"custom-source",featureId:S,action:"block",sourceType:"custom",reason:`Custom policy source "${P.id}" removed tool "${S}" from candidates without emitting a decision; auto-logged for trail completeness.`,value:{customSourceId:P.id}})}}for(let D of U)for(let P of Z.unappliedItems??[]){let M=["restrictedTools","requiredTools"].filter((E)=>P.settings[E]?.includes(D)===!0);if(M.length===0)continue;let C={itemId:P.id,settings:M,toolbarLevel:Q.scope.level};$.push({code:"tool-policy.itemSettingNotApplied",level:Q.level,toolId:D,message:`Item "${P.id}" names "${D}" in ${M.join(" and ")}, but "${D}" is on the ${Q.scope.level}-level toolbar, which item settings do not reach. Place "${D}" at item level to enforce the setting per item.`,details:C})}let O=new Set(U),N=U.map((D)=>{let P=H?.perToolFlags.get(D);return{toolId:D,required:P?.required??!1,alwaysAvailable:P?.alwaysAvailable??!1,activateAtInit:P?.activateAtInit??!1,parameters:oZ(D,Y.assessment,Y.item)}});return j.reconcileFinalStates(O),{visibleTools:N,diagnostics:$,provenance:j.build()}}function y2(Z,Q){if(!Q.placedAtAnyLevel.has(Z))return{hostRule:"placement-missing",hostValue:Q.allTools};if(Q.providers?.[Z]?.enabled===!1)return{hostRule:"provider-disabled",hostValue:!1};if(Q.allowed.length>0&&!Q.allowed.includes(Z))return{hostRule:"host-allowlist",hostValue:Q.allowed};if(Q.blocked.has(Z))return{hostRule:"host-blocked",hostValue:Array.from(Q.blocked)};return{hostRule:"placement-missing",hostValue:Q.allTools}}var N7={"district-block":"settings.districtPolicy.blockedTools","test-admin-override":"settings.testAdministration.toolOverrides","item-restriction":"item settings.restrictedTools","pnp-prohibited":"personalNeedsProfile.prohibitedSupports","support-conflict":"a withholding support in personalNeedsProfile.supports","item-requirement":"item settings.requiredTools","district-requirement":"settings.districtPolicy.requiredTools","pnp-support":"personalNeedsProfile.supports","pnp-activate-at-init":"personalNeedsProfile.activateAtInit"};function P7(Z,Q,J){return{code:"tool-policy.overrideBlocked",...J?{level:J}:{},toolId:Z,message:`settings.testAdministration.toolOverrides grants "${Z}", but ${N7[Q]} withdraws it and outranks a granting override.`,details:{rule:Q}}}function _Z(Z,Q,J,Y){let X=J==="placement"?"tools.placement":J==="attribute"?"The item player's attribute":J==="authored"?"The item's authored content":N7[J];return{code:"tool-policy.supportConflict",...Y?{level:Y}:{},toolId:Z,message:`${X} serves "${Z}", but the student's "${Q}" support withholds it.`,details:{support:Q,servedBy:J}}}function q1(Z,Q){let J=Q.map((Y)=>N7[Y]).join(", ");return{code:"tool-policy.unknownSupportId",toolId:Z,message:`No tool is registered under "${Z}", named in ${J}, so it matches nothing. These lists name tools by tool id.`,details:{origins:[...Q]}}}var T2=(Z)=>`No assessment is bound, so no policy source could grant "${Z}"`;function w7(Z,Q,J,Y){return{featureId:Z,granted:!1,action:"block",rule:Q,precedence:0,sourceType:"host",reason:Q==="host-blocked"?"Listed in tools.policy.blocked":`Not listed in tools.policy.allowed (${J.join(", ")})`,required:!1,assessmentBound:Y.assessmentBound,diagnostics:[]}}function U1(Z,Q,J,Y){let X=Q.decisions[0],G=Array.from(Q.perToolFlags.values())[0],j=X?.action==="enable",B=X?.reason??`Feature "${Z}" not configured`,V=X!==void 0&&X.action!=="skip",K=Q.supportConflicts.get(Z);return{featureId:Z,granted:j,action:X?.action??"skip",rule:V?X.rule:"none",precedence:V?X.precedence:null,sourceType:X?.sourceType??"system",reason:J.assessmentBound||j?B:T2(Z),required:Boolean(G?.required),parameters:Y,...V&&X.rule==="support-conflict"&&K?{withheldBy:K.support}:{},assessmentBound:J.assessmentBound,diagnostics:[...Array.from(Q.blockedOverrides,([U,$])=>P7(U,$)),...Array.from(Q.supportConflicts).flatMap(([U,{support:$,grant:z}])=>z?[_Z(U,$,z)]:[])]}}var u0=(Z)=>Array.isArray(Z)&&Z.length>0;function x2(Z){if(!Z)return!1;let Q=Z.personalNeedsProfile;if(Q&&(u0(Q.supports)||u0(Q.prohibitedSupports)||u0(Q.activateAtInit)))return!0;let J=Z.settings;if(J){let Y=J.districtPolicy;if(Y&&(u0(Y.blockedTools)||u0(Y.requiredTools)))return!0;let X=J.testAdministration?.toolOverrides;if(X&&typeof X==="object"&&Object.keys(X).length>0)return!0}return!1}function k2(Z){if(!Z)return!1;return u0(Z.requiredTools)||u0(Z.restrictedTools)}function $1(Z){if(x2(Z.assessment))return"on";if(k2(Z.itemSettings))return"on";return"off"}class tZ{id="pnp";toolRegistry;supportConflicts;withheldBy=new Map;registrylessIds=new Set;constructor(Z,Q=[]){this.toolRegistry=Z,this.supportConflicts=Q;for(let{support:J,withholds:Y}of Q){this.registrylessIds.add(J);for(let X of Y){this.registrylessIds.add(X);let G=this.withheldBy.get(X)??[];G.push(J),this.withheldBy.set(X,G)}}}apply(Z){let{ctx:Q,result:J}=this.prepare(Z),{pnp:Y,districtPolicy:X,testAdmin:G,itemSettings:j}=Q,B=new Set;Y?.supports?.forEach((V)=>B.add(V)),Y?.prohibitedSupports?.forEach((V)=>B.add(V)),Y?.activateAtInit?.forEach((V)=>B.add(V)),X?.blockedTools?.forEach((V)=>B.add(V)),X?.requiredTools?.forEach((V)=>B.add(V));for(let V of Object.keys(G?.toolOverrides??{}))B.add(V);j?.requiredTools?.forEach((V)=>B.add(V)),j?.restrictedTools?.forEach((V)=>B.add(V));for(let{support:V,withholds:K}of this.supportConflicts)if(this.supportInEffect(V,Q))K.forEach((U)=>B.add(U));for(let V of B)this.resolveSupport(V,Q,J);return J}resolveFeature(Z,Q){let{ctx:J,result:Y}=this.prepare(Q);return this.resolveSupport(Z,J,Y),Y}prepare(Z){let{assessment:Q,item:J}=Z,Y=Q?.personalNeedsProfile,X=Q?.settings,G=J?.settings,j=R7();if(X?.districtPolicy||X?.testAdministration)j.sources.assessment={id:Q?.id||"unknown",name:Q?.name||Q?.id||"Assessment",config:X};if(Y)j.sources.student={id:"student",name:"Student PNP Profile",config:Y};if(J)j.sources.item={id:J.id,name:J.id,config:J.settings};return{ctx:{pnp:Y,districtPolicy:X?.districtPolicy,testAdmin:X?.testAdministration,itemSettings:G},result:j}}supportInEffect(Z,Q){let J=R7();return this.resolveSupport(Z,Q,J,!1),J.decisions[0]?.action==="enable"}resolveSupport(Z,Q,J,Y=!0){if(Q.districtPolicy?.blockedTools?.includes(Z)){J.blockedToolIds.add(Z),J.decisions.push({precedence:1,rule:"district-block",featureId:Z,action:"block",sourceType:"assessment",reason:`District policy blocks "${Z}" for all assessments`,value:Q.districtPolicy.blockedTools});return}let X=Q.testAdmin?.toolOverrides?.[Z];if(X===!1){J.blockedToolIds.add(Z),J.decisions.push({precedence:2,rule:"test-admin-override",featureId:Z,action:"block",sourceType:"assessment",reason:`Test administrator disabled "${Z}" for this session`,value:Q.testAdmin?.toolOverrides});return}if(Q.itemSettings?.restrictedTools?.includes(Z)){if(J.blockedToolIds.add(Z),X===!0)J.blockedOverrides.set(Z,"item-restriction");J.decisions.push({precedence:3,rule:"item-restriction",featureId:Z,action:"block",sourceType:"item",reason:`Item restricts "${Z}" (e.g., mental math question blocks calculator)`,value:Q.itemSettings.restrictedTools});return}if(Q.pnp?.prohibitedSupports?.includes(Z)){if(J.blockedToolIds.add(Z),X===!0)J.blockedOverrides.set(Z,"pnp-prohibited");J.decisions.push({precedence:4,rule:"pnp-prohibited",featureId:Z,action:"block",sourceType:"student",reason:`Student PNP profile prohibits "${Z}"`,value:Q.pnp.prohibitedSupports});return}let G=Y?this.withheldBy.get(Z)?.find((V)=>this.supportInEffect(V,Q)):void 0;if(G){let V=R7();this.resolveSupport(Z,Q,V,!1);let K=V.decisions[0];J.blockedToolIds.add(Z),J.supportConflicts.set(Z,{support:G,...K?.action==="enable"?{grant:K.rule}:{}}),J.decisions.push({precedence:4,rule:"support-conflict",featureId:Z,action:"block",sourceType:"student",reason:`"${Z}" is withheld while the student's "${G}" support is in effect`,value:{support:G}});return}let j=Q.pnp?.activateAtInit?.includes(Z)===!0,B=Q.itemSettings?.requiredTools?.includes(Z)?"item-requirement":Q.districtPolicy?.requiredTools?.includes(Z)?"district-requirement":void 0;if(X===!0){if(B)J.mandates.set(Z,B);J.perToolFlags.set(Z,{required:B!==void 0,alwaysAvailable:!0,activateAtInit:j,rule:"test-admin-override"}),J.decisions.push({precedence:5,rule:"test-admin-override",featureId:Z,action:"enable",sourceType:"assessment",reason:`Test administrator enabled "${Z}" for this session`,value:Q.testAdmin?.toolOverrides});return}if(B==="item-requirement"){J.mandates.set(Z,B),J.perToolFlags.set(Z,{required:!0,alwaysAvailable:!1,activateAtInit:j,rule:"item-requirement"}),J.decisions.push({precedence:6,rule:"item-requirement",featureId:Z,action:"enable",sourceType:"item",reason:`Item requires "${Z}" for this question`,value:Q.itemSettings?.requiredTools});return}if(B==="district-requirement"){J.mandates.set(Z,B),J.perToolFlags.set(Z,{required:!0,alwaysAvailable:!1,activateAtInit:j,rule:"district-requirement"}),J.decisions.push({precedence:7,rule:"district-requirement",featureId:Z,action:"enable",sourceType:"assessment",reason:`District policy requires "${Z}" for all assessments`,value:Q.districtPolicy?.requiredTools});return}if(j){J.perToolFlags.set(Z,{required:!1,alwaysAvailable:!0,activateAtInit:j,rule:"pnp-activate-at-init"}),J.decisions.push({precedence:8,rule:"pnp-activate-at-init",featureId:Z,action:"enable",sourceType:"student",reason:`Student PNP profile turns on "${Z}" at start`,value:Q.pnp?.activateAtInit});return}if(Q.pnp?.supports?.includes(Z)){J.perToolFlags.set(Z,{required:!1,alwaysAvailable:!0,activateAtInit:!1,rule:"pnp-support"}),J.decisions.push({precedence:8,rule:"pnp-support",featureId:Z,action:"enable",sourceType:"student",reason:`Student PNP profile requests "${Z}"`,value:Q.pnp.supports});return}J.decisions.push({precedence:8,rule:"pnp-support",featureId:Z,action:"skip",sourceType:"system",reason:`Feature "${Z}" not configured at any level`,value:{supportId:Z}})}unknownSupportIds(Z,Q){let J=new Map;if(this.toolRegistry.getAllTools().length===0)return J;let Y=Z?.personalNeedsProfile,X=Z?.settings,G=[["district-block",X?.districtPolicy?.blockedTools],["test-admin-override",Object.keys(X?.testAdministration?.toolOverrides??{})],["item-restriction",Q.flatMap((j)=>j.restrictedTools??[])],["pnp-prohibited",Y?.prohibitedSupports],["item-requirement",Q.flatMap((j)=>j.requiredTools??[])],["district-requirement",X?.districtPolicy?.requiredTools],["pnp-activate-at-init",Y?.activateAtInit],["pnp-support",Y?.supports]];for(let[j,B]of G)for(let V of B??[]){if(this.toolRegistry.has(V)||this.registrylessIds.has(V))continue;let K=J.get(V)??[];if(!K.includes(j))K.push(j);J.set(V,K)}return J}}function R7(){return{blockedToolIds:new Set,mandates:new Map,perToolFlags:new Map,decisions:[],blockedOverrides:new Map,supportConflicts:new Map,sources:{}}}var F1=s0({policy:{allowed:[],blocked:[]},placement:{section:[],item:[],passage:[]},providers:{}});class eZ{toolRegistry;unsubscribeRegistry;contextId;assessmentOptional;pnpPolicySource;supportConflicts;customSources;listeners=new Set;tools;assessment;pnpEnforcementOverride;itemSettings=new Map;inputDiagnostics=Object.freeze([]);disposed=!1;constructor(Z){this.toolRegistry=Z.toolRegistry,this.contextId=Z.contextId??"tool-policy",this.assessmentOptional=Z.assessmentOptional===!0,this.supportConflicts=Z.supportConflicts??[],this.pnpPolicySource=new tZ(this.toolRegistry,this.supportConflicts),this.customSources=Z.customSources?[...Z.customSources]:[];let Q=Z.inputs??{};this.tools=Q.tools??F1,this.assessment=Q.assessment??null,this.pnpEnforcementOverride=Q.pnpEnforcement??null,this.refreshInputDiagnostics(),this.unsubscribeRegistry=this.watchRegistry()}decide(Z){this.assertNotDisposed();let Q=Z.scope.scopeId?`${this.contextId}:${Z.level}:${Z.scope.scopeId}`:`${this.contextId}:${Z.level}`,J=Z.level==="item"?this.itemForScope(Z.scope):void 0,Y=Z.level!=="item"||Z.scope.level==="section"||Z.scope.level==="assessment";return K1({request:Z,tools:this.tools,pnpPolicy:{source:this.pnpPolicySource,assessment:this.assessment??void 0,item:J,enforcement:this.enforcementFor(J)},unappliedItems:Y?this.enforcedItems():void 0,customSources:this.customSources,contextId:Q})}grantsFeatureAnywhere(Z,Q={}){let J=(Y)=>!Q.enforced||this.enforcementFor(Y)==="on";if(J()&&this.decideFeature(Z).granted)return!0;for(let Y of this.itemSettings.keys()){let X=this.itemSettingsFor(Y);if(!J(X?{id:Y,settings:X}:void 0))continue;if(this.decideFeature(Z,{level:"item",scopeId:Y}).granted)return!0}return!1}registerItemSettings(Z,Q){this.assertNotDisposed();let J={settings:Q},Y=this.itemSettingsFor(Z),X=this.itemSettings.get(Z)??[];return X.push(J),this.itemSettings.set(Z,X),this.emitIfItemSettingsChanged(Z,Y),()=>{if(this.disposed)return;let G=this.itemSettings.get(Z),j=G?.indexOf(J)??-1;if(!G||j<0)return;let B=this.itemSettingsFor(Z);if(G.splice(j,1),G.length===0)this.itemSettings.delete(Z);this.emitIfItemSettingsChanged(Z,B)}}decideFeature(Z,Q){this.assertNotDisposed();let J=this.hostFeatureGate(Z);if(J)return J;let Y=this.itemForScope(Q);return U1(Z,this.pnpPolicySource.resolveFeature(Z,{assessment:this.assessment??void 0,item:Y}),{assessmentBound:this.assessment!==null},oZ(Z,this.assessment,Y))}hostFeatureGate(Z){let Q={assessmentBound:this.assessment!==null},J=_0(this.tools.policy.blocked);if(J.includes(Z))return w7(Z,"host-blocked",J,Q);let Y=_0(this.tools.policy.allowed);if(Y.length>0&&!Y.includes(Z))return w7(Z,"host-allowlist",Y,Q);return null}getVisibleToolIds(Z,Q){return this.decide({level:Z,scope:{level:Z,scopeId:Q}}).visibleTools.map((J)=>J.toolId)}updateInputs(Z){this.assertNotDisposed();let Q=!1,J=!1;if("tools"in Z){let Y=Z.tools??F1;if(!Object.is(this.tools,Y))this.tools=Y,Q=!0}if("assessment"in Z){let Y=Z.assessment??null,X=!p0(this.assessment,Y);if(this.assessment=Y,X)Q=!0,this.refreshInputDiagnostics()}if("pnpEnforcement"in Z){let Y=Z.pnpEnforcement??null;if(this.pnpEnforcementOverride!==Y)this.pnpEnforcementOverride=Y,J=!0}if(Q||J)this.emit({reason:J&&!Q?"pnp-enforcement":"inputs",inputs:this.snapshotInputs()})}replaceToolRegistry(Z,Q){this.assertNotDisposed(),this.unsubscribeRegistry(),this.toolRegistry=Z,this.pnpPolicySource=new tZ(Z,this.supportConflicts),this.unsubscribeRegistry=this.watchRegistry(),this.tools=Q,this.refreshInputDiagnostics(),this.emit({reason:"inputs",inputs:this.snapshotInputs()})}registerPolicySource(Z){return this.assertNotDisposed(),this.customSources.push(Z),this.emit({reason:"policy-source-added",inputs:this.snapshotInputs()}),()=>{let Q=this.customSources.indexOf(Z);if(Q===-1)return;if(this.customSources.splice(Q,1),this.disposed)return;this.emit({reason:"policy-source-removed",inputs:this.snapshotInputs()})}}onPolicyChange(Z){return this.listeners.add(Z),()=>{this.listeners.delete(Z)}}getInputs(){return this.snapshotInputs()}dispose(){if(this.disposed)return;this.disposed=!0,this.unsubscribeRegistry(),this.emit({reason:"disposed",inputs:this.snapshotInputs()}),this.listeners.clear(),this.itemSettings.clear(),this.customSources.length=0}snapshotInputs(){return Object.freeze({tools:this.tools,assessment:this.assessment,pnpEnforcement:this.enforcementFor(),pnpEnforcementOverride:this.pnpEnforcementOverride,assessmentExpected:!this.assessmentOptional||this.pnpEnforcementOverride==="on",diagnostics:this.inputDiagnostics})}enforcementFor(Z){return this.pnpEnforcementOverride??$1({assessment:this.assessment,itemSettings:Z?.settings})}itemSettingsFor(Z){return this.itemSettings.get(Z)?.at(-1)?.settings}emitIfItemSettingsChanged(Z,Q){if(p0(Q,this.itemSettingsFor(Z)))return;this.refreshInputDiagnostics(),this.emit({reason:"item-settings",inputs:this.snapshotInputs()})}refreshInputDiagnostics(){let Z=[];for(let J of this.itemSettings.keys()){let Y=this.itemSettingsFor(J);if(Y)Z.push(Y)}let Q=Array.from(this.pnpPolicySource.unknownSupportIds(this.assessment,Z),([J,Y])=>q1(J,Y));if(p0(this.inputDiagnostics,Q))return!1;return this.inputDiagnostics=Object.freeze(Q),!0}watchRegistry(){return this.toolRegistry.onRegistryChange(()=>{if(this.disposed)return;if(this.refreshInputDiagnostics())this.emit({reason:"inputs",inputs:this.snapshotInputs()})})}itemForScope(Z){if(Z?.level!=="item")return;let Q=Z.canonicalItemId||Z.itemId||Z.scopeId,J=Q?this.itemSettingsFor(Q):void 0;return J?{id:Q,settings:J}:void 0}enforcedItems(){let Z=[];for(let Q of this.itemSettings.keys()){let J=this.itemSettingsFor(Q);if(!J)continue;let Y={id:Q,settings:J};if(this.enforcementFor(Y)==="on")Z.push(Y)}return Z}emit(Z){for(let Q of Array.from(this.listeners))try{Q(Z)}catch{}}assertNotDisposed(){if(this.disposed)throw Error("ToolPolicyEngine has been disposed.")}}import{hasResponseField as f2,hasResponseValue as z1}from"@pie-players/pie-players-shared/pie";import{isPlainRecord as YZ}from"@pie-players/pie-players-shared/object";function Z5(Z){return YZ(Z)&&YZ(Z.session)?Z.session:Z}function I2(Z,Q){let J=YZ(Z)?Z:{},Y=YZ(Q)?Q:{},X=new Set([...Object.keys(J),...Object.keys(Y)]);for(let G of X)if(!p0(Z5(J[G]),Z5(Y[G])))return!1;return!0}function v2(Z,Q){for(let[J,Y]of Object.entries(Z)){if(Y===void 0)continue;if(J==="itemSessions"){if(!I2(Y,Q.itemSessions))return!1;continue}if(!p0(Y,Q[J]))return!1}return!0}function Q5(Z,Q){if(!Z)return Q;let J=YZ(Q.itemSessions)?{...Q.itemSessions}:{},Y=YZ(Z.itemSessions)?Z.itemSessions:{};for(let[G,j]of Object.entries(Y)){if(!z1(Z5(j)))continue;let B=Z5(J[G]);if(z1(B)||f2(B))continue;J[G]=j}let X={...Q,itemSessions:J};return v2(X,Z)?null:X}var H1=[{support:"screenReader",withholds:["textToSpeech","autoplayAudio"]}];class s extends Error{constructor(){super("ToolkitCoordinator has been disposed.");this.name="ToolkitCoordinatorDisposedError"}}class J5 extends Error{constructor(){super("Section controller acquisition was retired during initialization.");this.name="SectionControllerRetiredError"}}var h2=(Z,Q,J)=>{let Y={...Q,...J},X=W1(Z,Q,J);if(X)Y.mathSpeech=X;return Y},m2={"tool-module-load":"failed to load","tool-request-open":"failed to open on request","tool-request-host-check":"failed its toolbar's host check","tool-visibility":"failed its relevance check","tool-applicability":"failed its applicability check","tool-state-load":"failed to restore its state","tool-state-save":"failed to save its state","tool-playback":"failed during playback"},u2=["item-selected","item-session-data-changed","item-session-meta-changed","item-complete-changed","content-loaded","item-player-error"],p2=["section-navigation-change","section-session-applied","section-loading-complete","section-items-complete-changed","section-error","timed-media-cue-changed","timed-media-policy-degraded","timed-media-invalid"];class b7{assessmentId;config;ttsService;toolCoordinator;highlightCoordinator;elementToolStateStore;catalogResolver;toolProviderRegistry;hooks;lazyInit;tts;stateLoadSettled=!1;stateLoadPromise;coordinatorReadyPromise;coordinatorReadyNotified=!1;providerInitPromises=new Map;degradedTools=new Map;reportedToolFailures=new Set;readyChangeListeners=new Set;eagerInit;toolRegistry;toolRegistrySupplied;toolRegistrySettled;toolRegistryAbsent=!1;toolContextResolvers=new Map;toolContextResolverChangeListeners=new Set;toolRequests=new O7((Z,Q,J)=>this.reportToolFailure(Z,Q,J));sectionControllers=new Map;sectionControllerKeys=new Map;sectionControllerInitEntries=new Map;sectionControllerDisposePromises=new Map;sectionPersistenceStrategies=new Map;sectionControllerLifecycleListeners=new Set;activeSubscriptions=new Map;activeCohortMapKey=null;latestRequestedActiveCohortMapKey=null;telemetryListeners=new Set;frameworkErrorBus;ownsFrameworkErrorBus;ownedToolCoordinator;frameworkErrorHookUnsubscribe=null;disposePromise=null;policyEngine;reportedPolicyDiagnostics=new Map;policyDiagnosticListeners=new Set;reportedUnboundFeaturePolicy=!1;reportedRegistryUnavailable=!1;resolveConfig(Z){let Q=P5(Z.toolConfigStrictness),J=Z.toolRegistry??new C7,Y=Z.deferToolConfigValidation===!0?s0(Z.tools):this.validateToolsConfig(Z.tools,{strictness:Q,source:"ToolkitCoordinator.init",toolRegistry:J}),X={...V1};return{...Z,toolConfigStrictness:Q,toolRegistry:J,tools:{...Y,providers:{...X,...Y.providers}},accessibility:{language:"en-US",...Z.accessibility??{},catalogs:Z.accessibility?.catalogs??[]}}}validateToolsConfig(Z,Q){let{config:J,diagnostics:Y}=w5(Z,Q.toolRegistry),X=this.reportedRegistryUnavailable||this.toolRegistryPending()?Y.filter((G)=>G.code!=="tools.registryUnavailable"):Y;if(R5(X,Q),Q.strictness!=="off"&&X.some((G)=>G.code==="tools.registryUnavailable"))this.reportedRegistryUnavailable=!0;return J}constructor(Z){if(!Z.assessmentId)throw Error("ToolkitCoordinator requires assessmentId in config");this.toolRegistrySupplied=Z.toolRegistry!=null,this.toolRegistrySettled=this.toolRegistrySupplied;let Q=this.resolveConfig(Z);if(this.assessmentId=Q.assessmentId,this.config=Q,this.toolRegistry=Q.toolRegistry??new C7,this.installToolContextResolvers(Q.toolContextResolvers),this.hooks={...Q.hooks},this.lazyInit=Z.lazyInit===!0,this.eagerInit=Z.eagerInit??!this.lazyInit,this.frameworkErrorBus=Z.frameworkErrorBus??new UZ,this.ownsFrameworkErrorBus=!Z.frameworkErrorBus,this.subscribeFrameworkErrorHookAdapters(),this.ownedToolCoordinator=new A1,this.toolCoordinator=this.ownedToolCoordinator,this.highlightCoordinator=new AZ,this.elementToolStateStore=new I5,this.catalogResolver=new k5(Q.accessibility?.catalogs||[],Q.accessibility?.language||"en-US"),this.toolProviderRegistry=new rZ,this._registerToolProviders(),this.ttsService=new z7,this.ttsService.setHighlightCoordinator(this.highlightCoordinator),this.ttsService.setReadinessGate(()=>this.ensureTTSReady()),this.tts=new M7({assertNotDisposed:()=>this.assertNotDisposed(),isDisposalStarted:()=>this.disposePromise!==null,isDisposalError:(J)=>J instanceof s,emitTelemetry:(J,Y)=>this.emitTelemetry(J,Y),hooks:this.hooks,toolProviderRegistry:this.toolProviderRegistry,initializeProvider:(J,Y)=>this.initializeProvider(J,Y),ttsService:this.ttsService,catalogResolver:this.catalogResolver,clearDegradedTool:(J)=>void this.degradedTools.delete(J),reportStartFailure:(J,Y,X)=>this.reportStartFailure(J,Y,X),isToolGranted:(J)=>this.isToolGranted(J),lazyInit:this.lazyInit,isToolRegistryPending:()=>this.toolRegistryPending(),providersConfig:()=>this.config.tools?.providers,getProviderDescriptorTools:()=>this.getProviderDescriptorTools(),registerProviderFromTool:(J,Y)=>this.registerProviderFromTool(J,Y),notifyReadyChange:()=>this.notifyReadyChange()}),this.ttsService.setMathSpeechSource(()=>this.tts.mathSpeechRuntimeOptions()),this.setupStatePersistenceHooks(),this.policyEngine=new eZ({toolRegistry:this.toolRegistry,contextId:`toolkit-coordinator:${this.assessmentId}`,assessmentOptional:this.config.assessmentOptional===!0,supportConflicts:H1,inputs:{tools:this.config.tools,assessment:null,pnpEnforcement:this.resolveConfiguredPnpEnforcement()}}),this.policyEngine.onPolicyChange((J)=>{if(J.reason==="disposed")return;if(J.reason==="inputs"||J.reason==="pnp-enforcement")this.reportedPolicyDiagnostics.clear();this.warnPolicyDiagnostics(J.inputs.diagnostics),this.reportNewlyGrantedFailures()}),this.eagerInit)this.waitUntilReady().catch((J)=>{if(J instanceof s)return;console.error("[ToolkitCoordinator] Failed eager initialization:",J),this.handleError(J,{phase:"coordinator-ready",recoverable:!1})})}assertNotDisposed(){if(this.disposePromise!==null)throw new s}subscribeFrameworkErrorHookAdapters(){this.frameworkErrorHookUnsubscribe=this.frameworkErrorBus.subscribeFrameworkErrors((Z)=>{let Q=this.hooks.onFrameworkError;if(!Q)return;try{Q(Z)}catch(J){console.warn("[ToolkitCoordinator] onFrameworkError hook failed:",J)}})}async emitTelemetry(Z,Q){try{await this.hooks.onTelemetry?.(Z,Q)}catch(Y){console.warn("[ToolkitCoordinator] telemetry hook failed:",Y)}let J=Q?{...Q}:void 0;for(let Y of this.telemetryListeners)try{Y({eventName:Z,payload:J?{...J}:void 0})}catch(X){console.warn("[ToolkitCoordinator] telemetry listener failed:",X)}}emitSectionControllerLifecycle(Z){for(let Q of this.sectionControllerLifecycleListeners)try{Q(Z)}catch(J){console.warn("[ToolkitCoordinator] section controller lifecycle listener failed:",J)}}handleError(Z,Q,J){let Y=C8({error:Z,context:Q,recoverable:Q.recoverable,scope:J?"cohort":"runtime",cohort:J});this.frameworkErrorBus.reportFrameworkError(Y)}isToolGranted(Z){try{return this.policyEngine.grantsFeatureAnywhere(Z,{enforced:this.toolRegistry.getToolActivation(Z)!=="region"})}catch{return!1}}reportStartFailure(Z,Q,J,Y=!1){let X=Array.from(J),G=Y||!X.some((j)=>this.isToolGranted(j));if(G&&!Y)for(let j of X)this.degradedTools.set(j,{error:Z,context:Q});this.handleError(Z,{...Q,recoverable:G})}reportToolFailure(Z,Q,J){if(Q==="tool-module-load")this.toolRequests.notifyTargetsChange();let Y=`${Q}\x00${Z}`;if(this.reportedToolFailures.has(Y))return;this.reportedToolFailures.add(Y);let X=J instanceof Error&&J.message.trim().length>0?J.message:String(J),G=()=>this.reportStartFailure(Error(`Tool "${Z}" ${m2[Q]}: ${X}`,{cause:J}),{phase:Q,details:{toolId:Z}},[Z],Q!=="tool-module-load");if(Q==="tool-module-load")G();else queueMicrotask(G)}reportNewlyGrantedFailures(){for(let[Z,Q]of this.degradedTools){if(!this.isToolGranted(Z))continue;this.degradedTools.delete(Z),this.handleError(Q.error,{...Q.context,recoverable:!1})}}onReadyChange(Z){return this.readyChangeListeners.add(Z),()=>{this.readyChangeListeners.delete(Z)}}notifyReadyChange(){for(let Z of this.readyChangeListeners)try{Z()}catch(Q){console.warn("[ToolkitCoordinator] ready-change listener failed:",Q)}}subscribeFrameworkErrors(Z){return this.frameworkErrorBus.subscribeFrameworkErrors(Z)}reportFrameworkError(Z){this.frameworkErrorBus.reportFrameworkError(Z)}sectionControllerKey(Z){return{assessmentId:this.assessmentId,sectionId:Z.sectionId,attemptId:Z.attemptId}}getSectionControllerMapKey(Z){return`${Z.assessmentId}::${Z.sectionId}::${Z.attemptId||""}`}createDefaultSectionPersistence(){let Z=(()=>{try{if(typeof window>"u")return null;return window.localStorage}catch{return null}})(),Q=(J)=>{let{assessmentId:Y,sectionId:X,attemptId:G}=J.key;if(!G)return null;return`pie:section-controller:v1:${Y}:${X}:${G}`};return{async loadSession(J){let Y=Q(J);if(!Z||!Y)return null;let X=Z.getItem(Y);if(!X)return null;try{return JSON.parse(X)}catch{return null}},async saveSession(J,Y){let X=Q(J);if(!Z||!X)return;Z.setItem(X,JSON.stringify(Y))},async clearSession(J){let Y=Q(J);if(!Z||!Y)return;Z.removeItem(Y)}}}async resolveSectionPersistence(Z){let Q=this.getSectionControllerMapKey(Z.key),J=this.sectionPersistenceStrategies.get(Q);if(J)return J;let Y={createDefaultPersistence:()=>this.createDefaultSectionPersistence()},X=await this.hooks.createSectionSessionPersistence?.(Z,Y)??await Y.createDefaultPersistence();return this.sectionPersistenceStrategies.set(Q,X),X}setupStatePersistenceHooks(){this.elementToolStateStore.setOnStateChange((Z)=>{if(!this.hooks.saveToolState)return;Promise.resolve(this.hooks.saveToolState(Z)).catch((Q)=>{this.handleError(Q,{phase:"state-save",recoverable:!0})})})}async ensureStateLoaded(){if(this.stateLoadSettled)return;if(this.stateLoadPromise)return this.stateLoadPromise;return this.stateLoadPromise=(async()=>{let Z=this.hooks.loadToolState;if(!Z)return;try{let Q=await Z();if(this.assertNotDisposed(),Q&&typeof Q==="object")this.elementToolStateStore.loadState(Q);this.stateLoadSettled=!0,await this.emitTelemetry("pie-toolkit-tool-state-loaded",{hasState:Boolean(Q)})}catch(Q){if(Q instanceof s)throw Q;this.stateLoadSettled=!0,this.handleError(Q,{phase:"state-load",recoverable:!0})}})().finally(()=>{this.stateLoadPromise=void 0,this.notifyReadyChange()}),this.stateLoadPromise}toolRegistryPending(){return!this.toolRegistrySettled&&!this.toolRegistryAbsent}adoptToolRegistry(Z){if(this.disposePromise!==null||this.toolRegistrySettled)return!1;if(!Z&&this.toolRegistryAbsent)return!1;let Q=this.config.toolConfigStrictness??"error",J="ToolkitCoordinator.adoptToolRegistry";if(!Z)return this.toolRegistryAbsent=!0,this.validateToolsConfig(this.config.tools,{strictness:Q,source:J,toolRegistry:this.toolRegistry}),this.tts.reportHeldMissingProvider(),!1;this.toolRegistrySettled=!0,this.toolRegistry=Z,this.config.toolRegistry=Z,this.tts.discardHeldMissingProvider();try{this.config.tools=this.validateToolsConfig(this.config.tools,{strictness:Q==="off"?"off":"warn",source:J,toolRegistry:Z})}catch(X){console.warn("[ToolkitCoordinator] Tool config does not validate against the adopted tool registry:",X)}this.policyEngine.replaceToolRegistry(Z,this.config.tools);let Y=this.tts.isStarted();for(let X of this.getProviderDescriptorTools()){if(Y&&this.tts.ownsTool(X.toolId))continue;this.registerProviderFromTool(X)}if(Y)this.tts.scheduleReconfigure();return!0}_registerToolProviders(){let Z=this.getProviderDescriptorTools();for(let Q of Z)this.registerProviderFromTool(Q)}getProviderDescriptorTools(){return this.toolRegistry.getAllTools().filter((Z)=>!!Z.provider)}async registerProviderFromTool(Z,Q=!1){let J=Z.provider;if(!J)return;let{toolId:Y}=Z,X;try{let G=this.getToolConfig(Y)||void 0;if(G?.enabled===!1){if(Q)this.toolProviderRegistry.unregister(Y);return}if(!Q&&this.toolProviderRegistry.has(Y))return;let j=J.createProvider(G),B=J.getInitConfig?.(G)??G?.provider?.init??{},V=this.addToolTelemetryReporter(Y,B),K=this.createToolTelemetryForwarder(Y),U=J.getAuthFetcher?.(G)??G?.provider?.runtime?.authFetcher;X={provider:j,config:V,lazy:J.lazy??!0,authFetcher:U,onTelemetry:K}}catch(G){this.reportProviderRegisterFailure(G,Y);return}await this.registerProvider(Y,X)}createToolTelemetryForwarder(Z){return async(Q,J)=>{await this.emitTelemetry(Q,{...J||{},toolId:Z})}}addToolTelemetryReporter(Z,Q){let J=Q&&typeof Q==="object"?{...Q}:{},Y=typeof J.onTelemetry==="function"?J.onTelemetry:null,X=this.createToolTelemetryForwarder(Z);return J.onTelemetry=async(G,j)=>{if(Y)await Y(G,j);await X(G,j)},J}async registerProvider(Z,Q){try{this.toolProviderRegistry.register(Z,Q);let J={providerName:Q.provider.providerName};await this.hooks.onProviderRegistered?.(Z,J),await this.emitTelemetry("pie-toolkit-provider-registered",{toolId:Z,providerName:Q.provider.providerName})}catch(J){this.reportProviderRegisterFailure(J,Z)}}reportProviderRegisterFailure(Z,Q){console.warn(`[ToolkitCoordinator] Failed to register the provider of tool "${Q}":`,Z),this.reportStartFailure(Z,{phase:"provider-register",toolId:Q},[Q])}async ensureProviderReady(Z){return this.initializeProvider(Z,!1)}async initializeProvider(Z,Q){this.assertNotDisposed();let J=this.providerInitPromises.get(Z);if(J)return J;let Y=(async()=>{try{let X=await this.toolProviderRegistry.getProvider(Z,!1);if(this.assertNotDisposed(),this.toolProviderRegistry.isInitialized(Z))return X;let G={providerName:X.providerName};return await this.hooks.onProviderInitStart?.(Z,G),this.assertNotDisposed(),await this.toolProviderRegistry.initialize(Z),this.assertNotDisposed(),X=await this.toolProviderRegistry.getProvider(Z,!1),await this.hooks.onProviderReady?.(Z,G),this.assertNotDisposed(),await this.emitTelemetry("pie-toolkit-provider-ready",{toolId:Z}),this.assertNotDisposed(),X}catch(X){if(X instanceof s)throw X;let G=X instanceof Error?X:Error(String(X));throw this.reportStartFailure(G,{phase:"provider-init",toolId:Z},this.toolRegistry.get(Z)?.provider?[Z]:[],Q),G}})().finally(()=>{this.providerInitPromises.delete(Z)});return this.providerInitPromises.set(Z,Y),Y}setHooks(Z){if(Object.assign(this.hooks,Z),this.setupStatePersistenceHooks(),this.disposePromise===null&&Z.onCoordinatorReady&&this.isReady())Promise.resolve(Z.onCoordinatorReady(this)).catch((Q)=>{this.handleError(Q,{phase:"coordinator-ready",recoverable:!1})})}subscribeTelemetry(Z){return this.telemetryListeners.add(Z),()=>{this.telemetryListeners.delete(Z)}}getSectionController(Z){let Q=this.sectionControllerKey(Z);return this.sectionControllers.get(this.getSectionControllerMapKey(Q))}subscribeSectionEvents(Z){if(this.activeCohortMapKey===null&&this.latestRequestedActiveCohortMapKey===null)throw Error("[ToolkitCoordinator] subscribeSectionEvents requires an active section cohort; call getOrCreateSectionController first.");let Q=this.activeSubscriptions.get(Z.listener);if(Q)Q.unsubscribeCurrent?.(),Q.unsubscribeCurrent=null;let J={listener:Z.listener,eventTypes:Z.eventTypes,itemIds:Z.itemIds,unsubscribeCurrent:null};this.activeSubscriptions.set(Z.listener,J);let Y=this.activeCohortMapKey===null?void 0:this.sectionControllers.get(this.activeCohortMapKey);if(Y)this.bindSubscriptionToController(J,Y);let X=!1;return()=>{if(X)return;if(X=!0,J.unsubscribeCurrent?.(),J.unsubscribeCurrent=null,this.activeSubscriptions.get(Z.listener)===J)this.activeSubscriptions.delete(Z.listener)}}bindSubscriptionToController(Z,Q){Z.unsubscribeCurrent?.(),Z.unsubscribeCurrent=null;let J=Q.subscribe;if(typeof J!=="function")return;let Y=this.buildSectionEventPredicate(Z);Z.unsubscribeCurrent=J.call(Q,(j)=>{if(!Y(j))return;this.deliverSectionEventSafely(Z.listener,j)});let X=this.buildContentLoadedReplayEvents(Q);for(let j of X)if(Y(j))this.deliverSectionEventSafely(Z.listener,j);let G=this.buildLoadingCompleteReplayEvent(Q);if(G&&Y(G))this.deliverSectionEventSafely(Z.listener,G)}deliverSectionEventSafely(Z,Q){try{Z(Q)}catch(J){console.warn("[ToolkitCoordinator] section-event listener failed:",J)}}setActiveCohort(Z){if(this.activeCohortMapKey===Z)return;this.activeCohortMapKey=Z;let Q=this.sectionControllers.get(Z);if(!Q)return;for(let J of Array.from(this.activeSubscriptions.values()))this.bindSubscriptionToController(J,Q)}setActiveCohortIfLatestRequest(Z){if(this.latestRequestedActiveCohortMapKey!==Z)return;this.setActiveCohort(Z)}suspendActiveCohortIfSuperseded(Z){if(this.activeCohortMapKey===null)return;if(this.activeCohortMapKey===Z)return;this.activeCohortMapKey=null,this.detachActiveSubscriptions()}clearActiveCohortIfMatches(Z){if(this.activeCohortMapKey!==Z)return;this.activeCohortMapKey=null,this.detachActiveSubscriptions()}detachActiveSubscriptions(){for(let Z of Array.from(this.activeSubscriptions.values()))Z.unsubscribeCurrent?.(),Z.unsubscribeCurrent=null}buildSectionEventPredicate(Z){let Q=Z.eventTypes?new Set(Z.eventTypes):null,J=Z.itemIds?new Set(Z.itemIds):null;return(Y)=>{if(Q){let X=Y?.type;if(!X||!Q.has(X))return!1}if(!J)return!0;return Array.from(this.collectEventItemIds(Y)).some((X)=>J.has(X))}}collectEventItemIds(Z){let Q=new Set;if("itemId"in Z&&typeof Z.itemId==="string")Q.add(Z.itemId);if("canonicalItemId"in Z&&typeof Z.canonicalItemId==="string")Q.add(Z.canonicalItemId);if("currentItemId"in Z&&typeof Z.currentItemId==="string")Q.add(Z.currentItemId);if("previousItemId"in Z&&typeof Z.previousItemId==="string")Q.add(Z.previousItemId);return Q}buildContentLoadedReplayEvents(Z){let Q=Z.getRuntimeState?.(),J=Q?.loadedRenderables;if(!Array.isArray(J)||J.length===0)return[];let Y=typeof Q?.currentItemIndex==="number"&&Number.isFinite(Q.currentItemIndex)?Q.currentItemIndex:0,X=Date.now(),G=[];for(let j of J){if(!j)continue;let B=j.itemId,V=typeof j.canonicalItemId==="string"&&j.canonicalItemId?j.canonicalItemId:B;if(typeof B!=="string"||!B)continue;G.push({type:"content-loaded",contentKind:j.contentKind??"unknown",itemId:B,canonicalItemId:V,currentItemIndex:Y,timestamp:X})}return G}buildLoadingCompleteReplayEvent(Z){let Q=Z.getRuntimeState?.();if(Q?.loadingComplete!==!0)return null;let J=typeof Q.totalRegistered==="number"&&Number.isFinite(Q.totalRegistered)?Math.max(0,Q.totalRegistered):0,Y=typeof Q.totalLoaded==="number"&&Number.isFinite(Q.totalLoaded)?Math.max(0,Q.totalLoaded):J;return{type:"section-loading-complete",totalRegistered:J,totalLoaded:Y,currentItemIndex:Q.currentItemIndex,timestamp:Date.now()}}subscribeItemEvents(Z){return this.subscribeSectionEvents({eventTypes:Z.eventTypes||u2,itemIds:Z.itemIds,listener:Z.listener})}subscribeSectionLifecycleEvents(Z){return this.subscribeSectionEvents({eventTypes:Z.eventTypes||p2,listener:Z.listener})}onSectionControllerLifecycle(Z){return this.sectionControllerLifecycleListeners.add(Z),()=>{this.sectionControllerLifecycleListeners.delete(Z)}}async getOrCreateSectionController(Z){if(this.disposePromise!==null)throw new s;let Q=this.sectionControllerKey(Z),J=this.getSectionControllerMapKey(Q);this.latestRequestedActiveCohortMapKey=J,this.suspendActiveCohortIfSuperseded(J);let Y;try{if(Y=await this.resolveExistingSectionController({mapKey:J,key:Q,input:Z.input,updateExisting:Z.updateExisting}),Y){if(this.disposePromise!==null)throw new s;if(Z.initialSession)await this.assignSessionToPublishedController(Y,Z.initialSession)}}catch(V){throw this.deliverSectionStartError(J,V),V}if(Y)return Y;let X=this.sectionControllerDisposePromises.get(J);if(X)await MZ([X]);if(this.disposePromise!==null)throw new s;let G=this.sectionControllerInitEntries.get(J);if(G){if(!Z.initialSession)return G.promise;let V=await G.promise;return await this.assignSessionToPublishedController(V,Z.initialSession),V}let j={retired:!1,candidateClaimed:!1},B=this.initializeNewSectionController({args:Z,key:Q,mapKey:J,token:j}).catch((V)=>{throw this.handleSectionControllerInitError(V,Z),this.deliverSectionStartError(J,V),V}).finally(()=>{if(this.sectionControllerInitEntries.get(J)?.token===j)this.sectionControllerInitEntries.delete(J)});return this.sectionControllerInitEntries.set(J,{key:Q,token:j,promise:B}),B}async resolveExistingSectionController(Z){let Q=this.sectionControllers.get(Z.mapKey);if(!Q)return;if(this.sectionControllerKeys.set(Z.mapKey,Z.key),Z.updateExisting!==!1)await Q.updateInput?.(Z.input);if(this.sectionControllers.get(Z.mapKey)!==Q)return;return this.setActiveCohortIfLatestRequest(Z.mapKey),Q}createSectionControllerContext(Z){return{key:Z.key,coordinator:this,input:Z.input}}async initializeNewSectionController(Z){let Q=this.createSectionControllerContext({key:Z.key,input:Z.args.input}),J=await this.resolveSectionPersistence(Q);if(this.disposePromise!==null||Z.token.retired){if(this.sectionPersistenceStrategies.get(Z.mapKey)===J)this.sectionPersistenceStrategies.delete(Z.mapKey);throw this.createSectionControllerRetirementError()}let Y={createDefaultController:Z.args.createDefaultController},X=await this.hooks.createSectionController?.(Q,Y)??await Y.createDefaultController(),G={mapKey:Z.mapKey,key:Z.key,controller:X,persistence:J,token:Z.token};try{await this.retireUnpublishedSectionControllerIfNeeded(G),await X.configureSessionPersistence?.({strategy:J,context:Q}),await this.retireUnpublishedSectionControllerIfNeeded(G),await X.initialize?.(Z.args.input),await this.retireUnpublishedSectionControllerIfNeeded(G);let j=Z.args.initialSession;if(j){if(!X.applySession)throw Error("Section controller cannot apply the session it was created with: it has no applySession.");await X.applySession(j,{mode:"replace"})}else await X.hydrate?.();return await this.finalizeSectionControllerReady({...G,context:Q}),X}catch(j){throw await this.cleanupUnpublishedSectionController(G),j}}async assignSessionToPublishedController(Z,Q){if(!Q)return;if(!Z.applySession)throw Error("Section controller cannot apply the assigned session: it has no applySession.");let J=Q5(Z.getSession?.()??null,Q);if(!J)return;await Z.applySession(J,{mode:"replace"})}createSectionControllerRetirementError(){return this.disposePromise!==null?new s:new J5}async retireUnpublishedSectionControllerIfNeeded(Z){if(this.disposePromise===null&&!Z.token.retired)return;throw await this.cleanupUnpublishedSectionController(Z),this.createSectionControllerRetirementError()}async cleanupUnpublishedSectionController(Z){if(Z.token.candidateClaimed)return;Z.token.candidateClaimed=!0;try{await Z.controller.dispose?.()}catch(Q){this.handleError(Q,{phase:"section-controller-dispose",details:{sectionId:Z.key.sectionId,attemptId:Z.key.attemptId},recoverable:!0})}finally{if(this.sectionPersistenceStrategies.get(Z.mapKey)===Z.persistence)this.sectionPersistenceStrategies.delete(Z.mapKey)}}retirePublishedSectionControllerIfNeeded(Z){if(this.disposePromise!==null&&!Z.token.retired)this.disposeSectionController({sectionId:Z.key.sectionId,attemptId:Z.key.attemptId});if(Z.token.retired)throw this.createSectionControllerRetirementError()}async finalizeSectionControllerReady(Z){await this.retireUnpublishedSectionControllerIfNeeded(Z),this.sectionControllers.set(Z.mapKey,Z.controller),this.sectionControllerKeys.set(Z.mapKey,Z.key),Z.token.candidateClaimed=!0,this.setActiveCohortIfLatestRequest(Z.mapKey),this.emitSectionControllerLifecycle({type:"ready",key:Z.key,controller:Z.controller}),await this.hooks.onSectionControllerReady?.(Z.context,Z.controller),this.retirePublishedSectionControllerIfNeeded(Z),await this.emitTelemetry("pie-toolkit-section-controller-ready",{assessmentId:Z.key.assessmentId,sectionId:Z.key.sectionId,attemptId:Z.key.attemptId}),this.retirePublishedSectionControllerIfNeeded(Z)}handleSectionControllerInitError(Z,Q){if(Z instanceof s||Z instanceof J5)return;this.handleError(Z,{phase:"section-controller-init",details:{sectionId:Q.sectionId,attemptId:Q.attemptId},recoverable:!1},{sectionId:Q.sectionId,attemptId:Q.attemptId})}deliverSectionStartError(Z,Q){if(Q instanceof s||Q instanceof J5||this.latestRequestedActiveCohortMapKey!==Z)return;let J={type:"section-error",source:"section-runtime",error:Q,currentItemIndex:0,timestamp:Date.now()};for(let Y of Array.from(this.activeSubscriptions.values()))if(this.buildSectionEventPredicate(Y)(J))this.deliverSectionEventSafely(Y.listener,J)}disposeSectionController(Z){let Q=this.sectionControllerKey(Z),J=this.getSectionControllerMapKey(Q),Y=this.sectionControllerInitEntries.get(J);if(Y)Y.token.retired=!0;let X=this.sectionControllers.get(J);if(!X){let K=this.sectionControllerDisposePromises.get(J);if(K)return K;if(!Y)return Promise.resolve();let U=MZ([Y.promise]).then(()=>{return});return this.trackSectionControllerDisposal(J,U)}let G=this.sectionPersistenceStrategies.get(J);if(this.clearActiveCohortIfMatches(J),this.sectionControllers.get(J)===X)this.sectionControllers.delete(J),this.sectionControllerKeys.delete(J),this.sectionPersistenceStrategies.delete(J),this.emitSectionControllerLifecycle({type:"disposed",key:Q});let j=this.createSectionControllerContext({key:Q,input:void 0}),B=this.disposeSectionControllerEntry({args:Z,key:Q,context:j,controller:X,persistenceStrategy:G}),V=Y?MZ([Y.promise]).then(()=>B):B;return this.trackSectionControllerDisposal(J,V)}trackSectionControllerDisposal(Z,Q){this.sectionControllerDisposePromises.set(Z,Q);let J=()=>{if(this.sectionControllerDisposePromises.get(Z)===Q)this.sectionControllerDisposePromises.delete(Z)};return Q.then(J,J),Q}async disposeSectionControllerEntry(Z){try{await this.runSectionControllerDisposePipeline({key:Z.key,context:Z.context,controller:Z.controller,persistBeforeDispose:Z.args.persistBeforeDispose})}catch(Q){this.handleError(Q,{phase:"section-controller-dispose",details:{sectionId:Z.args.sectionId,attemptId:Z.args.attemptId},recoverable:!0})}finally{await this.finalizeSectionControllerDispose({context:Z.context,persistenceStrategy:Z.persistenceStrategy,clearPersistence:Z.args.clearPersistence})}}async runSectionControllerDisposePipeline(Z){let Q=[];if(Z.persistBeforeDispose!==!1)try{await Z.controller.persist?.()}catch(J){Q.push(J)}try{await Z.controller.dispose?.()}catch(J){Q.push(J)}if(Q.length===1)throw Q[0];if(Q.length>1)throw AggregateError(Q,"Section controller persistence and disposal both failed.");await this.hooks.onSectionControllerDispose?.(Z.context,Z.controller),await this.emitTelemetry("pie-toolkit-section-controller-disposed",{assessmentId:Z.key.assessmentId,sectionId:Z.key.sectionId,attemptId:Z.key.attemptId})}async finalizeSectionControllerDispose(Z){if(Z.clearPersistence)await Z.persistenceStrategy?.clearSession?.(Z.context)}dispose(){if(this.disposePromise)return this.disposePromise;return this.disposePromise=Promise.resolve().then(()=>this.disposeOwnedResources()),this.disposePromise}async disposeOwnedResources(){let Z=[],Q=async(Y)=>{try{await Y()}catch(X){Z.push(X)}};await this.waitForAdmittedInitialization();let J=new Map;for(let[Y,X]of this.sectionControllerInitEntries)J.set(Y,X.key);for(let[Y,X]of this.sectionControllerKeys)J.set(Y,X);for(let Y of J.values())this.disposeSectionController({sectionId:Y.sectionId,attemptId:Y.attemptId});await MZ(Array.from(this.sectionControllerDisposePromises.values())),this.sectionControllers.clear(),this.sectionControllerKeys.clear(),this.sectionControllerInitEntries.clear(),this.sectionPersistenceStrategies.clear();for(let Y of this.activeSubscriptions.values())await Q(()=>Y.unsubscribeCurrent?.()),Y.unsubscribeCurrent=null;if(this.activeSubscriptions.clear(),this.activeCohortMapKey=null,this.latestRequestedActiveCohortMapKey=null,await Q(()=>this.ttsService.dispose()),await Q(()=>this.toolProviderRegistry.destroy()),await Q(()=>this.highlightCoordinator.destroy()),await Q(()=>this.ownedToolCoordinator.destroy()),await Q(()=>this.catalogResolver.destroy()),await Q(()=>this.toolRequests.dispose()),await Q(()=>this.policyEngine.dispose()),this.toolContextResolvers.clear(),this.toolContextResolverChangeListeners.clear(),this.policyDiagnosticListeners.clear(),this.sectionControllerLifecycleListeners.clear(),this.telemetryListeners.clear(),this.frameworkErrorHookUnsubscribe?.(),this.frameworkErrorHookUnsubscribe=null,this.ownsFrameworkErrorBus)this.frameworkErrorBus.dispose();if(Z.length===1)throw Z[0];if(Z.length>1)throw AggregateError(Z,"ToolkitCoordinator cleanup failed for multiple owned resources.")}async waitForAdmittedInitialization(){let Z=new Set;if(this.coordinatorReadyPromise)Z.add(this.coordinatorReadyPromise);this.tts.flushInitPromises(Z);for(let Q of this.providerInitPromises.values())Z.add(Q);await MZ(Z)}async ensureTTSReady(){return this.tts.ensureReady()}async waitUntilReady(){if(this.assertNotDisposed(),this.isReady())return;if(this.coordinatorReadyPromise)return this.coordinatorReadyPromise;return this.coordinatorReadyPromise=(async()=>{if(await this.ensureStateLoaded(),this.assertNotDisposed(),this.tts.requiredForReadiness())await this.tts.startForReadiness();if(this.assertNotDisposed(),!this.coordinatorReadyNotified)this.coordinatorReadyNotified=!0,await this.hooks.onCoordinatorReady?.(this),this.assertNotDisposed(),await this.emitTelemetry("pie-toolkit-coordinator-ready",{assessmentId:this.assessmentId})})().finally(()=>{this.coordinatorReadyPromise=void 0}),this.coordinatorReadyPromise}isReady(){return(this.stateLoadSettled||!this.hooks.loadToolState)&&(this.tts.started||this.tts.failedUngranted||!this.tts.requiredForReadiness())}assertCanonicalToolId(Z){if(typeof Z!=="string"||Z.trim().length===0)throw Error("Tool id must be a non-empty string.");if(this.toolRegistry.getAllToolIds().length===0)return;if(!this.toolRegistry.get(Z))throw Error(`Unknown tool id "${Z}".`)}installToolContextResolvers(Z){if(!Z)return;for(let[Q,J]of Object.entries(Z)){if(J==null)continue;if(this.assertCanonicalToolId(Q),typeof J!=="function")throw Error(`Invalid tool context resolver for "${Q}": expected a function.`);this.toolContextResolvers.set(Q,J)}}setToolContextResolvers(Z){this.toolContextResolvers.clear(),this.installToolContextResolvers(Z??void 0),this.notifyToolContextResolverChange()}notifyToolContextResolverChange(){for(let Z of this.toolContextResolverChangeListeners)try{Z()}catch(Q){console.warn("[ToolkitCoordinator] Tool context resolver listener threw:",Q)}}getToolConfig(Z){return this.assertCanonicalToolId(Z),this.config.tools?.providers?.[Z]||null}updateToolConfig(Z,Q){this.assertCanonicalToolId(Z);let J=this.getToolConfig(Z)||{};if(!this.config.tools)this.config.tools=this.validateToolsConfig(void 0,{strictness:this.config.toolConfigStrictness??"error",source:"ToolkitCoordinator.updateToolConfig",toolRegistry:this.toolRegistry});if(!this.config.tools.providers)this.config.tools.providers={};let Y={...this.config.tools.providers,[Z]:h2(Z,J,Q)},X=this.validateToolsConfig({...this.config.tools,providers:Y},{strictness:this.config.toolConfigStrictness??"error",source:"ToolkitCoordinator.updateToolConfig",toolRegistry:this.toolRegistry});this.config.tools=X,this.policyEngine.updateInputs({tools:X}),this.emitTelemetry("pie-toolkit-tool-config-updated",{toolId:Z}),this._applyToolConfigChange(Z)}updateToolsPlacement(Z){if(!this.config.tools)this.config.tools=this.validateToolsConfig(void 0,{strictness:this.config.toolConfigStrictness??"error",source:"ToolkitCoordinator.updateToolsPlacement",toolRegistry:this.toolRegistry});let Q=this.config.tools?.placement??{section:[],item:[],passage:[]},J={section:[...Z.section??Q.section??[]],item:[...Z.item??Q.item??[]],passage:[...Z.passage??Q.passage??[]]},Y=this.validateToolsConfig({...this.config.tools,placement:J},{strictness:this.config.toolConfigStrictness??"error",source:"ToolkitCoordinator.updateToolsPlacement",toolRegistry:this.toolRegistry});Y.placement=J,this.config.tools=Y,this.policyEngine.updateInputs({tools:Y})}decideToolPolicy(Z){let Q=this.policyEngine.decide(Z);return this.warnPolicyDiagnostics(Q.diagnostics),Q}warnPolicyDiagnostics(Z){for(let Q of Z){let J=Q.code==="tool-policy.itemSettingNotApplied"?Q.details.itemId:"",Y=`${Q.code}\x00${Q.toolId}\x00${J}`;if(this.reportedPolicyDiagnostics.has(Y))continue;this.reportedPolicyDiagnostics.set(Y,Q),console.warn(`[ToolkitCoordinator] ${Q.message}`);for(let X of Array.from(this.policyDiagnosticListeners))this.notifyPolicyDiagnosticListener(X,Q)}}notifyPolicyDiagnosticListener(Z,Q){try{Z(Q)}catch(J){console.error("[ToolkitCoordinator] Policy diagnostic listener failed:",J)}}registerItemSettings(Z,Q){return this.policyEngine.registerItemSettings(Z,Q)}decideFeaturePolicy(Z,Q){let J=this.policyEngine.decideFeature(Z,Q);if(this.warnPolicyDiagnostics(J.diagnostics),!J.assessmentBound&&this.policyEngine.getInputs().assessmentExpected&&!this.reportedUnboundFeaturePolicy)this.reportedUnboundFeaturePolicy=!0,console.warn(`[ToolkitCoordinator] Feature policy was asked about "${Z}" with no assessment bound, so profile, district and test-administration policy have nothing to read and only an item's requiredTools can grant. Pass the assessment to the toolkit's assessment property, or call updateAssessment(...), before relying on any accommodation. Reported once per coordinator.`);return J}reportFeatureDecisionApplied(Z,Q){if(Z.granted||Z.rule!=="support-conflict"||Z.overrode!=="attribute"&&Z.overrode!=="authored")return;let J=this.policyEngine.decideFeature(Z.featureId,Q);if(J.rule!=="support-conflict"||!J.withheldBy)return;this.warnPolicyDiagnostics([_Z(Z.featureId,J.withheldBy,Z.overrode)])}onPolicyChange(Z){return this.policyEngine.onPolicyChange(Z)}onPolicyDiagnostic(Z){this.policyDiagnosticListeners.add(Z);for(let Q of Array.from(this.reportedPolicyDiagnostics.values()))this.notifyPolicyDiagnosticListener(Z,Q);return()=>{this.policyDiagnosticListeners.delete(Z)}}onCatalogsChange(Z){return this.catalogResolver.onCatalogsChange(Z)}updateAssessment(Z){this.policyEngine.updateInputs({assessment:Z})}setPnpEnforcement(Z){this.policyEngine.updateInputs({pnpEnforcement:Z})}getPolicyInputs(){return this.policyEngine.getInputs()}registerPolicySource(Z){return this.policyEngine.registerPolicySource(Z)}hasToolContextResolver(Z){return this.assertCanonicalToolId(Z),this.toolContextResolvers.has(Z)}resolveToolContext(Z){this.assertCanonicalToolId(Z.toolId);let Q=this.toolContextResolvers.get(Z.toolId);if(!Q)return null;let J;try{J=Q(Z)}catch(X){return console.error(`[ToolkitCoordinator] Tool context resolver for "${Z.toolId}" threw:`,X),{toolId:Z.toolId,visible:!1,params:{},reason:"Tool context resolver threw."}}if(!J)return{toolId:Z.toolId,visible:!0,params:{}};let Y=J.params&&typeof J.params==="object"&&!Array.isArray(J.params)?J.params:{};return{toolId:Z.toolId,visible:J.visible!==!1,params:Y,reason:typeof J.reason==="string"?J.reason:void 0}}onToolContextResolverChange(Z){return this.toolContextResolverChangeListeners.add(Z),()=>{this.toolContextResolverChangeListeners.delete(Z)}}getToolRegistry(){return this.toolRegistry}registerToolRequestTarget(Z){return this.toolRequests.registerTarget(Z)}requestTool(Z){return this.assertCanonicalToolId(Z.toolId),this.toolRequests.request(Z)}canRequestTool(Z,Q,J){try{this.assertCanonicalToolId(Z)}catch{return!1}return this.toolRequests.canRequest(Z,Q,J)}onToolRequestTargetsChange(Z){return this.toolRequests.onTargetsChange(Z)}resolveConfiguredPnpEnforcement(){return this.config.tools?.pnpEnforcement??null}_applyToolConfigChange(Z){if(this.disposePromise!==null)return;if(this.tts.ownsTool(Z)){this.tts.scheduleReconfigure();return}this._registerChangedToolProvider(Z)}_registerChangedToolProvider(Z){let Q=this.getProviderDescriptorTools().find((J)=>J.toolId===Z);if(!Q)return;this.degradedTools.delete(Z),this.registerProviderFromTool(Q,!0)}}var g2=()=>{};function D1(Z){return Z===R.PLAYING||Z===R.LOADING}function _1(Z){let{ttsService:Q,silence:J}=Z;if(typeof Q?.onStateChange!=="function")return g2;let Y=Q.onStateChange((X)=>{if(D1(X))J()});return()=>{try{Y()}catch{}}}function M1(Z){try{if(D1(Z?.getState?.()))Z?.pause?.()}catch{}}import{timedMediaProjectionSignature as FQ}from"@pie-players/pie-players-shared/timed-media";function O1(Z,Q,J){let Y=Z.detail?.runtimeId;if(typeof Y==="string"&&Y!=="")return Y===Q;return J(Z.target)}function L1(Z,Q,J){let Y=[Z.catalogResolver.registerOwner({owner:{kind:Q.kind,itemId:Q.itemId,canonicalItemId:Q.canonicalItemId,assessmentId:J.assessmentId,sectionId:J.sectionId},entity:Q.item})];if(Q.kind==="item"&&Q.settings)Y.push(Z.registerItemSettings(Q.canonicalItemId||Q.itemId,Q.settings));return Y}var c2=["a[href]","button","label","summary",...["button","checkbox","combobox","link","menuitem","menuitemcheckbox","menuitemradio","option","radio","switch","tab","treeitem"].map((Z)=>`[role="${Z}"]`)].join(", "),N1=new Set(["mi","mn","mtext"]),d2=(Z)=>N1.has(Z.localName)||Z.localName==="mrow"&&Z.children.length===1&&N1.has(Z.children[0].localName),i2=(Z)=>Array.from(Z.getElementsByTagName("mfrac")).every((Q)=>Array.from(Q.children).every(d2))?"Fraction_Over":"Fraction_General",l2=(Z)=>!Z||Z.toLowerCase().split("-")[0]==="en",s2=(Z)=>{if(Z.localName!=="label")return Z;let Q=Z;if(Q.control)return Q.control;let J=Q.getAttribute("for"),Y=Q.getRootNode();return(J?Y.getElementById?.(J):null)??Q.querySelector("input, select, textarea, button")},P1=(Z,Q)=>{let J=s2(Z),Y=J?.getAttribute("aria-labelledby")?.split(/\s+/).filter(Boolean);if(!J||!Y?.length)return!1;let X=J.getRootNode(),G=Y.map((j)=>X.getElementById?.(j)??null).filter((j)=>j!==null);return G.length>0&&!G.some((j)=>j.contains(Q))};function w1(Z,Q={}){if(typeof MutationObserver>"u")return()=>{};let J=new Map,Y=!1,X=async(U,$,z)=>{let H=await ZZ([{type:"math",mathml:U,fallbackText:""}],{language:z,loadSre:Q.loadSre,mathSpeech:{...l2(z)?{style:i2($)}:{},engineOptions:Q.getMathSpeech?.()?.engineOptions}});return H.usedMathSpeech?H.speechText:null},G=(U)=>{let $=h5(U,c2);if(!$||P1($,U))return;let z=E0(U,"math"),H=z&&e0(z.outerHTML);if(!z||!H)return;let O=g8(U,{contentLanguage:Q.getContentLanguage?.()}),N=`${O??""}\x00${H}`,D=J.get(N);if(!D)D=X(H,z,O),J.set(N,D);D.then((P)=>{if(Y||!P||!U.isConnected)return;if(P1($,U))return;if(U.getAttribute("aria-label")!==P)U.setAttribute("aria-label",P)})},j=new WeakSet,B=(U)=>{if(j.has(U))return;j.add(U),K.observe(U,{childList:!0,subtree:!0})},V=(U)=>{if(U.nodeType!==1)return;let $=U,z=h5($,"mjx-container");if(z){G(z);return}if($.shadowRoot)B($.shadowRoot);$Z($,(H)=>{if(H.nodeType!==1)return"skip";let O=H;if(O.localName==="mjx-container")return G(O),"skip";if(O.shadowRoot)B(O.shadowRoot);return})},K=new MutationObserver((U)=>{for(let $ of U)for(let z of $.addedNodes)V(z)});return B(Z),V(Z),()=>{Y=!0,K.disconnect()}}import{createPieLogger as r2,isGlobalDebugEnabled as a2}from"@pie-players/pie-players-shared";function n2(Z,Q){if(Z===Q)return 0;let J=Z.compareDocumentPosition(Q);if(J&Node.DOCUMENT_POSITION_PRECEDING)return 1;if(J&Node.DOCUMENT_POSITION_FOLLOWING)return-1;return 0}class E7{shellsByElement=new Map;register(Z){let Q=this.shellsByElement.get(Z.element),J={...Z,sortKey:Date.now()};if(Q&&Q.kind===J.kind&&Q.itemId===J.itemId&&Q.canonicalItemId===J.canonicalItemId)return!1;return this.shellsByElement.set(Z.element,J),!0}unregister(Z){return this.shellsByElement.delete(Z)}getOrderedShells(Z){let Q=Array.from(this.shellsByElement.values()).filter((J)=>!Z||J.kind===Z);return Q.sort((J,Y)=>n2(J.element,Y.element)),Q}getCanonicalIdMap(){let Z={};for(let Q of this.getOrderedShells("item")){if(!Q.itemId)continue;Z[Q.itemId]=Q.canonicalItemId||Q.itemId}return Z}clear(){this.shellsByElement.clear()}}var R1=r2("section-controller-binding",()=>a2());function o2(Z){let Q=Z?.renderables;if(!Array.isArray(Q))return null;let J=new Set;for(let Y of Q){let X=Y?.entity?.id;if(typeof X==="string"&&X)J.add(X)}return J}function C1(Z,Q){return Z.has(Q.itemId)||!!Q.canonicalItemId&&Z.has(Q.canonicalItemId)}class S7{registry=new E7;controller=null;coordinator=null;sectionId="";attemptId;unsubscribeController=null;activeInitToken=0;sectionRenderableIds=null;boundSections=new Map;loadedRenderableKeys=new Set;async initialize(Z){this.activeInitToken+=1;let Q=this.activeInitToken;this.coordinator=Z.coordinator,this.sectionId=Z.sectionId,this.attemptId=Z.attemptId,this.forgetUnregisteredLoads(Z.coordinator.getSectionController({sectionId:Z.sectionId,attemptId:Z.attemptId}));let J;try{J=await Z.coordinator.getOrCreateSectionController({sectionId:Z.sectionId,attemptId:Z.attemptId,input:{section:Z.section,sectionId:Z.sectionId,assessmentId:Z.assessmentId,view:Z.view},updateExisting:!0,initialSession:Z.initialSession,createDefaultController:Z.createDefaultController})}catch(X){if(Q===this.activeInitToken)this.unsubscribeController?.(),this.unsubscribeController=null,this.controller=null;throw X}if(Q!==this.activeInitToken)return;this.unsubscribeController?.(),this.controller=J,this.sectionRenderableIds=o2(J.getCompositionModel?.());let Y=this.getSectionKey(Z.sectionId,Z.attemptId);this.boundSections.delete(Y),this.boundSections.set(Y,{sectionId:Z.sectionId,attemptId:Z.attemptId,renderableIds:this.sectionRenderableIds}),this.replayRegisteredShellsIntoController(J),Z.onCompositionChanged?.(J.getCompositionModel?.()),this.unsubscribeController=J.subscribe?.((X)=>{try{Z.onControllerEvent?.(X)}catch(G){R1.warn("onControllerEvent handler threw",G)}Z.onCompositionChanged?.(J.getCompositionModel?.())})||null}replayRegisteredShellsIntoController(Z){if(!Z.handleContentRegistered)return;let Q=this.registry.getOrderedShells().filter((Y)=>this.isSectionRenderable(Y));if(Q.length===0)return;for(let Y of Q){let X=Y.canonicalItemId||Y.itemId;Z.handleContentRegistered({itemId:Y.itemId,canonicalItemId:X,contentKind:Y.contentKind||Y.kind})}let J=Date.now();for(let Y of Q){let X=Y.canonicalItemId||Y.itemId,G=this.getLoadedKey(X,Y.contentKind);if(this.loadedRenderableKeys.has(G))Z.handleContentLoaded?.({itemId:Y.itemId,canonicalItemId:X,contentKind:Y.contentKind||Y.kind,timestamp:J})}}getLoadedKey(Z,Q){return`${Q??""}:${Z}`}isSectionRenderable(Z){let Q=this.sectionRenderableIds;return!Q||C1(Q,Z)}getSectionKey(Z,Q){return`${Z}\x00${Q??""}`}controllerFor(Z){if(this.isSectionRenderable(Z))return this.controller;let Q=this.getSectionKey(this.sectionId,this.attemptId),J=[...this.boundSections.entries()].reverse();for(let[Y,X]of J){if(Y===Q||!X.renderableIds)continue;if(!C1(X.renderableIds,Z))continue;let G=this.coordinator?.getSectionController({sectionId:X.sectionId,attemptId:X.attemptId});if(G)return G}return null}requireControllerFor(Z,Q){let J=this.controllerFor(Z);if(!J)R1.warn(`Dropped ${Q} for "${Z.itemId}": no section this toolkit bound renders it.`);return J}forgetUnregisteredLoads(Z){if(!Z||Z===this.controller)return;let Q=Z.getRuntimeState?.()?.loadedRenderables??[];if(Q.length===0)return;let J=new Set;for(let Y of this.registry.getOrderedShells())if(J.add(Y.itemId),Y.canonicalItemId)J.add(Y.canonicalItemId);for(let Y of Q){if(J.has(Y.canonicalItemId)||J.has(Y.itemId))continue;Z.handleContentUnregistered?.({itemId:Y.itemId,canonicalItemId:Y.canonicalItemId,contentKind:Y.contentKind})}}register(Z){return this.registry.register(Z)}unregister(Z){return this.registry.unregister(Z)}getCompositionModel(){return this.controller?.getCompositionModel?.()??null}getCanonicalItemId(Z){return this.registry.getCanonicalIdMap()[Z]||this.controller?.getCanonicalItemId?.(Z)||Z}handleContentRegistered(Z){if(!this.isSectionRenderable(Z))return;this.controller?.handleContentRegistered?.({itemId:Z.itemId,canonicalItemId:Z.canonicalItemId||Z.itemId,contentKind:Z.contentKind||Z.kind})}handleContentUnregistered(Z){let Q=Z.canonicalItemId||Z.itemId,J=this.getLoadedKey(Q,Z.contentKind);if(this.registry.getOrderedShells().some((X)=>this.getLoadedKey(X.canonicalItemId||X.itemId,X.contentKind)===J))return;this.loadedRenderableKeys.delete(J),this.controllerFor(Z)?.handleContentUnregistered?.({itemId:Z.itemId,canonicalItemId:Q,contentKind:Z.contentKind||Z.kind})}handleContentLoaded(Z){let Q=Z.canonicalItemId||Z.itemId;if(this.loadedRenderableKeys.add(this.getLoadedKey(Q,Z.contentKind)),!this.isSectionRenderable(Z))return;this.controller?.handleContentLoaded?.(Z)}handleItemPlayerError(Z){this.requireControllerFor(Z,"an item player error")?.handleItemPlayerError?.(Z)}reportSectionError(Z){(Z.itemId?this.requireControllerFor({itemId:Z.itemId,canonicalItemId:Z.canonicalItemId},"a section error"):this.controller)?.reportSectionError?.(Z)}updateItemSession(Z,Q){let J=this.getCanonicalItemId(Z);return this.requireControllerFor({itemId:Z,canonicalItemId:J},"a session update")?.updateItemSession?.(J,Q)??null}recordServedContentIdentity(Z){let Q=Z.canonicalItemId||this.getCanonicalItemId(Z.itemId);this.requireControllerFor({itemId:Z.itemId,canonicalItemId:Q},"a served content identity")?.recordServedContentIdentity?.({itemId:Q,identity:Z.identity})}navigateToItem(Z){return this.controller?.navigateToItem?.(Z)??null}handleFormativeAction(Z){if(!Z?.itemId)return;let Q=Z.canonicalItemId||this.getCanonicalItemId(Z.itemId),J=this.requireControllerFor({itemId:Z.itemId,canonicalItemId:Q},"a formative action");if(Z.action==="retry"){J?.retryFormativeItem?.({itemId:Q});return}J?.recordFormativeTry?.({itemId:Q,outcomes:Z.outcomes})}handleMediaTimeSource(Z){if(!Z?.renderableId)return;let Q=this.requireControllerFor({itemId:Z.renderableId,canonicalItemId:this.getCanonicalItemId(Z.renderableId)},"a media time source");if(Z.action==="detach"){Q?.detachMediaTimeSource?.({origin:Z.origin??"host"});return}if(!Z.source)return;Q?.attachMediaTimeSource?.(Z.source,{origin:Z.origin??"host",renderableId:Z.renderableId})}requestMediaPauseForCompetingAudio(){return this.controller?.pauseMediaForCompetingAudio?.()??!0}async persist(){await this.controller?.persist?.()}async hydrate(){await this.controller?.hydrate?.()}async dispose(){this.activeInitToken+=1,this.unsubscribeController?.(),this.unsubscribeController=null;let Z=this.coordinator;if(Z)for(let Q of this.boundSections.values())await Z.disposeSectionController({sectionId:Q.sectionId,attemptId:Q.attemptId});this.registry.clear(),this.loadedRenderableKeys.clear(),this.boundSections.clear(),this.controller=null,this.sectionRenderableIds=null,this.coordinator=null}}function b1(Z){let Q=Z.section?.identifier;return Z.sectionId||(typeof Q==="string"?Q:"")||`section-${Z.assessmentId||"default"}`}function E1(Z,Q){return["pnpEnforcement","assessment"].filter((Y)=>Z?!Object.is(Z[Y],Q[Y]):Q[Y]!==null)}function y1(Z){if(!Z)return;let Q=Symbol.for("pie.assessmentToolkit.unclaimedRegistrationWatch"),J=Z;if(J[Q])return;J[Q]=!0,Z.addEventListener(Y5,(Y)=>{let X=Y.detail,G=typeof X?.itemId==="string"?X.itemId:"";S1(Z,"unclaimedRegistration",`[pie-assessment-toolkit] Item "${G}" registered, but no toolkit claimed the registration, so its accessibility catalogs are not filed and it does not count toward its section's loading. Render its shell or scope inside the <pie-assessment-toolkit> that answered it. Reported once per page.`)})}function OZ(Z,Q){if(typeof Z==="function")return Z;if(Z===null)return null;return typeof Q==="function"?Q:null}function T1(Z={}){let Q=Z.frameDeadlineMs??100,J=!1,Y=null,X=null,G=null,j=null,B=null;function V(){if(J=!1,X!==null)j?.(X),X=null;if(G!==null)B?.(G),G=null;j=null,B=null}function K(z){if(!J)return;if(z==="frame")X=null;if(z==="timer")G=null;let H=Y;Y=null,V(),H?.()}function U(z){if(Y=z,J)return;J=!0;let H=globalThis,O=OZ(Z.requestFrame,H.requestAnimationFrame);j=OZ(Z.cancelFrame,H.cancelAnimationFrame);let N=OZ(Z.setTimer,H.setTimeout);if(B=OZ(Z.clearTimer,H.clearTimeout),O){let P=O(()=>K("frame"));if(!J)return;if(X=P,N){let M=N(()=>K("timer"),Q);if(J)G=M}return}let D=OZ(Z.queueMicrotaskFn,H.queueMicrotask);if(D){D(()=>K("microtask"));return}if(N){let P=N(()=>K("timer"),0);if(J)G=P;return}K("microtask")}function $(){if(!J)return;Y=null,V()}return{schedule:U,cancel:$,isPending:()=>J}}function x1(Z="runtime"){return`${Z}-${Math.random().toString(16).slice(2)}-${Date.now()}`}function k1(){return{lastSessionEventSignatureByItemId:new Map,lastMetadataSignatureByItemId:new Map}}function f1(Z){Z.lastSessionEventSignatureByItemId.clear(),Z.lastMetadataSignatureByItemId.clear()}function I1(Z){let{state:Q,itemId:J,payload:Y}=Z;if(e2(Y)){let j=ZQ(Y);if(Q.lastMetadataSignatureByItemId.get(J)===j)return!1;Q.lastMetadataSignatureByItemId.set(J,j)}let X=t2(Y);if(Q.lastSessionEventSignatureByItemId.get(J)===X)return!1;return Q.lastSessionEventSignatureByItemId.set(J,X),!0}function t2(Z){let Q={...Z};delete Q.timestamp,delete Q.sourceRuntimeId;try{return JSON.stringify(Q)}catch{return String(Q.itemId||"")}}function e2(Z){return Z.intent==="metadata-only"}function ZQ(Z){try{return JSON.stringify({itemId:Z.itemId,canonicalItemId:Z.canonicalItemId,intent:Z.intent,complete:Z.complete??null,component:Z.component??null})}catch{return String(Z.itemId||"")}}var QQ=(Z,Q)=>{if(customElements.get(Z))return;try{customElements.define(Z,Q)}catch(J){if(!(J instanceof DOMException&&J.name==="NotSupportedError"||J&&typeof J==="object"&&J.name==="NotSupportedError")||!customElements.get(Z))throw J}},zQ=k7('<div class="pie-assessment-toolkit-error svelte-15pthty" role="alert" aria-live="assertive"><div class="pie-assessment-toolkit-error-title svelte-15pthty"> </div> <div class="pie-assessment-toolkit-error-message svelte-15pthty"> </div> <pre class="pie-assessment-toolkit-error-details svelte-15pthty"> </pre></div>'),HQ=k7('<div class="pie-assessment-toolkit-anchor svelte-15pthty" aria-hidden="true"></div> <!>',1),AQ={hash:"svelte-15pthty",code:`.pie-assessment-toolkit-anchor.svelte-15pthty {display:none;}.pie-assessment-toolkit-error.svelte-15pthty {margin:0.75rem;padding:0.75rem 1rem;border-radius:0.5rem;border:1px solid
|
|
224
|
-
color-mix(in srgb, var(--pie-incorrect-icon, #dc2626) 40%, transparent);background:color-mix(in srgb, var(--pie-incorrect-icon, #dc2626) 12%, transparent);color:var(--pie-incorrect, #7f1d1d);font-size:0.9rem;}.pie-assessment-toolkit-error-title.svelte-15pthty {font-weight:600;margin-bottom:0.25rem;}.pie-assessment-toolkit-error-message.svelte-15pthty {margin-bottom:0.5rem;}.pie-assessment-toolkit-error-details.svelte-15pthty {margin:0;white-space:pre-wrap;word-break:break-word;}`};function B4(Z,Q){u1(Q,!0),n1(Z,AQ);let J=BQ("pie-assessment-toolkit",()=>WQ()),Y=x1("toolkit"),X=new S7,G=new UZ,j={mode:"gather",role:"student"},B={iife:"pie-item-player",esm:"pie-item-player",preloaded:"pie-item-player",custom:""},V="Unable to initialize assessment toolkit.",K=f(Q,"assessmentId",7,""),U=f(Q,"section",7,null),$=f(Q,"sectionId",7,""),z=f(Q,"attemptId",7,""),H=f(Q,"env",23,()=>({})),O=f(Q,"ndsIcons",7,!1),N=f(Q,"locale",7,""),D=f(Q,"i18n",7,null),P=f(Q,"contentLanguage",7,""),M=f(Q,"lazyInit",7,!1),C=f(Q,"toolConfigStrictness",7,"error"),E=f(Q,"tools",23,()=>({})),v=f(Q,"toolContextResolvers",7,null),S=f(Q,"enabledTools",7,""),p=f(Q,"toolRegistry",7,null),e=f(Q,"accessibility",23,()=>({})),r=f(Q,"player",7,null),q0=f(Q,"playerType",7,""),Z0=f(Q,"coordinator",7,null),M0=f(Q,"createSectionController",7,null),O0=f(Q,"onFrameworkError",7,null),LZ=f(Q,"errorRenderer",7,null),NZ=f(Q,"assessment",7,null),U0=f(Q,"isolation",7,"inherit"),L0=f(Q,"session",7,null),XZ=n(null),g=n(null),Y0=n(null),f7=null,I7=null,GZ=!1,g0=null,c0=null,d0=null,i0=null,PZ=n(0),V5=n(null),X0=n(null),K5=n(V),q5=n(g1([])),v7="",U5="",jZ=null,BZ=null,wZ=null,h7=null,$5=null,m7=null,RZ=null,u7=!1,p7=null,g7=!1,c7=n(""),F5=null,CZ=T1(),N0=[],bZ=new Map,z5=new WeakMap,EZ=new Map,d7=k1(),WZ=n(!1);function W4(){if(!F(XZ))return null;let W=F(XZ).getRootNode();if(W&&"host"in W)return W.host;return F(XZ).parentElement}let x=d(()=>W4());function P0(W,q){if(!F(x)){N0=[...N0,{name:W,detail:q}];return}x7(F(x),W,q)}y(()=>{if(!F(x))return;if(N0.length===0)return;let W=N0;N0=[],queueMicrotask(()=>{let q=F(x);if(!q){N0=[...W,...N0];return}for(let _ of W)x7(q,_.name,_.detail)})});function i7(W){return W.details.length>0?W.details:[W.message]}function V4(W){if(!LZ())return{title:V,details:i7(W)};try{let q=LZ()(W)||{};return{title:typeof q.title==="string"&&q.title.trim().length>0?q.title:V,details:Array.isArray(q.details)&&q.details.length>0?q.details.map((_)=>String(_)):i7(W)}}catch(q){let _=q instanceof Error&&q.message.trim().length>0?q.message:String(q||"Unknown renderer error");return{title:V,details:[...W.details,`Error renderer failed: ${_}`]}}}function w0(W){let q=v5({kind:W.kind,source:W.source,error:W.error,recoverable:W.recoverable,scope:W.cohort?"cohort":"runtime",cohort:W.cohort});return G.reportFrameworkError(q),q}function l7(W){return(W||[]).map((q)=>q?.message).filter((q)=>typeof q==="string")}function K4(W,q){if(W?.type==="timed-media-policy-degraded"){G.reportFrameworkError(fZ({kind:"timed-media",severity:"warning",source:"pie-assessment-toolkit",message:"A timed-media playback policy degraded to advisory: the media time source does not report the capability it needs.",details:l7(W.degradations),recoverable:!0,scope:"cohort",cohort:q}));return}if(W?.type!=="timed-media-invalid")return;G.reportFrameworkError(fZ({kind:"timed-media",severity:"error",source:"pie-assessment-toolkit",message:'This section declares sectionType: "timed-media" but its timedMedia data is not deliverable; the section renders without cue behavior.',details:l7(W.errors),recoverable:!1,scope:"cohort",cohort:q}))}function q4(W){if(W?.type!=="timed-media-audio-started")return;if(!F(b))return;M1(F(b).ttsService)}function U4(W){return W==="coordinator-init"||W==="runtime-init"||W==="tool-config"}function VZ(W){return`${W.kind}|${W.source}|${W.message}`}function s7(W){if(!O0())return;try{O0()(W),v7=VZ(W)}catch(q){console.error(`[pie-framework:${W.kind}:${W.source}] framework error hook failed`,q)}}let n7=new WeakSet,r7=new WeakMap;function $4(W){if(typeof W!=="object"||W===null)return null;return r7.get(W)??null}function a7(W){let q=V4(W);m(X0,W,!0),m(K5,q.title,!0),m(q5,q.details,!0)}function o7(){m(X0,null),m(K5,V),m(q5,[],!0)}y(()=>{let W=G.subscribeFrameworkErrors((q)=>{if(console.error(b8(q),q.cause),typeof q.cause==="object"&&q.cause!==null)r7.set(q.cause,q);if(U4(q.kind)&&!n7.has(q))a7(q);P0("framework-error",q),s7(q)});return()=>{W()}}),y(()=>{let W=Z0();if(!W||F(b)!==W)return;if(typeof W.subscribeFrameworkErrors!=="function")return;return I(()=>W.subscribeFrameworkErrors((q)=>{n7.add(q),G.reportFrameworkError(q)}))}),y(()=>{let W=F(b),q=p();if(!W||F(TZ))return;if(typeof W.adoptToolRegistry!=="function")return;I(()=>{let _=W===F(g);if(_&&!q)return;if(W.adoptToolRegistry(q)&&_&&jZ)jZ={...jZ,toolRegistry:q}})}),y(()=>{if(!F(X0))return;if(v7===VZ(F(X0)))return;s7(F(X0))});function F4(W){let q=5381;for(let _=0;_<W.length;_+=1)q=(q<<5)+q^W.charCodeAt(_);return(q>>>0).toString(36)}function a(W){return W&&typeof W==="object"?W:{}}function z4(W){let q=a(W.section),_=typeof q.identifier==="string"?q.identifier:"",w=typeof W.sectionId==="string"?W.sectionId:"";return _||w}function H4(W){return typeof W.currentItemIndex==="number"?W.currentItemIndex:-1}function A4(W){return(Array.isArray(W.renderables)?W.renderables:[]).map((_,w)=>{let L=a(_),A=a(L.entity),l=typeof A.id==="string"&&A.id||`renderable-${w}`,xZ=a(A.config),N5=typeof A.version==="string"&&A.version||(typeof A.version==="number"?String(A.version):"")||(typeof xZ.version==="string"?xZ.version:"");return{id:l,version:N5}})}function D4(W){let q=a(W.itemSessionsByItemId);return Object.keys(q).sort((_,w)=>_.localeCompare(w)).map((_)=>{let w=a(q[_]),L=typeof w.id==="string"?w.id:"",A=Array.isArray(w.data)?w.data:[],l="";try{l=F4(JSON.stringify(A))}catch{l=String(A.length)}return{itemId:_,sessionId:L,payloadSignature:l}})}function _4(W){let q=a(a(W.formative).states);return Object.entries(q).map(([_,w])=>{let L=a(w),A=a(L.lastOutcome).correctness??"";return`${_}:${L.tryCount??0}:${L.revealed===!0?1:0}:${String(A)}:${String(L.revealOverride??"")}`}).sort().join("|")}function M4(W){let q=W.timedMedia;return FQ(q)}function O4(W){let q=a(W),_=A4(q).map((L)=>`${L.id}:${L.version}`).join("|"),w=D4(q).map((L)=>`${L.itemId}:${L.sessionId}:${L.payloadSignature}`).join("|");return{sectionId:z4(q),currentItemIndex:H4(q),renderableSignature:_,itemSessionSignature:w,formativeSignature:_4(q),timedMediaSignature:M4(q)}}function L4(W){let q=O4(W);return`${q.sectionId}|${q.currentItemIndex}|${q.renderableSignature}|${q.itemSessionSignature}|${q.formativeSignature}|${q.timedMediaSignature}`}function t7(W){return W==="iife"||W==="esm"||W==="preloaded"||W==="custom"}function N4(W,q){let _=W?.type,w=t7(_)?_:t7(q)?q:W?.tagName?"custom":"iife",L=W?.tagName?.trim();if(w==="custom"&&!L)return{type:"iife",tagName:B.iife,version:void 0,source:void 0,isDefault:!0};return{type:w,tagName:L||B[w],version:W?.version,source:W?.source,loaderConfig:W?.loaderConfig,loaderOptions:W?.loaderOptions,isDefault:!W&&!q}}function e7(W){let q=W||{},_=typeof q.mode==="string"&&q.mode.trim()?q.mode.trim():j.mode,w=typeof q.role==="string"&&q.role.trim()?q.role.trim():j.role;return{mode:_,role:w}}function P4(W){let q=e7(W);if(q.mode==="author")return"author";if(q.role==="instructor")return"scorer";return"candidate"}function Z8(W,q){return W.sectionId===q.sectionId&&W.attemptId===q.attemptId}function Q8(){if(!L0()||L0()===h7)return;h7=L0(),wZ={value:L0(),cohort:{sectionId:F(Q0),attemptId:z()||void 0}}}function J8(W,q){Q8();let _=wZ;if(!_)return null;if(!Z8(_.cohort,W)){if(q)wZ=null;return null}return wZ=null,_.value}function Y8(){let W=$5,q=F(b);if(!W||!q)return;let _=J8(W,!1);if(!_)return;let w=q.getSectionController(W);if(!w)return;let L=Q5(w.getSession?.()??null,_);if(!L)return;Promise.resolve().then(()=>{if(!w.applySession)throw Error("Section controller cannot apply the assigned session: it has no applySession.");return w.applySession(L,{mode:"replace"})}).catch((A)=>{w0({kind:"unknown",source:"pie-assessment-toolkit",error:A,recoverable:!0})})}async function w4(){if(M0())return M0()();throw Error("pie-assessment-toolkit requires createSectionController when no coordinator hook provides one")}function H5(){let W=E()||{},q=e1(S());if(q.length===0)return W;let _=W.placement||{},w=Array.isArray(_.section)?_.section:null;if(w&&w.length>0)return W;return{...W,placement:{..._,section:q}}}function R4(){return z8(H5(),{strictness:C(),source:"pie-assessment-toolkit.bootstrap",toolRegistry:p()}).config}function C4(){let W="",q="";try{W=JSON.stringify(H5())}catch{W="[unserializable-tools]"}try{q=JSON.stringify(Object.entries(v()??{}).map(([_,w])=>[_,typeof w]))}catch{q="[unserializable-resolvers]"}return[K()||"",String(C()||"error"),W,q].join("|")}function b4(W){let q=W?.pnpEnforcement;return q==="on"||q==="off"?q:null}function E4(W){let q=K()||U()?.identifier||`assessment-${Math.random().toString(16).slice(2)}`;return new b7({assessmentId:q,lazyInit:M(),eagerInit:!1,toolConfigStrictness:C(),deferToolConfigValidation:!0,assessmentOptional:!0,tools:W,toolRegistry:p(),toolContextResolvers:v(),accessibility:e(),frameworkErrorBus:G})}function X8(W){try{return JSON.stringify(W??null)}catch{return"[unserializable]"}}function G8(){return{signatures:{assessmentId:K()||"",toolConfigStrictness:String(C()||"error"),lazyInit:String(M()),tools:X8({...H5(),pnpEnforcement:void 0}),accessibility:X8(e())},toolRegistry:p()}}function S4(){let W=jZ;if(!W)return[];let q=G8(),_=Object.keys(q.signatures).filter((w)=>q.signatures[w]!==W.signatures[w]);if(W.toolRegistry&&q.toolRegistry!==W.toolRegistry)_.push("toolRegistry");return _}function y4(W,q){if(u7)return;u7=!0,console.warn(`[pie-assessment-toolkit] ${W.join(", ")} changed after ${q} with the coordinator this toolkit built, and that coordinator keeps the values it was built with. Set these inputs no later than the section or the first item scope, pass a coordinator of your own, or update this one from runtime-ready with updateToolConfig(...) or updateToolsPlacement(...). Reported once per toolkit.`)}function T4(W){if(g7)return;g7=!0,console.warn(`[pie-assessment-toolkit] The toolkit above this one (runtime "${W}") had no coordinator when this one connected, so this one built its own and keeps it: the two share no tool state, policy or read-aloud. Give the outer toolkit its coordinator before the inner one connects, or set isolation="force" on the inner one to keep them apart on purpose. Reported once per toolkit.`)}function SZ(){let W=F(g);if(!W)return Promise.resolve();return m(g,null),W.dispose()}function yZ(W){w0({kind:"runtime-dispose",source:"pie-assessment-toolkit",error:W,recoverable:!0})}let TZ=d(()=>!Z0()&&U0()!=="force"&&F(Y0)?.coordinator!=null),b=d(()=>{if(F(TZ))return F(Y0)?.coordinator;return Z0()||F(g)}),A5=d(()=>U()!=null);y(()=>{F(x),Z0(),U0(),F(Y0),v(),F(A5),F(WZ),E(),S(),K(),C(),M(),e(),p(),I(()=>{if(!F(x))return;if(Z0()){if(F(g))SZ().catch(yZ);g0=null;return}if(U0()!=="force"&&F(Y0)?.coordinator){if(F(g))SZ().catch(yZ);g0=null;return}if(F(g)){let W=S4();if(W.length>0&&BZ)y4(W,BZ);else if(W.length>0&&(U()||F(WZ)))SZ().catch(yZ)}if(F(g)&&g0!==v()){try{F(g).setToolContextResolvers(v()),g0=v()}catch(W){w0({kind:"coordinator-init",source:"pie-assessment-toolkit",error:W})}return}if(!F(g)){if(U0()!=="force"&&!GZ){let q=v1(F(x),W5);if(q?.coordinator&&q.runtimeId!==Y){m(Y0,q,!0),g0=null;return}}let W=C4();if(U5===W)return;try{let q=R4();m(g,E4(q),!0),GZ=U0()!=="force",jZ=G8(),BZ=null,g0=v(),U5="",o7()}catch(q){m(g,null),U5=W,w0({kind:"coordinator-init",source:"pie-assessment-toolkit",error:q})}}})}),y(()=>{if(!F(WZ)||!F(b))return;let W=F(b);I(()=>{if(W===F(g))BZ??="an item registered"})});let j8=KQ(),R0=d(()=>D()??j8),KZ=n(0);y(()=>{return F(R0).subscribe?.(()=>{m(KZ,F(KZ)+1)})}),y(()=>{let W=typeof N()==="string"?N().trim():"",q=F(R0);if(!W&&q!==j8)return;I(()=>{Promise.resolve(q.setLocale(W||qQ)).catch((_)=>{w0({kind:"i18n-locale-load",source:"pie-assessment-toolkit",error:_ instanceof Error?_:Error(String(_)),recoverable:!0})})})});let x4=d(()=>{return F(KZ),{locale:F(R0).getLocale(),direction:F(R0).getDirection?.()??"ltr"}});y(()=>{F(KZ);let W=F(x);if(!W)return;$Q(W,F(R0))});let C0=d(()=>K()||F(b)?.assessmentId||""),Q0=d(()=>b1({sectionId:$(),section:U(),assessmentId:K()})),D5=d(()=>e7(H())),k4=d(()=>P4(F(D5))),l0=d(()=>N4(r(),q0())),qZ=d(()=>GQ({player:F(l0),component:"pie-assessment-toolkit"})),f4=d(()=>{if(!F(b))return null;return{toolkitCoordinator:F(b),toolCoordinator:F(b).toolCoordinator,ttsService:F(b).ttsService,highlightCoordinator:F(b).highlightCoordinator,catalogResolver:F(b).catalogResolver,elementToolStateStore:F(b).elementToolStateStore,assessmentId:F(C0),sectionId:F(Q0),attemptId:z()||void 0,itemPlayer:F(l0),ndsIcons:O()===!0,locale:(F(KZ),F(R0).getLocale()),i18n:F(R0),contentLanguage:P()?.trim()||void 0,contentLanguageDefault:UQ({contentLanguage:P(),interfaceLocale:N()}),reportSectionError:(W)=>{X.reportSectionError({source:"section-runtime",error:W,timestamp:Date.now()})}}}),I4=d(()=>{if(!F(b)||!F(x))return null;return{runtimeId:Y,coordinator:F(b),sectionBound:F(A5),eventTarget:F(x)}});function B8(W){if(W==null)return;let q=L4(W);if(q===F(c7))return;m(c7,q,!0),m(PZ,F(PZ)+1),m(V5,W,!0),P0("composition-changed",{composition:F(V5),version:F(PZ)})}function _5(W){F5=W??X.getCompositionModel(),CZ.schedule(()=>{B8(F5)})}function v4(){if(!CZ.isPending())return;CZ.cancel(),B8(F5)}function M5(W){if(!W)return;let q=z5.get(W);if(!q)return;for(let _ of q)_();z5.delete(W)}function W8(){for(let W of bZ.values())M5(W.element)}function V8(W){if(M5(W.element),!F(b))return;z5.set(W.element,L1(F(b),W,{assessmentId:F(C0),sectionId:F(Q0)}))}function h4(){W8();for(let W of bZ.values())V8(W)}function O5(W){if(!W)return;EZ.get(W)?.(),EZ.delete(W)}function m4(W){O5(W),EZ.set(W,w1(W,{getMathSpeech:()=>F(b)?.ttsService.getMathSpeechOptions(),getContentLanguage:()=>P()}))}function u4(W){let _={...W.result?.eventDetail||W.fallbackSession,itemId:W.itemId,canonicalItemId:W.canonicalItemId||W.itemId,sourceRuntimeId:Y};if(!I1({state:d7,itemId:W.itemId,payload:_}))return;P0("session-changed",_)}function p4(W){if(!(W instanceof HTMLElement))return!1;return v1(W,W5)?.runtimeId===Y}function $0(W){return W.detail??null}function g4(W,q){for(let _ of q)W.addEventListener(_.name,_.handler);return()=>{for(let _ of q)W.removeEventListener(_.name,_.handler)}}y(()=>{let W=F(x),q=U0();return I(()=>{if(!W)return;if(q==="force")return m(Y0,null),()=>{GZ=!1};let _=t1(W,(w)=>{if(w.runtimeId===Y)return;if(GZ){T4(w.runtimeId);return}m(Y0,w,!0)});return()=>{_(),m(Y0,null),GZ=!1}})}),y(()=>{let W=F(b);if(!W)return;return I(()=>_1({ttsService:W.ttsService,silence:()=>X.requestMediaPauseForCompetingAudio()}))}),y(()=>{let W=F(TZ)?F(Y0)?.runtimeId??null:null,q=W?"inherited":"owned";if(q!==f7)f7=q,P0(q==="inherited"?"runtime-inherited":"runtime-owned",{runtimeId:Y,parentRuntimeId:W})}),y(()=>{let W=F(x);if(!W)return;I(()=>y1(W.ownerDocument))}),y(()=>{let W=F(b);if(!W)return;let q=F(TZ)?"inherited":"owned";I(()=>{if(W===I7)return;I7=W,P0("runtime-ready",{runtimeId:Y,coordinator:W,ownership:q})})}),y(()=>{let W=F(Q0),q=z()||"";f1(d7)}),y(()=>{if(!F(x))return;F(x).setAttribute("data-item-player-type",F(l0).type),F(x).setAttribute("data-item-player-tag",F(l0).tagName),F(x).setAttribute("data-env-mode",F(D5).mode),F(x).setAttribute("data-env-role",F(D5).role)}),y(()=>{return F(b),F(C0),F(Q0),h4(),()=>{W8()}}),y(()=>{if(!F(x))return;return XQ({host:F(x),instrumentationProvider:F(qZ),component:"pie-assessment-toolkit",eventMap:jQ,staticAttributes:{instrumentationLayer:"toolkit",assessmentId:F(C0),sectionId:F(Q0),attemptId:z()||void 0}})});let L5=null;y(()=>{NZ(),E();let W=F(b);if(!W)return;if(W!==F(g))return;I(()=>{let q={pnpEnforcement:b4(E()),assessment:NZ()??null},_=L5?.coordinator===W?L5.inputs:null;L5={coordinator:W,inputs:q};for(let w of E1(_,q))if(w==="pnpEnforcement")W.setPnpEnforcement(q.pnpEnforcement);else W.updateAssessment(q.assessment)})}),y(()=>{if(!F(b))return;return F(b).subscribeTelemetry(({eventName:W,payload:q})=>{if(!VQ(F(qZ)))return;if(!F(qZ).isReady())return;let _=new Date().toISOString(),w={...q||{},instrumentationLayer:"toolkit",assessmentId:F(C0),sectionId:F(Q0),attemptId:z()||void 0,component:"pie-assessment-toolkit",sourceEventName:W,timestamp:_};F(qZ).trackEvent(W,w);let L=q&&typeof q.errorType==="string"?q.errorType:void 0;if(!W.endsWith("-error")&&!L)return;let A=q&&typeof q.message==="string"?q.message:`Toolkit telemetry error: ${W}`;F(qZ).trackError(Error(A),{component:"pie-assessment-toolkit",errorType:L||"ToolkitTelemetryError",...w})})}),y(()=>{if(!U()||!F(b))return;let W=!1;if(F(b)===I(()=>F(g)))BZ??="a section initialized";let q={sectionId:F(Q0),attemptId:z()||void 0},_=m7;if(m7=q,_&&!Z8(_,q))I(()=>h1(F(x),{reason:"teardown",logger:J}));$5=null;let w=I(()=>J8(q,!0));return X.initialize({coordinator:F(b),section:U(),sectionId:F(Q0),assessmentId:F(C0),attemptId:z()||void 0,view:F(k4),initialSession:w,createDefaultController:w4,onCompositionChanged:(L)=>{if(W)return;_5(L)},onControllerEvent:(L)=>{if(W)return;q4(L),K4(L,q)}}).then(()=>{if(W)return;$5=q;let L=I(()=>F(X0));if(L&&VZ(L)===RZ)o7();RZ=null,I(()=>Y8()),I(()=>v4()),queueMicrotask(()=>{if(W)return;P0("toolkit-ready",{runtimeId:Y,assessmentId:F(C0),sectionId:F(Q0),itemPlayer:F(l0),coordinator:F(b)}),P0("section-ready",{sectionId:q.sectionId,attemptId:q.attemptId,controller:F(b).getSectionController(q)??null})})}).catch((L)=>{if(W)return;let A=I(()=>$4(L));if(A)I(()=>a7(A)),RZ=VZ(A);else RZ=VZ(w0({kind:"runtime-init",source:"pie-assessment-toolkit",error:L,cohort:q}))}),()=>{W=!0}}),y(()=>{L0(),I(()=>{Q8(),Y8()})}),y(()=>{if(!F(x))return;let W=F(x),q=(L)=>{if(!O1(L,Y,p4))return!1;return L.stopPropagation(),!0},w=g4(W,[{name:Y5,handler:(L)=>{if(!q(L))return;let A=$0(L);if(!A?.element||!A?.itemId)return;let l=X.register(A);if(bZ.set(A.element,A),m(WZ,!0),V8(A),m4(A.element),X.handleContentRegistered(A),l)_5()}},{name:Z4,handler:(L)=>{if(!q(L))return;let A=$0(L);if(!A?.itemId)return;let l=A?.element?X.unregister(A.element):!1;if(M5(A.element),O5(A.element),A.element)bZ.delete(A.element);if(X.handleContentUnregistered(A),l)_5()}},{name:Q4,handler:(L)=>{if(!q(L))return;let A=$0(L);if(!A?.itemId)return;let l=X.updateItemSession(A.itemId,A.session);u4({itemId:A.itemId,canonicalItemId:X.getCanonicalItemId(A.itemId),result:l,fallbackSession:A.session})}},{name:Y4,handler:(L)=>{if(!q(L))return;let A=$0(L);if(!A?.itemId)return;X.recordServedContentIdentity({itemId:A.itemId,canonicalItemId:A.canonicalItemId,identity:A.identity})}},{name:J4,handler:(L)=>{if(!q(L))return;let A=$0(L);if(!A?.itemId)return;X.handleContentLoaded({itemId:A.itemId,canonicalItemId:A.canonicalItemId,contentKind:A.contentKind,detail:A.detail,timestamp:Date.now()})}},{name:X4,handler:(L)=>{if(!q(L))return;let A=$0(L);if(!A?.itemId)return;X.handleItemPlayerError({itemId:A.itemId,canonicalItemId:A.canonicalItemId,contentKind:A.contentKind,error:A.error,timestamp:Date.now()})}},{name:G4,handler:(L)=>{if(!q(L))return;let A=$0(L);if(!A?.itemId)return;if(A.action!=="check"&&A.action!=="retry")return;X.handleFormativeAction({itemId:A.itemId,canonicalItemId:A.canonicalItemId,action:A.action,outcomes:A.outcomes})}},{name:j4,handler:(L)=>{if(!q(L))return;let A=$0(L);if(!A?.renderableId)return;if(A.action!=="attach"&&A.action!=="detach")return;X.handleMediaTimeSource({renderableId:A.renderableId,action:A.action,source:A.source,origin:A.origin})}}]);return()=>{I(()=>h1(W,{reason:"teardown",logger:J})),w();for(let L of[...EZ.keys()])O5(L)}}),y(()=>{if(!F(x))return;return()=>{d0?.disconnect(),d0=null,c0?.disconnect(),c0=null,i0?.disconnect(),i0=null}}),y(()=>{let W=F(x),q=F(I4);if(!W||!q)return;I(()=>{if(d0){d0.setValue(q);return}d0=new y7(W,{context:W5,initialValue:q}),d0.connect()})}),y(()=>{let W=F(x),q=F(f4);if(!W||!q)return;I(()=>{if(c0){c0.setValue(q);return}c0=new y7(W,{context:o1,initialValue:q}),c0.connect()})}),y(()=>{let W=F(x),q=F(x4);if(!W)return;I(()=>{if(i0){i0.setValue(q);return}i0=new y7(W,{context:YQ,initialValue:q}),i0.connect()})});async function c4(){if(!F(b))throw Error("Coordinator not initialized");await F(b).waitUntilReady()}function d4(W){if(!F(b))throw Error("Coordinator not initialized");F(b).setHooks(W)}function i4(W){return X.navigateToItem(W)}function l4(){return X.getCompositionModel()}function s4(){return F(l0)}async function n4(){await X.persist()}async function r4(){await X.hydrate()}y(()=>{let W=F(b);if(!W)return;let q=F(PZ)>0||F(V5)!==null,_=!F(A5)&&F(WZ);if(!q&&!_)return;I(()=>{if(W===p7)return;p7=W,W.waitUntilReady().catch(()=>{})})}),y(()=>{return()=>{CZ.cancel(),X.dispose().catch((W)=>{w0({kind:"runtime-dispose",source:"pie-assessment-toolkit",error:W,recoverable:!0})}).then(()=>SZ()).catch(yZ).finally(()=>{G.dispose()})}});var a4={waitUntilReady:c4,setHooks:d4,navigateToItem:i4,getCompositionModel:l4,getItemPlayerConfig:s4,persist:n4,hydrate:r4,get assessmentId(){return K()},set assessmentId(W){K(W),k()},get section(){return U()},set section(W){U(W),k()},get sectionId(){return $()},set sectionId(W){$(W),k()},get attemptId(){return z()},set attemptId(W){z(W),k()},get env(){return H()},set env(W){H(W),k()},get ndsIcons(){return O()},set ndsIcons(W){O(W),k()},get locale(){return N()},set locale(W){N(W),k()},get i18n(){return D()},set i18n(W){D(W),k()},get contentLanguage(){return P()},set contentLanguage(W){P(W),k()},get lazyInit(){return M()},set lazyInit(W){M(W),k()},get toolConfigStrictness(){return C()},set toolConfigStrictness(W){C(W),k()},get tools(){return E()},set tools(W){E(W),k()},get toolContextResolvers(){return v()},set toolContextResolvers(W){v(W),k()},get enabledTools(){return S()},set enabledTools(W){S(W),k()},get toolRegistry(){return p()},set toolRegistry(W){p(W),k()},get accessibility(){return e()},set accessibility(W){e(W),k()},get player(){return r()},set player(W){r(W),k()},get playerType(){return q0()},set playerType(W){q0(W),k()},get coordinator(){return Z0()},set coordinator(W){Z0(W),k()},get createSectionController(){return M0()},set createSectionController(W){M0(W),k()},get onFrameworkError(){return O0()},set onFrameworkError(W){O0(W),k()},get errorRenderer(){return LZ()},set errorRenderer(W){LZ(W),k()},get assessment(){return NZ()},set assessment(W){NZ(W),k()},get isolation(){return U0()},set isolation(W){U0(W),k()},get session(){return L0()},set session(W){L0(W),k()}},K8=HQ(),q8=T7(K8);r1(q8,(W)=>m(XZ,W),()=>F(XZ));var o4=G5(q8,2);{var t4=(W)=>{var q=zQ(),_=c1(q),w=X5(_,!0),L=G5(_,2),A=X5(L,!0),l=G5(L,2),xZ=X5(l,!0);m1(q),d1((N5)=>{B5(w,F(K5)),B5(A,F(X0).message),B5(xZ,N5)},[()=>F(q5).join(`
|
|
223
|
+
`}return Y}function K1(Z){let{request:Q,tools:J,pnpPolicy:Y,customSources:X,contextId:G}=Z,j=new L7(G);j.addSource("host",{id:Q.scope.scopeId,name:`${Q.level}:${Q.scope.scopeId}`,config:{placement:J.placement,policy:J.policy}});let B=_0(J.placement[Q.level]),V=_0(J.policy.allowed),K=new Set(_0(J.policy.blocked)),U=[];for(let D of B)U.push(D),j.addDecision({precedence:0,rule:"placement-membership",featureId:D,action:"skip",sourceType:"host",reason:`Listed in tools.placement.${Q.level}`});if(U=U.filter((D)=>{if(J.providers?.[D]?.enabled===!1)return j.addDecision({precedence:0,rule:"provider-disabled",featureId:D,action:"block",sourceType:"host",reason:`tools.providers.${D}.enabled === false`,value:!1}),!1;return!0}),V.length>0){let D=new Set(V);U=U.filter((P)=>{if(!D.has(P))return j.addDecision({precedence:0,rule:"host-allowlist",featureId:P,action:"block",sourceType:"host",reason:"Not present in tools.policy.allowed",value:V}),!1;return!0})}U=U.filter((D)=>{if(K.has(D))return j.addDecision({precedence:0,rule:"host-blocked",featureId:D,action:"block",sourceType:"host",reason:"Listed in tools.policy.blocked",value:J.policy.blocked}),!1;return!0});let $=[],z=new Set(U),H=null;if(Y.enforcement==="on"&&Y.source&&(Y.assessment||Y.item)){if(H=Y.source.apply({assessment:Y.assessment,item:Y.item}),H.sources.assessment)j.addSource("assessment",H.sources.assessment);if(H.sources.student)j.addSource("student",H.sources.student);if(H.sources.item)j.addSource("item",H.sources.item);for(let M of H.decisions)j.addDecision({precedence:M.precedence,rule:M.rule,featureId:M.featureId,action:M.action,sourceType:M.sourceType,reason:M.reason,value:M.value});for(let[M,C]of H.blockedOverrides)$.push(P7(M,C,Q.level));for(let[M,C]of H.supportConflicts){if(!z.has(M))continue;$.push(_Z(M,C.support,C.grant??"placement",Q.level))}let{blockedToolIds:D}=H;U=U.filter((M)=>!D.has(M));let P=new Set(Object.values(J.placement).flatMap(_0));for(let[M,C]of H.mandates){if(z.has(M))continue;if(!B.includes(M)&&P.has(M))continue;let E=y2(M,{placedAtAnyLevel:P,allTools:J.placement,allowed:V,blocked:K,providers:J.providers}),v={rule:C,hostRule:E.hostRule,hostValue:E.hostValue};$.push({code:"tool-policy.requiredToolBlocked",level:Q.level,toolId:M,message:E.hostRule==="placement-missing"?`Profile policy mandates "${M}" (${C}), but no level of tools.placement lists it.`:`Profile policy mandates "${M}" (${C}), but host policy removes it via ${E.hostRule}.`,details:v}),j.addDecision({precedence:0,rule:"required-tool-blocked",featureId:M,action:"advisory",sourceType:"host",reason:`Host removed required tool "${M}" via ${E.hostRule}`,value:v})}}for(let D=0;D<X.length;D++){let P=X[D],M=U.slice(),C=P.refine({request:Q,candidates:M}),E=new Set(C.refinedCandidates);for(let S of C.refinedCandidates)if(!M.includes(S))$.push({code:"tool-policy.placementMissing",level:Q.level,toolId:S,message:`Custom source "${P.id}" tried to add tool "${S}" that was not in candidates; ignored.`,details:{customSourceId:P.id}}),E.delete(S);U=M.filter((S)=>E.has(S));let v=new Set;if(C.decisions){for(let S of C.decisions)if(j.addDecision({precedence:S.precedence??100+D,rule:S.rule,featureId:S.featureId,action:S.action,sourceType:S.sourceType,reason:S.reason,value:S.value}),S.action==="block")v.add(S.featureId)}for(let S of M){if(E.has(S))continue;if(v.has(S))continue;j.addDecision({precedence:100+D,rule:"custom-source",featureId:S,action:"block",sourceType:"custom",reason:`Custom policy source "${P.id}" removed tool "${S}" from candidates without emitting a decision; auto-logged for trail completeness.`,value:{customSourceId:P.id}})}}for(let D of U)for(let P of Z.unappliedItems??[]){let M=["restrictedTools","requiredTools"].filter((E)=>P.settings[E]?.includes(D)===!0);if(M.length===0)continue;let C={itemId:P.id,settings:M,toolbarLevel:Q.scope.level};$.push({code:"tool-policy.itemSettingNotApplied",level:Q.level,toolId:D,message:`Item "${P.id}" names "${D}" in ${M.join(" and ")}, but "${D}" is on the ${Q.scope.level}-level toolbar, which item settings do not reach. Place "${D}" at item level to enforce the setting per item.`,details:C})}let O=new Set(U),N=U.map((D)=>{let P=H?.perToolFlags.get(D);return{toolId:D,required:P?.required??!1,alwaysAvailable:P?.alwaysAvailable??!1,activateAtInit:P?.activateAtInit??!1,parameters:oZ(D,Y.assessment,Y.item)}});return j.reconcileFinalStates(O),{visibleTools:N,diagnostics:$,provenance:j.build()}}function y2(Z,Q){if(!Q.placedAtAnyLevel.has(Z))return{hostRule:"placement-missing",hostValue:Q.allTools};if(Q.providers?.[Z]?.enabled===!1)return{hostRule:"provider-disabled",hostValue:!1};if(Q.allowed.length>0&&!Q.allowed.includes(Z))return{hostRule:"host-allowlist",hostValue:Q.allowed};if(Q.blocked.has(Z))return{hostRule:"host-blocked",hostValue:Array.from(Q.blocked)};return{hostRule:"placement-missing",hostValue:Q.allTools}}var N7={"district-block":"settings.districtPolicy.blockedTools","test-admin-override":"settings.testAdministration.toolOverrides","item-restriction":"item settings.restrictedTools","pnp-prohibited":"personalNeedsProfile.prohibitedSupports","support-conflict":"a withholding support in personalNeedsProfile.supports","item-requirement":"item settings.requiredTools","district-requirement":"settings.districtPolicy.requiredTools","pnp-support":"personalNeedsProfile.supports","pnp-activate-at-init":"personalNeedsProfile.activateAtInit"};function P7(Z,Q,J){return{code:"tool-policy.overrideBlocked",...J?{level:J}:{},toolId:Z,message:`settings.testAdministration.toolOverrides grants "${Z}", but ${N7[Q]} withdraws it and outranks a granting override.`,details:{rule:Q}}}function _Z(Z,Q,J,Y){let X=J==="placement"?"tools.placement":J==="attribute"?"The item player's attribute":J==="authored"?"The item's authored content":N7[J];return{code:"tool-policy.supportConflict",...Y?{level:Y}:{},toolId:Z,message:`${X} serves "${Z}", but the student's "${Q}" support withholds it.`,details:{support:Q,servedBy:J}}}function q1(Z,Q){let J=Q.map((Y)=>N7[Y]).join(", ");return{code:"tool-policy.unknownSupportId",toolId:Z,message:`No tool is registered under "${Z}", named in ${J}, so it matches nothing. These lists name tools by tool id.`,details:{origins:[...Q]}}}var T2=(Z)=>`No assessment is bound, so no policy source could grant "${Z}"`;function w7(Z,Q,J,Y){return{featureId:Z,granted:!1,action:"block",rule:Q,precedence:0,sourceType:"host",reason:Q==="host-blocked"?"Listed in tools.policy.blocked":`Not listed in tools.policy.allowed (${J.join(", ")})`,required:!1,assessmentBound:Y.assessmentBound,diagnostics:[]}}function U1(Z,Q,J,Y){let X=Q.decisions[0],G=Array.from(Q.perToolFlags.values())[0],j=X?.action==="enable",B=X?.reason??`Feature "${Z}" not configured`,V=X!==void 0&&X.action!=="skip",K=Q.supportConflicts.get(Z);return{featureId:Z,granted:j,action:X?.action??"skip",rule:V?X.rule:"none",precedence:V?X.precedence:null,sourceType:X?.sourceType??"system",reason:J.assessmentBound||j?B:T2(Z),required:Boolean(G?.required),parameters:Y,...V&&X.rule==="support-conflict"&&K?{withheldBy:K.support}:{},assessmentBound:J.assessmentBound,diagnostics:[...Array.from(Q.blockedOverrides,([U,$])=>P7(U,$)),...Array.from(Q.supportConflicts).flatMap(([U,{support:$,grant:z}])=>z?[_Z(U,$,z)]:[])]}}var u0=(Z)=>Array.isArray(Z)&&Z.length>0;function x2(Z){if(!Z)return!1;let Q=Z.personalNeedsProfile;if(Q&&(u0(Q.supports)||u0(Q.prohibitedSupports)||u0(Q.activateAtInit)))return!0;let J=Z.settings;if(J){let Y=J.districtPolicy;if(Y&&(u0(Y.blockedTools)||u0(Y.requiredTools)))return!0;let X=J.testAdministration?.toolOverrides;if(X&&typeof X==="object"&&Object.keys(X).length>0)return!0}return!1}function k2(Z){if(!Z)return!1;return u0(Z.requiredTools)||u0(Z.restrictedTools)}function $1(Z){if(x2(Z.assessment))return"on";if(k2(Z.itemSettings))return"on";return"off"}class tZ{id="pnp";toolRegistry;supportConflicts;withheldBy=new Map;registrylessIds=new Set;constructor(Z,Q=[]){this.toolRegistry=Z,this.supportConflicts=Q;for(let{support:J,withholds:Y}of Q){this.registrylessIds.add(J);for(let X of Y){this.registrylessIds.add(X);let G=this.withheldBy.get(X)??[];G.push(J),this.withheldBy.set(X,G)}}}apply(Z){let{ctx:Q,result:J}=this.prepare(Z),{pnp:Y,districtPolicy:X,testAdmin:G,itemSettings:j}=Q,B=new Set;Y?.supports?.forEach((V)=>B.add(V)),Y?.prohibitedSupports?.forEach((V)=>B.add(V)),Y?.activateAtInit?.forEach((V)=>B.add(V)),X?.blockedTools?.forEach((V)=>B.add(V)),X?.requiredTools?.forEach((V)=>B.add(V));for(let V of Object.keys(G?.toolOverrides??{}))B.add(V);j?.requiredTools?.forEach((V)=>B.add(V)),j?.restrictedTools?.forEach((V)=>B.add(V));for(let{support:V,withholds:K}of this.supportConflicts)if(this.supportInEffect(V,Q))K.forEach((U)=>B.add(U));for(let V of B)this.resolveSupport(V,Q,J);return J}resolveFeature(Z,Q){let{ctx:J,result:Y}=this.prepare(Q);return this.resolveSupport(Z,J,Y),Y}prepare(Z){let{assessment:Q,item:J}=Z,Y=Q?.personalNeedsProfile,X=Q?.settings,G=J?.settings,j=R7();if(X?.districtPolicy||X?.testAdministration)j.sources.assessment={id:Q?.id||"unknown",name:Q?.name||Q?.id||"Assessment",config:X};if(Y)j.sources.student={id:"student",name:"Student PNP Profile",config:Y};if(J)j.sources.item={id:J.id,name:J.id,config:J.settings};return{ctx:{pnp:Y,districtPolicy:X?.districtPolicy,testAdmin:X?.testAdministration,itemSettings:G},result:j}}supportInEffect(Z,Q){let J=R7();return this.resolveSupport(Z,Q,J,!1),J.decisions[0]?.action==="enable"}resolveSupport(Z,Q,J,Y=!0){if(Q.districtPolicy?.blockedTools?.includes(Z)){J.blockedToolIds.add(Z),J.decisions.push({precedence:1,rule:"district-block",featureId:Z,action:"block",sourceType:"assessment",reason:`District policy blocks "${Z}" for all assessments`,value:Q.districtPolicy.blockedTools});return}let X=Q.testAdmin?.toolOverrides?.[Z];if(X===!1){J.blockedToolIds.add(Z),J.decisions.push({precedence:2,rule:"test-admin-override",featureId:Z,action:"block",sourceType:"assessment",reason:`Test administrator disabled "${Z}" for this session`,value:Q.testAdmin?.toolOverrides});return}if(Q.itemSettings?.restrictedTools?.includes(Z)){if(J.blockedToolIds.add(Z),X===!0)J.blockedOverrides.set(Z,"item-restriction");J.decisions.push({precedence:3,rule:"item-restriction",featureId:Z,action:"block",sourceType:"item",reason:`Item restricts "${Z}" (e.g., mental math question blocks calculator)`,value:Q.itemSettings.restrictedTools});return}if(Q.pnp?.prohibitedSupports?.includes(Z)){if(J.blockedToolIds.add(Z),X===!0)J.blockedOverrides.set(Z,"pnp-prohibited");J.decisions.push({precedence:4,rule:"pnp-prohibited",featureId:Z,action:"block",sourceType:"student",reason:`Student PNP profile prohibits "${Z}"`,value:Q.pnp.prohibitedSupports});return}let G=Y?this.withheldBy.get(Z)?.find((V)=>this.supportInEffect(V,Q)):void 0;if(G){let V=R7();this.resolveSupport(Z,Q,V,!1);let K=V.decisions[0];J.blockedToolIds.add(Z),J.supportConflicts.set(Z,{support:G,...K?.action==="enable"?{grant:K.rule}:{}}),J.decisions.push({precedence:4,rule:"support-conflict",featureId:Z,action:"block",sourceType:"student",reason:`"${Z}" is withheld while the student's "${G}" support is in effect`,value:{support:G}});return}let j=Q.pnp?.activateAtInit?.includes(Z)===!0,B=Q.itemSettings?.requiredTools?.includes(Z)?"item-requirement":Q.districtPolicy?.requiredTools?.includes(Z)?"district-requirement":void 0;if(X===!0){if(B)J.mandates.set(Z,B);J.perToolFlags.set(Z,{required:B!==void 0,alwaysAvailable:!0,activateAtInit:j,rule:"test-admin-override"}),J.decisions.push({precedence:5,rule:"test-admin-override",featureId:Z,action:"enable",sourceType:"assessment",reason:`Test administrator enabled "${Z}" for this session`,value:Q.testAdmin?.toolOverrides});return}if(B==="item-requirement"){J.mandates.set(Z,B),J.perToolFlags.set(Z,{required:!0,alwaysAvailable:!1,activateAtInit:j,rule:"item-requirement"}),J.decisions.push({precedence:6,rule:"item-requirement",featureId:Z,action:"enable",sourceType:"item",reason:`Item requires "${Z}" for this question`,value:Q.itemSettings?.requiredTools});return}if(B==="district-requirement"){J.mandates.set(Z,B),J.perToolFlags.set(Z,{required:!0,alwaysAvailable:!1,activateAtInit:j,rule:"district-requirement"}),J.decisions.push({precedence:7,rule:"district-requirement",featureId:Z,action:"enable",sourceType:"assessment",reason:`District policy requires "${Z}" for all assessments`,value:Q.districtPolicy?.requiredTools});return}if(j){J.perToolFlags.set(Z,{required:!1,alwaysAvailable:!0,activateAtInit:j,rule:"pnp-activate-at-init"}),J.decisions.push({precedence:8,rule:"pnp-activate-at-init",featureId:Z,action:"enable",sourceType:"student",reason:`Student PNP profile turns on "${Z}" at start`,value:Q.pnp?.activateAtInit});return}if(Q.pnp?.supports?.includes(Z)){J.perToolFlags.set(Z,{required:!1,alwaysAvailable:!0,activateAtInit:!1,rule:"pnp-support"}),J.decisions.push({precedence:8,rule:"pnp-support",featureId:Z,action:"enable",sourceType:"student",reason:`Student PNP profile requests "${Z}"`,value:Q.pnp.supports});return}J.decisions.push({precedence:8,rule:"pnp-support",featureId:Z,action:"skip",sourceType:"system",reason:`Feature "${Z}" not configured at any level`,value:{supportId:Z}})}unknownSupportIds(Z,Q){let J=new Map;if(this.toolRegistry.getAllTools().length===0)return J;let Y=Z?.personalNeedsProfile,X=Z?.settings,G=[["district-block",X?.districtPolicy?.blockedTools],["test-admin-override",Object.keys(X?.testAdministration?.toolOverrides??{})],["item-restriction",Q.flatMap((j)=>j.restrictedTools??[])],["pnp-prohibited",Y?.prohibitedSupports],["item-requirement",Q.flatMap((j)=>j.requiredTools??[])],["district-requirement",X?.districtPolicy?.requiredTools],["pnp-activate-at-init",Y?.activateAtInit],["pnp-support",Y?.supports]];for(let[j,B]of G)for(let V of B??[]){if(this.toolRegistry.has(V)||this.registrylessIds.has(V))continue;let K=J.get(V)??[];if(!K.includes(j))K.push(j);J.set(V,K)}return J}}function R7(){return{blockedToolIds:new Set,mandates:new Map,perToolFlags:new Map,decisions:[],blockedOverrides:new Map,supportConflicts:new Map,sources:{}}}var F1=s0({policy:{allowed:[],blocked:[]},placement:{section:[],item:[],passage:[]},providers:{}});class eZ{toolRegistry;unsubscribeRegistry;contextId;assessmentOptional;pnpPolicySource;supportConflicts;customSources;listeners=new Set;tools;assessment;pnpEnforcementOverride;itemSettings=new Map;inputDiagnostics=Object.freeze([]);disposed=!1;constructor(Z){this.toolRegistry=Z.toolRegistry,this.contextId=Z.contextId??"tool-policy",this.assessmentOptional=Z.assessmentOptional===!0,this.supportConflicts=Z.supportConflicts??[],this.pnpPolicySource=new tZ(this.toolRegistry,this.supportConflicts),this.customSources=Z.customSources?[...Z.customSources]:[];let Q=Z.inputs??{};this.tools=Q.tools??F1,this.assessment=Q.assessment??null,this.pnpEnforcementOverride=Q.pnpEnforcement??null,this.refreshInputDiagnostics(),this.unsubscribeRegistry=this.watchRegistry()}decide(Z){this.assertNotDisposed();let Q=Z.scope.scopeId?`${this.contextId}:${Z.level}:${Z.scope.scopeId}`:`${this.contextId}:${Z.level}`,J=Z.level==="item"?this.itemForScope(Z.scope):void 0,Y=Z.level!=="item"||Z.scope.level==="section"||Z.scope.level==="assessment";return K1({request:Z,tools:this.tools,pnpPolicy:{source:this.pnpPolicySource,assessment:this.assessment??void 0,item:J,enforcement:this.enforcementFor(J)},unappliedItems:Y?this.enforcedItems():void 0,customSources:this.customSources,contextId:Q})}grantsFeatureAnywhere(Z,Q={}){let J=(Y)=>!Q.enforced||this.enforcementFor(Y)==="on";if(J()&&this.decideFeature(Z).granted)return!0;for(let Y of this.itemSettings.keys()){let X=this.itemSettingsFor(Y);if(!J(X?{id:Y,settings:X}:void 0))continue;if(this.decideFeature(Z,{level:"item",scopeId:Y}).granted)return!0}return!1}registerItemSettings(Z,Q){this.assertNotDisposed();let J={settings:Q},Y=this.itemSettingsFor(Z),X=this.itemSettings.get(Z)??[];return X.push(J),this.itemSettings.set(Z,X),this.emitIfItemSettingsChanged(Z,Y),()=>{if(this.disposed)return;let G=this.itemSettings.get(Z),j=G?.indexOf(J)??-1;if(!G||j<0)return;let B=this.itemSettingsFor(Z);if(G.splice(j,1),G.length===0)this.itemSettings.delete(Z);this.emitIfItemSettingsChanged(Z,B)}}decideFeature(Z,Q){this.assertNotDisposed();let J=this.hostFeatureGate(Z);if(J)return J;let Y=this.itemForScope(Q);return U1(Z,this.pnpPolicySource.resolveFeature(Z,{assessment:this.assessment??void 0,item:Y}),{assessmentBound:this.assessment!==null},oZ(Z,this.assessment,Y))}hostFeatureGate(Z){let Q={assessmentBound:this.assessment!==null},J=_0(this.tools.policy.blocked);if(J.includes(Z))return w7(Z,"host-blocked",J,Q);let Y=_0(this.tools.policy.allowed);if(Y.length>0&&!Y.includes(Z))return w7(Z,"host-allowlist",Y,Q);return null}getVisibleToolIds(Z,Q){return this.decide({level:Z,scope:{level:Z,scopeId:Q}}).visibleTools.map((J)=>J.toolId)}updateInputs(Z){this.assertNotDisposed();let Q=!1,J=!1;if("tools"in Z){let Y=Z.tools??F1;if(!Object.is(this.tools,Y))this.tools=Y,Q=!0}if("assessment"in Z){let Y=Z.assessment??null,X=!p0(this.assessment,Y);if(this.assessment=Y,X)Q=!0,this.refreshInputDiagnostics()}if("pnpEnforcement"in Z){let Y=Z.pnpEnforcement??null;if(this.pnpEnforcementOverride!==Y)this.pnpEnforcementOverride=Y,J=!0}if(Q||J)this.emit({reason:J&&!Q?"pnp-enforcement":"inputs",inputs:this.snapshotInputs()})}replaceToolRegistry(Z,Q){this.assertNotDisposed(),this.unsubscribeRegistry(),this.toolRegistry=Z,this.pnpPolicySource=new tZ(Z,this.supportConflicts),this.unsubscribeRegistry=this.watchRegistry(),this.tools=Q,this.refreshInputDiagnostics(),this.emit({reason:"inputs",inputs:this.snapshotInputs()})}registerPolicySource(Z){return this.assertNotDisposed(),this.customSources.push(Z),this.emit({reason:"policy-source-added",inputs:this.snapshotInputs()}),()=>{let Q=this.customSources.indexOf(Z);if(Q===-1)return;if(this.customSources.splice(Q,1),this.disposed)return;this.emit({reason:"policy-source-removed",inputs:this.snapshotInputs()})}}onPolicyChange(Z){return this.listeners.add(Z),()=>{this.listeners.delete(Z)}}getInputs(){return this.snapshotInputs()}dispose(){if(this.disposed)return;this.disposed=!0,this.unsubscribeRegistry(),this.emit({reason:"disposed",inputs:this.snapshotInputs()}),this.listeners.clear(),this.itemSettings.clear(),this.customSources.length=0}snapshotInputs(){return Object.freeze({tools:this.tools,assessment:this.assessment,pnpEnforcement:this.enforcementFor(),pnpEnforcementOverride:this.pnpEnforcementOverride,assessmentExpected:!this.assessmentOptional||this.pnpEnforcementOverride==="on",diagnostics:this.inputDiagnostics})}enforcementFor(Z){return this.pnpEnforcementOverride??$1({assessment:this.assessment,itemSettings:Z?.settings})}itemSettingsFor(Z){return this.itemSettings.get(Z)?.at(-1)?.settings}emitIfItemSettingsChanged(Z,Q){if(p0(Q,this.itemSettingsFor(Z)))return;this.refreshInputDiagnostics(),this.emit({reason:"item-settings",inputs:this.snapshotInputs()})}refreshInputDiagnostics(){let Z=[];for(let J of this.itemSettings.keys()){let Y=this.itemSettingsFor(J);if(Y)Z.push(Y)}let Q=Array.from(this.pnpPolicySource.unknownSupportIds(this.assessment,Z),([J,Y])=>q1(J,Y));if(p0(this.inputDiagnostics,Q))return!1;return this.inputDiagnostics=Object.freeze(Q),!0}watchRegistry(){return this.toolRegistry.onRegistryChange(()=>{if(this.disposed)return;if(this.refreshInputDiagnostics())this.emit({reason:"inputs",inputs:this.snapshotInputs()})})}itemForScope(Z){if(Z?.level!=="item")return;let Q=Z.canonicalItemId||Z.itemId||Z.scopeId,J=Q?this.itemSettingsFor(Q):void 0;return J?{id:Q,settings:J}:void 0}enforcedItems(){let Z=[];for(let Q of this.itemSettings.keys()){let J=this.itemSettingsFor(Q);if(!J)continue;let Y={id:Q,settings:J};if(this.enforcementFor(Y)==="on")Z.push(Y)}return Z}emit(Z){for(let Q of Array.from(this.listeners))try{Q(Z)}catch{}}assertNotDisposed(){if(this.disposed)throw Error("ToolPolicyEngine has been disposed.")}}import{hasResponseField as f2,hasResponseValue as z1}from"@pie-players/pie-players-shared/pie";import{isPlainRecord as YZ}from"@pie-players/pie-players-shared/object";function Z5(Z){return YZ(Z)&&YZ(Z.session)?Z.session:Z}function I2(Z,Q){let J=YZ(Z)?Z:{},Y=YZ(Q)?Q:{},X=new Set([...Object.keys(J),...Object.keys(Y)]);for(let G of X)if(!p0(Z5(J[G]),Z5(Y[G])))return!1;return!0}function v2(Z,Q){for(let[J,Y]of Object.entries(Z)){if(Y===void 0)continue;if(J==="itemSessions"){if(!I2(Y,Q.itemSessions))return!1;continue}if(!p0(Y,Q[J]))return!1}return!0}function Q5(Z,Q){if(!Z)return Q;let J=YZ(Q.itemSessions)?{...Q.itemSessions}:{},Y=YZ(Z.itemSessions)?Z.itemSessions:{};for(let[G,j]of Object.entries(Y)){if(!z1(Z5(j)))continue;let B=Z5(J[G]);if(z1(B)||f2(B))continue;J[G]=j}let X={...Q,itemSessions:J};return v2(X,Z)?null:X}var H1=[{support:"screenReader",withholds:["textToSpeech","autoplayAudio"]}];class s extends Error{constructor(){super("ToolkitCoordinator has been disposed.");this.name="ToolkitCoordinatorDisposedError"}}class J5 extends Error{constructor(){super("Section controller acquisition was retired during initialization.");this.name="SectionControllerRetiredError"}}var h2=(Z,Q,J)=>{let Y={...Q,...J},X=W1(Z,Q,J);if(X)Y.mathSpeech=X;return Y},m2={"tool-module-load":"failed to load","tool-request-open":"failed to open on request","tool-request-host-check":"failed its toolbar's host check","tool-visibility":"failed its relevance check","tool-applicability":"failed its applicability check","tool-state-load":"failed to restore its state","tool-state-save":"failed to save its state","tool-playback":"failed during playback"},u2=["item-selected","item-session-data-changed","item-session-meta-changed","item-complete-changed","content-loaded","item-player-error"],p2=["section-navigation-change","section-session-applied","section-loading-complete","section-items-complete-changed","section-error","timed-media-cue-changed","timed-media-policy-degraded","timed-media-invalid"];class b7{assessmentId;config;ttsService;toolCoordinator;highlightCoordinator;elementToolStateStore;catalogResolver;toolProviderRegistry;hooks;lazyInit;tts;stateLoadSettled=!1;stateLoadPromise;coordinatorReadyPromise;coordinatorReadyNotified=!1;providerInitPromises=new Map;degradedTools=new Map;reportedToolFailures=new Set;readyChangeListeners=new Set;eagerInit;toolRegistry;toolRegistrySupplied;toolRegistrySettled;toolRegistryAbsent=!1;toolContextResolvers=new Map;toolContextResolverChangeListeners=new Set;toolRequests=new O7((Z,Q,J)=>this.reportToolFailure(Z,Q,J));sectionControllers=new Map;sectionControllerKeys=new Map;sectionControllerInitEntries=new Map;sectionControllerDisposePromises=new Map;sectionPersistenceStrategies=new Map;sectionControllerLifecycleListeners=new Set;activeSubscriptions=new Map;activeCohortMapKey=null;latestRequestedActiveCohortMapKey=null;telemetryListeners=new Set;frameworkErrorBus;ownsFrameworkErrorBus;ownedToolCoordinator;frameworkErrorHookUnsubscribe=null;disposePromise=null;policyEngine;reportedPolicyDiagnostics=new Map;policyDiagnosticListeners=new Set;reportedUnboundFeaturePolicy=!1;reportedRegistryUnavailable=!1;resolveConfig(Z){let Q=P5(Z.toolConfigStrictness),J=Z.toolRegistry??new C7,Y=Z.deferToolConfigValidation===!0?s0(Z.tools):this.validateToolsConfig(Z.tools,{strictness:Q,source:"ToolkitCoordinator.init",toolRegistry:J}),X={...V1};return{...Z,toolConfigStrictness:Q,toolRegistry:J,tools:{...Y,providers:{...X,...Y.providers}},accessibility:{language:"en-US",...Z.accessibility??{},catalogs:Z.accessibility?.catalogs??[]}}}validateToolsConfig(Z,Q){let{config:J,diagnostics:Y}=w5(Z,Q.toolRegistry),X=this.reportedRegistryUnavailable||this.toolRegistryPending()?Y.filter((G)=>G.code!=="tools.registryUnavailable"):Y;if(R5(X,Q),Q.strictness!=="off"&&X.some((G)=>G.code==="tools.registryUnavailable"))this.reportedRegistryUnavailable=!0;return J}constructor(Z){if(!Z.assessmentId)throw Error("ToolkitCoordinator requires assessmentId in config");this.toolRegistrySupplied=Z.toolRegistry!=null,this.toolRegistrySettled=this.toolRegistrySupplied;let Q=this.resolveConfig(Z);if(this.assessmentId=Q.assessmentId,this.config=Q,this.toolRegistry=Q.toolRegistry??new C7,this.installToolContextResolvers(Q.toolContextResolvers),this.hooks={...Q.hooks},this.lazyInit=Z.lazyInit===!0,this.eagerInit=Z.eagerInit??!this.lazyInit,this.frameworkErrorBus=Z.frameworkErrorBus??new UZ,this.ownsFrameworkErrorBus=!Z.frameworkErrorBus,this.subscribeFrameworkErrorHookAdapters(),this.ownedToolCoordinator=new A1,this.toolCoordinator=this.ownedToolCoordinator,this.highlightCoordinator=new AZ,this.elementToolStateStore=new I5,this.catalogResolver=new k5(Q.accessibility?.catalogs||[],Q.accessibility?.language||"en-US"),this.toolProviderRegistry=new rZ,this._registerToolProviders(),this.ttsService=new z7,this.ttsService.setHighlightCoordinator(this.highlightCoordinator),this.ttsService.setReadinessGate(()=>this.ensureTTSReady()),this.tts=new M7({assertNotDisposed:()=>this.assertNotDisposed(),isDisposalStarted:()=>this.disposePromise!==null,isDisposalError:(J)=>J instanceof s,emitTelemetry:(J,Y)=>this.emitTelemetry(J,Y),hooks:this.hooks,toolProviderRegistry:this.toolProviderRegistry,initializeProvider:(J,Y)=>this.initializeProvider(J,Y),ttsService:this.ttsService,catalogResolver:this.catalogResolver,clearDegradedTool:(J)=>void this.degradedTools.delete(J),reportStartFailure:(J,Y,X)=>this.reportStartFailure(J,Y,X),isToolGranted:(J)=>this.isToolGranted(J),lazyInit:this.lazyInit,isToolRegistryPending:()=>this.toolRegistryPending(),providersConfig:()=>this.config.tools?.providers,getProviderDescriptorTools:()=>this.getProviderDescriptorTools(),registerProviderFromTool:(J,Y)=>this.registerProviderFromTool(J,Y),notifyReadyChange:()=>this.notifyReadyChange()}),this.ttsService.setMathSpeechSource(()=>this.tts.mathSpeechRuntimeOptions()),this.setupStatePersistenceHooks(),this.policyEngine=new eZ({toolRegistry:this.toolRegistry,contextId:`toolkit-coordinator:${this.assessmentId}`,assessmentOptional:this.config.assessmentOptional===!0,supportConflicts:H1,inputs:{tools:this.config.tools,assessment:null,pnpEnforcement:this.resolveConfiguredPnpEnforcement()}}),this.policyEngine.onPolicyChange((J)=>{if(J.reason==="disposed")return;if(J.reason==="inputs"||J.reason==="pnp-enforcement")this.reportedPolicyDiagnostics.clear();this.warnPolicyDiagnostics(J.inputs.diagnostics),this.reportNewlyGrantedFailures()}),this.eagerInit)this.waitUntilReady().catch((J)=>{if(J instanceof s)return;console.error("[ToolkitCoordinator] Failed eager initialization:",J),this.handleError(J,{phase:"coordinator-ready",recoverable:!1})})}assertNotDisposed(){if(this.disposePromise!==null)throw new s}subscribeFrameworkErrorHookAdapters(){this.frameworkErrorHookUnsubscribe=this.frameworkErrorBus.subscribeFrameworkErrors((Z)=>{let Q=this.hooks.onFrameworkError;if(!Q)return;try{Q(Z)}catch(J){console.warn("[ToolkitCoordinator] onFrameworkError hook failed:",J)}})}async emitTelemetry(Z,Q){try{await this.hooks.onTelemetry?.(Z,Q)}catch(Y){console.warn("[ToolkitCoordinator] telemetry hook failed:",Y)}let J=Q?{...Q}:void 0;for(let Y of this.telemetryListeners)try{Y({eventName:Z,payload:J?{...J}:void 0})}catch(X){console.warn("[ToolkitCoordinator] telemetry listener failed:",X)}}emitSectionControllerLifecycle(Z){for(let Q of this.sectionControllerLifecycleListeners)try{Q(Z)}catch(J){console.warn("[ToolkitCoordinator] section controller lifecycle listener failed:",J)}}handleError(Z,Q,J){let Y=C8({error:Z,context:Q,recoverable:Q.recoverable,scope:J?"cohort":"runtime",cohort:J});this.frameworkErrorBus.reportFrameworkError(Y)}isToolGranted(Z){try{return this.policyEngine.grantsFeatureAnywhere(Z,{enforced:this.toolRegistry.getToolActivation(Z)!=="region"})}catch{return!1}}reportStartFailure(Z,Q,J,Y=!1){let X=Array.from(J),G=Y||!X.some((j)=>this.isToolGranted(j));if(G&&!Y)for(let j of X)this.degradedTools.set(j,{error:Z,context:Q});this.handleError(Z,{...Q,recoverable:G})}reportToolFailure(Z,Q,J){if(Q==="tool-module-load")this.toolRequests.notifyTargetsChange();let Y=`${Q}\x00${Z}`;if(this.reportedToolFailures.has(Y))return;this.reportedToolFailures.add(Y);let X=J instanceof Error&&J.message.trim().length>0?J.message:String(J),G=()=>this.reportStartFailure(Error(`Tool "${Z}" ${m2[Q]}: ${X}`,{cause:J}),{phase:Q,details:{toolId:Z}},[Z],Q!=="tool-module-load");if(Q==="tool-module-load")G();else queueMicrotask(G)}reportNewlyGrantedFailures(){for(let[Z,Q]of this.degradedTools){if(!this.isToolGranted(Z))continue;this.degradedTools.delete(Z),this.handleError(Q.error,{...Q.context,recoverable:!1})}}onReadyChange(Z){return this.readyChangeListeners.add(Z),()=>{this.readyChangeListeners.delete(Z)}}notifyReadyChange(){for(let Z of this.readyChangeListeners)try{Z()}catch(Q){console.warn("[ToolkitCoordinator] ready-change listener failed:",Q)}}subscribeFrameworkErrors(Z){return this.frameworkErrorBus.subscribeFrameworkErrors(Z)}reportFrameworkError(Z){this.frameworkErrorBus.reportFrameworkError(Z)}sectionControllerKey(Z){return{assessmentId:this.assessmentId,sectionId:Z.sectionId,attemptId:Z.attemptId}}getSectionControllerMapKey(Z){return`${Z.assessmentId}::${Z.sectionId}::${Z.attemptId||""}`}createDefaultSectionPersistence(){let Z=(()=>{try{if(typeof window>"u")return null;return window.localStorage}catch{return null}})(),Q=(J)=>{let{assessmentId:Y,sectionId:X,attemptId:G}=J.key;if(!G)return null;return`pie:section-controller:v1:${Y}:${X}:${G}`};return{async loadSession(J){let Y=Q(J);if(!Z||!Y)return null;let X=Z.getItem(Y);if(!X)return null;try{return JSON.parse(X)}catch{return null}},async saveSession(J,Y){let X=Q(J);if(!Z||!X)return;Z.setItem(X,JSON.stringify(Y))},async clearSession(J){let Y=Q(J);if(!Z||!Y)return;Z.removeItem(Y)}}}async resolveSectionPersistence(Z){let Q=this.getSectionControllerMapKey(Z.key),J=this.sectionPersistenceStrategies.get(Q);if(J)return J;let Y={createDefaultPersistence:()=>this.createDefaultSectionPersistence()},X=await this.hooks.createSectionSessionPersistence?.(Z,Y)??await Y.createDefaultPersistence();return this.sectionPersistenceStrategies.set(Q,X),X}setupStatePersistenceHooks(){this.elementToolStateStore.setOnStateChange((Z)=>{if(!this.hooks.saveToolState)return;Promise.resolve(this.hooks.saveToolState(Z)).catch((Q)=>{this.handleError(Q,{phase:"state-save",recoverable:!0})})})}async ensureStateLoaded(){if(this.stateLoadSettled)return;if(this.stateLoadPromise)return this.stateLoadPromise;return this.stateLoadPromise=(async()=>{let Z=this.hooks.loadToolState;if(!Z)return;try{let Q=await Z();if(this.assertNotDisposed(),Q&&typeof Q==="object")this.elementToolStateStore.loadState(Q);this.stateLoadSettled=!0,await this.emitTelemetry("pie-toolkit-tool-state-loaded",{hasState:Boolean(Q)})}catch(Q){if(Q instanceof s)throw Q;this.stateLoadSettled=!0,this.handleError(Q,{phase:"state-load",recoverable:!0})}})().finally(()=>{this.stateLoadPromise=void 0,this.notifyReadyChange()}),this.stateLoadPromise}toolRegistryPending(){return!this.toolRegistrySettled&&!this.toolRegistryAbsent}adoptToolRegistry(Z){if(this.disposePromise!==null||this.toolRegistrySettled)return!1;if(!Z&&this.toolRegistryAbsent)return!1;let Q=this.config.toolConfigStrictness??"error",J="ToolkitCoordinator.adoptToolRegistry";if(!Z)return this.toolRegistryAbsent=!0,this.validateToolsConfig(this.config.tools,{strictness:Q,source:J,toolRegistry:this.toolRegistry}),this.tts.reportHeldMissingProvider(),!1;this.toolRegistrySettled=!0,this.toolRegistry=Z,this.config.toolRegistry=Z,this.tts.discardHeldMissingProvider();try{this.config.tools=this.validateToolsConfig(this.config.tools,{strictness:Q==="off"?"off":"warn",source:J,toolRegistry:Z})}catch(X){console.warn("[ToolkitCoordinator] Tool config does not validate against the adopted tool registry:",X)}this.policyEngine.replaceToolRegistry(Z,this.config.tools);let Y=this.tts.isStarted();for(let X of this.getProviderDescriptorTools()){if(Y&&this.tts.ownsTool(X.toolId))continue;this.registerProviderFromTool(X)}if(Y)this.tts.scheduleReconfigure();return!0}_registerToolProviders(){let Z=this.getProviderDescriptorTools();for(let Q of Z)this.registerProviderFromTool(Q)}getProviderDescriptorTools(){return this.toolRegistry.getAllTools().filter((Z)=>!!Z.provider)}async registerProviderFromTool(Z,Q=!1){let J=Z.provider;if(!J)return;let{toolId:Y}=Z,X;try{let G=this.getToolConfig(Y)||void 0;if(G?.enabled===!1){if(Q)this.toolProviderRegistry.unregister(Y);return}if(!Q&&this.toolProviderRegistry.has(Y))return;let j=J.createProvider(G),B=J.getInitConfig?.(G)??G?.provider?.init??{},V=this.addToolTelemetryReporter(Y,B),K=this.createToolTelemetryForwarder(Y),U=J.getAuthFetcher?.(G)??G?.provider?.runtime?.authFetcher;X={provider:j,config:V,lazy:J.lazy??!0,authFetcher:U,onTelemetry:K}}catch(G){this.reportProviderRegisterFailure(G,Y);return}await this.registerProvider(Y,X)}createToolTelemetryForwarder(Z){return async(Q,J)=>{await this.emitTelemetry(Q,{...J||{},toolId:Z})}}addToolTelemetryReporter(Z,Q){let J=Q&&typeof Q==="object"?{...Q}:{},Y=typeof J.onTelemetry==="function"?J.onTelemetry:null,X=this.createToolTelemetryForwarder(Z);return J.onTelemetry=async(G,j)=>{if(Y)await Y(G,j);await X(G,j)},J}async registerProvider(Z,Q){try{this.toolProviderRegistry.register(Z,Q);let J={providerName:Q.provider.providerName};await this.hooks.onProviderRegistered?.(Z,J),await this.emitTelemetry("pie-toolkit-provider-registered",{toolId:Z,providerName:Q.provider.providerName})}catch(J){this.reportProviderRegisterFailure(J,Z)}}reportProviderRegisterFailure(Z,Q){console.warn(`[ToolkitCoordinator] Failed to register the provider of tool "${Q}":`,Z),this.reportStartFailure(Z,{phase:"provider-register",toolId:Q},[Q])}async ensureProviderReady(Z){return this.initializeProvider(Z,!1)}async initializeProvider(Z,Q){this.assertNotDisposed();let J=this.providerInitPromises.get(Z);if(J)return J;let Y=(async()=>{try{let X=await this.toolProviderRegistry.getProvider(Z,!1);if(this.assertNotDisposed(),this.toolProviderRegistry.isInitialized(Z))return X;let G={providerName:X.providerName};return await this.hooks.onProviderInitStart?.(Z,G),this.assertNotDisposed(),await this.toolProviderRegistry.initialize(Z),this.assertNotDisposed(),X=await this.toolProviderRegistry.getProvider(Z,!1),await this.hooks.onProviderReady?.(Z,G),this.assertNotDisposed(),await this.emitTelemetry("pie-toolkit-provider-ready",{toolId:Z}),this.assertNotDisposed(),X}catch(X){if(X instanceof s)throw X;let G=X instanceof Error?X:Error(String(X));throw this.reportStartFailure(G,{phase:"provider-init",toolId:Z},this.toolRegistry.get(Z)?.provider?[Z]:[],Q),G}})().finally(()=>{this.providerInitPromises.delete(Z)});return this.providerInitPromises.set(Z,Y),Y}setHooks(Z){if(Object.assign(this.hooks,Z),this.setupStatePersistenceHooks(),this.disposePromise===null&&Z.onCoordinatorReady&&this.isReady())Promise.resolve(Z.onCoordinatorReady(this)).catch((Q)=>{this.handleError(Q,{phase:"coordinator-ready",recoverable:!1})})}subscribeTelemetry(Z){return this.telemetryListeners.add(Z),()=>{this.telemetryListeners.delete(Z)}}getSectionController(Z){let Q=this.sectionControllerKey(Z);return this.sectionControllers.get(this.getSectionControllerMapKey(Q))}subscribeSectionEvents(Z){if(this.activeCohortMapKey===null&&this.latestRequestedActiveCohortMapKey===null)throw Error("[ToolkitCoordinator] subscribeSectionEvents requires an active section cohort; call getOrCreateSectionController first.");let Q=this.activeSubscriptions.get(Z.listener);if(Q)Q.unsubscribeCurrent?.(),Q.unsubscribeCurrent=null;let J={listener:Z.listener,eventTypes:Z.eventTypes,itemIds:Z.itemIds,unsubscribeCurrent:null};this.activeSubscriptions.set(Z.listener,J);let Y=this.activeCohortMapKey===null?void 0:this.sectionControllers.get(this.activeCohortMapKey);if(Y)this.bindSubscriptionToController(J,Y);let X=!1;return()=>{if(X)return;if(X=!0,J.unsubscribeCurrent?.(),J.unsubscribeCurrent=null,this.activeSubscriptions.get(Z.listener)===J)this.activeSubscriptions.delete(Z.listener)}}bindSubscriptionToController(Z,Q){Z.unsubscribeCurrent?.(),Z.unsubscribeCurrent=null;let J=Q.subscribe;if(typeof J!=="function")return;let Y=this.buildSectionEventPredicate(Z);Z.unsubscribeCurrent=J.call(Q,(j)=>{if(!Y(j))return;this.deliverSectionEventSafely(Z.listener,j)});let X=this.buildContentLoadedReplayEvents(Q);for(let j of X)if(Y(j))this.deliverSectionEventSafely(Z.listener,j);let G=this.buildLoadingCompleteReplayEvent(Q);if(G&&Y(G))this.deliverSectionEventSafely(Z.listener,G)}deliverSectionEventSafely(Z,Q){try{Z(Q)}catch(J){console.warn("[ToolkitCoordinator] section-event listener failed:",J)}}setActiveCohort(Z){if(this.activeCohortMapKey===Z)return;this.activeCohortMapKey=Z;let Q=this.sectionControllers.get(Z);if(!Q)return;for(let J of Array.from(this.activeSubscriptions.values()))this.bindSubscriptionToController(J,Q)}setActiveCohortIfLatestRequest(Z){if(this.latestRequestedActiveCohortMapKey!==Z)return;this.setActiveCohort(Z)}suspendActiveCohortIfSuperseded(Z){if(this.activeCohortMapKey===null)return;if(this.activeCohortMapKey===Z)return;this.activeCohortMapKey=null,this.detachActiveSubscriptions()}clearActiveCohortIfMatches(Z){if(this.activeCohortMapKey!==Z)return;this.activeCohortMapKey=null,this.detachActiveSubscriptions()}detachActiveSubscriptions(){for(let Z of Array.from(this.activeSubscriptions.values()))Z.unsubscribeCurrent?.(),Z.unsubscribeCurrent=null}buildSectionEventPredicate(Z){let Q=Z.eventTypes?new Set(Z.eventTypes):null,J=Z.itemIds?new Set(Z.itemIds):null;return(Y)=>{if(Q){let X=Y?.type;if(!X||!Q.has(X))return!1}if(!J)return!0;return Array.from(this.collectEventItemIds(Y)).some((X)=>J.has(X))}}collectEventItemIds(Z){let Q=new Set;if("itemId"in Z&&typeof Z.itemId==="string")Q.add(Z.itemId);if("canonicalItemId"in Z&&typeof Z.canonicalItemId==="string")Q.add(Z.canonicalItemId);if("currentItemId"in Z&&typeof Z.currentItemId==="string")Q.add(Z.currentItemId);if("previousItemId"in Z&&typeof Z.previousItemId==="string")Q.add(Z.previousItemId);return Q}buildContentLoadedReplayEvents(Z){let Q=Z.getRuntimeState?.(),J=Q?.loadedRenderables;if(!Array.isArray(J)||J.length===0)return[];let Y=typeof Q?.currentItemIndex==="number"&&Number.isFinite(Q.currentItemIndex)?Q.currentItemIndex:0,X=Date.now(),G=[];for(let j of J){if(!j)continue;let B=j.itemId,V=typeof j.canonicalItemId==="string"&&j.canonicalItemId?j.canonicalItemId:B;if(typeof B!=="string"||!B)continue;G.push({type:"content-loaded",contentKind:j.contentKind??"unknown",itemId:B,canonicalItemId:V,currentItemIndex:Y,timestamp:X})}return G}buildLoadingCompleteReplayEvent(Z){let Q=Z.getRuntimeState?.();if(Q?.loadingComplete!==!0)return null;let J=typeof Q.totalRegistered==="number"&&Number.isFinite(Q.totalRegistered)?Math.max(0,Q.totalRegistered):0,Y=typeof Q.totalLoaded==="number"&&Number.isFinite(Q.totalLoaded)?Math.max(0,Q.totalLoaded):J;return{type:"section-loading-complete",totalRegistered:J,totalLoaded:Y,currentItemIndex:Q.currentItemIndex,timestamp:Date.now()}}subscribeItemEvents(Z){return this.subscribeSectionEvents({eventTypes:Z.eventTypes||u2,itemIds:Z.itemIds,listener:Z.listener})}subscribeSectionLifecycleEvents(Z){return this.subscribeSectionEvents({eventTypes:Z.eventTypes||p2,listener:Z.listener})}onSectionControllerLifecycle(Z){return this.sectionControllerLifecycleListeners.add(Z),()=>{this.sectionControllerLifecycleListeners.delete(Z)}}async getOrCreateSectionController(Z){if(this.disposePromise!==null)throw new s;let Q=this.sectionControllerKey(Z),J=this.getSectionControllerMapKey(Q);this.latestRequestedActiveCohortMapKey=J,this.suspendActiveCohortIfSuperseded(J);let Y;try{if(Y=await this.resolveExistingSectionController({mapKey:J,key:Q,input:Z.input,updateExisting:Z.updateExisting}),Y){if(this.disposePromise!==null)throw new s;if(Z.initialSession)await this.assignSessionToPublishedController(Y,Z.initialSession)}}catch(V){throw this.deliverSectionStartError(J,V),V}if(Y)return Y;let X=this.sectionControllerDisposePromises.get(J);if(X)await MZ([X]);if(this.disposePromise!==null)throw new s;let G=this.sectionControllerInitEntries.get(J);if(G){if(!Z.initialSession)return G.promise;let V=await G.promise;return await this.assignSessionToPublishedController(V,Z.initialSession),V}let j={retired:!1,candidateClaimed:!1},B=this.initializeNewSectionController({args:Z,key:Q,mapKey:J,token:j}).catch((V)=>{throw this.handleSectionControllerInitError(V,Z),this.deliverSectionStartError(J,V),V}).finally(()=>{if(this.sectionControllerInitEntries.get(J)?.token===j)this.sectionControllerInitEntries.delete(J)});return this.sectionControllerInitEntries.set(J,{key:Q,token:j,promise:B}),B}async resolveExistingSectionController(Z){let Q=this.sectionControllers.get(Z.mapKey);if(!Q)return;if(this.sectionControllerKeys.set(Z.mapKey,Z.key),Z.updateExisting!==!1)await Q.updateInput?.(Z.input);if(this.sectionControllers.get(Z.mapKey)!==Q)return;return this.setActiveCohortIfLatestRequest(Z.mapKey),Q}createSectionControllerContext(Z){return{key:Z.key,coordinator:this,input:Z.input}}async initializeNewSectionController(Z){let Q=this.createSectionControllerContext({key:Z.key,input:Z.args.input}),J=await this.resolveSectionPersistence(Q);if(this.disposePromise!==null||Z.token.retired){if(this.sectionPersistenceStrategies.get(Z.mapKey)===J)this.sectionPersistenceStrategies.delete(Z.mapKey);throw this.createSectionControllerRetirementError()}let Y={createDefaultController:Z.args.createDefaultController},X=await this.hooks.createSectionController?.(Q,Y)??await Y.createDefaultController(),G={mapKey:Z.mapKey,key:Z.key,controller:X,persistence:J,token:Z.token};try{await this.retireUnpublishedSectionControllerIfNeeded(G),await X.configureSessionPersistence?.({strategy:J,context:Q}),await this.retireUnpublishedSectionControllerIfNeeded(G),await X.initialize?.(Z.args.input),await this.retireUnpublishedSectionControllerIfNeeded(G);let j=Z.args.initialSession;if(j){if(!X.applySession)throw Error("Section controller cannot apply the session it was created with: it has no applySession.");await X.applySession(j,{mode:"replace"})}else await X.hydrate?.();return await this.finalizeSectionControllerReady({...G,context:Q}),X}catch(j){throw await this.cleanupUnpublishedSectionController(G),j}}async assignSessionToPublishedController(Z,Q){if(!Q)return;if(!Z.applySession)throw Error("Section controller cannot apply the assigned session: it has no applySession.");let J=Q5(Z.getSession?.()??null,Q);if(!J)return;await Z.applySession(J,{mode:"replace"})}createSectionControllerRetirementError(){return this.disposePromise!==null?new s:new J5}async retireUnpublishedSectionControllerIfNeeded(Z){if(this.disposePromise===null&&!Z.token.retired)return;throw await this.cleanupUnpublishedSectionController(Z),this.createSectionControllerRetirementError()}async cleanupUnpublishedSectionController(Z){if(Z.token.candidateClaimed)return;Z.token.candidateClaimed=!0;try{await Z.controller.dispose?.()}catch(Q){this.handleError(Q,{phase:"section-controller-dispose",details:{sectionId:Z.key.sectionId,attemptId:Z.key.attemptId},recoverable:!0})}finally{if(this.sectionPersistenceStrategies.get(Z.mapKey)===Z.persistence)this.sectionPersistenceStrategies.delete(Z.mapKey)}}retirePublishedSectionControllerIfNeeded(Z){if(this.disposePromise!==null&&!Z.token.retired)this.disposeSectionController({sectionId:Z.key.sectionId,attemptId:Z.key.attemptId});if(Z.token.retired)throw this.createSectionControllerRetirementError()}async finalizeSectionControllerReady(Z){await this.retireUnpublishedSectionControllerIfNeeded(Z),this.sectionControllers.set(Z.mapKey,Z.controller),this.sectionControllerKeys.set(Z.mapKey,Z.key),Z.token.candidateClaimed=!0,this.setActiveCohortIfLatestRequest(Z.mapKey),this.emitSectionControllerLifecycle({type:"ready",key:Z.key,controller:Z.controller}),await this.hooks.onSectionControllerReady?.(Z.context,Z.controller),this.retirePublishedSectionControllerIfNeeded(Z),await this.emitTelemetry("pie-toolkit-section-controller-ready",{assessmentId:Z.key.assessmentId,sectionId:Z.key.sectionId,attemptId:Z.key.attemptId}),this.retirePublishedSectionControllerIfNeeded(Z)}handleSectionControllerInitError(Z,Q){if(Z instanceof s||Z instanceof J5)return;this.handleError(Z,{phase:"section-controller-init",details:{sectionId:Q.sectionId,attemptId:Q.attemptId},recoverable:!1},{sectionId:Q.sectionId,attemptId:Q.attemptId})}deliverSectionStartError(Z,Q){if(Q instanceof s||Q instanceof J5||this.latestRequestedActiveCohortMapKey!==Z)return;let J={type:"section-error",source:"section-runtime",error:Q,currentItemIndex:0,timestamp:Date.now()};for(let Y of Array.from(this.activeSubscriptions.values()))if(this.buildSectionEventPredicate(Y)(J))this.deliverSectionEventSafely(Y.listener,J)}disposeSectionController(Z){let Q=this.sectionControllerKey(Z),J=this.getSectionControllerMapKey(Q),Y=this.sectionControllerInitEntries.get(J);if(Y)Y.token.retired=!0;let X=this.sectionControllers.get(J);if(!X){let K=this.sectionControllerDisposePromises.get(J);if(K)return K;if(!Y)return Promise.resolve();let U=MZ([Y.promise]).then(()=>{return});return this.trackSectionControllerDisposal(J,U)}let G=this.sectionPersistenceStrategies.get(J);if(this.clearActiveCohortIfMatches(J),this.sectionControllers.get(J)===X)this.sectionControllers.delete(J),this.sectionControllerKeys.delete(J),this.sectionPersistenceStrategies.delete(J),this.emitSectionControllerLifecycle({type:"disposed",key:Q});let j=this.createSectionControllerContext({key:Q,input:void 0}),B=this.disposeSectionControllerEntry({args:Z,key:Q,context:j,controller:X,persistenceStrategy:G}),V=Y?MZ([Y.promise]).then(()=>B):B;return this.trackSectionControllerDisposal(J,V)}trackSectionControllerDisposal(Z,Q){this.sectionControllerDisposePromises.set(Z,Q);let J=()=>{if(this.sectionControllerDisposePromises.get(Z)===Q)this.sectionControllerDisposePromises.delete(Z)};return Q.then(J,J),Q}async disposeSectionControllerEntry(Z){try{await this.runSectionControllerDisposePipeline({key:Z.key,context:Z.context,controller:Z.controller,persistBeforeDispose:Z.args.persistBeforeDispose})}catch(Q){this.handleError(Q,{phase:"section-controller-dispose",details:{sectionId:Z.args.sectionId,attemptId:Z.args.attemptId},recoverable:!0})}finally{await this.finalizeSectionControllerDispose({context:Z.context,persistenceStrategy:Z.persistenceStrategy,clearPersistence:Z.args.clearPersistence})}}async runSectionControllerDisposePipeline(Z){let Q=[];if(Z.persistBeforeDispose!==!1)try{await Z.controller.persist?.()}catch(J){Q.push(J)}try{await Z.controller.dispose?.()}catch(J){Q.push(J)}if(Q.length===1)throw Q[0];if(Q.length>1)throw AggregateError(Q,"Section controller persistence and disposal both failed.");await this.hooks.onSectionControllerDispose?.(Z.context,Z.controller),await this.emitTelemetry("pie-toolkit-section-controller-disposed",{assessmentId:Z.key.assessmentId,sectionId:Z.key.sectionId,attemptId:Z.key.attemptId})}async finalizeSectionControllerDispose(Z){if(Z.clearPersistence)await Z.persistenceStrategy?.clearSession?.(Z.context)}dispose(){if(this.disposePromise)return this.disposePromise;return this.disposePromise=Promise.resolve().then(()=>this.disposeOwnedResources()),this.disposePromise}async disposeOwnedResources(){let Z=[],Q=async(Y)=>{try{await Y()}catch(X){Z.push(X)}};await this.waitForAdmittedInitialization();let J=new Map;for(let[Y,X]of this.sectionControllerInitEntries)J.set(Y,X.key);for(let[Y,X]of this.sectionControllerKeys)J.set(Y,X);for(let Y of J.values())this.disposeSectionController({sectionId:Y.sectionId,attemptId:Y.attemptId});await MZ(Array.from(this.sectionControllerDisposePromises.values())),this.sectionControllers.clear(),this.sectionControllerKeys.clear(),this.sectionControllerInitEntries.clear(),this.sectionPersistenceStrategies.clear();for(let Y of this.activeSubscriptions.values())await Q(()=>Y.unsubscribeCurrent?.()),Y.unsubscribeCurrent=null;if(this.activeSubscriptions.clear(),this.activeCohortMapKey=null,this.latestRequestedActiveCohortMapKey=null,await Q(()=>this.ttsService.dispose()),await Q(()=>this.toolProviderRegistry.destroy()),await Q(()=>this.highlightCoordinator.destroy()),await Q(()=>this.ownedToolCoordinator.destroy()),await Q(()=>this.catalogResolver.destroy()),await Q(()=>this.toolRequests.dispose()),await Q(()=>this.policyEngine.dispose()),this.toolContextResolvers.clear(),this.toolContextResolverChangeListeners.clear(),this.policyDiagnosticListeners.clear(),this.sectionControllerLifecycleListeners.clear(),this.telemetryListeners.clear(),this.frameworkErrorHookUnsubscribe?.(),this.frameworkErrorHookUnsubscribe=null,this.ownsFrameworkErrorBus)this.frameworkErrorBus.dispose();if(Z.length===1)throw Z[0];if(Z.length>1)throw AggregateError(Z,"ToolkitCoordinator cleanup failed for multiple owned resources.")}async waitForAdmittedInitialization(){let Z=new Set;if(this.coordinatorReadyPromise)Z.add(this.coordinatorReadyPromise);this.tts.flushInitPromises(Z);for(let Q of this.providerInitPromises.values())Z.add(Q);await MZ(Z)}async ensureTTSReady(){return this.tts.ensureReady()}async waitUntilReady(){if(this.assertNotDisposed(),this.isReady())return;if(this.coordinatorReadyPromise)return this.coordinatorReadyPromise;return this.coordinatorReadyPromise=(async()=>{if(await this.ensureStateLoaded(),this.assertNotDisposed(),this.tts.requiredForReadiness())await this.tts.startForReadiness();if(this.assertNotDisposed(),!this.coordinatorReadyNotified)this.coordinatorReadyNotified=!0,await this.hooks.onCoordinatorReady?.(this),this.assertNotDisposed(),await this.emitTelemetry("pie-toolkit-coordinator-ready",{assessmentId:this.assessmentId})})().finally(()=>{this.coordinatorReadyPromise=void 0}),this.coordinatorReadyPromise}isReady(){return(this.stateLoadSettled||!this.hooks.loadToolState)&&(this.tts.started||this.tts.failedUngranted||!this.tts.requiredForReadiness())}assertCanonicalToolId(Z){if(typeof Z!=="string"||Z.trim().length===0)throw Error("Tool id must be a non-empty string.");if(this.toolRegistry.getAllToolIds().length===0)return;if(!this.toolRegistry.get(Z))throw Error(`Unknown tool id "${Z}".`)}installToolContextResolvers(Z){if(!Z)return;for(let[Q,J]of Object.entries(Z)){if(J==null)continue;if(this.assertCanonicalToolId(Q),typeof J!=="function")throw Error(`Invalid tool context resolver for "${Q}": expected a function.`);this.toolContextResolvers.set(Q,J)}}setToolContextResolvers(Z){this.toolContextResolvers.clear(),this.installToolContextResolvers(Z??void 0),this.notifyToolContextResolverChange()}notifyToolContextResolverChange(){for(let Z of this.toolContextResolverChangeListeners)try{Z()}catch(Q){console.warn("[ToolkitCoordinator] Tool context resolver listener threw:",Q)}}getToolConfig(Z){return this.assertCanonicalToolId(Z),this.config.tools?.providers?.[Z]||null}updateToolConfig(Z,Q){this.assertCanonicalToolId(Z);let J=this.getToolConfig(Z)||{};if(!this.config.tools)this.config.tools=this.validateToolsConfig(void 0,{strictness:this.config.toolConfigStrictness??"error",source:"ToolkitCoordinator.updateToolConfig",toolRegistry:this.toolRegistry});if(!this.config.tools.providers)this.config.tools.providers={};let Y={...this.config.tools.providers,[Z]:h2(Z,J,Q)},X=this.validateToolsConfig({...this.config.tools,providers:Y},{strictness:this.config.toolConfigStrictness??"error",source:"ToolkitCoordinator.updateToolConfig",toolRegistry:this.toolRegistry});this.config.tools=X,this.policyEngine.updateInputs({tools:X}),this.emitTelemetry("pie-toolkit-tool-config-updated",{toolId:Z}),this._applyToolConfigChange(Z)}updateToolsPlacement(Z){if(!this.config.tools)this.config.tools=this.validateToolsConfig(void 0,{strictness:this.config.toolConfigStrictness??"error",source:"ToolkitCoordinator.updateToolsPlacement",toolRegistry:this.toolRegistry});let Q=this.config.tools?.placement??{section:[],item:[],passage:[]},J={section:[...Z.section??Q.section??[]],item:[...Z.item??Q.item??[]],passage:[...Z.passage??Q.passage??[]]},Y=this.validateToolsConfig({...this.config.tools,placement:J},{strictness:this.config.toolConfigStrictness??"error",source:"ToolkitCoordinator.updateToolsPlacement",toolRegistry:this.toolRegistry});Y.placement=J,this.config.tools=Y,this.policyEngine.updateInputs({tools:Y})}decideToolPolicy(Z){let Q=this.policyEngine.decide(Z);return this.warnPolicyDiagnostics(Q.diagnostics),Q}warnPolicyDiagnostics(Z){for(let Q of Z){let J=Q.code==="tool-policy.itemSettingNotApplied"?Q.details.itemId:"",Y=`${Q.code}\x00${Q.toolId}\x00${J}`;if(this.reportedPolicyDiagnostics.has(Y))continue;this.reportedPolicyDiagnostics.set(Y,Q),console.warn(`[ToolkitCoordinator] ${Q.message}`);for(let X of Array.from(this.policyDiagnosticListeners))this.notifyPolicyDiagnosticListener(X,Q)}}notifyPolicyDiagnosticListener(Z,Q){try{Z(Q)}catch(J){console.error("[ToolkitCoordinator] Policy diagnostic listener failed:",J)}}registerItemSettings(Z,Q){return this.policyEngine.registerItemSettings(Z,Q)}decideFeaturePolicy(Z,Q){let J=this.policyEngine.decideFeature(Z,Q);if(this.warnPolicyDiagnostics(J.diagnostics),!J.assessmentBound&&this.policyEngine.getInputs().assessmentExpected&&!this.reportedUnboundFeaturePolicy)this.reportedUnboundFeaturePolicy=!0,console.warn(`[ToolkitCoordinator] Feature policy was asked about "${Z}" with no assessment bound, so profile, district and test-administration policy have nothing to read and only an item's requiredTools can grant. Pass the assessment to the toolkit's assessment property, or call updateAssessment(...), before relying on any accommodation. Reported once per coordinator.`);return J}reportFeatureDecisionApplied(Z,Q){if(Z.granted||Z.rule!=="support-conflict"||Z.overrode!=="attribute"&&Z.overrode!=="authored")return;let J=this.policyEngine.decideFeature(Z.featureId,Q);if(J.rule!=="support-conflict"||!J.withheldBy)return;this.warnPolicyDiagnostics([_Z(Z.featureId,J.withheldBy,Z.overrode)])}onPolicyChange(Z){return this.policyEngine.onPolicyChange(Z)}onPolicyDiagnostic(Z){this.policyDiagnosticListeners.add(Z);for(let Q of Array.from(this.reportedPolicyDiagnostics.values()))this.notifyPolicyDiagnosticListener(Z,Q);return()=>{this.policyDiagnosticListeners.delete(Z)}}onCatalogsChange(Z){return this.catalogResolver.onCatalogsChange(Z)}updateAssessment(Z){this.policyEngine.updateInputs({assessment:Z})}setPnpEnforcement(Z){this.policyEngine.updateInputs({pnpEnforcement:Z})}getPolicyInputs(){return this.policyEngine.getInputs()}registerPolicySource(Z){return this.policyEngine.registerPolicySource(Z)}hasToolContextResolver(Z){return this.assertCanonicalToolId(Z),this.toolContextResolvers.has(Z)}resolveToolContext(Z){this.assertCanonicalToolId(Z.toolId);let Q=this.toolContextResolvers.get(Z.toolId);if(!Q)return null;let J;try{J=Q(Z)}catch(X){return console.error(`[ToolkitCoordinator] Tool context resolver for "${Z.toolId}" threw:`,X),{toolId:Z.toolId,visible:!1,params:{},reason:"Tool context resolver threw."}}if(!J)return{toolId:Z.toolId,visible:!0,params:{}};let Y=J.params&&typeof J.params==="object"&&!Array.isArray(J.params)?J.params:{};return{toolId:Z.toolId,visible:J.visible!==!1,params:Y,reason:typeof J.reason==="string"?J.reason:void 0}}onToolContextResolverChange(Z){return this.toolContextResolverChangeListeners.add(Z),()=>{this.toolContextResolverChangeListeners.delete(Z)}}getToolRegistry(){return this.toolRegistry}registerToolRequestTarget(Z){return this.toolRequests.registerTarget(Z)}requestTool(Z){return this.assertCanonicalToolId(Z.toolId),this.toolRequests.request(Z)}canRequestTool(Z,Q,J){try{this.assertCanonicalToolId(Z)}catch{return!1}return this.toolRequests.canRequest(Z,Q,J)}onToolRequestTargetsChange(Z){return this.toolRequests.onTargetsChange(Z)}resolveConfiguredPnpEnforcement(){return this.config.tools?.pnpEnforcement??null}_applyToolConfigChange(Z){if(this.disposePromise!==null)return;if(this.tts.ownsTool(Z)){this.tts.scheduleReconfigure();return}this._registerChangedToolProvider(Z)}_registerChangedToolProvider(Z){let Q=this.getProviderDescriptorTools().find((J)=>J.toolId===Z);if(!Q)return;this.degradedTools.delete(Z),this.registerProviderFromTool(Q,!0)}}var g2=()=>{};function D1(Z){return Z===R.PLAYING||Z===R.LOADING}function _1(Z){let{ttsService:Q,silence:J}=Z;if(typeof Q?.onStateChange!=="function")return g2;let Y=Q.onStateChange((X)=>{if(D1(X))J()});return()=>{try{Y()}catch{}}}function M1(Z){try{if(D1(Z?.getState?.()))Z?.pause?.()}catch{}}import{timedMediaProjectionSignature as FQ}from"@pie-players/pie-players-shared/timed-media";function O1(Z,Q,J){let Y=Z.detail?.runtimeId;if(typeof Y==="string"&&Y!=="")return Y===Q;return J(Z.target)}function L1(Z,Q,J){let Y=[Z.catalogResolver.registerOwner({owner:{kind:Q.kind,itemId:Q.itemId,canonicalItemId:Q.canonicalItemId,assessmentId:J.assessmentId,sectionId:J.sectionId},entity:Q.item})];if(Q.kind==="item"&&Q.settings)Y.push(Z.registerItemSettings(Q.canonicalItemId||Q.itemId,Q.settings));return Y}var c2=["a[href]","button","label","summary",...["button","checkbox","combobox","link","menuitem","menuitemcheckbox","menuitemradio","option","radio","switch","tab","treeitem"].map((Z)=>`[role="${Z}"]`)].join(", "),N1=new Set(["mi","mn","mtext"]),d2=(Z)=>N1.has(Z.localName)||Z.localName==="mrow"&&Z.children.length===1&&N1.has(Z.children[0].localName),i2=(Z)=>Array.from(Z.getElementsByTagName("mfrac")).every((Q)=>Array.from(Q.children).every(d2))?"Fraction_Over":"Fraction_General",l2=(Z)=>!Z||Z.toLowerCase().split("-")[0]==="en",s2=(Z)=>{if(Z.localName!=="label")return Z;let Q=Z;if(Q.control)return Q.control;let J=Q.getAttribute("for"),Y=Q.getRootNode();return(J?Y.getElementById?.(J):null)??Q.querySelector("input, select, textarea, button")},P1=(Z,Q)=>{let J=s2(Z),Y=J?.getAttribute("aria-labelledby")?.split(/\s+/).filter(Boolean);if(!J||!Y?.length)return!1;let X=J.getRootNode(),G=Y.map((j)=>X.getElementById?.(j)??null).filter((j)=>j!==null);return G.length>0&&!G.some((j)=>j.contains(Q))};function w1(Z,Q={}){if(typeof MutationObserver>"u")return()=>{};let J=new Map,Y=!1,X=async(U,$,z)=>{let H=await ZZ([{type:"math",mathml:U,fallbackText:""}],{language:z,loadSre:Q.loadSre,mathSpeech:{...l2(z)?{style:i2($)}:{},engineOptions:Q.getMathSpeech?.()?.engineOptions}});return H.usedMathSpeech?H.speechText:null},G=(U)=>{let $=h5(U,c2);if(!$||P1($,U))return;let z=E0(U,"math"),H=z&&e0(z.outerHTML);if(!z||!H)return;let O=g8(U,{contentLanguage:Q.getContentLanguage?.()}),N=`${O??""}\x00${H}`,D=J.get(N);if(!D)D=X(H,z,O),J.set(N,D);D.then((P)=>{if(Y||!P||!U.isConnected)return;if(P1($,U))return;if(U.getAttribute("aria-label")!==P)U.setAttribute("aria-label",P)})},j=new WeakSet,B=(U)=>{if(j.has(U))return;j.add(U),K.observe(U,{childList:!0,subtree:!0})},V=(U)=>{if(U.nodeType!==1)return;let $=U,z=h5($,"mjx-container");if(z){G(z);return}if($.shadowRoot)B($.shadowRoot);$Z($,(H)=>{if(H.nodeType!==1)return"skip";let O=H;if(O.localName==="mjx-container")return G(O),"skip";if(O.shadowRoot)B(O.shadowRoot);return})},K=new MutationObserver((U)=>{for(let $ of U)for(let z of $.addedNodes)V(z)});return B(Z),V(Z),()=>{Y=!0,K.disconnect()}}import{createPieLogger as r2,isGlobalDebugEnabled as a2}from"@pie-players/pie-players-shared";function n2(Z,Q){if(Z===Q)return 0;let J=Z.compareDocumentPosition(Q);if(J&Node.DOCUMENT_POSITION_PRECEDING)return 1;if(J&Node.DOCUMENT_POSITION_FOLLOWING)return-1;return 0}class E7{shellsByElement=new Map;register(Z){let Q=this.shellsByElement.get(Z.element),J={...Z,sortKey:Date.now()};if(Q&&Q.kind===J.kind&&Q.itemId===J.itemId&&Q.canonicalItemId===J.canonicalItemId)return!1;return this.shellsByElement.set(Z.element,J),!0}unregister(Z){return this.shellsByElement.delete(Z)}getOrderedShells(Z){let Q=Array.from(this.shellsByElement.values()).filter((J)=>!Z||J.kind===Z);return Q.sort((J,Y)=>n2(J.element,Y.element)),Q}getCanonicalIdMap(){let Z={};for(let Q of this.getOrderedShells("item")){if(!Q.itemId)continue;Z[Q.itemId]=Q.canonicalItemId||Q.itemId}return Z}clear(){this.shellsByElement.clear()}}var R1=r2("section-controller-binding",()=>a2());function o2(Z){let Q=Z?.renderables;if(!Array.isArray(Q))return null;let J=new Set;for(let Y of Q){let X=Y?.entity?.id;if(typeof X==="string"&&X)J.add(X)}return J}function C1(Z,Q){return Z.has(Q.itemId)||!!Q.canonicalItemId&&Z.has(Q.canonicalItemId)}class S7{registry=new E7;controller=null;coordinator=null;sectionId="";attemptId;unsubscribeController=null;activeInitToken=0;sectionRenderableIds=null;boundSections=new Map;loadedRenderableKeys=new Set;async initialize(Z){this.activeInitToken+=1;let Q=this.activeInitToken;this.coordinator=Z.coordinator,this.sectionId=Z.sectionId,this.attemptId=Z.attemptId,this.forgetUnregisteredLoads(Z.coordinator.getSectionController({sectionId:Z.sectionId,attemptId:Z.attemptId}));let J;try{J=await Z.coordinator.getOrCreateSectionController({sectionId:Z.sectionId,attemptId:Z.attemptId,input:{section:Z.section,sectionId:Z.sectionId,assessmentId:Z.assessmentId,view:Z.view},updateExisting:!0,initialSession:Z.initialSession,createDefaultController:Z.createDefaultController})}catch(X){if(Q===this.activeInitToken)this.unsubscribeController?.(),this.unsubscribeController=null,this.controller=null;throw X}if(Q!==this.activeInitToken)return;this.unsubscribeController?.(),this.controller=J,this.sectionRenderableIds=o2(J.getCompositionModel?.());let Y=this.getSectionKey(Z.sectionId,Z.attemptId);this.boundSections.delete(Y),this.boundSections.set(Y,{sectionId:Z.sectionId,attemptId:Z.attemptId,renderableIds:this.sectionRenderableIds}),this.replayRegisteredShellsIntoController(J),Z.onCompositionChanged?.(J.getCompositionModel?.()),this.unsubscribeController=J.subscribe?.((X)=>{try{Z.onControllerEvent?.(X)}catch(G){R1.warn("onControllerEvent handler threw",G)}Z.onCompositionChanged?.(J.getCompositionModel?.())})||null}replayRegisteredShellsIntoController(Z){if(!Z.handleContentRegistered)return;let Q=this.registry.getOrderedShells().filter((Y)=>this.isSectionRenderable(Y));if(Q.length===0)return;for(let Y of Q){let X=Y.canonicalItemId||Y.itemId;Z.handleContentRegistered({itemId:Y.itemId,canonicalItemId:X,contentKind:Y.contentKind||Y.kind})}let J=Date.now();for(let Y of Q){let X=Y.canonicalItemId||Y.itemId,G=this.getLoadedKey(X,Y.contentKind);if(this.loadedRenderableKeys.has(G))Z.handleContentLoaded?.({itemId:Y.itemId,canonicalItemId:X,contentKind:Y.contentKind||Y.kind,timestamp:J})}}getLoadedKey(Z,Q){return`${Q??""}:${Z}`}isSectionRenderable(Z){let Q=this.sectionRenderableIds;return!Q||C1(Q,Z)}getSectionKey(Z,Q){return`${Z}\x00${Q??""}`}controllerFor(Z){if(this.isSectionRenderable(Z))return this.controller;let Q=this.getSectionKey(this.sectionId,this.attemptId),J=[...this.boundSections.entries()].reverse();for(let[Y,X]of J){if(Y===Q||!X.renderableIds)continue;if(!C1(X.renderableIds,Z))continue;let G=this.coordinator?.getSectionController({sectionId:X.sectionId,attemptId:X.attemptId});if(G)return G}return null}requireControllerFor(Z,Q){let J=this.controllerFor(Z);if(!J)R1.warn(`Dropped ${Q} for "${Z.itemId}": no section this toolkit bound renders it.`);return J}forgetUnregisteredLoads(Z){if(!Z||Z===this.controller)return;let Q=Z.getRuntimeState?.()?.loadedRenderables??[];if(Q.length===0)return;let J=new Set;for(let Y of this.registry.getOrderedShells())if(J.add(Y.itemId),Y.canonicalItemId)J.add(Y.canonicalItemId);for(let Y of Q){if(J.has(Y.canonicalItemId)||J.has(Y.itemId))continue;Z.handleContentUnregistered?.({itemId:Y.itemId,canonicalItemId:Y.canonicalItemId,contentKind:Y.contentKind})}}register(Z){return this.registry.register(Z)}unregister(Z){return this.registry.unregister(Z)}getCompositionModel(){return this.controller?.getCompositionModel?.()??null}getCanonicalItemId(Z){return this.registry.getCanonicalIdMap()[Z]||this.controller?.getCanonicalItemId?.(Z)||Z}handleContentRegistered(Z){if(!this.isSectionRenderable(Z))return;this.controller?.handleContentRegistered?.({itemId:Z.itemId,canonicalItemId:Z.canonicalItemId||Z.itemId,contentKind:Z.contentKind||Z.kind})}handleContentUnregistered(Z){let Q=Z.canonicalItemId||Z.itemId,J=this.getLoadedKey(Q,Z.contentKind);if(this.registry.getOrderedShells().some((X)=>this.getLoadedKey(X.canonicalItemId||X.itemId,X.contentKind)===J))return;this.loadedRenderableKeys.delete(J),this.controllerFor(Z)?.handleContentUnregistered?.({itemId:Z.itemId,canonicalItemId:Q,contentKind:Z.contentKind||Z.kind})}handleContentLoaded(Z){let Q=Z.canonicalItemId||Z.itemId;if(this.loadedRenderableKeys.add(this.getLoadedKey(Q,Z.contentKind)),!this.isSectionRenderable(Z))return;this.controller?.handleContentLoaded?.(Z)}handleItemPlayerError(Z){this.requireControllerFor(Z,"an item player error")?.handleItemPlayerError?.(Z)}reportSectionError(Z){(Z.itemId?this.requireControllerFor({itemId:Z.itemId,canonicalItemId:Z.canonicalItemId},"a section error"):this.controller)?.reportSectionError?.(Z)}updateItemSession(Z,Q){let J=this.getCanonicalItemId(Z);return this.requireControllerFor({itemId:Z,canonicalItemId:J},"a session update")?.updateItemSession?.(J,Q)??null}recordServedContentIdentity(Z){let Q=Z.canonicalItemId||this.getCanonicalItemId(Z.itemId);this.requireControllerFor({itemId:Z.itemId,canonicalItemId:Q},"a served content identity")?.recordServedContentIdentity?.({itemId:Q,identity:Z.identity})}navigateToItem(Z){return this.controller?.navigateToItem?.(Z)??null}handleTryAction(Z){if(!Z?.itemId)return;let Q=Z.canonicalItemId||this.getCanonicalItemId(Z.itemId),J=this.requireControllerFor({itemId:Z.itemId,canonicalItemId:Q},"a Try action");if(Z.action==="retry"){J?.retryItem?.({itemId:Q});return}J?.recordTry?.({itemId:Q,outcomes:Z.outcomes})}handleMediaTimeSource(Z){if(!Z?.renderableId)return;let Q=this.requireControllerFor({itemId:Z.renderableId,canonicalItemId:this.getCanonicalItemId(Z.renderableId)},"a media time source");if(Z.action==="detach"){Q?.detachMediaTimeSource?.({origin:Z.origin??"host"});return}if(!Z.source)return;Q?.attachMediaTimeSource?.(Z.source,{origin:Z.origin??"host",renderableId:Z.renderableId})}requestMediaPauseForCompetingAudio(){return this.controller?.pauseMediaForCompetingAudio?.()??!0}async persist(){await this.controller?.persist?.()}async hydrate(){await this.controller?.hydrate?.()}async dispose(){this.activeInitToken+=1,this.unsubscribeController?.(),this.unsubscribeController=null;let Z=this.coordinator;if(Z)for(let Q of this.boundSections.values())await Z.disposeSectionController({sectionId:Q.sectionId,attemptId:Q.attemptId});this.registry.clear(),this.loadedRenderableKeys.clear(),this.boundSections.clear(),this.controller=null,this.sectionRenderableIds=null,this.coordinator=null}}function b1(Z){let Q=Z.section?.identifier;return Z.sectionId||(typeof Q==="string"?Q:"")||`section-${Z.assessmentId||"default"}`}function E1(Z,Q){return["pnpEnforcement","assessment"].filter((Y)=>Z?!Object.is(Z[Y],Q[Y]):Q[Y]!==null)}function y1(Z){if(!Z)return;let Q=Symbol.for("pie.assessmentToolkit.unclaimedRegistrationWatch"),J=Z;if(J[Q])return;J[Q]=!0,Z.addEventListener(Y5,(Y)=>{let X=Y.detail,G=typeof X?.itemId==="string"?X.itemId:"";S1(Z,"unclaimedRegistration",`[pie-assessment-toolkit] Item "${G}" registered, but no toolkit claimed the registration, so its accessibility catalogs are not filed and it does not count toward its section's loading. Render its shell or scope inside the <pie-assessment-toolkit> that answered it. Reported once per page.`)})}function OZ(Z,Q){if(typeof Z==="function")return Z;if(Z===null)return null;return typeof Q==="function"?Q:null}function T1(Z={}){let Q=Z.frameDeadlineMs??100,J=!1,Y=null,X=null,G=null,j=null,B=null;function V(){if(J=!1,X!==null)j?.(X),X=null;if(G!==null)B?.(G),G=null;j=null,B=null}function K(z){if(!J)return;if(z==="frame")X=null;if(z==="timer")G=null;let H=Y;Y=null,V(),H?.()}function U(z){if(Y=z,J)return;J=!0;let H=globalThis,O=OZ(Z.requestFrame,H.requestAnimationFrame);j=OZ(Z.cancelFrame,H.cancelAnimationFrame);let N=OZ(Z.setTimer,H.setTimeout);if(B=OZ(Z.clearTimer,H.clearTimeout),O){let P=O(()=>K("frame"));if(!J)return;if(X=P,N){let M=N(()=>K("timer"),Q);if(J)G=M}return}let D=OZ(Z.queueMicrotaskFn,H.queueMicrotask);if(D){D(()=>K("microtask"));return}if(N){let P=N(()=>K("timer"),0);if(J)G=P;return}K("microtask")}function $(){if(!J)return;Y=null,V()}return{schedule:U,cancel:$,isPending:()=>J}}function x1(Z="runtime"){return`${Z}-${Math.random().toString(16).slice(2)}-${Date.now()}`}function k1(){return{lastSessionEventSignatureByItemId:new Map,lastMetadataSignatureByItemId:new Map}}function f1(Z){Z.lastSessionEventSignatureByItemId.clear(),Z.lastMetadataSignatureByItemId.clear()}function I1(Z){let{state:Q,itemId:J,payload:Y}=Z;if(e2(Y)){let j=ZQ(Y);if(Q.lastMetadataSignatureByItemId.get(J)===j)return!1;Q.lastMetadataSignatureByItemId.set(J,j)}let X=t2(Y);if(Q.lastSessionEventSignatureByItemId.get(J)===X)return!1;return Q.lastSessionEventSignatureByItemId.set(J,X),!0}function t2(Z){let Q={...Z};delete Q.timestamp,delete Q.sourceRuntimeId;try{return JSON.stringify(Q)}catch{return String(Q.itemId||"")}}function e2(Z){return Z.intent==="metadata-only"}function ZQ(Z){try{return JSON.stringify({itemId:Z.itemId,canonicalItemId:Z.canonicalItemId,intent:Z.intent,complete:Z.complete??null,component:Z.component??null})}catch{return String(Z.itemId||"")}}var QQ=(Z,Q)=>{if(customElements.get(Z))return;try{customElements.define(Z,Q)}catch(J){if(!(J instanceof DOMException&&J.name==="NotSupportedError"||J&&typeof J==="object"&&J.name==="NotSupportedError")||!customElements.get(Z))throw J}},zQ=k7('<div class="pie-assessment-toolkit-error svelte-15pthty" role="alert" aria-live="assertive"><div class="pie-assessment-toolkit-error-title svelte-15pthty"> </div> <div class="pie-assessment-toolkit-error-message svelte-15pthty"> </div> <pre class="pie-assessment-toolkit-error-details svelte-15pthty"> </pre></div>'),HQ=k7('<div class="pie-assessment-toolkit-anchor svelte-15pthty" aria-hidden="true"></div> <!>',1),AQ={hash:"svelte-15pthty",code:`.pie-assessment-toolkit-anchor.svelte-15pthty {display:none;}.pie-assessment-toolkit-error.svelte-15pthty {margin:0.75rem;padding:0.75rem 1rem;border-radius:0.5rem;border:1px solid
|
|
224
|
+
color-mix(in srgb, var(--pie-incorrect-icon, #dc2626) 40%, transparent);background:color-mix(in srgb, var(--pie-incorrect-icon, #dc2626) 12%, transparent);color:var(--pie-incorrect, #7f1d1d);font-size:0.9rem;}.pie-assessment-toolkit-error-title.svelte-15pthty {font-weight:600;margin-bottom:0.25rem;}.pie-assessment-toolkit-error-message.svelte-15pthty {margin-bottom:0.5rem;}.pie-assessment-toolkit-error-details.svelte-15pthty {margin:0;white-space:pre-wrap;word-break:break-word;}`};function B4(Z,Q){u1(Q,!0),n1(Z,AQ);let J=BQ("pie-assessment-toolkit",()=>WQ()),Y=x1("toolkit"),X=new S7,G=new UZ,j={mode:"gather",role:"student"},B={iife:"pie-item-player",esm:"pie-item-player",preloaded:"pie-item-player",custom:""},V="Unable to initialize assessment toolkit.",K=f(Q,"assessmentId",7,""),U=f(Q,"section",7,null),$=f(Q,"sectionId",7,""),z=f(Q,"attemptId",7,""),H=f(Q,"env",23,()=>({})),O=f(Q,"ndsIcons",7,!1),N=f(Q,"locale",7,""),D=f(Q,"i18n",7,null),P=f(Q,"contentLanguage",7,""),M=f(Q,"lazyInit",7,!1),C=f(Q,"toolConfigStrictness",7,"error"),E=f(Q,"tools",23,()=>({})),v=f(Q,"toolContextResolvers",7,null),S=f(Q,"enabledTools",7,""),p=f(Q,"toolRegistry",7,null),e=f(Q,"accessibility",23,()=>({})),r=f(Q,"player",7,null),q0=f(Q,"playerType",7,""),Z0=f(Q,"coordinator",7,null),M0=f(Q,"createSectionController",7,null),O0=f(Q,"onFrameworkError",7,null),LZ=f(Q,"errorRenderer",7,null),NZ=f(Q,"assessment",7,null),U0=f(Q,"isolation",7,"inherit"),L0=f(Q,"session",7,null),XZ=n(null),g=n(null),Y0=n(null),f7=null,I7=null,GZ=!1,g0=null,c0=null,d0=null,i0=null,PZ=n(0),V5=n(null),X0=n(null),K5=n(V),q5=n(g1([])),v7="",U5="",jZ=null,BZ=null,wZ=null,h7=null,$5=null,m7=null,RZ=null,u7=!1,p7=null,g7=!1,c7=n(""),F5=null,CZ=T1(),N0=[],bZ=new Map,z5=new WeakMap,EZ=new Map,d7=k1(),WZ=n(!1);function W4(){if(!F(XZ))return null;let W=F(XZ).getRootNode();if(W&&"host"in W)return W.host;return F(XZ).parentElement}let x=d(()=>W4());function P0(W,q){if(!F(x)){N0=[...N0,{name:W,detail:q}];return}x7(F(x),W,q)}y(()=>{if(!F(x))return;if(N0.length===0)return;let W=N0;N0=[],queueMicrotask(()=>{let q=F(x);if(!q){N0=[...W,...N0];return}for(let _ of W)x7(q,_.name,_.detail)})});function i7(W){return W.details.length>0?W.details:[W.message]}function V4(W){if(!LZ())return{title:V,details:i7(W)};try{let q=LZ()(W)||{};return{title:typeof q.title==="string"&&q.title.trim().length>0?q.title:V,details:Array.isArray(q.details)&&q.details.length>0?q.details.map((_)=>String(_)):i7(W)}}catch(q){let _=q instanceof Error&&q.message.trim().length>0?q.message:String(q||"Unknown renderer error");return{title:V,details:[...W.details,`Error renderer failed: ${_}`]}}}function w0(W){let q=v5({kind:W.kind,source:W.source,error:W.error,recoverable:W.recoverable,scope:W.cohort?"cohort":"runtime",cohort:W.cohort});return G.reportFrameworkError(q),q}function l7(W){return(W||[]).map((q)=>q?.message).filter((q)=>typeof q==="string")}function K4(W,q){if(W?.type==="timed-media-policy-degraded"){G.reportFrameworkError(fZ({kind:"timed-media",severity:"warning",source:"pie-assessment-toolkit",message:"A timed-media playback policy degraded to advisory: the media time source does not report the capability it needs.",details:l7(W.degradations),recoverable:!0,scope:"cohort",cohort:q}));return}if(W?.type!=="timed-media-invalid")return;G.reportFrameworkError(fZ({kind:"timed-media",severity:"error",source:"pie-assessment-toolkit",message:'This section declares sectionType: "timed-media" but its timedMedia data is not deliverable; the section renders without cue behavior.',details:l7(W.errors),recoverable:!1,scope:"cohort",cohort:q}))}function q4(W){if(W?.type!=="timed-media-audio-started")return;if(!F(b))return;M1(F(b).ttsService)}function U4(W){return W==="coordinator-init"||W==="runtime-init"||W==="tool-config"}function VZ(W){return`${W.kind}|${W.source}|${W.message}`}function s7(W){if(!O0())return;try{O0()(W),v7=VZ(W)}catch(q){console.error(`[pie-framework:${W.kind}:${W.source}] framework error hook failed`,q)}}let n7=new WeakSet,r7=new WeakMap;function $4(W){if(typeof W!=="object"||W===null)return null;return r7.get(W)??null}function a7(W){let q=V4(W);m(X0,W,!0),m(K5,q.title,!0),m(q5,q.details,!0)}function o7(){m(X0,null),m(K5,V),m(q5,[],!0)}y(()=>{let W=G.subscribeFrameworkErrors((q)=>{if(console.error(b8(q),q.cause),typeof q.cause==="object"&&q.cause!==null)r7.set(q.cause,q);if(U4(q.kind)&&!n7.has(q))a7(q);P0("framework-error",q),s7(q)});return()=>{W()}}),y(()=>{let W=Z0();if(!W||F(b)!==W)return;if(typeof W.subscribeFrameworkErrors!=="function")return;return I(()=>W.subscribeFrameworkErrors((q)=>{n7.add(q),G.reportFrameworkError(q)}))}),y(()=>{let W=F(b),q=p();if(!W||F(TZ))return;if(typeof W.adoptToolRegistry!=="function")return;I(()=>{let _=W===F(g);if(_&&!q)return;if(W.adoptToolRegistry(q)&&_&&jZ)jZ={...jZ,toolRegistry:q}})}),y(()=>{if(!F(X0))return;if(v7===VZ(F(X0)))return;s7(F(X0))});function F4(W){let q=5381;for(let _=0;_<W.length;_+=1)q=(q<<5)+q^W.charCodeAt(_);return(q>>>0).toString(36)}function a(W){return W&&typeof W==="object"?W:{}}function z4(W){let q=a(W.section),_=typeof q.identifier==="string"?q.identifier:"",w=typeof W.sectionId==="string"?W.sectionId:"";return _||w}function H4(W){return typeof W.currentItemIndex==="number"?W.currentItemIndex:-1}function A4(W){return(Array.isArray(W.renderables)?W.renderables:[]).map((_,w)=>{let L=a(_),A=a(L.entity),l=typeof A.id==="string"&&A.id||`renderable-${w}`,xZ=a(A.config),N5=typeof A.version==="string"&&A.version||(typeof A.version==="number"?String(A.version):"")||(typeof xZ.version==="string"?xZ.version:"");return{id:l,version:N5}})}function D4(W){let q=a(W.itemSessionsByItemId);return Object.keys(q).sort((_,w)=>_.localeCompare(w)).map((_)=>{let w=a(q[_]),L=typeof w.id==="string"?w.id:"",A=Array.isArray(w.data)?w.data:[],l="";try{l=F4(JSON.stringify(A))}catch{l=String(A.length)}return{itemId:_,sessionId:L,payloadSignature:l}})}function _4(W){let q=a(a(W.tries).states);return Object.entries(q).map(([_,w])=>{let L=a(w),A=a(L.lastOutcome).correctness??"";return`${_}:${L.tryCount??0}:${L.revealed===!0?1:0}:${String(A)}:${String(L.revealOverride??"")}`}).sort().join("|")}function M4(W){let q=W.timedMedia;return FQ(q)}function O4(W){let q=a(W),_=A4(q).map((L)=>`${L.id}:${L.version}`).join("|"),w=D4(q).map((L)=>`${L.itemId}:${L.sessionId}:${L.payloadSignature}`).join("|");return{sectionId:z4(q),currentItemIndex:H4(q),renderableSignature:_,itemSessionSignature:w,trySignature:_4(q),timedMediaSignature:M4(q)}}function L4(W){let q=O4(W);return`${q.sectionId}|${q.currentItemIndex}|${q.renderableSignature}|${q.itemSessionSignature}|${q.trySignature}|${q.timedMediaSignature}`}function t7(W){return W==="iife"||W==="esm"||W==="preloaded"||W==="custom"}function N4(W,q){let _=W?.type,w=t7(_)?_:t7(q)?q:W?.tagName?"custom":"iife",L=W?.tagName?.trim();if(w==="custom"&&!L)return{type:"iife",tagName:B.iife,version:void 0,source:void 0,isDefault:!0};return{type:w,tagName:L||B[w],version:W?.version,source:W?.source,loaderConfig:W?.loaderConfig,loaderOptions:W?.loaderOptions,isDefault:!W&&!q}}function e7(W){let q=W||{},_=typeof q.mode==="string"&&q.mode.trim()?q.mode.trim():j.mode,w=typeof q.role==="string"&&q.role.trim()?q.role.trim():j.role;return{mode:_,role:w}}function P4(W){let q=e7(W);if(q.mode==="author")return"author";if(q.role==="instructor")return"scorer";return"candidate"}function Z8(W,q){return W.sectionId===q.sectionId&&W.attemptId===q.attemptId}function Q8(){if(!L0()||L0()===h7)return;h7=L0(),wZ={value:L0(),cohort:{sectionId:F(Q0),attemptId:z()||void 0}}}function J8(W,q){Q8();let _=wZ;if(!_)return null;if(!Z8(_.cohort,W)){if(q)wZ=null;return null}return wZ=null,_.value}function Y8(){let W=$5,q=F(b);if(!W||!q)return;let _=J8(W,!1);if(!_)return;let w=q.getSectionController(W);if(!w)return;let L=Q5(w.getSession?.()??null,_);if(!L)return;Promise.resolve().then(()=>{if(!w.applySession)throw Error("Section controller cannot apply the assigned session: it has no applySession.");return w.applySession(L,{mode:"replace"})}).catch((A)=>{w0({kind:"unknown",source:"pie-assessment-toolkit",error:A,recoverable:!0})})}async function w4(){if(M0())return M0()();throw Error("pie-assessment-toolkit requires createSectionController when no coordinator hook provides one")}function H5(){let W=E()||{},q=e1(S());if(q.length===0)return W;let _=W.placement||{},w=Array.isArray(_.section)?_.section:null;if(w&&w.length>0)return W;return{...W,placement:{..._,section:q}}}function R4(){return z8(H5(),{strictness:C(),source:"pie-assessment-toolkit.bootstrap",toolRegistry:p()}).config}function C4(){let W="",q="";try{W=JSON.stringify(H5())}catch{W="[unserializable-tools]"}try{q=JSON.stringify(Object.entries(v()??{}).map(([_,w])=>[_,typeof w]))}catch{q="[unserializable-resolvers]"}return[K()||"",String(C()||"error"),W,q].join("|")}function b4(W){let q=W?.pnpEnforcement;return q==="on"||q==="off"?q:null}function E4(W){let q=K()||U()?.identifier||`assessment-${Math.random().toString(16).slice(2)}`;return new b7({assessmentId:q,lazyInit:M(),eagerInit:!1,toolConfigStrictness:C(),deferToolConfigValidation:!0,assessmentOptional:!0,tools:W,toolRegistry:p(),toolContextResolvers:v(),accessibility:e(),frameworkErrorBus:G})}function X8(W){try{return JSON.stringify(W??null)}catch{return"[unserializable]"}}function G8(){return{signatures:{assessmentId:K()||"",toolConfigStrictness:String(C()||"error"),lazyInit:String(M()),tools:X8({...H5(),pnpEnforcement:void 0}),accessibility:X8(e())},toolRegistry:p()}}function S4(){let W=jZ;if(!W)return[];let q=G8(),_=Object.keys(q.signatures).filter((w)=>q.signatures[w]!==W.signatures[w]);if(W.toolRegistry&&q.toolRegistry!==W.toolRegistry)_.push("toolRegistry");return _}function y4(W,q){if(u7)return;u7=!0,console.warn(`[pie-assessment-toolkit] ${W.join(", ")} changed after ${q} with the coordinator this toolkit built, and that coordinator keeps the values it was built with. Set these inputs no later than the section or the first item scope, pass a coordinator of your own, or update this one from runtime-ready with updateToolConfig(...) or updateToolsPlacement(...). Reported once per toolkit.`)}function T4(W){if(g7)return;g7=!0,console.warn(`[pie-assessment-toolkit] The toolkit above this one (runtime "${W}") had no coordinator when this one connected, so this one built its own and keeps it: the two share no tool state, policy or read-aloud. Give the outer toolkit its coordinator before the inner one connects, or set isolation="force" on the inner one to keep them apart on purpose. Reported once per toolkit.`)}function SZ(){let W=F(g);if(!W)return Promise.resolve();return m(g,null),W.dispose()}function yZ(W){w0({kind:"runtime-dispose",source:"pie-assessment-toolkit",error:W,recoverable:!0})}let TZ=d(()=>!Z0()&&U0()!=="force"&&F(Y0)?.coordinator!=null),b=d(()=>{if(F(TZ))return F(Y0)?.coordinator;return Z0()||F(g)}),A5=d(()=>U()!=null);y(()=>{F(x),Z0(),U0(),F(Y0),v(),F(A5),F(WZ),E(),S(),K(),C(),M(),e(),p(),I(()=>{if(!F(x))return;if(Z0()){if(F(g))SZ().catch(yZ);g0=null;return}if(U0()!=="force"&&F(Y0)?.coordinator){if(F(g))SZ().catch(yZ);g0=null;return}if(F(g)){let W=S4();if(W.length>0&&BZ)y4(W,BZ);else if(W.length>0&&(U()||F(WZ)))SZ().catch(yZ)}if(F(g)&&g0!==v()){try{F(g).setToolContextResolvers(v()),g0=v()}catch(W){w0({kind:"coordinator-init",source:"pie-assessment-toolkit",error:W})}return}if(!F(g)){if(U0()!=="force"&&!GZ){let q=v1(F(x),W5);if(q?.coordinator&&q.runtimeId!==Y){m(Y0,q,!0),g0=null;return}}let W=C4();if(U5===W)return;try{let q=R4();m(g,E4(q),!0),GZ=U0()!=="force",jZ=G8(),BZ=null,g0=v(),U5="",o7()}catch(q){m(g,null),U5=W,w0({kind:"coordinator-init",source:"pie-assessment-toolkit",error:q})}}})}),y(()=>{if(!F(WZ)||!F(b))return;let W=F(b);I(()=>{if(W===F(g))BZ??="an item registered"})});let j8=KQ(),R0=d(()=>D()??j8),KZ=n(0);y(()=>{return F(R0).subscribe?.(()=>{m(KZ,F(KZ)+1)})}),y(()=>{let W=typeof N()==="string"?N().trim():"",q=F(R0);if(!W&&q!==j8)return;I(()=>{Promise.resolve(q.setLocale(W||qQ)).catch((_)=>{w0({kind:"i18n-locale-load",source:"pie-assessment-toolkit",error:_ instanceof Error?_:Error(String(_)),recoverable:!0})})})});let x4=d(()=>{return F(KZ),{locale:F(R0).getLocale(),direction:F(R0).getDirection?.()??"ltr"}});y(()=>{F(KZ);let W=F(x);if(!W)return;$Q(W,F(R0))});let C0=d(()=>K()||F(b)?.assessmentId||""),Q0=d(()=>b1({sectionId:$(),section:U(),assessmentId:K()})),D5=d(()=>e7(H())),k4=d(()=>P4(F(D5))),l0=d(()=>N4(r(),q0())),qZ=d(()=>GQ({player:F(l0),component:"pie-assessment-toolkit"})),f4=d(()=>{if(!F(b))return null;return{toolkitCoordinator:F(b),toolCoordinator:F(b).toolCoordinator,ttsService:F(b).ttsService,highlightCoordinator:F(b).highlightCoordinator,catalogResolver:F(b).catalogResolver,elementToolStateStore:F(b).elementToolStateStore,assessmentId:F(C0),sectionId:F(Q0),attemptId:z()||void 0,itemPlayer:F(l0),ndsIcons:O()===!0,locale:(F(KZ),F(R0).getLocale()),i18n:F(R0),contentLanguage:P()?.trim()||void 0,contentLanguageDefault:UQ({contentLanguage:P(),interfaceLocale:N()}),reportSectionError:(W)=>{X.reportSectionError({source:"section-runtime",error:W,timestamp:Date.now()})}}}),I4=d(()=>{if(!F(b)||!F(x))return null;return{runtimeId:Y,coordinator:F(b),sectionBound:F(A5),eventTarget:F(x)}});function B8(W){if(W==null)return;let q=L4(W);if(q===F(c7))return;m(c7,q,!0),m(PZ,F(PZ)+1),m(V5,W,!0),P0("composition-changed",{composition:F(V5),version:F(PZ)})}function _5(W){F5=W??X.getCompositionModel(),CZ.schedule(()=>{B8(F5)})}function v4(){if(!CZ.isPending())return;CZ.cancel(),B8(F5)}function M5(W){if(!W)return;let q=z5.get(W);if(!q)return;for(let _ of q)_();z5.delete(W)}function W8(){for(let W of bZ.values())M5(W.element)}function V8(W){if(M5(W.element),!F(b))return;z5.set(W.element,L1(F(b),W,{assessmentId:F(C0),sectionId:F(Q0)}))}function h4(){W8();for(let W of bZ.values())V8(W)}function O5(W){if(!W)return;EZ.get(W)?.(),EZ.delete(W)}function m4(W){O5(W),EZ.set(W,w1(W,{getMathSpeech:()=>F(b)?.ttsService.getMathSpeechOptions(),getContentLanguage:()=>P()}))}function u4(W){let _={...W.result?.eventDetail||W.fallbackSession,itemId:W.itemId,canonicalItemId:W.canonicalItemId||W.itemId,sourceRuntimeId:Y};if(!I1({state:d7,itemId:W.itemId,payload:_}))return;P0("session-changed",_)}function p4(W){if(!(W instanceof HTMLElement))return!1;return v1(W,W5)?.runtimeId===Y}function $0(W){return W.detail??null}function g4(W,q){for(let _ of q)W.addEventListener(_.name,_.handler);return()=>{for(let _ of q)W.removeEventListener(_.name,_.handler)}}y(()=>{let W=F(x),q=U0();return I(()=>{if(!W)return;if(q==="force")return m(Y0,null),()=>{GZ=!1};let _=t1(W,(w)=>{if(w.runtimeId===Y)return;if(GZ){T4(w.runtimeId);return}m(Y0,w,!0)});return()=>{_(),m(Y0,null),GZ=!1}})}),y(()=>{let W=F(b);if(!W)return;return I(()=>_1({ttsService:W.ttsService,silence:()=>X.requestMediaPauseForCompetingAudio()}))}),y(()=>{let W=F(TZ)?F(Y0)?.runtimeId??null:null,q=W?"inherited":"owned";if(q!==f7)f7=q,P0(q==="inherited"?"runtime-inherited":"runtime-owned",{runtimeId:Y,parentRuntimeId:W})}),y(()=>{let W=F(x);if(!W)return;I(()=>y1(W.ownerDocument))}),y(()=>{let W=F(b);if(!W)return;let q=F(TZ)?"inherited":"owned";I(()=>{if(W===I7)return;I7=W,P0("runtime-ready",{runtimeId:Y,coordinator:W,ownership:q})})}),y(()=>{let W=F(Q0),q=z()||"";f1(d7)}),y(()=>{if(!F(x))return;F(x).setAttribute("data-item-player-type",F(l0).type),F(x).setAttribute("data-item-player-tag",F(l0).tagName),F(x).setAttribute("data-env-mode",F(D5).mode),F(x).setAttribute("data-env-role",F(D5).role)}),y(()=>{return F(b),F(C0),F(Q0),h4(),()=>{W8()}}),y(()=>{if(!F(x))return;return XQ({host:F(x),instrumentationProvider:F(qZ),component:"pie-assessment-toolkit",eventMap:jQ,staticAttributes:{instrumentationLayer:"toolkit",assessmentId:F(C0),sectionId:F(Q0),attemptId:z()||void 0}})});let L5=null;y(()=>{NZ(),E();let W=F(b);if(!W)return;if(W!==F(g))return;I(()=>{let q={pnpEnforcement:b4(E()),assessment:NZ()??null},_=L5?.coordinator===W?L5.inputs:null;L5={coordinator:W,inputs:q};for(let w of E1(_,q))if(w==="pnpEnforcement")W.setPnpEnforcement(q.pnpEnforcement);else W.updateAssessment(q.assessment)})}),y(()=>{if(!F(b))return;return F(b).subscribeTelemetry(({eventName:W,payload:q})=>{if(!VQ(F(qZ)))return;if(!F(qZ).isReady())return;let _=new Date().toISOString(),w={...q||{},instrumentationLayer:"toolkit",assessmentId:F(C0),sectionId:F(Q0),attemptId:z()||void 0,component:"pie-assessment-toolkit",sourceEventName:W,timestamp:_};F(qZ).trackEvent(W,w);let L=q&&typeof q.errorType==="string"?q.errorType:void 0;if(!W.endsWith("-error")&&!L)return;let A=q&&typeof q.message==="string"?q.message:`Toolkit telemetry error: ${W}`;F(qZ).trackError(Error(A),{component:"pie-assessment-toolkit",errorType:L||"ToolkitTelemetryError",...w})})}),y(()=>{if(!U()||!F(b))return;let W=!1;if(F(b)===I(()=>F(g)))BZ??="a section initialized";let q={sectionId:F(Q0),attemptId:z()||void 0},_=m7;if(m7=q,_&&!Z8(_,q))I(()=>h1(F(x),{reason:"teardown",logger:J}));$5=null;let w=I(()=>J8(q,!0));return X.initialize({coordinator:F(b),section:U(),sectionId:F(Q0),assessmentId:F(C0),attemptId:z()||void 0,view:F(k4),initialSession:w,createDefaultController:w4,onCompositionChanged:(L)=>{if(W)return;_5(L)},onControllerEvent:(L)=>{if(W)return;q4(L),K4(L,q)}}).then(()=>{if(W)return;$5=q;let L=I(()=>F(X0));if(L&&VZ(L)===RZ)o7();RZ=null,I(()=>Y8()),I(()=>v4()),queueMicrotask(()=>{if(W)return;P0("toolkit-ready",{runtimeId:Y,assessmentId:F(C0),sectionId:F(Q0),itemPlayer:F(l0),coordinator:F(b)}),P0("section-ready",{sectionId:q.sectionId,attemptId:q.attemptId,controller:F(b).getSectionController(q)??null})})}).catch((L)=>{if(W)return;let A=I(()=>$4(L));if(A)I(()=>a7(A)),RZ=VZ(A);else RZ=VZ(w0({kind:"runtime-init",source:"pie-assessment-toolkit",error:L,cohort:q}))}),()=>{W=!0}}),y(()=>{L0(),I(()=>{Q8(),Y8()})}),y(()=>{if(!F(x))return;let W=F(x),q=(L)=>{if(!O1(L,Y,p4))return!1;return L.stopPropagation(),!0},w=g4(W,[{name:Y5,handler:(L)=>{if(!q(L))return;let A=$0(L);if(!A?.element||!A?.itemId)return;let l=X.register(A);if(bZ.set(A.element,A),m(WZ,!0),V8(A),m4(A.element),X.handleContentRegistered(A),l)_5()}},{name:Z4,handler:(L)=>{if(!q(L))return;let A=$0(L);if(!A?.itemId)return;let l=A?.element?X.unregister(A.element):!1;if(M5(A.element),O5(A.element),A.element)bZ.delete(A.element);if(X.handleContentUnregistered(A),l)_5()}},{name:Q4,handler:(L)=>{if(!q(L))return;let A=$0(L);if(!A?.itemId)return;let l=X.updateItemSession(A.itemId,A.session);u4({itemId:A.itemId,canonicalItemId:X.getCanonicalItemId(A.itemId),result:l,fallbackSession:A.session})}},{name:Y4,handler:(L)=>{if(!q(L))return;let A=$0(L);if(!A?.itemId)return;X.recordServedContentIdentity({itemId:A.itemId,canonicalItemId:A.canonicalItemId,identity:A.identity})}},{name:J4,handler:(L)=>{if(!q(L))return;let A=$0(L);if(!A?.itemId)return;X.handleContentLoaded({itemId:A.itemId,canonicalItemId:A.canonicalItemId,contentKind:A.contentKind,detail:A.detail,timestamp:Date.now()})}},{name:X4,handler:(L)=>{if(!q(L))return;let A=$0(L);if(!A?.itemId)return;X.handleItemPlayerError({itemId:A.itemId,canonicalItemId:A.canonicalItemId,contentKind:A.contentKind,error:A.error,timestamp:Date.now()})}},{name:G4,handler:(L)=>{if(!q(L))return;let A=$0(L);if(!A?.itemId)return;if(A.action!=="check"&&A.action!=="retry")return;X.handleTryAction({itemId:A.itemId,canonicalItemId:A.canonicalItemId,action:A.action,outcomes:A.outcomes})}},{name:j4,handler:(L)=>{if(!q(L))return;let A=$0(L);if(!A?.renderableId)return;if(A.action!=="attach"&&A.action!=="detach")return;X.handleMediaTimeSource({renderableId:A.renderableId,action:A.action,source:A.source,origin:A.origin})}}]);return()=>{I(()=>h1(W,{reason:"teardown",logger:J})),w();for(let L of[...EZ.keys()])O5(L)}}),y(()=>{if(!F(x))return;return()=>{d0?.disconnect(),d0=null,c0?.disconnect(),c0=null,i0?.disconnect(),i0=null}}),y(()=>{let W=F(x),q=F(I4);if(!W||!q)return;I(()=>{if(d0){d0.setValue(q);return}d0=new y7(W,{context:W5,initialValue:q}),d0.connect()})}),y(()=>{let W=F(x),q=F(f4);if(!W||!q)return;I(()=>{if(c0){c0.setValue(q);return}c0=new y7(W,{context:o1,initialValue:q}),c0.connect()})}),y(()=>{let W=F(x),q=F(x4);if(!W)return;I(()=>{if(i0){i0.setValue(q);return}i0=new y7(W,{context:YQ,initialValue:q}),i0.connect()})});async function c4(){if(!F(b))throw Error("Coordinator not initialized");await F(b).waitUntilReady()}function d4(W){if(!F(b))throw Error("Coordinator not initialized");F(b).setHooks(W)}function i4(W){return X.navigateToItem(W)}function l4(){return X.getCompositionModel()}function s4(){return F(l0)}async function n4(){await X.persist()}async function r4(){await X.hydrate()}y(()=>{let W=F(b);if(!W)return;let q=F(PZ)>0||F(V5)!==null,_=!F(A5)&&F(WZ);if(!q&&!_)return;I(()=>{if(W===p7)return;p7=W,W.waitUntilReady().catch(()=>{})})}),y(()=>{return()=>{CZ.cancel(),X.dispose().catch((W)=>{w0({kind:"runtime-dispose",source:"pie-assessment-toolkit",error:W,recoverable:!0})}).then(()=>SZ()).catch(yZ).finally(()=>{G.dispose()})}});var a4={waitUntilReady:c4,setHooks:d4,navigateToItem:i4,getCompositionModel:l4,getItemPlayerConfig:s4,persist:n4,hydrate:r4,get assessmentId(){return K()},set assessmentId(W){K(W),k()},get section(){return U()},set section(W){U(W),k()},get sectionId(){return $()},set sectionId(W){$(W),k()},get attemptId(){return z()},set attemptId(W){z(W),k()},get env(){return H()},set env(W){H(W),k()},get ndsIcons(){return O()},set ndsIcons(W){O(W),k()},get locale(){return N()},set locale(W){N(W),k()},get i18n(){return D()},set i18n(W){D(W),k()},get contentLanguage(){return P()},set contentLanguage(W){P(W),k()},get lazyInit(){return M()},set lazyInit(W){M(W),k()},get toolConfigStrictness(){return C()},set toolConfigStrictness(W){C(W),k()},get tools(){return E()},set tools(W){E(W),k()},get toolContextResolvers(){return v()},set toolContextResolvers(W){v(W),k()},get enabledTools(){return S()},set enabledTools(W){S(W),k()},get toolRegistry(){return p()},set toolRegistry(W){p(W),k()},get accessibility(){return e()},set accessibility(W){e(W),k()},get player(){return r()},set player(W){r(W),k()},get playerType(){return q0()},set playerType(W){q0(W),k()},get coordinator(){return Z0()},set coordinator(W){Z0(W),k()},get createSectionController(){return M0()},set createSectionController(W){M0(W),k()},get onFrameworkError(){return O0()},set onFrameworkError(W){O0(W),k()},get errorRenderer(){return LZ()},set errorRenderer(W){LZ(W),k()},get assessment(){return NZ()},set assessment(W){NZ(W),k()},get isolation(){return U0()},set isolation(W){U0(W),k()},get session(){return L0()},set session(W){L0(W),k()}},K8=HQ(),q8=T7(K8);r1(q8,(W)=>m(XZ,W),()=>F(XZ));var o4=G5(q8,2);{var t4=(W)=>{var q=zQ(),_=c1(q),w=X5(_,!0),L=G5(_,2),A=X5(L,!0),l=G5(L,2),xZ=X5(l,!0);m1(q),d1((N5)=>{B5(w,F(K5)),B5(A,F(X0).message),B5(xZ,N5)},[()=>F(q5).join(`
|
|
225
225
|
`)]),j5(W,q)},e4=(W)=>{var q=i1(),_=T7(q);s1(_,Q,"default",{},null),j5(W,q)};l1(o4,(W)=>{if(F(X0)&&!F(X0).recoverable)W(t4);else W(e4,-1)})}return j5(Z,K8),p1(a4)}QQ("pie-assessment-toolkit",a1(B4,{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"},locale:{attribute:"locale",type:"String"},i18n:{type:"Object"},contentLanguage:{attribute:"content-language",type:"String"},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"},assessment:{type:"Object"},isolation:{attribute:"isolation",type:"String"},session:{type:"Object"}},["default"],["waitUntilReady","setHooks","navigateToItem","getCompositionModel","getItemPlayerConfig","persist","hydrate"],{mode:"open"},JQ));export{B4 as default};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{ContextProvider as Y,FEATURE_DECISION_APPLIED_EVENT as M,itemFeatureDecisionsContext as V}from"@pie-players/pie-context";var k=["autoplayAudio"],X=Object.freeze({features:Object.freeze({})});function L(j){let G=j.canonicalItemId||j.itemId;return{level:"item",scopeId:G,itemId:j.itemId,canonicalItemId:G}}function U(j,G){if(!G||typeof j?.decideFeaturePolicy!=="function")return X;let H={};for(let q of k){let z=j.decideFeaturePolicy(q,G);if(z.rule==="none")continue;H[q]={granted:z.granted,rule:z.rule}}return{features:H}}function A(j){let G=new Y(j,{context:V,initialValue:X});G.connect();let H=JSON.stringify(X.features),q=null,z=null,K=null,Q=()=>{let B=U(q,z),J=JSON.stringify(B.features);if(J===H)return;H=J,G.setValue(B)},W=()=>{let B=K;K=null;try{B?.()}catch{}},$=(B)=>{let J=B.detail;if(!J||!z)return;q?.reportFeatureDecisionApplied?.(J,z)};return j.addEventListener(M,$),{setCoordinator(B){if(B===q)return;if(W(),q=B,B&&typeof B.onPolicyChange==="function")K=B.onPolicyChange((J)=>{if(J.reason==="disposed")W(),q=null;Q()});Q()},setItem(B){let J=B?.itemId?L(B):null;if(J?.scopeId===z?.scopeId&&J?.itemId===z?.itemId)return;z=J,Q()},disconnect(){j.removeEventListener(M,$),W(),q=null,z=null,G.disconnect()}}}var P="pie-register",D="pie-unregister",N="pie-item-session-changed",O="item-session-changed",C="item-player-event",S=["load-complete","player-error","correct-responses-populated","bundle-retry-status","session-snapshot-available","backend-load-complete","backend-model-complete","backend-session-saved","backend-score-complete","backend-error"],_="pie-content-loaded",m="pie-content-identity",u="pie-item-player-error",v="pie-
|
|
1
|
+
import{ContextProvider as Y,FEATURE_DECISION_APPLIED_EVENT as M,itemFeatureDecisionsContext as V}from"@pie-players/pie-context";var k=["autoplayAudio"],X=Object.freeze({features:Object.freeze({})});function L(j){let G=j.canonicalItemId||j.itemId;return{level:"item",scopeId:G,itemId:j.itemId,canonicalItemId:G}}function U(j,G){if(!G||typeof j?.decideFeaturePolicy!=="function")return X;let H={};for(let q of k){let z=j.decideFeaturePolicy(q,G);if(z.rule==="none")continue;H[q]={granted:z.granted,rule:z.rule}}return{features:H}}function A(j){let G=new Y(j,{context:V,initialValue:X});G.connect();let H=JSON.stringify(X.features),q=null,z=null,K=null,Q=()=>{let B=U(q,z),J=JSON.stringify(B.features);if(J===H)return;H=J,G.setValue(B)},W=()=>{let B=K;K=null;try{B?.()}catch{}},$=(B)=>{let J=B.detail;if(!J||!z)return;q?.reportFeatureDecisionApplied?.(J,z)};return j.addEventListener(M,$),{setCoordinator(B){if(B===q)return;if(W(),q=B,B&&typeof B.onPolicyChange==="function")K=B.onPolicyChange((J)=>{if(J.reason==="disposed")W(),q=null;Q()});Q()},setItem(B){let J=B?.itemId?L(B):null;if(J?.scopeId===z?.scopeId&&J?.itemId===z?.itemId)return;z=J,Q()},disconnect(){j.removeEventListener(M,$),W(),q=null,z=null,G.disconnect()}}}var P="pie-register",D="pie-unregister",N="pie-item-session-changed",O="item-session-changed",C="item-player-event",S=["load-complete","player-error","correct-responses-populated","bundle-retry-status","session-snapshot-available","backend-load-complete","backend-model-complete","backend-session-saved","backend-score-complete","backend-error"],_="pie-content-loaded",m="pie-content-identity",u="pie-item-player-error",v="pie-try-action",F="pie-media-time-source";var Z=(j)=>Array.isArray(j)&&j.length>0;function b(j){if(j.kind==="passage")return{ownerKind:"passage",assessmentId:j.assessmentId,sectionId:j.sectionId,passageId:j.canonicalItemId||j.itemId};return{ownerKind:"itemModel",assessmentId:j.assessmentId,sectionId:j.sectionId,itemId:j.itemId,canonicalItemId:j.canonicalItemId||j.itemId}}function R(j,G){if(!j)return[];let H=b(G),q=[];if(Z(j.accessibilityCatalogs))q.push({context:H,catalogs:j.accessibilityCatalogs});if(Z(j.config?.extractedCatalogs))q.push({context:H,catalogs:j.config.extractedCatalogs});if(G.kind==="passage")return q;if(H.ownerKind!=="itemModel")return q;for(let z of j.config?.models??[]){if(!Z(z.accessibilityCatalogs))continue;q.push({context:{...H,modelId:z.id},catalogs:z.accessibilityCatalogs})}return q}function E(j,G){let H=R(j,{kind:G,itemId:""});try{return JSON.stringify(H.map((q)=>[q.context.modelId??null,q.catalogs]))}catch{return null}}
|
|
2
2
|
export{k as a,A as b,P as c,D as d,N as e,O as f,C as g,S as h,_ as i,m as j,u as k,v as l,F as m,b as n,R as o,E as p};
|
package/dist/index.d.ts
CHANGED
|
@@ -9,7 +9,7 @@
|
|
|
9
9
|
export type { AssessmentToolkitRuntimeContext, ItemPlayerConfig, ItemPlayerType, ShellContextKind, } from "./context/assessment-toolkit-context.js";
|
|
10
10
|
export type { TTSHighlightContext, TTSHighlightTargetResolver, TTSHighlightTargetResolverProvider, TTSHighlightTargetResolverRuntime, } from "./services/tts/highlight-target-resolver.js";
|
|
11
11
|
export { catalogOwnerContextFor, type CatalogOwnerContext, type CatalogOwnerIdentity, type CatalogSourceEntity, } from "./services/catalog-owner.js";
|
|
12
|
-
export {
|
|
12
|
+
export { PIE_INTERNAL_TRY_ACTION_EVENT, PIE_INTERNAL_ITEM_SESSION_CHANGED_EVENT, PIE_INTERNAL_MEDIA_TIME_SOURCE_EVENT, PIE_ITEM_PLAYER_EVENT, PIE_ITEM_SESSION_CHANGED_EVENT, RELAYED_ITEM_PLAYER_EVENTS, type InternalTryActionDetail, type InternalMediaTimeSourceDetail, type ItemPlayerEventDetail, type RelayedItemPlayerEventType, } from "./runtime/registration-events.js";
|
|
13
13
|
export { createShellScope, type ShellScope, type ShellScopeState, } from "./runtime/shell-scope.js";
|
|
14
14
|
export { createShellEventBridge, type ShellEventBridge, type ShellEventBridgeOptions, } from "./runtime/shell-event-bridge.js";
|
|
15
15
|
export { connectToolRuntimeContext, dispatchCrossBoundaryEvent, } from "./runtime/tool-host-contract.js";
|
package/dist/index.js
CHANGED
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
* @packageDocumentation
|
|
8
8
|
*/
|
|
9
9
|
export { catalogOwnerContextFor, } from "./services/catalog-owner.js";
|
|
10
|
-
export {
|
|
10
|
+
export { PIE_INTERNAL_TRY_ACTION_EVENT, PIE_INTERNAL_ITEM_SESSION_CHANGED_EVENT, PIE_INTERNAL_MEDIA_TIME_SOURCE_EVENT, PIE_ITEM_PLAYER_EVENT, PIE_ITEM_SESSION_CHANGED_EVENT, RELAYED_ITEM_PLAYER_EVENTS, } from "./runtime/registration-events.js";
|
|
11
11
|
export { createShellScope, } from "./runtime/shell-scope.js";
|
|
12
12
|
// A shell's translation of its player's events into the runtime's, shared by the
|
|
13
13
|
// section player's passage shell and `<pie-item-scope>`.
|
|
@@ -91,8 +91,8 @@ export interface SectionRuntimeMediaTimeSourceAction {
|
|
|
91
91
|
source?: MediaTimeSource;
|
|
92
92
|
origin?: "native-adapter" | "host";
|
|
93
93
|
}
|
|
94
|
-
/** What a
|
|
95
|
-
export interface
|
|
94
|
+
/** What a Try action reaching the binding has to say. */
|
|
95
|
+
export interface SectionRuntimeTryAction {
|
|
96
96
|
itemId: string;
|
|
97
97
|
canonicalItemId?: string;
|
|
98
98
|
action: "check" | "retry";
|
|
@@ -255,18 +255,18 @@ export declare class SectionControllerBinding {
|
|
|
255
255
|
}): void;
|
|
256
256
|
navigateToItem(index: number): unknown;
|
|
257
257
|
/**
|
|
258
|
-
* Route a learner's
|
|
258
|
+
* Route a learner's Try action to the controller.
|
|
259
259
|
*
|
|
260
260
|
* Canonicalized here for the same reason `updateItemSession` is: the runtime
|
|
261
261
|
* id a card dispatches with is not necessarily the identifier the controller
|
|
262
262
|
* keys state by. Both ids are kept, since the composition's renderables are
|
|
263
263
|
* keyed by the runtime one.
|
|
264
264
|
*/
|
|
265
|
-
|
|
265
|
+
handleTryAction(action: SectionRuntimeTryAction): void;
|
|
266
266
|
/**
|
|
267
267
|
* Bind or release the section's Media Time Source.
|
|
268
268
|
*
|
|
269
|
-
* A pass-through, like `
|
|
269
|
+
* A pass-through, like `handleTryAction`: the binding routes, the
|
|
270
270
|
* controller decides. `renderableId` travels with the attach because whether the
|
|
271
271
|
* registering renderable is the one `stimulusRef` names is the controller's call
|
|
272
272
|
* — it validated `stimulusRef` in the first place.
|
|
@@ -369,23 +369,23 @@ export class SectionControllerBinding {
|
|
|
369
369
|
return this.controller?.navigateToItem?.(index) ?? null;
|
|
370
370
|
}
|
|
371
371
|
/**
|
|
372
|
-
* Route a learner's
|
|
372
|
+
* Route a learner's Try action to the controller.
|
|
373
373
|
*
|
|
374
374
|
* Canonicalized here for the same reason `updateItemSession` is: the runtime
|
|
375
375
|
* id a card dispatches with is not necessarily the identifier the controller
|
|
376
376
|
* keys state by. Both ids are kept, since the composition's renderables are
|
|
377
377
|
* keyed by the runtime one.
|
|
378
378
|
*/
|
|
379
|
-
|
|
379
|
+
handleTryAction(action) {
|
|
380
380
|
if (!action?.itemId)
|
|
381
381
|
return;
|
|
382
382
|
const canonicalId = action.canonicalItemId || this.getCanonicalItemId(action.itemId);
|
|
383
|
-
const controller = this.requireControllerFor({ itemId: action.itemId, canonicalItemId: canonicalId }, "a
|
|
383
|
+
const controller = this.requireControllerFor({ itemId: action.itemId, canonicalItemId: canonicalId }, "a Try action");
|
|
384
384
|
if (action.action === "retry") {
|
|
385
|
-
controller?.
|
|
385
|
+
controller?.retryItem?.({ itemId: canonicalId });
|
|
386
386
|
return;
|
|
387
387
|
}
|
|
388
|
-
controller?.
|
|
388
|
+
controller?.recordTry?.({
|
|
389
389
|
itemId: canonicalId,
|
|
390
390
|
outcomes: action.outcomes,
|
|
391
391
|
});
|
|
@@ -393,7 +393,7 @@ export class SectionControllerBinding {
|
|
|
393
393
|
/**
|
|
394
394
|
* Bind or release the section's Media Time Source.
|
|
395
395
|
*
|
|
396
|
-
* A pass-through, like `
|
|
396
|
+
* A pass-through, like `handleTryAction`: the binding routes, the
|
|
397
397
|
* controller decides. `renderableId` travels with the attach because whether the
|
|
398
398
|
* registering renderable is the one `stimulusRef` names is the controller's call
|
|
399
399
|
* — it validated `stimulusRef` in the first place.
|
|
@@ -16,7 +16,7 @@ export type RelayedItemPlayerEventType = (typeof RELAYED_ITEM_PLAYER_EVENTS)[num
|
|
|
16
16
|
export declare const PIE_INTERNAL_CONTENT_LOADED_EVENT = "pie-content-loaded";
|
|
17
17
|
export declare const PIE_INTERNAL_CONTENT_IDENTITY_EVENT = "pie-content-identity";
|
|
18
18
|
export declare const PIE_INTERNAL_ITEM_PLAYER_ERROR_EVENT = "pie-item-player-error";
|
|
19
|
-
export declare const
|
|
19
|
+
export declare const PIE_INTERNAL_TRY_ACTION_EVENT = "pie-try-action";
|
|
20
20
|
export declare const PIE_INTERNAL_MEDIA_TIME_SOURCE_EVENT = "pie-media-time-source";
|
|
21
21
|
export type RuntimeRegistrationKind = "item" | "passage";
|
|
22
22
|
export interface RuntimeRegistrationDetail {
|
|
@@ -80,7 +80,7 @@ export interface InternalItemPlayerErrorDetail {
|
|
|
80
80
|
error: unknown;
|
|
81
81
|
}
|
|
82
82
|
/**
|
|
83
|
-
* A learner's
|
|
83
|
+
* A learner's Try action, dispatched by the component that owns the
|
|
84
84
|
* control and the item player node — the only place that can call
|
|
85
85
|
* `provideScore()`. It reports outcomes rather than interpreting them; the
|
|
86
86
|
* section controller derives correctness and owns the state.
|
|
@@ -89,7 +89,7 @@ export interface InternalItemPlayerErrorDetail {
|
|
|
89
89
|
* including the `undefined` slots it leaves for models with no element or
|
|
90
90
|
* controller.
|
|
91
91
|
*/
|
|
92
|
-
export interface
|
|
92
|
+
export interface InternalTryActionDetail {
|
|
93
93
|
itemId: string;
|
|
94
94
|
canonicalItemId?: string;
|
|
95
95
|
action: "check" | "retry";
|
|
@@ -23,5 +23,5 @@ export const RELAYED_ITEM_PLAYER_EVENTS = [
|
|
|
23
23
|
export const PIE_INTERNAL_CONTENT_LOADED_EVENT = "pie-content-loaded";
|
|
24
24
|
export const PIE_INTERNAL_CONTENT_IDENTITY_EVENT = "pie-content-identity";
|
|
25
25
|
export const PIE_INTERNAL_ITEM_PLAYER_ERROR_EVENT = "pie-item-player-error";
|
|
26
|
-
export const
|
|
26
|
+
export const PIE_INTERNAL_TRY_ACTION_EVENT = "pie-try-action";
|
|
27
27
|
export const PIE_INTERNAL_MEDIA_TIME_SOURCE_EVENT = "pie-media-time-source";
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type {
|
|
1
|
+
import type { FeedbackReveal, MasteryRollup, TrySectionProjection, TryOutcome } from "@pie-players/pie-players-shared/item-session-control";
|
|
2
2
|
import type { MediaTimeSource, TimedMediaDegradation, TimedMediaSectionProjection, TimedMediaValidationError } from "@pie-players/pie-players-shared/timed-media";
|
|
3
3
|
import type { SessionCommitReason } from "@pie-players/pie-players-shared/pie";
|
|
4
4
|
import type { SectionControllerSessionState } from "@pie-players/pie-players-shared/types";
|
|
@@ -175,12 +175,12 @@ export type SectionControllerSectionErrorEvent = SectionControllerEventBase & {
|
|
|
175
175
|
contentKind?: "item" | "passage" | "rubric" | "unknown";
|
|
176
176
|
currentItemIndex: number;
|
|
177
177
|
};
|
|
178
|
-
export type
|
|
179
|
-
type: "
|
|
178
|
+
export type SectionControllerItemTryRecordedEvent = SectionControllerEventBase & {
|
|
179
|
+
type: "item-try-recorded";
|
|
180
180
|
itemId: string;
|
|
181
181
|
canonicalItemId: string;
|
|
182
182
|
tryCount: number;
|
|
183
|
-
outcome:
|
|
183
|
+
outcome: TryOutcome;
|
|
184
184
|
/** Whether feedback is now on screen for this item. */
|
|
185
185
|
revealed: boolean;
|
|
186
186
|
currentItemIndex: number;
|
|
@@ -189,16 +189,16 @@ export type SectionControllerFormativeTryRecordedEvent = SectionControllerEventB
|
|
|
189
189
|
* The reveal state changed without a Try being recorded: a learner dismissed
|
|
190
190
|
* feedback to edit again, or a host forced a reveal or withdrew one.
|
|
191
191
|
*
|
|
192
|
-
* A Try that reveals reports through `
|
|
192
|
+
* A Try that reveals reports through `item-try-recorded`, which carries its
|
|
193
193
|
* own `revealed`. This event is for every other transition.
|
|
194
194
|
*/
|
|
195
|
-
export type
|
|
196
|
-
type: "
|
|
195
|
+
export type SectionControllerItemFeedbackRevealChangedEvent = SectionControllerEventBase & {
|
|
196
|
+
type: "item-feedback-reveal-changed";
|
|
197
197
|
itemId: string;
|
|
198
198
|
canonicalItemId: string;
|
|
199
199
|
revealed: boolean;
|
|
200
200
|
/** Reveal level in force, when a host overrode the policy's. */
|
|
201
|
-
feedback?:
|
|
201
|
+
feedback?: FeedbackReveal;
|
|
202
202
|
/** Tries already spent; none of these transitions consume one. */
|
|
203
203
|
tryCount: number;
|
|
204
204
|
source: "learner" | "host";
|
|
@@ -206,7 +206,7 @@ export type SectionControllerFormativeRevealChangedEvent = SectionControllerEven
|
|
|
206
206
|
};
|
|
207
207
|
export type SectionControllerSectionMasteryChangedEvent = SectionControllerEventBase & {
|
|
208
208
|
type: "section-mastery-changed";
|
|
209
|
-
mastery:
|
|
209
|
+
mastery: MasteryRollup;
|
|
210
210
|
currentItemIndex: number;
|
|
211
211
|
};
|
|
212
212
|
/**
|
|
@@ -268,7 +268,7 @@ export type SectionControllerTimedMediaInvalidEvent = SectionControllerEventBase
|
|
|
268
268
|
errors: TimedMediaValidationError[];
|
|
269
269
|
currentItemIndex: number;
|
|
270
270
|
};
|
|
271
|
-
export type SectionControllerEvent = SectionControllerItemSessionDataChangedEvent | SectionControllerItemSessionMetaChangedEvent | SectionControllerItemSelectedEvent | SectionControllerSectionNavigationChangedEvent | SectionControllerSectionSessionAppliedEvent | SectionControllerContentLoadedEvent | SectionControllerItemPlayerErrorEvent | SectionControllerItemCompleteChangedEvent | SectionControllerSectionLoadingCompleteEvent | SectionControllerSectionItemsCompleteChangedEvent | SectionControllerSectionErrorEvent |
|
|
271
|
+
export type SectionControllerEvent = SectionControllerItemSessionDataChangedEvent | SectionControllerItemSessionMetaChangedEvent | SectionControllerItemSelectedEvent | SectionControllerSectionNavigationChangedEvent | SectionControllerSectionSessionAppliedEvent | SectionControllerContentLoadedEvent | SectionControllerItemPlayerErrorEvent | SectionControllerItemCompleteChangedEvent | SectionControllerSectionLoadingCompleteEvent | SectionControllerSectionItemsCompleteChangedEvent | SectionControllerSectionErrorEvent | SectionControllerItemTryRecordedEvent | SectionControllerItemFeedbackRevealChangedEvent | SectionControllerSectionMasteryChangedEvent | SectionControllerTimedMediaCueChangedEvent | SectionControllerTimedMediaAudioStartedEvent | SectionControllerTimedMediaPolicyDegradedEvent | SectionControllerTimedMediaInvalidEvent;
|
|
272
272
|
export type SectionControllerEventType = SectionControllerEvent["type"];
|
|
273
273
|
/** One item's part of a {@link SectionScore}. */
|
|
274
274
|
export type SectionItemScore = {
|
|
@@ -286,10 +286,10 @@ export type SectionScore = {
|
|
|
286
286
|
items: SectionItemScore[];
|
|
287
287
|
};
|
|
288
288
|
/**
|
|
289
|
-
* Scores one rendered item in the browser: its element outcomes,
|
|
290
|
-
* the item
|
|
289
|
+
* Scores one rendered item in the browser: its element outcomes, `false` when
|
|
290
|
+
* the item has no scorable model, or `null` when its player has not mounted.
|
|
291
291
|
*/
|
|
292
|
-
export type SectionItemScorer = (canonicalItemId: string) => Promise<false | Array<Record<string, unknown> | undefined>>;
|
|
292
|
+
export type SectionItemScorer = (canonicalItemId: string) => Promise<false | null | Array<Record<string, unknown> | undefined>>;
|
|
293
293
|
/**
|
|
294
294
|
* Host-facing controller for a single section cohort.
|
|
295
295
|
*
|
|
@@ -465,7 +465,7 @@ export interface SectionControllerHandle {
|
|
|
465
465
|
/**
|
|
466
466
|
* Record one Try for an item: derive correctness from the element outcomes,
|
|
467
467
|
* increment the Try count, and reveal feedback if the item's resolved
|
|
468
|
-
*
|
|
468
|
+
* item session control policy says so.
|
|
469
469
|
*
|
|
470
470
|
* `outcomes` is what `pie-item-player.provideScore()` returned. The caller
|
|
471
471
|
* does not interpret it — correctness derivation belongs to the controller so
|
|
@@ -474,18 +474,29 @@ export interface SectionControllerHandle {
|
|
|
474
474
|
* No-op when the item's policy is disabled, when feedback is already
|
|
475
475
|
* revealed, or when Tries are spent, which makes a double submit safe.
|
|
476
476
|
*/
|
|
477
|
-
|
|
477
|
+
recordTry?(args: {
|
|
478
478
|
itemId: string;
|
|
479
479
|
outcomes?: unknown[];
|
|
480
480
|
}): void;
|
|
481
|
+
/**
|
|
482
|
+
* Score a rendered item through the registered item scorer and record the
|
|
483
|
+
* Try from its outcomes: Check answer, for a host that hides the built-in
|
|
484
|
+
* control (`policies.checkControl.enabled: false`). Rejects, spending no
|
|
485
|
+
* Try, when no layout has registered a scorer, the item's player has not
|
|
486
|
+
* mounted, or scoring throws. A call while a check of the same item is
|
|
487
|
+
* pending is dropped.
|
|
488
|
+
*/
|
|
489
|
+
checkItem?(args: {
|
|
490
|
+
itemId: string;
|
|
491
|
+
}): Promise<void>;
|
|
481
492
|
/**
|
|
482
493
|
* Dismiss a revealed item's feedback and reopen it for editing. Withdrawing
|
|
483
494
|
* the reveal is what withdraws the `mode: "evaluate"` projection.
|
|
484
495
|
*
|
|
485
496
|
* The learner action, so it respects the Try budget: no-op when nothing is
|
|
486
|
-
* revealed or Tries are spent. Use `
|
|
497
|
+
* revealed or Tries are spent. Use `hideItemFeedback` for host authority.
|
|
487
498
|
*/
|
|
488
|
-
|
|
499
|
+
retryItem?(args: {
|
|
489
500
|
itemId: string;
|
|
490
501
|
}): void;
|
|
491
502
|
/**
|
|
@@ -497,27 +508,27 @@ export interface SectionControllerHandle {
|
|
|
497
508
|
* `feedback` is stated rather than taken from the policy, because a reveal
|
|
498
509
|
* under `feedback: "none"` would project nothing.
|
|
499
510
|
*/
|
|
500
|
-
|
|
511
|
+
revealItemFeedback?(args: {
|
|
501
512
|
itemId: string;
|
|
502
513
|
feedback: "correctness" | "solution";
|
|
503
514
|
}): void;
|
|
504
515
|
/**
|
|
505
|
-
* Withdraw a reveal on host authority. Unlike `
|
|
516
|
+
* Withdraw a reveal on host authority. Unlike `retryItem` this
|
|
506
517
|
* ignores the Try budget, so a host that revealed a spent item can put it
|
|
507
518
|
* back.
|
|
508
519
|
*/
|
|
509
|
-
|
|
520
|
+
hideItemFeedback?(args: {
|
|
510
521
|
itemId: string;
|
|
511
522
|
}): void;
|
|
512
523
|
/**
|
|
513
|
-
* The section's
|
|
524
|
+
* The section's Try projection — resolved policies, per-item state, and
|
|
514
525
|
* the mastery rollup.
|
|
515
526
|
*
|
|
516
|
-
* `null` when no item in the section
|
|
527
|
+
* `null` when no item in the section enables item session control. The same
|
|
517
528
|
* projection rides on the composition model, so layouts normally read it from
|
|
518
529
|
* there rather than calling this.
|
|
519
530
|
*/
|
|
520
|
-
|
|
531
|
+
getTryProjection?(): TrySectionProjection | null;
|
|
521
532
|
/**
|
|
522
533
|
* Bind the section's Media Time Source — the only way it reaches media.
|
|
523
534
|
*
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@pie-players/pie-assessment-toolkit",
|
|
3
|
-
"version": "1.0.0-beta.
|
|
3
|
+
"version": "1.0.0-beta.9",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "PIE assessment toolkit: composable services + reference implementation for assessment players and tool coordination",
|
|
6
6
|
"license": "MIT",
|
|
@@ -69,16 +69,16 @@
|
|
|
69
69
|
"test": "bun test"
|
|
70
70
|
},
|
|
71
71
|
"dependencies": {
|
|
72
|
-
"@pie-players/pie-calculator": "1.0.0-beta.
|
|
73
|
-
"@pie-players/pie-context": "1.0.0-beta.
|
|
74
|
-
"@pie-players/pie-players-shared": "1.0.0-beta.
|
|
75
|
-
"@pie-players/pie-tts": "1.0.0-beta.
|
|
72
|
+
"@pie-players/pie-calculator": "1.0.0-beta.9",
|
|
73
|
+
"@pie-players/pie-context": "1.0.0-beta.9",
|
|
74
|
+
"@pie-players/pie-players-shared": "1.0.0-beta.9",
|
|
75
|
+
"@pie-players/pie-tts": "1.0.0-beta.9",
|
|
76
76
|
"speech-rule-engine": "5.0.0-rc.4"
|
|
77
77
|
},
|
|
78
78
|
"devDependencies": {
|
|
79
79
|
"@biomejs/biome": "^2.6.4",
|
|
80
80
|
"@happy-dom/global-registrator": "^21.0.4",
|
|
81
|
-
"@pie-players/tts-client-server": "1.0.0-beta.
|
|
81
|
+
"@pie-players/tts-client-server": "1.0.0-beta.9",
|
|
82
82
|
"svelte": "^5.57.3",
|
|
83
83
|
"svelte-check": "^4.7.6",
|
|
84
84
|
"typescript": "^5.9.3"
|