@pie-players/pie-section-player 0.3.72 → 0.3.74

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.
Files changed (123) hide show
  1. package/README.md +198 -37
  2. package/dist/browser/assets/evaluation-worker-DkU_wGh3.js +155241 -0
  3. package/dist/browser/chunks/ItemToolBar-wr2myaah-2ce4b643.js +1 -0
  4. package/dist/browser/chunks/PUA-tLuTiQ7--f2b27953.js +1 -0
  5. package/dist/browser/chunks/ToolCoordinator-cc2dc319.js +1 -0
  6. package/dist/browser/chunks/accents-BTUYmhn9-cafeb96e.js +1 -0
  7. package/dist/browser/chunks/accents-b-i-CngHZsLL-e0eb98fd.js +1 -0
  8. package/dist/browser/chunks/arabic-BzEHMVZD-30ac1ade.js +1 -0
  9. package/dist/browser/chunks/arrows-VjxlU-jv-2e17c192.js +1 -0
  10. package/dist/browser/chunks/base-dfd67c41.js +1 -0
  11. package/dist/browser/chunks/braille-BeWC_Ruq-a3bb8ef9.js +1 -0
  12. package/dist/browser/chunks/braille-d-Dk6J96GO-d832bfbf.js +1 -0
  13. package/dist/browser/chunks/browser-a3c32178.js +36 -0
  14. package/dist/browser/chunks/calculator-element-271c142f.js +9 -0
  15. package/dist/browser/chunks/calligraphic-Cew9cU3x-04cf0735.js +1 -0
  16. package/dist/browser/chunks/cherokee-Cny3FYho-4da7d2f3.js +1 -0
  17. package/dist/browser/chunks/classPrivateFieldGet2-338e0179.js +1 -0
  18. package/dist/browser/chunks/custom-element-define-2a92deb0.js +1 -0
  19. package/dist/browser/chunks/cyrillic-CfCDulXU-5550df0b.js +1 -0
  20. package/dist/browser/chunks/cyrillic-ss-lU7bNGG9-12eb0188.js +1 -0
  21. package/dist/browser/chunks/defineProperty-a20a667d.js +1 -0
  22. package/dist/browser/chunks/devanagari-CDIz2h-r-18c38725.js +1 -0
  23. package/dist/browser/chunks/dist-41b39e7f.js +1 -0
  24. package/dist/browser/chunks/dist-59132a53.js +1 -0
  25. package/dist/browser/chunks/dist-60d7afef.js +1 -0
  26. package/dist/browser/chunks/dist-ca9b9622.js +1 -0
  27. package/dist/browser/chunks/double-struck-BpJEQk8y-500ce8dd.js +1 -0
  28. package/dist/browser/chunks/en-5ff22e17.js +1 -0
  29. package/dist/browser/chunks/es-a0ba6cb6.js +1 -0
  30. package/dist/browser/chunks/focus-trap-44913bf3.js +1 -0
  31. package/dist/browser/chunks/fraktur-rLEq9DEH-44cc14d8.js +1 -0
  32. package/dist/browser/chunks/greek-BlraJTyL-90ce8924.js +1 -0
  33. package/dist/browser/chunks/greek-ss-D-EN2PK0-91610739.js +1 -0
  34. package/dist/browser/chunks/hebrew-GiQZeybp-b583f555.js +1 -0
  35. package/dist/browser/chunks/latin-b-BhEnC7R2-d13e06ff.js +1 -0
  36. package/dist/browser/chunks/latin-bi-DqiIKv3U-1dec8705.js +1 -0
  37. package/dist/browser/chunks/latin-i-B1xtwaE1-21637466.js +1 -0
  38. package/dist/browser/chunks/latin-xfWFlLkD-5bcea5cf.js +1 -0
  39. package/dist/browser/chunks/logger-8b07fb72.js +1 -0
  40. package/dist/browser/chunks/marrows-DD1NgMQi-15b63755.js +1 -0
  41. package/dist/browser/chunks/math-DpWn1mbG-38eeb914.js +1 -0
  42. package/dist/browser/chunks/math-rendering-ready-9a0fd90a.js +1 -0
  43. package/dist/browser/chunks/mathjax-D2JHb_R_-64780dc5.js +232 -0
  44. package/dist/browser/chunks/module-0191e321.js +74 -0
  45. package/dist/browser/chunks/module-shim-58659a86.js +0 -0
  46. package/dist/browser/chunks/module-shim-b4470740.js +12 -0
  47. package/dist/browser/chunks/monospace-D116QD2a-98d484fd.js +1 -0
  48. package/dist/browser/chunks/monospace-ex-DcXpouKS-456b403c.js +1 -0
  49. package/dist/browser/chunks/monospace-l-Ct5wkMDs-f34a4a9e.js +1 -0
  50. package/dist/browser/chunks/mshapes-DCp86WSX-c0055952.js +1 -0
  51. package/dist/browser/chunks/nds-icon-button-d602f784.js +194 -0
  52. package/dist/browser/chunks/nl-NL-364d61b9.js +1 -0
  53. package/dist/browser/chunks/nl-NL-8b7e6d4b.js +1 -0
  54. package/dist/browser/chunks/overlay-containment-edaaff13.js +1 -0
  55. package/dist/browser/chunks/overlay-placement-e8058232.js +1 -0
  56. package/dist/browser/chunks/phonetics-BwOCw2Y9-d2e3af59.js +1 -0
  57. package/dist/browser/chunks/phonetics-ss-CRtMn02f-579b6135.js +1 -0
  58. package/dist/browser/chunks/pie-api-client-687c319a.js +1 -0
  59. package/dist/browser/chunks/pie-tool-calculator-cortex-0626bc24.js +9 -0
  60. package/dist/browser/chunks/pie-tool-calculator-geogebra-561236cb.js +9 -0
  61. package/dist/browser/chunks/pointer-gesture-ce75f0a7.js +1 -0
  62. package/dist/browser/chunks/preload-helper-6ad28da3.js +1 -0
  63. package/dist/browser/chunks/provider-4c704118.js +1 -0
  64. package/dist/browser/chunks/rolldown-runtime-1287ba31.js +1 -0
  65. package/dist/browser/chunks/runtime-C7H1jS4E-64772f5e.js +8413 -0
  66. package/dist/browser/chunks/sanitize-svg-icon-b9082bba.js +3 -0
  67. package/dist/browser/chunks/sans-serif-BYPZKlE9-2efdbcd9.js +1 -0
  68. package/dist/browser/chunks/sans-serif-b-B0kRKiC--b5530dce.js +1 -0
  69. package/dist/browser/chunks/sans-serif-bi-DXWul6mu-5370dba4.js +1 -0
  70. package/dist/browser/chunks/sans-serif-ex-Boux1kMP-aa178f31.js +1 -0
  71. package/dist/browser/chunks/sans-serif-i-676RFaSO-2db54474.js +1 -0
  72. package/dist/browser/chunks/sans-serif-r-DrN9xdZt-0fc72eea.js +1 -0
  73. package/dist/browser/chunks/script-0ohehnXc-526904f4.js +1 -0
  74. package/dist/browser/chunks/shapes-BG47NodJ-d59b0eca.js +1 -0
  75. package/dist/browser/chunks/src-BcptuNS5-ed25d7fd.js +191 -0
  76. package/dist/browser/chunks/sre-engine-wf9s43gg-f09289c5.js +53 -0
  77. package/dist/browser/chunks/symbols-BqnUxf_t-83087e87.js +1 -0
  78. package/dist/browser/chunks/symbols-b-i-eg9k5hmF-9c461ac2.js +1 -0
  79. package/dist/browser/chunks/tool-annotation-toolbar-997438b4.js +248 -0
  80. package/dist/browser/chunks/tool-answer-eliminator-35483abd.js +13 -0
  81. package/dist/browser/chunks/tool-color-scheme-b7de5cdf.js +26 -0
  82. package/dist/browser/chunks/tool-dictionary-cecff3b4.js +7 -0
  83. package/dist/browser/chunks/tool-graph-cb0338e8.js +11 -0
  84. package/dist/browser/chunks/tool-host-contract-b93b482c.js +1 -0
  85. package/dist/browser/chunks/tool-line-reader-f8ef3c6a.js +62 -0
  86. package/dist/browser/chunks/tool-periodic-table-43b133b8.js +153 -0
  87. package/dist/browser/chunks/tool-picture-dictionary-33721e91.js +4 -0
  88. package/dist/browser/chunks/tool-protractor-23f77028.js +17 -0
  89. package/dist/browser/chunks/tool-ruler-1d9a03a6.js +15 -0
  90. package/dist/browser/chunks/tool-tts-inline-98c2ce7a.js +179 -0
  91. package/dist/browser/chunks/variants-2LRNhOUP-966fc49d.js +1 -0
  92. package/dist/browser/chunks/versioned-tag-54a76be9.js +1 -0
  93. package/dist/browser/pie-section-player.js +1613 -0
  94. package/dist/browser.d.ts +10 -0
  95. package/dist/chunks/ItemToolBar-wr2myaah-1287ba31.js +28 -0
  96. package/dist/chunks/module-shim-58659a86.js +2129 -0
  97. package/dist/chunks/{nl-NL-9312c316.js → nl-NL-364d61b9.js} +8 -2
  98. package/dist/chunks/sre-engine-wf9s43gg-f09289c5.js +8 -0
  99. package/dist/components/shared/composition.d.ts +0 -1
  100. package/dist/components/shared/layout-host-methods.d.ts +400 -0
  101. package/dist/components/shared/missing-tool-providers.d.ts +16 -0
  102. package/dist/components/shared/player-preload.d.ts +14 -10
  103. package/dist/contracts/host-hooks.d.ts +4 -5
  104. package/dist/contracts/host-hooks.js +0 -0
  105. package/dist/contracts/layout-contract.js +0 -0
  106. package/dist/contracts/layout-parity-metadata.js +87 -0
  107. package/dist/contracts/public-events.d.ts +14 -15
  108. package/dist/contracts/public-events.js +12 -0
  109. package/dist/contracts/runtime-host-contract.js +0 -0
  110. package/dist/controllers/SectionController.d.ts +21 -0
  111. package/dist/controllers/toolkit-section-contracts.d.ts +1 -17
  112. package/dist/controllers/types.d.ts +17 -10
  113. package/dist/pie-section-player.js +19353 -37273
  114. package/dist/policies/index.d.ts +9 -2
  115. package/dist/policies/index.js +25 -0
  116. package/package.json +34 -29
  117. package/dist/chunks/module-a516757f.js +0 -73997
  118. package/dist/chunks/nl-NL-ef6dd604.js +0 -505
  119. package/dist/chunks/pie-api-client-22de9d9c.js +0 -161
  120. package/dist/chunks/rolldown-runtime-1287ba31.js +0 -20
  121. package/dist/chunks/sre-0162a7a9.js +0 -17637
  122. package/dist/contracts/stages.d.ts +0 -10
  123. package/dist/utils/z-index.d.ts +0 -5
@@ -0,0 +1,1613 @@
1
+ import{t as Ct}from"./chunks/rolldown-runtime-1287ba31.js";import{t as T}from"./chunks/defineProperty-a20a667d.js";import{a as ad,i as Le,n as Ce,r as je,t as S}from"./chunks/classPrivateFieldGet2-338e0179.js";import{_ as Ly,a as Ms,d as Zl,f as $u,g as Zs,h as ak,l as lk,m as X_,n as ck,p as Z_,s as Oy,u as dk}from"./chunks/tool-host-contract-b93b482c.js";import{a as ya,i as Y_,n as uk,r as J_,t as $h}from"./chunks/versioned-tag-54a76be9.js";import{n as Yl,t as Ys}from"./chunks/logger-8b07fb72.js";import{t as br}from"./chunks/preload-helper-6ad28da3.js";import{n as Q_,r as Ny,t as Dy}from"./chunks/custom-element-define-2a92deb0.js";import{a as Nw,c as Am,d as eP,i as tP,l as rP,n as Dw,o as nP,r as Mm,s as iP,t as oP,u as fk}from"./chunks/nds-icon-button-d602f784.js";import{a as sP,i as xa,n as aP,o as jw,r as lP}from"./chunks/provider-4c704118.js";import{t as bf}from"./chunks/sanitize-svg-icon-b9082bba.js";import{t as cP}from"./chunks/pointer-gesture-ce75f0a7.js";import{i as dP,n as uP,r as fP,t as hP}from"./chunks/focus-trap-44913bf3.js";import{r as pP,t as mP}from"./chunks/ItemToolBar-wr2myaah-2ce4b643.js";import{C as jy,D as jp,E as gP,O as Lu,S as hk,T as To,_ as vP,b as Te,c as yP,d as bP,f as wP,g as pk,h as mk,i as gk,l as Ac,m as Ou,n as By,o as SP,p as IP,s as kP,t as TP,u as vk,v as Bp,w as du,x as yk,y as EP}from"./chunks/math-rendering-ready-9a0fd90a.js";if(typeof window<"u"){var Bw,Fw;((Bw=(Fw=window).__svelte??(Fw.__svelte={})).v??(Bw.v=new Set)).add("5")}var Uc={},mn=Symbol("uninitialized");var CP="http://www.w3.org/2000/svg";var Nu=Array.isArray,xP=Array.prototype.indexOf,Lh=Array.prototype.includes,Fp=Array.from,Oh=Object.keys,uu=Object.defineProperty,gl=Object.getOwnPropertyDescriptor,bk=Object.getOwnPropertyDescriptors,RP=Object.prototype,_P=Array.prototype,Fy=Object.getPrototypeOf,Hw=Object.isExtensible,PP=()=>{};function AP(e){for(var t=0;t<e.length;t++)e[t]()}function wk(){var e,t;return{promise:new Promise((r,n)=>{e=r,t=n}),resolve:e,reject:t}}var MP=1<<24,co=1024,Ki=2048,Jl=4096,Hy=8192,$P=16384,zy=32768,zw=1<<25,Du=65536,IV=1<<17,kV=1<<18,ld=1<<19,LP=1<<20,Yd=1<<25,Ww=1<<21,OP=1<<22,Nh=1<<23,Os=Symbol("$state"),Sk=Symbol("component"),Ik=Symbol("legacy props"),NP=Symbol(""),DP=Symbol("proxy path"),Bg=Symbol("attributes"),Fg=Symbol("class"),Hg=Symbol("style"),ch=Symbol("text"),kk=Symbol("form reset");var ju=new class extends Error{constructor(...t){super(...t),T(this,"name","StaleReactionError"),T(this,"message","The reaction that called `getAbortSignal()` was re-run or destroyed")}},Hp=!!globalThis.document?.contentType&&globalThis.document.contentType.includes("xml");function jP(){console.warn("https://svelte.dev/e/derived_inert")}function zp(e){console.warn("https://svelte.dev/e/hydration_mismatch")}function BP(){console.warn("https://svelte.dev/e/select_multiple_invalid_value")}function FP(){console.warn("https://svelte.dev/e/svelte_boundary_reset_noop")}var It=!1;function di(e){It=e}var or;function Fn(e){if(e===null)throw zp(),Uc;return or=e}function $l(){return Fn(ks(or))}function Kt(e){if(It){if(ks(or)!==null)throw zp(),Uc;or=e}}function HP(e=1){if(It){for(var t=e,r=or;t--;)r=ks(r);or=r}}function Dh(e=!0){for(var t=0,r=or;;){if(r.nodeType===8){var n=r.data;if(n==="]"){if(t===0)return r;t-=1}else(n==="["||n==="[!"||n[0]==="["&&!isNaN(Number(n.slice(1))))&&(t+=1)}var i=ks(r);e&&r.remove(),r=i}}function Tk(e){if(!e||e.nodeType!==8)throw zp(),Uc;return e.data}function Ek(e){return e===this.v}function Ck(e,t){return e!=e?t==t:e!==t||e!==null&&typeof e=="object"||typeof e=="function"}function xk(e){return!Ck(e,this.v)}function Wp(){throw new Error("https://svelte.dev/e/invalid_default_snippet")}function Up(e){throw new Error("https://svelte.dev/e/lifecycle_outside_component")}function zP(){throw new Error("https://svelte.dev/e/set_context_after_init")}function WP(){throw new Error("https://svelte.dev/e/async_derived_orphan")}function UP(e,t,r){throw new Error("https://svelte.dev/e/each_key_duplicate")}function qP(e){throw new Error("https://svelte.dev/e/effect_in_teardown")}function VP(){throw new Error("https://svelte.dev/e/effect_in_unowned_derived")}function GP(e){throw new Error("https://svelte.dev/e/effect_orphan")}function KP(){throw new Error("https://svelte.dev/e/effect_update_depth_exceeded")}function XP(){throw new Error("https://svelte.dev/e/hydration_failed")}function ZP(e){throw new Error("https://svelte.dev/e/props_invalid_value")}function YP(){throw new Error("https://svelte.dev/e/state_descriptors_fixed")}function JP(){throw new Error("https://svelte.dev/e/state_prototype_fixed")}function QP(){throw new Error("https://svelte.dev/e/state_unsafe_mutation")}function eA(){throw new Error("https://svelte.dev/e/svelte_boundary_reset_onerror")}var Js=!1,Bu=!1;function Uw(e,t){return e.label=t,tA(e.v,t),e}function tA(e,t){return e?.[DP]?.(t),e}function rA(e){let t=e.p;for(;t!==null&&t.c===null;)t=t.p;return t?.c??null}function nA(e,t){return e===null&&Up(t),e.c??(e.c=new Map(rA(e)||void 0))}var Mr=null;function qc(e){Mr=e}function iA(e,t){const r=nA(Mr,"setContext");if(Js){var n=Nt.f;!tr&&(n&32)!==0&&!Mr.i||zP()}return r.set(e,t),t}function un(e,t=!1,r){Mr={p:Mr,i:!1,c:null,e:null,s:e,x:null,r:Nt,l:Bu&&!t?{s:null,u:null,$:[]}:null}}function fn(e){var t=Mr,r=t.e;if(r!==null){t.e=null;for(var n of r)Yk(n)}return e!==void 0&&(t.x=e),t.i=!0,Mr=t.p,Wy(e)}function Wy(e={}){return uu(e,Sk,{value:!0}),e}function Fu(){return!Bu||Mr!==null&&Mr.l===null}var il=[];function Rk(){var e=il;il=[],AP(e)}function Vo(e){if(il.length===0&&!Jd){var t=il;queueMicrotask(()=>{t===il&&Rk()})}il.push(e)}function oA(){for(;il.length>0;)Rk()}var sA=~(Ki|Jl|co);function sn(e,t){e.f=e.f&sA|t}function Uy(e){(e.f&512)!==0||e.deps===null?sn(e,co):sn(e,Jl)}function _k(e,t,r){(e.f&2048)!==0?t.add(e):(e.f&4096)!==0&&r.add(e),sn(e,co)}function aA(e,t){if(t){const r=document.body;e.autofocus=!0,Vo(()=>{document.activeElement===r&&e.focus()})}}var qw=!1;function lA(){qw||(qw=!0,document.addEventListener("reset",e=>{Promise.resolve().then(()=>{if(!e.defaultPrevented)for(const t of e.target.elements)t[kk]?.()})},{capture:!0}))}function Hu(e){var t=tr,r=Nt;Ri(null),uo(null);try{return e()}finally{Ri(t),uo(r)}}function Pk(e,t,r,n){const i=Fu()?fu:qy;var o=e.filter(p=>!p.settled),s=t.map(i);if(r.length===0&&o.length===0){n(s);return}var a=Nt,l=cA(),d=o.length===1?o[0].promise:o.length>1?Promise.all(o.map(p=>p.promise)):null;function c(p){if((a.f&16384)===0){l();try{n([...s,...p])}catch(g){gs(g,a)}jh()}}var u=Ak();if(r.length===0){d.then(()=>c([])).finally(u);return}function f(){Promise.all(r.map(p=>uA(p))).then(c).catch(p=>gs(p,a)).finally(u)}d?d.then(()=>{l(),f(),jh()}):f()}function cA(){var e=Nt,t=tr,r=Mr,n=Ut;if(0)var i;return function(s=!0){uo(e),Ri(t),qc(r),s&&(e.f&16384)===0&&(n?.activate(),n?.apply())}}var dA=!1;function jh(e=!0){dA=!1,uo(null),Ri(null),qc(null),e&&Ut?.deactivate()}function Ak(){var e=Nt,t=e.b,r=Ut,n=!!t?.is_rendered();return t?.update_pending_count(1,r),r.increment(n,e),()=>{t?.update_pending_count(-1,r),r.decrement(n,e)}}function fu(e){var t=2|Ki;return Nt!==null&&(Nt.f|=ld),{ctx:Mr,deps:null,effects:null,equals:Ek,f:t,fn:e,reactions:null,rv:0,v:mn,wv:0,parent:Nt,ac:null}}var Nd=Symbol("obsolete");function uA(e,t,r){let n=Nt;n===null&&WP();var i=void 0,o=Ol(mn),s=!tr,a=new Set;return RA(()=>{var l=Nt,d=wk();i=d.promise;try{Promise.resolve(e()).then(d.resolve,p=>{p!==ju&&d.reject(p)}).finally(jh)}catch(p){d.reject(p),jh()}var c=Ut;if(s){if((l.f&32768)!==0)var u=Ak();if(n.b?.is_rendered())c.async_deriveds.get(l)?.reject(Nd);else for(const p of a.values())p.reject(Nd);a.add(d),c.async_deriveds.set(l,d)}const f=(p,g=void 0)=>{u?.(),a.delete(d),g!==Nd&&(c.activate(),g?(o.f|=Nh,Vc(o,g)):((o.f&8388608)!==0&&(o.f^=Nh),Vc(o,p)),c.deactivate())};d.promise.then(f,p=>f(null,p||"unknown"))}),Vp(()=>{for(const l of a)l.reject(Nd)}),new Promise(l=>{function d(c){function u(){c===i?l(o):d(i)}c.then(u,u)}d(i)})}function ee(e){const t=fu(e);return Js||nT(t),t}function qy(e){const t=fu(e);return t.equals=xk,t}function fA(e){var t=e.effects;if(t!==null){e.effects=null;for(var r=0;r<t.length;r+=1)Hn(t[r])}}function Vy(e){var t,r=Nt,n=e.parent;if(!zs&&n!==null&&e.v!==mn&&(n.f&24576)!==0)return jP(),e.v;uo(n);try{fA(e),t=aT(e)}finally{uo(r)}return t}function Mk(e){var t=Vy(e);if(!e.equals(t)&&(e.wv=oT(),(!Ut?.is_fork||e.deps===null)&&(Ut!==null?(Ut.capture(e,t,!0),zg?.capture(e,t,!0)):e.v=t,e.deps===null))){sn(e,co);return}zs||(ai!==null?(Xy()||Ut?.is_fork)&&ai.set(e,t):Uy(e))}function hA(e){if(e.effects!==null)for(const t of e.effects)(t.teardown||t.ac)&&(t.teardown?.(),t.ac!==null&&Hu(()=>{t.ac.abort(ju),t.ac=null}),t.fn!==null&&(t.teardown=PP),pu(t,0),Zy(t))}function $k(e){if(e.effects!==null)for(const t of e.effects)t.teardown&&t.fn!==null&&Gc(t)}var Lk,Bh=null,yc=null,Ut=null,zg=null,ai=null,Wg=null,Jd=!1,$m=!1,hu=null,Fh=null,Ok=0;var pA=1,Hh=new WeakMap,vl=new WeakMap,ol=new WeakMap,zh=new WeakMap,wf=new WeakMap,bc=new WeakMap,Za=new WeakMap,Dd=new WeakMap,Eo=new WeakMap,Ug=new WeakMap,Ll=new WeakMap,Ns=new WeakMap,pa=new WeakMap,dh=new WeakMap,jd=new WeakMap,Jr=new WeakSet,Ql=class Nk{constructor(){ad(this,Jr),T(this,"id",pA++),Le(this,Hh,!1),T(this,"linked",!0),Le(this,vl,null),Le(this,ol,null),T(this,"async_deriveds",new Map),T(this,"current",new Map),T(this,"previous",new Map),Le(this,zh,new Set),Le(this,wf,new Set),Le(this,bc,0),Le(this,Za,new Map),Le(this,Dd,null),Le(this,Eo,[]),Le(this,Ug,[]),Le(this,Ll,new Set),Le(this,Ns,new Set),Le(this,pa,new Map),Le(this,dh,new Set),T(this,"is_fork",!1),Le(this,jd,!1),yc===null?Bh=yc=this:(Ce(ol,yc,this),Ce(vl,this,yc)),yc=this}skip_effect(t){S(pa,this).has(t)||S(pa,this).set(t,{d:[],m:[]}),S(dh,this).delete(t)}unskip_effect(t,r=n=>this.schedule(n)){var n=S(pa,this).get(t);if(n){S(pa,this).delete(t);for(var i of n.d)sn(i,Ki),r(i);for(i of n.m)sn(i,Jl),r(i)}S(dh,this).add(t)}capture(t,r,n=!1){t.v!==mn&&!this.previous.has(t)&&this.previous.set(t,t.v),(t.f&8388608)===0&&(this.current.set(t,[r,n]),ai?.set(t,r)),this.is_fork||(t.v=r)}activate(){Ut=this}deactivate(){Ut=null,ai=null}flush(){try{$m=!0,Ut=this,je(Jr,this,Wh).call(this)}finally{Ok=0,Wg=null,hu=null,Fh=null,$m=!1,Ut=null,ai=null,ms.clear()}}discard(){for(const t of S(wf,this))t(this);S(wf,this).clear();for(const t of this.async_deriveds.values())t.reject(Nd);je(Jr,this,Uh).call(this),S(Dd,this)?.resolve()}register_created_effect(t){S(Ug,this).push(t)}increment(t,r){if(Ce(bc,this,S(bc,this)+1),t){let n=S(Za,this).get(r)??0;S(Za,this).set(r,n+1)}}decrement(t,r){if(Ce(bc,this,S(bc,this)-1),t){let n=S(Za,this).get(r)??0;n===1?S(Za,this).delete(r):S(Za,this).set(r,n-1)}S(jd,this)||(Ce(jd,this,!0),Vo(()=>{Ce(jd,this,!1),this.linked&&this.flush()}))}transfer_effects(t,r){for(const n of t)S(Ll,this).add(n);for(const n of r)S(Ns,this).add(n);t.clear(),r.clear()}oncommit(t){S(zh,this).add(t)}ondiscard(t){S(wf,this).add(t)}settled(){return(S(Dd,this)??Ce(Dd,this,wk())).promise}static ensure(){if(Ut===null){const t=Ut=new Nk;!$m&&!Jd&&Vo(()=>{S(Hh,t)||t.flush()})}return Ut}apply(){if(!Js||!this.is_fork&&S(vl,this)===null&&S(ol,this)===null){ai=null;return}ai=new Map;for(const[r,[n]]of this.current)ai.set(r,n);for(let r=Bh;r!==null;r=S(ol,r))if(!(r===this||r.is_fork)){var t=!1;if(r.id<this.id){for(const[n,[,i]]of r.current)if(!i&&this.current.has(n)){t=!0;break}}if(!t)for(const[n,i]of r.previous)ai.has(n)||ai.set(n,i)}}schedule(t){if(Wg=t,t.b?.is_pending&&(t.f&16777228)!==0&&(t.f&32768)===0){t.b.defer_effect(t);return}S(Eo,this).push(t)}};Lk=Ql;function Vw(){if(this.is_fork)return!0;for(const r of S(Za,this).keys()){for(var e=r,t=!1;e.parent!==null;){if(S(pa,this).has(e)){t=!0;break}e=e.parent}if(!t)return!0}return!1}function Dk(){var e=[];for(const i of S(Eo,this))if(!((i.f&16384)!==0||(i.f&6144)===0)){for(var t=i,r=!1;t.parent!==null;){t=t.parent;var n=t.f;if((n&96)!==0){if((n&1024)===0){r=!0;break}t.f^=co}}r||e.push(t)}return Ce(Eo,this,[]),e}function Wh(){Ce(Hh,this,!0);for(const s of S(Ll,this))S(Ns,this).delete(s),sn(s,Ki),this.schedule(s);for(const s of S(Ns,this))sn(s,Jl),this.schedule(s);this.apply();for(var e=hu=[],t=[],r=Fh=[];S(Eo,this).length>0;){Ok++>1e3&&(je(Jr,this,Uh).call(this),yA());for(const s of je(Jr,this,Dk).call(this))try{je(Jr,this,jk).call(this,s,e,t)}catch(a){throw Hk(s),je(Jr,this,Vw).call(this)||this.discard(),a}}if(Ut=null,r.length>0){var n=Lk.ensure();for(const s of r)n.schedule(s)}if(hu=null,Fh=null,je(Jr,this,Vw).call(this)){je(Jr,this,Bd).call(this,t),je(Jr,this,Bd).call(this,e);for(const[s,a]of S(pa,this))Fk(s,a);r.length>0&&je(Jr,Ut,Wh).call(Ut);return}const i=je(Jr,this,mA).call(this);if(i){je(Jr,this,Bd).call(this,t),je(Jr,this,Bd).call(this,e),je(Jr,i,gA).call(i,this);return}S(Ll,this).clear(),S(Ns,this).clear();for(const s of S(zh,this))s(this);S(zh,this).clear(),zg=this,Gw(t),Gw(e),zg=null,S(Dd,this)?.resolve();var o=Ut;if(S(bc,this)===0&&(S(Eo,this).length===0||o!==null)&&(je(Jr,this,Uh).call(this),Js&&(je(Jr,this,vA).call(this),Ut=o)),S(Eo,this).length>0)if(o!==null){for(const s of S(Eo,this))S(Eo,o).push(s);Ce(Eo,this,[])}else o=this;o!==null&&(ms.clear(),je(Jr,o,Wh).call(o))}function jk(e,t,r){e.f^=co;for(var n=e.first;n!==null;){var i=n.f,o=(i&96)!==0;if(!(o&&(i&1024)!==0||(i&8192)!==0||S(pa,this).has(n))&&n.fn!==null){o?n.f^=co:(i&4)!==0?t.push(n):Js&&(i&16777224)!==0?r.push(n):qu(n)&&((i&16)!==0&&S(Ns,this).add(n),Gc(n));var s=n.first;if(s!==null){n=s;continue}}for(;n!==null;){var a=n.next;if(a!==null){n=a;break}n=n.parent}}}function mA(){for(var e=S(vl,this);e!==null;){if(!e.is_fork){for(const[t,[,r]]of this.current)if(e.current.has(t)&&!r)return e}e=S(vl,e)}return null}function gA(e){for(const[r,n]of e.current)!this.previous.has(r)&&e.previous.has(r)&&this.previous.set(r,e.previous.get(r)),this.current.set(r,n);for(const[r,n]of e.async_deriveds){const i=this.async_deriveds.get(r);i&&n.promise.then(i.resolve).catch(i.reject)}e.async_deriveds.clear(),this.transfer_effects(S(Ll,e),S(Ns,e));const t=r=>{var n=r.reactions;if(n!==null&&!((r.f&2)!==0&&(r.f&6144)===0))for(const s of n){var i=s.f;if((i&2)!==0)t(s);else{var o=s;i&4194320&&!this.async_deriveds.has(o)&&(S(Ns,this).delete(o),sn(o,Ki),this.schedule(o))}}};for(const r of this.current.keys())t(r);this.oncommit(()=>e.discard()),je(Jr,e,Uh).call(e),Ut=this,je(Jr,this,Wh).call(this)}function Bd(e){for(var t=0;t<e.length;t+=1)_k(e[t],S(Ll,this),S(Ns,this))}function vA(){for(let c=Bh;c!==null;c=S(ol,c)){var e=c.id<this.id,t=[];for(const[u,[f,p]]of this.current){if(c.current.has(u)){var r=c.current.get(u)[0];if(e&&f!==r)c.current.set(u,[f,p]);else continue}t.push(u)}if(e)for(const[u,f]of this.async_deriveds){const p=c.async_deriveds.get(u);p&&f.promise.then(p.resolve).catch(p.reject)}var n=[...c.current.keys()].filter(u=>!c.current.get(u)[1]);if(!(!S(Hh,c)||n.length===0)){var i=n.filter(u=>!this.current.has(u));if(i.length===0)e&&c.discard();else if(t.length>0){if(e)for(const u of S(dh,this))c.unskip_effect(u,f=>{(f.f&4194320)!==0?c.schedule(f):je(Jr,c,Bd).call(c,[f])});c.activate();var o=new Set,s=new Map;for(var a of t)Bk(a,i,o,s);s=new Map;var l=[...c.current].filter(([u,f])=>{const p=this.current.get(u);return p?p[0]!==f[0]||p[1]!==f[1]:!0}).map(([u])=>u);if(l.length>0)for(const u of S(Ug,this))(u.f&155648)===0&&Gy(u,l,s)&&((u.f&4194320)!==0?(sn(u,Ki),c.schedule(u)):S(Ll,c).add(u));if(S(Eo,c).length>0&&!S(jd,c)){c.apply();for(var d of je(Jr,c,Dk).call(c))je(Jr,c,jk).call(c,d,[],[])}c.deactivate()}}}}function Uh(){if(this.linked){var e=S(vl,this),t=S(ol,this);e===null?Bh=t:Ce(ol,e,t),t===null?yc=e:Ce(vl,t,e),this.linked=!1}}function R(e){var t=Jd;Jd=!0;try{var r;for(e&&(Ut!==null&&!Ut.is_fork&&Ut.flush(),r=e());;){if(oA(),Ut===null)return r;Ut.flush()}}finally{Jd=t}}function yA(){if(0){var e;for(const r of Ut.current.keys())for(const[n,i]of r.updated??[])var t}try{KP()}catch(r){gs(r,Wg)}}var ss=null;function Gw(e){var t=e.length;if(t!==0){for(var r=0;r<t;){var n=e[r++];if((n.f&24576)===0&&qu(n)&&(ss=new Set,Gc(n),n.deps===null&&n.first===null&&n.nodes===null&&n.teardown===null&&n.ac===null&&eT(n),ss?.size>0)){ms.clear();for(const i of ss){if((i.f&24576)!==0)continue;const o=[i];let s=i.parent;for(;s!==null;)ss.has(s)&&(ss.delete(s),o.push(s)),s=s.parent;for(let a=o.length-1;a>=0;a--){const l=o[a];(l.f&24576)===0&&Gc(l)}}ss.clear()}}ss=null}}function Bk(e,t,r,n){if(!r.has(e)&&(r.add(e),e.reactions!==null))for(const i of e.reactions){const o=i.f;(o&2)!==0?Bk(i,t,r,n):(o&4194320)!==0&&(o&2048)===0&&Gy(i,t,n)&&(sn(i,Ki),Ky(i))}}function Gy(e,t,r){const n=r.get(e);if(n!==void 0)return n;if(e.deps!==null)for(const i of e.deps){if(Lh.call(t,i))return!0;if((i.f&2)!==0&&Gy(i,t,r))return r.set(i,!0),!0}return r.set(e,!1),!1}function Ky(e){Ut.schedule(e)}function Fk(e,t){if(!((e.f&32)!==0&&(e.f&1024)!==0)){(e.f&2048)!==0?t.d.push(e):(e.f&4096)!==0&&t.m.push(e),sn(e,co);for(var r=e.first;r!==null;)Fk(r,t),r=r.next}}function Hk(e){sn(e,co);for(var t=e.first;t!==null;)Hk(t),t=t.next}var qh=new Set,ms=new Map;var zk=!1;function Ol(e,t){var r={f:0,v:e,reactions:null,equals:Ek,rv:0,wv:0};return r}function He(e,t){const r=Ol(e,t);return nT(r),r}function Wk(e,t=!1,r=!0){const n=Ol(e);if(t||(n.equals=xk),Bu&&r&&Mr!==null&&Mr.l!==null){var i;((i=Mr.l).s??(i.s=[])).push(n)}return n}function be(e,t,r=!1){tr!==null&&(!_o||(tr.f&131072)!==0)&&Fu()&&(tr.f&4325394)!==0&&(No===null||!No.has(e))&&QP();let n=r?Ti(t):t;return Vc(e,n,Fh)}var el=null,qg=0;function Vc(e,t,r=null){if(!e.equals(t)){zs?ms.set(e,t):ms.has(e)||ms.set(e,e.v);var n=Ql.ensure();if(n.capture(e,t),(e.f&2)!==0){const i=e;(e.f&2048)!==0&&Vy(i),ai===null&&Uy(i)}e.wv=oT(),el=null,qg=0,Uk(e,Ki,r),el=null,Fu()&&Nt!==null&&(Nt.f&1024)!==0&&(Nt.f&96)===0&&(to===null?MA([e]):to.push(e)),!n.is_fork&&qh.size>0&&!zk&&bA()}return t}function bA(){zk=!1;for(const e of qh){(e.f&1024)!==0&&sn(e,Jl);let t;try{t=qu(e)}catch{t=!0}t&&Gc(e)}qh.clear()}function Qd(e){be(e,e.v+1)}function Uk(e,t,r){var n=e.reactions;if(n!==null){var i=Fu(),o=n.length;if(qg+=o,qg>1e5&&el===null&&(el=new Set),el!==null){if(el.has(e))return;el.add(e)}for(var s=0;s<o;s++){var a=n[s],l=a.f;if(!(!i&&a===Nt)){var d=(l&Ki)===0;if(d&&sn(a,t),(l&131072)!==0)qh.add(a);else if((l&2)!==0){var c=a;ai?.delete(c),Uk(c,Jl,r)}else if(d){var u=a;(l&16)!==0&&ss!==null&&ss.add(u),r!==null?r.push(u):Ky(u)}}}}}var wA=/^[a-zA-Z_$][a-zA-Z_$0-9]*$/;function Ti(e){if(typeof e!="object"||e===null||Os in e||Sk in e)return e;const t=Fy(e);if(t!==RP&&t!==_P)return e;var r=new Map,n=Nu(e),i=He(0),o=null,s=yl,a=u=>{if(yl===s)return u();var f=tr,p=yl;Ri(null),Yw(s);var g=u();return Ri(f),Yw(p),g};n&&r.set("length",He(e.length,o));var l="";let d=!1;function c(u){if(!d){d=!0,l=u,Uw(i,`${l} version`);for(const[f,p]of r)Uw(p,SA(l,f));d=!1}}return new Proxy(e,{defineProperty(u,f,p){(!("value"in p)||p.configurable===!1||p.enumerable===!1||p.writable===!1)&&YP();var g=r.get(f);return g===void 0?a(()=>{var v=He(p.value,o);return r.set(f,v),v}):be(g,p.value,!0),!0},deleteProperty(u,f){var p=r.get(f);if(p===void 0){if(f in u){const g=a(()=>He(mn,o));r.set(f,g),Qd(i)}}else be(p,mn),Qd(i);return!0},get(u,f,p){if(f===Os)return e;var g=r.get(f),v=f in u;if(g===void 0&&(!v||gl(u,f)?.writable)&&(g=a(()=>{var w=Ti(v?u[f]:mn),I=He(w,o);return I}),r.set(f,g)),g!==void 0){var b=h(g);return b===mn?void 0:b}return Reflect.get(u,f,p)},getOwnPropertyDescriptor(u,f){this.has?.(u,f);var p=Reflect.getOwnPropertyDescriptor(u,f),g=r.get(f);if(g!==void 0){var v=h(g);if(v===mn)return;if(p&&"value"in p)p.value=v;else return{enumerable:!0,configurable:!0,value:v,writable:!0}}return p},has(u,f){if(f===Os)return!0;var p=r.get(f),g=p!==void 0&&p.v!==mn||Reflect.has(u,f);return(p!==void 0||Nt!==null&&(!g||gl(u,f)?.writable))&&(p===void 0&&(p=a(()=>{var v=g?Ti(u[f]):mn,b=He(v,o);return b}),r.set(f,p)),h(p)===mn)?!1:g},set(u,f,p,g){var v=r.get(f),b=f in u;if(n&&f==="length")for(var w=p;w<v.v;w+=1){var I=r.get(w+"");I!==void 0?be(I,mn):w in u&&(I=a(()=>He(mn,o)),r.set(w+"",I))}if(v===void 0)(!b||gl(u,f)?.writable)&&(v=a(()=>He(void 0,o)),be(v,Ti(p)),r.set(f,v));else{b=v.v!==mn;var x=a(()=>Ti(p));be(v,x)}var C=Reflect.getOwnPropertyDescriptor(u,f);if(C?.set&&C.set.call(g,p),!b){if(n&&typeof f=="string"){var L=r.get("length"),E=Number(f);Number.isInteger(E)&&E>=L.v&&be(L,E+1)}Qd(i)}return!0},ownKeys(u){h(i);var f=Reflect.ownKeys(u).filter(v=>{var b=r.get(v);return b===void 0||b.v!==mn});for(var[p,g]of r)g.v!==mn&&!(p in u)&&f.push(p);return f},setPrototypeOf(){JP()}})}function SA(e,t){return typeof t=="symbol"?`${e}[Symbol(${t.description??""})]`:wA.test(t)?`${e}.${t}`:/^\d+$/.test(t)?`${e}[${t}]`:`${e}['${t}']`}function Kw(e){try{if(e!==null&&typeof e=="object"&&Os in e)return e[Os]}catch{}return e}function qk(e,t){return Object.is(Kw(e),Kw(t))}var Xw,IA,Vk,Gk,Kk;function Vg(){if(Xw===void 0){Xw=window,IA=document,Vk=/Firefox/.test(navigator.userAgent);var e=Element.prototype,t=Node.prototype,r=Text.prototype;Gk=gl(t,"firstChild").get,Kk=gl(t,"nextSibling").get,Hw(e)&&(e[Fg]=void 0,e[Bg]=null,e[Hg]=void 0,e.__e=void 0),Hw(r)&&(r[ch]=void 0)}}function Zn(e=""){return document.createTextNode(e)}function Hs(e){return Gk.call(e)}function ks(e){return Kk.call(e)}function Xt(e,t){if(!It)return Hs(e);var r=Hs(or);if(r===null)r=or.appendChild(Zn());else if(t&&r.nodeType!==3){var n=Zn();return r?.before(n),Fn(n),n}return t&&qp(r),Fn(r),r}function jn(e,t=!1){if(!It){var r=Hs(e);return r instanceof Comment&&r.data===""?ks(r):r}if(t){if(or?.nodeType!==3){var n=Zn();return or?.before(n),Fn(n),n}qp(or)}return or}function Ta(e,t=!1){if(!It)return Hs(e);var r=Xt(e,t);return Kt(e),r}function lr(e,t=1,r=!1){let n=It?or:e;for(var i;t--;)i=n,n=ks(n);if(!It)return n;if(r){if(n?.nodeType!==3){var o=Zn();return n===null?i?.after(o):n.before(o),Fn(o),o}qp(n)}return Fn(n),n}function Xk(e){e.textContent=""}function Zk(){return!Js||ss!==null?!1:(Nt.f&zy)!==0}function zu(e,t,r){return t==null||t==="http://www.w3.org/1999/xhtml"?r?document.createElement(e,{is:r}):document.createElement(e):r?document.createElementNS(t,e,{is:r}):document.createElementNS(t,e)}function qp(e){if(e.nodeValue.length<65536)return;let t=e.nextSibling;for(;t!==null&&t.nodeType===3;)t.remove(),e.nodeValue+=t.nodeValue,t=e.nextSibling}function kA(e){var t=Nt;if(t===null)return tr.f|=Nh,e;if((t.f&32768)===0&&(t.f&4)===0)throw e;gs(e,t)}function gs(e,t){if(!(t!==null&&(t.f&16384)!==0)){for(;t!==null;){if((t.f&128)!==0&&(t.f&33570816)===0){if((t.f&32768)===0)throw e;try{t.b.error(e);return}catch(r){e=r}}t=t.parent}throw e}}function TA(e){Nt===null&&(tr===null&&GP(e),VP()),zs&&qP(e)}function EA(e,t){var r=t.last;r===null?t.last=t.first=e:(r.next=e,e.prev=r,t.last=e)}function Ko(e,t){var r=Nt;r!==null&&(r.f&8192)!==0&&(e|=Hy);var n={ctx:Mr,deps:null,nodes:null,f:e|Ki|512,first:null,fn:t,last:null,next:null,parent:r,b:r&&r.b,prev:null,teardown:null,wv:0,ac:null};Ut?.register_created_effect(n);var i=n;if((e&4)!==0)hu!==null?hu.push(n):Ql.ensure().schedule(n);else if(t!==null){try{Gc(n)}catch(s){throw Hn(n),s}i.deps===null&&i.teardown===null&&i.nodes===null&&i.first===i.last&&(i.f&524288)===0&&(i=i.first,(e&16)!==0&&(e&65536)!==0&&i!==null&&(i.f|=Du))}if(i!==null&&(i.parent=r,r!==null&&EA(i,r),tr!==null&&(tr.f&2)!==0&&(e&64)===0)){var o=tr;(o.effects??(o.effects=[])).push(i)}return n}function Xy(){return tr!==null&&!_o}function Vp(e){const t=Ko(8,null);return sn(t,co),t.teardown=e,t}function ct(e){TA("$effect");var t=Nt.f;if(!tr&&(t&32)!==0&&Mr!==null&&!Mr.i){var r=Mr;(r.e??(r.e=[])).push(e)}else return Yk(e)}function Yk(e){return Ko(4|LP,e)}function CA(e){Ql.ensure();const t=Ko(64|ld,e);return()=>{Hn(t)}}function xA(e){Ql.ensure();const t=Ko(64|ld,e);return(r={})=>new Promise(n=>{r.outro?ec(t,()=>{Hn(t),n(void 0)}):(Hn(t),n(void 0))})}function Wu(e){return Ko(4,e)}function RA(e){return Ko(OP|ld,e)}function Gp(e,t=0){return Ko(8|t,e)}function q(e,t=[],r=[],n=[]){Pk(n,t,r,i=>{Ko(8,()=>{e(...i.map(h))})})}function Uu(e,t=0){var r=Ko(16|t,e);return r}function Jk(e,t=0){var r=Ko(MP|t,e);return r}function xi(e){return Ko(32|ld,e)}function Qk(e){var t=e.teardown;if(t!==null){const r=zs,n=tr;Zw(!0),Ri(null);try{t.call(null)}catch(i){gs(i,e.parent)}finally{Zw(r),Ri(n)}}}function Zy(e,t=!1){var r=e.first;for(e.first=e.last=null;r!==null;){const i=r.ac;i!==null&&Hu(()=>{i.abort(ju)});var n=r.next;(r.f&64)!==0?r.parent=null:Hn(r,t),r=n}}function _A(e){for(var t=e.first;t!==null;){var r=t.next;(t.f&32)===0&&Hn(t),t=r}}function Hn(e,t=!0){var r=!1;(t||(e.f&262144)!==0)&&e.nodes!==null&&e.nodes.end!==null&&(PA(e.nodes.start,e.nodes.end),r=!0),e.f|=zw,Zy(e,t&&!r),pu(e,0);var n=e.nodes&&e.nodes.t;if(n!==null)for(const o of n)o.stop();Qk(e),e.f^=zw,e.f|=$P;var i=e.parent;i!==null&&i.first!==null&&eT(e),e.next=e.prev=e.teardown=e.ctx=e.deps=e.fn=e.nodes=e.ac=e.b=null}function PA(e,t){for(;e!==null;){var r=e===t?null:ks(e);e.remove(),e=r}}function eT(e){var t=e.parent,r=e.prev,n=e.next;r!==null&&(r.next=n),n!==null&&(n.prev=r),t!==null&&(t.first===e&&(t.first=n),t.last===e&&(t.last=r))}function ec(e,t,r=!0){var n=[];e.f|=256,tT(e,n,!0);var i=()=>{r&&Hn(e),t&&t()},o=n.length;if(o>0){var s=()=>--o||i();for(var a of n)a.out(s)}else i()}function tT(e,t,r){if((e.f&8192)===0){e.f^=Hy;var n=e.nodes&&e.nodes.t;if(n!==null)for(const a of n)(a.is_global||r)&&t.push(a);for(var i=e.first;i!==null;){var o=i.next;if((i.f&64)===0){var s=(i.f&65536)!==0||(i.f&32)!==0&&(e.f&16)!==0;tT(i,t,s?r:!1)}i=o}}}function Vh(e){e.f&=-257,rT(e,!0)}function rT(e,t){if((e.f&256)===0&&(e.f&8192)!==0){e.f^=Hy,(e.f&1024)===0&&(sn(e,Ki),Ql.ensure().schedule(e));for(var r=e.first;r!==null;){var n=r.next,i=(r.f&65536)!==0||(r.f&32)!==0;rT(r,i?t:!1),r=n}var o=e.nodes&&e.nodes.t;if(o!==null)for(const s of o)(s.is_global||t)&&s.in()}}function Yy(e,t){if(e.nodes)for(var r=e.nodes.start,n=e.nodes.end;r!==null;){var i=r===n?null:ks(r);t.append(r),r=i}}var AA=null,uh=!1,zs=!1;function Zw(e){zs=e}var tr=null,_o=!1;function Ri(e){tr=e}var Nt=null;function uo(e){Nt=e}var No=null;function nT(e){tr!==null&&(!Js&&(tr.f&2097152)!==0||(tr.f&2)!==0)&&(No??(No=new Set)).add(e)}var Si=null,Di=0,to=null;function MA(e){to=e}var iT=1,sl=0,yl=sl;function Yw(e){yl=e}function oT(){return++iT}function qu(e){var t=e.f;if((t&2048)!==0)return!0;if((t&4096)!==0){for(var r=e.deps,n=r.length,i=0;i<n;i++){var o=r[i];if(qu(o)&&Mk(o),o.wv>e.wv)return!0}(t&512)!==0&&ai===null&&sn(e,co)}return!1}function sT(e,t,r=!0){var n=e.reactions;if(n!==null&&!(!Js&&No!==null&&No.has(e)))for(var i=0;i<n.length;i++){var o=n[i];(o.f&2)!==0?sT(o,t,!1):t===o&&(r?sn(o,Ki):(o.f&1024)!==0&&sn(o,Jl),Ky(o))}}function aT(e){var t=Si,r=Di,n=to,i=tr,o=No,s=Mr,a=_o,l=yl,d=e.f;Si=null,Di=0,to=null,tr=(d&96)===0?e:null,No=null,qc(e.ctx),_o=!1,yl=++sl,e.ac!==null&&(Hu(()=>{e.ac.abort(ju)}),e.ac=null);try{e.f|=Ww;var c=e.fn,u=c();e.f|=zy;var f=Jw(e);if(Fu()&&to!==null&&!_o&&f!==null&&(e.f&6146)===0)for(var p=0;p<to.length;p++)sT(to[p],e);if(i!==null&&i!==e){if(sl++,i.deps!==null)for(let g=0;g<r;g+=1)i.deps[g].rv=sl;if(t!==null)for(const g of t)g.rv=sl;to!==null&&(n===null?n=to:n.push(...to))}return(e.f&8388608)!==0&&(e.f^=Nh),u}catch(g){return Jw(e),kA(g)}finally{e.f^=Ww,Si=t,Di=r,to=n,tr=i,No=o,qc(s),_o=a,yl=l}}function Jw(e){var t=e.deps,r=Ut?.is_fork;if(Si!==null){var n;if(r||pu(e,Di),t!==null&&Di>0)for(t.length=Di+Si.length,n=0;n<Si.length;n++)t[Di+n]=Si[n];else e.deps=t=Si;if(Xy()&&(e.f&512)!==0)for(n=Di;n<t.length;n++){var i;((i=t[n]).reactions??(i.reactions=[])).push(e)}}else!r&&t!==null&&Di<t.length&&(pu(e,Di),t.length=Di);return t}function $A(e,t){let r=t.reactions;if(r!==null){var n=xP.call(r,e);if(n!==-1){var i=r.length-1;i===0?r=t.reactions=null:(r[n]=r[i],r.pop())}}if(r===null&&(t.f&2)!==0&&(Si===null||!Lh.call(Si,t))){var o=t;(o.f&512)!==0&&(o.f^=512),o.v!==mn&&Uy(o),o.ac!==null&&Hu(()=>{o.ac.abort(ju),o.ac=null,sn(o,Ki)}),hA(o),pu(o,0)}}function pu(e,t){var r=e.deps;if(r!==null)for(var n=t;n<r.length;n++)$A(e,r[n])}function Gc(e){var t=e.f;if((t&16384)===0){sn(e,co);var r=Nt,n=uh;if(Nt=e,uh=(t&96)===0,0)var i,o;try{(t&16777232)!==0?_A(e):Zy(e),Qk(e);var s=aT(e);if(e.teardown=typeof s=="function"?s:null,e.wv=iT,0)for(var a of e.deps);}finally{uh=n,Nt=r}}}function h(e){var t=(e.f&2)!==0;if(AA?.add(e),tr!==null&&!_o&&!(Nt!==null&&(Nt.f&16384)!==0)&&(No===null||!No.has(e))){var r=tr.deps;if((tr.f&2097152)!==0)e.rv<sl&&(e.rv=sl,Si===null&&r!==null&&r[Di]===e?Di++:Si===null?Si=[e]:Si.push(e));else{var n;(n=tr).deps??(n.deps=[]),Lh.call(tr.deps,e)||tr.deps.push(e);var i=e.reactions;i===null?e.reactions=[tr]:Lh.call(i,tr)||i.push(tr)}}if(0){if(!_o&&reactivity_loss_tracker&&Ut===null&&zg===null&&!reactivity_loss_tracker.warned&&(reactivity_loss_tracker.effect.f&2097152)===0&&!reactivity_loss_tracker.effect_deps.has(e))var o;if(tracing_mode_flag&&!_o&&tracing_expressions!==null&&tr!==null&&tracing_expressions.reaction===tr&&!e.trace){if(o)var s,a}}if(zs&&ms.has(e))return ms.get(e);if(t){var l=e;if(zs){var d=l.v;return((l.f&1024)===0&&l.reactions!==null||cT(l))&&(d=Vy(l)),ms.set(l,d),d}var c=(l.f&512)===0&&!_o&&tr!==null&&(uh||(tr.f&512)!==0),u=(l.f&zy)===0;qu(l)&&(c&&(l.f|=512),Mk(l)),c&&!u&&($k(l),lT(l))}if(ai?.has(e))return ai.get(e);if((e.f&8388608)!==0)throw e.v;return e.v}function lT(e){if(e.f|=512,e.deps!==null)for(const t of e.deps)(t.reactions??(t.reactions=[])).push(e),(t.f&2)!==0&&(t.f&512)===0&&($k(t),lT(t))}function cT(e){if(e.v===mn)return!0;if(e.deps===null)return!1;for(const t of e.deps)if(ms.has(t)||(t.f&2)!==0&&cT(t))return!0;return!1}function on(e){var t=_o;try{return _o=!0,e()}finally{_o=t}}function LA(e){if(!(typeof e!="object"||!e||e instanceof EventTarget)){if(Os in e)Gg(e);else if(!Array.isArray(e))for(let t in e){const r=e[t];typeof r=="object"&&r&&Os in r&&Gg(r)}}}function Gg(e,t=new Set){if(typeof e=="object"&&e!==null&&!(e instanceof EventTarget)&&!t.has(e)){t.add(e),e instanceof Date&&e.getTime();for(let n in e)try{Gg(e[n],t)}catch{}const r=Fy(e);if(r!==Object.prototype&&r!==Array.prototype&&r!==Map.prototype&&r!==Set.prototype&&r!==Date.prototype){const n=bk(r);for(let i in n){const o=n[i].get;if(o)try{o.call(e)}catch{}}}}}var Mc=Symbol("events"),dT=new Set,Kg=new Set;function uT(e,t,r,n={}){function i(o){if(n.capture||Xg.call(t,o),!o.cancelBubble)return Hu(()=>r?.call(this,o))}return e.startsWith("pointer")||e.startsWith("touch")||e==="wheel"?(i.__removed=!1,Vo(()=>{i.__removed||t.addEventListener(e,i,n)})):t.addEventListener(e,i,n),i}function Gn(e,t,r,n,i){var o={capture:n,passive:i},s=uT(e,t,r,o);(t===document.body||t===window||t===document||t instanceof HTMLMediaElement)&&Vp(()=>{s.__removed=!0,t.removeEventListener(e,s,o)})}function lo(e,t,r){(t[Mc]??(t[Mc]={}))[e]=r}function cd(e){for(var t=0;t<e.length;t++)dT.add(e[t]);for(var r of Kg)r(e)}var Lm=null,Om=!1;function Xg(e){var t=this,r=t.ownerDocument,n=e.type,i=e.composedPath?.()||[],o=i[0]||e.target;Lm=e,Om||(Om=!0,setTimeout(()=>{Om=!1,Lm=null}));var s=0,a=Lm===e&&e[Mc];if(a){var l=i.indexOf(a);if(l!==-1&&(t===document||t===window)){e[Mc]=t;return}var d=i.indexOf(t);if(d===-1)return;l<=d&&(s=l)}if(o=i[s]||e.target,o!==t){uu(e,"currentTarget",{configurable:!0,get(){return o||r}});var c=tr,u=Nt;Ri(null),uo(null);try{for(var f,p=[];o!==null&&o!==t;){try{var g=o[Mc]?.[n];g!=null&&(!o.disabled||e.target===o)&&g.call(o,e)}catch(v){f?p.push(v):f=v}if(e.cancelBubble)break;s++,o=s<i.length?i[s]:null}if(f){for(let v of p)queueMicrotask(()=>{throw v});throw f}}finally{e[Mc]=t,delete e.currentTarget,Ri(c),uo(u)}}}var OA=globalThis?.window?.trustedTypes&&globalThis.window.trustedTypes.createPolicy("svelte-trusted-html",{createHTML:e=>e});function NA(e){return OA?.createHTML(e)??e}function DA(e){var t=zu("template");return t.innerHTML=NA(e.replaceAll("<!>","<!---->")),t.content}function Ds(e,t){var r=Nt;r.nodes===null&&(r.nodes={start:e,end:t,a:null,t:null})}function Ht(e,t){var r=(t&1)!==0,n=(t&2)!==0,i,o=!e.startsWith("<!>");return()=>{if(It)return Ds(or,null),or;i===void 0&&(i=DA(o?e:"<!>"+e),r||(i=Hs(i)));var s=n||Vk?document.importNode(i,!0):i.cloneNode(!0);if(r){var a=Hs(s),l=s.lastChild;Ds(a,l)}else Ds(s,s);return s}}function fT(e=""){if(!It){var t=Zn(e+"");return Ds(t,t),t}var r=or;return r.nodeType!==3?(r.before(r=Zn()),Fn(r)):qp(r),Ds(r,r),r}function Nl(){if(It)return Ds(or,null),or;var e=document.createDocumentFragment(),t=document.createComment(""),r=Zn();return e.append(t,r),Ds(t,r),e}function ft(e,t){if(It){var r=Nt;((r.f&32768)===0||r.nodes.end===null)&&(r.nodes.end=or),$l();return}e!==null&&e.before(t)}function jA(e){return e.endsWith("capture")&&e!=="gotpointercapture"&&e!=="lostpointercapture"}var BA=["beforeinput","click","change","dblclick","contextmenu","focusin","focusout","input","keydown","keyup","mousedown","mousemove","mouseout","mouseover","mouseup","pointerdown","pointermove","pointerout","pointerover","pointerup","touchend","touchmove","touchstart"];function FA(e){return BA.includes(e)}var HA=["allowfullscreen","async","autofocus","autoplay","checked","controls","default","disabled","formnovalidate","indeterminate","inert","ismap","loop","multiple","muted","nomodule","novalidate","open","playsinline","readonly","required","reversed","seamless","selected","webkitdirectory","defer","disablepictureinpicture","disableremoteplayback"],zA={formnovalidate:"formNoValidate",ismap:"isMap",nomodule:"noModule",playsinline:"playsInline",readonly:"readOnly",defaultvalue:"defaultValue",defaultchecked:"defaultChecked",srcobject:"srcObject",novalidate:"noValidate",allowfullscreen:"allowFullscreen",disablepictureinpicture:"disablePictureInPicture",disableremoteplayback:"disableRemotePlayback"};function WA(e){return e=e.toLowerCase(),zA[e]??e}var EV=[...HA,"formNoValidate","isMap","noModule","playsInline","readOnly","value","volume","defaultValue","defaultChecked","srcObject","noValidate","allowFullscreen","disablePictureInPicture","disableRemotePlayback"],UA=["touchstart","touchmove"];function qA(e){return UA.includes(e)}var VA=["$state","$state.raw","$derived","$derived.by"],CV=[...VA,"$state.eager","$state.snapshot","$props","$props.id","$bindable","$effect","$effect.pre","$effect.tracking","$effect.root","$effect.pending","$inspect","$inspect().with","$inspect.trace","$host"],GA=["textarea","script","style","title"];function KA(e){return GA.includes(e)}function XA(e){let t=0,r=Ol(0),n;return()=>{Xy()&&(h(r),Gp(()=>(t===0&&(n=on(()=>e(()=>Qd(r)))),t+=1,()=>{Vo(()=>{t-=1,t===0&&(n?.(),n=void 0,Qd(r))})})))}}var ZA=Du|ld;function YA(e,t,r,n){new JA(e,t,r,n)}var Do=new WeakMap,Zg=new WeakMap,ds=new WeakMap,mu=new WeakMap,Fi=new WeakMap,jo=new WeakMap,Ui=new WeakMap,Po=new WeakMap,ba=new WeakMap,wc=new WeakMap,bl=new WeakMap,Sf=new WeakMap,Yg=new WeakMap,Jg=new WeakMap,Oa=new WeakMap,Qw=new WeakMap,Rn=new WeakSet,JA=class{constructor(e,t,r,n){ad(this,Rn),T(this,"parent",void 0),T(this,"is_pending",!1),T(this,"transform_error",void 0),Le(this,Do,void 0),Le(this,Zg,It?or:null),Le(this,ds,void 0),Le(this,mu,void 0),Le(this,Fi,void 0),Le(this,jo,null),Le(this,Ui,null),Le(this,Po,null),Le(this,ba,null),Le(this,wc,0),Le(this,bl,0),Le(this,Sf,!1),Le(this,Yg,new Set),Le(this,Jg,new Set),Le(this,Oa,null),Le(this,Qw,XA(()=>(Ce(Oa,this,Ol(S(wc,this))),()=>{Ce(Oa,this,null)}))),Ce(Do,this,e),Ce(ds,this,t),Ce(mu,this,i=>{var o=Nt;o.b=this,o.f|=128,r(i)}),this.parent=Nt.b,this.transform_error=n??this.parent?.transform_error??(i=>i),Ce(Fi,this,Uu(()=>{if(It){const i=S(Zg,this);$l();const o=i.data==="[!";if(i.data.startsWith("[?")){const s=JSON.parse(i.data.slice(2));je(Rn,this,eM).call(this,s)}else o?je(Rn,this,tM).call(this):je(Rn,this,QA).call(this)}else je(Rn,this,pT).call(this)},ZA)),It&&Ce(Do,this,or)}defer_effect(e){_k(e,S(Yg,this),S(Jg,this))}is_rendered(){return!this.is_pending&&(!this.parent||this.parent.is_rendered())}has_pending_snippet(){return!!S(ds,this).pending}update_pending_count(e,t){je(Rn,this,mT).call(this,e,t),Ce(wc,this,S(wc,this)+e),!(!S(Oa,this)||S(Sf,this))&&(Ce(Sf,this,!0),Vo(()=>{Ce(Sf,this,!1),S(Oa,this)&&Vc(S(Oa,this),S(wc,this))}))}get_effect_pending(){return S(Qw,this).call(this),h(S(Oa,this))}error(e){if(!S(ds,this).onerror&&!S(ds,this).failed)throw e;Ut?.is_fork?(S(jo,this)&&Ut.skip_effect(S(jo,this)),S(Ui,this)&&Ut.skip_effect(S(Ui,this)),S(Po,this)&&Ut.skip_effect(S(Po,this)),Ut.oncommit(()=>{je(Rn,this,e0).call(this,e)})):je(Rn,this,e0).call(this,e)}};function QA(){try{Ce(jo,this,xi(()=>S(mu,this).call(this,S(Do,this))))}catch(e){this.error(e)}}function eM(e){const t=S(ds,this).failed,{reset:r,invoke_onerror:n}=je(Rn,this,hT).call(this,e);Vo(n),t&&Ce(Po,this,xi(()=>{t(S(Do,this),()=>e,()=>r)}))}function hT(e){var t=!1,r=!1;const n=()=>{if(t){FP();return}t=!0,r&&eA(),S(Po,this)!==null&&ec(S(Po,this),()=>{Ce(Po,this,null)}),je(Rn,this,Jy).call(this,()=>{je(Rn,this,pT).call(this)})};return{reset:n,invoke_onerror:()=>{try{r=!0,S(ds,this).onerror?.(e,n),r=!1}catch(o){gs(o,S(Fi,this)&&S(Fi,this).parent)}}}}function tM(){const e=S(ds,this).pending;e&&(this.is_pending=!0,Ce(Ui,this,xi(()=>e(S(Do,this)))),Vo(()=>{var t=Ce(ba,this,document.createDocumentFragment()),r=Zn(),n=!1;if(t.append(r),Ce(jo,this,je(Rn,this,Jy).call(this,()=>{try{return xi(()=>S(mu,this).call(this,r))}catch(i){try{this.error(i),n=!0}catch(o){gs(o,S(Fi,this).parent)}return null}})),S(jo,this)===null){Ce(ba,this,null),n&&je(Rn,this,Gh).call(this,Ut);return}S(bl,this)===0&&(S(Do,this).before(t),Ce(ba,this,null),ec(S(Ui,this),()=>{Ce(Ui,this,null)}),je(Rn,this,Gh).call(this,Ut))}))}function pT(){try{if(this.is_pending=this.has_pending_snippet(),Ce(bl,this,0),Ce(wc,this,0),Ce(jo,this,xi(()=>{S(mu,this).call(this,S(Do,this))})),S(bl,this)>0){var e=Ce(ba,this,document.createDocumentFragment());Yy(S(jo,this),e);const t=S(ds,this).pending;Ce(Ui,this,xi(()=>t(S(Do,this))))}else je(Rn,this,Gh).call(this,Ut)}catch(t){this.error(t)}}function Gh(e){this.is_pending=!1,e.transfer_effects(S(Yg,this),S(Jg,this))}function Jy(e){var t=Nt,r=tr,n=Mr;uo(S(Fi,this)),Ri(S(Fi,this)),qc(S(Fi,this).ctx);try{return Ql.ensure(),e()}finally{uo(t),Ri(r),qc(n)}}function mT(e,t){if(!this.has_pending_snippet()){if(this.parent){var r;je(Rn,r=this.parent,mT).call(r,e,t)}return}Ce(bl,this,S(bl,this)+e),S(bl,this)===0&&(je(Rn,this,Gh).call(this,t),S(Ui,this)&&ec(S(Ui,this),()=>{Ce(Ui,this,null)}),S(ba,this)&&(S(Do,this).before(S(ba,this)),Ce(ba,this,null)))}function e0(e){S(jo,this)&&(Hn(S(jo,this)),Ce(jo,this,null)),S(Ui,this)&&(Hn(S(Ui,this)),Ce(Ui,this,null)),S(Po,this)&&(Hn(S(Po,this)),Ce(Po,this,null)),It&&(Fn(S(Zg,this)),HP(),Fn(Dh()));let t=S(ds,this).failed;const r=n=>{const{reset:i,invoke_onerror:o}=je(Rn,this,hT).call(this,n);o(),t&&Ce(Po,this,je(Rn,this,Jy).call(this,()=>{try{return xi(()=>{var s=Nt;s.b=this,s.f|=128,t(S(Do,this),()=>n,()=>i)})}catch(s){return gs(s,S(Fi,this).parent),null}}))};Vo(()=>{var n;try{n=this.transform_error(e)}catch(i){gs(i,S(Fi,this)&&S(Fi,this).parent);return}n!==null&&typeof n=="object"&&typeof n.then=="function"?n.then(r,i=>gs(i,S(Fi,this)&&S(Fi,this).parent)):r(n)})}var Qg=!0;function If(e){Qg=e}function vs(e,t){var r=t==null?"":typeof t=="object"?`${t}`:t;r!==(e[ch]??(e[ch]=e.nodeValue))&&(e[ch]=r,e.nodeValue=`${r}`)}function gT(e,t){return vT(e,t)}function rM(e,t){Vg(),t.intro=t.intro??!1;const r=t.target,n=It,i=or;try{for(var o=Hs(r);o&&(o.nodeType!==8||o.data!=="[");)o=ks(o);if(!o)throw Uc;di(!0),Fn(o);const s=vT(e,{...t,anchor:o});return di(!1),s}catch(s){if(s instanceof Error&&s.message.split(`
2
+ `).some(a=>a.startsWith("https://svelte.dev/e/")))throw s;return s!==Uc&&console.warn("Failed to hydrate: ",s),t.recover===!1&&XP(),Vg(),Xk(r),di(!1),gT(e,t)}finally{di(n),Fn(i)}}var kf=new Map;function vT(e,{target:t,anchor:r,props:n={},events:i,context:o,intro:s=!0,transformError:a}){Vg();var l=void 0,d=xA(()=>{var c=r??t.appendChild(Zn());YA(c,{pending:()=>{}},p=>{un({});var g=Mr;if(o&&(g.c=o),i&&(n.$$events=i),It&&Ds(p,null),Qg=s,l=e(p,n)||Wy(),Qg=!0,It&&(Nt.nodes.end=or,or===null||or.nodeType!==8||or.data!=="]"))throw zp(),Uc;fn()},a);var u=new Set,f=p=>{for(var g=0;g<p.length;g++){var v=p[g];if(!u.has(v)){u.add(v);var b=qA(v);for(const x of[t,document]){var w=kf.get(x);w===void 0&&(w=new Map,kf.set(x,w));var I=w.get(v);I===void 0?(x.addEventListener(v,Xg,{passive:b}),w.set(v,1)):w.set(v,I+1)}}}};return f(Fp(dT)),Kg.add(f),()=>{for(var p of u)for(const b of[t,document]){var g=kf.get(b),v=g.get(p);--v==0?(b.removeEventListener(p,Xg),g.delete(p),g.size===0&&kf.delete(b)):g.set(p,v)}Kg.delete(f),c!==r&&c.parentNode?.removeChild(c)}});return ev.set(l,d),l}var ev=new WeakMap;function nM(e,t){const r=ev.get(e);return r?(ev.delete(e),r(t)):Promise.resolve()}var xs=new WeakMap,na=new WeakMap,wo=new WeakMap,wd=new WeakMap,Nm=new WeakMap,Dm=new WeakMap,t0=new WeakMap,Qy=class{constructor(e,t=!0){T(this,"anchor",void 0),Le(this,xs,new Map),Le(this,na,new Map),Le(this,wo,new Map),Le(this,wd,new Set),Le(this,Nm,!0),Le(this,Dm,r=>{if(S(xs,this).has(r)){var n=S(xs,this).get(r),i=S(na,this).get(n);if(i)Vh(i),S(wd,this).delete(n);else{var o=S(wo,this).get(n);o&&(Vh(o.effect),S(na,this).set(n,o.effect),S(wo,this).delete(n),o.fragment.lastChild.remove(),this.anchor.before(o.fragment),i=o.effect)}for(const[s,a]of S(xs,this)){if(S(xs,this).delete(s),s===r)break;const l=S(wo,this).get(a);l&&(Hn(l.effect),S(wo,this).delete(a))}for(const[s,a]of S(na,this)){if(s===n||S(wd,this).has(s))continue;const l=()=>{if(Array.from(S(xs,this).values()).includes(s)){var d=document.createDocumentFragment();Yy(a,d),d.append(Zn()),S(wo,this).set(s,{effect:a,fragment:d})}else Hn(a);S(wd,this).delete(s),S(na,this).delete(s)};S(Nm,this)||!i?(S(wd,this).add(s),ec(a,l,!1)):l()}}}),Le(this,t0,r=>{S(xs,this).delete(r);const n=Array.from(S(xs,this).values());for(const[i,o]of S(wo,this))n.includes(i)||(Hn(o.effect),S(wo,this).delete(i))}),this.anchor=e,Ce(Nm,this,t)}ensure(e,t){var r=Ut,n=Zk();if(t&&!S(na,this).has(e)&&!S(wo,this).has(e))if(n){var i=document.createDocumentFragment(),o=Zn();i.append(o),S(wo,this).set(e,{effect:xi(()=>t(o)),fragment:i})}else S(na,this).set(e,xi(()=>t(this.anchor)));if(S(xs,this).set(r,e),n){for(const[s,a]of S(na,this))s===e?r.unskip_effect(a):r.skip_effect(a);for(const[s,a]of S(wo,this))s===e?r.unskip_effect(a.effect):r.skip_effect(a.effect);r.oncommit(S(Dm,this)),r.ondiscard(S(t0,this))}else It&&(this.anchor=or),S(Dm,this).call(this,r)}};function iM(e,t,...r){var n=new Qy(e);Uu(()=>{const i=t()??null;n.ensure(i,i&&(o=>i(o,...r)))},Du)}function Kp(e){Mr===null&&Up("onMount"),Bu&&Mr.l!==null?sM(Mr).m.push(e):ct(()=>{const t=on(e);if(typeof t=="function")return t})}function Xp(e){Mr===null&&Up("onDestroy"),Kp(()=>()=>on(e))}function oM(e,t,{bubbles:r=!1,cancelable:n=!1}={}){return new CustomEvent(e,{detail:t,bubbles:r,cancelable:n})}function tc(){const e=Mr;return e===null&&Up("createEventDispatcher"),(t,r,n)=>{const i=e.s.$$events?.[t];if(i){const o=Nu(i)?i.slice():[i],s=oM(t,r,n);for(const a of o)a.call(e.x,s);return!s.defaultPrevented}return!0}}function sM(e){var t=e.l;return t.u??(t.u={a:[],b:[],m:[]})}function vn(e,t,r=!1){var n;It&&(n=or,$l());var i=new Qy(e),o=r?Du:0;function s(a,l){if(It){var d=Tk(n);if(a!==parseInt(d.substring(1))){var c=Dh();Fn(c),i.anchor=c,di(!1),i.ensure(a,l),di(!0);return}}i.ensure(a,l)}Uu(()=>{var a=!1;t((l,d=0)=>{a=!0,s(d,l)}),a||s(-1,null)},o)}function aM(e,t,r){for(var n=[],i=t.length,o,s=t.length,a=0;a<i;a++){let u=t[a];ec(u,()=>{if(o){if(o.pending.delete(u),o.done.add(u),o.pending.size===0){var f=e.outrogroups;tv(e,Fp(o.done)),f.delete(o),f.size===0&&(e.outrogroups=null)}}else s-=1},!1)}if(s===0){var l=n.length===0&&r!==null&&e.pending.size===0;if(l){var d=r,c=d.parentNode;Xk(c),c.append(d),e.items.clear()}tv(e,t,!l)}else o={pending:new Set(t),done:new Set},(e.outrogroups??(e.outrogroups=new Set)).add(o)}function tv(e,t,r=!0){var n;if(e.pending.size>0){n=new Set;for(const s of e.pending.values())for(const a of s)n.add(e.items.get(a).e)}for(var i=0;i<t.length;i++){var o=t[i];if(n?.has(o)){o.f|=Yd;const s=document.createDocumentFragment();Yy(o,s)}else Hn(t[i],r)}}var Tf;function yT(e,t,r,n,i,o=null){var s=e,a=new Map;if((t&4)!==0){var l=e;s=It?Fn(Hs(l)):l.appendChild(Zn())}It&&$l();var d=null,c=qy(()=>{var w=r();return Nu(w)?w:w==null?[]:Fp(w)}),u,f=new Map,p=!0;function g(w){(b.effect.f&16384)===0&&(b.pending.delete(w),b.fallback=d,lM(b,u,s,t,n),d!==null&&(u.length===0?(d.f&33554432)===0?Vh(d):(d.f^=Yd,Fd(d,null,s)):ec(d,()=>{d=null})))}function v(w){b.pending.delete(w)}var b={effect:Uu(()=>{u=h(c);var w=u.length;let I=!1;It&&Tk(s)==="[!"!=(w===0)&&(s=Dh(),Fn(s),di(!1),I=!0);for(var x=new Set,C=Ut,L=Zk(),E=0;E<w;E+=1){It&&or.nodeType===8&&or.data==="]"&&(s=or,I=!0,di(!1));var M=u[E],U=n(M,E);if(0)var te;var re=p?null:a.get(U);re?(re.v&&Vc(re.v,M),re.i&&Vc(re.i,E),L&&C.unskip_effect(re.e)):(re=cM(a,p?s:Tf??(Tf=Zn()),M,U,E,i,t,r),p||(re.e.f|=Yd),a.set(U,re)),x.add(U)}if(w===0&&o&&!d&&(p?d=xi(()=>o(s)):(d=xi(()=>o(Tf??(Tf=Zn()))),d.f|=Yd)),w>x.size&&UP("","",""),It&&w>0&&Fn(Dh()),!p)if(f.set(C,x),L){for(const[Pe,z]of a)x.has(Pe)||C.skip_effect(z.e);C.oncommit(g),C.ondiscard(v)}else g(C);I&&di(!0),h(c)}),flags:t,items:a,pending:f,outrogroups:null,fallback:d};p=!1,It&&(s=or)}function Sd(e){for(;e!==null&&(e.f&32)===0;)e=e.next;return e}function lM(e,t,r,n,i){var o=(n&8)!==0,s=t.length,a=e.items,l=Sd(e.effect.first),d,c=null,u,f=[],p=[],g,v,b,w;if(o)for(w=0;w<s;w+=1)g=t[w],v=i(g,w),b=a.get(v).e,(b.f&33554432)===0&&(b.nodes?.a?.measure(),(u??(u=new Set)).add(b));for(w=0;w<s;w+=1){if(g=t[w],v=i(g,w),b=a.get(v).e,e.outrogroups!==null)for(const re of e.outrogroups)re.pending.delete(b),re.done.delete(b);if((b.f&8192)!==0&&(Vh(b),o&&(b.nodes?.a?.unfix(),(u??(u=new Set)).delete(b))),(b.f&33554432)!==0)if(b.f^=Yd,b===l)Fd(b,null,r);else{var I=c?c.next:l;b===e.effect.last&&(e.effect.last=b.prev),b.prev&&(b.prev.next=b.next),b.next&&(b.next.prev=b.prev),ia(e,c,b),ia(e,b,I),Fd(b,I,r),c=b,f=[],p=[],l=Sd(c.next);continue}if(b!==l){if(d!==void 0&&d.has(b)){if(f.length<p.length){var x=p[0],C;c=x.prev;var L=f[0],E=f[f.length-1];for(C=0;C<f.length;C+=1)Fd(f[C],x,r);for(C=0;C<p.length;C+=1)d.delete(p[C]);ia(e,L.prev,E.next),ia(e,c,L),ia(e,E,x),l=x,c=E,w-=1,f=[],p=[]}else d.delete(b),Fd(b,l,r),ia(e,b.prev,b.next),ia(e,b,c===null?e.effect.first:c.next),ia(e,c,b),c=b;continue}for(f=[],p=[];l!==null&&l!==b;)(d??(d=new Set)).add(l),p.push(l),l=Sd(l.next);if(l===null)continue}(b.f&33554432)===0&&f.push(b),c=b,l=Sd(b.next)}if(e.outrogroups!==null){for(const re of e.outrogroups)re.pending.size===0&&(tv(e,Fp(re.done)),e.outrogroups?.delete(re));e.outrogroups.size===0&&(e.outrogroups=null)}if(l!==null||d!==void 0){var M=[];if(d!==void 0)for(b of d)(b.f&8192)===0&&M.push(b);for(;l!==null;)(l.f&8192)===0&&l!==e.fallback&&M.push(l),l=Sd(l.next);var U=M.length;if(U>0){var te=(n&4)!==0&&s===0?r:null;if(o){for(w=0;w<U;w+=1)M[w].nodes?.a?.measure();for(w=0;w<U;w+=1)M[w].nodes?.a?.fix()}aM(e,M,te)}}o&&Vo(()=>{if(u!==void 0)for(b of u)b.nodes?.a?.apply()})}function cM(e,t,r,n,i,o,s,a){var l=(s&1)!==0?(s&16)===0?Wk(r,!1,!1):Ol(r):null,d=(s&2)!==0?Ol(i):null;return{v:l,i:d,e:xi(()=>(o(t,l??r,d??i,a),()=>{e.delete(n)}))}}function Fd(e,t,r){if(e.nodes)for(var n=e.nodes.start,i=e.nodes.end,o=t&&(t.f&33554432)===0?t.nodes.start:r;n!==null;){var s=ks(n);if(o.before(n),n===i)return;n=s}}function ia(e,t,r){t===null?e.effect.first=r:t.next=r,r===null?e.effect.last=t:r.prev=t}function dd(e,t,r,n,i){if(It&&$l(),t.$$host?.$$shadowRoot){const a=zu("slot");if(r!=="default"&&(a.name=r),ft(e,a),i!==null){const l=Zn();a.append(l),i(l)}return}var o=t.$$slots?.[r],s=!1;o===!0&&(o=t[r==="default"?"children":r],s=!0),o===void 0?i!==null&&i(e):o(e,s?()=>n:n)}var dM=null;function r0(e){dM=e}function Kh(e,t,r,n,i,o){let s=It;It&&$l();var a=!1,l=null;It&&or.nodeType===1&&(l=or,$l());var d=It?or:e,c=Nt,u=new Qy(d,!1);Uu(()=>{const f=t()||null;var p=i?i():r||f==="svg"?CP:void 0;if(f===null){u.ensure(null,null),If(!0);return}return u.ensure(f,g=>{if(f){if(l=It?l:zu(f,p),Ds(l,l),n){var v=null;It&&KA(f)&&l.append(v=document.createComment(""));var b=It?Hs(l):l.appendChild(Zn());It&&(b===null?di(!1):Fn(b)),r0(c),n(l,b),v?.remove(),r0(null)}Nt.nodes.end=l,g.before(l)}It&&Fn(g)}),If(!0),()=>{f&&If(!1)}},Du),Vp(()=>{If(!0)}),s&&(di(!0),Fn(d))}function Mn(e,t){Wu(()=>{e=Nt?.parent?.nodes?.start??e;var r=e.getRootNode(),n=r.host?r:r.head??r.ownerDocument.head;if(!n.querySelector("#"+t.hash)){const i=zu("style");i.id=t.hash,i.textContent=t.code,n.appendChild(i)}})}function bT(e,t,r){Wu(()=>{var n=on(()=>t(e,r?.())||{});if(r&&n?.update){var i=!1,o={};Gp(()=>{var s=r();LA(s),i&&Ck(o,s)&&(o=s,n.update(s))}),i=!0}if(n?.destroy)return()=>n.destroy()})}function uM(e,t){var r=void 0,n;Jk(()=>{r!==(r=t())&&(n&&(Hn(n),n=null),r&&(n=xi(()=>{Wu(()=>r(e))})))})}function wT(e){var t,r,n="";if(typeof e=="string"||typeof e=="number")n+=e;else if(typeof e=="object")if(Array.isArray(e)){var i=e.length;for(t=0;t<i;t++)e[t]&&(r=wT(e[t]))&&(n&&(n+=" "),n+=r)}else for(r in e)e[r]&&(n&&(n+=" "),n+=r);return n}function fM(){for(var e,t,r=0,n="",i=arguments.length;r<i;r++)(e=arguments[r])&&(t=wT(e))&&(n&&(n+=" "),n+=t);return n}function hM(e){return typeof e=="object"?fM(e):e??""}var n0=[...`
3
+ \r\f \v\uFEFF`];function pM(e,t,r){var n=e==null?"":""+e;if(t&&(n=n?n+" "+t:t),r){for(var i of Object.keys(r))if(r[i])n=n?n+" "+i:i;else if(n.length)for(var o=i.length,s=0;(s=n.indexOf(i,s))>=0;){var a=s+o;(s===0||n0.includes(n[s-1]))&&(a===n.length||n0.includes(n[a]))?n=(s===0?"":n.substring(0,s))+n.substring(a+1):s=a}}return n===""?null:n}function i0(e,t=!1){var r=t?" !important;":";",n="";for(var i of Object.keys(e)){var o=e[i];o!=null&&o!==""&&(n+=" "+i+": "+o+r)}return n}function jm(e){return e[0]!=="-"||e[1]!=="-"?e.toLowerCase():e}function mM(e,t){if(t){var r="",n,i;if(Array.isArray(t)?(n=t[0],i=t[1]):n=t,e){e=String(e).replaceAll(/\/\*.*?\*\//g,"").trim();var o=!1,s=0,a=!1,l=[];n&&l.push(...Object.keys(n).map(jm)),i&&l.push(...Object.keys(i).map(jm));var d=0,c=-1;const v=e.length;for(var u=0;u<v;u++){var f=e[u];if(a?f==="/"&&e[u-1]==="*"&&(a=!1):o?o===f&&(o=!1):f==="/"&&e[u+1]==="*"?a=!0:f==='"'||f==="'"?o=f:f==="("?s++:f===")"&&s--,!a&&o===!1&&s===0){if(f===":"&&c===-1)c=u;else if(f===";"||u===v-1){if(c!==-1){var p=jm(e.substring(d,c).trim());if(!l.includes(p)){f!==";"&&u++;var g=e.substring(d,u).trim();r+=" "+g+";"}}d=u+1,c=-1}}}}return n&&(r+=i0(n)),i&&(r+=i0(i,!0)),r=r.trim(),r===""?null:r}return e==null?null:String(e)}function gn(e,t,r,n,i,o){var s=e[Fg];if(It||s!==r||s===void 0){var a=pM(r,n,o);(!It||a!==e.getAttribute("class"))&&(a==null?e.removeAttribute("class"):t?e.className=a:e.setAttribute("class",a)),e[Fg]=r}else if(o&&i!==o)for(var l in o){var d=!!o[l];(i==null||d!==!!i[l])&&e.classList.toggle(l,d)}return o}function Bm(e,t={},r,n){for(var i in r){var o=r[i];t[i]!==o&&(r[i]==null?e.style.removeProperty(i):e.style.setProperty(i,o,n))}}function Dl(e,t,r,n){var i=e[Hg];if(It||i!==t){var o=mM(t,n);(!It||o!==e.getAttribute("style"))&&(o==null?e.removeAttribute("style"):e.style.cssText=o),e[Hg]=t}else n&&(Array.isArray(n)?(Bm(e,r?.[0],n[0]),Bm(e,r?.[1],n[1],"important")):Bm(e,r,n));return n}function ST(e,t){t?e.hasAttribute("selected")||e.setAttribute("selected",""):e.removeAttribute("selected")}function o0(e,t){var r=!("__defaultValue"in e);!r&&e.__defaultValue===t||(e.__defaultValue=t,IT(e,!r||"__value"in e))}function IT(e,t){var r=e.__defaultValue,n=e.multiple,i=n?r??[]:null;if(!(n&&!Nu(i))){var o=e.selectedIndex,s=t&&n?new Set(e.selectedOptions):null;for(var a of e.options){var l=nv(a);ST(a,n?i.includes(l):qk(l,r))}if(t)if(s!==null)for(a of e.options){var d=s.has(a);a.selected!==d&&(a.selected=d)}else e.selectedIndex!==o&&(e.selectedIndex=o)}}function rv(e,t,r=!1){if(e.multiple){if(t==null)return;if(!Nu(t))return BP();for(var n of e.options)n.selected=t.includes(nv(n));return}for(n of e.options){var i=nv(n);if(qk(i,t)){n.selected=!0;return}}(!r||t!==void 0)&&(e.selectedIndex=-1)}function gM(e){var t=new MutationObserver(r=>{r.every(vM)||("__defaultValue"in e&&IT(e,!1),"__value"in e&&rv(e,e.__value))});t.observe(e,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["value"]}),Vp(()=>{t.disconnect()})}function nv(e){return"__value"in e?e.__value:e.value}function vM(e){if(e.target.closest("selectedcontent")!==null)return!0;if(e.type==="childList"){var t=[...e.addedNodes,...e.removedNodes];return t.length>0&&t.every(r=>r.nodeName==="SELECTEDCONTENT")}return!1}var Id=Symbol("class"),kd=Symbol("style"),kT=Symbol("is custom element"),TT=Symbol("is html"),yM=Hp?"link":"LINK",s0=Hp?"input":"INPUT",bM=Hp?"option":"OPTION",ET=Hp?"select":"SELECT";function wM(e){if(It){var t=!1,r=()=>{if(!t){if(t=!0,e.hasAttribute("value")){var n=e.value;nt(e,"value",null),e.value=n}if(e.hasAttribute("checked")){var i=e.checked;nt(e,"checked",null),e.checked=i}}};e[kk]=r,Vo(r),lA()}}function nt(e,t,r,n){var i=xT(e);if(It&&(i[t]=e.getAttribute(t),t==="src"||t==="srcset"||t==="href"&&e.nodeName===yM)){n||void 0;return}i[t]!==(i[t]=r)&&(t==="loading"&&(e[NP]=r),r==null?e.removeAttribute(t):typeof r!="string"&&eb(e).has(t)?e[t]=r:e.setAttribute(t,r))}function G(e,t,r){var n=tr,i=Nt;let o=It;It&&di(!1),Ri(null),uo(null);try{t!=="style"&&(iv.has(e.getAttribute("is")||e.nodeName)||!customElements||customElements.get(e.getAttribute("is")||e.nodeName.toLowerCase())?eb(e).has(t):r&&typeof r=="object")?e[t]=r:nt(e,t,r==null?r:String(r))}finally{Ri(n),uo(i),o&&di(!0)}}function SM(e,t,r,n,i=!1,o=!1){It&&i&&e.nodeName===s0&&("defaultValue"in r||"defaultChecked"in r||wM(e));var s=xT(e),a=s[kT],l=!s[TT];let d=It&&a;d&&di(!1);var c=t||{},u=e.nodeName===bM,f=e.nodeName===ET;for(var p in t)!(p in r)&&p[0]+p[1]!=="$$"&&(r[p]=null);r.class?r.class=hM(r.class):(n||r[Id])&&(r.class=null),r[kd]&&(r.style??(r.style=null));var g=eb(e);if(e.nodeName===s0&&"type"in r&&("value"in r||"__value"in r)){var v=r.type;(v!==c.type||v===void 0&&e.hasAttribute("type"))&&(c.type=v,nt(e,"type",v,o))}for(const E in r){let M=r[E];if(u&&E==="value"&&M==null){e.value=e.__value="",c[E]=M;continue}if(E==="class"){var b=e.namespaceURI==="http://www.w3.org/1999/xhtml";gn(e,b,M,n,t?.[Id],r[Id]),c[E]=M,c[Id]=r[Id];continue}if(E==="style"){Dl(e,M,t?.[kd],r[kd]),c[E]=M,c[kd]=r[kd];continue}var w=c[E];if(!(M===w&&!(M===void 0&&e.hasAttribute(E)))){c[E]=M;var I=E[0]+E[1];if(I!=="$$")if(I==="on"){const U={},te="$$"+E;let re=E.slice(2);var x=FA(re);if(jA(re)&&(re=re.slice(0,-7),U.capture=!0),!x&&w){if(M!=null)continue;e.removeEventListener(re,c[te],U),c[te]=null}if(x)lo(re,e,M),cd([re]);else if(M!=null){let Pe=function(z){c[E].call(this,z)};c[te]=uT(re,e,Pe,U)}}else if(E==="style")nt(e,E,M);else if(E==="autofocus")aA(e,!!M);else if(!a&&(E==="__value"||E==="value"&&M!=null))e.value=e.__value=M;else if(E==="selected"&&u)ST(e,M);else{var C=E;l||(C=WA(C));var L=C==="defaultValue"||C==="defaultChecked";if(f&&C==="defaultValue")continue;if(M==null&&!a&&!L)if(s[E]=null,C==="value"||C==="checked"){let U=e;const te=t===void 0;if(C==="value"){let re=U.defaultValue;U.removeAttribute(C),U.defaultValue=re,U.value=U.__value=te?re:null}else{let re=U.defaultChecked;U.removeAttribute(C),U.defaultChecked=re,U.checked=te?re:!1}}else e.removeAttribute(E);else L||(a||typeof M!="string")&&g.has(C)?(e[C]=M,C in s&&(s[C]=mn)):typeof M!="function"&&nt(e,C,M,o)}}}return d&&di(!0),c}function CT(e,t,r=[],n=[],i=[],o,s=!1,a=!1){Pk(i,r,n,l=>{var d=void 0,c={},u=e.nodeName===ET,f=!1;if(Jk(()=>{var g=t(...l.map(h)),v=SM(e,d,g,o,s,a);if(f&&u){var b=e;"defaultValue"in g&&o0(b,g.defaultValue),"value"in g&&rv(b,g.value)}for(let I of Object.getOwnPropertySymbols(c))g[I]||Hn(c[I]);for(let I of Object.getOwnPropertySymbols(g)){var w=g[I];I.description==="@attach"&&(!d||w!==d[I])&&(c[I]&&Hn(c[I]),c[I]=xi(()=>uM(e,()=>w))),v[I]=w}d=v}),u){var p=e;Wu(()=>{var g=d;"defaultValue"in g&&o0(p,g.defaultValue),rv(p,g.value,!0),gM(p)})}f=!0})}function xT(e){return e[Bg]??(e[Bg]={[kT]:e.nodeName.includes("-"),[TT]:e.namespaceURI==="http://www.w3.org/1999/xhtml"})}var iv=new Map;function eb(e){var t=e.getAttribute("is")||e.nodeName,r=iv.get(t);if(r)return r;iv.set(t,r=new Set);for(var n,i=e,o=Element.prototype;o!==i;){n=bk(i);for(var s in n)n[s].set&&s!=="innerHTML"&&s!=="textContent"&&s!=="innerText"&&r.add(s);i=Fy(i)}return r}var RT,Sc=new WeakMap,Xh=new WeakMap,Fm=new WeakMap,a0=new WeakSet,_T=class{constructor(e){ad(this,a0),Le(this,Sc,new WeakMap),Le(this,Xh,void 0),Le(this,Fm,void 0),Ce(Fm,this,e)}observe(e,t){var r=S(Sc,this).get(e)||new Set;return r.add(t),S(Sc,this).set(e,r),je(a0,this,IM).call(this).observe(e,S(Fm,this)),()=>{var n=S(Sc,this).get(e);n.delete(t),n.size===0&&(S(Sc,this).delete(e),S(Xh,this).unobserve(e))}}};RT=_T;function IM(){return S(Xh,this)??Ce(Xh,this,new ResizeObserver(e=>{for(var t of e){RT.entries.set(t.target,t);for(var r of S(Sc,this).get(t.target)||[])r(t)}}))}T(_T,"entries",new WeakMap);function Hm(e,t){return e===t||e?.[Os]===t}function Er(e=Wy(),t,r,n){var i=Mr.r,o=Nt;return Wu(()=>{var s,a;return Gp(()=>{s=a,a=n?.()||[],on(()=>{Hm(r(...a),e)||(t(e,...a),s&&Hm(r(...s),e)&&t(null,...s))})}),()=>{let l=o;for(;l!==i&&l.parent!==null&&l.parent.f&33554432;)l=l.parent;const d=()=>{a&&Hm(r(...a),e)&&t(null,...a)},c=l.teardown;l.teardown=()=>{d(),c?.()}}}),e}var Ef=!1;function kM(e){var t=Ef;try{return Ef=!1,[e(),Ef]}finally{Ef=t}}function _(e,t,r,n){var i=!Bu||(r&2)!==0,o=(r&8)!==0,s=(r&16)!==0,a=n,l=!0,d=void 0,c=()=>s&&i?(d??(d=fu(n)),h(d)):(l&&(l=!1,a=s?on(n):n),a);let u;if(o){var f=Os in e||Ik in e;u=gl(e,t)?.set??(f&&t in e?C=>e[t]=C:void 0)}var p,g=!1;o?[p,g]=kM(()=>e[t]):p=e[t],p===void 0&&n!==void 0&&(p=c(),u&&(i&&ZP(t),u(p)));var v;if(i?v=()=>{var C=e[t];return C===void 0?c():(l=!0,C)}:v=()=>{var C=e[t];return C!==void 0&&(a=void 0),C===void 0?a:C},i&&(r&4)===0)return v;if(u){var b=e.$$legacy;return(function(C,L){return arguments.length>0?((!i||!L||b||g)&&u(L?v():C),C):v()})}var w=!1,I=((r&1)!==0?fu:qy)(()=>(w=!1,v()));o&&h(I);var x=Nt;return(function(C,L){if(arguments.length>0){const E=L?h(I):i&&o?Ti(C):C;return be(I,E),w=!0,a!==void 0&&(a=E),C}return zs&&w||(x.f&16384)!==0?I.v:h(I)})}function TM(e){return new EM(e)}var Na=new WeakMap,es=new WeakMap,EM=class{constructor(e){Le(this,Na,void 0),Le(this,es,void 0);var t=new Map,r=(i,o)=>{var s=Wk(o,!1,!1);return t.set(i,s),s};const n=new Proxy({...e.props||{},$$events:{}},{get(i,o){return h(t.get(o)??r(o,Reflect.get(i,o)))},has(i,o){return o===Ik?!0:(h(t.get(o)??r(o,Reflect.get(i,o))),Reflect.has(i,o))},set(i,o,s){return be(t.get(o)??r(o,s),s),Reflect.set(i,o,s)}});Ce(es,this,(e.hydrate?rM:gT)(e.component,{target:e.target,anchor:e.anchor,props:n,context:e.context,intro:e.intro??!1,recover:e.recover,transformError:e.transformError})),!Js&&(!e?.props?.$$host||e.sync===!1)&&R(),Ce(Na,this,n.$$events);for(const i of Object.keys(S(es,this)))i==="$set"||i==="$destroy"||i==="$on"||uu(this,i,{get(){return S(es,this)[i]},set(o){S(es,this)[i]=o},enumerable:!0});S(es,this).$set=i=>{Object.assign(n,i)},S(es,this).$destroy=()=>{nM(S(es,this))}}$set(e){S(es,this).$set(e)}$on(e,t){S(Na,this)[e]=S(Na,this)[e]||[];const r=(...n)=>t.call(this,...n);return S(Na,this)[e].push(r),()=>{S(Na,this)[e]=S(Na,this)[e].filter(n=>n!==r)}}$destroy(){S(es,this).$destroy()}},PT;typeof HTMLElement=="function"&&(PT=class extends HTMLElement{constructor(e,t,r){super(),T(this,"$$ctor",void 0),T(this,"$$s",void 0),T(this,"$$c",void 0),T(this,"$$cn",!1),T(this,"$$d",{}),T(this,"$$r",!1),T(this,"$$p_d",{}),T(this,"$$l",{}),T(this,"$$l_u",new Map),T(this,"$$me",void 0),T(this,"$$shadowRoot",null),this.$$ctor=e,this.$$s=t,r&&(this.$$shadowRoot=this.attachShadow(r))}addEventListener(e,t,r){if(this.$$l[e]=this.$$l[e]||[],this.$$l[e].push(t),this.$$c){const n=this.$$c.$on(e,t);this.$$l_u.set(t,n)}super.addEventListener(e,t,r)}removeEventListener(e,t,r){if(super.removeEventListener(e,t,r),this.$$c){const n=this.$$l_u.get(t);n&&(n(),this.$$l_u.delete(t))}}async connectedCallback(){if(this.$$cn=!0,!this.$$c){let e=function(n){return i=>{const o=zu("slot");n!=="default"&&(o.name=n),ft(i,o)}};if(await Promise.resolve(),!this.$$cn||this.$$c)return;const t={},r=CM(this);for(const n of this.$$s)n in r&&(n==="default"&&!this.$$d.children?(this.$$d.children=e(n),t.default=!0):t[n]=e(n));for(const n of this.attributes){const i=this.$$g_p(n.name);i in this.$$d||(this.$$d[i]=fh(i,n.value,this.$$p_d,"toProp"))}for(const n in this.$$p_d)!(n in this.$$d)&&this[n]!==void 0&&(this.$$d[n]=this[n],delete this[n]);this.$$c=TM({component:this.$$ctor,target:this.$$shadowRoot||this,props:{...this.$$d,$$slots:t,$$host:this}}),this.$$me=CA(()=>{Gp(()=>{this.$$r=!0;for(const n of Oh(this.$$c)){if(!this.$$p_d[n]?.reflect)continue;this.$$d[n]=this.$$c[n];const i=fh(n,this.$$d[n],this.$$p_d,"toAttribute");i==null?this.removeAttribute(this.$$p_d[n].attribute||n):this.setAttribute(this.$$p_d[n].attribute||n,i)}this.$$r=!1})});for(const n in this.$$l)for(const i of this.$$l[n]){const o=this.$$c.$on(n,i);this.$$l_u.set(i,o)}this.$$l={}}}attributeChangedCallback(e,t,r){this.$$r||(e=this.$$g_p(e),this.$$d[e]=fh(e,r,this.$$p_d,"toProp"),this.$$c?.$set({[e]:this.$$d[e]}))}disconnectedCallback(){this.$$cn=!1,Promise.resolve().then(()=>{!this.$$cn&&this.$$c&&(this.$$c.$destroy(),this.$$me(),this.$$c=void 0)})}$$g_p(e){return Oh(this.$$p_d).find(t=>this.$$p_d[t].attribute===e||!this.$$p_d[t].attribute&&t.toLowerCase()===e)||e}});function fh(e,t,r,n){const i=r[e]?.type;if(t=i==="Boolean"&&typeof t!="boolean"?t!=null:t,!n||!r[e])return t;if(n==="toAttribute")switch(i){case"Object":case"Array":return t==null?null:JSON.stringify(t);case"Boolean":return t?"":null;case"Number":return t??null;default:return t}else switch(i){case"Object":case"Array":return t&&JSON.parse(t);case"Boolean":return t;case"Number":return t!=null?+t:t;default:return t}}function CM(e){const t={};return e.childNodes.forEach(r=>{t[r.slot||"default"]=!0}),t}function In(e,t,r,n,i,o){let s=class extends PT{constructor(){super(e,r,i),this.$$p_d=t}static get observedAttributes(){return Oh(t).map(a=>(t[a].attribute||a).toLowerCase())}};return Oh(t).forEach(a=>{uu(s.prototype,a,{get(){return this.$$c&&a in this.$$c?this.$$c[a]:this.$$d[a]},set(l){l=fh(a,l,t),this.$$d[a]=l;var d=this.$$c;d&&(gl(d,a)?.get?d[a]=l:d.$set({[a]:l}))}})}),n.forEach(a=>{uu(s.prototype,a,{get(){return this.$$c?.[a]}})}),o&&(s=o(s)),e.element=s,s}function xM(e){const t=new Set,r=/<\/?([a-zA-Z][a-zA-Z0-9._-]*)(?=[\t\n\f\r />])/g;let n=null;for(;(n=r.exec(e))!==null;){const i=String(n[1]||"").trim();i&&i.includes("-")&&t.add(i)}return t}var AT=e=>{const t=[],r=[];if(!e||typeof e!="object"||Array.isArray(e))return{valid:!1,errors:["Config must be an object."],warnings:r};const n=e,i=n.markup,o=n.elements,s=n.models;if(typeof i!="string"&&t.push("`markup` must be a string."),(!o||typeof o!="object"||Array.isArray(o))&&t.push("`elements` must be an object."),Array.isArray(s)||t.push("`models` must be an array."),t.length>0)return{valid:!1,errors:t,warnings:r};const a=o,l=s,d=Object.keys(a);for(const[p,g]of Object.entries(a)){if(typeof p!="string"||p.trim().length===0){t.push("`elements` contains an empty tag name.");continue}if(typeof g!="string"||g.trim().length===0){t.push(`Element "${p}" must map to a non-empty package spec.`);continue}try{uk(p,g)}catch{t.push(`Element "${p}" has invalid package spec "${g}".`)}}const c=new Set;for(const[p,g]of l.entries()){const v=g?.element;if(typeof v!="string"||v.trim().length===0){t.push(`Model at index ${p} is missing a valid "element" reference.`);continue}c.add(v),v in a||t.push(`Model element "${v}" is not declared in \`elements\`.`)}const u=xM(i);for(const p of u)p in a||t.push(`Markup tag "${p}" is not declared in \`elements\`.`);const f=new Set([...c,...u]);for(const p of d)f.has(p)||r.push(`Element "${p}" is declared in \`elements\` but not referenced by models or markup.`);return{valid:t.length===0,errors:t,warnings:r}},RM=e=>{const t=AT(e);if(!t.valid)throw new Error(`Invalid PIE config contract: ${t.errors.join(" | ")}`)},_M="https://proxy.pie-api.com/bundles/",PM="https://cdn.jsdelivr.net/npm",ov={retryDelayMs:3e3,timeoutMs:12e4},$s;(function(e){e.player="player.js",e.clientPlayer="client-player.js",e.editor="editor.js",e.esm="esm"})($s||($s={}));var jl;(function(e){e.loading="loading",e.loaded="loaded"})(jl||(jl={}));function sv(e){return typeof e=="function"&&"prototype"in e&&e.prototype instanceof HTMLElement}function AM(e){return e&&typeof e.PIE_REGISTRY=="object"}var Zp=()=>{let e;return AM(window)?e=window.PIE_REGISTRY:(e={},window.PIE_REGISTRY=e),e};function tb(e){const t=Zp(),r=t[e.tagName];if(!r||r.status!==jl.loaded||!MM(e.tagName))return t[e.tagName]=e,e;const n=!r.controller&&!!e.controller,i=r.config==null&&e.config!=null;if(!n&&!i)return r;const o={...r};return n&&(o.controller=e.controller,o.bundleType=e.bundleType),i&&(o.config=e.config),t[e.tagName]=o,o}function MM(e){return typeof customElements<"u"&&customElements.get(e)!==void 0}function Vu(e){if(!e||typeof e!="object")return!1;const t=e;return typeof t.providerId=="string"&&typeof t.providerName=="string"&&typeof t.initialize=="function"&&typeof t.trackError=="function"&&typeof t.trackEvent=="function"&&typeof t.destroy=="function"&&typeof t.isReady=="function"}var $M=Ys("instrumentation-event-bridge",()=>Yl());function LM(e){return e&&typeof e=="object"?e:typeof e>"u"?{}:{value:e}}function OM(e){$M.warn(`[InstrumentationEventBridge:${e}] Ignoring invalid instrumentation provider; expected InstrumentationProvider contract`)}function NM(e){try{e.provider.trackError(e.error instanceof Error?e.error:new Error(String(e.error??"Unknown instrumentation bridge error")),{component:e.component,errorType:"InstrumentationBridgeError",sourceEventName:e.sourceEventName})}catch{}}function Gu(e){if(!e.host||!e.eventMap.length)return()=>{};if(!e.instrumentationProvider)return()=>{};if(!Vu(e.instrumentationProvider))return e.debug&&OM(e.component),()=>{};const t=e.instrumentationProvider,r=[],n=Math.max(0,e.dedupeWindowMs??0),i=new Map,o=(s,a)=>{const l=[a.assessmentId,a.sectionId,a.attemptId,a.itemId,a.canonicalItemId,a.sourceRuntimeId].map(d=>String(d??"")).join("|");return`${s.instrumentationEventName}|${l}`};for(const s of e.eventMap){const a=l=>{try{if(!t.isReady()||e.shouldTrackEvent&&!e.shouldTrackEvent(l))return;const d=LM(l.detail),c=new Date().toISOString(),u={...d,...e.staticAttributes,component:e.component,sourceEventName:s.sourceEventName,timestamp:c};if(n>0){const f=Date.now(),p=o(s,u),g=i.get(p);if(typeof g=="number"&&f-g<n)return;i.set(p,f)}t.trackEvent(s.instrumentationEventName,{...u})}catch(d){NM({provider:t,component:e.component,error:d,sourceEventName:s.sourceEventName})}};e.host.addEventListener(s.sourceEventName,a),r.push(()=>{e.host?.removeEventListener(s.sourceEventName,a)})}return()=>{for(const s of r)s()}}function l0(e){const t=e;return typeof t?.noticeError=="function"&&typeof t.addPageAction=="function"}function uc(){if(typeof window>"u")return;const{newrelic:e,NREUM:t}=window;if(l0(e))return e;if(l0(t))return t}var DM=class{constructor(){T(this,"initialized",!1),T(this,"config",void 0)}trackError(e,t){if(!this.guardedOperation("trackError",e,t)||!this.applyErrorFilter(e,t))return;const r=this.transformAttributes(t);try{this.doTrackError(e,r),this.config?.debug&&console.log(`[${this.providerName}] Tracked error:`,e,r)}catch(n){console.error(`[${this.providerName}] Error tracking error:`,n)}}trackEvent(e,t){if(!this.guardedOperation("trackEvent",e,t)||!this.applyEventFilter(e,t)||!this.applySampling(e))return;let r=this.transformAttributes(t);r.timestamp||(r={...r,timestamp:new Date().toISOString()});try{this.doTrackEvent(e,r),this.config?.debug&&console.log(`[${this.providerName}] Tracked event:`,e,r)}catch(n){console.error(`[${this.providerName}] Error tracking event:`,n)}}trackMetric(e,t,r){this.trackEvent(`metric:${e}`,{...r,metricValue:t,metricName:e})}setUserContext(e,t){if(this.guardedOperation("setUserContext",e,t))try{this.doSetUserContext(e,t),this.config?.debug&&console.log(`[${this.providerName}] Set user context:`,e,t)}catch(r){console.error(`[${this.providerName}] Error setting user context:`,r)}}setGlobalAttributes(e){if(this.guardedOperation("setGlobalAttributes",e))try{this.doSetGlobalAttributes(e),this.config?.debug&&console.log(`[${this.providerName}] Set global attributes:`,e)}catch(t){console.error(`[${this.providerName}] Error setting global attributes:`,t)}}guardedOperation(e,...t){return this.isReady()?!0:(this.config?.debug&&console.warn(`[${this.providerName}] Attempted to ${e} but provider not ready:`,...t),!1)}applyErrorFilter(e,t){return this.config?.errorFilter&&!this.config.errorFilter(e,t)?(this.config?.debug&&console.log(`[${this.providerName}] Error filtered out:`,e,t),!1):!0}applyEventFilter(e,t){return this.config?.eventFilter&&!this.config.eventFilter(e,t)?(this.config?.debug&&console.log(`[${this.providerName}] Event filtered out:`,e,t),!1):!0}applySampling(e){return this.config?.sampleRate!==void 0&&this.config.sampleRate<1&&Math.random()>this.config.sampleRate?(this.config?.debug&&console.log(`[${this.providerName}] Event sampled out:`,e),!1):!0}transformAttributes(e){return this.config?.attributeTransformer?this.config.attributeTransformer(e):e}},jM=class extends DM{constructor(...e){super(...e),T(this,"providerId","newrelic"),T(this,"providerName","New Relic")}async initialize(e){this.config=e,this.initialized=!0,this.config?.debug&&console.log(uc()?"[NewRelicProvider] Initialized successfully":"[NewRelicProvider] Initialized; sends once the New Relic agent is on the page")}isReady(){return this.initialized&&uc()!==void 0}destroy(){this.initialized=!1,this.config?.debug&&console.log("[NewRelicProvider] Destroyed")}doTrackError(e,t){uc()?.noticeError(e,t)}doTrackEvent(e,t){uc()?.addPageAction(e,t)}doSetUserContext(e,t){const r=uc();if(typeof r?.setUserId=="function"&&r.setUserId(e),t&&typeof r?.setCustomAttribute=="function")for(const[n,i]of Object.entries(t))r.setCustomAttribute(n,i)}doSetGlobalAttributes(e){const t=uc();if(typeof t?.setCustomAttribute=="function")for(const[r,n]of Object.entries(e))t.setCustomAttribute(r,n)}};function c0(e){return e&&typeof e=="object"?e:{}}function d0(e){const t=c0(c0(e).loaderConfig);return Object.keys(t).length>0?t:null}function u0(e){if(!e||!("instrumentationProvider"in e))return{kind:"unset"};const t=e.instrumentationProvider;return t===null?{kind:"null"}:typeof t>"u"?{kind:"unset"}:{kind:"value",value:t}}function f0(e){if(!e||!("trackPageActions"in e))return;const t=e.trackPageActions;return typeof t=="boolean"?t:void 0}function BM(e,t){return e.kind==="value"||e.kind==="null"?e:t}var Cf,FM=Ys("instrumentation-provider-resolution",()=>Yl());function HM(){return Cf||(Cf=new jM,Cf.initialize()),Cf}function ud(e){const t=d0(e.runtimePlayer),r=d0(e.player),n=f0(t),i=f0(r),o=n??i??!1,s=BM(u0(t),u0(r));if(s.kind!=="null"){if(s.kind==="unset")return o?HM():void 0;if(Vu(s.value))return s.value;if(e.debug){const a=e.component?`[${e.component}] `:"";FM.warn(`${a}Ignoring invalid instrumentation provider; expected InstrumentationProvider contract`)}}}var rb=Object.freeze(["composed","engine-ready","interactive","disposed"]);function zM(e){return rb}function xf(e){const t=rb.indexOf(e);if(t===-1)throw new Error(`Unknown stage \`${e}\``);return t}var h0=!1;function WM(e){h0||(h0=!0,typeof console<"u"&&console.warn&&console.warn(`[pie-stage-tracker] Unexpected ${e.reason} stage transition from \`${e.from??"<none>"}\` to \`${e.to}\`. Stage transitions are expected to be monotonic within a cohort; call \`reset()\` when \`(sectionId, attemptId)\` changes.`))}function UM(e){const t=zM(e.sourceCeShape),r=new Set(t),n=e.now??(()=>new Date().toISOString()),i=e.onUnexpectedTransition??WM;let o=null,s=e.sectionId,a=e.attemptId;const l=new Set;function d(g,v){e.emit({stage:g,status:v,runtimeId:e.runtimeId,sectionId:s,attemptId:a,timestamp:n(),sourceCe:e.sourceCe})}function c(g){const v=xf(g),b=o===null?0:xf(o)+1;for(let w=b;w<v;w+=1){const I=rb[w];r.has(I)||l.has(I)||(l.add(I),d(I,"skipped"))}}function u(g,v="entered"){const b=xf(g),w=o===null?-1:xf(o);if(v==="entered"){if(l.has(g)){i({from:o,to:g,reason:"duplicate"});return}if(b<w){i({from:o,to:g,reason:"backward"});return}if(!r.has(g)){if(l.has(g))return;l.add(g),d(g,"skipped");return}c(g),l.add(g),o=g,d(g,"entered");return}if(v==="failed"){c(g),l.add(g),o=g,d(g,"failed");return}l.has(g)||(l.add(g),d(g,"skipped"))}function f(g){o=null,l.clear(),g&&(s=g.sectionId,a=g.attemptId)}function p(){return o}return{enter:u,reset:f,getCurrent:p}}var qM=[{sourceEventName:"pie-stage-change",instrumentationEventName:"pie-toolkit-stage-change"},{sourceEventName:"runtime-owned",instrumentationEventName:"pie-toolkit-runtime-owned"},{sourceEventName:"runtime-inherited",instrumentationEventName:"pie-toolkit-runtime-inherited"},{sourceEventName:"toolkit-ready",instrumentationEventName:"pie-toolkit-ready"},{sourceEventName:"section-ready",instrumentationEventName:"pie-toolkit-section-ready"},{sourceEventName:"framework-error",instrumentationEventName:"pie-toolkit-framework-error"}],Yp=[{sourceEventName:"pie-stage-change",instrumentationEventName:"pie-section-stage-change"},{sourceEventName:"pie-loading-complete",instrumentationEventName:"pie-section-loading-complete"},{sourceEventName:"framework-error",instrumentationEventName:"pie-section-framework-error"},{sourceEventName:"element-preload-retry",instrumentationEventName:"pie-section-element-preload-retry"},{sourceEventName:"element-preload-error",instrumentationEventName:"pie-section-element-preload-error"}],VM="",av=new Set(["complete","component","elementId","timestamp","sourceRuntimeId"]),GM=new Set(["id","element",...av]);function KM(e,t){if(!e&&!t)return!0;if(!e||!t||(e.id||"")!==(t.id||""))return!1;try{return JSON.stringify(e.data||[])===JSON.stringify(t.data||[])}catch{return!1}}function XM(e,t){return!t||e.id!==""?t:{...t,id:""}}function lv(e,t=VM){if(e&&typeof e=="object"){const r=e;return Array.isArray(r.data)?{id:typeof r.id=="string"?r.id:t,data:r.data}:Array.isArray(e)?{id:t,data:e}:{id:t,data:[e]}}return Array.isArray(e)?{id:t,data:e}:{id:t,data:[]}}var ZM=new Set(["id","element","complete","component","timestamp","sourceRuntimeId","shuffledValues"]);function cv(e,t){return e==null?!1:typeof e=="string"?e.trim()!=="":typeof e=="number"||typeof e=="boolean"?!0:Array.isArray(e)?e.some(r=>cv(r)):typeof e!="object"?!1:Object.entries(e).some(([r,n])=>r==="id"&&t!==void 0&&n===t?!1:cv(n,r))}function nb(e){return!e||typeof e!="object"?!1:Array.isArray(e)?e.some(nb):Object.entries(e).some(([t,r])=>!ZM.has(t)&&cv(r,t))}function dv(e){if(e==null)return!1;if(Array.isArray(e))return e.some(t=>dv(t));if(typeof e!="object")return!1;for(const[t,r]of Object.entries(e))if(t==="value"||dv(r))return!0;return!1}function p0(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Da(e,t){if(typeof e.component=="string")return e.component;if(typeof t?.component=="string")return t.component}function ja(e,t){if(typeof e.complete=="boolean")return e.complete;if(typeof t?.complete=="boolean")return t.complete}function Ba(e,t){const r=typeof e.elementId=="string"&&e.elementId?e.elementId:typeof t?.id=="string"&&t.id?t.id:void 0;return r?{elementId:r}:{}}function MT(e){const t=Object.keys(e);return("id"in e||"element"in e)&&!dv(e)&&t.every(r=>GM.has(r))}function YM(e){return e.data.length>0&&e.data.every(t=>t&&typeof t=="object"&&!Array.isArray(t)&&MT(t))}function $T(e,t){const r={...e};for(const[n,i]of Object.entries(t)){const o=r[n];r[n]=p0(o)&&p0(i)?$T(o,i):i}return r}function JM(e,t,r,n){const i=lv(t,e),o=[...i.data],s=o.findIndex(a=>!a||typeof a!="object"?!1:a.id===r);if(s>=0){const a=o[s];o[s]=a&&typeof a=="object"?$T(a,n):n}else o.push(n);return{id:i.id||e,data:o}}function LT(e){const t=QM(e),r=e.sessionDetail?.sessionCommitReason;return typeof r=="string"&&r?{...t,sessionCommitReason:r}:t}function QM(e){const t=e.sessionDetail||{},r=t&&typeof t=="object"&&"session"in t?t.session:e.sessionDetail,n=typeof e.itemId=="string"&&e.itemId?e.itemId:typeof r?.id=="string"?String(r.id):"";if(!r||typeof r!="object")return{itemId:n,session:null,intent:"metadata-only",component:Da(t),...Ba(t),complete:ja(t)};const i=r;if(Array.isArray(i.data)){const l=lv(i,n),d=XM(l,e.previousItemSession!==void 0?lv(e.previousItemSession,n):null),c=Object.keys(t),u=c.length>0&&c.every(p=>p==="session"||av.has(p)),f=c.some(p=>p!=="session");return u&&f&&d&&KM(l,d)?{itemId:n,session:null,intent:"metadata-only",component:Da(t),...Ba(t),complete:ja(t)}:u&&YM(l)?{itemId:n,session:null,intent:"metadata-only",component:Da(t),...Ba(t),complete:ja(t)}:{itemId:n,session:l,intent:"replace-item-session",component:Da(t),...Ba(t),complete:ja(t)}}const o=Object.keys(i);if(o.length>0&&o.every(l=>av.has(l)))return{itemId:n,session:null,intent:"metadata-only",component:Da(t,i),...Ba(t),complete:ja(t,i)};if(MT(i))return{itemId:n,session:null,intent:"metadata-only",component:Da(t,i),...Ba(t,i),complete:ja(t,i)};const s=Da(t,i)??"response",a=typeof i.id=="string"&&i.id?i.id:s;return{itemId:n,session:JM(n,e.previousItemSession,a,{id:a,...i}),intent:"merge-element-session",component:s,...Ba(t,i),complete:ja(t,i)}}var e$="commitPendingSession",OT=Symbol.for("pie.sessionCommit.observedSignature");function NT(e){return!!e&&typeof e=="object"}function DT(e){return e.tagName.includes("-")?"session"in e&&"model"in e:!1}function t$(e){return e?.shadowRoot??null}function r$(e){const t=e;if(typeof t.assignedElements!="function")return[];try{return t.assignedElements({flatten:!0})}catch{return[]}}function uv(e,t,r){const n=t$(e);n&&uv(n,t,r);const i=s=>{t.has(s)||(t.add(s),DT(s)&&r.push(s),uv(s,t,r))};for(const s of r$(e))i(s);const o=e.children;if(o)for(const s of Array.from(o))i(s)}function n$(e){return!!e&&typeof e=="object"&&typeof e.tagName=="string"}function i$(e){const t=[],r=new Set;return n$(e)&&DT(e)&&(r.add(e),t.push(e)),uv(e,r,t),t}function o$(e){try{return e.session}catch{return}}function s$(e){try{const t=JSON.stringify(e);return typeof t=="string"?t:null}catch{return null}}function a$(e){const t=e[OT];return typeof t=="string"?t:void 0}function m0(e,t){try{Object.defineProperty(e,OT,{value:t,configurable:!0,enumerable:!1,writable:!0})}catch{}}function l$(e,t,r){const n=e;if(typeof n.addEventListener!="function")return r();const i=o=>{const s=o.detail;if(!(!NT(s)||"sessionCommitReason"in s))try{s.sessionCommitReason=t}catch{}};n.addEventListener("session-changed",i,!0);try{return r()}finally{n.removeEventListener("session-changed",i,!0)}}function ib(e,t={}){const r={committed:0,synthesized:0,skipped:0};if(!e)return r;const n=t.reason??"teardown";return l$(e,n,()=>c$(e,n,t.logger,r))}function c$(e,t,r,n){const i=t?"commitPendingSessions":"flushPendingSessionNotifications";for(const o of i$(e)){const s=o$(o);if(!NT(s)){n.skipped+=1;continue}const a=s$(s);if(a===null){n.skipped+=1;continue}const l=a$(o);if(l===a){n.skipped+=1;continue}if(l===void 0&&!nb(s)){n.skipped+=1;continue}const d=o[e$];if(typeof d=="function"){let c=!1;const u=()=>{c=!0};o.addEventListener("session-changed",u,!0);let f=!1;try{d.call(o)}catch(p){f=!0,r?.warn(`[${i}] ${o.tagName.toLowerCase()} failed to commit its pending session`,p)}finally{o.removeEventListener("session-changed",u,!0)}if(f){n.skipped+=1;continue}if(c){m0(o,a),n.committed+=1;continue}}try{o.dispatchEvent(new CustomEvent("session-changed",{bubbles:!0,composed:!0,detail:{component:o.tagName.toLowerCase(),session:JSON.parse(a),...t?{sessionCommitReason:t}:{}}})),m0(o,a),n.synthesized+=1}catch(c){r?.warn(`[${i}] ${o.tagName.toLowerCase()} session commit dispatch failed`,c),n.skipped+=1}}return n}function d$(e){if(typeof document>"u"||typeof window>"u")return()=>{};const t=i=>{ib(e.root(),{reason:i,logger:e.logger});try{e.onHidden?.(i)}catch(o){e.logger?.warn("[bindPageLifecycleCommit] onHidden failed",o)}},r=()=>{document.visibilityState==="hidden"&&t("page-hidden")},n=()=>{t("page-hidden")};return document.addEventListener("visibilitychange",r),window.addEventListener("pagehide",n),()=>{document.removeEventListener("visibilitychange",r),window.removeEventListener("pagehide",n)}}var Ws=class{constructor(e,t){T(this,"host",void 0),T(this,"context",void 0),T(this,"currentValue",void 0),T(this,"subscriptions",new Map),T(this,"isConnected",!1),T(this,"handleContextRequest",r=>{if(r.context!==this.context)return;const n=this.getContextTarget(r,this.host);if(n===this.host)return;if(r.stopPropagation(),!r.subscribe){r.callback(this.currentValue);return}this.subscriptions.get(r.callback)?.unsubscribe();const i=()=>{this.subscriptions.delete(r.callback)};this.subscriptions.set(r.callback,{consumerHost:n,callback:r.callback,unsubscribe:i}),r.callback(this.currentValue,i)}),T(this,"handleContextProvider",r=>{if(r.context!==this.context||this.getContextTarget(r,this.host)===this.host)return;const n=new Set;for(const[i,{consumerHost:o}]of this.subscriptions)n.has(i)||(n.add(i),o.dispatchEvent(new ak(this.context,o,i,!0)));r.stopPropagation()}),this.host=e,this.context=t.context,this.currentValue=t.initialValue}connect(){this.isConnected||(this.isConnected=!0,this.host.addEventListener("context-request",this.handleContextRequest),this.host.addEventListener("context-provider",this.handleContextProvider),this.host.dispatchEvent(new X_(this.context,this.host)))}disconnect(){this.isConnected&&(this.isConnected=!1,this.host.removeEventListener("context-request",this.handleContextRequest),this.host.removeEventListener("context-provider",this.handleContextProvider),this.subscriptions.clear())}setValue(e,t=!1){!t&&Object.is(this.currentValue,e)||(this.currentValue=e,this.notifySubscribers())}get value(){return this.currentValue}getContextTarget(e,t){if("contextTarget"in e&&e.contextTarget)return e.contextTarget;const r=(typeof e.composedPath=="function"?e.composedPath():[])[0];return r||t}notifySubscribers(){for(const e of this.subscriptions.values())e.callback(this.currentValue,e.unsubscribe)}},u$=e=>{const t=[];for(const r of e)r.requestorRef.deref()&&r.callbackRef.deref()&&t.push(r);return t},Bl=class{constructor(e){T(this,"host",void 0),T(this,"pendingByContext",new Map),T(this,"attached",!1),T(this,"onContextRequest",t=>{if(!t.subscribe)return;let r=this.pendingByContext.get(t.context);r||(r={callbacks:new WeakMap,requests:[]},this.pendingByContext.set(t.context,r));const n=t.contextTarget,i=t.callback;let o=r.callbacks.get(n);o||(o=new WeakSet,r.callbacks.set(n,o)),!o.has(i)&&(o.add(i),r.requests.push({requestorRef:new WeakRef(n),callbackRef:new WeakRef(i)}),r.requests=u$(r.requests))}),T(this,"onContextProvider",t=>{const r=this.pendingByContext.get(t.context);if(!(!r||r.requests.length===0)){this.pendingByContext.delete(t.context);for(const n of r.requests){const i=n.requestorRef.deref(),o=n.callbackRef.deref();!i||!o||i.dispatchEvent(new ak(t.context,i,o,!0))}}}),this.host=e}attach(){this.attached||(this.attached=!0,this.host.addEventListener("context-request",this.onContextRequest),this.host.addEventListener("context-provider",this.onContextProvider))}detach(){this.attached&&(this.attached=!1,this.host.removeEventListener("context-request",this.onContextRequest),this.host.removeEventListener("context-provider",this.onContextProvider),this.pendingByContext.clear())}},g0="pie-register",f$="pie-unregister",h$="pie-item-session-changed",p$="item-session-changed",m$="pie-formative-action",g$="pie-media-time-source",v$={"nl-NL":()=>br(()=>import("./chunks/nl-NL-364d61b9.js"),[],import.meta.url)},y$=["en-US","nl-NL"];async function b$(e){const t=v$[e];if(!t)throw new Error(`No bundled i18n catalog for locale: ${e}`);return(await t()).default}function w$(e={}){return new aP({loadCatalog:b$,availableLocales:y$,...e})}var zm={assessment:[],section:[],item:[],passage:[],rubric:[],element:[]},xV={section:[...zm.section],item:[...zm.item],passage:[...zm.passage]};function S$(e){const t=e.trim();return t||""}function I$(e,t){const r=e.provider;return r?r.getProviderId?.(t)??t?.provider?.id??e.toolId:null}function k$(e,t){return T$(e.name,e.nameKey,t)}function T$(e,t,r){if(!t||!r)return e;const n=lP(t);if(r.hasKey)return r.hasKey(n)?r.t(n):e;const i=r.t(n);return i===t?e:i}var E$=["assessment","section","item","passage","rubric","element"];function hh(e,t){if(typeof e!="string"||e.trim().length===0)throw new Error(`Invalid tool registration: "${t}" must be a non-empty string.`)}var C$=[{pattern:/<script\b/i,reason:"contains a <script> tag"},{pattern:/\son[a-z]+\s*=/i,reason:"contains an inline event handler (on*=) attribute"},{pattern:/javascript:/i,reason:"contains a javascript: URL"},{pattern:/<foreignObject\b/i,reason:"contains a <foreignObject> element"}];function x$(e,t,r){const n=t.trimStart(),i=n.toLowerCase().startsWith("<svg"),o=/^https?:/i.test(n);if(/^data:/i.test(n))throw new Error(`Invalid tool registration "${e}": "${r}" may not be a data: URL.`);if(!(!i&&!o)){for(const{pattern:s,reason:a}of C$)if(s.test(t))throw new Error(`Invalid tool registration "${e}": "${r}" ${a}. Inline SVG icons must not include scriptable content.`)}}function v0(e){hh(e.toolId,"toolId"),hh(e.name,"name"),hh(e.description,"description");const t=e.activation==="region";if((!t||e.icon!==void 0)&&typeof e.icon!="string"&&typeof e.icon!="function")throw new Error(`Invalid tool registration "${e.toolId}": "icon" must be a string or function.`);if(typeof e.icon=="string"&&x$(e.toolId,e.icon,"icon"),!Array.isArray(e.supportedLevels)||e.supportedLevels.length===0)throw new Error(`Invalid tool registration "${e.toolId}": "supportedLevels" must be a non-empty array.`);const r=e.supportedLevels.find(n=>!E$.includes(n));if(r)throw new Error(`Invalid tool registration "${e.toolId}": unsupported level "${r}".`);if(e.activation!==void 0&&e.activation!=="toolbar-toggle"&&e.activation!=="selection-gateway"&&e.activation!=="region")throw new Error(`Invalid tool registration "${e.toolId}": unsupported activation "${String(e.activation)}".`);if(e.surfaces!==void 0&&(!Array.isArray(e.surfaces)||e.surfaces.some(n=>typeof n!="string"||n.trim().length===0)))throw new Error(`Invalid tool registration "${e.toolId}": "surfaces" must be an array of non-empty strings.`);if(t&&!e.surfaces?.length)throw new Error(`Invalid tool registration "${e.toolId}": region tools must declare at least one host surface in "surfaces".`);if(t&&typeof e.renderSurface!="function")throw new Error(`Invalid tool registration "${e.toolId}": region tools must implement "renderSurface".`);if(e.resolvesWithoutGrant!==void 0&&typeof e.resolvesWithoutGrant!="boolean")throw new Error(`Invalid tool registration "${e.toolId}": "resolvesWithoutGrant" must be a boolean.`);if(e.resolvesWithoutGrant&&!e.requiresAuthoredContent)throw new Error(`Invalid tool registration "${e.toolId}": "resolvesWithoutGrant" requires "requiresAuthoredContent".`);if(e.renderSurface!==void 0&&typeof e.renderSurface!="function")throw new Error(`Invalid tool registration "${e.toolId}": "renderSurface" must be a function.`);if(e.renderSurface&&!e.surfaces?.length)throw new Error(`Invalid tool registration "${e.toolId}": "renderSurface" requires at least one entry in "surfaces".`);if(e.singletonScope!==void 0&&e.singletonScope!=="section")throw new Error(`Invalid tool registration "${e.toolId}": unsupported singletonScope "${String(e.singletonScope)}".`);if(e.activation==="selection-gateway"&&e.singletonScope!=="section")throw new Error(`Invalid tool registration "${e.toolId}": selection-gateway tools must declare singletonScope "section".`);if(e.pnpSupportIds!==void 0&&(!Array.isArray(e.pnpSupportIds)||e.pnpSupportIds.some(n=>typeof n!="string"||n.trim().length===0)))throw new Error(`Invalid tool registration "${e.toolId}": "pnpSupportIds" must be an array of non-empty strings.`);if(e.activation!=="region"&&typeof e.isVisibleInContext!="function")throw new Error(`Invalid tool registration "${e.toolId}": "isVisibleInContext" must be a function.`);if(e.isVisibleInContext!==void 0&&typeof e.isVisibleInContext!="function")throw new Error(`Invalid tool registration "${e.toolId}": "isVisibleInContext" must be a function when present.`);if(e.isApplicableToContent!==void 0&&typeof e.isApplicableToContent!="function")throw new Error(`Invalid tool registration "${e.toolId}": "isApplicableToContent" must be a function when present.`);if(e.requiresAuthoredContent!==void 0){if(typeof e.requiresAuthoredContent!="object"||e.requiresAuthoredContent===null||typeof e.requiresAuthoredContent.resolve!="function")throw new Error(`Invalid tool registration "${e.toolId}": "requiresAuthoredContent" must be an object with a "resolve" function.`);if(!e.pnpSupportIds?.length)throw new Error(`Invalid tool registration "${e.toolId}": "requiresAuthoredContent" requires at least one entry in "pnpSupportIds", which is what a host filters a default grant list on.`)}if(e.renderToolbar!==void 0){if(typeof e.renderToolbar!="function")throw new Error(`Invalid tool registration "${e.toolId}": "renderToolbar" must be a function.`)}else if(!t)throw new Error(`Invalid tool registration "${e.toolId}": "renderToolbar" must be a function.`)}var R$=class{constructor(){T(this,"tools",new Map),T(this,"pnpIndex",new Map),T(this,"componentOverrides",{}),T(this,"moduleLoaders",new Map),T(this,"loadedToolModules",new Set),T(this,"moduleLoadPromises",new Map),T(this,"changeListeners",new Set)}emitChange(e){for(const t of this.changeListeners)try{t(e)}catch(r){console.warn("[ToolRegistry] change listener failed:",r)}}onRegistryChange(e){this.changeListeners.add(e);let t=!0;return()=>{t&&(t=!1,this.changeListeners.delete(e))}}normalizeToolId(e){return S$(e)}normalizeToolIds(e){return e.map(t=>this.normalizeToolId(t))}register(e){if(v0(e),this.tools.has(e.toolId))throw new Error(`Tool '${e.toolId}' is already registered`);if(this.tools.set(e.toolId,e),e.pnpSupportIds)for(const t of e.pnpSupportIds)this.pnpIndex.has(t)||this.pnpIndex.set(t,new Set),this.pnpIndex.get(t).add(e.toolId);this.emitChange({kind:"register",toolIds:[e.toolId]})}override(e){if(v0(e),!this.tools.has(e.toolId))throw new Error(`Cannot override non-existent tool '${e.toolId}'`);const t=this.tools.get(e.toolId);if(t.pnpSupportIds)for(const r of t.pnpSupportIds)this.pnpIndex.get(r)?.delete(e.toolId);if(this.tools.set(e.toolId,e),e.pnpSupportIds)for(const r of e.pnpSupportIds)this.pnpIndex.has(r)||this.pnpIndex.set(r,new Set),this.pnpIndex.get(r).add(e.toolId);this.emitChange({kind:"override",toolIds:[e.toolId]})}unregister(e){const t=this.tools.get(e);if(t){if(t.pnpSupportIds)for(const r of t.pnpSupportIds)this.pnpIndex.get(r)?.delete(e);this.tools.delete(e),this.emitChange({kind:"unregister",toolIds:[e]})}}get(e){return this.tools.get(e)}has(e){return this.tools.has(e)}getAllToolIds(){return Array.from(this.tools.keys())}getAllTools(){return Array.from(this.tools.values())}getToolsByPNPSupport(e){return this.pnpIndex.get(e)||new Set}getToolsByLevel(e){return this.getAllTools().filter(t=>t.supportedLevels.includes(e))}getToolActivation(e){return this.get(e)?.activation||"toolbar-toggle"}getToolSingletonScope(e){return this.get(e)?.singletonScope||null}getToolsBySurface(e){return e?this.getAllTools().filter(t=>typeof t.renderSurface=="function"&&t.surfaces?.includes(e)):[]}getContentDependentSupportIds(){const e=new Set;for(const t of this.getAllTools())if(t.requiresAuthoredContent)for(const r of t.pnpSupportIds||[])e.add(r);return[...e].sort()}filterToolIdsByActivation(e,t){return e.filter(r=>this.getToolActivation(r)===t)}filterVisibleInContext(e,t){const r=[];for(const n of e){const i=this.get(n);if(!i){console.warn(`Tool '${n}' is allowed but not registered`);continue}if(i.supportedLevels.includes(t.level))try{i.isVisibleInContext?.(t)&&r.push(i)}catch(o){console.error(`Error evaluating visibility for tool '${n}':`,o)}}return r}isApplicableToAnyContext(e,t){const r=this.get(e);return!r?.isApplicableToContent||t.length===0?!0:t.some(n=>{try{return r.isApplicableToContent?.(n)??!0}catch(i){return console.error(`Error evaluating applicability for tool '${e}':`,i),!0}})}getToolMetadata(){return this.getAllTools().map(e=>({toolId:e.toolId,name:e.name,description:e.description,pnpSupportIds:e.pnpSupportIds||[],supportedLevels:e.supportedLevels,activation:e.activation||"toolbar-toggle",singletonScope:e.singletonScope||null,surfaces:e.surfaces||[],requiresAuthoredContent:!!e.requiresAuthoredContent,contentDependencyDescription:e.requiresAuthoredContent?.description??null}))}generatePNPSupportsFromTools(e){const t=new Set;for(const r of e){const n=this.get(r);if(n?.pnpSupportIds)for(const i of n.pnpSupportIds)t.add(i)}return Array.from(t)}clear(){const e=this.getAllToolIds();e.length!==0&&(this.tools.clear(),this.pnpIndex.clear(),this.emitChange({kind:"clear",toolIds:e}))}setComponentOverrides(e){this.componentOverrides!==e&&(this.componentOverrides=e,this.emitChange({kind:"component-overrides",toolIds:[]}))}setToolModuleLoaders(e){const t=Object.entries(e).filter(n=>n[1]!==void 0);for(const[n,i]of t)if(hh(n,"tool module loader id"),typeof i!="function")throw new Error(`Invalid tool module loader for "${n}": expected a function.`);const r=[];for(const[n,i]of t)this.moduleLoaders.get(n)!==i&&(this.moduleLoaders.set(n,i),r.push(n));r.length>0&&this.emitChange({kind:"module-loaders",toolIds:r})}async ensureToolModuleLoaded(e){if(this.loadedToolModules.has(e))return;const t=this.moduleLoadPromises.get(e);if(t){await t;return}const r=this.moduleLoaders.get(e);if(!r)return;const n=(async()=>{await r(),this.loadedToolModules.add(e)})();this.moduleLoadPromises.set(e,n);try{await n}finally{this.moduleLoadPromises.delete(e)}}async ensureToolModulesLoaded(e){await Promise.all(e.map(t=>this.ensureToolModuleLoaded(t)))}isToolModuleLoaded(e){return this.loadedToolModules.has(e)}renderForToolbar(e,t,r){const n=this.get(e);if(!n)throw new Error(`Tool '${e}' is not registered`);if(typeof n.renderToolbar!="function")throw new Error(`Tool '${e}' has activation "${n.activation||"toolbar-toggle"}" and renders into a host surface, not a toolbar. Remove it from toolbar placement.`);const i={...r,componentOverrides:{...this.componentOverrides||{},...r.componentOverrides||{}}};return n.renderToolbar(t,i)}renderForSurface(e,t){const r=this.get(e);if(!r)throw new Error(`Tool '${e}' is not registered`);if(typeof r.renderSurface!="function")throw new Error(`Tool '${e}' does not render into a host surface. Surface capabilities declare "surfaces" and implement "renderSurface".`);return r.renderSurface({...t,componentOverrides:{...this.componentOverrides||{},...t.componentOverrides||{}}})}};function jT(e){return e.level==="item"}function _$(e){return e.level==="passage"}function P$(e){return e.level==="rubric"}function BT(e){return e.level==="element"}var A$=e=>e.replace(/<[^>]*>/g," ").trim();function Wm(e){return Array.isArray(e)?e:e&&typeof e=="object"?Object.values(e):[]}function Um(e,t){if(!(!e||typeof e!="object")){for(const r of Object.values(e))if(typeof r=="string"&&t(r),Array.isArray(r)){for(const n of r)if(n&&typeof n=="object")for(const i of Object.values(n))typeof i=="string"&&t(i)}}}function y0(e,t){if(!(!e||typeof e!="object"))for(const r of Object.values(e))typeof r=="string"&&t(r)}function FT(e,t){const r=[],n=o=>{r.push(t(o))},i=()=>r.filter(Boolean).join(" ").trim();if(BT(e)){const o=e.item.config;if(!o)return"";const s=o.elements?.[e.elementId];return typeof s=="string"&&n(s),Um(Wm(o.models).find(a=>!!a&&typeof a=="object"&&a.id===e.elementId),n),i()}if(jT(e)){const o=e.item?.config;if(!o)return"";typeof o.markup=="string"&&n(o.markup),y0(o.elements,n);for(const s of Wm(o.models))Um(s,n);return i()}if(_$(e)){const o=e.passage?.config;if(!o)return"";for(const s of["markup","content","prompt"]){const a=o[s];typeof a=="string"&&n(a)}y0(o.elements,n);for(const s of Wm(o.models))Um(s,n);return i()}if(P$(e)){const o=e.rubricBlock;return o.passage?.config?t(o.passage.config.markup||""):t(o.content||"")}return""}function ob(e){return FT(e,A$)}function M$(e){return FT(e,t=>t)}var $$=new Set(["H","He","Li","Be","B","C","N","O","F","Ne","Na","Mg","Al","Si","P","S","Cl","Ar","K","Ca","Sc","Ti","V","Cr","Mn","Fe","Co","Ni","Cu","Zn","Ga","Ge","As","Se","Br","Kr","Rb","Sr","Y","Zr","Nb","Mo","Tc","Ru","Rh","Pd","Ag","Cd","In","Sn","Sb","Te","I","Xe","Cs","Ba","La","Ce","Pr","Nd","Pm","Sm","Eu","Gd","Tb","Dy","Ho","Er","Tm","Yb","Lu","Hf","Ta","W","Re","Os","Ir","Pt","Au","Hg","Tl","Pb","Bi","Po","At","Rn","Fr","Ra","Ac","Th","Pa","U","Np","Pu","Am","Cm","Bk","Cf","Es","Fm","Md","No","Lr"]),L$=/\b[A-Z][A-Za-z]*\d*(?:[A-Z][A-Za-z]*\d*)*\b/g,qm=/([A-Z][a-z]?)(\d*)/g;function O$(e){for(const t of e.match(L$)??[]){qm.lastIndex=0;let r=0,n=!1,i=0,o=!0,s=qm.exec(t);for(;s!==null&&s[0]!=="";){if(!$$.has(s[1])){o=!1;break}r+=1,s[2]&&(n=!0),i+=s[0].length,s=qm.exec(t)}if(o&&i===t.length&&(r>1||n))return!0}return!1}function Jp(e){const t=M$(e);if([/<math[>\s]/i,/\\\[([^\]]+)\\\]/,/\$\$[^$]+\$\$/,/\\\(/].some(n=>n.test(t)))return!0;const r=ob(e);return[/[≤≥≠±×÷∑∫√∞π]/,/\d+\s*[+\-*/×÷=]\s*\d+/,/\d\s*[<>]\s*\d/,/\b\d+\s*\/\s*\d+\b/,/\b\d+(?:\.\d+)?\s*%/,/\^\s*\d/].some(n=>n.test(r))}var b0=new Set(["multiple-choice","inline-choice","select-text","ebsr"]),N$=e=>e.toLowerCase().replace(/--version-[0-9a-z-]+$/,"").replace(/^pie-(element-)?/,"");function w0(e,t){if(b0.has(N$(e)))return!0;if(!t||typeof t!="object")return!1;const r=t,n=r[e]??r[e.replace(/--version-[0-9A-Za-z-]+$/,"")];if(typeof n!="string")return!1;const i=n.match(/^@pie-element\/([^@]+)/)?.[1];return!!i&&b0.has(i)}function S0(e){if(BT(e)){const t=e.item.config;if(!t?.models)return!1;const r=(Array.isArray(t.models)?t.models:Object.values(t.models)).find(n=>n&&typeof n=="object"&&n.id===e.elementId);return r?w0(r.element||"",t.elements):!1}if(jT(e)){const t=e.item.config,r=t?.models;return(Array.isArray(r)?r:r&&typeof r=="object"?Object.values(r):[]).some(n=>{if(!n||typeof n!="object")return!1;const i=n.element||"";return i?w0(i,t?.elements):Array.isArray(n.choices)&&n.choices.length>0})}return!1}function Ku(e){return ob(e).trim().length>=10}function D$(e){const t=ob(e);return O$(t)||/[A-Z][a-z]?[\u2080-\u2089]/.test(t)?!0:[/chemistry|chemical|molecule|compound|periodic\s+table/i,/\bchemical\s+element\b|\belement\s+symbol\b/i,/biology|organism|\bDNA\b|\bRNA\b|protein|photosynthesis|ecosystem/i,/physics|\bforce\b|\benergy\b|velocity|acceleration|momentum/i].some(r=>r.test(t))}function HT(e){return{kind:e.kind,severity:e.severity??"error",source:e.source,message:e.message,details:[...e.details||[]],recoverable:e.recoverable===!0,cause:e.cause}}var zT=(e,t)=>{const r=t?.toolTagMap?.[e];if(r===void 0&&!e.includes("-"))throw new Error(`No element tag is mapped for tool "${e}". Install a tag map on the registry via setComponentOverrides({ toolTagMap }) — for the packaged capabilities, PACKAGED_TOOL_TAG_MAP from "@pie-players/pie-default-tool-loaders".`);return Ny(r??e,`tool component tag for "${e}"`)},j$=e=>document.createElement(e),Qp=(e,t,r,n)=>{const i=zT(e,n),o=n?.toolComponentFactories?.[e]??n?.toolComponentFactory;return o?o({toolId:e,tagName:i,context:t,toolbarContext:r}):j$(i)},B$=/^[a-z][a-z0-9+.-]*:/i,F$=new Set(["http:","https:","data:","blob:"]);function H$(e){return e!==void 0&&e!==1}function z$(e){if(typeof e!="string")return!1;const t=e.trim();if(!t)return!1;if(t.startsWith("//")||!B$.test(t))return!0;const r=t.slice(0,t.indexOf(":")+1).toLowerCase();return F$.has(r)}function W$(e){if(!Array.isArray(e))return[];const t=[];for(const r of e){if(!r||typeof r!="object")continue;const n=r;if(!z$(n.src))continue;const i={src:n.src.trim()};typeof n.type=="string"&&n.type.trim()&&(i.type=n.type.trim()),Number.isFinite(n.width)&&(i.width=n.width),Number.isFinite(n.height)&&(i.height=n.height),!t.some(o=>o.src===i.src)&&t.push(i)}return t}function WT(e){if(!e||typeof e!="object")return;const t=e,r=Number(t.startSeconds);if(!Number.isFinite(r)||r<0)return;const n=Number(t.endSeconds);return!Number.isFinite(n)||n<=r?{startSeconds:r}:{startSeconds:r,endSeconds:n}}function U$(e){if(typeof e=="string")return e.trim()||void 0}var q$=100,V$=1;function G$(e,t,r){if(!t)return()=>{};const{startSeconds:n,endSeconds:i}=t;let o;n>0&&(o=()=>{e.currentTime<n&&(e.currentTime=n)},e.readyState>=V$?o():e.addEventListener("loadedmetadata",o));let s,a;return i!==void 0&&(s=()=>{e.currentTime>=i&&r()},e.addEventListener("timeupdate",s),a=setInterval(()=>{e.paused||s?.()},q$)),()=>{o&&e.removeEventListener("loadedmetadata",o),s&&e.removeEventListener("timeupdate",s),a!==void 0&&clearInterval(a)}}function K$(e,t){if(!t||e.includes("#"))return e;const r=t.endSeconds!==void 0?`,${t.endSeconds}`:"";return`${e}#t=${t.startSeconds}${r}`}var X$=class{constructor(){T(this,"listeners",new Set)}subscribeFrameworkErrors(e){this.listeners.add(e);let t=!0;return()=>{t&&(t=!1,this.listeners.delete(e))}}reportFrameworkError(e){const t=Array.from(this.listeners);for(const r of t)try{r(e)}catch(n){console.warn("[FrameworkErrorBus] listener failed:",n)}}dispose(){this.listeners.clear()}getListenerCount(){return this.listeners.size}},Z$=(e,t)=>{const r=t?.useSentenceSegmenter!==!1;try{if(!r)throw new Error("Segmenter disabled by policy");const s=globalThis.Intl?.Segmenter;if(typeof s=="function"){const a=new s(t?.locale,{granularity:"sentence"}),l=Array.from(a.segment(e)).map(d=>({text:d.segment,offset:d.index})).filter(d=>d.text.trim().length>0);if(l.length>0)return l}}catch{}const n=e.match(/[^.!?]+(?:[.!?]+|$)/g)||[e],i=[];let o=0;for(const s of n){const a=e.indexOf(s,o);a!==-1&&(i.push({text:s,offset:a}),o=a+s.length)}return i.length>0?i:[{text:e,offset:0}]},I0=5e3,k0=2e3,UT=e=>String(e||"").trim().toLowerCase(),Y$=()=>{const e=typeof navigator<"u"?navigator.language||navigator.languages?.[0]:"";return UT(e||"en-US")},J$=(e,t)=>{if(t)return e.find(s=>s.voiceURI===t)||e.find(s=>s.name===t)||null;const r=Y$(),n=r.split("-")[0]||"en",i=s=>{const a=UT(s.lang);return a===r||a.startsWith(`${n}-`)},o=[s=>s.localService&&i(s),s=>s.default&&i(s),s=>i(s),s=>s.localService,s=>s.default];for(const s of o){const a=e.find(s);if(a)return a}return e[0]||null},Q$=e=>!e.default,eL=class{constructor(){T(this,"providerId","browser"),T(this,"providerName","Browser Speech Synthesis"),T(this,"version","1.0.0")}async initialize(e){if(typeof window>"u")throw new Error("BrowserTTSProvider requires browser environment");if(!("speechSynthesis"in window))throw new Error("Browser does not support Speech Synthesis API");return new tL(e)}supportsFeature(e){return!0}getCapabilities(){return{supportsPause:!0,supportsResume:!0,supportsWordBoundary:!0,supportsVoiceSelection:!0,supportsRateControl:!0,supportsPitchControl:!0,supportsSSML:!1}}destroy(){}},tL=class{constructor(e){T(this,"utterance",null),T(this,"config",null),T(this,"_isPlaying",!1),T(this,"_isPaused",!1),T(this,"speakRunId",0),T(this,"settlePendingVoiceWait",null),T(this,"settlePendingChunk",null),T(this,"onPlaybackStart",void 0),T(this,"onWordBoundary",void 0),this.config=e}waitForBrowserVoices(e,t){return new Promise((r,n)=>{const i=speechSynthesis,o=typeof i.addEventListener=="function"&&typeof i.removeEventListener=="function",s=o?null:i.onvoiceschanged;let a=!1,l=null,d=null;const c=()=>{l!==null&&(clearTimeout(l),l=null),o?i.removeEventListener("voiceschanged",p):i.onvoiceschanged===g&&(i.onvoiceschanged=s),d&&this.settlePendingVoiceWait===d&&(this.settlePendingVoiceWait=null)},u=(v,b)=>{a||(a=!0,c(),b?n(b):r(v))},f=()=>{if(e!==this.speakRunId){u(!1);return}i.getVoices().length>0&&u(!0)},p=()=>f(),g=v=>{try{s?.call(i,v)}finally{f()}};d=()=>u(!1),this.settlePendingVoiceWait=d,l=setTimeout(()=>u(!1,new Error(`Configured browser voice "${t}" could not be resolved because the browser did not publish its voice inventory within ${k0/1e3} seconds.`)),k0),o?i.addEventListener("voiceschanged",p):i.onvoiceschanged=g,f()})}async resolveBrowserVoice(e){const t=typeof this.config?.voice=="string"?this.config.voice.trim():"";let r=speechSynthesis.getVoices();if(t&&r.length===0){if(!await this.waitForBrowserVoices(e,t)||e!==this.speakRunId)return{shouldContinue:!1,voice:null};r=speechSynthesis.getVoices()}if(e!==this.speakRunId)return{shouldContinue:!1,voice:null};const n=J$(r,t||void 0);if(t&&!n)throw new Error(`Configured browser voice "${t}" is unavailable. Select a voice exposed by this browser using its voiceURI or name.`);return{shouldContinue:!0,voice:n}}async speak(e){if(!this.config)throw new Error("TTS not initialized");this.stop();const t=this.speakRunId,r=await this.resolveBrowserVoice(t);if(!r.shouldContinue)return;const n=this.splitIntoChunks(e);for(const i of n)if(t!==this.speakRunId||!await this.speakChunk(i.text,i.offset,t,r.voice))break}async speakSegments(e){if(!this.config)throw new Error("TTS not initialized");this.stop();const t=this.speakRunId,r=await this.resolveBrowserVoice(t);if(r.shouldContinue)for(const n of e){if(t!==this.speakRunId)break;const i=this.splitIntoChunks(n.text);for(const s of i)if(t!==this.speakRunId||!await this.speakChunk(s.text,n.startOffset+s.offset,t,r.voice))break;const o=Math.max(0,Number(n.pauseMsAfter||0));if(o>0&&t===this.speakRunId&&!await this.waitForPause(o,t))break}}async waitForPause(e,t){return await new Promise(r=>setTimeout(r,e)),t===this.speakRunId}splitIntoChunks(e){if(e.length<=260)return[{text:e,offset:0}];const r=this.segmentSentences(e),n=[];let i="",o=0;for(const s of r){const a=s.text.trim();if(!a)continue;const l=s.text.search(/\S/),d=s.offset+(l===-1?0:l);if(!i){i=a,o=d;continue}const c=`${i} ${a}`;c.length<=260?i=c:(n.push({text:i,offset:o}),i=a,o=d)}return i&&n.push({text:i,offset:o}),n.length?n:[{text:e,offset:0}]}getHighlightMode(){return(this.config?.providerOptions||{}).highlightMode==="word"?"word":"sentence"}getSegmentationPolicy(){const e=this.config?.providerOptions||{},t=e.segmenter||{},r=t.mode!=="regexOnly";return{useSentenceSegmenter:r,useWordSegmenter:r,locale:typeof t.locale=="string"&&t.locale.trim().length>0?t.locale:typeof e.locale=="string"&&e.locale.trim().length>0?e.locale:void 0}}segmentSentences(e){const t=this.getSegmentationPolicy();return Z$(e,{locale:t.locale,useSentenceSegmenter:t.useSentenceSegmenter})}inferWordLength(e,t){const r=Math.max(0,Math.min(t,Math.max(0,e.length-1)));return e.slice(r).match(/^\s*([^\s]+)/)?.[1]?.length||1}async speakChunk(e,t,r,n){return new Promise((i,o)=>{if(r!==this.speakRunId){i(!1);return}const s=new SpeechSynthesisUtterance(e);this.utterance=s,n&&Q$(n)&&(s.voice=n),this.config?.rate&&(s.rate=this.config.rate),this.config?.pitch&&(s.pitch=this.config.pitch);let a=!1,l=!1,d=null,c=null;const u=()=>{this.utterance===s&&(this.utterance=null)},f=()=>{d!==null&&(clearTimeout(d),d=null)},p=()=>{s.onstart=null,s.onend=null,s.onerror=null,s.onpause=null,s.onresume=null,s.onboundary=null},g=(b,w)=>{l||(l=!0,f(),p(),u(),c&&this.settlePendingChunk===c&&(this.settlePendingChunk=null),r===this.speakRunId&&(this._isPlaying=!1,this._isPaused=!1),w?o(w):i(b))},v=b=>new Error(b==="ended"?"Browser speech synthesis ended before audio started. The browser speech engine may be unavailable or stuck; try another voice or restart the browser.":`Browser speech synthesis did not start within ${I0/1e3} seconds. The browser speech engine may be unavailable or stuck; try another voice or restart the browser.`);c=()=>g(!1),this.settlePendingChunk=c,s.onstart=()=>{if(r!==this.speakRunId){g(!1);return}a=!0,f(),this._isPlaying=!0,this._isPaused=!1;try{this.onPlaybackStart?.()}catch(b){console.error("Browser TTS playback-start callback failed",b)}},s.onend=()=>{if(r!==this.speakRunId){g(!1);return}if(!a){g(!1,v("ended"));return}g(!0)},s.onerror=b=>{if(r!==this.speakRunId){g(!1);return}if(b.error==="interrupted"||b.error==="canceled"){g(!1);return}g(!1,new Error(`Speech synthesis error: ${b.error}`))},s.onpause=()=>{r===this.speakRunId&&(this._isPaused=!0)},s.onresume=()=>{r===this.speakRunId&&(this._isPaused=!1)},s.onboundary=b=>{if(r!==this.speakRunId||(console.log("[BrowserProvider] Boundary event:",b.name,"charIndex:",b.charIndex,"charLength:",b.charLength),b.name!=="word"||!this.onWordBoundary)||this.getHighlightMode()==="sentence")return;const w=Math.max(0,Math.min(b.charIndex,Math.max(0,e.length-1))),I=Number(b.charLength||0),x=this.inferWordLength(e,w),C=Number.isFinite(I)&&I>0&&I<=80&&w+I<=e.length?I:x,L=e.substring(w,Math.min(e.length,w+C)).trim(),E=t+w;console.log("[BrowserProvider] Calling onWordBoundary with word:",L,"at position:",E),this.onWordBoundary(L,E,C)},d=setTimeout(()=>{l||a||r!==this.speakRunId||(g(!1,v("timedOut")),speechSynthesis.cancel())},I0);try{speechSynthesis.speak(s)}catch(b){g(!1,b instanceof Error?b:new Error("Browser speech synthesis failed to queue speech"))}})}pause(){this._isPlaying&&!this._isPaused&&speechSynthesis.pause()}resume(){this._isPlaying&&this._isPaused&&speechSynthesis.resume()}stop(){const e=this.utterance,t=this._isPlaying||e!==null;this.speakRunId+=1,this.settlePendingVoiceWait?.(),this.settlePendingChunk?.(),t&&speechSynthesis.cancel(),this.utterance=null,this._isPlaying=!1,this._isPaused=!1}isPlaying(){return this._isPlaying&&!this._isPaused}isPaused(){return this._isPaused}updateSettings(e){this.config||(this.config={}),e.rate!==void 0&&(this.config.rate=e.rate),e.pitch!==void 0&&(this.config.pitch=e.pitch),e.voice!==void 0&&(this.config.voice=e.voice),e.providerOptions!==void 0&&(this.config.providerOptions={...this.config.providerOptions||{},...e.providerOptions||{}})}};function rL(e,t){return{providerId:e.providerId,providerName:e.providerName,version:e.version,initialize:r=>{const n=r,i={...n,...t,headers:{...n.headers,...t.headers},providerOptions:{...n.providerOptions,...t.providerOptions}};return e.initialize(i)},supportsFeature:r=>e.supportsFeature(r),getCapabilities:()=>e.getCapabilities(),destroy:()=>e.destroy()}}var nL=class{async emitTelemetry(e,t){try{await this.config?.onTelemetry?.(e,t)}catch(r){console.warn("[TTSToolProvider] telemetry callback failed:",r)}}constructor(e="browser",t={}){T(this,"providerId","tts-service"),T(this,"providerName","Text-to-Speech"),T(this,"category","tts"),T(this,"version","1.0"),T(this,"requiresAuth",void 0),T(this,"ttsProvider",null),T(this,"config",null),T(this,"loadServerProvider",void 0),this.requiresAuth=e!=="browser",this.loadServerProvider=t.loadServerProvider}async initialize(e){if(this.ttsProvider){console.warn("[TTSToolProvider] Already initialized, skipping reinitialization");return}switch(this.config=e,e.backend){case"browser":await this._initializeBrowserTTS(e);break;case"polly":case"google":case"server":await this._initializeServerTTS(e);break;default:throw new Error(`[TTSToolProvider] Unknown backend: ${e.backend}`)}console.log(`[TTSToolProvider] Initialized successfully (backend: ${e.backend})`)}async _initializeBrowserTTS(e){if(typeof window>"u"||!("speechSynthesis"in window))throw new Error("[TTSToolProvider] Browser TTS not supported (Web Speech API not available)");this.ttsProvider=new eL,console.log("[TTSToolProvider] Browser TTS initialized (Web Speech API)")}async _initializeServerTTS(e){if(!e.apiEndpoint)throw new Error("[TTSToolProvider] apiEndpoint required for server-based TTS backends");const t=this.loadServerProvider;if(!t)throw new Error("[TTSToolProvider] server-based TTS backends need the loadServerProvider option");const r=Date.now();await this.emitTelemetry("pie-tool-library-load-start",{toolId:"textToSpeech",operation:"server-provider-module-import",backend:e.serverProvider||e.backend});const n=await(async()=>{try{const l=await t();return await this.emitTelemetry("pie-tool-library-load-success",{toolId:"textToSpeech",operation:"server-provider-module-import",backend:e.serverProvider||e.backend,duration:Date.now()-r}),l}catch(l){throw await this.emitTelemetry("pie-tool-library-load-error",{toolId:"textToSpeech",operation:"server-provider-module-import",backend:e.serverProvider||e.backend,duration:Date.now()-r,errorType:"ToolLibraryLoadError",message:l instanceof Error?l.message:String(l)}),l}})(),{backend:i,serverProvider:o,onTelemetry:s,...a}=e;this.ttsProvider=rL(new n,a),console.log(`[TTSToolProvider] Server TTS initialized (provider: ${e.serverProvider||e.backend})`)}async createInstance(e){if(!this.ttsProvider)throw new Error("[TTSToolProvider] Provider not initialized. Call initialize() first.");return this.ttsProvider}getCapabilities(){const e=this.config?.backend==="browser";return{supportsOffline:e,requiresAuth:!e,maxInstances:1,features:{wordBoundary:!0,pause:!0,resume:!0,rateControl:!0,pitchControl:e,voiceSelection:!0}}}isReady(){return this.ttsProvider!==null}destroy(){this.ttsProvider&&(this.ttsProvider.destroy(),this.ttsProvider=null),this.config=null,console.log("[TTSToolProvider] Destroyed")}};function iL(e){return e?.rule==="host-blocked"||e?.rule==="host-allowlist"}var oL=["assessment","section","item","passage","rubric"],sL=new Set(oL);function aL(e){return sL.has(e)}function sb(e,t,r){const n=e.trim(),i=r.trim();if(!n||!i)throw new Error("Tool instance ids require non-empty tool and scope ids");if(!aL(t))throw new Error(`Unknown tool scope level '${t}'. Register custom levels with registerToolScopeLevel().`);return`${n}:${t}:${i}`}var lL=1;function qT(){return new Date().toISOString()}function cL(e){const t=qT();return{version:lL,testAttemptSessionIdentifier:e.testAttemptSessionIdentifier,assessmentId:e.assessmentId,startedAt:t,updatedAt:t,navigationState:{currentItemIndex:-1,visitedItemIdentifiers:[]},realization:{seed:e.seed,itemIdentifiers:e.itemIdentifiers},itemSessions:{}}}function dL(e,t){if(!t)return e;const r=new Set(e.navigationState.visitedItemIdentifiers||[]);return r.add(t),{...e,navigationState:{...e.navigationState,visitedItemIdentifiers:Array.from(r)}}}function uL(e,t){return{...e,navigationState:{...e.navigationState,currentItemIndex:t.currentItemIndex,currentSectionIdentifier:t.currentSectionIdentifier}}}function fL(e,t){const{itemIdentifier:r,pieSessionId:n,isCompleted:i}=t;if(!r||!n)return e;const o=qT(),s=e.itemSessions[r],a=s&&s.pieSessionId&&s.pieSessionId!==n?s.attemptCount+1:s?s.attemptCount:1,l=!!(i??s?.isCompleted),d={itemIdentifier:r,pieSessionId:n,attemptCount:a,isCompleted:l,startedAt:s?.startedAt||o,updatedAt:o,completedAt:l?s?.completedAt||o:void 0,session:t.session??s?.session};return{...e,itemSessions:{...e.itemSessions,[r]:d}}}function fv(e){return Object.entries(e.itemSessions).reduce((t,[r,n])=>(n.session&&(t[r]=n.session),t),{})}function hL(e,t="iife"){return e==="iife"||e==="esm"||e==="preloaded"?e:t}function T0(e){const t={};return e.forEach(r=>{const n=r.config?.elements||{};Object.entries(n).forEach(([i,o])=>{const s=String(o),a=uk(i,s,{preserveUnversionedTag:!0});if(!t[a])t[a]=s;else if(t[a]!==s)throw new Error(`Element version conflict: ${a} requires both ${t[a]} and ${s}. Each full versioned tag must map to exactly one package spec.`)})}),t}var Xu=Ct(((e,t)=>{var r="2.0.0",n=256,i=Number.MAX_SAFE_INTEGER||9007199254740991,o=16,s=250,a=["major","premajor","minor","preminor","patch","prepatch","prerelease"];t.exports={MAX_LENGTH:n,MAX_SAFE_COMPONENT_LENGTH:o,MAX_SAFE_BUILD_LENGTH:s,MAX_SAFE_INTEGER:i,RELEASE_TYPES:a,SEMVER_SPEC_VERSION:r,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}})),em=Ct(((e,t)=>{var r=typeof process=="object"&&{}.NODE_DEBUG&&/\bsemver\b/i.test({}.NODE_DEBUG)?(...n)=>console.error("SEMVER",...n):()=>{};t.exports=r})),Zu=Ct(((e,t)=>{var{MAX_SAFE_COMPONENT_LENGTH:r,MAX_SAFE_BUILD_LENGTH:n,MAX_LENGTH:i}=Xu(),o=em();e=t.exports={};var s=e.re=[],a=e.safeRe=[],l=e.src=[],d=e.safeSrc=[],c=e.t={},u=0,f="[a-zA-Z0-9-]",p=[["\\s",1],["\\d",i],[f,n]],g=b=>{for(const[w,I]of p)b=b.split(`${w}*`).join(`${w}{0,${I}}`).split(`${w}+`).join(`${w}{1,${I}}`);return b},v=(b,w,I)=>{const x=g(w),C=u++;o(b,C,w),c[b]=C,l[C]=w,d[C]=x,s[C]=new RegExp(w,I?"g":void 0),a[C]=new RegExp(x,I?"g":void 0)};v("NUMERICIDENTIFIER","0|[1-9]\\d*"),v("NUMERICIDENTIFIERLOOSE","\\d+"),v("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${f}*`),v("MAINVERSION",`(${l[c.NUMERICIDENTIFIER]})\\.(${l[c.NUMERICIDENTIFIER]})\\.(${l[c.NUMERICIDENTIFIER]})`),v("MAINVERSIONLOOSE",`(${l[c.NUMERICIDENTIFIERLOOSE]})\\.(${l[c.NUMERICIDENTIFIERLOOSE]})\\.(${l[c.NUMERICIDENTIFIERLOOSE]})`),v("PRERELEASEIDENTIFIER",`(?:${l[c.NONNUMERICIDENTIFIER]}|${l[c.NUMERICIDENTIFIER]})`),v("PRERELEASEIDENTIFIERLOOSE",`(?:${l[c.NONNUMERICIDENTIFIER]}|${l[c.NUMERICIDENTIFIERLOOSE]})`),v("PRERELEASE",`(?:-(${l[c.PRERELEASEIDENTIFIER]}(?:\\.${l[c.PRERELEASEIDENTIFIER]})*))`),v("PRERELEASELOOSE",`(?:-?(${l[c.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${l[c.PRERELEASEIDENTIFIERLOOSE]})*))`),v("BUILDIDENTIFIER",`${f}+`),v("BUILD",`(?:\\+(${l[c.BUILDIDENTIFIER]}(?:\\.${l[c.BUILDIDENTIFIER]})*))`),v("FULLPLAIN",`v?${l[c.MAINVERSION]}${l[c.PRERELEASE]}?${l[c.BUILD]}?`),v("FULL",`^${l[c.FULLPLAIN]}$`),v("LOOSEPLAIN",`[v=\\s]*${l[c.MAINVERSIONLOOSE]}${l[c.PRERELEASELOOSE]}?${l[c.BUILD]}?`),v("LOOSE",`^${l[c.LOOSEPLAIN]}$`),v("GTLT","((?:<|>)?=?)"),v("XRANGEIDENTIFIERLOOSE",`${l[c.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`),v("XRANGEIDENTIFIER",`${l[c.NUMERICIDENTIFIER]}|x|X|\\*`),v("XRANGEPLAIN",`[v=\\s]*(${l[c.XRANGEIDENTIFIER]})(?:\\.(${l[c.XRANGEIDENTIFIER]})(?:\\.(${l[c.XRANGEIDENTIFIER]})(?:${l[c.PRERELEASE]})?${l[c.BUILD]}?)?)?`),v("XRANGEPLAINLOOSE",`[v=\\s]*(${l[c.XRANGEIDENTIFIERLOOSE]})(?:\\.(${l[c.XRANGEIDENTIFIERLOOSE]})(?:\\.(${l[c.XRANGEIDENTIFIERLOOSE]})(?:${l[c.PRERELEASELOOSE]})?${l[c.BUILD]}?)?)?`),v("XRANGE",`^${l[c.GTLT]}\\s*${l[c.XRANGEPLAIN]}$`),v("XRANGELOOSE",`^${l[c.GTLT]}\\s*${l[c.XRANGEPLAINLOOSE]}$`),v("COERCEPLAIN",`(^|[^\\d])(\\d{1,${r}})(?:\\.(\\d{1,${r}}))?(?:\\.(\\d{1,${r}}))?`),v("COERCE",`${l[c.COERCEPLAIN]}(?:$|[^\\d])`),v("COERCEFULL",l[c.COERCEPLAIN]+`(?:${l[c.PRERELEASE]})?(?:${l[c.BUILD]})?(?:$|[^\\d])`),v("COERCERTL",l[c.COERCE],!0),v("COERCERTLFULL",l[c.COERCEFULL],!0),v("LONETILDE","(?:~>?)"),v("TILDETRIM",`(\\s*)${l[c.LONETILDE]}\\s+`,!0),e.tildeTrimReplace="$1~",v("TILDE",`^${l[c.LONETILDE]}${l[c.XRANGEPLAIN]}$`),v("TILDELOOSE",`^${l[c.LONETILDE]}${l[c.XRANGEPLAINLOOSE]}$`),v("LONECARET","(?:\\^)"),v("CARETTRIM",`(\\s*)${l[c.LONECARET]}\\s+`,!0),e.caretTrimReplace="$1^",v("CARET",`^${l[c.LONECARET]}${l[c.XRANGEPLAIN]}$`),v("CARETLOOSE",`^${l[c.LONECARET]}${l[c.XRANGEPLAINLOOSE]}$`),v("COMPARATORLOOSE",`^${l[c.GTLT]}\\s*(${l[c.LOOSEPLAIN]})$|^$`),v("COMPARATOR",`^${l[c.GTLT]}\\s*(${l[c.FULLPLAIN]})$|^$`),v("COMPARATORTRIM",`(\\s*)${l[c.GTLT]}\\s*(${l[c.LOOSEPLAIN]}|${l[c.XRANGEPLAIN]})`,!0),e.comparatorTrimReplace="$1$2$3",v("HYPHENRANGE",`^\\s*(${l[c.XRANGEPLAIN]})\\s+-\\s+(${l[c.XRANGEPLAIN]})\\s*$`),v("HYPHENRANGELOOSE",`^\\s*(${l[c.XRANGEPLAINLOOSE]})\\s+-\\s+(${l[c.XRANGEPLAINLOOSE]})\\s*$`),v("STAR","(<|>)?=?\\s*\\*"),v("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$"),v("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")})),ab=Ct(((e,t)=>{var r=Object.freeze({loose:!0}),n=Object.freeze({}),i=o=>o?typeof o!="object"?r:o:n;t.exports=i})),VT=Ct(((e,t)=>{var r=/^[0-9]+$/,n=(o,s)=>{if(typeof o=="number"&&typeof s=="number")return o===s?0:o<s?-1:1;const a=r.test(o),l=r.test(s);return a&&l&&(o=+o,s=+s),o===s?0:a&&!l?-1:l&&!a?1:o<s?-1:1},i=(o,s)=>n(s,o);t.exports={compareIdentifiers:n,rcompareIdentifiers:i}})),Qn=Ct(((e,t)=>{var r=em(),{MAX_LENGTH:n,MAX_SAFE_INTEGER:i}=Xu(),{safeRe:o,t:s}=Zu(),a=ab(),{compareIdentifiers:l}=VT(),d=(u,f)=>{const p=f.split(".");if(p.length>u.length)return!1;for(let g=0;g<p.length;g++)if(l(u[g],p[g])!==0)return!1;return!0},c=class os{constructor(f,p){if(p=a(p),f instanceof os){if(f.loose===!!p.loose&&f.includePrerelease===!!p.includePrerelease)return f;f=f.version}else if(typeof f!="string")throw new TypeError(`Invalid version. Must be a string. Got type "${typeof f}".`);if(f.length>n)throw new TypeError(`version is longer than ${n} characters`);r("SemVer",f,p),this.options=p,this.loose=!!p.loose,this.includePrerelease=!!p.includePrerelease;const g=f.trim().match(p.loose?o[s.LOOSE]:o[s.FULL]);if(!g)throw new TypeError(`Invalid Version: ${f}`);if(this.raw=f,this.major=+g[1],this.minor=+g[2],this.patch=+g[3],this.major>i||this.major<0)throw new TypeError("Invalid major version");if(this.minor>i||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>i||this.patch<0)throw new TypeError("Invalid patch version");g[4]?this.prerelease=g[4].split(".").map(v=>{if(/^[0-9]+$/.test(v)){const b=+v;if(b>=0&&b<i)return b}return v}):this.prerelease=[],this.build=g[5]?g[5].split("."):[],this.format()}format(){return this.version=`${this.major}.${this.minor}.${this.patch}`,this.prerelease.length&&(this.version+=`-${this.prerelease.join(".")}`),this.version}toString(){return this.version}compare(f){if(r("SemVer.compare",this.version,this.options,f),!(f instanceof os)){if(typeof f=="string"&&f===this.version)return 0;f=new os(f,this.options)}return f.version===this.version?0:this.compareMain(f)||this.comparePre(f)}compareMain(f){return f instanceof os||(f=new os(f,this.options)),this.major<f.major?-1:this.major>f.major?1:this.minor<f.minor?-1:this.minor>f.minor?1:this.patch<f.patch?-1:this.patch>f.patch?1:0}comparePre(f){if(f instanceof os||(f=new os(f,this.options)),this.prerelease.length&&!f.prerelease.length)return-1;if(!this.prerelease.length&&f.prerelease.length)return 1;if(!this.prerelease.length&&!f.prerelease.length)return 0;let p=0;do{const g=this.prerelease[p],v=f.prerelease[p];if(r("prerelease compare",p,g,v),g===void 0&&v===void 0)return 0;if(v===void 0)return 1;if(g===void 0)return-1;if(g===v)continue;return l(g,v)}while(++p)}compareBuild(f){f instanceof os||(f=new os(f,this.options));let p=0;do{const g=this.build[p],v=f.build[p];if(r("build compare",p,g,v),g===void 0&&v===void 0)return 0;if(v===void 0)return 1;if(g===void 0)return-1;if(g===v)continue;return l(g,v)}while(++p)}inc(f,p,g){if(f.startsWith("pre")){if(!p&&g===!1)throw new Error("invalid increment argument: identifier is empty");if(p){const v=`-${p}`.match(this.options.loose?o[s.PRERELEASELOOSE]:o[s.PRERELEASE]);if(!v||v[1]!==p)throw new Error(`invalid identifier: ${p}`)}}switch(f){case"premajor":this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc("pre",p,g);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",p,g);break;case"prepatch":this.prerelease.length=0,this.inc("patch",p,g),this.inc("pre",p,g);break;case"prerelease":this.prerelease.length===0&&this.inc("patch",p,g),this.inc("pre",p,g);break;case"release":if(this.prerelease.length===0)throw new Error(`version ${this.raw} is not a prerelease`);this.prerelease.length=0;break;case"major":(this.minor!==0||this.patch!==0||this.prerelease.length===0)&&this.major++,this.minor=0,this.patch=0,this.prerelease=[];break;case"minor":(this.patch!==0||this.prerelease.length===0)&&this.minor++,this.patch=0,this.prerelease=[];break;case"patch":this.prerelease.length===0&&this.patch++,this.prerelease=[];break;case"pre":{const v=Number(g)?1:0;if(this.prerelease.length===0)this.prerelease=[v];else{let b=this.prerelease.length;for(;--b>=0;)typeof this.prerelease[b]=="number"&&(this.prerelease[b]++,b=-2);if(b===-1){if(p===this.prerelease.join(".")&&g===!1)throw new Error("invalid increment argument: identifier already exists");this.prerelease.push(v)}}if(p){let b=[p,v];if(g===!1&&(b=[p]),d(this.prerelease,p)){const w=this.prerelease[p.split(".").length];isNaN(w)&&(this.prerelease=b)}else this.prerelease=b}break}default:throw new Error(`invalid increment argument: ${f}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(".")}`),this}};t.exports=c})),rc=Ct(((e,t)=>{var r=Qn(),n=(i,o,s=!1)=>{if(i instanceof r)return i;try{return new r(i,o)}catch(a){if(!s)return null;throw a}};t.exports=n})),pL=Ct(((e,t)=>{var r=rc(),n=(i,o)=>{const s=r(i,o);return s?s.version:null};t.exports=n})),mL=Ct(((e,t)=>{var r=rc(),n=(i,o)=>{const s=r(i.trim().replace(/^[=v]+/,""),o);return s?s.version:null};t.exports=n})),gL=Ct(((e,t)=>{var r=Qn(),n=(i,o,s,a,l)=>{typeof s=="string"&&(l=a,a=s,s=void 0);try{return new r(i instanceof r?i.version:i,s).inc(o,a,l).version}catch{return null}};t.exports=n})),vL=Ct(((e,t)=>{var r=rc(),n=(i,o)=>{const s=r(i,null,!0),a=r(o,null,!0),l=s.compare(a);if(l===0)return null;const d=l>0,c=d?s:a,u=d?a:s,f=!!c.prerelease.length;if(u.prerelease.length&&!f){if(!u.patch&&!u.minor)return"major";if(u.compareMain(c)===0)return u.minor&&!u.patch?"minor":"patch"}const p=f?"pre":"";return s.major!==a.major?p+"major":s.minor!==a.minor?p+"minor":s.patch!==a.patch?p+"patch":"prerelease"};t.exports=n})),yL=Ct(((e,t)=>{var r=Qn(),n=(i,o)=>new r(i,o).major;t.exports=n})),bL=Ct(((e,t)=>{var r=Qn(),n=(i,o)=>new r(i,o).minor;t.exports=n})),wL=Ct(((e,t)=>{var r=Qn(),n=(i,o)=>new r(i,o).patch;t.exports=n})),SL=Ct(((e,t)=>{var r=rc(),n=(i,o)=>{const s=r(i,o);return s&&s.prerelease.length?s.prerelease:null};t.exports=n})),Xo=Ct(((e,t)=>{var r=Qn(),n=(i,o,s)=>new r(i,s).compare(new r(o,s));t.exports=n})),IL=Ct(((e,t)=>{var r=Xo(),n=(i,o,s)=>r(o,i,s);t.exports=n})),kL=Ct(((e,t)=>{var r=Xo(),n=(i,o)=>r(i,o,!0);t.exports=n})),lb=Ct(((e,t)=>{var r=Qn(),n=(i,o,s)=>{const a=new r(i,s),l=new r(o,s);return a.compare(l)||a.compareBuild(l)};t.exports=n})),TL=Ct(((e,t)=>{var r=lb(),n=(i,o)=>i.sort((s,a)=>r(s,a,o));t.exports=n})),EL=Ct(((e,t)=>{var r=lb(),n=(i,o)=>i.sort((s,a)=>r(a,s,o));t.exports=n})),tm=Ct(((e,t)=>{var r=Xo(),n=(i,o,s)=>r(i,o,s)>0;t.exports=n})),cb=Ct(((e,t)=>{var r=Xo(),n=(i,o,s)=>r(i,o,s)<0;t.exports=n})),GT=Ct(((e,t)=>{var r=Xo(),n=(i,o,s)=>r(i,o,s)===0;t.exports=n})),KT=Ct(((e,t)=>{var r=Xo(),n=(i,o,s)=>r(i,o,s)!==0;t.exports=n})),db=Ct(((e,t)=>{var r=Xo(),n=(i,o,s)=>r(i,o,s)>=0;t.exports=n})),ub=Ct(((e,t)=>{var r=Xo(),n=(i,o,s)=>r(i,o,s)<=0;t.exports=n})),XT=Ct(((e,t)=>{var r=GT(),n=KT(),i=tm(),o=db(),s=cb(),a=ub(),l=(d,c,u,f)=>{switch(c){case"===":return typeof d=="object"&&(d=d.version),typeof u=="object"&&(u=u.version),d===u;case"!==":return typeof d=="object"&&(d=d.version),typeof u=="object"&&(u=u.version),d!==u;case"":case"=":case"==":return r(d,u,f);case"!=":return n(d,u,f);case">":return i(d,u,f);case">=":return o(d,u,f);case"<":return s(d,u,f);case"<=":return a(d,u,f);default:throw new TypeError(`Invalid operator: ${c}`)}};t.exports=l})),CL=Ct(((e,t)=>{var r=Qn(),n=rc(),{safeRe:i,t:o}=Zu(),s=(a,l)=>{if(a instanceof r)return a;if(typeof a=="number"&&(a=String(a)),typeof a!="string")return null;l=l||{};let d=null;if(!l.rtl)d=a.match(l.includePrerelease?i[o.COERCEFULL]:i[o.COERCE]);else{const v=l.includePrerelease?i[o.COERCERTLFULL]:i[o.COERCERTL];let b;for(;(b=v.exec(a))&&(!d||d.index+d[0].length!==a.length);)(!d||b.index+b[0].length!==d.index+d[0].length)&&(d=b),v.lastIndex=b.index+b[1].length+b[2].length;v.lastIndex=-1}if(d===null)return null;const c=d[2],u=d[3]||"0",f=d[4]||"0",p=l.includePrerelease&&d[5]?`-${d[5]}`:"",g=l.includePrerelease&&d[6]?`+${d[6]}`:"";return n(`${c}.${u}.${f}${p}${g}`,l)};t.exports=s})),xL=Ct(((e,t)=>{var r=rc(),n=Xu(),i=Qn(),o=(d,c,u)=>{if(!n.RELEASE_TYPES.includes(c))return null;const f=s(d,u);return f&&a(f,c)},s=(d,c)=>{const u=d instanceof i?d.version:d;return r(u,c)},a=(d,c)=>{if(l(c))return d.version;switch(d.prerelease=[],c){case"major":d.minor=0,d.patch=0;break;case"minor":d.patch=0}return d.format()},l=d=>d.startsWith("pre");t.exports=o})),RL=Ct(((e,t)=>{var r=class{constructor(){this.max=1e3,this.map=new Map}get(n){const i=this.map.get(n);if(i!==void 0)return this.map.delete(n),this.map.set(n,i),i}delete(n){return this.map.delete(n)}set(n,i){if(!this.delete(n)&&i!==void 0){if(this.map.size>=this.max){const o=this.map.keys().next().value;this.delete(o)}this.map.set(n,i)}return this}};t.exports=r})),Zo=Ct(((e,t)=>{var r=/\s+/g,n=class ph{constructor(D,Z){if(Z=o(Z),D instanceof ph)return D.loose===!!Z.loose&&D.includePrerelease===!!Z.includePrerelease?D:new ph(D.raw,Z);if(D instanceof s)return this.raw=D.value,this.set=[[D]],this.formatted=void 0,this;if(this.options=Z,this.loose=!!Z.loose,this.includePrerelease=!!Z.includePrerelease,this.raw=D.trim().replace(r," "),this.set=this.raw.split("||").map(F=>this.parseRange(F.trim())).filter(F=>F.length),!this.set.length)throw new TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){const F=this.set[0];if(this.set=this.set.filter(W=>!I(W[0])),this.set.length===0)this.set=[F];else if(this.set.length>1){for(const W of this.set)if(W.length===1&&x(W[0])){this.set=[W];break}}}this.formatted=void 0}get range(){if(this.formatted===void 0){this.formatted="";for(let D=0;D<this.set.length;D++){D>0&&(this.formatted+="||");const Z=this.set[D];for(let F=0;F<Z.length;F++)F>0&&(this.formatted+=" "),this.formatted+=Z[F].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(D){D=D.replace(w,"");const Z=((this.options.includePrerelease&&v)|(this.options.loose&&b))+":"+D,F=i.get(Z);if(F)return F;const W=this.options.loose,O=W?d[u.HYPHENRANGELOOSE]:d[u.HYPHENRANGE];D=D.replace(O,ae(this.options.includePrerelease)),a("hyphen replace",D),D=D.replace(d[u.COMPARATORTRIM],f),a("comparator trim",D),D=D.replace(d[u.TILDETRIM],p),a("tilde trim",D),D=D.replace(d[u.CARETTRIM],g),a("caret trim",D);let $=D.split(" ").map(ge=>L(ge,this.options)).join(" ").split(/\s+/).map(ge=>ue(ge,this.options));W&&($=$.filter(ge=>(a("loose invalid filter",ge,this.options),!!ge.match(d[u.COMPARATORLOOSE])))),a("range list",$);const ie=new Map,N=$.map(ge=>new s(ge,this.options));for(const ge of N){if(I(ge))return[ge];ie.set(ge.value,ge)}ie.size>1&&ie.has("")&&ie.delete("");const ne=[...ie.values()];return i.set(Z,ne),ne}intersects(D,Z){if(!(D instanceof ph))throw new TypeError("a Range is required");return this.set.some(F=>C(F,Z)&&D.set.some(W=>C(W,Z)&&F.every(O=>W.every($=>O.intersects($,Z)))))}test(D){if(!D)return!1;if(typeof D=="string")try{D=new l(D,this.options)}catch{return!1}for(let Z=0;Z<this.set.length;Z++)if(X(this.set[Z],D,this.options))return!0;return!1}};t.exports=n;var i=new(RL()),o=ab(),s=rm(),a=em(),l=Qn(),{safeRe:d,src:c,t:u,comparatorTrimReplace:f,tildeTrimReplace:p,caretTrimReplace:g}=Zu(),{FLAG_INCLUDE_PRERELEASE:v,FLAG_LOOSE:b}=Xu(),w=new RegExp(c[u.BUILD],"g"),I=j=>j.value==="<0.0.0-0",x=j=>j.value==="",C=(j,D)=>{let Z=!0;const F=j.slice();let W=F.pop();for(;Z&&F.length;)Z=F.every(O=>W.intersects(O,D)),W=F.pop();return Z},L=(j,D)=>(j=j.replace(d[u.BUILD],""),a("comp",j,D),j=re(j,D),a("caret",j),j=U(j,D),a("tildes",j),j=z(j,D),a("xrange",j),j=oe(j,D),a("stars",j),j),E=j=>!j||j.toLowerCase()==="x"||j==="*",M=(j,D,Z)=>E(j)&&!E(D)||E(D)&&Z&&!E(Z),U=(j,D)=>j.trim().split(/\s+/).map(Z=>te(Z,D)).join(" "),te=(j,D)=>{const Z=D.loose?d[u.TILDELOOSE]:d[u.TILDE],F=D.includePrerelease?"-0":"";return j.replace(Z,(W,O,$,ie,N)=>{a("tilde",j,W,O,$,ie,N);let ne;return E(O)?ne="":E($)?ne=`>=${O}.0.0${F} <${+O+1}.0.0-0`:E(ie)?ne=`>=${O}.${$}.0${F} <${O}.${+$+1}.0-0`:N?(a("replaceTilde pr",N),ne=`>=${O}.${$}.${ie}-${N} <${O}.${+$+1}.0-0`):ne=`>=${O}.${$}.${ie} <${O}.${+$+1}.0-0`,a("tilde return",ne),ne})},re=(j,D)=>j.trim().split(/\s+/).map(Z=>Pe(Z,D)).join(" "),Pe=(j,D)=>{a("caret",j,D);const Z=D.loose?d[u.CARETLOOSE]:d[u.CARET],F=D.includePrerelease?"-0":"";return j.replace(Z,(W,O,$,ie,N)=>{a("caret",j,W,O,$,ie,N);let ne;return E(O)?ne="":E($)?ne=`>=${O}.0.0${F} <${+O+1}.0.0-0`:E(ie)?O==="0"?ne=`>=${O}.${$}.0${F} <${O}.${+$+1}.0-0`:ne=`>=${O}.${$}.0${F} <${+O+1}.0.0-0`:N?(a("replaceCaret pr",N),O==="0"?$==="0"?ne=`>=${O}.${$}.${ie}-${N} <${O}.${$}.${+ie+1}-0`:ne=`>=${O}.${$}.${ie}-${N} <${O}.${+$+1}.0-0`:ne=`>=${O}.${$}.${ie}-${N} <${+O+1}.0.0-0`):(a("no pr"),O==="0"?$==="0"?ne=`>=${O}.${$}.${ie} <${O}.${$}.${+ie+1}-0`:ne=`>=${O}.${$}.${ie} <${O}.${+$+1}.0-0`:ne=`>=${O}.${$}.${ie} <${+O+1}.0.0-0`),a("caret return",ne),ne})},z=(j,D)=>(a("replaceXRanges",j,D),j.split(/\s+/).map(Z=>K(Z,D)).join(" ")),K=(j,D)=>{j=j.trim();const Z=D.loose?d[u.XRANGELOOSE]:d[u.XRANGE];return j.replace(Z,(F,W,O,$,ie,N)=>{if(a("xRange",j,F,W,O,$,ie,N),M(O,$,ie))return j;const ne=E(O),ge=ne||E($),Oe=ge||E(ie),We=Oe;return W==="="&&We&&(W=""),N=D.includePrerelease?"-0":"",ne?W===">"||W==="<"?F="<0.0.0-0":F="*":W&&We?(ge&&($=0),ie=0,W===">"?(W=">=",ge?(O=+O+1,$=0,ie=0):($=+$+1,ie=0)):W==="<="&&(W="<",ge?O=+O+1:$=+$+1),W==="<"&&(N="-0"),F=`${W+O}.${$}.${ie}${N}`):ge?F=`>=${O}.0.0${N} <${+O+1}.0.0-0`:Oe&&(F=`>=${O}.${$}.0${N} <${O}.${+$+1}.0-0`),a("xRange return",F),F})},oe=(j,D)=>(a("replaceStars",j,D),j.trim().replace(d[u.STAR],"")),ue=(j,D)=>(a("replaceGTE0",j,D),j.trim().replace(d[D.includePrerelease?u.GTE0PRE:u.GTE0],"")),ae=j=>(D,Z,F,W,O,$,ie,N,ne,ge,Oe,We)=>(E(F)?Z="":E(W)?Z=`>=${F}.0.0${j?"-0":""}`:E(O)?Z=`>=${F}.${W}.0${j?"-0":""}`:$?Z=`>=${Z}`:Z=`>=${Z}${j?"-0":""}`,E(ne)?N="":E(ge)?N=`<${+ne+1}.0.0-0`:E(Oe)?N=`<${ne}.${+ge+1}.0-0`:We?N=`<=${ne}.${ge}.${Oe}-${We}`:j?N=`<${ne}.${ge}.${+Oe+1}-0`:N=`<=${N}`,`${Z} ${N}`.trim()),X=(j,D,Z)=>{for(let F=0;F<j.length;F++)if(!j[F].test(D))return!1;if(D.prerelease.length&&!Z.includePrerelease){for(let F=0;F<j.length;F++)if(a(j[F].semver),j[F].semver!==s.ANY&&j[F].semver.prerelease.length>0){const W=j[F].semver;if(W.major===D.major&&W.minor===D.minor&&W.patch===D.patch)return!0}return!1}return!0}})),rm=Ct(((e,t)=>{var r=Symbol("SemVer ANY"),n=class hv{static get ANY(){return r}constructor(f,p){if(p=i(p),f instanceof hv){if(f.loose===!!p.loose)return f;f=f.value}f=f.trim().split(/\s+/).join(" "),l("comparator",f,p),this.options=p,this.loose=!!p.loose,this.parse(f),this.semver===r?this.value="":this.value=this.operator+this.semver.version,l("comp",this)}parse(f){const p=this.options.loose?o[s.COMPARATORLOOSE]:o[s.COMPARATOR],g=f.match(p);if(!g)throw new TypeError(`Invalid comparator: ${f}`);this.operator=g[1]!==void 0?g[1]:"",this.operator==="="&&(this.operator=""),g[2]?this.semver=new d(g[2],this.options.loose):this.semver=r}toString(){return this.value}test(f){if(l("Comparator.test",f,this.options.loose),this.semver===r||f===r)return!0;if(typeof f=="string")try{f=new d(f,this.options)}catch{return!1}return a(f,this.operator,this.semver,this.options)}intersects(f,p){if(!(f instanceof hv))throw new TypeError("a Comparator is required");return this.operator===""?this.value===""?!0:new c(f.value,p).test(this.value):f.operator===""?f.value===""?!0:new c(this.value,p).test(f.semver):(p=i(p),p.includePrerelease&&(this.value==="<0.0.0-0"||f.value==="<0.0.0-0")||!p.includePrerelease&&(this.value.startsWith("<0.0.0")||f.value.startsWith("<0.0.0"))?!1:!!(this.operator.startsWith(">")&&f.operator.startsWith(">")||this.operator.startsWith("<")&&f.operator.startsWith("<")||this.semver.version===f.semver.version&&this.operator.includes("=")&&f.operator.includes("=")||a(this.semver,"<",f.semver,p)&&this.operator.startsWith(">")&&f.operator.startsWith("<")||a(this.semver,">",f.semver,p)&&this.operator.startsWith("<")&&f.operator.startsWith(">")))}};t.exports=n;var i=ab(),{safeRe:o,t:s}=Zu(),a=XT(),l=em(),d=Qn(),c=Zo()})),nm=Ct(((e,t)=>{var r=Zo(),n=(i,o,s)=>{try{o=new r(o,s)}catch{return!1}return o.test(i)};t.exports=n})),_L=Ct(((e,t)=>{var r=Zo(),n=(i,o)=>new r(i,o).set.map(s=>s.map(a=>a.value).join(" ").trim().split(" "));t.exports=n})),PL=Ct(((e,t)=>{var r=Qn(),n=Zo(),i=(o,s,a)=>{let l=null,d=null,c=null;try{c=new n(s,a)}catch{return null}return o.forEach(u=>{c.test(u)&&(!l||d.compare(u)===-1)&&(l=u,d=new r(l,a))}),l};t.exports=i})),AL=Ct(((e,t)=>{var r=Qn(),n=Zo(),i=(o,s,a)=>{let l=null,d=null,c=null;try{c=new n(s,a)}catch{return null}return o.forEach(u=>{c.test(u)&&(!l||d.compare(u)===1)&&(l=u,d=new r(l,a))}),l};t.exports=i})),ML=Ct(((e,t)=>{var r=Qn(),n=Zo(),i=tm(),o=(s,a)=>{s=new n(s,a);let l=new r("0.0.0");if(s.test(l)||(l=new r("0.0.0-0"),s.test(l)))return l;l=null;for(let d=0;d<s.set.length;++d){const c=s.set[d];let u=null;c.forEach(f=>{const p=new r(f.semver.version);switch(f.operator){case">":p.prerelease.length===0?p.patch++:p.prerelease.push(0),p.raw=p.format();case"":case">=":(!u||i(p,u))&&(u=p);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${f.operator}`)}}),u&&(!l||i(l,u))&&(l=u)}return l&&s.test(l)?l:null};t.exports=o})),$L=Ct(((e,t)=>{var r=Zo(),n=(i,o)=>{try{return new r(i,o).range||"*"}catch{return null}};t.exports=n})),fb=Ct(((e,t)=>{var r=Qn(),n=rm(),{ANY:i}=n,o=Zo(),s=nm(),a=tm(),l=cb(),d=ub(),c=db(),u=(f,p,g,v)=>{f=new r(f,v),p=new o(p,v);let b,w,I,x,C;switch(g){case">":b=a,w=d,I=l,x=">",C=">=";break;case"<":b=l,w=c,I=a,x="<",C="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(s(f,p,v))return!1;for(let L=0;L<p.set.length;++L){const E=p.set[L];let M=null,U=null;if(E.forEach(te=>{te.semver===i&&(te=new n(">=0.0.0")),M=M||te,U=U||te,b(te.semver,M.semver,v)?M=te:I(te.semver,U.semver,v)&&(U=te)}),M.operator===x||M.operator===C||(!U.operator||U.operator===x)&&w(f,U.semver))return!1;if(U.operator===C&&I(f,U.semver))return!1}return!0};t.exports=u})),LL=Ct(((e,t)=>{var r=fb(),n=(i,o,s)=>r(i,o,">",s);t.exports=n})),OL=Ct(((e,t)=>{var r=fb(),n=(i,o,s)=>r(i,o,"<",s);t.exports=n})),NL=Ct(((e,t)=>{var r=Zo(),n=(i,o,s)=>(i=new r(i,s),o=new r(o,s),i.intersects(o,s));t.exports=n})),DL=Ct(((e,t)=>{var r=nm(),n=Xo();t.exports=(i,o,s)=>{const a=[];let l=null,d=null;const c=i.sort((g,v)=>n(g,v,s));for(const g of c)r(g,o,s)?(d=g,l||(l=g)):(d&&a.push([l,d]),d=null,l=null);l&&a.push([l,null]);const u=[];for(const[g,v]of a)g===v?u.push(g):!v&&g===c[0]?u.push("*"):v?g===c[0]?u.push(`<=${v}`):u.push(`${g} - ${v}`):u.push(`>=${g}`);const f=u.join(" || "),p=typeof o.raw=="string"?o.raw:String(o);return f.length<p.length?f:o}})),jL=Ct(((e,t)=>{var r=Zo(),n=rm(),{ANY:i}=n,o=nm(),s=Xo(),a=(p,g,v={})=>{if(p===g)return!0;p=new r(p,v),g=new r(g,v);let b=!1;e:for(const w of p.set){for(const I of g.set){const x=c(w,I,v);if(b=b||x!==null,x)continue e}if(b)return!1}return!0},l=[new n(">=0.0.0-0")],d=[new n(">=0.0.0")],c=(p,g,v)=>{if(p===g)return!0;if(p.length===1&&p[0].semver===i){if(g.length===1&&g[0].semver===i)return!0;v.includePrerelease?p=l:p=d}if(g.length===1&&g[0].semver===i){if(v.includePrerelease)return!0;g=d}const b=new Set;let w,I;for(const re of p)re.operator===">"||re.operator===">="?w=u(w,re,v):re.operator==="<"||re.operator==="<="?I=f(I,re,v):b.add(re.semver);if(b.size>1)return null;let x;if(w&&I){if(x=s(w.semver,I.semver,v),x>0)return null;if(x===0&&(w.operator!==">="||I.operator!=="<="))return null}for(const re of b){if(w&&!o(re,String(w),v)||I&&!o(re,String(I),v))return null;for(const Pe of g)if(!o(re,String(Pe),v))return!1;return!0}let C,L,E,M,U=I&&!v.includePrerelease&&I.semver.prerelease.length?I.semver:!1,te=w&&!v.includePrerelease&&w.semver.prerelease.length?w.semver:!1;U&&U.prerelease.length===1&&I.operator==="<"&&U.prerelease[0]===0&&(U=!1);for(const re of g){if(M=M||re.operator===">"||re.operator===">=",E=E||re.operator==="<"||re.operator==="<=",w){if(te&&re.semver.prerelease&&re.semver.prerelease.length&&re.semver.major===te.major&&re.semver.minor===te.minor&&re.semver.patch===te.patch&&(te=!1),re.operator===">"||re.operator===">="){if(C=u(w,re,v),C===re&&C!==w)return!1}else if(w.operator===">="&&!re.test(w.semver))return!1}if(I){if(U&&re.semver.prerelease&&re.semver.prerelease.length&&re.semver.major===U.major&&re.semver.minor===U.minor&&re.semver.patch===U.patch&&(U=!1),re.operator==="<"||re.operator==="<="){if(L=f(I,re,v),L===re&&L!==I)return!1}else if(I.operator==="<="&&!re.test(I.semver))return!1}if(!re.operator&&(I||w)&&x!==0)return!1}return!(w&&E&&!I&&x!==0||I&&M&&!w&&x!==0||te||U)},u=(p,g,v)=>{if(!p)return g;const b=s(p.semver,g.semver,v);return b>0?p:b<0||g.operator===">"&&p.operator===">="?g:p},f=(p,g,v)=>{if(!p)return g;const b=s(p.semver,g.semver,v);return b<0?p:b>0||g.operator==="<"&&p.operator==="<="?g:p};t.exports=a})),BL=Ct(((e,t)=>{var r=Zu(),n=Xu(),i=Qn(),o=VT(),s=rc(),a=pL(),l=mL(),d=gL(),c=vL(),u=yL(),f=bL(),p=wL(),g=SL(),v=Xo(),b=IL(),w=kL(),I=lb(),x=TL(),C=EL(),L=tm(),E=cb(),M=GT(),U=KT(),te=db(),re=ub(),Pe=XT(),z=CL(),K=xL(),oe=rm(),ue=Zo(),ae=nm(),X=_L(),j=PL(),D=AL(),Z=ML(),F=$L(),W=fb(),O=LL(),$=OL(),ie=NL(),N=DL(),ne=jL();t.exports={parse:s,valid:a,clean:l,inc:d,diff:c,major:u,minor:f,patch:p,prerelease:g,compare:v,rcompare:b,compareLoose:w,compareBuild:I,sort:x,rsort:C,gt:L,lt:E,eq:M,neq:U,gte:te,lte:re,cmp:Pe,coerce:z,truncate:K,Comparator:oe,Range:ue,satisfies:ae,toComparators:X,maxSatisfying:j,minSatisfying:D,minVersion:Z,validRange:F,outside:W,gtr:O,ltr:$,intersects:ie,simplifyRange:N,subset:ne,SemVer:i,re:r.re,src:r.src,tokens:r.t,SEMVER_SPEC_VERSION:n.SEMVER_SPEC_VERSION,RELEASE_TYPES:n.RELEASE_TYPES,compareIdentifiers:o.compareIdentifiers,rcompareIdentifiers:o.rcompareIdentifiers}})),io=BL(),Vm=class extends Error{constructor(e,t,r){super(r),T(this,"tagName",void 0),T(this,"packageSpec",void 0),T(this,"name","ElementPackagePolicyError"),this.tagName=e,this.packageSpec=t}};function im(e){return(0,io.valid)(e)===e}function E0(e){const t=ya(e);return{packageName:t.name,packagePath:t.path?`${t.name}/${t.path}`:t.name,version:t.version}}function ZT(e,t){if(!t)return;const r=t.allowedPackages.filter(n=>typeof n=="string").map(n=>n.trim()).filter(Boolean);for(const[n,i]of Object.entries(e)){const o=String(i).trim();let s;try{s=E0(o)}catch{throw new Vm(n,o,`Element package policy rejected invalid package spec "${o}" for ${n}.`)}if((t.requireExactVersions??!0)&&!im(s.version)){const a=s.version.includes("+")?"does not allow semver build metadata because legacy IIFE bundle routes use + as a package separator":"requires an exact version";throw new Vm(n,o,`Element package policy ${a} for ${n}; received "${o}".`)}if(!r.some(a=>{if(a===o)return!0;try{const l=E0(a);return l.version.length===0&&l.packagePath===s.packagePath}catch{return!1}}))throw new Vm(n,o,`Element package policy does not allow "${o}" for ${n}.`)}}var al=class extends Error{constructor(e){const t=[...e.keys()];super(`Backend adapter failure for ${e.size} tag(s): ${t.join(", ")}`),T(this,"name","AdapterFailure"),T(this,"reasons",void 0),this.reasons=e}},C0="pie-mathjax-version-conflict",Rf=Symbol.for("@pie-players/pie-players-shared/mathjax-version-conflict-tracked");function FL(e){const t=globalThis;t[Rf]??(t[Rf]=new WeakMap);let r=t[Rf].get(e);return r||(r=new WeakSet,t[Rf].set(e,r)),r}function HL(e,t){e.addEventListener(C0,r=>{const n=t();if(!n)return;const i=FL(r);if(i.has(n))return;i.add(n);const o=r.detail,{condition:s,docsUrl:a}=o&&typeof o=="object"?o:{};try{n.trackEvent(C0,{condition:s,docsUrl:a})}catch{}})}var Fl={delivery:{subpath:"",tagSuffix:""},author:{subpath:"/author",tagSuffix:"-config",fallback:"delivery"},print:{subpath:"/print",tagSuffix:"-print",fallback:"delivery"}};function zL(e){const t=e.cdnBaseUrl.replace(/\/+$/,""),r=UL(e.cdnProvider,t),n=e.moduleResolution??"url",i=e.view??"delivery",o=e.loadControllers??!0,s=XL(i,e.viewConfig),a=Zh(s,i),l=new Set,d=new Map,c=new Map,u=new Map,f=new WeakSet;let p={},g=x0,v=R0,b,w=M0,I;const x={replaceImporter(j){g=j},observeImportMapInjection(j){b=j},replacePackageMetadataLoader(j){v=j},replaceImportShimLoader(j){w=j,I=void 0},restore(){g=x0,v=R0,w=M0,I=void 0,b=void 0,l.clear(),d.clear(),c.clear(),u.clear(),p={}}};async function C(j,D){if(!j||Object.keys(j).length===0)return;n==="import-map"&&$0(),oe(D.doc);const Z={};for(const[W,O]of Object.entries(j)){const $=ya(O).name;if(n==="import-map"){const ie=d.get($);if(ie&&ie!==O)throw new Error(`Conflicting browser ESM package version for ${$}: ${ie} is already mapped, but ${O} was requested`)}l.has(O)||(Z[W]=O)}if(Object.keys(Z).length>0){let W;try{W=await rO(Z,s,r,o,n==="import-map",v,p,ue)}catch(ne){throw X(ne),ne}for(const[ne,ge]of W.unpublished)u.set(ne,ge),typeof console<"u"&&console.error&&console.error(`[pie-esm] ${ge}`);const O=n==="url"?await re(W.metadata,D.doc):void 0,$=O?z(O,D.doc):void 0,ie=lO({...W.imports,...$?.imports},D.doc);let N;if(Object.keys(ie).length>0){const ne=JSON.stringify({imports:ie},null,2);$0(),N=cO(ne,D.doc,$?.mappedRuntime),b?.(ne,D.doc)}for(const[ne,ge]of $?.served??[])c.set(ne,ge);p=W.sharedDependencyVersions;for(const ne of Object.values(Z))l.add(ne),n==="import-map"&&d.set(ya(ne).name,ne);N&&await M(ie,N,D.doc)}const F=new Map;if(await Promise.all(Object.entries(j).map(async([W,O])=>{const $=ya(O).name;let ie;try{ie=Ny(W,`element tag for ${$}`)}catch(Ne){F.set(W,{kind:"define-failed",tag:W,cause:Ne instanceof Error?Ne.message:String(Ne)});return}const N=_0($,O,s,n,r,i),ne=u.get(O);if(ne){F.set(W,{kind:"module-load-failed",tag:W,specifier:N,cause:ne});return}const ge=c.get(O);let Oe;if(ge&&(Oe=await L(O,ge,D.doc)),!Oe){let Ne;try{Ne=await E(N,D.doc)}catch(xe){if(s.fallback){const et=_0($,O,Fl[s.fallback]??Fl.delivery,n,r,s.fallback);try{Ne=await E(et,D.doc)}catch(Ue){F.set(W,{kind:"module-load-failed",tag:W,specifier:et,cause:Ue instanceof Error?Ue.message:String(Ue)});return}}else{F.set(W,{kind:"module-load-failed",tag:W,specifier:N,cause:xe instanceof Error?xe.message:String(xe)});return}}if(Oe=P0(Ne,i),!Oe){F.set(W,{kind:"no-element-class",tag:W,packageName:$});return}}if(!sv(Oe)){F.set(W,{kind:"not-a-constructor",tag:W,packageName:$});return}try{Dy(ie,class extends Oe{},`element tag for ${$}`)}catch(Ne){F.set(W,{kind:"define-failed",tag:W,cause:Ne instanceof Error?Ne.message:String(Ne)});return}let We=null;if(o){const Ne=c.get(O),xe=Ne?.views.controller;if(Ne&&xe)try{const et=await E(r.browserViewUrl(O,xe),D.doc);We=et?.default??et}catch(et){ae(O,Ne.declaration,Ne.runtime,`its editor-runtime controller failed to load: ${Gm(et)}`)}if(!We){const et=YL($,O,n,r);try{const Ue=await E(et,D.doc);We=Ue?.default??Ue}catch{}}}tb({package:O,status:jl.loaded,tagName:ie,element:Oe,controller:We,config:null,bundleType:$s.esm})})),F.size>0)throw new al(F)}async function L(j,D,Z){const F=r.browserViewUrl(j,D.views[a]);try{const W=P0(await E(F,Z),i);if(sv(W))return W;throw new Error(`${F} exports no custom element class`)}catch(W){c.delete(j),ae(j,D.declaration,D.runtime,`its editor-runtime ${a} view failed to load: ${Gm(W)}`);return}}async function E(j,D){return await uO(D),iE(D)?(await te(D))(j):g(j)}async function M(j,D,Z){let F="applied";try{D.type===hb?(await te(Z)).addImportMap({imports:j}):await U(j)&&(F="rejected",await te(Z))}finally{dO(D,F)}}async function U(j){const D="react"in j?"react":Object.keys(j)[0];try{return await g(D),!1}catch{}try{await g(j[D])}catch{return!1}return!0}function te(j){return I??(I=w().then(D=>(D.addImportMap({imports:gv(j)}),D),D=>{throw I=void 0,D})),I}async function re(j,D){const Z=[];for(const[W,O]of j){const $=iO(O);if($!==void 0){if($===null){ae(W,void 0,void 0,"its pie.browserEditorRuntime declaration is invalid");continue}$.views[a]&&Z.push({packageVersion:W,declaration:$})}}if(Z.length===0)return{candidates:Z};if(!oE()){for(const{packageVersion:W,declaration:O}of Z)ae(W,O,void 0,"this browser does not support import maps");return{candidates:[]}}if(A0(D))return{candidates:Z};const F=sO(Z);return{candidates:Z,target:{runtime:F,...await Pe(F)}}}async function Pe(j){const D=`${j.name}@${j.version}`;let Z;try{Z=await v(D,r.packageJsonUrl(D))}catch(W){return{failure:`the package.json of ${D} could not be loaded: ${Gm(W)}`}}if(!Z)return{failure:`the package.json of ${D} could not be loaded`};const F=oO(Z);return F?{modules:F}:{failure:`${D} declares no valid pie.browserModules`}}function z(j,D){const Z={imports:{},served:new Map};if(j.candidates.length===0)return Z;let F=A0(D);if(!F){const{target:W}=j;let O=W?.failure;if(W?.modules){const ie=gv(D),N=Object.keys(W.modules).find(ne=>ne in ie);N&&(O=`the page already maps ${N}`)}if(O||!W?.modules){for(const{packageVersion:ie,declaration:N}of j.candidates)ae(ie,N,void 0,O??"the page no longer maps its editor runtime");return Z}F=W.runtime;const $=`${F.name}@${F.version}`;for(const[ie,N]of Object.entries(W.modules))Z.imports[ie]=r.browserViewUrl($,N);Z.mappedRuntime=$}for(const{packageVersion:W,declaration:O}of j.candidates){if(!aO(F,O)){ae(W,O,F,`the page maps ${F.name}@${F.version}, which cannot serve ${O.name}@${O.version}`);continue}Z.served.set(W,{views:O.views,declaration:O,runtime:F}),O.version!==F.version&&ue({dependencyName:F.name,existingVersion:F.version,requestedVersion:O.version,resolvedVersion:F.version,packageVersion:W})}return Z}function K(){if(!e.trackPageActions)return;const j=e.instrumentationProvider;if(Vu(j)&&j.isReady())return j}function oe(j){const D=j.defaultView;!D||f.has(D)||(f.add(D),HL(D,K))}function ue(j,D=`[pie-esm] Shared dependency version conflict resolved for ${String(j.dependencyName)}`){typeof console<"u"&&console.warn&&console.warn(D,j);const Z=K();if(Z)try{Z.trackEvent("pie-esm-shared-dependency-conflict",j)}catch{}}function ae(j,D,Z,F){ue({dependencyName:D?.name,existingVersion:Z?.version,requestedVersion:D?.version,packageVersion:j,fallback:"./browser/*",reason:F},`[pie-esm] ${j} loads ./browser/* in place of its editor-runtime variant: ${F}`)}function X(j){const D=j instanceof Error?j:new Error(String(j));typeof console<"u"&&console.error&&console.error("[pie-esm] Shared dependency resolution failed",D);const Z=K();if(Z)try{Z.trackError(D,{component:"esm-adapter",errorType:"EsmSharedDependencyError"})}catch{}}return{load:C,get __seams(){return x}}}function x0(e){return br(()=>import(e),[],import.meta.url)}var _f=new Map;function R0(e,t){const r=_f.get(t);if(r)return r;const n=WL(t);_f.set(t,n);const i=()=>{_f.get(t)===n&&_f.delete(t)};return n.then(o=>{o===null&&i()},i),n}async function WL(e){const t=typeof window<"u"&&typeof window.fetch=="function"?window.fetch.bind(window):void 0;if(!t)return null;const r=await t(e);return r.ok?await r.json():null}var YT="dist/runtime-support.js";function UL(e,t){if(qL(e))return e;const r=e??(t.includes("esm.sh")?"esm.sh":"jsdelivr");return r==="esm.sh"?GL(t):VL(t,r)}function qL(e){if(!e||typeof e!="object")return!1;const t=e;return typeof t.name=="string"&&typeof t.packageJsonUrl=="function"&&typeof t.browserViewUrl=="function"&&typeof t.browserControllerUrl=="function"&&typeof t.sharedDependencyUrl=="function"}function VL(e,t="jsdelivr"){return{name:t,packageJsonUrl:r=>`${e}/${r}/package.json`,browserViewUrl:(r,n)=>`${e}/${r}/dist/browser/${n}/index.js`,browserControllerUrl:r=>`${e}/${r}/dist/browser/controller/index.js`,runtimeSupportUrl:r=>`${e}/${r}/${YT}`,sharedDependencyUrl:(r,n,i)=>`${e}/${r}@${n}${i?`/${i}/+esm`:"/+esm"}`}}function GL(e){const t=e.replace(/\/+$/,""),r=KL(t);return{name:"esm.sh",packageJsonUrl:n=>`${r}/${n}/package.json`,browserViewUrl:(n,i)=>`${r}/${n}/dist/browser/${i}/index.js`,browserControllerUrl:n=>`${r}/${n}/dist/browser/controller/index.js`,runtimeSupportUrl:n=>`${r}/${n}/${YT}`,sharedDependencyUrl:(n,i,o)=>{const s=o?`/${o}`:"";return`${t}/${n}@${i}${s}`}}}function KL(e){try{const t=new URL(e);if(t.hostname==="raw.esm.sh")return t.toString().replace(/\/+$/,"");if(t.hostname==="esm.sh")return t.hostname="raw.esm.sh",t.toString().replace(/\/+$/,"")}catch{}return"https://raw.esm.sh"}function XL(e,t){return t??Fl[e]??Fl.delivery}function ZL(e,t,r,n,i){if(!e?.exports)return;const o=new Set([`./browser/${Zh(r,i)}`]);if(r.fallback){const s=Fl[r.fallback];s&&o.add(`./browser/${Zh(s,r.fallback)}`)}n&&o.add("./browser/controller");for(const s of o)if(!(s in e.exports))return`${t} does not publish browser ESM export ${s}; use IIFE/preloaded mode or publish browser ESM artifacts first`}function pv(e){const t=e.replace(/^\/+|\/+$/g,"");return t.length>0?t:null}function Zh(e,t="delivery"){return pv(e.subpath)??t}function mh(e,t,r,n="delivery"){const i=Zh(t,n);return r.browserViewUrl(e,i)}function JT(e,t){return t.browserControllerUrl(e)}function _0(e,t,r,n,i,o){return n==="import-map"?r.subpath?`${e}${r.subpath}`:e:mh(t,r,i,o)}function YL(e,t,r,n){return r==="import-map"?`${e}/controller`:JT(t,n)}function P0(e,t){if(!(!e||typeof e!="object"))return t==="author"?e.default??e.Configure??e.Element:t==="print"?e.default??e.Print??e.Element:e.default??e.Element}var QT=["react","react-dom"];function JL(e,t,r){const n=e?.pie?.browserSharedDependencies?.[t];if(!n)throw new Error(`${r} is missing required pie.browserSharedDependencies.${t}`);if(!im(n))throw new Error(`${r} pie.browserSharedDependencies.${t} must be an exact version; received "${n}"`);return n}function QL(e,t){return!!(e?.pie?.browserSharedDependencies?.[t]||e?.peerDependencies?.[t]||e?.dependencies?.[t]||e?.optionalDependencies?.[t])}function eO(e,t,r,n,i,o,s,a){if(!i)return;const l=t[n];let d=i;l&&l!==i&&(d=tO(n,l,i,s,r.has(n)),a({dependencyName:n,existingVersion:l,requestedVersion:i,resolvedVersion:d,packageVersion:s})),t[n]=d,e[n]=o.sharedDependencyUrl(n,d),n==="react"&&(e["react/jsx-runtime"]=o.sharedDependencyUrl("react",d,"jsx-runtime"),e["react/jsx-dev-runtime"]=o.sharedDependencyUrl("react",d,"jsx-dev-runtime")),n==="react-dom"&&(e["react-dom/client"]=o.sharedDependencyUrl("react-dom",d,"client"))}function tO(e,t,r,n,i){if((0,io.major)(t)!==(0,io.major)(r))throw new Error(`Conflicting shared browser dependency ${e}: ${t} vs ${r} from ${n}; different major versions cannot share one browser singleton`);if(i&&(0,io.compare)(r,t)>0)throw new Error(`Conflicting shared browser dependency ${e}: ${t} is already selected, but ${n} requires higher version ${r}; the browser singleton cannot be upgraded after import-map injection`);return(0,io.compare)(t,r)>=0?t:r}async function rO(e,t,r,n,i,o,s,a){const l={},d={...s},c=new Set(Object.keys(s)),u=new Map,f=new Map;for(const[,p]of Object.entries(e)){const g=await o(p,r.packageJsonUrl(p)),v=ZL(g,p,t,n,pv(t.subpath)??"delivery");if(v){f.set(p,v);continue}u.set(p,g);const b=ya(p).name;if(i&&(l[b]=mh(p,Fl.delivery,r,"delivery"),t.subpath&&(l[`${b}${t.subpath}`]=mh(p,t,r,pv(t.subpath)??"delivery")),n&&(l[`${b}/controller`]=JT(p,r)),t.fallback)){const w=Fl[t.fallback];if(w){const I=w.subpath?`${b}${w.subpath}`:b;l[I]=mh(p,w,r,t.fallback)}}for(const w of QT)QL(g,w)&&eO(l,d,c,w,JL(g,w,p),r,p,a)}return{imports:l,sharedDependencyVersions:d,metadata:u,unpublished:f}}var eE="data-pie-editor-runtime",tE=/^(?:@[a-z0-9][a-z0-9._~-]*\/)?[a-z0-9][a-z0-9._~-]*$/,rE=/^[A-Za-z0-9_-][A-Za-z0-9._-]*(?:\/[A-Za-z0-9_-][A-Za-z0-9._-]*)*$/,nO=/^(?:@[A-Za-z0-9_-][A-Za-z0-9._-]*\/)?[A-Za-z0-9_-][A-Za-z0-9._-]*(?:\/[A-Za-z0-9_-][A-Za-z0-9._-]*)*$/;function mv(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function iO(e){const t=e?.pie?.browserEditorRuntime;if(t===void 0)return;if(!mv(t)||!mv(t.views))return null;const{name:r,version:n}=t;if(typeof r!="string"||!tE.test(r)||typeof n!="string"||!im(n))return null;const i=Object.entries(t.views);return i.length===0||!i.every(([,o])=>typeof o=="string"&&rE.test(o))?null:{name:r,version:n,views:Object.fromEntries(i)}}function oO(e){const t=e.pie?.browserModules;if(!mv(t))return null;const r=Object.entries(t);return r.length>0&&r.every(([n,i])=>nO.test(n)&&!QT.some(o=>n===o||n.startsWith(`${o}/`))&&typeof i=="string"&&rE.test(i))?Object.fromEntries(r):null}function sO(e){const{name:t}=e[0].declaration;let{version:r}=e[0].declaration;for(const{declaration:n}of e)n.name===t&&(0,io.compare)(n.version,r)>0&&(r=n.version);return{name:t,version:r}}function aO(e,t){return e.name!==t.name||(0,io.major)(e.version)!==(0,io.major)(t.version)||(0,io.major)(e.version)===0&&(0,io.minor)(e.version)!==(0,io.minor)(t.version)?!1:(0,io.compare)(e.version,t.version)>=0}function om(e){return typeof e.querySelectorAll=="function"?Array.from(e.querySelectorAll(`script[type="importmap"], script[type="${hb}"]`)):[]}function A0(e){for(const t of om(e)){const r=t.getAttribute(eE),n=r?.lastIndexOf("@")??-1;if(!r||n<=0)continue;const i=r.slice(0,n),o=r.slice(n+1);if(tE.test(i)&&im(o))return{name:i,version:o}}return null}function Gm(e){return e instanceof Error?e.message:String(e)}function lO(e,t){const r=gv(t);return Object.fromEntries(Object.entries(e).filter(([n])=>!(n in r)))}var sm="data-pie-import-map",nE="pie-import-map-settled",hb="importmap-shim";function cO(e,t,r){const n=t.createElement("script");return n.type=iE(t)?hb:"importmap",n.setAttribute(sm,"pending"),r&&n.setAttribute(eE,r),n.textContent=e,t.head.appendChild(n),n}function dO(e,t){e.setAttribute(sm,t),e.dispatchEvent(new Event(nE))}function iE(e){return om(e).some(t=>t.getAttribute(sm)==="rejected")}async function uO(e){const t=om(e).filter(r=>r.getAttribute(sm)==="pending");await Promise.all(t.map(r=>new Promise(n=>r.addEventListener(nE,()=>n(),{once:!0}))))}function gv(e){const t=Object.create(null);for(const r of om(e))try{const n=JSON.parse(r.textContent||"{}")?.imports;if(!n||typeof n!="object")continue;for(const[i,o]of Object.entries(n))typeof o=="string"&&!(i in t)&&(t[i]=o)}catch{}return t}async function M0(){const e=globalThis;e.importShim||(e.esmsInitOptions={...e.esmsInitOptions,shimMode:!0,noLoadEventRetriggers:!0},await br(()=>import("./chunks/module-shim-58659a86.js"),[],import.meta.url));const t=e.importShim;if(typeof t!="function"||typeof t.addImportMap!="function")throw new Error("es-module-shims did not initialize, so this browser cannot load browser ESM elements after the page's first module load. Use the iife or preloaded strategy.");try{t.addImportMap({imports:{}})}catch{throw new Error("This page runs es-module-shims in polyfill mode, and this browser rejects import maps added after the page's first module load. Load es-module-shims in shim mode, or use the iife or preloaded strategy.")}return t}function oE(){const e=typeof HTMLScriptElement<"u"?HTMLScriptElement:void 0;return typeof e?.supports=="function"&&e.supports("importmap")}function $0(){if(!oE())throw new Error('This browser does not support import maps. Use moduleResolution="url" or switch to iife/preloaded strategy.')}function fO(e){const t=new Map;for(const n of Object.values(e)){const i=String(n),o=ya(i).name,s=t.get(o)??new Set;s.add(i),t.set(o,s)}const r=[...t.entries()].filter(([,n])=>n.size>1).map(([n])=>n).sort();return r.length>0?`IIFE bundles cannot load multiple package specs for: ${r.join(", ")}`:void 0}function hO(e){const t=e.bundleType??$s.clientPlayer,r=e.needsControllers??!0;let n=L0;const i=new Map,o={replaceLoadBundleScript(f){n=f,i.clear()},restore(){n=L0,i.clear()}};async function s(f,p){const g=i.get(f);if(g)return g;const v=a(f,p).finally(()=>{i.delete(f)});return i.set(f,v),v}async function a(f,p){const{retryDelayMs:g,timeoutMs:v}=vO(e.bundleRetry),b=Date.now();let w=0;for(;;){w+=1;try{await n(f,p);const I=Date.now()-b;w>1&&(e.onBundleRetryStatus?.({state:"completed",url:f,attempt:w,elapsedMs:I,timeoutMs:v}),d("pie-iife-bundle-retry-success",{url:f,attempt:w,elapsedMs:I,timeoutMs:v}));return}catch(I){const x=Date.now()-b,C=v-x,L=I instanceof Error?I.message:String(I);if(C<=0){const M=new Error(`IIFE bundle load timed out after ${v}ms: ${f}`);throw e.onBundleRetryStatus?.({state:"timeout",url:f,attempt:w,elapsedMs:x,timeoutMs:v,reason:L}),d("pie-iife-bundle-retry-timeout",{url:f,attempt:w,elapsedMs:x,timeoutMs:v,lastError:L}),c(M,{url:f,attempt:w,elapsedMs:x,timeoutMs:v,lastError:L}),M}const E=Math.min(g,C);e.onBundleRetryStatus?.({state:"retrying",url:f,attempt:w,elapsedMs:x,timeoutMs:v,retryDelayMs:E,reason:L}),d("pie-iife-bundle-retry",{url:f,attempt:w,elapsedMs:x,retryDelayMs:E,timeoutMs:v,lastError:L}),await yO(E)}}}function l(){if(!e.trackPageActions)return;const f=e.instrumentationProvider;if(Vu(f)&&f.isReady())return f}function d(f,p){const g=l();if(g)try{g.trackEvent(f,p)}catch{}}function c(f,p){const g=l();if(g)try{g.trackError(f,{...p,component:"iife-adapter",errorType:"IifeBundleRetryError"})}catch{}}async function u(f,p){if(!f||Object.keys(f).length===0)return;const g=fO(f);if(g){const x=new Map;for(const C of Object.keys(f))x.set(C,{kind:"backend-rejected",tag:C,cause:g});throw new al(x)}const v=mO(f,t,e);try{await s(v,p.doc)}catch(x){const C=x instanceof Error?x.message:String(x),L=new Map;for(const E of Object.keys(f))L.set(E,{kind:"bundle-load-failed",tag:E,url:v,cause:C});throw new al(L)}const b=pO();if(!b){const x=new Map;for(const C of Object.keys(f))x.set(C,{kind:"bundle-load-failed",tag:C,url:v,cause:"window.pie.default missing after bundle load"});throw new al(x)}const w=new Map,I=t===$s.editor;for(const[x,C]of Object.entries(f)){const L=Y_(C),E=b[L];if(!E){w.set(x,{kind:"package-not-in-bundle",tag:x,packageName:L,availablePackages:Object.keys(b)});continue}const M=I?E.Configure??bO():E.Element;if(!M){w.set(x,{kind:"no-element-class",tag:x,packageName:L});continue}if(!sv(M)){w.set(x,{kind:"not-a-constructor",tag:x,packageName:L});continue}let U;try{U=Ny(x,`element tag for ${L}`)}catch(te){w.set(x,{kind:"define-failed",tag:x,cause:te instanceof Error?te.message:String(te)});continue}try{Dy(U,class extends M{},`element tag for ${L}`)}catch(te){w.set(x,{kind:"define-failed",tag:x,cause:te instanceof Error?te.message:String(te)});continue}tb({package:C,status:jl.loaded,tagName:U,element:M,controller:r?E.controller??null:null,config:E.config??null,bundleType:t})}if(w.size>0)throw new al(w)}return{load:u,get __seams(){return o}}}function L0(e,t){return new Promise((r,n)=>{const i=t.createElement("script");i.src=e,i.defer=!0,i.setAttribute("data-pie-bundle","true"),i.onload=()=>r(),i.onerror=()=>n(new Error(`Failed to load IIFE bundle from: ${e}`)),t.head.appendChild(i)})}function pO(){const e=globalThis.window?.pie?.default;if(!(!e||typeof e!="object"))return e}function mO(e,t,r){const n=Object.keys(e).sort().join(",");if(r.bundleInfo?.url){const s=r.bundleInfo.url.includes("?")?"&":"?";return n?`${r.bundleInfo.url}${s}elements=${encodeURIComponent(n)}`:r.bundleInfo.url}const i=J_(Object.values(e)),o=`${gO(r.bundleHost)}${i}/${t}`;return n?`${o}?elements=${encodeURIComponent(n)}`:o}function gO(e){return`${e.trim().replace(/\/+$/,"")}/`}function vO(e){return{retryDelayMs:typeof e?.retryDelayMs=="number"&&e.retryDelayMs>0?e.retryDelayMs:ov.retryDelayMs,timeoutMs:typeof e?.timeoutMs=="number"&&e.timeoutMs>0?e.timeoutMs:ov.timeoutMs}}function yO(e){return new Promise(t=>setTimeout(t,e))}function bO(){return class extends HTMLElement{constructor(...t){super(...t),T(this,"_model",void 0),T(this,"_configuration",void 0)}get model(){return this._model}set model(t){this._model=t}get configuration(){return this._configuration}set configuration(t){this._configuration=t}}}var wO=class extends Error{constructor(e,t,r){super(e),T(this,"name","ElementLoaderError"),T(this,"unregisteredTags",void 0),T(this,"reasons",void 0),this.unregisteredTags=t,this.reasons=r}},SO=class extends Error{constructor(e,t,r,n={}){super(IO(e,t,r,n)),T(this,"name","ElementAssertionError"),T(this,"expectedTags",void 0),T(this,"missingTags",void 0),T(this,"currentlyRegisteredTags",void 0),this.expectedTags=e,this.missingTags=t,this.currentlyRegisteredTags=r}};function IO(e,t,r,n){const i=t.map(o=>{const s=sE(n[o]),a=$h(o).baseName,l=s?r.filter(c=>kO(c)===s):r.filter(c=>$h(c).baseName===a);!l.includes(a)&&Yu(a)&&l.push(a);const d=s??a;return l.length>0?`${d} is registered as [${l.join(", ")}]`:`nothing is registered for ${d}`});return`ElementLoader.assertRegistered: missing [${t.join(", ")}] of [${e.join(", ")}]; ${i.join("; ")}.`}function sE(e){if(e)try{return ya(e).name||void 0}catch{return}}function kO(e){return sE(Zp()[e]?.package)}var TO=5e3,EO=ov.timeoutMs,Pf=new Map,O0=new Map,CO=new Map;async function xO(e,t){if(!e||Object.keys(e).length===0)return;ZT(e,t.elementPackagePolicy);const r=Object.keys(e),n=t.whenDefinedTimeoutMs??TO,i=t.loadTimeoutMs??EO;if(FO(r))return;const o=$O(t.backend,e),s=Pf.get(o);if(s)return s;const a=RO(e,r,AO(t.backend),{doc:MO(t.doc),whenDefinedTimeoutMs:n},n,i);Pf.set(o,a);try{await a}finally{Pf.get(o)===a&&Pf.delete(o)}}async function RO(e,t,r,n,i,o){let s;try{await _O(r.load(e,n),t,o)}catch(c){s=c instanceof Error?c:new Error(String(c))}const a=await Promise.all(t.map(async c=>{if(Yu(c))return{tag:c,ok:!0};const u=F0(s,c);if(u&&u.kind!=="timeout")return{tag:c,ok:!1};try{return await HO(c,i),{tag:c,ok:!0}}catch{return{tag:c,ok:!1}}})),l=new Set,d=new Map;for(const c of a){if(c.ok)continue;l.add(c.tag);const u=F0(s,c.tag);d.set(c.tag,u??{kind:"timeout",tag:c.tag,timeoutMs:i})}if(l.size>0)throw new wO(`Element registration failed; missing tags: ${[...l].join(", ")}`,l,d)}async function _O(e,t,r){let n;try{await Promise.race([e,new Promise((i,o)=>{n=setTimeout(()=>{const s=new Map;for(const a of t)s.set(a,{kind:"timeout",tag:a,timeoutMs:r});o(new al(s))},r)})])}finally{n&&clearTimeout(n)}}function PO(e){const t=Array.isArray(e)?{}:e??{},r=Array.isArray(e)?e:Object.keys(t);if(r.length===0)return;const n=r.filter(i=>!Yu(i));if(n.length!==0)throw new SO(r,n,zO(),t)}function AO(e){if(aE(e))return e;if("kind"in e){if(e.kind==="iife")return hO(e);if(e.kind==="esm"){const t=lE(e),r=CO.get(t);if(r)return r;const n=O0.get(t);if(n)return n;const i=zL(e);return O0.set(t,i),i}}throw new Error("ElementLoader: invalid backend option")}function aE(e){return typeof e.load=="function"&&!("kind"in e)}function MO(e){if(e)return e;if(typeof document<"u")return document;throw new Error("ElementLoader: no Document available; pass options.doc explicitly")}function $O(e,t){const r=lE(e),n=Object.entries(t).sort(([i],[o])=>i.localeCompare(o));return`${r}|${JSON.stringify(n)}`}var N0=new WeakMap,LO=0,D0=new WeakMap,OO=0,j0=new WeakMap,NO=0;function lE(e){if(aE(e)){let t=N0.get(e);return t||(t=`b${++LO}`,N0.set(e,t)),`backend#${t}`}if("kind"in e){if(e.kind==="iife")return`iife#${B0({kind:"iife",bundleHost:e.bundleHost,bundleType:e.bundleType??"",needsControllers:e.needsControllers??!0,bundleInfo:e.bundleInfo??null,debugEnabled:e.debugEnabled??null,bundleRetry:e.bundleRetry??null,onBundleRetryStatus:e.onBundleRetryStatus??null,trackPageActions:e.trackPageActions??!1,instrumentationProvider:e.instrumentationProvider??null})}`;if(e.kind==="esm")return`esm#${B0({kind:"esm",cdnBaseUrl:e.cdnBaseUrl,cdnProvider:e.cdnProvider??null,moduleResolution:e.moduleResolution??"url",view:e.view??"delivery",viewConfig:e.viewConfig??null,loadControllers:e.loadControllers??!0,debugEnabled:e.debugEnabled??null,trackPageActions:e.trackPageActions??!1,instrumentationProvider:e.instrumentationProvider??null})}`}return"unknown"}function B0(e){return JSON.stringify(vv(e,new Map))}function vv(e,t){if(e==null)return e;const r=typeof e;if(r==="string"||r==="number"||r==="boolean")return e;if(r==="function")return{__functionRef:jO(e)};if(r!=="object")return String(e);const n=e,i=t.get(n);if(i)return{__cycleRef:i};const o=`cycle#${t.size+1}`;if(t.set(n,o),Array.isArray(e))return e.map(a=>vv(a,t));if(!DO(e))return{__objectRef:BO(n)};const s={};for(const a of Object.keys(e).sort())s[a]=vv(e[a],t);return s}function DO(e){if(!e||typeof e!="object")return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function jO(e){let t=D0.get(e);return t||(t=`fn#${++OO}`,D0.set(e,t)),t}function BO(e){let t=j0.get(e);return t||(t=`obj#${++NO}`,j0.set(e,t)),t}function FO(e){return e.every(t=>Yu(t))}function Yu(e){return typeof customElements>"u"?!1:customElements.get(e)!==void 0}async function HO(e,t){if(typeof customElements>"u")throw new Error(`no customElements to await ${e}`);let r;try{return await Promise.race([customElements.whenDefined(e).then(()=>{}),new Promise((n,i)=>{r=setTimeout(()=>i(new Error(`Timeout waiting for ${e}`)),t)})])}finally{r&&clearTimeout(r)}}function zO(){return typeof window>"u"?[]:Object.values(Zp()).filter(e=>e?.status===jl.loaded).map(e=>e.tagName).filter(e=>typeof e=="string"&&Yu(e)).sort()}function F0(e,t){if(e)return e instanceof al?e.reasons.get(t):{kind:"backend-rejected",tag:t,cause:e.message}}function WO(e){return e.loadControllers??(e.author||!e.hosted)}function UO(e,t=VO()){const r=e?.elements;if(!t||!r||typeof r!="object")return e;let n=!1;const i={};for(const[o,s]of Object.entries(r)){const a=String(s),l=qO(a,t);i[o]=l??a,l!==void 0&&l!==a&&(n=!0)}return n?{...e,elements:i}:e}function qO(e,t){let r;try{r=ya(e).name}catch{return}const n=t[r];return typeof n=="string"&&n.length>0?n:void 0}function VO(){if(typeof window>"u")return;const e=window.PIE_PRELOADED_ELEMENTS;return e&&typeof e=="object"?e:void 0}function GO(e){if(typeof window>"u"||typeof customElements>"u")return[];const t=[];for(const[r,n]of Object.entries(e)){if(customElements.get(r))continue;const i=KO(r,n);if(!i)continue;const{entry:o,elementClass:s}=i;Dy(r,class extends s{},`preloaded element tag for ${n}`),tb({...o,tagName:r}),t.push(r)}return t}function KO(e,t){const{existingEncodedVersion:r}=$h(e);if(!r)return;let n;for(const i of Object.values(Zp())){if(i?.status!==jl.loaded||i.package!==t||typeof i.tagName!="string"||$h(i.tagName).existingEncodedVersion!==r)continue;const o=customElements.get(i.tagName);o&&(!n||!n.entry.controller&&i.controller)&&(n={entry:i,elementClass:o})}return n}function XO(e,t){return e.kind===t.kind&&e.host===t.host&&e.itemId===t.itemId&&e.canonicalItemId===t.canonicalItemId&&e.contentKind===t.contentKind}function H0(e){return eP(e.item,e.kind)}function Km(e,t){const r={kind:t.kind,itemId:t.itemId,canonicalItemId:t.canonicalItemId,contentKind:t.contentKind,item:t.item,element:t.host};Ms(t.host,e,r)}function cE(){let e=null,t=null;function r(){const i=e;i&&(e=null,t=null,Km(f$,i))}function n(i){if(!i){r();return}if(e&&XO(e,i)){if(e.item===i.item)return;const o=H0(i);if(o!==null&&o===t){e=i;return}e=i,t=o,Km(g0,i);return}e=i,t=H0(i),Km(g0,i)}return{sync:n,retire:r}}var ZO=Ht('<div class="pie-item-shell-anchor svelte-1w54qg5" aria-hidden="true"></div> <!>',1),YO={hash:"svelte-1w54qg5",code:".pie-item-shell-anchor.svelte-1w54qg5 {display:none;}"};function JO(e,t){un(t,!0),Mn(e,YO);const r=Ys("pie-item-shell",()=>!1),n="pie-content-loaded",i="pie-item-player-error";let o=_(t,"itemId",7,""),s=_(t,"canonicalItemId",7,""),a=_(t,"contentKind",7,"assessment-item"),l=_(t,"regionPolicy",7,"default"),d=_(t,"scopeElement",7,null),c=_(t,"ttsHighlightTargetResolver",7,null),u=_(t,"item",7,null),f=He(null);const p=Date.now();let g=null,v=null,b=null,w=null;function I(){if(!h(f))return null;const X=h(f).getRootNode();return X&&"host"in X?X.host:h(f).parentElement}const x=ee(()=>I()),C=ee(()=>d()||h(x)||null),L=ee(()=>h(C)?{scopeElement:h(C),ttsHighlightTargetResolver:c()}:null),E=ee(()=>{if(!h(x))return null;const X=s()||o();return{kind:"item",itemId:o(),canonicalItemId:X,contentKind:a(),regionPolicy:l(),scopeElement:h(C),item:u(),contextVersion:p}}),M=cE();function U(){return!h(x)||!o()?null:{kind:"item",host:h(x),itemId:o(),canonicalItemId:s()||o(),contentKind:a(),item:u()}}function te(X){if(!h(x)||!o())return;const j=X.detail,D={itemId:o(),session:j};Ms(h(x),h$,D);const Z=LT({itemId:o(),sessionDetail:j});if(Z.intent==="metadata-only"||!Z.session)return;const F={itemId:o(),canonicalItemId:s()||o(),session:Z.session,...Z.sessionCommitReason?{sessionCommitReason:Z.sessionCommitReason}:{}};Ms(h(x),p$,F)}function re(X){if(!h(x)||!o())return;const j={itemId:o(),canonicalItemId:s()||o(),contentKind:a(),detail:X};Ms(h(x),n,j)}function Pe(X){if(!h(x)||!o())return;const j={itemId:o(),canonicalItemId:s()||o(),contentKind:a(),error:X};Ms(h(x),i,j)}function z(X){const j=X&&typeof X=="object"?{...X}:X;j&&typeof j=="object"&&(delete j.timestamp,delete j.sourceRuntimeId);try{return JSON.stringify(j)}catch{return String(j)}}ct(()=>{if(!h(x))return;let X="";const j=F=>{F.stopPropagation();const W=F.detail,O=z(W);!(W&&typeof W=="object"&&W.sessionCommitReason)&&O===X||(X=O,te(F))};h(x).addEventListener("session-changed",j);const D=F=>{F.stopPropagation(),re(F.detail)},Z=F=>{F.stopPropagation(),Pe(F.detail)};return h(x).addEventListener("load-complete",D),h(x).addEventListener("player-error",Z),()=>{try{ib(h(x),{reason:"teardown",logger:r})}finally{h(x)?.removeEventListener("session-changed",j),h(x)?.removeEventListener("load-complete",D),h(x)?.removeEventListener("player-error",Z),M.retire()}}}),ct(()=>{M.sync(U())}),ct(()=>{h(x)&&(h(x).setAttribute("data-item-id",o()),h(x).setAttribute("data-canonical-item-id",s()||o()),h(x).setAttribute("data-pie-shell-root","item"),h(x).setAttribute("data-region-policy",l()))}),ct(()=>{if(!(!h(x)||!h(E)))return g=new Ws(h(x),{context:dk,initialValue:h(E)}),g.connect(),v=new Bl(h(x)),v.attach(),()=>{v?.detach(),v=null,g?.disconnect(),g=null}}),ct(()=>{h(E)&&g?.setValue(h(E))}),ct(()=>{if(!(!h(x)||!h(L)))return b=new Ws(h(x),{context:lk,initialValue:h(L)}),b.connect(),w=new Bl(h(x)),w.attach(),()=>{w?.detach(),w=null,b?.disconnect(),b=null}}),ct(()=>{h(L)&&b?.setValue(h(L))});var K={get itemId(){return o()},set itemId(X=""){o(X),R()},get canonicalItemId(){return s()},set canonicalItemId(X=""){s(X),R()},get contentKind(){return a()},set contentKind(X="assessment-item"){a(X),R()},get regionPolicy(){return l()},set regionPolicy(X="default"){l(X),R()},get scopeElement(){return d()},set scopeElement(X=null){d(X),R()},get ttsHighlightTargetResolver(){return c()},set ttsHighlightTargetResolver(X=null){c(X),R()},get item(){return u()},set item(X=null){u(X),R()}},oe=ZO(),ue=jn(oe);Er(ue,X=>be(f,X),()=>h(f));var ae=lr(ue,2);return dd(ae,t,"default",{},null),ft(e,oe),fn(K)}QO("pie-item-shell",In(JO,{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"}},["default"],[],{mode:"open"}));function QO(e,t){customElements.get(e)||customElements.define(e,t)}var z0,W0,dE,uE,e2="5";typeof window<"u"&&((z0=(W0=window).__svelte??(W0.__svelte={})).v??(z0.v=new Set)).add(e2);var Jn=2,fd=4,Ju=8,pb=16777216,Go=16,vo=32,Ts=64,mb=128,gb=256,Bo=512,yn=1024,dn=2048,Xi=4096,ui=8192,fi=16384,Ra=32768,Yh=33554432,Kc=65536,Jh=131072,t2=262144,nc=524288,r2=1048576,ps=33554432,Qh=2097152,Xc=4194304,wa=8388608,wl=Symbol("$state"),fE=Symbol("component"),hE=Symbol("legacy props"),n2=Symbol(""),yv=Symbol("attributes"),bv=Symbol("class"),i2=Symbol("style"),gh=Symbol("text"),Qu=new class extends Error{constructor(...e){super(...e),T(this,"name","StaleReactionError"),T(this,"message","The reaction that called `getAbortSignal()` was re-run or destroyed")}},o2=!!globalThis.document?.contentType&&globalThis.document.contentType.includes("xml"),am=3,hd=8,s2=1,a2=2,pE=4,l2=8,c2=16,d2=1,u2=2,f2=4,h2=8,p2=16,m2=1,g2=2,mE="[",vb="[!",U0="[?",yb="]",Hl={},Cn=Symbol("uninitialized"),gE="http://www.w3.org/1999/xhtml",v2="http://www.w3.org/2000/svg",y2="http://www.w3.org/1998/Math/MathML";function b2(){console.warn("https://svelte.dev/e/derived_inert")}function ef(e){console.warn("https://svelte.dev/e/hydration_mismatch")}function w2(){console.warn("https://svelte.dev/e/svelte_boundary_reset_noop")}var vE=Array.isArray,S2=Array.prototype.indexOf,ep=Array.prototype.includes,lm=Array.from,tp=Object.keys,gu=Object.defineProperty,Sl=Object.getOwnPropertyDescriptor,yE=Object.getOwnPropertyDescriptors,I2=Object.prototype,k2=Array.prototype,bb=Object.getPrototypeOf,q0=Object.isExtensible,T2=()=>{};function E2(e){for(var t=0;t<e.length;t++)e[t]()}function bE(){var e,t;return{promise:new Promise((r,n)=>{e=r,t=n}),resolve:e,reject:t}}function C2(e){var t=Ft;if(t===null)return ir.f|=wa,e;if((t.f&Ra)===0&&(t.f&fd)===0)throw e;ys(e,t)}function ys(e,t){if(!(t!==null&&(t.f&fi)!==0)){for(;t!==null;){if((t.f&mb)!==0&&(t.f&(fi|Yh))===0){if((t.f&Ra)===0)throw e;try{t.b.error(e);return}catch(r){e=r}}t=t.parent}throw e}}function x2(){throw Error("https://svelte.dev/e/async_derived_orphan")}function R2(e,t,r){throw Error("https://svelte.dev/e/each_key_duplicate")}function _2(e){throw Error("https://svelte.dev/e/effect_in_teardown")}function P2(){throw Error("https://svelte.dev/e/effect_in_unowned_derived")}function A2(e){throw Error("https://svelte.dev/e/effect_orphan")}function M2(){throw Error("https://svelte.dev/e/effect_update_depth_exceeded")}function $2(){throw Error("https://svelte.dev/e/hydration_failed")}function L2(e){throw Error("https://svelte.dev/e/props_invalid_value")}function O2(){throw Error("https://svelte.dev/e/state_descriptors_fixed")}function N2(){throw Error("https://svelte.dev/e/state_prototype_fixed")}function D2(){throw Error("https://svelte.dev/e/state_unsafe_mutation")}function j2(){throw Error("https://svelte.dev/e/svelte_boundary_reset_onerror")}var _a=!1,cm=!1,bn=null;function Zc(e){bn=e}function dm(e,t=!1,r){bn={p:bn,i:!1,c:null,e:null,s:e,x:null,r:Ft,l:cm&&!t?{s:null,u:null,$:[]}:null}}function um(e){var t=bn,r=t.e;if(r!==null){t.e=null;for(var n of r)jE(n)}return e!==void 0&&(t.x=e),t.i=!0,bn=t.p,wb(e)}function wb(e={}){return gu(e,fE,{value:!0}),e}function pd(){return!cm||bn!==null&&bn.l===null}var ll=[];function wE(){var e=ll;ll=[],E2(e)}function Ea(e){if(ll.length===0&&!tu){var t=ll;queueMicrotask(()=>{t===ll&&wE()})}ll.push(e)}function B2(){for(;ll.length>0;)wE()}function SE(e){return e===this.v}function IE(e,t){return e!=e?t==t:e!==t||e!==null&&typeof e=="object"||typeof e=="function"}function kE(e){return!IE(e,this.v)}function fm(e){var t=ir,r=Ft;_i(null),ho(null);try{return e()}finally{_i(t),ho(r)}}function F2(e,t,r,n){let i=pd()?vu:Ib;var o=e.filter(p=>!p.settled),s=t.map(i);if(r.length===0&&o.length===0){n(s);return}var a=Ft,l=H2(),d=o.length===1?o[0].promise:o.length>1?Promise.all(o.map(p=>p.promise)):null;function c(p){if((a.f&fi)===0){l();try{n([...s,...p])}catch(g){ys(g,a)}rp()}}var u=TE();if(r.length===0){d.then(()=>c([])).finally(u);return}function f(){Promise.all(r.map(p=>W2(p))).then(c).catch(p=>ys(p,a)).finally(u)}d?d.then(()=>{l(),f(),rp()}):f()}function H2(){var e=Ft,t=ir,r=bn,n=qt;return function(i=!0){ho(e),_i(t),Zc(r),i&&(e.f&fi)===0&&(n?.activate(),n?.apply())}}function rp(e=!0){ho(null),_i(null),Zc(null),e&&qt?.deactivate()}function TE(){var e=Ft,t=e.b,r=qt,n=!!t?.is_rendered();return t?.update_pending_count(1,r),r.increment(n,e),()=>{t?.update_pending_count(-1,r),r.decrement(n,e)}}var z2=~(dn|Xi|yn);function an(e,t){e.f=e.f&z2|t}function Sb(e){(e.f&Bo)!==0||e.deps===null?an(e,yn):an(e,Xi)}function vu(e){var t=Jn|dn;return Ft!==null&&(Ft.f|=nc),{ctx:bn,deps:null,effects:null,equals:SE,f:t,fn:e,reactions:null,rv:0,v:Cn,wv:0,parent:Ft,ac:null}}var Hd=Symbol("obsolete");function W2(e,t,r){let n=Ft;n===null&&x2();var i=void 0,o=zl(Cn),s=!ir,a=new Set;return nN(()=>{var l=Ft,d=bE();i=d.promise;try{Promise.resolve(e()).then(d.resolve,p=>{p!==Qu&&d.reject(p)}).finally(rp)}catch(p){d.reject(p),rp()}var c=qt;if(s){if((l.f&Ra)!==0)var u=TE();if(n.b?.is_rendered())c.async_deriveds.get(l)?.reject(Hd);else for(let p of a.values())p.reject(Hd);a.add(d),c.async_deriveds.set(l,d)}let f=(p,g=void 0)=>{u?.(),a.delete(d),g!==Hd&&(c.activate(),g?(o.f|=wa,Yc(o,g)):((o.f&wa)!==0&&(o.f^=wa),Yc(o,p)),c.deactivate())};d.promise.then(f,p=>f(null,p||"unknown"))}),eN(()=>{for(let l of a)l.reject(Hd)}),new Promise(l=>{function d(c){function u(){c===i?l(o):d(i)}c.then(u,u)}d(i)})}function Ze(e){let t=vu(e);return _a||UE(t),t}function Ib(e){let t=vu(e);return t.equals=kE,t}function U2(e){var t=e.effects;if(t!==null){e.effects=null;for(var r=0;r<t.length;r+=1)hi(t[r])}}function kb(e){var t,r=Ft,n=e.parent;if(!Us&&n!==null&&e.v!==Cn&&(n.f&(fi|ui))!==0)return b2(),e.v;ho(n);try{U2(e),t=KE(e)}finally{ho(r)}return t}function EE(e){var t=kb(e);if(!e.equals(t)&&(e.wv=VE(),(!qt?.is_fork||e.deps===null)&&(qt!==null?(qt.capture(e,t,!0),Sv?.capture(e,t,!0)):e.v=t,e.deps===null))){an(e,yn);return}Us||(li!==null?(Cb()||qt?.is_fork)&&li.set(e,t):Sb(e))}function q2(e){if(e.effects!==null)for(let t of e.effects)(t.teardown||t.ac)&&(t.teardown?.(),t.ac!==null&&fm(()=>{t.ac.abort(Qu),t.ac=null}),t.fn!==null&&(t.teardown=T2),bu(t,0),Rb(t))}function CE(e){if(e.effects!==null)for(let t of e.effects)t.teardown&&t.fn!==null&&Jc(t)}var np=new Set,bs=new Map,xE=!1;function zl(e,t){return{f:0,v:e,reactions:null,equals:SE,rv:0,wv:0}}function Sr(e,t){let r=zl(e,t);return UE(r),r}function RE(e,t=!1,r=!0){var n;let i=zl(e);return t||(i.equals=kE),cm&&r&&bn!==null&&bn.l!==null&&((n=bn.l).s??(n.s=[])).push(i),i}function bt(e,t,r=!1){return ir!==null&&(!Ao||(ir.f&Jh)!==0)&&pd()&&(ir.f&(Jn|Go|Xc|Jh))!==0&&(Fo===null||!Fo.has(e))&&D2(),Yc(e,r?Ls(t):t,op)}var tl=null,wv=0;function Yc(e,t,r=null){if(!e.equals(t)){Us?bs.set(e,t):bs.has(e)||bs.set(e,e.v);var n=ic.ensure();if(n.capture(e,t),(e.f&Jn)!==0){let i=e;(e.f&dn)!==0&&kb(i),li===null&&Sb(i)}e.wv=VE(),tl=null,wv=0,_E(e,dn,r),tl=null,pd()&&Ft!==null&&(Ft.f&yn)!==0&&(Ft.f&(vo|Ts))===0&&(ro===null?sN([e]):ro.push(e)),!n.is_fork&&np.size>0&&!xE&&V2()}return t}function V2(){xE=!1;for(let e of np){(e.f&yn)!==0&&an(e,Xi);let t;try{t=tf(e)}catch{t=!0}t&&Jc(e)}np.clear()}function eu(e){bt(e,e.v+1)}function _E(e,t,r){var n=e.reactions;if(n!==null){var i=pd(),o=n.length;if(wv+=o,wv>1e5&&tl===null&&(tl=new Set),tl!==null){if(tl.has(e))return;tl.add(e)}for(var s=0;s<o;s++){var a=n[s],l=a.f;if(!(!i&&a===Ft)){var d=(l&dn)===0;if(d&&an(a,t),(l&Jh)!==0)np.add(a);else if((l&Jn)!==0){var c=a;li?.delete(c),_E(c,Xi,r)}else if(d){var u=a;(l&Go)!==0&&as!==null&&as.add(u),r!==null?r.push(u):Eb(u)}}}}}function PE(e,t,r){(e.f&dn)!==0?t.add(e):(e.f&Xi)!==0&&r.add(e),an(e,yn)}var ip=null,Ic=null,qt=null,Sv=null,li=null,Iv=null,tu=!1,Xm=!1,yu=null,op=null,AE=0,G2=1,sp=new WeakMap,Il=new WeakMap,cl=new WeakMap,ap=new WeakMap,Af=new WeakMap,kc=new WeakMap,Ya=new WeakMap,zd=new WeakMap,Co=new WeakMap,kv=new WeakMap,Wl=new WeakMap,js=new WeakMap,ma=new WeakMap,vh=new WeakMap,Wd=new WeakMap,Qr=new WeakSet,ic=class ME{constructor(){ad(this,Qr),T(this,"id",G2++),Le(this,sp,!1),T(this,"linked",!0),Le(this,Il,null),Le(this,cl,null),T(this,"async_deriveds",new Map),T(this,"current",new Map),T(this,"previous",new Map),Le(this,ap,new Set),Le(this,Af,new Set),Le(this,kc,0),Le(this,Ya,new Map),Le(this,zd,null),Le(this,Co,[]),Le(this,kv,[]),Le(this,Wl,new Set),Le(this,js,new Set),Le(this,ma,new Map),Le(this,vh,new Set),T(this,"is_fork",!1),Le(this,Wd,!1),Ic===null?ip=Ic=this:(Ce(cl,Ic,this),Ce(Il,this,Ic)),Ic=this}skip_effect(t){S(ma,this).has(t)||S(ma,this).set(t,{d:[],m:[]}),S(vh,this).delete(t)}unskip_effect(t,r=n=>this.schedule(n)){var n=S(ma,this).get(t);if(n){S(ma,this).delete(t);for(var i of n.d)an(i,dn),r(i);for(i of n.m)an(i,Xi),r(i)}S(vh,this).add(t)}capture(t,r,n=!1){t.v!==Cn&&!this.previous.has(t)&&this.previous.set(t,t.v),(t.f&wa)===0&&(this.current.set(t,[r,n]),li?.set(t,r)),this.is_fork||(t.v=r)}activate(){qt=this}deactivate(){qt=null,li=null}flush(){try{Xm=!0,qt=this,je(Qr,this,lp).call(this)}finally{AE=0,Iv=null,yu=null,op=null,Xm=!1,qt=null,li=null,bs.clear()}}discard(){for(let t of S(Af,this))t(this);S(Af,this).clear();for(let t of this.async_deriveds.values())t.reject(Hd);je(Qr,this,cp).call(this),S(zd,this)?.resolve()}register_created_effect(t){S(kv,this).push(t)}increment(t,r){if(Ce(kc,this,S(kc,this)+1),t){let n=S(Ya,this).get(r)??0;S(Ya,this).set(r,n+1)}}decrement(t,r){if(Ce(kc,this,S(kc,this)-1),t){let n=S(Ya,this).get(r)??0;n===1?S(Ya,this).delete(r):S(Ya,this).set(r,n-1)}S(Wd,this)||(Ce(Wd,this,!0),Ea(()=>{Ce(Wd,this,!1),this.linked&&this.flush()}))}transfer_effects(t,r){for(let n of t)S(Wl,this).add(n);for(let n of r)S(js,this).add(n);t.clear(),r.clear()}oncommit(t){S(ap,this).add(t)}ondiscard(t){S(Af,this).add(t)}settled(){return(S(zd,this)??Ce(zd,this,bE())).promise}static ensure(){if(qt===null){let t=qt=new ME;!Xm&&!tu&&Ea(()=>{S(sp,t)||t.flush()})}return qt}apply(){if(!_a||!this.is_fork&&S(Il,this)===null&&S(cl,this)===null){li=null;return}li=new Map;for(let[r,[n]]of this.current)li.set(r,n);for(let r=ip;r!==null;r=S(cl,r))if(!(r===this||r.is_fork)){var t=!1;if(r.id<this.id){for(let[n,[,i]]of r.current)if(!i&&this.current.has(n)){t=!0;break}}if(!t)for(let[n,i]of r.previous)li.has(n)||li.set(n,i)}}schedule(t){if(Iv=t,t.b?.is_pending&&(t.f&(fd|Ju|pb))!==0&&(t.f&Ra)===0){t.b.defer_effect(t);return}S(Co,this).push(t)}};dE=ic;function V0(){if(this.is_fork)return!0;for(let r of S(Ya,this).keys()){for(var e=r,t=!1;e.parent!==null;){if(S(ma,this).has(e)){t=!0;break}e=e.parent}if(!t)return!0}return!1}function $E(){var e=[];for(let i of S(Co,this))if(!((i.f&fi)!==0||(i.f&(dn|Xi))===0)){for(var t=i,r=!1;t.parent!==null;){t=t.parent;var n=t.f;if((n&(Ts|vo))!==0){if((n&yn)===0){r=!0;break}t.f^=yn}}r||e.push(t)}return Ce(Co,this,[]),e}function lp(){Ce(sp,this,!0);for(let s of S(Wl,this))S(js,this).delete(s),an(s,dn),this.schedule(s);for(let s of S(js,this))an(s,Xi),this.schedule(s);this.apply();for(var e=yu=[],t=[],r=op=[];S(Co,this).length>0;){AE++>1e3&&(je(Qr,this,cp).call(this),Y2());for(let s of je(Qr,this,$E).call(this))try{je(Qr,this,LE).call(this,s,e,t)}catch(a){throw DE(s),!je(Qr,this,V0).call(this)&&this.discard(),a}}if(qt=null,r.length>0){var n=dE.ensure();for(let s of r)n.schedule(s)}if(yu=null,op=null,je(Qr,this,V0).call(this)){je(Qr,this,Ud).call(this,t),je(Qr,this,Ud).call(this,e);for(let[s,a]of S(ma,this))NE(s,a);r.length>0&&je(Qr,qt,lp).call(qt);return}let i=je(Qr,this,K2).call(this);if(i){je(Qr,this,Ud).call(this,t),je(Qr,this,Ud).call(this,e),je(Qr,i,X2).call(i,this);return}S(Wl,this).clear(),S(js,this).clear();for(let s of S(ap,this))s(this);S(ap,this).clear(),Sv=this,G0(t),G0(e),Sv=null,S(zd,this)?.resolve();var o=qt;if(S(kc,this)===0&&(S(Co,this).length===0||o!==null)&&(je(Qr,this,cp).call(this),_a&&(je(Qr,this,Z2).call(this),qt=o)),S(Co,this).length>0)if(o!==null){for(let s of S(Co,this))S(Co,o).push(s);Ce(Co,this,[])}else o=this;o!==null&&(bs.clear(),je(Qr,o,lp).call(o))}function LE(e,t,r){e.f^=yn;for(var n=e.first;n!==null;){var i=n.f,o=(i&(vo|Ts))!==0;if(!(o&&(i&yn)!==0||(i&ui)!==0||S(ma,this).has(n))&&n.fn!==null){o?n.f^=yn:(i&fd)!==0?t.push(n):_a&&(i&(Ju|pb))!==0?r.push(n):tf(n)&&((i&Go)!==0&&S(js,this).add(n),Jc(n));var s=n.first;if(s!==null){n=s;continue}}for(;n!==null;){var a=n.next;if(a!==null){n=a;break}n=n.parent}}}function K2(){for(var e=S(Il,this);e!==null;){if(!e.is_fork){for(let[t,[,r]]of this.current)if(e.current.has(t)&&!r)return e}e=S(Il,e)}return null}function X2(e){for(let[r,n]of e.current)!this.previous.has(r)&&e.previous.has(r)&&this.previous.set(r,e.previous.get(r)),this.current.set(r,n);for(let[r,n]of e.async_deriveds){let i=this.async_deriveds.get(r);i&&n.promise.then(i.resolve).catch(i.reject)}e.async_deriveds.clear(),this.transfer_effects(S(Wl,e),S(js,e));let t=r=>{var n=r.reactions;if(n!==null&&!((r.f&Jn)!==0&&(r.f&(dn|Xi))===0))for(let s of n){var i=s.f;if((i&Jn)!==0)t(s);else{var o=s;i&(Xc|Go)&&!this.async_deriveds.has(o)&&(S(js,this).delete(o),an(o,dn),this.schedule(o))}}};for(let r of this.current.keys())t(r);this.oncommit(()=>e.discard()),je(Qr,e,cp).call(e),qt=this,je(Qr,this,lp).call(this)}function Ud(e){for(var t=0;t<e.length;t+=1)PE(e[t],S(Wl,this),S(js,this))}function Z2(){for(let c=ip;c!==null;c=S(cl,c)){var e=c.id<this.id,t=[];for(let[u,[f,p]]of this.current){if(c.current.has(u)){var r=c.current.get(u)[0];if(e&&f!==r)c.current.set(u,[f,p]);else continue}t.push(u)}if(e)for(let[u,f]of this.async_deriveds){let p=c.async_deriveds.get(u);p&&f.promise.then(p.resolve).catch(p.reject)}var n=[...c.current.keys()].filter(u=>!c.current.get(u)[1]);if(!(!S(sp,c)||n.length===0)){var i=n.filter(u=>!this.current.has(u));if(i.length===0)e&&c.discard();else if(t.length>0){if(e)for(let u of S(vh,this))c.unskip_effect(u,f=>{(f.f&(Go|Xc))!==0?c.schedule(f):je(Qr,c,Ud).call(c,[f])});c.activate();var o=new Set,s=new Map;for(var a of t)OE(a,i,o,s);s=new Map;var l=[...c.current].filter(([u,f])=>{let p=this.current.get(u);return p?p[0]!==f[0]||p[1]!==f[1]:!0}).map(([u])=>u);if(l.length>0)for(let u of S(kv,this))(u.f&(fi|ui|Jh))===0&&Tb(u,l,s)&&((u.f&(Xc|Go))!==0?(an(u,dn),c.schedule(u)):S(Wl,c).add(u));if(S(Co,c).length>0&&!S(Wd,c)){c.apply();for(var d of je(Qr,c,$E).call(c))je(Qr,c,LE).call(c,d,[],[])}c.deactivate()}}}}function cp(){if(this.linked){var e=S(Il,this),t=S(cl,this);e===null?ip=t:Ce(cl,e,t),t===null?Ic=e:Ce(Il,t,e),this.linked=!1}}function gt(e){var t=tu;tu=!0;try{var r;for(e&&(qt!==null&&!qt.is_fork&&qt.flush(),r=e());;){if(B2(),qt===null)return r;qt.flush()}}finally{tu=t}}function Y2(){try{M2()}catch(e){ys(e,Iv)}}var as=null;function G0(e){var t=e.length;if(t!==0){for(var r=0;r<t;){var n=e[r++];if((n.f&(fi|ui))===0&&tf(n)&&(as=new Set,Jc(n),n.deps===null&&n.first===null&&n.nodes===null&&n.teardown===null&&n.ac===null&&HE(n),as?.size>0)){bs.clear();for(let i of as){if((i.f&(fi|ui))!==0)continue;let o=[i],s=i.parent;for(;s!==null;)as.has(s)&&(as.delete(s),o.push(s)),s=s.parent;for(let a=o.length-1;a>=0;a--){let l=o[a];(l.f&(fi|ui))===0&&Jc(l)}}as.clear()}}as=null}}function OE(e,t,r,n){if(!r.has(e)&&(r.add(e),e.reactions!==null))for(let i of e.reactions){let o=i.f;(o&Jn)!==0?OE(i,t,r,n):(o&(Xc|Go))!==0&&(o&dn)===0&&Tb(i,t,n)&&(an(i,dn),Eb(i))}}function Tb(e,t,r){let n=r.get(e);if(n!==void 0)return n;if(e.deps!==null)for(let i of e.deps){if(ep.call(t,i))return!0;if((i.f&Jn)!==0&&Tb(i,t,r))return r.set(i,!0),!0}return r.set(e,!1),!1}function Eb(e){qt.schedule(e)}function NE(e,t){if(!((e.f&vo)!==0&&(e.f&yn)!==0)){(e.f&dn)!==0?t.d.push(e):(e.f&Xi)!==0&&t.m.push(e),an(e,yn);for(var r=e.first;r!==null;)NE(r,t),r=r.next}}function DE(e){an(e,yn);for(var t=e.first;t!==null;)DE(t),t=t.next}function J2(e){Ft===null&&(ir===null&&A2(e),P2()),Us&&_2(e)}function Q2(e,t){var r=t.last;r===null?t.last=t.first=e:(r.next=e,e.prev=r,t.last=e)}function Es(e,t){var r=Ft;r!==null&&(r.f&ui)!==0&&(e|=ui);var n={ctx:bn,deps:null,nodes:null,f:e|dn|Bo,first:null,fn:t,last:null,next:null,parent:r,b:r&&r.b,prev:null,teardown:null,wv:0,ac:null};qt?.register_created_effect(n);var i=n;if((e&fd)!==0)yu!==null?yu.push(n):ic.ensure().schedule(n);else if(t!==null){try{Jc(n)}catch(s){throw hi(n),s}i.deps===null&&i.teardown===null&&i.nodes===null&&i.first===i.last&&(i.f&nc)===0&&(i=i.first,(e&Go)!==0&&(e&Kc)!==0&&i!==null&&(i.f|=Kc))}if(i!==null&&(i.parent=r,r!==null&&Q2(i,r),ir!==null&&(ir.f&Jn)!==0&&(e&Ts)===0)){var o=ir;(o.effects??(o.effects=[])).push(i)}return n}function Cb(){return ir!==null&&!Ao}function eN(e){let t=Es(Ju,null);return an(t,yn),t.teardown=e,t}function jt(e){J2("$effect");var t=Ft.f;if(!ir&&(t&vo)!==0&&bn!==null&&!bn.i){var r=bn;(r.e??(r.e=[])).push(e)}else return jE(e)}function jE(e){return Es(fd|r2,e)}function tN(e){ic.ensure();let t=Es(Ts|nc,e);return()=>{hi(t)}}function rN(e){ic.ensure();let t=Es(Ts|nc,e);return(r={})=>new Promise(n=>{r.outro?oc(t,()=>{hi(t),n(void 0)}):(hi(t),n(void 0))})}function xb(e){return Es(fd,e)}function nN(e){return Es(Xc|nc,e)}function hm(e,t=0){return Es(Ju|t,e)}function en(e,t=[],r=[],n=[]){F2(n,t,r,i=>{Es(Ju,()=>{e(...i.map(y))})})}function pm(e,t=0){return Es(Go|t,e)}function fo(e){return Es(vo|nc,e)}function BE(e){var t=e.teardown;if(t!==null){let r=Us,n=ir;K0(!0),_i(null);try{t.call(null)}catch(i){ys(i,e.parent)}finally{K0(r),_i(n)}}}function Rb(e,t=!1){var r=e.first;for(e.first=e.last=null;r!==null;){let i=r.ac;i!==null&&fm(()=>{i.abort(Qu)});var n=r.next;(r.f&Ts)!==0?r.parent=null:hi(r,t),r=n}}function iN(e){for(var t=e.first;t!==null;){var r=t.next;(t.f&vo)===0&&hi(t),t=r}}function hi(e,t=!0){var r=!1;(t||(e.f&t2)!==0)&&e.nodes!==null&&e.nodes.end!==null&&(FE(e.nodes.start,e.nodes.end),r=!0),e.f|=Yh,Rb(e,t&&!r),bu(e,0);var n=e.nodes&&e.nodes.t;if(n!==null)for(let o of n)o.stop();BE(e),e.f^=Yh,e.f|=fi;var i=e.parent;i!==null&&i.first!==null&&HE(e),e.next=e.prev=e.teardown=e.ctx=e.deps=e.fn=e.nodes=e.ac=e.b=null}function FE(e,t){for(;e!==null;){var r=e===t?null:Yo(e);e.remove(),e=r}}function HE(e){var{parent:t,prev:r,next:n}=e;r!==null&&(r.next=n),n!==null&&(n.prev=r),t!==null&&(t.first===e&&(t.first=n),t.last===e&&(t.last=r))}function oc(e,t,r=!0){var n=[];e.f|=gb,zE(e,n,!0);var i=()=>{r&&hi(e),t&&t()},o=n.length;if(o>0){var s=()=>--o||i();for(var a of n)a.out(s)}else i()}function zE(e,t,r){if((e.f&ui)===0){e.f^=ui;var n=e.nodes&&e.nodes.t;if(n!==null)for(let a of n)(a.is_global||r)&&t.push(a);for(var i=e.first;i!==null;){var o=i.next;if((i.f&Ts)===0){var s=(i.f&Kc)!==0||(i.f&vo)!==0&&(e.f&Go)!==0;zE(i,t,s?r:!1)}i=o}}}function dp(e){e.f&=~gb,WE(e,!0)}function WE(e,t){if((e.f&gb)===0&&(e.f&ui)!==0){e.f^=ui,(e.f&yn)===0&&(an(e,dn),ic.ensure().schedule(e));for(var r=e.first;r!==null;){var n=r.next,i=(r.f&Kc)!==0||(r.f&vo)!==0;WE(r,i?t:!1),r=n}var o=e.nodes&&e.nodes.t;if(o!==null)for(let s of o)(s.is_global||t)&&s.in()}}function _b(e,t){if(e.nodes)for(var r=e.nodes.start,n=e.nodes.end;r!==null;){var i=r===n?null:Yo(r);t.append(r),r=i}}var oN=null,yh=!1,Us=!1;function K0(e){Us=e}var ir=null,Ao=!1;function _i(e){ir=e}var Ft=null;function ho(e){Ft=e}var Fo=null;function UE(e){ir!==null&&(!_a&&(ir.f&Qh)!==0||(ir.f&Jn)!==0)&&(Fo??(Fo=new Set)).add(e)}var Ii=null,ji=0,ro=null;function sN(e){ro=e}var qE=1,dl=0,kl=dl;function X0(e){kl=e}function VE(){return++qE}function tf(e){var t=e.f;if((t&dn)!==0)return!0;if((t&Xi)!==0){for(var r=e.deps,n=r.length,i=0;i<n;i++){var o=r[i];if(tf(o)&&EE(o),o.wv>e.wv)return!0}(t&Bo)!==0&&li===null&&an(e,yn)}return!1}function GE(e,t,r=!0){var n=e.reactions;if(n!==null&&!(!_a&&Fo!==null&&Fo.has(e)))for(var i=0;i<n.length;i++){var o=n[i];(o.f&Jn)!==0?GE(o,t,!1):t===o&&(r?an(o,dn):(o.f&yn)!==0&&an(o,Xi),Eb(o))}}function KE(e){var t=Ii,r=ji,n=ro,i=ir,o=Fo,s=bn,a=Ao,l=kl,d=e.f;Ii=null,ji=0,ro=null,ir=(d&(vo|Ts))===0?e:null,Fo=null,Zc(e.ctx),Ao=!1,kl=++dl,e.ac!==null&&(fm(()=>{e.ac.abort(Qu)}),e.ac=null);try{e.f|=Qh;var c=e.fn,u=c();e.f|=Ra;var f=Z0(e);if(pd()&&ro!==null&&!Ao&&f!==null&&(e.f&(Jn|Xi|dn))===0)for(var p=0;p<ro.length;p++)GE(ro[p],e);if(i!==null&&i!==e){if(dl++,i.deps!==null)for(let g=0;g<r;g+=1)i.deps[g].rv=dl;if(t!==null)for(let g of t)g.rv=dl;ro!==null&&(n===null?n=ro:n.push(...ro))}return(e.f&wa)!==0&&(e.f^=wa),u}catch(g){return Z0(e),C2(g)}finally{e.f^=Qh,Ii=t,ji=r,ro=n,ir=i,Fo=o,Zc(s),Ao=a,kl=l}}function Z0(e){var t=e.deps,r=qt?.is_fork;if(Ii!==null){var n,i;if(r||bu(e,ji),t!==null&&ji>0)for(t.length=ji+Ii.length,i=0;i<Ii.length;i++)t[ji+i]=Ii[i];else e.deps=t=Ii;if(Cb()&&(e.f&Bo)!==0)for(i=ji;i<t.length;i++)((n=t[i]).reactions??(n.reactions=[])).push(e)}else!r&&t!==null&&ji<t.length&&(bu(e,ji),t.length=ji);return t}function aN(e,t){let r=t.reactions;if(r!==null){var n=S2.call(r,e);if(n!==-1){var i=r.length-1;i===0?r=t.reactions=null:(r[n]=r[i],r.pop())}}if(r===null&&(t.f&Jn)!==0&&(Ii===null||!ep.call(Ii,t))){var o=t;(o.f&Bo)!==0&&(o.f^=Bo),o.v!==Cn&&Sb(o),o.ac!==null&&fm(()=>{o.ac.abort(Qu),o.ac=null,an(o,dn)}),q2(o),bu(o,0)}}function bu(e,t){var r=e.deps;if(r!==null)for(var n=t;n<r.length;n++)aN(e,r[n])}function Jc(e){var t=e.f;if((t&fi)===0){an(e,yn);var r=Ft,n=yh;Ft=e,yh=(t&(vo|Ts))===0;try{(t&(Go|pb))!==0?iN(e):Rb(e),BE(e);var i=KE(e);e.teardown=typeof i=="function"?i:null,e.wv=qE}finally{yh=n,Ft=r}}}function y(e){var t=(e.f&Jn)!==0;if(oN?.add(e),ir!==null&&!Ao&&!(Ft!==null&&(Ft.f&fi)!==0)&&(Fo===null||!Fo.has(e))){var r=ir.deps;if((ir.f&Qh)!==0)e.rv<dl&&(e.rv=dl,Ii===null&&r!==null&&r[ji]===e?ji++:Ii===null?Ii=[e]:Ii.push(e));else{var n;(n=ir).deps??(n.deps=[]),!ep.call(ir.deps,e)&&ir.deps.push(e);var i=e.reactions;i===null?e.reactions=[ir]:ep.call(i,ir)||i.push(ir)}}if(Us&&bs.has(e))return bs.get(e);if(t){var o=e;if(Us){var s=o.v;return((o.f&yn)===0&&o.reactions!==null||ZE(o))&&(s=kb(o)),bs.set(o,s),s}var a=(o.f&Bo)===0&&!Ao&&ir!==null&&(yh||(ir.f&Bo)!==0),l=(o.f&Ra)===0;tf(o)&&(a&&(o.f|=Bo),EE(o)),a&&!l&&(CE(o),XE(o))}if(li?.has(e))return li.get(e);if((e.f&wa)!==0)throw e.v;return e.v}function XE(e){if(e.f|=Bo,e.deps!==null)for(let t of e.deps)(t.reactions??(t.reactions=[])).push(e),(t.f&Jn)!==0&&(t.f&Bo)===0&&(CE(t),XE(t))}function ZE(e){if(e.v===Cn)return!0;if(e.deps===null)return!1;for(let t of e.deps)if(bs.has(t)||(t.f&Jn)!==0&&ZE(t))return!0;return!1}function Hr(e){var t=Ao;try{return Ao=!0,e()}finally{Ao=t}}function lN(e){if(!(typeof e!="object"||!e||e instanceof EventTarget)){if(wl in e)Tv(e);else if(!Array.isArray(e))for(let t in e){let r=e[t];typeof r=="object"&&r&&wl in r&&Tv(r)}}}function Tv(e,t=new Set){if(typeof e=="object"&&e!==null&&!(e instanceof EventTarget)&&!t.has(e)){t.add(e),e instanceof Date&&e.getTime();for(let n in e)try{Tv(e[n],t)}catch{}let r=bb(e);if(r!==Object.prototype&&r!==Array.prototype&&r!==Map.prototype&&r!==Set.prototype&&r!==Date.prototype){let n=yE(r);for(let i in n){let o=n[i].get;if(o)try{o.call(e)}catch{}}}}}function Ls(e){if(typeof e!="object"||e===null||wl in e||fE in e)return e;let t=bb(e);if(t!==I2&&t!==k2)return e;var r=new Map,n=vE(e),i=Sr(0),o=null,s=kl,a=l=>{if(kl===s)return l();var d=ir,c=kl;_i(null),X0(s);var u=l();return _i(d),X0(c),u};return n&&r.set("length",Sr(e.length,o)),new Proxy(e,{defineProperty(l,d,c){(!("value"in c)||c.configurable===!1||c.enumerable===!1||c.writable===!1)&&O2();var u=r.get(d);return u===void 0?a(()=>{var f=Sr(c.value,o);return r.set(d,f),f}):bt(u,c.value,!0),!0},deleteProperty(l,d){var c=r.get(d);if(c===void 0){if(d in l){let u=a(()=>Sr(Cn,o));r.set(d,u),eu(i)}}else bt(c,Cn),eu(i);return!0},get(l,d,c){if(d===wl)return e;var u=r.get(d),f=d in l;if(u===void 0&&(!f||Sl(l,d)?.writable)&&(u=a(()=>Sr(Ls(f?l[d]:Cn),o)),r.set(d,u)),u!==void 0){var p=y(u);return p===Cn?void 0:p}return Reflect.get(l,d,c)},getOwnPropertyDescriptor(l,d){this.has?.(l,d);var c=Reflect.getOwnPropertyDescriptor(l,d),u=r.get(d);if(u!==void 0){var f=y(u);if(f===Cn)return;if(c&&"value"in c)c.value=f;else return{enumerable:!0,configurable:!0,value:f,writable:!0}}return c},has(l,d){if(d===wl)return!0;var c=r.get(d),u=c!==void 0&&c.v!==Cn||Reflect.has(l,d);return(c!==void 0||Ft!==null&&(!u||Sl(l,d)?.writable))&&(c===void 0&&(c=a(()=>Sr(u?Ls(l[d]):Cn,o)),r.set(d,c)),y(c)===Cn)?!1:u},set(l,d,c,u){var f=r.get(d),p=d in l;if(n&&d==="length")for(var g=c;g<f.v;g+=1){var v=r.get(g+"");v!==void 0?bt(v,Cn):g in l&&(v=a(()=>Sr(Cn,o)),r.set(g+"",v))}if(f===void 0)(!p||Sl(l,d)?.writable)&&(f=a(()=>Sr(void 0,o)),bt(f,Ls(c)),r.set(d,f));else{p=f.v!==Cn;var b=a(()=>Ls(c));bt(f,b)}var w=Reflect.getOwnPropertyDescriptor(l,d);if(w?.set&&w.set.call(u,c),!p){if(n&&typeof d=="string"){var I=r.get("length"),x=Number(d);Number.isInteger(x)&&x>=I.v&&bt(I,x+1)}eu(i)}return!0},ownKeys(l){y(i);var d=Reflect.ownKeys(l).filter(f=>{var p=r.get(f);return p===void 0||p.v!==Cn});for(var[c,u]of r)u.v!==Cn&&!(c in l)&&d.push(c);return d},setPrototypeOf(){N2()}})}var Y0,YE,JE,QE;function Ev(){if(Y0===void 0){Y0=window,YE=/Firefox/.test(navigator.userAgent);var e=Element.prototype,t=Node.prototype,r=Text.prototype;JE=Sl(t,"firstChild").get,QE=Sl(t,"nextSibling").get,q0(e)&&(e[bv]=void 0,e[yv]=null,e[i2]=void 0,e.__e=void 0),q0(r)&&(r[gh]=void 0)}}function qi(e=""){return document.createTextNode(e)}function Hi(e){return JE.call(e)}function Yo(e){return QE.call(e)}function rl(e,t){if(!Zt)return Hi(e);var r=Hi(pr);if(r===null)r=pr.appendChild(qi());else if(t&&r.nodeType!==am){var n=qi();return r?.before(n),Yn(n),n}return t&&Pb(r),Yn(r),r}function vi(e,t=!1){if(!Zt){var r=Hi(e);return r instanceof Comment&&r.data===""?Yo(r):r}if(t){if(pr?.nodeType!==am){var n=qi();return pr?.before(n),Yn(n),n}Pb(pr)}return pr}function Zm(e,t=!1){if(!Zt)return Hi(e);var r=rl(e,t);return eo(e),r}function jc(e,t=1,r=!1){let n=Zt?pr:e;for(var i;t--;)i=n,n=Yo(n);if(!Zt)return n;if(r){if(n?.nodeType!==am){var o=qi();return n===null?i?.after(o):n.before(o),Yn(o),o}Pb(n)}return Yn(n),n}function eC(e){e.textContent=""}function tC(){return!_a||as!==null?!1:(Ft.f&Ra)!==0}function rf(e,t,r){return t==null||t===gE?r?document.createElement(e,{is:r}):document.createElement(e):r?document.createElementNS(t,e,{is:r}):document.createElementNS(t,e)}function Pb(e){if(e.nodeValue.length<65536)return;let t=e.nextSibling;for(;t!==null&&t.nodeType===am;)t.remove(),e.nodeValue+=t.nodeValue,t=e.nextSibling}var Zt=!1;function Mo(e){Zt=e}var pr;function Yn(e){if(e===null)throw ef(),Hl;return pr=e}function Ca(){return Yn(Yo(pr))}function eo(e){if(Zt){if(Yo(pr)!==null)throw ef(),Hl;pr=e}}function cN(e=1){if(Zt){for(var t=e,r=pr;t--;)r=Yo(r);pr=r}}function up(e=!0){for(var t=0,r=pr;;){if(r.nodeType===hd){var n=r.data;if(n===yb){if(t===0)return r;t-=1}else(n===mE||n===vb||n[0]==="["&&!isNaN(Number(n.slice(1))))&&(t+=1)}var i=Yo(r);e&&r.remove(),r=i}}function rC(e){if(!e||e.nodeType!==hd)throw ef(),Hl;return e.data}var $c=Symbol("events"),nC=new Set,Cv=new Set;function Mf(e,t,r){(t[$c]??(t[$c]={}))[e]=r}function dN(e){for(var t=0;t<e.length;t++)nC.add(e[t]);for(var r of Cv)r(e)}var Ym=null,Jm=!1;function J0(e){var t=this,r=t.ownerDocument,n=e.type,i=e.composedPath?.()||[],o=i[0]||e.target;Ym=e,!Jm&&(Jm=!0,setTimeout(()=>{Jm=!1,Ym=null}));var s=0,a=Ym===e&&e[$c];if(a){var l=i.indexOf(a);if(l!==-1&&(t===document||t===window)){e[$c]=t;return}var d=i.indexOf(t);if(d===-1)return;l<=d&&(s=l)}if(o=i[s]||e.target,o!==t){gu(e,"currentTarget",{configurable:!0,get(){return o||r}});var c=ir,u=Ft;_i(null),ho(null);try{for(var f,p=[];o!==null&&o!==t;){try{var g=o[$c]?.[n];g!=null&&(!o.disabled||e.target===o)&&g.call(o,e)}catch(v){f?p.push(v):f=v}if(e.cancelBubble)break;s++,o=s<i.length?i[s]:null}if(f){for(let v of p)queueMicrotask(()=>{throw v});throw f}}finally{e[$c]=t,delete e.currentTarget,_i(c),ho(u)}}}var uN=globalThis?.window?.trustedTypes&&globalThis.window.trustedTypes.createPolicy("svelte-trusted-html",{createHTML:e=>e});function fN(e){return uN?.createHTML(e)??e}function hN(e){var t=rf("template");return t.innerHTML=fN(e.replaceAll("<!>","<!---->")),t.content}function Bs(e,t){var r=Ft;r.nodes===null&&(r.nodes={start:e,end:t,a:null,t:null})}function Zi(e,t){var r=(t&m2)!==0,n=(t&g2)!==0,i,o=!e.startsWith("<!>");return()=>{if(Zt)return Bs(pr,null),pr;i===void 0&&(i=hN(o?e:"<!>"+e),!r&&(i=Hi(i)));var s=n||YE?document.importNode(i,!0):i.cloneNode(!0);if(r){var a=Hi(s),l=s.lastChild;Bs(a,l)}else Bs(s,s);return s}}function $i(){if(Zt)return Bs(pr,null),pr;var e=document.createDocumentFragment(),t=document.createComment(""),r=qi();return e.append(t,r),Bs(t,r),e}function Qt(e,t){if(Zt){var r=Ft;((r.f&Ra)===0||r.nodes.end===null)&&(r.nodes.end=pr),Ca();return}e!==null&&e.before(t)}var pN=["touchstart","touchmove"];function mN(e){return pN.includes(e)}function gN(e){let t=0,r=zl(0),n;return()=>{Cb()&&(y(r),hm(()=>(t===0&&(n=Hr(()=>e(()=>eu(r)))),t+=1,()=>{Ea(()=>{t-=1,t===0&&(n?.(),n=void 0,eu(r))})})))}}var vN=Kc|nc;function yN(e,t,r,n){new bN(e,t,r,n)}var Ho=new WeakMap,xv=new WeakMap,us=new WeakMap,wu=new WeakMap,zi=new WeakMap,zo=new WeakMap,Vi=new WeakMap,$o=new WeakMap,Sa=new WeakMap,Tc=new WeakMap,Tl=new WeakMap,$f=new WeakMap,Rv=new WeakMap,_v=new WeakMap,Fa=new WeakMap,Q0=new WeakMap,_n=new WeakSet,bN=class{constructor(e,t,r,n){ad(this,_n),T(this,"parent",void 0),T(this,"is_pending",!1),T(this,"transform_error",void 0),Le(this,Ho,void 0),Le(this,xv,Zt?pr:null),Le(this,us,void 0),Le(this,wu,void 0),Le(this,zi,void 0),Le(this,zo,null),Le(this,Vi,null),Le(this,$o,null),Le(this,Sa,null),Le(this,Tc,0),Le(this,Tl,0),Le(this,$f,!1),Le(this,Rv,new Set),Le(this,_v,new Set),Le(this,Fa,null),Le(this,Q0,gN(()=>(Ce(Fa,this,zl(S(Tc,this))),()=>{Ce(Fa,this,null)}))),Ce(Ho,this,e),Ce(us,this,t),Ce(wu,this,i=>{var o=Ft;o.b=this,o.f|=mb,r(i)}),this.parent=Ft.b,this.transform_error=n??this.parent?.transform_error??(i=>i),Ce(zi,this,pm(()=>{if(Zt){let i=S(xv,this);Ca();let o=i.data===vb;if(i.data.startsWith(U0)){let s=JSON.parse(i.data.slice(U0.length));je(_n,this,SN).call(this,s)}else o?je(_n,this,IN).call(this):je(_n,this,wN).call(this)}else je(_n,this,oC).call(this)},vN)),Zt&&Ce(Ho,this,pr)}defer_effect(e){PE(e,S(Rv,this),S(_v,this))}is_rendered(){return!this.is_pending&&(!this.parent||this.parent.is_rendered())}has_pending_snippet(){return!!S(us,this).pending}update_pending_count(e,t){je(_n,this,sC).call(this,e,t),Ce(Tc,this,S(Tc,this)+e),!(!S(Fa,this)||S($f,this))&&(Ce($f,this,!0),Ea(()=>{Ce($f,this,!1),S(Fa,this)&&Yc(S(Fa,this),S(Tc,this))}))}get_effect_pending(){return S(Q0,this).call(this),y(S(Fa,this))}error(e){if(!S(us,this).onerror&&!S(us,this).failed)throw e;qt?.is_fork?(S(zo,this)&&qt.skip_effect(S(zo,this)),S(Vi,this)&&qt.skip_effect(S(Vi,this)),S($o,this)&&qt.skip_effect(S($o,this)),qt.oncommit(()=>{je(_n,this,eS).call(this,e)})):je(_n,this,eS).call(this,e)}};function wN(){try{Ce(zo,this,fo(()=>S(wu,this).call(this,S(Ho,this))))}catch(e){this.error(e)}}function SN(e){let t=S(us,this).failed,{reset:r,invoke_onerror:n}=je(_n,this,iC).call(this,e);Ea(n),t&&Ce($o,this,fo(()=>{t(S(Ho,this),()=>e,()=>r)}))}function iC(e){var t=!1,r=!1;let n=()=>{if(t){w2();return}t=!0,r&&j2(),S($o,this)!==null&&oc(S($o,this),()=>{Ce($o,this,null)}),je(_n,this,Ab).call(this,()=>{je(_n,this,oC).call(this)})};return{reset:n,invoke_onerror:()=>{try{r=!0,S(us,this).onerror?.(e,n),r=!1}catch(i){ys(i,S(zi,this)&&S(zi,this).parent)}}}}function IN(){let e=S(us,this).pending;e&&(this.is_pending=!0,Ce(Vi,this,fo(()=>e(S(Ho,this)))),Ea(()=>{var t=Ce(Sa,this,document.createDocumentFragment()),r=qi(),n=!1;if(t.append(r),Ce(zo,this,je(_n,this,Ab).call(this,()=>{try{return fo(()=>S(wu,this).call(this,r))}catch(i){try{this.error(i),n=!0}catch(o){ys(o,S(zi,this).parent)}return null}})),S(zo,this)===null){Ce(Sa,this,null),n&&je(_n,this,fp).call(this,qt);return}S(Tl,this)===0&&(S(Ho,this).before(t),Ce(Sa,this,null),oc(S(Vi,this),()=>{Ce(Vi,this,null)}),je(_n,this,fp).call(this,qt))}))}function oC(){try{if(this.is_pending=this.has_pending_snippet(),Ce(Tl,this,0),Ce(Tc,this,0),Ce(zo,this,fo(()=>{S(wu,this).call(this,S(Ho,this))})),S(Tl,this)>0){var e=Ce(Sa,this,document.createDocumentFragment());_b(S(zo,this),e);let t=S(us,this).pending;Ce(Vi,this,fo(()=>t(S(Ho,this))))}else je(_n,this,fp).call(this,qt)}catch(t){this.error(t)}}function fp(e){this.is_pending=!1,e.transfer_effects(S(Rv,this),S(_v,this))}function Ab(e){var t=Ft,r=ir,n=bn;ho(S(zi,this)),_i(S(zi,this)),Zc(S(zi,this).ctx);try{return ic.ensure(),e()}finally{ho(t),_i(r),Zc(n)}}function sC(e,t){if(!this.has_pending_snippet()){var r;this.parent&&je(_n,r=this.parent,sC).call(r,e,t);return}Ce(Tl,this,S(Tl,this)+e),S(Tl,this)===0&&(je(_n,this,fp).call(this,t),S(Vi,this)&&oc(S(Vi,this),()=>{Ce(Vi,this,null)}),S(Sa,this)&&(S(Ho,this).before(S(Sa,this)),Ce(Sa,this,null)))}function eS(e){S(zo,this)&&(hi(S(zo,this)),Ce(zo,this,null)),S(Vi,this)&&(hi(S(Vi,this)),Ce(Vi,this,null)),S($o,this)&&(hi(S($o,this)),Ce($o,this,null)),Zt&&(Yn(S(xv,this)),cN(),Yn(up()));let t=S(us,this).failed,r=n=>{let{reset:i,invoke_onerror:o}=je(_n,this,iC).call(this,n);o(),t&&Ce($o,this,je(_n,this,Ab).call(this,()=>{try{return fo(()=>{var s=Ft;s.b=this,s.f|=mb,t(S(Ho,this),()=>n,()=>i)})}catch(s){return ys(s,S(zi,this).parent),null}}))};Ea(()=>{var n;try{n=this.transform_error(e)}catch(i){ys(i,S(zi,this)&&S(zi,this).parent);return}n!==null&&typeof n=="object"&&typeof n.then=="function"?n.then(r,i=>ys(i,S(zi,this)&&S(zi,this).parent)):r(n)})}function Qm(e,t){var r=t==null?"":typeof t=="object"?`${t}`:t;r!==(e[gh]??(e[gh]=e.nodeValue))&&(e[gh]=r,e.nodeValue=`${r}`)}function aC(e,t){return lC(e,t)}function kN(e,t){Ev(),t.intro=t.intro??!1;let r=t.target,n=Zt,i=pr;try{for(var o=Hi(r);o&&(o.nodeType!==hd||o.data!==mE);)o=Yo(o);if(!o)throw Hl;Mo(!0),Yn(o);let s=lC(e,{...t,anchor:o});return Mo(!1),s}catch(s){if(s instanceof Error&&s.message.split(`
4
+ `).some(a=>a.startsWith("https://svelte.dev/e/")))throw s;return s!==Hl&&console.warn("Failed to hydrate: ",s),t.recover===!1&&$2(),Ev(),eC(r),Mo(!1),aC(e,t)}finally{Mo(n),Yn(i)}}var Lf=new Map;function lC(e,{target:t,anchor:r,props:n={},events:i,context:o,intro:s=!0,transformError:a}){Ev();var l=void 0,d=rN(()=>{var c=r??t.appendChild(qi());yN(c,{pending:()=>{}},p=>{dm({});var g=bn;if(o&&(g.c=o),i&&(n.$$events=i),Zt&&Bs(p,null),l=e(p,n)||wb(),Zt&&(Ft.nodes.end=pr,pr===null||pr.nodeType!==hd||pr.data!==yb))throw ef(),Hl;um()},a);var u=new Set,f=p=>{for(var g=0;g<p.length;g++){var v=p[g];if(!u.has(v)){u.add(v);var b=mN(v);for(let x of[t,document]){var w=Lf.get(x);w===void 0&&(w=new Map,Lf.set(x,w));var I=w.get(v);I===void 0?(x.addEventListener(v,J0,{passive:b}),w.set(v,1)):w.set(v,I+1)}}}};return f(lm(nC)),Cv.add(f),()=>{for(var p of u)for(let b of[t,document]){var g=Lf.get(b),v=g.get(p);--v==0?(b.removeEventListener(p,J0),g.delete(p),g.size===0&&Lf.delete(b)):g.set(p,v)}Cv.delete(f),c!==r&&c.parentNode?.removeChild(c)}});return Pv.set(l,d),l}var Pv=new WeakMap;function TN(e,t){let r=Pv.get(e);return r?(Pv.delete(e),r(t)):Promise.resolve()}var Rs=new WeakMap,oa=new WeakMap,So=new WeakMap,Td=new WeakMap,eg=new WeakMap,tg=new WeakMap,tS=new WeakMap,cC=class{constructor(e,t=!0){T(this,"anchor",void 0),Le(this,Rs,new Map),Le(this,oa,new Map),Le(this,So,new Map),Le(this,Td,new Set),Le(this,eg,!0),Le(this,tg,r=>{if(S(Rs,this).has(r)){var n=S(Rs,this).get(r),i=S(oa,this).get(n);if(i)dp(i),S(Td,this).delete(n);else{var o=S(So,this).get(n);o&&(dp(o.effect),S(oa,this).set(n,o.effect),S(So,this).delete(n),o.fragment.lastChild.remove(),this.anchor.before(o.fragment),i=o.effect)}for(let[s,a]of S(Rs,this)){if(S(Rs,this).delete(s),s===r)break;let l=S(So,this).get(a);l&&(hi(l.effect),S(So,this).delete(a))}for(let[s,a]of S(oa,this)){if(s===n||S(Td,this).has(s))continue;let l=()=>{if(Array.from(S(Rs,this).values()).includes(s)){var d=document.createDocumentFragment();_b(a,d),d.append(qi()),S(So,this).set(s,{effect:a,fragment:d})}else hi(a);S(Td,this).delete(s),S(oa,this).delete(s)};S(eg,this)||!i?(S(Td,this).add(s),oc(a,l,!1)):l()}}}),Le(this,tS,r=>{S(Rs,this).delete(r);let n=Array.from(S(Rs,this).values());for(let[i,o]of S(So,this))n.includes(i)||(hi(o.effect),S(So,this).delete(i))}),this.anchor=e,Ce(eg,this,t)}ensure(e,t){var r=qt,n=tC();if(t&&!S(oa,this).has(e)&&!S(So,this).has(e))if(n){var i=document.createDocumentFragment(),o=qi();i.append(o),S(So,this).set(e,{effect:fo(()=>t(o)),fragment:i})}else S(oa,this).set(e,fo(()=>t(this.anchor)));if(S(Rs,this).set(r,e),n){for(let[s,a]of S(oa,this))s===e?r.unskip_effect(a):r.skip_effect(a);for(let[s,a]of S(So,this))s===e?r.unskip_effect(a.effect):r.skip_effect(a.effect);r.oncommit(S(tg,this)),r.ondiscard(S(tS,this))}else Zt&&(this.anchor=pr),S(tg,this).call(this,r)}};function Li(e,t,r=!1){var n;Zt&&(n=pr,Ca());var i=new cC(e),o=r?Kc:0;function s(a,l){if(Zt){var d=rC(n);if(a!==parseInt(d.substring(1))){var c=up();Yn(c),i.anchor=c,Mo(!1),i.ensure(a,l),Mo(!0);return}}i.ensure(a,l)}pm(()=>{var a=!1;t((l,d=0)=>{a=!0,s(d,l)}),!a&&s(-1,null)},o)}var EN=Symbol("NaN");function rg(e,t,r){Zt&&Ca();var n=new cC(e),i=!pd();pm(()=>{var o=t();o!==o&&(o=EN),i&&o!==null&&typeof o=="object"&&(o={}),n.ensure(o,r)})}function CN(e,t,r){for(var n=[],i=t.length,o,s=t.length,a=0;a<i;a++){let u=t[a];oc(u,()=>{if(o){if(o.pending.delete(u),o.done.add(u),o.pending.size===0){var f=e.outrogroups;Av(e,lm(o.done)),f.delete(o),f.size===0&&(e.outrogroups=null)}}else s-=1},!1)}if(s===0){var l=n.length===0&&r!==null&&e.pending.size===0;if(l){var d=r,c=d.parentNode;eC(c),c.append(d),e.items.clear()}Av(e,t,!l)}else o={pending:new Set(t),done:new Set},(e.outrogroups??(e.outrogroups=new Set)).add(o)}function Av(e,t,r=!0){var n;if(e.pending.size>0){n=new Set;for(let s of e.pending.values())for(let a of s)n.add(e.items.get(a).e)}for(var i=0;i<t.length;i++){var o=t[i];n?.has(o)?(o.f|=ps,_b(o,document.createDocumentFragment())):hi(t[i],r)}}var Of;function Nf(e,t,r,n,i,o=null){var s=e,a=new Map;if((t&pE)!==0){var l=e;s=Zt?Yn(Hi(l)):l.appendChild(qi())}Zt&&Ca();var d=null,c=Ib(()=>{var w=r();return vE(w)?w:w==null?[]:lm(w)}),u,f=new Map,p=!0;function g(w){(b.effect.f&fi)===0&&(b.pending.delete(w),b.fallback=d,xN(b,u,s,t,n),d!==null&&(u.length===0?(d.f&ps)===0?dp(d):(d.f^=ps,qd(d,null,s)):oc(d,()=>{d=null})))}function v(w){b.pending.delete(w)}var b={effect:pm(()=>{u=y(c);var w=u.length;let I=!1;Zt&&rC(s)===vb!=(w===0)&&(s=up(),Yn(s),Mo(!1),I=!0);for(var x=new Set,C=qt,L=tC(),E=0;E<w;E+=1){Zt&&pr.nodeType===hd&&pr.data===yb&&(s=pr,I=!0,Mo(!1));var M=u[E],U=n(M,E),te=p?null:a.get(U);te?(te.v&&Yc(te.v,M),te.i&&Yc(te.i,E),L&&C.unskip_effect(te.e)):(te=RN(a,p?s:Of??(Of=qi()),M,U,E,i,t,r),!p&&(te.e.f|=ps),a.set(U,te)),x.add(U)}if(w===0&&o&&!d&&(p?d=fo(()=>o(s)):(d=fo(()=>o(Of??(Of=qi()))),d.f|=ps)),w>x.size&&R2("","",""),Zt&&w>0&&Yn(up()),!p)if(f.set(C,x),L){for(let[re,Pe]of a)x.has(re)||C.skip_effect(Pe.e);C.oncommit(g),C.ondiscard(v)}else g(C);I&&Mo(!0),y(c)}),flags:t,items:a,pending:f,outrogroups:null,fallback:d};p=!1,Zt&&(s=pr)}function Ed(e){for(;e!==null&&(e.f&vo)===0;)e=e.next;return e}function xN(e,t,r,n,i){var o=(n&l2)!==0,s=t.length,a=e.items,l=Ed(e.effect.first),d,c=null,u,f=[],p=[],g,v,b,w;if(o)for(w=0;w<s;w+=1)g=t[w],v=i(g,w),b=a.get(v).e,(b.f&ps)===0&&(b.nodes?.a?.measure(),(u??(u=new Set)).add(b));for(w=0;w<s;w+=1){if(g=t[w],v=i(g,w),b=a.get(v).e,e.outrogroups!==null)for(let re of e.outrogroups)re.pending.delete(b),re.done.delete(b);if((b.f&ui)!==0&&(dp(b),o&&(b.nodes?.a?.unfix(),(u??(u=new Set)).delete(b))),(b.f&ps)!==0)if(b.f^=ps,b===l)qd(b,null,r);else{var I=c?c.next:l;b===e.effect.last&&(e.effect.last=b.prev),b.prev&&(b.prev.next=b.next),b.next&&(b.next.prev=b.prev),sa(e,c,b),sa(e,b,I),qd(b,I,r),c=b,f=[],p=[],l=Ed(c.next);continue}if(b!==l){if(d!==void 0&&d.has(b)){if(f.length<p.length){var x=p[0],C;c=x.prev;var L=f[0],E=f[f.length-1];for(C=0;C<f.length;C+=1)qd(f[C],x,r);for(C=0;C<p.length;C+=1)d.delete(p[C]);sa(e,L.prev,E.next),sa(e,c,L),sa(e,E,x),l=x,c=E,w-=1,f=[],p=[]}else d.delete(b),qd(b,l,r),sa(e,b.prev,b.next),sa(e,b,c===null?e.effect.first:c.next),sa(e,c,b),c=b;continue}for(f=[],p=[];l!==null&&l!==b;)(d??(d=new Set)).add(l),p.push(l),l=Ed(l.next);if(l===null)continue}(b.f&ps)===0&&f.push(b),c=b,l=Ed(b.next)}if(e.outrogroups!==null){for(let re of e.outrogroups)re.pending.size===0&&(Av(e,lm(re.done)),e.outrogroups?.delete(re));e.outrogroups.size===0&&(e.outrogroups=null)}if(l!==null||d!==void 0){var M=[];if(d!==void 0)for(b of d)(b.f&ui)===0&&M.push(b);for(;l!==null;)(l.f&ui)===0&&l!==e.fallback&&M.push(l),l=Ed(l.next);var U=M.length;if(U>0){var te=(n&pE)!==0&&s===0?r:null;if(o){for(w=0;w<U;w+=1)M[w].nodes?.a?.measure();for(w=0;w<U;w+=1)M[w].nodes?.a?.fix()}CN(e,M,te)}}o&&Ea(()=>{if(u!==void 0)for(b of u)b.nodes?.a?.apply()})}function RN(e,t,r,n,i,o,s,a){var l=(s&s2)!==0?(s&c2)===0?RE(r,!1,!1):zl(r):null,d=(s&a2)!==0?zl(i):null;return{v:l,i:d,e:fo(()=>(o(t,l??r,d??i,a),()=>{e.delete(n)}))}}function qd(e,t,r){if(e.nodes)for(var n=e.nodes.start,i=e.nodes.end,o=t&&(t.f&ps)===0?t.nodes.start:r;n!==null;){var s=Yo(n);if(o.before(n),n===i)return;n=s}}function sa(e,t,r){t===null?e.effect.first=r:t.next=r,r===null?e.effect.last=t:r.prev=t}function Df(e,t,r=!1,n=!1,i=!1,o=!1){var s=e,a="";if(r){var l=e;Zt&&(s=Yn(Hi(l)))}en(()=>{var d=Ft;if(a===(a=t()??"")){Zt&&Ca();return}if(r&&!Zt){d.nodes=null,l.innerHTML=a,a!==""&&Bs(Hi(l),l.lastChild);return}if(d.nodes!==null&&(FE(d.nodes.start,d.nodes.end),d.nodes=null),a!==""){if(Zt){pr.data;for(var c=Ca(),u=c;c!==null&&(c.nodeType!==hd||c.data!=="");)u=c,c=Yo(c);if(c===null)throw ef(),Hl;Bs(pr,u),s=Yn(c);return}var f=rf(n?"svg":i?"math":"template",n?v2:i?y2:void 0);f.innerHTML=a;var p=n||i?f:f.content;if(Bs(Hi(p),p.lastChild),n||i)for(;Hi(p);)s.before(Hi(p));else s.before(p)}})}function _N(e,t,r,n,i){if(Zt&&Ca(),t.$$host?.$$shadowRoot){let a=rf("slot");if(r!=="default"&&(a.name=r),Qt(e,a),i!==null){let l=qi();a.append(l),i(l)}return}var o=t.$$slots?.[r],s=!1;o===!0&&(o=t[r==="default"?"children":r],s=!0),o===void 0?i!==null&&i(e):o(e,s?()=>n:n)}function dC(e,t){xb(()=>{e=Ft?.parent?.nodes?.start??e;var r=e.getRootNode(),n=r.host?r:r.head??r.ownerDocument.head;if(!n.querySelector("#"+t.hash)){let i=rf("style");i.id=t.hash,i.textContent=t.code,n.appendChild(i)}})}function aa(e,t,r){xb(()=>{var n=Hr(()=>t(e,r?.())||{});if(r&&n?.update){var i=!1,o={};hm(()=>{var s=r();lN(s),i&&IE(o,s)&&(o=s,n.update(s))}),i=!0}if(n?.destroy)return()=>n.destroy()})}var rS=[...`
5
+ \r\f \v\uFEFF`];function PN(e,t,r){var n=e==null?"":""+e;if(t&&(n=n?n+" "+t:t),r){for(var i of Object.keys(r))if(r[i])n=n?n+" "+i:i;else if(n.length)for(var o=i.length,s=0;(s=n.indexOf(i,s))>=0;){var a=s+o;(s===0||rS.includes(n[s-1]))&&(a===n.length||rS.includes(n[a]))?n=(s===0?"":n.substring(0,s))+n.substring(a+1):s=a}}return n===""?null:n}function Ha(e,t,r,n,i,o){var s=e[bv];if(Zt||s!==r||s===void 0){var a=PN(r,n,o);(!Zt||a!==e.getAttribute("class"))&&(a==null?e.removeAttribute("class"):t?e.className=a:e.setAttribute("class",a)),e[bv]=r}else if(o&&i!==o)for(var l in o){var d=!!o[l];(i==null||d!==!!i[l])&&e.classList.toggle(l,d)}return o}var AN=Symbol("is custom element"),MN=Symbol("is html"),$N=o2?"link":"LINK";function gi(e,t,r,n){var i=LN(e);Zt&&(i[t]=e.getAttribute(t),t==="src"||t==="srcset"||t==="href"&&e.nodeName===$N)||i[t]!==(i[t]=r)&&(t==="loading"&&(e[n2]=r),r==null?e.removeAttribute(t):typeof r!="string"&&uC(e).has(t)?e[t]=r:e.setAttribute(t,r))}function Dn(e,t,r){var n=ir,i=Ft;let o=Zt;Zt&&Mo(!1),_i(null),ho(null);try{t!=="style"&&(Mv.has(e.getAttribute("is")||e.nodeName)||!customElements||customElements.get(e.getAttribute("is")||e.nodeName.toLowerCase())?uC(e).has(t):r&&typeof r=="object")?e[t]=r:gi(e,t,r==null?r:String(r))}finally{_i(n),ho(i),o&&Mo(!0)}}function LN(e){return e[yv]??(e[yv]={[AN]:e.nodeName.includes("-"),[MN]:e.namespaceURI===gE})}var Mv=new Map;function uC(e){var t=e.getAttribute("is")||e.nodeName,r=Mv.get(t);if(r)return r;Mv.set(t,r=new Set);for(var n,i=e,o=Element.prototype;o!==i;){n=yE(i);for(var s in n)n[s].set&&s!=="innerHTML"&&s!=="textContent"&&s!=="innerText"&&r.add(s);i=bb(i)}return r}var Ec=new WeakMap,hp=new WeakMap,ng=new WeakMap,nS=new WeakSet,fC=class{constructor(e){ad(this,nS),Le(this,Ec,new WeakMap),Le(this,hp,void 0),Le(this,ng,void 0),Ce(ng,this,e)}observe(e,t){var r=S(Ec,this).get(e)||new Set;return r.add(t),S(Ec,this).set(e,r),je(nS,this,ON).call(this).observe(e,S(ng,this)),()=>{var n=S(Ec,this).get(e);n.delete(t),n.size===0&&(S(Ec,this).delete(e),S(hp,this).unobserve(e))}}};uE=fC;function ON(){return S(hp,this)??Ce(hp,this,new ResizeObserver(e=>{for(var t of e){uE.entries.set(t.target,t);for(var r of S(Ec,this).get(t.target)||[])r(t)}}))}T(fC,"entries",new WeakMap);function ig(e,t){return e===t||e?.[wl]===t}function hC(e=wb(),t,r,n){var i=bn.r,o=Ft;return xb(()=>{var s,a;return hm(()=>{s=a,a=n?.()||[],Hr(()=>{ig(r(...a),e)||(t(e,...a),s&&ig(r(...s),e)&&t(null,...s))})}),()=>{let l=o;for(;l!==i&&l.parent!==null&&l.parent.f&Yh;)l=l.parent;let d=()=>{a&&ig(r(...a),e)&&t(null,...a)},c=l.teardown;l.teardown=()=>{d(),c?.()}}}),e}var jf=!1;function NN(e){var t=jf;try{return jf=!1,[e(),jf]}finally{jf=t}}function wt(e,t,r,n){var i=!cm||(r&u2)!==0,o=(r&h2)!==0,s=(r&p2)!==0,a=n,l=!0,d=void 0,c=()=>s&&i?(d??(d=vu(n)),y(d)):(l&&(l=!1,a=s?Hr(n):n),a);let u;if(o){var f=wl in e||hE in e;u=Sl(e,t)?.set??(f&&t in e?C=>e[t]=C:void 0)}var p,g=!1;o?[p,g]=NN(()=>e[t]):p=e[t],p===void 0&&n!==void 0&&(p=c(),u&&(i&&L2(t),u(p)));var v;if(i?v=()=>{var C=e[t];return C===void 0?c():(l=!0,C)}:v=()=>{var C=e[t];return C!==void 0&&(a=void 0),C===void 0?a:C},i&&(r&f2)===0)return v;if(u){var b=e.$$legacy;return function(C,L){return arguments.length>0?((!i||!L||b||g)&&u(L?v():C),C):v()}}var w=!1,I=((r&d2)!==0?vu:Ib)(()=>(w=!1,v()));o&&y(I);var x=Ft;return function(C,L){if(arguments.length>0){let E=L?y(I):i&&o?Ls(C):C;return bt(I,E),w=!0,a!==void 0&&(a=E),C}return Us&&w||(x.f&fi)!==0?I.v:y(I)}}function DN(e){return new jN(e)}var za=new WeakMap,ts=new WeakMap,jN=class{constructor(e){Le(this,za,void 0),Le(this,ts,void 0);var t=new Map,r=(i,o)=>{var s=RE(o,!1,!1);return t.set(i,s),s};let n=new Proxy({...e.props||{},$$events:{}},{get(i,o){return y(t.get(o)??r(o,Reflect.get(i,o)))},has(i,o){return o===hE?!0:(y(t.get(o)??r(o,Reflect.get(i,o))),Reflect.has(i,o))},set(i,o,s){return bt(t.get(o)??r(o,s),s),Reflect.set(i,o,s)}});Ce(ts,this,(e.hydrate?kN:aC)(e.component,{target:e.target,anchor:e.anchor,props:n,context:e.context,intro:e.intro??!1,recover:e.recover,transformError:e.transformError})),!_a&&(!e?.props?.$$host||e.sync===!1)&&gt(),Ce(za,this,n.$$events);for(let i of Object.keys(S(ts,this)))i==="$set"||i==="$destroy"||i==="$on"||gu(this,i,{get(){return S(ts,this)[i]},set(o){S(ts,this)[i]=o},enumerable:!0});S(ts,this).$set=i=>{Object.assign(n,i)},S(ts,this).$destroy=()=>{TN(S(ts,this))}}$set(e){S(ts,this).$set(e)}$on(e,t){S(za,this)[e]=S(za,this)[e]||[];let r=(...n)=>t.call(this,...n);return S(za,this)[e].push(r),()=>{S(za,this)[e]=S(za,this)[e].filter(n=>n!==r)}}$destroy(){S(ts,this).$destroy()}},pC;typeof HTMLElement=="function"&&(pC=class extends HTMLElement{constructor(e,t,r){super(),T(this,"$$ctor",void 0),T(this,"$$s",void 0),T(this,"$$c",void 0),T(this,"$$cn",!1),T(this,"$$d",{}),T(this,"$$r",!1),T(this,"$$p_d",{}),T(this,"$$l",{}),T(this,"$$l_u",new Map),T(this,"$$me",void 0),T(this,"$$shadowRoot",null),this.$$ctor=e,this.$$s=t,r&&(this.$$shadowRoot=this.attachShadow(r))}addEventListener(e,t,r){if(this.$$l[e]=this.$$l[e]||[],this.$$l[e].push(t),this.$$c){let n=this.$$c.$on(e,t);this.$$l_u.set(t,n)}super.addEventListener(e,t,r)}removeEventListener(e,t,r){if(super.removeEventListener(e,t,r),this.$$c){let n=this.$$l_u.get(t);n&&(n(),this.$$l_u.delete(t))}}async connectedCallback(){if(this.$$cn=!0,!this.$$c){let e=function(n){return i=>{let o=rf("slot");n!=="default"&&(o.name=n),Qt(i,o)}};if(await Promise.resolve(),!this.$$cn||this.$$c)return;let t={},r=BN(this);for(let n of this.$$s)n in r&&(n==="default"&&!this.$$d.children?(this.$$d.children=e(n),t.default=!0):t[n]=e(n));for(let n of this.attributes){let i=this.$$g_p(n.name);i in this.$$d||(this.$$d[i]=bh(i,n.value,this.$$p_d,"toProp"))}for(let n in this.$$p_d)!(n in this.$$d)&&this[n]!==void 0&&(this.$$d[n]=this[n],delete this[n]);this.$$c=DN({component:this.$$ctor,target:this.$$shadowRoot||this,props:{...this.$$d,$$slots:t,$$host:this}}),this.$$me=tN(()=>{hm(()=>{this.$$r=!0;for(let n of tp(this.$$c)){if(!this.$$p_d[n]?.reflect)continue;this.$$d[n]=this.$$c[n];let i=bh(n,this.$$d[n],this.$$p_d,"toAttribute");i==null?this.removeAttribute(this.$$p_d[n].attribute||n):this.setAttribute(this.$$p_d[n].attribute||n,i)}this.$$r=!1})});for(let n in this.$$l)for(let i of this.$$l[n]){let o=this.$$c.$on(n,i);this.$$l_u.set(i,o)}this.$$l={}}}attributeChangedCallback(e,t,r){this.$$r||(e=this.$$g_p(e),this.$$d[e]=bh(e,r,this.$$p_d,"toProp"),this.$$c?.$set({[e]:this.$$d[e]}))}disconnectedCallback(){this.$$cn=!1,Promise.resolve().then(()=>{!this.$$cn&&this.$$c&&(this.$$c.$destroy(),this.$$me(),this.$$c=void 0)})}$$g_p(e){return tp(this.$$p_d).find(t=>this.$$p_d[t].attribute===e||!this.$$p_d[t].attribute&&t.toLowerCase()===e)||e}});function bh(e,t,r,n){let i=r[e]?.type;if(t=i==="Boolean"&&typeof t!="boolean"?t!=null:t,!n||!r[e])return t;if(n==="toAttribute")switch(i){case"Object":case"Array":return t==null?null:JSON.stringify(t);case"Boolean":return t?"":null;case"Number":return t??null;default:return t}else switch(i){case"Object":case"Array":return t&&JSON.parse(t);case"Boolean":return t;case"Number":return t!=null?+t:t;default:return t}}function BN(e){let t={};return e.childNodes.forEach(r=>{t[r.slot||"default"]=!0}),t}function Mb(e,t,r,n,i,o){let s=class extends pC{constructor(){super(e,r,i),this.$$p_d=t}static get observedAttributes(){return tp(t).map(a=>(t[a].attribute||a).toLowerCase())}};return tp(t).forEach(a=>{gu(s.prototype,a,{get(){return this.$$c&&a in this.$$c?this.$$c[a]:this.$$d[a]},set(l){l=bh(a,l,t),this.$$d[a]=l;var d=this.$$c;d&&(Sl(d,a)?.get?d[a]=l:d.$set({[a]:l}))}})}),n.forEach(a=>{gu(s.prototype,a,{get(){return this.$$c?.[a]}})}),o&&(s=o(s)),e.element=s,s}var $b=Zl(Symbol.for("pie.assessmentToolkit.runtimeContext")),$v=Zl(Symbol.for("pie.assessmentToolkit.hostRuntimeContext")),FN=Zl(Symbol.for("pie.assessmentToolkit.shellContext"));Zl(Symbol.for("pie.assessmentToolkit.regionScopeContext"));function HN(e,t){return $u(e,$b,t)}function zN(e,t){return $u(e,$v,t)}function WN(e,t){return $u(e,FN,t)}var og={assessment:[],section:[],item:[],passage:[],rubric:[],element:[]},sg={section:[...og.section],item:[...og.item],passage:[...og.passage]};function El(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function la(e,t){if(e==null)return[];if(!Array.isArray(e))throw Error(`Invalid tools config at "${t}": expected an array of tool ids.`);if(e.find(r=>typeof r!="string")!==void 0)throw Error(`Invalid tools config at "${t}": all entries must be strings.`);return e}function UN(e){if(e!=null){if(!El(e))throw Error('Invalid tools config at "placement": expected an object with section/item/passage arrays.');return e}}function qN(e){if(e!=null){if(!El(e))throw Error('Invalid tools config at "policy": expected an object with allowed/blocked arrays.');return e}}function VN(e,t){if(t==null)return;if(!El(t))throw Error(`Invalid tools config at "providers.${e}": expected an object.`);let r=t,n=i=>i==="polly"||i==="google"||i==="custom";if("enabled"in r&&r.enabled!==void 0&&typeof r.enabled!="boolean")throw Error(`Invalid tools config at "providers.${e}.enabled": expected a boolean.`);if("settings"in r&&r.settings!==void 0&&!El(r.settings))throw Error(`Invalid tools config at "providers.${e}.settings": expected an object.`);if("provider"in r&&r.provider!==void 0&&!El(r.provider)&&!(e==="textToSpeech"&&n(r.provider)))throw Error(`Invalid tools config at "providers.${e}.provider": expected an object.`);return r}function GN(e){if(e==null)return{};if(!El(e))throw Error('Invalid tools config at "providers": expected an object keyed by tool id.');let t={};for(let[r,n]of Object.entries(e))t[r]=VN(r,n);return t}function mC(e){let t=e.trim();return t||""}function bi(e){if(!e||e.length===0)return[];let t=new Set;for(let r of e){if(typeof r!="string")throw Error("Invalid tools config: tool list entries must be strings.");let n=mC(r);n&&t.add(n)}return Array.from(t)}function gC(e){return e?bi(e.split(",").map(t=>t.trim()).filter(Boolean)):[]}function KN(e,t){if(e!=null){if(e==="on"||e==="off")return e;throw Error(`Invalid tools config at "${t}": expected "on" or "off", got ${JSON.stringify(e)}.`)}}function Lb(e){if(e!=null&&!El(e))throw Error('Invalid tools config: expected an object with "policy", "placement", and "providers".');let t=qN(e?.policy),r=UN(e?.placement),n=GN(e?.providers),i=KN(e?.pnpEnforcement,"pnpEnforcement"),o={policy:{allowed:bi(la(t?.allowed,"policy.allowed")),blocked:bi(la(t?.blocked,"policy.blocked"))},placement:{section:bi(la(r?.section,"placement.section")).length?bi(la(r?.section,"placement.section")):[...sg.section],item:bi(la(r?.item,"placement.item")).length?bi(la(r?.item,"placement.item")):[...sg.item],passage:bi(la(r?.passage,"placement.passage")).length?bi(la(r?.passage,"placement.passage")):[...sg.passage]},providers:n};return i&&(o.pnpEnforcement=i),o}function iS(e,t){let r=e.provider;return r?r.getProviderId?.(t)??t?.provider?.id??e.toolId:null}var XN=["assessment","section","item","passage","rubric","element"];function wh(e,t){if(typeof e!="string"||e.trim().length===0)throw Error(`Invalid tool registration: "${t}" must be a non-empty string.`)}var ZN=[{pattern:/<script\b/i,reason:"contains a <script> tag"},{pattern:/\son[a-z]+\s*=/i,reason:"contains an inline event handler (on*=) attribute"},{pattern:/javascript:/i,reason:"contains a javascript: URL"},{pattern:/<foreignObject\b/i,reason:"contains a <foreignObject> element"}];function YN(e,t,r){let n=t.trimStart(),i=n.toLowerCase().startsWith("<svg"),o=/^https?:/i.test(n);if(/^data:/i.test(n))throw Error(`Invalid tool registration "${e}": "${r}" may not be a data: URL.`);if(!(!i&&!o)){for(let{pattern:s,reason:a}of ZN)if(s.test(t))throw Error(`Invalid tool registration "${e}": "${r}" ${a}. Inline SVG icons must not include scriptable content.`)}}function oS(e){wh(e.toolId,"toolId"),wh(e.name,"name"),wh(e.description,"description");let t=e.activation==="region";if((!t||e.icon!==void 0)&&typeof e.icon!="string"&&typeof e.icon!="function")throw Error(`Invalid tool registration "${e.toolId}": "icon" must be a string or function.`);if(typeof e.icon=="string"&&YN(e.toolId,e.icon,"icon"),!Array.isArray(e.supportedLevels)||e.supportedLevels.length===0)throw Error(`Invalid tool registration "${e.toolId}": "supportedLevels" must be a non-empty array.`);let r=e.supportedLevels.find(n=>!XN.includes(n));if(r)throw Error(`Invalid tool registration "${e.toolId}": unsupported level "${r}".`);if(e.activation!==void 0&&e.activation!=="toolbar-toggle"&&e.activation!=="selection-gateway"&&e.activation!=="region")throw Error(`Invalid tool registration "${e.toolId}": unsupported activation "${String(e.activation)}".`);if(e.surfaces!==void 0&&(!Array.isArray(e.surfaces)||e.surfaces.some(n=>typeof n!="string"||n.trim().length===0)))throw Error(`Invalid tool registration "${e.toolId}": "surfaces" must be an array of non-empty strings.`);if(t&&!e.surfaces?.length)throw Error(`Invalid tool registration "${e.toolId}": region tools must declare at least one host surface in "surfaces".`);if(t&&typeof e.renderSurface!="function")throw Error(`Invalid tool registration "${e.toolId}": region tools must implement "renderSurface".`);if(e.resolvesWithoutGrant!==void 0&&typeof e.resolvesWithoutGrant!="boolean")throw Error(`Invalid tool registration "${e.toolId}": "resolvesWithoutGrant" must be a boolean.`);if(e.resolvesWithoutGrant&&!e.requiresAuthoredContent)throw Error(`Invalid tool registration "${e.toolId}": "resolvesWithoutGrant" requires "requiresAuthoredContent".`);if(e.renderSurface!==void 0&&typeof e.renderSurface!="function")throw Error(`Invalid tool registration "${e.toolId}": "renderSurface" must be a function.`);if(e.renderSurface&&!e.surfaces?.length)throw Error(`Invalid tool registration "${e.toolId}": "renderSurface" requires at least one entry in "surfaces".`);if(e.singletonScope!==void 0&&e.singletonScope!=="section")throw Error(`Invalid tool registration "${e.toolId}": unsupported singletonScope "${String(e.singletonScope)}".`);if(e.activation==="selection-gateway"&&e.singletonScope!=="section")throw Error(`Invalid tool registration "${e.toolId}": selection-gateway tools must declare singletonScope "section".`);if(e.pnpSupportIds!==void 0&&(!Array.isArray(e.pnpSupportIds)||e.pnpSupportIds.some(n=>typeof n!="string"||n.trim().length===0)))throw Error(`Invalid tool registration "${e.toolId}": "pnpSupportIds" must be an array of non-empty strings.`);if(e.activation!=="region"&&typeof e.isVisibleInContext!="function")throw Error(`Invalid tool registration "${e.toolId}": "isVisibleInContext" must be a function.`);if(e.isVisibleInContext!==void 0&&typeof e.isVisibleInContext!="function")throw Error(`Invalid tool registration "${e.toolId}": "isVisibleInContext" must be a function when present.`);if(e.isApplicableToContent!==void 0&&typeof e.isApplicableToContent!="function")throw Error(`Invalid tool registration "${e.toolId}": "isApplicableToContent" must be a function when present.`);if(e.requiresAuthoredContent!==void 0){if(typeof e.requiresAuthoredContent!="object"||e.requiresAuthoredContent===null||typeof e.requiresAuthoredContent.resolve!="function")throw Error(`Invalid tool registration "${e.toolId}": "requiresAuthoredContent" must be an object with a "resolve" function.`);if(!e.pnpSupportIds?.length)throw Error(`Invalid tool registration "${e.toolId}": "requiresAuthoredContent" requires at least one entry in "pnpSupportIds", which is what a host filters a default grant list on.`)}if(e.renderToolbar!==void 0){if(typeof e.renderToolbar!="function")throw Error(`Invalid tool registration "${e.toolId}": "renderToolbar" must be a function.`)}else if(!t)throw Error(`Invalid tool registration "${e.toolId}": "renderToolbar" must be a function.`)}var Lv=class{constructor(){T(this,"tools",new Map),T(this,"pnpIndex",new Map),T(this,"componentOverrides",{}),T(this,"moduleLoaders",new Map),T(this,"loadedToolModules",new Set),T(this,"moduleLoadPromises",new Map),T(this,"changeListeners",new Set)}emitChange(e){for(let t of this.changeListeners)try{t(e)}catch(r){console.warn("[ToolRegistry] change listener failed:",r)}}onRegistryChange(e){this.changeListeners.add(e);let t=!0;return()=>{t&&(t=!1,this.changeListeners.delete(e))}}normalizeToolId(e){return mC(e)}normalizeToolIds(e){return e.map(t=>this.normalizeToolId(t))}register(e){if(oS(e),this.tools.has(e.toolId))throw Error(`Tool '${e.toolId}' is already registered`);if(this.tools.set(e.toolId,e),e.pnpSupportIds)for(let t of e.pnpSupportIds)this.pnpIndex.has(t)||this.pnpIndex.set(t,new Set),this.pnpIndex.get(t).add(e.toolId);this.emitChange({kind:"register",toolIds:[e.toolId]})}override(e){if(oS(e),!this.tools.has(e.toolId))throw Error(`Cannot override non-existent tool '${e.toolId}'`);let t=this.tools.get(e.toolId);if(t.pnpSupportIds)for(let r of t.pnpSupportIds)this.pnpIndex.get(r)?.delete(e.toolId);if(this.tools.set(e.toolId,e),e.pnpSupportIds)for(let r of e.pnpSupportIds)this.pnpIndex.has(r)||this.pnpIndex.set(r,new Set),this.pnpIndex.get(r).add(e.toolId);this.emitChange({kind:"override",toolIds:[e.toolId]})}unregister(e){let t=this.tools.get(e);if(t){if(t.pnpSupportIds)for(let r of t.pnpSupportIds)this.pnpIndex.get(r)?.delete(e);this.tools.delete(e),this.emitChange({kind:"unregister",toolIds:[e]})}}get(e){return this.tools.get(e)}has(e){return this.tools.has(e)}getAllToolIds(){return Array.from(this.tools.keys())}getAllTools(){return Array.from(this.tools.values())}getToolsByPNPSupport(e){return this.pnpIndex.get(e)||new Set}getToolsByLevel(e){return this.getAllTools().filter(t=>t.supportedLevels.includes(e))}getToolActivation(e){return this.get(e)?.activation||"toolbar-toggle"}getToolSingletonScope(e){return this.get(e)?.singletonScope||null}getToolsBySurface(e){return e?this.getAllTools().filter(t=>typeof t.renderSurface=="function"&&t.surfaces?.includes(e)):[]}getContentDependentSupportIds(){let e=new Set;for(let t of this.getAllTools())if(t.requiresAuthoredContent)for(let r of t.pnpSupportIds||[])e.add(r);return[...e].sort()}filterToolIdsByActivation(e,t){return e.filter(r=>this.getToolActivation(r)===t)}filterVisibleInContext(e,t){let r=[];for(let n of e){let i=this.get(n);if(!i){console.warn(`Tool '${n}' is allowed but not registered`);continue}if(i.supportedLevels.includes(t.level))try{i.isVisibleInContext?.(t)&&r.push(i)}catch(o){console.error(`Error evaluating visibility for tool '${n}':`,o)}}return r}isApplicableToAnyContext(e,t){let r=this.get(e);return!r?.isApplicableToContent||t.length===0?!0:t.some(n=>{try{return r.isApplicableToContent?.(n)??!0}catch(i){return console.error(`Error evaluating applicability for tool '${e}':`,i),!0}})}getToolMetadata(){return this.getAllTools().map(e=>({toolId:e.toolId,name:e.name,description:e.description,pnpSupportIds:e.pnpSupportIds||[],supportedLevels:e.supportedLevels,activation:e.activation||"toolbar-toggle",singletonScope:e.singletonScope||null,surfaces:e.surfaces||[],requiresAuthoredContent:!!e.requiresAuthoredContent,contentDependencyDescription:e.requiresAuthoredContent?.description??null}))}generatePNPSupportsFromTools(e){let t=new Set;for(let r of e){let n=this.get(r);if(n?.pnpSupportIds)for(let i of n.pnpSupportIds)t.add(i)}return Array.from(t)}clear(){let e=this.getAllToolIds();e.length!==0&&(this.tools.clear(),this.pnpIndex.clear(),this.emitChange({kind:"clear",toolIds:e}))}setComponentOverrides(e){this.componentOverrides!==e&&(this.componentOverrides=e,this.emitChange({kind:"component-overrides",toolIds:[]}))}setToolModuleLoaders(e){let t=Object.entries(e).filter(n=>n[1]!==void 0);for(let[n,i]of t)if(wh(n,"tool module loader id"),typeof i!="function")throw Error(`Invalid tool module loader for "${n}": expected a function.`);let r=[];for(let[n,i]of t)this.moduleLoaders.get(n)!==i&&(this.moduleLoaders.set(n,i),r.push(n));r.length>0&&this.emitChange({kind:"module-loaders",toolIds:r})}async ensureToolModuleLoaded(e){if(this.loadedToolModules.has(e))return;let t=this.moduleLoadPromises.get(e);if(t){await t;return}let r=this.moduleLoaders.get(e);if(!r)return;let n=(async()=>{await r(),this.loadedToolModules.add(e)})();this.moduleLoadPromises.set(e,n);try{await n}finally{this.moduleLoadPromises.delete(e)}}async ensureToolModulesLoaded(e){await Promise.all(e.map(t=>this.ensureToolModuleLoaded(t)))}isToolModuleLoaded(e){return this.loadedToolModules.has(e)}renderForToolbar(e,t,r){let n=this.get(e);if(!n)throw Error(`Tool '${e}' is not registered`);if(typeof n.renderToolbar!="function")throw Error(`Tool '${e}' has activation "${n.activation||"toolbar-toggle"}" and renders into a host surface, not a toolbar. Remove it from toolbar placement.`);let i={...r,componentOverrides:{...this.componentOverrides||{},...r.componentOverrides||{}}};return n.renderToolbar(t,i)}renderForSurface(e,t){let r=this.get(e);if(!r)throw Error(`Tool '${e}' is not registered`);if(typeof r.renderSurface!="function")throw Error(`Tool '${e}' does not render into a host surface. Surface capabilities declare "surfaces" and implement "renderSurface".`);return r.renderSurface({...t,componentOverrides:{...this.componentOverrides||{},...t.componentOverrides||{}}})}};function sS(e){return typeof e.href=="string"}function JN(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;if(typeof t.id!="string"||t.id.trim().length===0||typeof t.label!="string"||t.label.trim().length===0||t.ariaLabel!==void 0&&typeof t.ariaLabel!="string"||t.icon!==void 0&&typeof t.icon!="string"||t.tooltip!==void 0&&typeof t.tooltip!="string"||t.active!==void 0&&typeof t.active!="boolean"||t.disabled!==void 0&&typeof t.disabled!="boolean")return!1;let r=typeof t.href=="string",n=typeof t.onClick=="function";return r===n?!1:r?!0:n}function aS(e){return typeof e=="string"&&e.trimStart().startsWith("<svg")}function lS(e){return typeof e=="string"&&e.trimStart().startsWith("http")}var QN={calculator:'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M7 2h10a2 2 0 0 1 2 2v16a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2Zm0 2v4h10V4H7Zm0 6v2h2v-2H7Zm4 0v2h2v-2h-2Zm4 0v2h2v-2h-2Zm-8 4v2h2v-2H7Zm4 0v2h2v-2h-2Zm4 0v2h2v-2h-2Zm-8 4v2h2v-2H7Zm4 0v2h2v-2h-2Zm4 0v2h2v-2h-2Z" fill="currentColor"/></svg>',"volume-up":'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M14 3.23v2.06A7.002 7.002 0 0 1 19 12a7 7 0 0 1-5 6.71v2.06c4.01-.91 7-4.49 7-8.77s-2.99-7.86-7-8.77Zm-2 17.75V3L7 8H3v8h4l5 5Zm4.5-9a4.5 4.5 0 0 0-2.5-4.03v8.05A4.5 4.5 0 0 0 16.5 12Z" fill="currentColor"/></svg>',swatch:'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M12 3a9 9 0 1 0 9 9c0-.55-.45-1-1-1h-2.5a1.5 1.5 0 0 1 0-3H20a1 1 0 0 0 1-1 8.99 8.99 0 0 0-9-4Zm-5.5 9A1.5 1.5 0 1 1 8 13.5 1.5 1.5 0 0 1 6.5 12Zm3-4A1.5 1.5 0 1 1 11 9.5 1.5 1.5 0 0 1 9.5 8Zm5 0A1.5 1.5 0 1 1 16 9.5 1.5 1.5 0 0 1 14.5 8Z" fill="currentColor"/></svg>',"chart-bar":'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M4.75 5a.76.76 0 0 1 .75.75v11c0 .438.313.75.75.75h13a.76.76 0 0 1 .696 1.039.74.74 0 0 1-.696.461h-13C5 19 4 18 4 16.75v-11A.74.74 0 0 1 4.75 5ZM8 8.25a.74.74 0 0 1 .75-.75h6.5a.76.76 0 0 1 .696 1.039.74.74 0 0 1-.696.461h-6.5A.722.722 0 0 1 8 8.25Zm.75 2.25h4.5a.76.76 0 0 1 .696 1.039.74.74 0 0 1-.696.461h-4.5a.723.723 0 0 1-.75-.75.74.74 0 0 1 .75-.75Zm0 3h8.5a.76.76 0 0 1 .696 1.039.74.74 0 0 1-.696.461h-8.5a.723.723 0 0 1-.75-.75.74.74 0 0 1 .75-.75Z" fill="currentColor"/></svg>',beaker:'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M5 21c-.85 0-1.454-.38-1.813-1.137-.358-.759-.27-1.463.263-2.113L9 11V5H8a.968.968 0 0 1-.713-.287A.968.968 0 0 1 7 4c0-.283.096-.52.287-.712A.968.968 0 0 1 8 3h8c.283 0 .52.096.712.288.192.191.288.429.288.712s-.096.52-.288.713A.968.968 0 0 1 16 5h-1v6l5.55 6.75c.533.65.62 1.354.262 2.113C20.454 20.62 19.85 21 19 21H5Zm2-3h10l-3.4-4h-3.2L7 18Zm-2 1h14l-6-7.3V5h-2v6.7L5 19Z" fill="currentColor"/></svg>',protractor:'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="m6.75 21-.25-2.2 2.85-7.85a3.95 3.95 0 0 0 1.75.95l-2.75 7.55L6.75 21Zm10.5 0-1.6-1.55-2.75-7.55a3.948 3.948 0 0 0 1.75-.95l2.85 7.85-.25 2.2ZM12 11a2.893 2.893 0 0 1-2.125-.875A2.893 2.893 0 0 1 9 8c0-.65.188-1.23.563-1.737A2.935 2.935 0 0 1 11 5.2V3h2v2.2c.583.2 1.063.554 1.438 1.063C14.812 6.77 15 7.35 15 8c0 .833-.292 1.542-.875 2.125A2.893 2.893 0 0 1 12 11Zm0-2c.283 0 .52-.096.713-.287A.967.967 0 0 0 13 8a.967.967 0 0 0-.287-.713A.968.968 0 0 0 12 7a.968.968 0 0 0-.713.287A.967.967 0 0 0 11 8c0 .283.096.52.287.713.192.191.43.287.713.287Z" fill="currentColor"/></svg>',"bars-3":'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M6.85 15c.517 0 .98-.15 1.388-.45.408-.3.695-.692.862-1.175l.375-1.15c.267-.8.2-1.537-.2-2.213C8.875 9.337 8.3 9 7.55 9H4.025l.475 3.925c.083.583.346 1.075.787 1.475.442.4.963.6 1.563.6Zm10.3 0c.6 0 1.12-.2 1.563-.6.441-.4.704-.892.787-1.475L19.975 9h-3.5c-.75 0-1.325.342-1.725 1.025-.4.683-.467 1.425-.2 2.225l.35 1.125c.167.483.454.875.862 1.175.409.3.871.45 1.388.45Zm-10.3 2c-1.1 0-2.063-.363-2.887-1.088a4.198 4.198 0 0 1-1.438-2.737L2 9H1V7h6.55c.733 0 1.404.18 2.013.537A3.906 3.906 0 0 1 11 9h2.025c.35-.617.83-1.104 1.438-1.463A3.892 3.892 0 0 1 16.474 7H23v2h-1l-.525 4.175a4.198 4.198 0 0 1-1.438 2.737A4.238 4.238 0 0 1 17.15 17c-.95 0-1.804-.27-2.562-.813A4.234 4.234 0 0 1 13 14.026l-.375-1.125a21.35 21.35 0 0 1-.1-.363 4.926 4.926 0 0 1-.1-.537h-.85c-.033.2-.067.363-.1.488a21.35 21.35 0 0 1-.1.362L11 14a4.3 4.3 0 0 1-1.588 2.175A4.258 4.258 0 0 1 6.85 17Z" fill="currentColor"/></svg>',ruler:'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="m8.8 10.95 2.15-2.175-1.4-1.425-1.1 1.1-1.4-1.4 1.075-1.1L7 4.825 4.825 7 8.8 10.95Zm8.2 8.225L19.175 17l-1.125-1.125-1.1 1.075-1.4-1.4 1.075-1.1-1.425-1.4-2.15 2.15L17 19.175ZM7.25 21H3v-4.25l4.375-4.375L2 7l5-5 5.4 5.4 3.775-3.8c.2-.2.425-.35.675-.45a2.068 2.068 0 0 1 1.55 0c.25.1.475.25.675.45L20.4 4.95c.2.2.35.425.45.675.1.25.15.508.15.775a1.975 1.975 0 0 1-.6 1.425l-3.775 3.8L22 17l-5 5-5.375-5.375L7.25 21ZM5 19h1.4l9.8-9.775L14.775 7.8 5 17.6V19Z" fill="currentColor"/></svg>',"book-open":'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M12 6.25a6.6 6.6 0 0 0-2.3-1.32A8.6 8.6 0 0 0 7 4.5c-.63 0-1.25.06-1.85.18-.6.12-1.19.3-1.76.54a1.5 1.5 0 0 0-.93 1.4v10.1c0 .52.26.98.68 1.24.42.26.92.28 1.35.06.36-.18.75-.31 1.18-.4.42-.09.86-.13 1.33-.13.78 0 1.53.14 2.24.42.7.28 1.35.7 1.93 1.24l.83-.75.83.75c.58-.54 1.22-.96 1.93-1.24a6.1 6.1 0 0 1 2.24-.42c.47 0 .91.04 1.33.13.43.09.82.22 1.18.4.43.22.93.2 1.35-.06.42-.26.68-.72.68-1.24V6.62c0-.6-.36-1.15-.93-1.4a9.3 9.3 0 0 0-1.76-.54A9.8 9.8 0 0 0 17 4.5a8.6 8.6 0 0 0-2.7.43A6.6 6.6 0 0 0 12 6.25Zm1 10.06V8.02c.55-.5 1.16-.88 1.84-1.13A6 6 0 0 1 17 6.5c.45 0 .89.04 1.32.11.43.08.85.19 1.26.34v9.24a8.2 8.2 0 0 0-1.28-.24A10 10 0 0 0 17 15.85c-.72 0-1.42.09-2.09.26a7.7 7.7 0 0 0-1.91.8Zm-2 0a7.7 7.7 0 0 0-1.91-.8 8.4 8.4 0 0 0-2.09-.26c-.44 0-.87.02-1.3.07-.43.05-.86.13-1.28.24V6.95c.41-.15.83-.26 1.26-.34A7.7 7.7 0 0 1 7 6.5c.76 0 1.48.13 2.16.39.68.25 1.29.63 1.84 1.13Z" fill="currentColor"/></svg>',photo:'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M4 21c-.55 0-1.02-.2-1.41-.59A1.93 1.93 0 0 1 2 19V5c0-.55.2-1.02.59-1.41A1.93 1.93 0 0 1 4 3h16c.55 0 1.02.2 1.41.59.39.39.59.86.59 1.41v14c0 .55-.2 1.02-.59 1.41-.39.39-.86.59-1.41.59H4Zm0-2h16V5H4v14Zm1.5-2.5h13l-4.1-5.47-3.4 4.47-2.5-3.25L5.5 16.5ZM8.5 10a1.5 1.5 0 1 0 0-3 1.5 1.5 0 0 0 0 3Z" fill="currentColor"/></svg>'};function eD(e){return QN[e]||null}var tD=new Set(["assessment","section","item","passage","rubric"]);function vC(e){return tD.has(e)}function ag(e,t,r){let n=e.trim(),i=r.trim();if(!n||!i)throw Error("Tool instance ids require non-empty tool and scope ids");if(!vC(t))throw Error(`Unknown tool scope level '${t}'. Register custom levels with registerToolScopeLevel().`);return`${n}:${t}:${i}`}function cS(e){let t=e.split(":");if(t.length!==3)return null;let[r,n,i]=t;return!r||!i||!vC(n)?null:{baseToolId:r,scopeLevel:n,scopeId:i}}var rD=(e,t)=>{if(!customElements.get(e))try{customElements.define(e,t)}catch(r){if(!(r instanceof DOMException&&r.name==="NotSupportedError"||r&&typeof r=="object"&&r.name==="NotSupportedError")||!customElements.get(e))throw r}},Bf=Zi('<span class="item-toolbar__element-host svelte-1c13522"></span>'),nD=Zi('<span class="item-toolbar__nds-button-zoom svelte-1c13522"><nds-icon-button></nds-icon-button></span>',2),Ff=Zi('<span aria-hidden="true"></span>'),dS=Zi('<img class="item-toolbar__icon-image svelte-1c13522" alt=""/>'),uS=Zi('<i aria-hidden="true"></i>'),iD=Zi("<a><!></a>"),oD=Zi('<button type="button"><!></button>'),fS=Zi('<span class="item-toolbar__controls-host svelte-1c13522"></span>'),sD=Zi("<div></div>"),aD=Zi('<div><div class="item-toolbar__tools-row svelte-1c13522"><!> <!> <!></div> <!></div>'),lD={hash:"svelte-1c13522",code:`.item-toolbar.svelte-1c13522 {display:flex;flex-direction:column;align-items:flex-end;min-width:0;max-width:100%;gap:0;--pie-toolbar-tools-row-height: 2rem;--pie-tts-controls-row-height: 2.875rem;}.item-toolbar__tools-row.svelte-1c13522 {display:flex;align-items:center;justify-content:flex-end;flex-wrap:wrap;gap:0.5rem;max-width:100%;min-height:var(--pie-toolbar-tools-row-height);}
6
+
7
+ /* A granted section tool must stay reachable even when there isn't room for
8
+ every button: scroll the row rather than clipping items past the edge,
9
+ which left them impossible to focus, tab to, or click. \`min-width: 0\`
10
+ beats the flex default (\`auto\`, i.e. never shrink below content), which
11
+ would otherwise keep the row at full content width and make overflow-x
12
+ moot. Item and passage rows wrap without an overflow clip so an inline
13
+ reading-controls panel can still extend outside the row. */.item-toolbar[data-level="section"].svelte-1c13522 .item-toolbar__tools-row:where(.svelte-1c13522) {flex-wrap:nowrap;justify-content:flex-start;
14
+ /* Keep the focus outline inside the scrolling box on both axes. */padding:4px;scroll-padding:4px;box-sizing:border-box;overflow-x:auto;max-width:100%;min-width:0;}.item-toolbar__controls-row.svelte-1c13522 {display:flex;align-items:center;justify-content:flex-end;width:100%;min-height:0;height:auto;}.item-toolbar__controls-row--reserve.svelte-1c13522 {min-height:var(--pie-tts-controls-row-height);height:var(--pie-tts-controls-row-height);}.item-toolbar__controls-row--active.svelte-1c13522 {min-height:var(--pie-tts-controls-row-height);height:var(--pie-tts-controls-row-height);}.item-toolbar__controls-row--align-start.svelte-1c13522 {justify-content:flex-start;}.item-toolbar__controls-host.svelte-1c13522 {display:inline-flex;align-items:center;justify-content:flex-end;width:100%;}.item-toolbar--top.svelte-1c13522,
15
+ .item-toolbar--bottom.svelte-1c13522 {align-items:flex-end;}.item-toolbar--left.svelte-1c13522,
16
+ .item-toolbar--right.svelte-1c13522 {align-items:stretch;}.item-toolbar--left.svelte-1c13522 .item-toolbar__tools-row:where(.svelte-1c13522),
17
+ .item-toolbar--right.svelte-1c13522 .item-toolbar__tools-row:where(.svelte-1c13522) {flex-direction:column;align-items:center;justify-content:flex-start;flex-wrap:nowrap;}.item-toolbar--left.svelte-1c13522 .item-toolbar__controls-row:where(.svelte-1c13522),
18
+ .item-toolbar--right.svelte-1c13522 .item-toolbar__controls-row:where(.svelte-1c13522) {justify-content:flex-start;width:auto;min-height:0;height:auto;}.item-toolbar__button.svelte-1c13522 {display:flex;flex-shrink:0;align-items:center;justify-content:center;width:2rem;height:2rem;padding:0.25rem;border:1px solid var(--pie-button-border, var(--pie-border, #ccc));border-radius:0.25rem;background-color:var(--pie-button-bg, var(--pie-background, white));color:var(--pie-button-color, var(--pie-text, #333));cursor:pointer;transition:all 0.15s ease;text-decoration:none;}
19
+
20
+ /* Drive the vendored NDS icon button's outer size via its own \`--height-32\`
21
+ custom property so its light-DOM inner button matches the toolbar's
22
+ md/sm/lg dimensions (32 / 44 / 40 px) without a layout shift. The glyph
23
+ keeps the NDS-native icon size (we render size="small"), so it isn't
24
+ oversized. */.item-toolbar__nds-button-zoom.svelte-1c13522 {display:inline-flex;flex-shrink:0;}.item-toolbar.svelte-1c13522 nds-icon-button:where(.svelte-1c13522) {
25
+ /* Host-settable button size per toolbar size (drives the NDS outer button
26
+ via its own --height-32). */--height-32: var(--pie-calculator-button-size, 2rem);
27
+ /* Host-settable accent for the calculator button: the NDS tertiary glyph
28
+ colour derives from --color-interactive-blue, remapped here to a
29
+ themeable variable. --pie-calculator-button-color is package-private, so
30
+ nothing sets it and the default is what ships: it now resolves through
31
+ --pie-button-color (DaisyUI base-content) instead of holding the Figma
32
+ blue on every theme, with the literal as the no-theme last resort.
33
+ Not --pie-primary or --pie-tertiary: both are \`direct\` mappings of
34
+ DaisyUI slots chosen to pair with their own -content colour, so a glyph
35
+ taken from either sits at 1.37:1 against the page under \`pastel\` and 11
36
+ of the 35 shipped themes fall under SC 1.4.11's 3:1. */--color-interactive-blue: var(--pie-calculator-button-color, var(--pie-button-color, var(--pie-text, #222)));
37
+ /* NDS palette bridge — keep in sync with the copies in tool-tts-inline
38
+ and section-player SectionItemsPane (asserted by
39
+ scripts/check-theme-tokens.mjs). The vendored button paints its fill,
40
+ its on-accent glyph, its hover ring and its focus ring from the NDS
41
+ design-system palette, which no PIE theme sets, so a tertiary button
42
+ kept a #f3f5f7 pill on every page — and once the glyph followed the
43
+ theme, a light glyph landed on that light pill. */--color-new-gray: var(--pie-background-dark, #f3f5f7);--color-primary-white: var(--pie-white, #ffffff);--color-primary-black: var(--pie-text, #000000);--color-focus-blue: var(--pie-button-focus-outline, #2b87ff);}.item-toolbar--sm.svelte-1c13522 nds-icon-button:where(.svelte-1c13522) {--height-32: var(--pie-calculator-button-size-sm, 2.75rem);}.item-toolbar--lg.svelte-1c13522 nds-icon-button:where(.svelte-1c13522) {--height-32: var(--pie-calculator-button-size-lg, 2.5rem);}.item-toolbar__element-host.svelte-1c13522 {display:contents;}.item-toolbar--sm.svelte-1c13522 .item-toolbar__button:where(.svelte-1c13522) {width:2.75rem;height:2.75rem;}.item-toolbar--sm.svelte-1c13522 {--pie-toolbar-tools-row-height: 2.75rem;--pie-tts-controls-row-height: 3.625rem;}.item-toolbar--lg.svelte-1c13522 .item-toolbar__button:where(.svelte-1c13522) {width:2.5rem;height:2.5rem;}.item-toolbar--lg.svelte-1c13522 {--pie-toolbar-tools-row-height: 2.5rem;--pie-tts-controls-row-height: 3.375rem;}.item-toolbar__button.svelte-1c13522:hover:not(:disabled) {background-color:var(--pie-button-hover-bg, var(--pie-secondary-background, #f5f5f5));border-color:var(--pie-button-hover-border, var(--pie-button-border, var(--pie-border, #ccc)));color:var(--pie-button-hover-color, var(--pie-button-color, var(--pie-text, #333)));transform:translateY(-1px);box-shadow:0 2px 4px color-mix(in srgb, var(--pie-black, #000) 10%, transparent);}.item-toolbar__button.svelte-1c13522:active:not(:disabled) {transform:translateY(0);box-shadow:none;}.item-toolbar__button--active.svelte-1c13522 {background-color:var(--pie-primary, #1976d2);color:var(--pie-white, #fff);border-color:var(--pie-primary, #1976d2);}.item-toolbar__button--active.svelte-1c13522:hover:not(:disabled) {background-color:var(--pie-primary-dark, #1565c0);}.item-toolbar__button.svelte-1c13522:focus-visible {outline:2px solid var(--pie-button-focus-outline, var(--pie-primary, #1976d2));outline-offset:2px;}.item-toolbar__button.svelte-1c13522:disabled {opacity:0.5;cursor:not-allowed;}.item-toolbar__button.svelte-1c13522 svg {width:100%;height:100%;}.item-toolbar__icon-image.svelte-1c13522 {width:100%;height:100%;object-fit:contain;}`};function cD(e,t){dm(t,!0),dC(e,lD);let r=typeof window<"u",n=["/_fa-pro/fontawesome.min.css","/_fa-pro/light.min.css"],i="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@6.5.2/css/all.min.css",o="https://fonts.googleapis.com/css2?family=Roboto:wght@400;500;700&display=swap",s=/font.?awesome|fa-?pro/i,a=H=>{if(document.querySelector(`link[href="${H}"]`))return;let ce=document.createElement("link");ce.rel="stylesheet",ce.href=H,ce.addEventListener("error",()=>{ce.dataset.pieLoadFailed=""},{once:!0}),document.head.appendChild(ce)},l=!1,d=()=>{if(!(!r||l)&&(l=!0,!document.querySelector('link[href*="Roboto"]')&&a(o),!Array.from(document.querySelectorAll('link[rel="stylesheet"][href]')).some(H=>s.test(H.href)))){a(i);for(let H of n)a(H)}},c="__pieFaToolbarShadowInstalled",u=H=>{let ce=H.getRootNode();if(!(ce instanceof ShadowRoot))return;let se=ce;if(se[c])return;se[c]=!0;let de=new Set,lt=Ee=>{if(!Ee||de.has(Ee))return;de.add(Ee);let rt=document.createElement("link");rt.rel="stylesheet",rt.href=Ee,ce.appendChild(rt)},nr=Array.from(document.querySelectorAll('link[rel="stylesheet"][href]')).filter(Ee=>s.test(Ee.href));for(let Ee of nr){if("pieLoadFailed"in Ee.dataset)continue;if(Ee.sheet){lt(Ee.href);continue}let rt=sr=>{Ee.removeEventListener("load",rt),Ee.removeEventListener("error",rt),sr.type==="load"&&lt(Ee.href)};Ee.addEventListener("load",rt),Ee.addEventListener("error",rt)}},f=H=>(d(),u(H),{}),p=(H,ce)=>{let se=ce,de=()=>{let nr=H.querySelector("button");nr&&nr.setAttribute("aria-pressed",se?"true":"false")};de();let lt=new MutationObserver(de);return lt.observe(H,{childList:!0,subtree:!0}),{update(nr){se=nr,de()},destroy(){lt.disconnect()}}},g=H=>H.faIconName||null,v=new Lv,b=Sr(Ls({})),w=wt(t,"level",7,"item"),I=wt(t,"scopeId",7,""),x=wt(t,"itemId",7,""),C=wt(t,"sectionId",7,""),L=wt(t,"catalogId",7,""),E=wt(t,"tools",7,""),M=wt(t,"contentKind",7,"assessment-item"),U=wt(t,"position",7,"bottom"),te=wt(t,"scopeElement",7,null),re=wt(t,"toolRegistry",7,null),Pe=wt(t,"item",7,null),z=wt(t,"hostButtons",23,()=>[]),K=wt(t,"class",7,""),oe=wt(t,"size",7,"md"),ue=wt(t,"language",7,"en-US"),ae=Sr(null),X=Sr(null),j=Ze(()=>y(X)?.ndsIcons===!0),D=Ze(()=>xa(y(X))),Z=Sr(null),F=Sr(0),W=Sr(0),O=Sr(0);jt(()=>{if(y(ae))return HN(y(ae),H=>{bt(X,H,!0)})}),jt(()=>{if(y(ae))return WN(y(ae),H=>{bt(Z,H,!0)})}),jt(()=>{let H=y(X)?.toolkitCoordinator;if(!H||typeof H.onPolicyChange!="function")return;let ce=H.onPolicyChange(()=>{bt(W,y(W)+1)});return()=>{try{ce?.()}catch{}}}),jt(()=>{let H=y(X)?.toolkitCoordinator;if(!H||typeof H.onToolContextResolverChange!="function")return;let ce=H.onToolContextResolverChange(()=>{bt(O,y(O)+1)});return()=>{try{ce?.()}catch{}}});let $=Ze(()=>y(X)?.toolCoordinator),ie=Ze(()=>y(X)?.ttsService),N=Ze(()=>y(X)?.elementToolStateStore),ne=Ze(()=>y(X)?.assessmentId??""),ge=Ze(()=>x()||y(Z)?.itemId||""),Oe=Ze(()=>y(Z)?.canonicalItemId||y(ge)),We=Ze(()=>C()||y(X)?.sectionId||""),Ne=Ze(()=>M()||y(Z)?.contentKind||(w()==="section"?"section":"assessment-item")),xe=Ze(()=>w()&&w()!=="item"?w():y(Ne)==="rubric-block-stimulus"?"passage":"item"),et=Ze(()=>I()?I():y(xe)==="section"?y(We)||y(X)?.sectionId||"default-section":y(xe)==="assessment"?y(X)?.assessmentId||"default-assessment":y(Oe)||y(ge)||"default-item"),Ue=Ze(()=>L()||y(et)),Se=Ze(()=>Pe()||y(Z)?.item||null),Re=Ze(()=>re()||v),mt=Ze(()=>gC(E())),$t=Ze(()=>y(Re).normalizeToolIds(y(mt)).filter(Boolean)),ve=Ze(()=>y(xe)==="section"?"section":y(xe)==="passage"||y(Ne)==="rubric-block-stimulus"?"passage":"item"),me=Ze(()=>{y(W);let H=y(X)?.toolkitCoordinator;return!H||typeof H.decideToolPolicy!="function"?null:H.decideToolPolicy({level:y(ve),scope:{level:y(xe),scopeId:y(et),assessmentId:y(X)?.assessmentId,sectionId:y(We)||void 0,itemId:y(ge)||void 0,canonicalItemId:y(Oe)||void 0,contentKind:y(Ne)}})}),Je=Ze(()=>{let H=ce=>Array.from(new Set(ce));return y(me)?H(y(Re).normalizeToolIds(y(me).visibleTools.map(ce=>ce.toolId)).filter(Boolean)):H(y($t))}),Gt=Ze(()=>{let H=new Set;if(!y(me))return H;for(let ce of y(me).visibleTools)if(!(!ce.required&&!ce.alwaysAvailable))for(let se of y(Re).normalizeToolIds([ce.toolId]).filter(Boolean))H.add(se);return H}),le=Ze(()=>{if(y(xe)==="section"||y(xe)==="assessment")return!0;let H=y(Se)?.config;return!!(y(Se)&&H&&typeof H=="object")}),Ae=Ze(()=>{y(W);let H=y(X)?.toolkitCoordinator;return!H||typeof H.getPolicyInputs!="function"?null:H.getPolicyInputs()}),Y=Ze(()=>y(Ae)?.assessment??null),we=Ze(()=>y(Ae)?.currentItemRef??null),_e=Ze(()=>y(xe)==="section"?{level:"section",assessment:y(Y)||{},section:{}}:y(xe)==="assessment"?{level:"assessment",assessment:y(Y)||{}}:!y(le)||!y(Se)?null:y(xe)==="passage"?{level:"passage",assessment:y(Y)||{},itemRef:y(we)||{id:y(Oe)},passage:y(Se)}:{level:"item",assessment:y(Y)||{},itemRef:y(we)||{id:y(Oe)},item:y(Se)}),Be=Ze(()=>y(_e)?y(_e):{level:"item",assessment:y(Y)||{},itemRef:y(we)||{id:y(Oe)},item:y(Se)||{id:y(Oe),config:{}}}),it=Ze(()=>{if(y(xe)!=="item"&&y(xe)!=="passage")return[];if(!y(le)||!y(Se))return[];let H=y(Se)?.config?.models;return(Array.isArray(H)?H:H&&typeof H=="object"?Object.values(H):[]).filter(ce=>ce&&typeof ce=="object"&&typeof ce.id=="string").map(ce=>({level:"element",assessment:y(Y)||{},itemRef:y(we)||{id:y(Oe)},item:y(Se),elementId:ce.id}))}),tt=Ze(()=>{let H=y(X)?.toolkitCoordinator||null,ce=se=>cS(se)?se:ag(se,y(xe),y(et));return{scope:{level:y(xe),scopeId:y(et),assessmentId:y(X)?.assessmentId,sectionId:y(We),itemId:y(ge),canonicalItemId:y(Oe),contentKind:y(Ne)},itemId:y(et),catalogId:y(Ue),language:ue(),i18n:y(D),ui:{size:oe()},getScopeElement:()=>te()||y(Z)?.scopeElement||null,getGlobalElementId:()=>!y(N)||!y(ne)||!y(We)||!y(Oe)?null:y(N).getGlobalElementId(y(ne),y(We),y(Oe),y(Oe)),toolCoordinator:y($)||null,toolkitCoordinator:H,ttsService:y(ie)||null,elementToolStateStore:y(N)||null,toggleTool:se=>{if(!y($))return;let de=ce(se);y($).getToolState(de)||y($).registerTool(de,se),y($).toggleTool(de)},isToolVisible:se=>y($)?y($).isToolVisible(ce(se)):!1,subscribeVisibility:y($)?se=>y($).subscribe(se):null}}),Bt=Ze(()=>{y(O);let H=y(X)?.toolkitCoordinator;if(!H||typeof H.hasToolContextResolver!="function"||typeof H.resolveToolContext!="function")return{};let ce={};for(let se of y(Je)){if(!y(Re).get(se)?.supportedLevels.includes(y(xe))||!H.hasToolContextResolver(se))continue;let de=H.resolveToolContext({toolId:se,context:y(Be),toolbarContext:y(tt)});de&&(ce[se]=de)}return ce}),ht=Ze(()=>{let H=y(Je).filter(Ee=>{let rt=y(Re).get(Ee);return rt?rt.supportedLevels.includes(y(xe)):!1}),ce=Object.values(y(Bt)),se=new Set(ce.map(Ee=>Ee.toolId)),de=new Set(ce.filter(Ee=>Ee.visible).map(Ee=>Ee.toolId)),lt=H.filter(Ee=>!se.has(Ee));if(y(xe)==="section")return lt.forEach(Ee=>de.add(Ee)),Array.from(de);if(!y(le))return lt.forEach(Ee=>de.add(Ee)),Array.from(de);if(!y(_e)&&y(it).length===0)return lt.forEach(Ee=>de.add(Ee)),Array.from(de);lt.filter(Ee=>y(Gt).has(Ee)).forEach(Ee=>de.add(Ee)),y(_e)&&y(Re).filterVisibleInContext(lt,y(_e)).forEach(Ee=>de.add(Ee.toolId));for(let Ee of y(it))y(Re).filterVisibleInContext(lt,Ee).forEach(rt=>de.add(rt.toolId));let nr=y(_e)?[y(_e),...y(it)]:y(it);for(let Ee of Array.from(de))se.has(Ee)||y(Re).isApplicableToAnyContext(Ee,nr)||de.delete(Ee);return Array.from(de)}),ot=Ze(()=>y(Re).filterToolIdsByActivation(y(ht),"toolbar-toggle"));jt(()=>{if(!r)return;let H=!1;return y(Re).ensureToolModulesLoaded(y(ot)).then(()=>{H||bt(F,y(F)+1)}).catch(ce=>{console.error("[ItemToolBar] Failed to load one or more tool modules:",ce)}),()=>{H=!0}});function $r(){return te()?te():y(Z)?.scopeElement||null}function Ur(){return!y(N)||!y(ne)||!y(We)||!y(Oe)?null:y(N).getGlobalElementId(y(ne),y(We),y(Oe),y(Oe))}let Lr=Ze(()=>{let H=y(X)?.toolkitCoordinator||null,ce=se=>cS(se)?se:ag(se,y(xe),y(et));return{scope:{level:y(xe),scopeId:y(et),assessmentId:y(X)?.assessmentId,sectionId:y(We),itemId:y(ge),canonicalItemId:y(Oe),contentKind:y(Ne)},itemId:y(et),catalogId:y(Ue),language:ue(),i18n:y(D),ui:{size:oe()},getScopeElement:$r,getGlobalElementId:Ur,toolCoordinator:y($)||null,toolkitCoordinator:H,ttsService:y(ie)||null,elementToolStateStore:y(N)||null,toggleTool:se=>{if(!y($))return;let de=ce(se);y($).getToolState(de)||y($).registerTool(de,se),y($).toggleTool(de)},isToolVisible:se=>y($)?y($).isToolVisible(ce(se)):!1,subscribeVisibility:y($)?se=>y($).subscribe(se):null,getResolvedToolContext:se=>y(Bt)[se]??null,getToolRenderParams:se=>{let de=y(Bt)[se]?.params??null,lt=ln.get(se);return lt?{...de??{},...lt}:de}}}),ln=new Map,qr=0,xr=Ze(()=>{if(!r)return[];y(F);let H=[];for(let ce of y(ot)){let se=y(Re).renderForToolbar(ce,y(Be),y(Lr));se&&H.push(se)}return H}),Ar=Ze(()=>{if(!Array.isArray(z()))return[];let H=[];return z().forEach((ce,se)=>{if(JN(ce)){H.push(ce);return}console.warn(`[ItemToolBar] Ignoring invalid host button at index ${se}. Expected { id, label, href | onClick } with valid types.`)}),H}),ye=Ze(()=>y(xr).filter(H=>!!H.button).map(H=>{let ce=H.button;return{id:H.toolId,label:ce.label,ariaLabel:ce.ariaLabel||ce.label,icon:ce.icon,faIconName:ce.faIconName,tooltip:ce.tooltip||ce.label,disabled:ce.disabled,active:y(b)[H.toolId]??ce.active??!1,onClick:()=>{ce.onClick(),_t()}}})),vt=Ze(()=>[...y(ye),...y(Ar)]),kt=Ze(()=>{let H={};for(let ce of y(xr))H[ce.toolId]=y(b)[ce.toolId]??ce.button?.active??!1;return H}),Qe=Ze(()=>y(xr).flatMap(H=>(H.elements||[]).filter(ce=>ce.mount==="before-buttons").filter(ce=>!!ce.element).map((ce,se)=>({key:`before-${H.toolId}-${se}`,toolId:H.toolId,entry:ce})))),cr=Ze(()=>y(xr).flatMap(H=>(H.elements||[]).filter(ce=>ce.mount==="after-buttons").filter(ce=>!!ce.element).map((ce,se)=>({key:`after-${H.toolId}-${se}`,toolId:H.toolId,entry:ce})))),V=Ze(()=>y(xr).flatMap(H=>(H.elements||[]).filter(ce=>ce.mount==="controls-row").filter(ce=>!!ce.element).map((ce,se)=>({key:`controls-row-${H.toolId}-${se}`,toolId:H.toolId,entry:ce})))),ke=Ze(()=>y(xr).flatMap(H=>(H.elements||[]).map(ce=>({toolId:H.toolId,hint:ce.layoutHints?.controlsRow})).filter(ce=>!!ce.hint))),qe=Ze(()=>y(xr).flatMap(H=>(H.elements||[]).map(ce=>({toolId:H.toolId,hint:ce.layoutHints?.headerOverlay})).filter(ce=>!!ce.hint))),Ve=Ze(()=>y(ke).some(H=>H.hint?.reserveSpace===!0)),at=Ze(()=>y(ke).some(H=>H.hint?.showWhenToolActive===!0&&(y(kt)[H.toolId]??!1))),Rt=Ze(()=>U()==="left"||U()==="right"),Rr=Ze(()=>y(qe).some(H=>H.hint?.showWhenToolActive===!0&&(y(kt)[H.toolId]??!1))),Vr=Ze(()=>y(V).length>0||y(Ve)||y(at));function jr(){if(!y(ae))return null;let H=y(ae).getRootNode();return H instanceof ShadowRoot?H.host:null}jt(()=>{let H=jr();if(!H)return;let ce=y(qe).length>0,se=y(Rr);return H.setAttribute("data-pie-header-overlay",ce?"true":"false"),H.setAttribute("data-pie-header-overlay-active",se?"true":"false"),()=>{H.removeAttribute("data-pie-header-overlay"),H.removeAttribute("data-pie-header-overlay-active")}}),jt(()=>{!r||!y(j)||y(vt).some(H=>!!g(H))&&d()});function dr(H){return H.id in y(b)?y(b)[H.id]===!0:H.active===!0}function fe(H){return eD(H)}function _t(){let H={};for(let ce of y(xr))ce.sync?.(),ce.button&&(H[ce.toolId]=ce.button.active??!1);bt(b,H,!0)}jt(()=>{let H=[];_t();for(let ce of y(xr))if(ce.subscribeActive){let se=!1,de=ce.subscribeActive(lt=>{queueMicrotask(()=>{se||(bt(b,{...y(b),[ce.toolId]:lt},!0),ce.sync?.())})});H.push(()=>{se=!0,de()})}return()=>{H.forEach(ce=>ce())}}),jt(()=>{let H=y(X)?.toolkitCoordinator;if(typeof H?.registerToolRequestTarget!="function")return;let ce=y(ve);return H.registerToolRequestTarget({level:ce,hostsTool:se=>y(ot).includes(se),open:(se,de)=>{if(!y($)||!y(ot).includes(se))return;de&&Object.keys(de).length>0&&(qr+=1,ln.set(se,{...de,toolRequestId:qr}));let lt=ag(se,y(xe),y(et));y($).getToolState(lt)||y($).registerTool(lt,se),y($).showTool(lt),queueMicrotask(()=>_t())}})}),jt(()=>{if(!y(Lr).subscribeVisibility)return;let H=!1,ce=y(Lr).subscribeVisibility(()=>{queueMicrotask(()=>{H||_t()})});return()=>{H=!0,ce?.()}}),jt(()=>{let H=y(Lr).toolkitCoordinator;if(typeof H?.subscribeTelemetry!="function")return;let ce=!1,se=H.subscribeTelemetry(({eventName:de,payload:lt})=>{de==="pie-toolkit-tool-config-updated"&&(lt?.toolId&&!y(ot).includes(lt.toolId)||queueMicrotask(()=>{ce||(bt(F,y(F)+1),_t())}))});return()=>{ce=!0,se?.()}});let Gr="[data-pie-tool-overlay-boundary]";function tn(H,ce){if(ce.container!=="content-boundary")return H;let se=H;for(;se;){if(se instanceof HTMLElement&&se.matches(Gr))return se;if(se instanceof HTMLElement&&se.parentElement){se=se.parentElement;continue}let de=se.getRootNode();se=de instanceof ShadowRoot?de.host:null}return H}function Wn(H,ce){let se=ce,de=null,lt=H,nr=rt=>{if(!rt)return;let sr=rt.__pieToolElementUnmount;typeof sr=="function"&&sr()},Ee=rt=>{de!==rt&&(de&&(nr(de),de.parentNode===lt&&lt.removeChild(de)),de=rt,de&&(lt=tn(H,se),de.parentNode&&de.parentNode!==lt&&de.parentNode.removeChild(de),lt.appendChild(de)))};return Ee(ce.element),{update(rt){se=rt,Ee(rt.element)},destroy(){Ee(null)}}}function ei(H,ce){let se=ce,de=null,lt=null,nr=[],Ee=null,rt=null,sr=null,Pt=null,$e=null,wr=null,hn=null,Ir=!1,Br=!1,mr=()=>se.mounted.entry.shell?.pageTabOrder===!0,ur=()=>se.mounted.entry.shell?.ndsHeaderControls===!0,Lt=null,gr=null,Fr=cP({onMove:he=>yf(he),onEnd:()=>{gr=null}}),Yt=0,dt=0,zt=0,fr=0,Kn=0,_r=0,$n=0,ri=0,pn=null,Zr=[],Pr=0,Or=0,kr=se.mounted.entry.shell?.initialWidth??720,xt=se.mounted.entry.shell?.initialHeight??560,Tr=kr,ni=xt,Ln=!1,On=null,m=null,k=!1,B=he=>{if(!he)return;let ze=he.__pieToolElementUnmount;typeof ze=="function"&&ze()},J=()=>{let he=se.mounted.entry.shell;return he?{toolId:se.mounted.toolId,toolbarContext:y(Lr),shellConfig:he}:null},Me=he=>{let ze=y(Re).get(se.mounted.toolId),pt=J();!ze?.onHostedMount||!pt||ze.onHostedMount(he,pt)},st=()=>{let he=y(Re).get(se.mounted.toolId),ze=J();!he?.onHostedResize||!ze||he.onHostedResize({width:kr,height:xt},se.mounted.entry.element,ze)},yt=()=>{let he=y(Re).get(se.mounted.toolId),ze=J();!he?.onHostedUnmount||!ze||he.onHostedUnmount(se.mounted.entry.element,ze)},Jt=(he,ze,pt)=>Math.max(ze,Math.min(he,pt)),ii=()=>{let he=se.mounted.entry.shell;return{minWidth:he?.minWidth??320,minHeight:he?.minHeight??240,maxWidth:he?.maxWidth??window.innerWidth,maxHeight:he?.maxHeight??window.innerHeight}},Un=()=>{let he=se.mounted.entry.shell?.minWidth,ze=typeof he=="number"&&he>0&&kr<he,pt=ze?`${he}px`:"";Lt&&(Lt.style.minWidth=pt),Ee&&(Ee.style.minWidth="0"),rt&&(rt.style.minWidth="0",rt.style.overflowX=ze?"auto":"hidden")},Nr=()=>se.mounted.entry.shell?.content?.overflowY==="auto"?"auto":"hidden",Pa=()=>{if(!Ee)return 0;let he=Ee.getBoundingClientRect().height;return he>0?he:Ee.offsetHeight||0},Yr=()=>{if(!rt)return;let he=se.mounted.entry.shell;if(rt.style.overflowY=Nr(),!!Lt){if(he?.content?.preserveMinHeight===!0){let ze=Pa(),pt=he.minHeight??240,Ke=Math.max(0,pt-ze),Ie=Math.max(0,xt-ze),Tt=Math.max(Ie,Ke);Lt.style.height=`${Tt}px`,Lt.style.minHeight="0",Lt.style.flex=`0 0 ${Tt}px`;return}Lt.style.height="100%",Lt.style.minHeight="0",Lt.style.flex="1 1 auto"}},Aa=()=>{let he=se.mounted.entry.shell,ze=he?.initialWidth??720,pt=he?.initialHeight??560;ze===Tr&&pt===ni||(Tr=ze,ni=pt,!Ln&&(kr=ze,xt=pt,Ge()))},cc=()=>{let{minWidth:he,minHeight:ze,maxWidth:pt,maxHeight:Ke}=ii(),Ie=Math.min(he,window.innerWidth),Tt=Math.min(ze,window.innerHeight);kr=Jt(kr,Ie,Math.max(Ie,Math.min(pt,window.innerWidth))),xt=Jt(xt,Tt,Math.max(Tt,Math.min(Ke,window.innerHeight))),Pr=Jt(Pr,0,Math.max(0,window.innerWidth-kr)),Or=Jt(Or,0,Math.max(0,window.innerHeight-xt)),Ma(),Un(),Yr(),st()},pi=(he,ze)=>{Ln=!0,Pr+=he,Or+=ze,cc()},dc=(he,ze)=>{Ln=!0,kr+=he,xt+=ze,cc()},gf=(he,ze,pt,Ke="fa-regular")=>{let Ie=document.createElement("nds-icon-button");if(Ie.setAttribute("variant","tertiary"),Ie.setAttribute("size","small"),Ie.setAttribute("type","circle"),Ie.setAttribute("icon-name",ze),Ie.setAttribute("button-aria-label",he),Ie.title=he,Ie.addEventListener("click",Tt=>{Tt.stopPropagation(),pt(),De()}),Ke!=="fa-light"){let Tt=rn=>{rn.classList.remove("fa-light"),rn.classList.add(Ke)},Ot=Ie.querySelector("i.fa-light");if(Ot)Tt(Ot);else{let rn=new MutationObserver(()=>{let Nn=Ie.querySelector("i.fa-light");Nn&&(Tt(Nn),rn.disconnect())});rn.observe(Ie,{childList:!0,subtree:!0})}}return Ie},vf=(he,ze,pt)=>{let Ke=document.createElement("button");return Ke.type="button",Ke.className="pie-tool-shell__control",Ke.setAttribute("aria-label",he),Ke.title=he,Ke.textContent=ze,Ke.style.border="1px solid transparent",Ke.style.background="color-mix(in srgb, var(--pie-white, #fff) 10%, transparent)",Ke.style.color="inherit",Ke.style.cursor="pointer",Ke.style.display="inline-flex",Ke.style.alignItems="center",Ke.style.justifyContent="center",Ke.style.width="28px",Ke.style.height="28px",Ke.style.padding="0",Ke.style.fontSize="14px",Ke.style.fontWeight="700",Ke.style.borderRadius="8px",Ke.style.lineHeight="1",Ke.onclick=Ie=>{Ie.stopPropagation(),pt(),De()},Ke.onfocus=()=>{Ke.style.outline="2px solid var(--pie-button-focus-outline, var(--pie-primary, #4A90E2))",Ke.style.outlineOffset="2px"},Ke.onblur=()=>{Ke.style.outline="none",Ke.style.outlineOffset="0"},Ke},Ma=()=>{de&&(de.style.left=`${Pr}px`,de.style.top=`${Or}px`,de.style.width=`${kr}px`,de.style.height=`${xt}px`,de.style.display=se.active?"flex":"none")},P=()=>{sr&&(sr.textContent=se.mounted.entry.shell?.title||se.mounted.toolId);for(let{el:he,key:ze}of nr){let pt=se.i18n.t(ze);he.tagName==="NDS-ICON-BUTTON"?he.setAttribute("button-aria-label",pt):he.setAttribute("aria-label",pt),he.title&&(he.title=pt)}},pe=()=>{if(!rt)return;let he=se.mounted.entry.element;he.style.display="block",he.style.width="100%",he.style.height="100%",he.style.flex="1 1 auto",he.style.minHeight="0",Lt&&Lt!==he&&(Lt.parentNode===rt&&(B(Lt),rt.removeChild(Lt)),Lt=null),he.parentNode&&he.parentNode!==rt&&he.parentNode.removeChild(he),he.parentNode!==rt&&rt.appendChild(he),Lt=he,Un(),Yr(),Me(he)},De=()=>{y($)&&de&&y($).bringToFront(de)},Ge=()=>{let{innerWidth:he,innerHeight:ze}=window,pt=se.mounted.entry.shell,Ke=pt?.initialAlign??"center",Ie=pt?.initialMargin??16,Tt=Ie+60;switch(Ke){case"top-left":Pr=Ie,Or=Tt;break;case"top-right":Pr=Math.max(0,he-kr-Ie),Or=Tt;break;case"bottom-left":Pr=Ie,Or=Math.max(0,ze-xt-Tt);break;case"bottom-right":Pr=Math.max(0,he-kr-Ie),Or=Math.max(0,ze-xt-Tt);break;default:Pr=Math.max(0,Math.round((he-kr)/2)),Or=Math.max(0,Math.round((ze-xt)/2))}cc()},ut=()=>{let he=m;he&&queueMicrotask(()=>{if(he.isConnected)try{he.focus()}catch{}})},Dt=()=>{if(typeof document>"u")return null;let he=document.activeElement;for(;he;){let ze=he.shadowRoot;if(ze&&ze.activeElement&&ze.activeElement!==he)he=ze.activeElement;else break}return he??null},At=()=>{if(!de||On)return;let he=Dt();!m&&he&&!de.contains(he)&&(m=he),mr()&&!Br&&(document.addEventListener("keydown",qn,!0),Br=!0),On=hP(de,{initialFocus:$e,onEscape:()=>{La()},wrap:!mr(),onTabExit:mr()?(ze,pt)=>{if(ze==="backward"){if(m?.isConnected){pt.preventDefault();try{m.focus()}catch{}}return}let Ke=yr();if(Ke){pt.preventDefault();try{Ke.focus()}catch{}}}:void 0})},yr=()=>{let he=y(Lr).getScopeElement?.()??null;if(!he)return null;let ze=Ke=>!!(y(ae)&&y(ae).contains(Ke)||de&&de.contains(Ke)),pt=Ke=>{if(Ke instanceof HTMLElement){if(ze(Ke))return null;if(Ke.matches?.(uP)&&dP(Ke))return Ke}let Ie=Ke.shadowRoot;if(Ie)for(let Tt=0;Tt<Ie.children.length;Tt++){let Ot=pt(Ie.children[Tt]);if(Ot)return Ot}for(let Tt=0;Tt<Ke.children.length;Tt++){let Ot=pt(Ke.children[Tt]);if(Ot)return Ot}return null};return pt(he)},mi=()=>de?fP(de).filter(he=>he!==wr&&he!==hn):[],qn=he=>{if(he.key!=="Tab"||!de||!se.active)return;let ze=Dt();if(!ze||de.contains(ze))return;let pt=mi();if(pt.length!==0){if(he.shiftKey){if(ze!==yr())return;he.preventDefault();try{pt[pt.length-1].focus()}catch{}return}if(ze===m){he.preventDefault();try{pt[0].focus()}catch{}}}},$a=()=>{if(Br&&(document.removeEventListener("keydown",qn,!0),Br=!1),!On)return;let he=On;On=null;try{he()}catch{}ut()},La=()=>{y(Lr).toggleTool(se.mounted.toolId),_t()},ra=he=>{se.mounted.entry.shell?.draggable&&(he.target.closest("button")||!de||Fr.begin(he,de)&&(gr="drag",Ln=!0,Yt=he.clientX-Pr,dt=he.clientY-Or,de.setPointerCapture(he.pointerId),De()))},cn=he=>ze=>{!de||!se.mounted.entry.shell?.resizable||(ze.stopPropagation(),Fr.begin(ze,de)&&(gr="resize",Ln=!0,pn=he,zt=kr,fr=xt,Kn=ze.clientX,_r=ze.clientY,$n=Pr,ri=Or,de.setPointerCapture(ze.pointerId),De()))},yf=he=>{if(de){if(gr==="drag"){he.preventDefault();let ze=Math.max(0,window.innerWidth-kr),pt=Math.max(0,window.innerHeight-xt);Pr=Jt(he.clientX-Yt,0,ze),Or=Jt(he.clientY-dt,0,pt),Ma();return}if(gr==="resize"){he.preventDefault();let ze=se.mounted.entry.shell,pt=ze?.minWidth??320,Ke=ze?.minHeight??240,Ie=Math.min(pt,window.innerWidth),Tt=Math.min(Ke,window.innerHeight),Ot=ze?.maxWidth??window.innerWidth,rn=ze?.maxHeight??window.innerHeight,Nn=he.clientX-Kn,Ai=he.clientY-_r;if(pn==="se")kr=Jt(zt+Nn,Ie,Math.max(Ie,Math.min(Ot,window.innerWidth-Pr))),xt=Jt(fr+Ai,Tt,Math.max(Tt,Math.min(rn,window.innerHeight-Or)));else if(pn==="sw"){let oi=$n+zt,bo=Jt(zt-Nn,Ie,Math.min(Ot,oi));Pr=oi-bo,kr=bo,xt=Jt(fr+Ai,Tt,Math.max(Tt,Math.min(rn,window.innerHeight-Or)))}else if(pn==="ne"){let oi=ri+fr;kr=Jt(zt+Nn,Ie,Math.max(Ie,Math.min(Ot,window.innerWidth-Pr)));let bo=Jt(fr-Ai,Tt,Math.min(rn,oi));Or=oi-bo,xt=bo}else if(pn==="nw"){let oi=$n+zt,bo=ri+fr,kn=Jt(zt-Nn,Ie,Math.min(Ot,oi));Pr=oi-kn,kr=kn;let bd=Jt(fr-Ai,Tt,Math.min(rn,bo));Or=bo-bd,xt=bd}Ma(),Un(),Yr(),st()}}},Pi=()=>{cc()};if(r&&se.mounted.entry.shell){let he=se.mounted.entry.shell?.ndsHeaderControls===!0&&y(j);he&&d(),de=document.createElement("div"),de.className="pie-tool-shell",de.setAttribute("data-pie-tool-shell",se.mounted.toolId),de.style.position="fixed",de.style.zIndex="2000",de.style.background="var(--pie-background, #fff)",de.style.border="1px solid var(--pie-border-light, #d1d5db)",de.style.borderRadius="12px",de.style.boxShadow="0 10px 40px color-mix(in srgb, var(--pie-black, #000) 25%, transparent)",de.style.setProperty("--color-interactive-blue","var(--pie-calculator-button-color, var(--pie-button-color, var(--pie-text, #222)))"),de.style.setProperty("--color-new-gray","var(--pie-background-dark, #f3f5f7)"),de.style.setProperty("--color-primary-white","var(--pie-white, #ffffff)"),de.style.setProperty("--color-primary-black","var(--pie-text, #000000)"),de.style.setProperty("--color-focus-blue","var(--pie-button-focus-outline, #2b87ff)"),de.style.overflow="visible",de.style.display=se.active?"flex":"none",de.style.flexDirection="column",de.style.userSelect="none",de.style.webkitUserSelect="none",de.style.touchAction="none",de.setAttribute("draggable","false"),de.addEventListener("dragstart",Ie=>Ie.preventDefault()),Ee=document.createElement("div"),Ee.className="pie-tool-shell__header",Ee.style.display="flex",Ee.style.flexWrap="wrap",Ee.style.alignItems="center",Ee.style.justifyContent="space-between",Ee.style.gap="6px",Ee.style.padding=ur()?"12px 12px 12px 28px":"10px 12px",ur()&&(Ee.style.minHeight="48px"),ur()?(Ee.style.background="var(--pie-section-player-card-header-background, var(--pie-button-active-bg, #f3f4f6))",Ee.style.color="var(--pie-text, #111827)",Ee.style.borderBottom="1px solid var(--pie-border-light, #e5e7eb)"):(Ee.style.background="var(--pie-primary-dark, #2c3e50)",Ee.style.color="var(--pie-white, #fff)"),Ee.style.cursor=se.mounted.entry.shell.draggable===!1?"default":"move",Ee.style.flex="0 0 auto",Ee.style.borderRadius="12px 12px 0 0",Ee.style.overflow="hidden",Ee.style.userSelect="none",Ee.style.webkitUserSelect="none",Ee.style.touchAction="none",Ee.setAttribute("draggable","false"),Ee.addEventListener("dragstart",Ie=>Ie.preventDefault()),sr=document.createElement("span"),sr.className="pie-tool-shell__title",sr.style.minWidth="0",sr.style.overflowWrap="anywhere",sr.textContent=se.mounted.entry.shell.title||se.mounted.toolId,Ee.appendChild(sr),Pt=document.createElement("div"),Pt.className="pie-tool-shell__controls",Pt.style.display="inline-flex",Pt.style.flexWrap="wrap",Pt.style.minWidth="0",Pt.style.alignItems="center",Pt.style.gap=ur()?"6px":"4px";let ze=se.mounted.entry.shell,pt=(Ie,Tt,Ot,rn,Nn="fa-regular")=>{if(!Pt)return;let Ai=se.i18n.t(Ie),oi=he?gf(Ai,Ot,rn,Nn):vf(Ai,Tt,rn);nr.push({el:oi,key:Ie}),Pt.appendChild(oi)};if(ze?.draggable!==!1&&(pt("toolkit.window.moveLeftA11y","←","chevron-left",()=>pi(-24,0)),pt("toolkit.window.moveRightA11y","→","chevron-right",()=>pi(24,0)),pt("toolkit.window.moveUpA11y","↑","chevron-up",()=>pi(0,-24)),pt("toolkit.window.moveDownA11y","↓","chevron-down",()=>pi(0,24))),ze?.resizable!==!1&&(pt("toolkit.window.shrinkA11y","−","magnifying-glass-minus",()=>dc(-40,-40)),pt("toolkit.window.growA11y","+","magnifying-glass-plus",()=>dc(40,40))),!ur()){let Ie=vf(se.i18n.t("toolkit.window.centerA11y"),"◎",Ge);nr.push({el:Ie,key:"toolkit.window.centerA11y"}),Pt.appendChild(Ie)}let Ke=null;if(ur()?(Ke=document.createElement("div"),Ke.className="pie-tool-shell__header-right",Ke.style.display="inline-flex",Ke.style.flexWrap="wrap",Ke.style.maxWidth="100%",Ke.style.justifyContent="flex-end",Ke.style.alignItems="center",Ke.style.gap="6px",Ke.appendChild(Pt),Ee.appendChild(Ke)):Ee.appendChild(Pt),he)$e=gf(se.i18n.t("toolkit.window.closeA11y"),"xmark",La,"fa-regular"),nr.push({el:$e,key:"toolkit.window.closeA11y"}),$e.style.display=se.mounted.entry.shell.closeable===!1?"none":"inline-block";else{let Ie=document.createElement("button");Ie.type="button",Ie.className="pie-tool-shell__close",Ie.setAttribute("aria-label",se.i18n.t("toolkit.window.closeA11y")),nr.push({el:Ie,key:"toolkit.window.closeA11y"});let Tt="http://www.w3.org/2000/svg",Ot=document.createElementNS(Tt,"svg");Ot.setAttribute("xmlns",Tt),Ot.setAttribute("viewBox","0 0 16 16"),Ot.setAttribute("aria-hidden","true");let rn=document.createElementNS(Tt,"path");rn.setAttribute("d","M3.5 3.5L12.5 12.5M12.5 3.5L3.5 12.5"),rn.setAttribute("stroke","currentColor"),rn.setAttribute("stroke-width","1.8"),rn.setAttribute("stroke-linecap","round"),Ot.appendChild(rn),Ie.appendChild(Ot);let Nn=Ot.style;Nn.width="16px",Nn.height="16px",Nn.display="block",Nn.flexShrink="0",Nn.pointerEvents="none";let Ai="color-mix(in srgb, var(--pie-white, #fff) 8%, transparent)",oi="color-mix(in srgb, var(--pie-white, #fff) 18%, transparent)";Ie.style.border="1px solid transparent",Ie.style.background=Ai,Ie.style.color="inherit",Ie.style.cursor="pointer",Ie.style.display="inline-flex",Ie.style.alignItems="center",Ie.style.justifyItems="center",Ie.style.width="28px",Ie.style.height="28px",Ie.style.padding="0",Ie.style.borderRadius="8px",Ie.style.lineHeight="0",Ie.style.transition="background-color 0.15s ease, border-color 0.15s ease",Ie.style.display=se.mounted.entry.shell.closeable===!1?"none":"inline-flex",Ie.onmouseenter=()=>{Ie.style.background=oi},Ie.onmouseleave=()=>{Ie.style.background=Ai},Ie.onfocus=()=>{Ie.style.outline="2px solid var(--pie-button-focus-outline, var(--pie-primary, #4A90E2))",Ie.style.outlineOffset="2px"},Ie.onblur=()=>{Ie.style.outline="none",Ie.style.outlineOffset="0"},Ie.onclick=La,$e=Ie}if(Ke?Ke.appendChild($e):Ee.appendChild($e),Ee.tabIndex=0,Ee.onkeydown=Ie=>{if(Ie.key==="Home"){Ie.preventDefault(),Ge();return}let Tt=se.mounted.entry.shell;if(Ie.shiftKey&&Tt?.resizable!==!1){if(Ie.key==="ArrowRight"||Ie.key==="ArrowDown"){Ie.preventDefault(),dc(40,40);return}if(Ie.key==="ArrowLeft"||Ie.key==="ArrowUp"){Ie.preventDefault(),dc(-40,-40);return}}Tt?.draggable!==!1&&(Ie.key==="ArrowLeft"?(Ie.preventDefault(),pi(-24,0)):Ie.key==="ArrowRight"?(Ie.preventDefault(),pi(24,0)):Ie.key==="ArrowUp"?(Ie.preventDefault(),pi(0,-24)):Ie.key==="ArrowDown"&&(Ie.preventDefault(),pi(0,24)))},rt=document.createElement("div"),rt.className="pie-tool-shell__content",rt.style.position="relative",rt.style.width="100%",rt.style.flex="1 1 auto",rt.style.minHeight="0",rt.style.overflowX="hidden",rt.style.overflowY=Nr(),rt.style.borderRadius="0 0 12px 12px",ur()){let Ie=Tt=>{let Ot=document.createElement("div");return Ot.tabIndex=0,Ot.setAttribute("aria-hidden","true"),Ot.setAttribute("data-pie-tool-shell-focus-guard",Tt),Ot.style.position="absolute",Ot.style.width="1px",Ot.style.height="1px",Ot.style.padding="0",Ot.style.margin="-1px",Ot.style.overflow="hidden",Ot.style.clipPath="inset(50%)",Ot.style.whiteSpace="nowrap",Ot.style.border="0",Ot};wr=Ie("start"),hn=Ie("end"),wr.addEventListener("focus",Tt=>{if(!Ir){Ir=!0;try{if(Tt.stopPropagation(),m?.isConnected)try{m.focus()}catch{}}finally{queueMicrotask(()=>{Ir=!1})}}}),hn.addEventListener("focus",Tt=>{if(!Ir){Ir=!0;try{Tt.stopPropagation();let Ot=yr();if(Ot)try{Ot.focus()}catch{}}finally{queueMicrotask(()=>{Ir=!1})}}}),de.appendChild(wr)}if(de.appendChild(Ee),de.appendChild(rt),ur()&&hn&&de.appendChild(hn),se.mounted.entry.shell.resizable!==!1){let Ie=(Tt,Ot,rn,Nn,Ai,oi,bo)=>{let kn=document.createElement("div");kn.className="pie-tool-shell__resize",kn.style.position="absolute",kn.style.width="24px",kn.style.height="24px",kn.style.cursor=oi,kn.style.zIndex="10",kn.style.touchAction="none",kn.setAttribute("draggable","false"),Ot!==null&&(kn.style.top=Ot),rn!==null&&(kn.style.right=rn),Nn!==null&&(kn.style.bottom=Nn),Ai!==null&&(kn.style.left=Ai),bo!==null&&(kn.style.background=`linear-gradient(${bo}, transparent 0%, transparent 40%, rgba(0,0,0,0.35) 40%, rgba(0,0,0,0.35) 60%, transparent 60%, transparent 100%)`);let bd=cn(Tt);kn.addEventListener("pointerdown",bd),de.appendChild(kn),Zr.push({el:kn,handler:bd})};Ie("se",null,"0","0",null,"nwse-resize",null),Ie("nw","0",null,null,"0","nwse-resize","135deg"),Ie("ne","0","0",null,null,"nesw-resize",null),Ie("sw",null,null,"0","0","nesw-resize",null)}Ee.addEventListener("pointerdown",ra),de.addEventListener("pointerdown",De),window.addEventListener("resize",Pi),document.body.appendChild(de),lt=new Ws(de,{context:$b,initialValue:se.runtime}),lt.connect(),Ge(),Ma(),P(),pe(),st(),se.active&&At(),k=se.active}return{update(he){if(se=he,!de||!rt||!sr||!$e)return;lt?.setValue(se.runtime),P(),Aa();let ze=$e.tagName.toLowerCase()==="nds-icon-button"?"inline-block":"inline-flex";$e.style.display=se.mounted.entry.shell?.closeable===!1?"none":ze,Ma(),pe(),st(),!k&&se.active?At():k&&!se.active&&($a(),m=null),k=se.active},destroy(){yt(),lt?.disconnect(),lt=null,nr.length=0,On&&$a(),Br&&(document.removeEventListener("keydown",qn,!0),Br=!1);for(let{el:he,handler:ze}of Zr)he.removeEventListener("pointerdown",ze);m=null,Zr.length=0,Ee&&(Ee.removeEventListener("pointerdown",ra),Ee.onkeydown=null),Fr.release(),de&&de.removeEventListener("pointerdown",De),window.removeEventListener("resize",Pi),Lt&&rt&&Lt.parentNode===rt&&(B(Lt),rt.removeChild(Lt)),Lt=null,de&&de.parentElement&&de.remove()}}}var ta={get level(){return w()},set level(H){w(H),gt()},get scopeId(){return I()},set scopeId(H){I(H),gt()},get itemId(){return x()},set itemId(H){x(H),gt()},get sectionId(){return C()},set sectionId(H){C(H),gt()},get catalogId(){return L()},set catalogId(H){L(H),gt()},get tools(){return E()},set tools(H){E(H),gt()},get contentKind(){return M()},set contentKind(H){M(H),gt()},get position(){return U()},set position(H){U(H),gt()},get scopeElement(){return te()},set scopeElement(H){te(H),gt()},get toolRegistry(){return re()},set toolRegistry(H){re(H),gt()},get item(){return Pe()},set item(H){Pe(H),gt()},get hostButtons(){return z()},set hostButtons(H){z(H),gt()},get class(){return K()},set class(H){K(H),gt()},get size(){return oe()},set size(H){oe(H),gt()},get language(){return ue()},set language(H){ue(H),gt()}},Cr=$i(),ti=vi(Cr),Qo=H=>{var ce=aD();let se;var de=rl(ce),lt=rl(de);Nf(lt,17,()=>y(Qe),Pt=>Pt.key,(Pt,$e)=>{var wr=$i(),hn=vi(wr),Ir=mr=>{var ur=$i(),Lt=vi(ur);rg(Lt,()=>y(j),gr=>{var Fr=Bf();aa(Fr,(Yt,dt)=>ei?.(Yt,dt),()=>({mounted:y($e),active:y(kt)[y($e).toolId]??!1,runtime:y(X),i18n:y(D)})),Qt(gr,Fr)}),Qt(mr,ur)},Br=mr=>{var ur=Bf();aa(ur,(Lt,gr)=>Wn?.(Lt,gr),()=>y($e).entry),Qt(mr,ur)};Li(hn,mr=>{y($e).entry.shell?mr(Ir):mr(Br,-1)}),Qt(Pt,wr)});var nr=jc(lt,2);Nf(nr,17,()=>y(vt),Pt=>Pt.id,(Pt,$e,wr,hn)=>{let Ir=Ze(()=>y(j)&&!sS(y($e))?g(y($e)):null);var Br=$i(),mr=vi(Br),ur=Yt=>{var dt=nD(),zt=rl(dt);Ha(zt,1,"item-toolbar__nds-button svelte-1c13522"),Dn(zt,"type","circle"),Dn(zt,"size","small"),Dn(zt,"variant","tertiary"),en(()=>Dn(zt,"icon-name",y(Ir))),en(()=>Dn(zt,"button-aria-label",y($e).ariaLabel||y($e).label)),en(()=>Dn(zt,"title",y($e).tooltip||y($e).label)),en(()=>Dn(zt,"disabled",y($e).disabled)),aa(zt,fr=>f?.(fr)),aa(zt,(fr,Kn)=>p?.(fr,Kn),()=>dr(y($e))),eo(dt),Mf("click",zt,function(...fr){y($e).onClick?.apply(this,fr)}),Qt(Yt,dt)},Lt=Yt=>{var dt=iD();let zt;var fr=rl(dt),Kn=_r=>{var $n=$i(),ri=vi($n),pn=xt=>{var Tr=Ff();Df(Tr,()=>bf(y($e).icon),!0),eo(Tr),Qt(xt,Tr)},Zr=Ze(()=>aS(y($e).icon)),Pr=xt=>{var Tr=dS();en(()=>gi(Tr,"src",y($e).icon)),Qt(xt,Tr)},Or=Ze(()=>lS(y($e).icon)),kr=xt=>{let Tr=Ze(()=>fe(y($e).icon));var ni=$i(),Ln=vi(ni),On=k=>{var B=Ff();Df(B,()=>bf(y(Tr)),!0),eo(B),Qt(k,B)},m=k=>{var B=uS();en(()=>Ha(B,1,`icon icon-${y($e).icon}`,"svelte-1c13522")),Qt(k,B)};Li(Ln,k=>{y(Tr)?k(On):k(m,-1)}),Qt(xt,ni)};Li(ri,xt=>{y(Zr)?xt(pn):y(Or)?xt(Pr,1):xt(kr,-1)}),Qt(_r,$n)};Li(fr,_r=>{y($e).icon&&_r(Kn)}),eo(dt),en(_r=>{zt=Ha(dt,1,"item-toolbar__button svelte-1c13522",null,zt,{"item-toolbar__button--active":_r}),gi(dt,"href",y($e).disabled?void 0:y($e).href),gi(dt,"target",y($e).target),gi(dt,"rel",y($e).rel),gi(dt,"aria-label",y($e).ariaLabel||y($e).label),gi(dt,"title",y($e).tooltip||y($e).label),gi(dt,"aria-disabled",y($e).disabled?"true":void 0)},[()=>dr(y($e))]),Mf("click",dt,_r=>{y($e).disabled&&_r.preventDefault()}),Qt(Yt,dt)},gr=Ze(()=>sS(y($e))),Fr=Yt=>{var dt=oD();let zt;var fr=rl(dt),Kn=_r=>{var $n=$i(),ri=vi($n),pn=xt=>{var Tr=Ff();Df(Tr,()=>bf(y($e).icon),!0),eo(Tr),Qt(xt,Tr)},Zr=Ze(()=>aS(y($e).icon)),Pr=xt=>{var Tr=dS();en(()=>gi(Tr,"src",y($e).icon)),Qt(xt,Tr)},Or=Ze(()=>lS(y($e).icon)),kr=xt=>{let Tr=Ze(()=>fe(y($e).icon));var ni=$i(),Ln=vi(ni),On=k=>{var B=Ff();Df(B,()=>bf(y(Tr)),!0),eo(B),Qt(k,B)},m=k=>{var B=uS();en(()=>Ha(B,1,`icon icon-${y($e).icon}`,"svelte-1c13522")),Qt(k,B)};Li(Ln,k=>{y(Tr)?k(On):k(m,-1)}),Qt(xt,ni)};Li(ri,xt=>{y(Zr)?xt(pn):y(Or)?xt(Pr,1):xt(kr,-1)}),Qt(_r,$n)};Li(fr,_r=>{y($e).icon&&_r(Kn)}),eo(dt),en((_r,$n)=>{zt=Ha(dt,1,"item-toolbar__button svelte-1c13522",null,zt,{"item-toolbar__button--active":_r}),gi(dt,"aria-label",y($e).ariaLabel||y($e).label),gi(dt,"aria-pressed",$n),gi(dt,"title",y($e).tooltip||y($e).label),dt.disabled=y($e).disabled},[()=>dr(y($e)),()=>dr(y($e))]),Mf("click",dt,function(..._r){y($e).onClick?.apply(this,_r)}),Qt(Yt,dt)};Li(mr,Yt=>{y(Ir)?Yt(ur):y(gr)?Yt(Lt,1):Yt(Fr,-1)}),Qt(Pt,Br)});var Ee=jc(nr,2);Nf(Ee,17,()=>y(cr),Pt=>Pt.key,(Pt,$e)=>{var wr=$i(),hn=vi(wr),Ir=mr=>{var ur=$i(),Lt=vi(ur);rg(Lt,()=>y(j),gr=>{var Fr=Bf();aa(Fr,(Yt,dt)=>ei?.(Yt,dt),()=>({mounted:y($e),active:y(kt)[y($e).toolId]??!1,runtime:y(X),i18n:y(D)})),Qt(gr,Fr)}),Qt(mr,ur)},Br=mr=>{var ur=Bf();aa(ur,(Lt,gr)=>Wn?.(Lt,gr),()=>y($e).entry),Qt(mr,ur)};Li(hn,mr=>{y($e).entry.shell?mr(Ir):mr(Br,-1)}),Qt(Pt,wr)}),eo(de);var rt=jc(de,2),sr=Pt=>{var $e=sD();let wr;Nf($e,21,()=>y(V),hn=>hn.key,(hn,Ir)=>{var Br=$i(),mr=vi(Br),ur=gr=>{var Fr=$i(),Yt=vi(Fr);rg(Yt,()=>y(j),dt=>{var zt=fS();aa(zt,(fr,Kn)=>ei?.(fr,Kn),()=>({mounted:y(Ir),active:y(kt)[y(Ir).toolId]??!1,runtime:y(X),i18n:y(D)})),Qt(dt,zt)}),Qt(gr,Fr)},Lt=gr=>{var Fr=fS();aa(Fr,(Yt,dt)=>Wn?.(Yt,dt),()=>y(Ir).entry),Qt(gr,Fr)};Li(mr,gr=>{y(Ir).entry.shell?gr(ur):gr(Lt,-1)}),Qt(hn,Br)}),eo($e),en(()=>wr=Ha($e,1,"item-toolbar__controls-row svelte-1c13522",null,wr,{"item-toolbar__controls-row--reserve":y(Ve),"item-toolbar__controls-row--active":y(at),"item-toolbar__controls-row--align-start":y(Rt)})),Qt(Pt,$e)};Li(rt,Pt=>{y(Vr)&&Pt(sr)}),eo(ce),hC(ce,Pt=>bt(ae,Pt),()=>y(ae)),en(()=>{se=Ha(ce,1,`item-toolbar ${K()??""} item-toolbar--${oe()??""}`,"svelte-1c13522",se,{"item-toolbar--top":U()==="top","item-toolbar--right":U()==="right","item-toolbar--bottom":U()==="bottom","item-toolbar--left":U()==="left","item-toolbar--header-overlay-active":y(Rr)}),gi(ce,"data-content-kind",y(Ne)),gi(ce,"data-level",y(xe))}),Mf("focusin",de,Pt=>{y(xe)==="section"&&Pt.target instanceof HTMLElement&&Pt.target.scrollIntoView({block:"nearest",inline:"nearest"})}),Qt(H,ce)};return Li(ti,H=>{r&&H(Qo)}),Qt(e,Cr),um(ta)}dN(["focusin","click"]);rD("pie-item-toolbar",Mb(cD,{level:{attribute:"level",type:"String"},scopeId:{attribute:"scope-id",type:"String"},itemId:{attribute:"item-id",type:"String"},sectionId:{attribute:"section-id",type:"String"},catalogId:{attribute:"catalog-id",type:"String"},tools:{attribute:"tools",type:"String"},contentKind:{attribute:"content-kind",type:"String"},position:{attribute:"position",type:"String"},size:{attribute:"size",type:"String"},language:{attribute:"language",type:"String"},scopeElement:{type:"Object"},toolRegistry:{type:"Object"},item:{type:"Object"},hostButtons:{type:"Object"},class:{}},[],[],{mode:"open"}));var Hf={enabled:!1,maxTries:1,feedback:"correctness",revealOn:"on-try"};function hS(e){if(e==="unlimited")return"unlimited";if(typeof e!="number"||!Number.isFinite(e))return;const t=Math.trunc(e);return t>=1?t:void 0}function pS(e){return e==="none"||e==="correctness"||e==="solution"?e:void 0}function mS(e){return e==="on-try"||e==="on-final-try"?e:void 0}function dD(e,t){const r=typeof t?.enabled=="boolean"?t.enabled:typeof e?.enabled=="boolean"?e.enabled:Hf.enabled,n=hS(t?.maxTries)??hS(e?.maxTries)??Hf.maxTries,i=pS(t?.feedback)??pS(e?.feedback)??Hf.feedback,o=mS(t?.revealOn)??mS(e?.revealOn)??Hf.revealOn;return{enabled:r,maxTries:n,feedback:i,revealOn:o==="on-final-try"&&n==="unlimited"?"on-try":o}}function uD(e){const t={};for(const r of e.items)r?.identifier&&(t[r.identifier]=dD(e.sectionPolicy,r.policy));return t}function fD(e){return Object.values(e).some(t=>t.enabled)}var hD=1e-9;function pD(e){return!!e&&typeof e.score=="number"&&Number.isFinite(e.score)}function gS(e){const t=e.max;return typeof t=="number"&&Number.isFinite(t)&&t>0?t:1}function vS(e){const t=e.filter(r=>!!r&&typeof r=="object");return t.length>0?t:void 0}function mD(e,t){return t<=0?"unknown":e+hD>=t?"correct":e<=0?"incorrect":"partial"}function gD(e){const t=Array.isArray(e)?e:[],r=t.filter(pD),n=t.length;if(r.length===0)return{correctness:"unknown",scoredElementCount:0,totalElementCount:n,elementOutcomes:vS(t)};let i,o;if(r.length===1){const a=r[0];o=gS(a),i=a.score}else o=1,i=r.reduce((a,l)=>a+l.score/gS(l),0)/r.length;const s=Math.min(Math.max(i,0),o);return{correctness:mD(s,o),points:s,max:o,scoredElementCount:r.length,totalElementCount:n,elementOutcomes:vS(t)}}function yC(e){return{version:1,itemIdentifier:e,tryCount:0,revealed:!1}}function Ob(e,t){return e.maxTries==="unlimited"?"unlimited":Math.max(0,e.maxTries-t)}function Nb(e){return e==="unlimited"||e>0}function vD(e,t){return e.feedback==="none"?!1:e.revealOn==="on-try"||e.maxTries==="unlimited"?!0:t>=e.maxTries}function yD(e){const t=e.state??yC(e.itemIdentifier);if(!e.policy.enabled)return t;const r=Ob(e.policy,t.tryCount);if(t.revealed||!Nb(r))return t;const n=t.tryCount+1;return{...t,version:1,itemIdentifier:e.itemIdentifier,tryCount:n,revealed:vD(e.policy,n),lastOutcome:e.outcome,firstCorrectTry:t.firstCorrectTry??(e.outcome.correctness==="correct"?n:void 0)}}function bD(e){const t=e.state;return!t||!e.policy.enabled||!t.revealed||!Nb(Ob(e.policy,t.tryCount))?t:{...t,revealed:!1,revealOverride:void 0}}function wD(e){const t=e.state??yC(e.itemIdentifier);return!e.policy.enabled||t.revealed&&t.revealOverride===e.feedback?t:{...t,revealed:!0,revealOverride:e.feedback}}function SD(e){const t=e.state;return!t||!e.policy.enabled||!t.revealed&&!t.revealOverride?t:{...t,revealed:!1,revealOverride:void 0}}function ID(e,t,r){const n=r??e.feedback;if(!(!t||n==="none"))return{mode:"evaluate",role:n==="solution"?"instructor":"student"}}function kD(e){const{policy:t}=e,r=e.state?.tryCount??0,n=e.state?.revealed===!0,i=Ob(t,r),o=t.enabled&&Nb(i);return{enabled:t.enabled,tryCount:r,triesRemaining:i,canCheck:o&&!n,canRetry:o&&n,revealed:n,envOverride:t.enabled?ID(t,n,e.state?.revealOverride):void 0,lastOutcome:e.state?.lastOutcome}}function TD(e){const t=e.itemIdentifiers??[],r=t.length;let n=0,i=0,o=0,s=0;for(const l of t){const d=e.states?.[l];d&&(d.tryCount>0&&(o+=1),d.lastOutcome?.correctness==="unknown"&&(n+=1),typeof d.firstCorrectTry=="number"&&(i+=1,s+=d.firstCorrectTry))}const a=Math.max(0,r-n);return{version:1,totalItems:r,scorableItems:a,masteredItems:i,triedItems:o,averageTriesToMastery:i>0?s/i:void 0,complete:a>0&&i===a}}var ED=["correct","partial","incorrect","unknown"];function Ov(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function pp(e){const t=Ov(e);if(t===void 0)return;const r=Math.trunc(t);return r>=0?r:void 0}function CD(e){if(!e||typeof e!="object")return;const t=e,r=ED.find(n=>n===t.correctness);if(r)return{correctness:r,points:Ov(t.points),max:Ov(t.max),scoredElementCount:pp(t.scoredElementCount)??0,totalElementCount:pp(t.totalElementCount)??0,elementOutcomes:xD(t.elementOutcomes)}}function xD(e){if(!Array.isArray(e))return;const t=e.filter(r=>!!r&&typeof r=="object"&&!Array.isArray(r));return t.length>0?t:void 0}function RD(e){return e==="correctness"||e==="solution"||e==="none"?e:void 0}function _D(e,t){if(!t||typeof t!="object")return null;const r=t;if(r.version!==1)return null;const n=pp(r.tryCount);if(n===void 0)return null;const i=pp(r.firstCorrectTry);return{version:1,itemIdentifier:e,tryCount:n,revealed:r.revealed===!0,lastOutcome:CD(r.lastOutcome),firstCorrectTry:i!==void 0&&i>=1?i:void 0,revealOverride:RD(r.revealOverride)}}function PD(e){return{version:1,items:{...e}}}function AD(e){const{slice:t}=e;if(!t||typeof t!="object")return null;const r=t;if(r.version!==1||!r.items||typeof r.items!="object")return null;const n=new Set(e.allowedItemIdentifiers??[]),i={};for(const[o,s]of Object.entries(r.items)){if(!n.has(o))continue;const a=_D(o,s);a&&(i[o]=a)}return i}var MD=Object.freeze({id:"",data:Object.freeze([])}),bC={section:null,assessmentItemRefs:[],passages:[],items:[],rubricBlocks:[],instructions:[],renderables:[],currentItemIndex:0,currentItem:null,isPageMode:!1,itemSessionsByItemId:{},testAttemptSession:null,itemViewModels:[],formative:null};function wC(e,t){return IC(e,t)?.canonicalItemId||""}function SC(e,t){return IC(e,t)?.session}function $D(e,t){return SC(e,t)||MD}function IC(e,t){const r=t.id||"";if(r)return e.itemViewModels.find(n=>n.itemId===r||n.canonicalItemId===r||n.item?.id===r)}if(typeof window<"u"){var yS,bS;((yS=(bS=window).__svelte??(bS.__svelte={})).v??(yS.v=new Set)).add("5")}var Ul={},xn=Symbol("uninitialized"),LD="http://www.w3.org/2000/svg",OD="http://www.w3.org/1998/Math/MathML",ND=Array.isArray,DD=Array.prototype.indexOf,Nv=Array.prototype.includes,jD=Array.from,mp=Object.keys,Su=Object.defineProperty,Cl=Object.getOwnPropertyDescriptor,BD=Object.prototype,FD=Array.prototype,HD=Object.getPrototypeOf,wS=Object.isExtensible,zD=()=>{};function WD(e){for(var t=0;t<e.length;t++)e[t]()}function kC(){var e,t;return{promise:new Promise((r,n)=>{e=r,t=n}),resolve:e,reject:t}}var po=1024,Jo=2048,sc=4096,Db=8192,UD=16384,jb=32768,SS=1<<25,Bb=65536,md=1<<19,qD=1<<20,IS=1<<21,VD=1<<22,gp=1<<23,ru=Symbol("$state"),TC=Symbol("component"),EC=Symbol("legacy props"),GD=Symbol("attributes"),Dv=Symbol("class"),KD=Symbol("style"),Sh=Symbol("text"),nf=new class extends Error{constructor(...e){super(...e),Te(this,"name","StaleReactionError"),Te(this,"message","The reaction that called `getAbortSignal()` was re-run or destroyed")}},_V=!!globalThis.document?.contentType&&globalThis.document.contentType.includes("xml");function XD(){console.warn("https://svelte.dev/e/derived_inert")}function of(e){console.warn("https://svelte.dev/e/hydration_mismatch")}function ZD(){console.warn("https://svelte.dev/e/svelte_boundary_reset_noop")}var Dr=!1;function Lc(e){Dr=e}var Kr;function mo(e){if(e===null)throw of(),Ul;return Kr=e}function Qc(){return mo(Qs(Kr))}function fs(e){if(Dr){if(Qs(Kr)!==null)throw of(),Ul;Kr=e}}function YD(e=1){if(Dr){for(var t=e,r=Kr;t--;)r=Qs(r);Kr=r}}function CC(e=!0){for(var t=0,r=Kr;;){if(r.nodeType===8){var n=r.data;if(n==="]"){if(t===0)return r;t-=1}else(n==="["||n==="[!"||n[0]==="["&&!isNaN(Number(n.slice(1))))&&(t+=1)}var i=Qs(r);e&&r.remove(),r=i}}function JD(e){if(!e||e.nodeType!==8)throw of(),Ul;return e.data}function xC(e){return e===this.v}function QD(e,t){return e!=e?t==t:e!==t||e!==null&&typeof e=="object"||typeof e=="function"}function RC(e){return!QD(e,this.v)}function _C(e){throw new Error("https://svelte.dev/e/lifecycle_outside_component")}function e5(){throw new Error("https://svelte.dev/e/async_derived_orphan")}function t5(e){throw new Error("https://svelte.dev/e/effect_in_teardown")}function r5(){throw new Error("https://svelte.dev/e/effect_in_unowned_derived")}function n5(e){throw new Error("https://svelte.dev/e/effect_orphan")}function i5(){throw new Error("https://svelte.dev/e/effect_update_depth_exceeded")}function o5(){throw new Error("https://svelte.dev/e/hydration_failed")}function s5(e){throw new Error("https://svelte.dev/e/props_invalid_value")}function a5(){throw new Error("https://svelte.dev/e/state_descriptors_fixed")}function l5(){throw new Error("https://svelte.dev/e/state_prototype_fixed")}function c5(){throw new Error("https://svelte.dev/e/state_unsafe_mutation")}function d5(){throw new Error("https://svelte.dev/e/svelte_boundary_reset_onerror")}var sf=!1,gd=!1;function u5(){gd=!0}var Xr=null;function ed(e){Xr=e}function mm(e,t=!1,r){Xr={p:Xr,i:!1,c:null,e:null,s:e,x:null,r:Vt,l:gd&&!t?{s:null,u:null,$:[]}:null}}function gm(e){var t=Xr,r=t.e;if(r!==null){t.e=null;for(var n of r)XC(n)}return e!==void 0&&(t.x=e),t.i=!0,Xr=t.p,Fb(e)}function Fb(e={}){return Su(e,TC,{value:!0}),e}function vd(){return!gd||Xr!==null&&Xr.l===null}var ul=[];function PC(){var e=ul;ul=[],WD(e)}function ql(e){if(ul.length===0&&!nu){var t=ul;queueMicrotask(()=>{t===ul&&PC()})}ul.push(e)}function f5(){for(;ul.length>0;)PC()}var h5=~(Jo|sc|po);function wn(e,t){e.f=e.f&h5|t}function Hb(e){(e.f&512)!==0||e.deps===null?wn(e,po):wn(e,sc)}function AC(e,t,r){(e.f&2048)!==0?t.add(e):e.f&4096&&r.add(e),wn(e,po)}function vm(e){var t=ar,r=Vt;go(null),Is(null);try{return e()}finally{go(t),Is(r)}}function p5(e,t,r,n){const i=vd()?Iu:$C;var o=e.filter(p=>!p.settled),s=t.map(i);if(r.length===0&&o.length===0){n(s);return}var a=Vt,l=m5(),d=o.length===1?o[0].promise:o.length>1?Promise.all(o.map(p=>p.promise)):null;function c(p){if((a.f&16384)===0){l();try{n([...s,...p])}catch(g){Ss(g,a)}vp()}}var u=MC();if(r.length===0){d.then(()=>c([])).finally(u);return}function f(){Promise.all(r.map(p=>g5(p))).then(c).catch(p=>Ss(p,a)).finally(u)}d?d.then(()=>{l(),f(),vp()}):f()}function m5(){var e=Vt,t=ar,r=Xr,n=rr;return function(i=!0){Is(e),go(t),ed(r),i&&!(e.f&16384)&&(n?.activate(),n?.apply())}}function vp(e=!0){Is(null),go(null),ed(null),e&&rr?.deactivate()}function MC(){var e=Vt,t=e.b,r=rr,n=!!t?.is_rendered();return t?.update_pending_count(1,r),r.increment(n,e),()=>{t?.update_pending_count(-1,r),r.decrement(n,e)}}function Iu(e){var t=2|Jo;return Vt!==null&&(Vt.f|=md),{ctx:Xr,deps:null,effects:null,equals:xC,f:t,fn:e,reactions:null,rv:0,v:xn,wv:0,parent:Vt,ac:null}}var Vd=Symbol("obsolete");function g5(e,t,r){let n=Vt;n===null&&e5();var i=void 0,o=af(xn),s=!ar,a=new Set;return O5(()=>{var l=Vt,d=kC();i=d.promise;try{Promise.resolve(e()).then(d.resolve,p=>{p!==nf&&d.reject(p)}).finally(vp)}catch(p){d.reject(p),vp()}var c=rr;if(s){if((l.f&32768)!==0)var u=MC();if(n.b?.is_rendered())c.async_deriveds.get(l)?.reject(Vd);else for(const p of a.values())p.reject(Vd);a.add(d),c.async_deriveds.set(l,d)}const f=(p,g=void 0)=>{u?.(),a.delete(d),g!==Vd&&(c.activate(),g?(o.f|=gp,kp(o,g)):(o.f&8388608&&(o.f^=gp),kp(o,p)),c.deactivate())};d.promise.then(f,p=>f(null,p||"unknown"))}),M5(()=>{for(const l of a)l.reject(Vd)}),new Promise(l=>{function d(c){function u(){c===i?l(o):d(i)}c.then(u,u)}d(i)})}function Et(e){const t=Iu(e);return nx(t),t}function $C(e){const t=Iu(e);return t.equals=RC,t}function v5(e){var t=e.effects;if(t!==null){e.effects=null;for(var r=0;r<t.length;r+=1)Ei(t[r])}}function zb(e){var t,r=Vt,n=e.parent;if(!Vs&&n!==null&&e.v!==xn&&(n.f&24576)!==0)return XD(),e.v;Is(n);try{v5(e),t=ax(e)}finally{Is(r)}return t}function LC(e){var t=zb(e);if(!e.equals(t)&&(e.wv=ox(),(!rr?.is_fork||e.deps===null)&&(rr!==null?(rr.capture(e,t,!0),Bv?.capture(e,t,!0)):e.v=t,e.deps===null))){wn(e,po);return}Vs||(ci!==null?(Ub()||rr?.is_fork)&&ci.set(e,t):Hb(e))}function y5(e){if(e.effects!==null)for(const t of e.effects)(t.teardown||t.ac)&&(t.teardown?.(),t.ac!==null&&vm(()=>{t.ac.abort(nf),t.ac=null}),t.fn!==null&&(t.teardown=zD),Tu(t,0),Gb(t))}function OC(e){if(e.effects!==null)for(const t of e.effects)t.teardown&&t.fn!==null&&rd(t)}function NC(e,t){if(t.has(e))throw new TypeError("Cannot initialize the same private elements twice on an object")}function Wb(e,t){NC(e,t),t.add(e)}function Mt(e,t,r){NC(e,t),t.set(e,r)}function Wt(e,t,r){if(typeof e=="function"?e===t:e.has(t))return arguments.length<3?t:r;throw new TypeError("Private element is not present on this object")}function St(e,t,r){return e.set(Wt(e,t),r),r}function Q(e,t){return e.get(Wt(e,t))}var DC,jv=null,Cc=null,rr=null,Bv=null,ci=null,Fv=null,nu=!1,lg=!1,ku=null,yp=null,jC=0,b5=1,Hv=new WeakMap,xl=new WeakMap,Oc=new WeakMap,bp=new WeakMap,zf=new WeakMap,xc=new WeakMap,Ja=new WeakMap,Gd=new WeakMap,cs=new WeakMap,kS=new WeakMap,td=new WeakMap,Fs=new WeakMap,ga=new WeakMap,cg=new WeakMap,Wf=new WeakMap,En=new WeakSet,ac=class BC{constructor(){Wb(this,En),Te(this,"id",b5++),Mt(this,Hv,!1),Te(this,"linked",!0),Mt(this,xl,null),Mt(this,Oc,null),Te(this,"async_deriveds",new Map),Te(this,"current",new Map),Te(this,"previous",new Map),Mt(this,bp,new Set),Mt(this,zf,new Set),Mt(this,xc,0),Mt(this,Ja,new Map),Mt(this,Gd,null),Mt(this,cs,[]),Mt(this,kS,[]),Mt(this,td,new Set),Mt(this,Fs,new Set),Mt(this,ga,new Map),Mt(this,cg,new Set),Te(this,"is_fork",!1),Mt(this,Wf,!1),Cc===null?jv=Cc=this:(St(Oc,Cc,this),St(xl,this,Cc)),Cc=this}skip_effect(t){Q(ga,this).has(t)||Q(ga,this).set(t,{d:[],m:[]}),Q(cg,this).delete(t)}unskip_effect(t,r=n=>this.schedule(n)){var n=Q(ga,this).get(t);if(n){Q(ga,this).delete(t);for(var i of n.d)wn(i,Jo),r(i);for(i of n.m)wn(i,sc),r(i)}Q(cg,this).add(t)}capture(t,r,n=!1){t.v!==xn&&!this.previous.has(t)&&this.previous.set(t,t.v),!(t.f&8388608)&&(this.current.set(t,[r,n]),ci?.set(t,r)),this.is_fork||(t.v=r)}activate(){rr=this}deactivate(){rr=null,ci=null}flush(){try{lg=!0,rr=this,Wt(En,this,wp).call(this)}finally{jC=0,Fv=null,ku=null,yp=null,lg=!1,rr=null,ci=null,ws.clear()}}discard(){for(const t of Q(zf,this))t(this);Q(zf,this).clear();for(const t of this.async_deriveds.values())t.reject(Vd);Wt(En,this,Sp).call(this),Q(Gd,this)?.resolve()}register_created_effect(t){Q(kS,this).push(t)}increment(t,r){if(St(xc,this,Q(xc,this)+1),t){let n=Q(Ja,this).get(r)??0;Q(Ja,this).set(r,n+1)}}decrement(t,r){if(St(xc,this,Q(xc,this)-1),t){let n=Q(Ja,this).get(r)??0;n===1?Q(Ja,this).delete(r):Q(Ja,this).set(r,n-1)}Q(Wf,this)||(St(Wf,this,!0),ql(()=>{St(Wf,this,!1),this.linked&&this.flush()}))}transfer_effects(t,r){for(const n of t)Q(td,this).add(n);for(const n of r)Q(Fs,this).add(n);t.clear(),r.clear()}oncommit(t){Q(bp,this).add(t)}ondiscard(t){Q(zf,this).add(t)}settled(){return(Q(Gd,this)??St(Gd,this,kC())).promise}static ensure(){if(rr===null){const t=rr=new BC;!lg&&!nu&&ql(()=>{Q(Hv,t)||t.flush()})}return rr}apply(){if(!sf||!this.is_fork&&Q(xl,this)===null&&Q(Oc,this)===null){ci=null;return}ci=new Map;for(const[r,[n]]of this.current)ci.set(r,n);for(let r=jv;r!==null;r=Q(Oc,r))if(!(r===this||r.is_fork)){var t=!1;if(r.id<this.id){for(const[n,[,i]]of r.current)if(!i&&this.current.has(n)){t=!0;break}}if(!t)for(const[n,i]of r.previous)ci.has(n)||ci.set(n,i)}}schedule(t){if(Fv=t,t.b?.is_pending&&(t.f&16777228)!==0&&(t.f&32768)===0){t.b.defer_effect(t);return}Q(cs,this).push(t)}};DC=ac;function TS(){if(this.is_fork)return!0;for(const r of Q(Ja,this).keys()){for(var e=r,t=!1;e.parent!==null;){if(Q(ga,this).has(e)){t=!0;break}e=e.parent}if(!t)return!0}return!1}function w5(){var e=[];for(const i of Q(cs,this))if(!((i.f&16384)!==0||(i.f&6144)===0)){for(var t=i,r=!1;t.parent!==null;){t=t.parent;var n=t.f;if((n&96)!==0){if((n&1024)===0){r=!0;break}t.f^=po}}r||e.push(t)}return St(cs,this,[]),e}function wp(){St(Hv,this,!0);for(const s of Q(td,this))Q(Fs,this).delete(s),wn(s,Jo),this.schedule(s);for(const s of Q(Fs,this))wn(s,sc),this.schedule(s);this.apply();for(var e=ku=[],t=[],r=yp=[];Q(cs,this).length>0;){jC++>1e3&&(Wt(En,this,Sp).call(this),T5());for(const s of Wt(En,this,w5).call(this))try{Wt(En,this,S5).call(this,s,e,t)}catch(a){throw zC(s),Wt(En,this,TS).call(this)||this.discard(),a}}if(rr=null,r.length>0){var n=DC.ensure();for(const s of r)n.schedule(s)}if(ku=null,yp=null,Wt(En,this,TS).call(this)){Wt(En,this,Uf).call(this,t),Wt(En,this,Uf).call(this,e);for(const[s,a]of Q(ga,this))HC(s,a);r.length>0&&Wt(En,rr,wp).call(rr);return}const i=Wt(En,this,I5).call(this);if(i){Wt(En,this,Uf).call(this,t),Wt(En,this,Uf).call(this,e),Wt(En,i,k5).call(i,this);return}Q(td,this).clear(),Q(Fs,this).clear();for(const s of Q(bp,this))s(this);Q(bp,this).clear(),Bv=this,ES(t),ES(e),Bv=null,Q(Gd,this)?.resolve();var o=rr;if(Q(xc,this)===0&&(Q(cs,this).length===0||o!==null)&&Wt(En,this,Sp).call(this),Q(cs,this).length>0)if(o!==null){for(const s of Q(cs,this))Q(cs,o).push(s);St(cs,this,[])}else o=this;o!==null&&(ws.clear(),Wt(En,o,wp).call(o))}function S5(e,t,r){e.f^=po;for(var n=e.first;n!==null;){var i=n.f,o=(i&96)!==0;if(!(o&&(i&1024)!==0||(i&8192)!==0||Q(ga,this).has(n))&&n.fn!==null){o?n.f^=po:(i&4)!==0?t.push(n):sf&&(i&16777224)!==0?r.push(n):cf(n)&&(i&16&&Q(Fs,this).add(n),rd(n));var s=n.first;if(s!==null){n=s;continue}}for(;n!==null;){var a=n.next;if(a!==null){n=a;break}n=n.parent}}}function I5(){for(var e=Q(xl,this);e!==null;){if(!e.is_fork){for(const[t,[,r]]of this.current)if(e.current.has(t)&&!r)return e}e=Q(xl,e)}return null}function k5(e){for(const[r,n]of e.current)!this.previous.has(r)&&e.previous.has(r)&&this.previous.set(r,e.previous.get(r)),this.current.set(r,n);for(const[r,n]of e.async_deriveds){const i=this.async_deriveds.get(r);i&&n.promise.then(i.resolve).catch(i.reject)}e.async_deriveds.clear(),this.transfer_effects(Q(td,e),Q(Fs,e));const t=r=>{var n=r.reactions;if(n!==null&&!((r.f&2)!==0&&(r.f&6144)===0))for(const s of n){var i=s.f;if((i&2)!==0)t(s);else{var o=s;i&4194320&&!this.async_deriveds.has(o)&&(Q(Fs,this).delete(o),wn(o,Jo),this.schedule(o))}}};for(const r of this.current.keys())t(r);this.oncommit(()=>e.discard()),Wt(En,e,Sp).call(e),rr=this,Wt(En,this,wp).call(this)}function Uf(e){for(var t=0;t<e.length;t+=1)AC(e[t],Q(td,this),Q(Fs,this))}function Sp(){if(this.linked){var e=Q(xl,this),t=Q(Oc,this);e===null?jv=t:St(Oc,e,t),t===null?Cc=e:St(xl,t,e),this.linked=!1}}function Xe(e){var t=nu;nu=!0;try{var r;for(e&&(rr!==null&&!rr.is_fork&&rr.flush(),r=e());;){if(f5(),rr===null)return r;rr.flush()}}finally{nu=t}}function T5(){try{i5()}catch(e){Ss(e,Fv)}}var ls=null;function ES(e){var t=e.length;if(t!==0){for(var r=0;r<t;){var n=e[r++];if((n.f&24576)===0&&cf(n)&&(ls=new Set,rd(n),n.deps===null&&n.first===null&&n.nodes===null&&n.teardown===null&&n.ac===null&&QC(n),ls?.size>0)){ws.clear();for(const i of ls){if((i.f&24576)!==0)continue;const o=[i];let s=i.parent;for(;s!==null;)ls.has(s)&&(ls.delete(s),o.push(s)),s=s.parent;for(let a=o.length-1;a>=0;a--){const l=o[a];!(l.f&24576)&&rd(l)}}ls.clear()}}ls=null}}function FC(e){rr.schedule(e)}function HC(e,t){if(!((e.f&32)!==0&&(e.f&1024)!==0)){(e.f&2048)!==0?t.d.push(e):e.f&4096&&t.m.push(e),wn(e,po);for(var r=e.first;r!==null;)HC(r,t),r=r.next}}function zC(e){wn(e,po);for(var t=e.first;t!==null;)zC(t),t=t.next}var Ip=new Set,ws=new Map,WC=!1;function af(e,t){return{f:0,v:e,reactions:null,equals:xC,rv:0,wv:0}}function er(e,t){const r=af(e,t);return nx(r),r}function E5(e,t=!1,r=!0){const n=af(e);if(t||(n.equals=RC),gd&&r&&Xr!==null&&Xr.l!==null){var i;((i=Xr.l).s??(i.s=[])).push(n)}return n}function Fe(e,t,r=!1){return ar!==null&&(!Lo||ar.f&131072)&&vd()&&ar.f&4325394&&(Wo===null||!Wo.has(e))&&c5(),kp(e,r?Nc(t):t,yp)}var nl=null,zv=0;function kp(e,t,r=null){if(!e.equals(t)){Vs?ws.set(e,t):ws.has(e)||ws.set(e,e.v);var n=ac.ensure();if(n.capture(e,t),(e.f&2)!==0){const i=e;e.f&2048&&zb(i),ci===null&&Hb(i)}e.wv=ox(),nl=null,zv=0,UC(e,Jo,r),nl=null,vd()&&Vt!==null&&Vt.f&1024&&!(Vt.f&96)&&(no===null?j5([e]):no.push(e)),!n.is_fork&&Ip.size>0&&!WC&&C5()}return t}function C5(){WC=!1;for(const e of Ip){e.f&1024&&wn(e,sc);let t;try{t=cf(e)}catch{t=!0}t&&rd(e)}Ip.clear()}function iu(e){Fe(e,e.v+1)}function UC(e,t,r){var n=e.reactions;if(n!==null){var i=vd(),o=n.length;if(zv+=o,zv>1e5&&nl===null&&(nl=new Set),nl!==null){if(nl.has(e))return;nl.add(e)}for(var s=0;s<o;s++){var a=n[s],l=a.f;if(!(!i&&a===Vt)){var d=(l&Jo)===0;if(d&&wn(a,t),(l&131072)!==0)Ip.add(a);else if((l&2)!==0){var c=a;ci?.delete(c),UC(c,sc,r)}else if(d){var u=a;l&16&&ls!==null&&ls.add(u),r!==null?r.push(u):FC(u)}}}}}function Nc(e){if(typeof e!="object"||e===null||ru in e||TC in e)return e;const t=HD(e);if(t!==BD&&t!==FD)return e;var r=new Map,n=ND(e),i=er(0),o=null,s=Rl,a=l=>{if(Rl===s)return l();var d=ar,c=Rl;go(null),_S(s);var u=l();return go(d),_S(c),u};return n&&r.set("length",er(e.length,o)),new Proxy(e,{defineProperty(l,d,c){(!("value"in c)||c.configurable===!1||c.enumerable===!1||c.writable===!1)&&a5();var u=r.get(d);return u===void 0?a(()=>{var f=er(c.value,o);return r.set(d,f),f}):Fe(u,c.value,!0),!0},deleteProperty(l,d){var c=r.get(d);if(c===void 0){if(d in l){const u=a(()=>er(xn,o));r.set(d,u),iu(i)}}else Fe(c,xn),iu(i);return!0},get(l,d,c){if(d===ru)return e;var u=r.get(d),f=d in l;if(u===void 0&&(!f||Cl(l,d)?.writable)&&(u=a(()=>er(Nc(f?l[d]:xn),o)),r.set(d,u)),u!==void 0){var p=A(u);return p===xn?void 0:p}return Reflect.get(l,d,c)},getOwnPropertyDescriptor(l,d){this.has?.(l,d);var c=Reflect.getOwnPropertyDescriptor(l,d),u=r.get(d);if(u!==void 0){var f=A(u);if(f===xn)return;if(c&&"value"in c)c.value=f;else return{enumerable:!0,configurable:!0,value:f,writable:!0}}return c},has(l,d){if(d===ru)return!0;var c=r.get(d),u=c!==void 0&&c.v!==xn||Reflect.has(l,d);return(c!==void 0||Vt!==null&&(!u||Cl(l,d)?.writable))&&(c===void 0&&(c=a(()=>er(u?Nc(l[d]):xn,o)),r.set(d,c)),A(c)===xn)?!1:u},set(l,d,c,u){var f=r.get(d),p=d in l;if(n&&d==="length")for(var g=c;g<f.v;g+=1){var v=r.get(g+"");v!==void 0?Fe(v,xn):g in l&&(v=a(()=>er(xn,o)),r.set(g+"",v))}if(f===void 0)(!p||Cl(l,d)?.writable)&&(f=a(()=>er(void 0,o)),Fe(f,Nc(c)),r.set(d,f));else{p=f.v!==xn;var b=a(()=>Nc(c));Fe(f,b)}var w=Reflect.getOwnPropertyDescriptor(l,d);if(w?.set&&w.set.call(u,c),!p){if(n&&typeof d=="string"){var I=r.get("length"),x=Number(d);Number.isInteger(x)&&x>=I.v&&Fe(I,x+1)}iu(i)}return!0},ownKeys(l){A(i);var d=Reflect.ownKeys(l).filter(f=>{var p=r.get(f);return p===void 0||p.v!==xn});for(var[c,u]of r)u.v!==xn&&!(c in l)&&d.push(c);return d},setPrototypeOf(){l5()}})}var CS,qC,VC,GC;function Wv(){if(CS===void 0){CS=window,qC=/Firefox/.test(navigator.userAgent);var e=Element.prototype,t=Node.prototype,r=Text.prototype;VC=Cl(t,"firstChild").get,GC=Cl(t,"nextSibling").get,wS(e)&&(e[Dv]=void 0,e[GD]=null,e[KD]=void 0,e.__e=void 0),wS(r)&&(r[Sh]=void 0)}}function Vl(e=""){return document.createTextNode(e)}function xo(e){return VC.call(e)}function Qs(e){return GC.call(e)}function va(e,t){if(!Dr)return xo(e);var r=xo(Kr);if(r===null)r=Kr.appendChild(Vl());else if(t&&r.nodeType!==3){var n=Vl();return r?.before(n),mo(n),n}return t&&KC(r),mo(r),r}function fl(e,t=!1){if(!Dr)return xo(e);var r=va(e,t);return fs(e),r}function Dc(e,t=1,r=!1){let n=Dr?Kr:e;for(var i;t--;)i=n,n=Qs(n);if(!Dr)return n;if(r){if(n?.nodeType!==3){var o=Vl();return n===null?i?.after(o):n.before(o),mo(o),o}KC(n)}return mo(n),n}function x5(e){e.textContent=""}function R5(){return!sf||ls!==null?!1:(Vt.f&jb)!==0}function ym(e,t,r){return t==null||t==="http://www.w3.org/1999/xhtml"?r?document.createElement(e,{is:r}):document.createElement(e):r?document.createElementNS(t,e,{is:r}):document.createElementNS(t,e)}function KC(e){if(e.nodeValue.length<65536)return;let t=e.nextSibling;for(;t!==null&&t.nodeType===3;)t.remove(),e.nodeValue+=t.nodeValue,t=e.nextSibling}function _5(e){var t=Vt;if(t===null)return ar.f|=gp,e;if((t.f&32768)===0&&(t.f&4)===0)throw e;Ss(e,t)}function Ss(e,t){if(!(t!==null&&(t.f&16384)!==0)){for(;t!==null;){if((t.f&128)!==0&&(t.f&33570816)===0){if((t.f&32768)===0)throw e;try{t.b.error(e);return}catch(r){e=r}}t=t.parent}throw e}}function P5(e){Vt===null&&(ar===null&&n5(e),r5()),Vs&&t5(e)}function A5(e,t){var r=t.last;r===null?t.last=t.first=e:(r.next=e,e.prev=r,t.last=e)}function Cs(e,t){var r=Vt;r!==null&&r.f&8192&&(e|=Db);var n={ctx:Xr,deps:null,nodes:null,f:e|Jo|512,first:null,fn:t,last:null,next:null,parent:r,b:r&&r.b,prev:null,teardown:null,wv:0,ac:null};rr?.register_created_effect(n);var i=n;if((e&4)!==0)ku!==null?ku.push(n):ac.ensure().schedule(n);else if(t!==null){try{rd(n)}catch(s){throw Ei(n),s}i.deps===null&&i.teardown===null&&i.nodes===null&&i.first===i.last&&!(i.f&524288)&&(i=i.first,e&16&&e&65536&&i!==null&&(i.f|=Bb))}if(i!==null&&(i.parent=r,r!==null&&A5(i,r),ar!==null&&(ar.f&2)!==0&&(e&64)===0)){var o=ar;(o.effects??(o.effects=[])).push(i)}return n}function Ub(){return ar!==null&&!Lo}function M5(e){const t=Cs(8,null);return wn(t,po),t.teardown=e,t}function zr(e){P5("$effect");var t=Vt.f;if(!ar&&(t&32)!==0&&Xr!==null&&!Xr.i){var r=Xr;(r.e??(r.e=[])).push(e)}else return XC(e)}function XC(e){return Cs(4|qD,e)}function $5(e){ac.ensure();const t=Cs(64|md,e);return()=>{Ei(t)}}function L5(e){ac.ensure();const t=Cs(64|md,e);return(r={})=>new Promise(n=>{r.outro?lf(t,()=>{Ei(t),n(void 0)}):(Ei(t),n(void 0))})}function ZC(e){return Cs(4,e)}function O5(e){return Cs(VD|md,e)}function qb(e,t=0){return Cs(8|t,e)}function Ro(e,t=[],r=[],n=[]){p5(n,t,r,i=>{Cs(8,()=>{e(...i.map(A))})})}function Vb(e,t=0){return Cs(16|t,e)}function qs(e){return Cs(32|md,e)}function YC(e){var t=e.teardown;if(t!==null){const r=Vs,n=ar;RS(!0),go(null);try{t.call(null)}catch(i){Ss(i,e.parent)}finally{RS(r),go(n)}}}function Gb(e,t=!1){var r=e.first;for(e.first=e.last=null;r!==null;){const i=r.ac;i!==null&&vm(()=>{i.abort(nf)});var n=r.next;(r.f&64)!==0?r.parent=null:Ei(r,t),r=n}}function N5(e){for(var t=e.first;t!==null;){var r=t.next;!(t.f&32)&&Ei(t),t=r}}function Ei(e,t=!0){var r=!1;(t||e.f&262144)&&e.nodes!==null&&e.nodes.end!==null&&(JC(e.nodes.start,e.nodes.end),r=!0),e.f|=SS,Gb(e,t&&!r),Tu(e,0);var n=e.nodes&&e.nodes.t;if(n!==null)for(const o of n)o.stop();YC(e),e.f^=SS,e.f|=UD;var i=e.parent;i!==null&&i.first!==null&&QC(e),e.next=e.prev=e.teardown=e.ctx=e.deps=e.fn=e.nodes=e.ac=e.b=null}function JC(e,t){for(;e!==null;){var r=e===t?null:Qs(e);e.remove(),e=r}}function QC(e){var t=e.parent,r=e.prev,n=e.next;r!==null&&(r.next=n),n!==null&&(n.prev=r),t!==null&&(t.first===e&&(t.first=n),t.last===e&&(t.last=r))}function lf(e,t,r=!0){var n=[];e.f|=256,ex(e,n,!0);var i=()=>{r&&Ei(e),t&&t()},o=n.length;if(o>0){var s=()=>--o||i();for(var a of n)a.out(s)}else i()}function ex(e,t,r){if((e.f&8192)===0){e.f^=Db;var n=e.nodes&&e.nodes.t;if(n!==null)for(const a of n)(a.is_global||r)&&t.push(a);for(var i=e.first;i!==null;){var o=i.next;if((i.f&64)===0){var s=(i.f&65536)!==0||(i.f&32)!==0&&(e.f&16)!==0;ex(i,t,s?r:!1)}i=o}}}function xS(e){e.f&=-257,tx(e,!0)}function tx(e,t){if((e.f&256)===0&&(e.f&8192)!==0){e.f^=Db,!(e.f&1024)&&(wn(e,Jo),ac.ensure().schedule(e));for(var r=e.first;r!==null;){var n=r.next,i=(r.f&65536)!==0||(r.f&32)!==0;tx(r,i?t:!1),r=n}var o=e.nodes&&e.nodes.t;if(o!==null)for(const s of o)(s.is_global||t)&&s.in()}}function rx(e,t){if(e.nodes)for(var r=e.nodes.start,n=e.nodes.end;r!==null;){var i=r===n?null:Qs(r);t.append(r),r=i}}var D5=null,Ih=!1,Vs=!1;function RS(e){Vs=e}var ar=null,Lo=!1;function go(e){ar=e}var Vt=null;function Is(e){Vt=e}var Wo=null;function nx(e){ar!==null&&(ar.f&2097152||ar.f&2)&&(Wo??(Wo=new Set)).add(e)}var ki=null,Bi=0,no=null;function j5(e){no=e}var ix=1,hl=0,Rl=hl;function _S(e){Rl=e}function ox(){return++ix}function cf(e){var t=e.f;if((t&2048)!==0)return!0;if((t&4096)!==0){for(var r=e.deps,n=r.length,i=0;i<n;i++){var o=r[i];if(cf(o)&&LC(o),o.wv>e.wv)return!0}t&512&&ci===null&&wn(e,po)}return!1}function sx(e,t,r=!0){var n=e.reactions;if(n!==null&&!(!sf&&Wo!==null&&Wo.has(e)))for(var i=0;i<n.length;i++){var o=n[i];(o.f&2)!==0?sx(o,t,!1):t===o&&(r?wn(o,Jo):o.f&1024&&wn(o,sc),FC(o))}}function ax(e){var t=ki,r=Bi,n=no,i=ar,o=Wo,s=Xr,a=Lo,l=Rl,d=e.f;ki=null,Bi=0,no=null,ar=(d&96)===0?e:null,Wo=null,ed(e.ctx),Lo=!1,Rl=++hl,e.ac!==null&&(vm(()=>{e.ac.abort(nf)}),e.ac=null);try{e.f|=IS;var c=e.fn,u=c();e.f|=jb;var f=PS(e);if(vd()&&no!==null&&!Lo&&f!==null&&(e.f&6146)===0)for(var p=0;p<no.length;p++)sx(no[p],e);if(i!==null&&i!==e){if(hl++,i.deps!==null)for(let g=0;g<r;g+=1)i.deps[g].rv=hl;if(t!==null)for(const g of t)g.rv=hl;no!==null&&(n===null?n=no:n.push(...no))}return e.f&8388608&&(e.f^=gp),u}catch(g){return PS(e),_5(g)}finally{e.f^=IS,ki=t,Bi=r,no=n,ar=i,Wo=o,ed(s),Lo=a,Rl=l}}function PS(e){var t=e.deps,r=rr?.is_fork;if(ki!==null){var n;if(r||Tu(e,Bi),t!==null&&Bi>0)for(t.length=Bi+ki.length,n=0;n<ki.length;n++)t[Bi+n]=ki[n];else e.deps=t=ki;if(Ub()&&(e.f&512)!==0)for(n=Bi;n<t.length;n++){var i;((i=t[n]).reactions??(i.reactions=[])).push(e)}}else!r&&t!==null&&Bi<t.length&&(Tu(e,Bi),t.length=Bi);return t}function B5(e,t){let r=t.reactions;if(r!==null){var n=DD.call(r,e);if(n!==-1){var i=r.length-1;i===0?r=t.reactions=null:(r[n]=r[i],r.pop())}}if(r===null&&(t.f&2)!==0&&(ki===null||!Nv.call(ki,t))){var o=t;o.f&512&&(o.f^=512),o.v!==xn&&Hb(o),o.ac!==null&&vm(()=>{o.ac.abort(nf),o.ac=null,wn(o,Jo)}),y5(o),Tu(o,0)}}function Tu(e,t){var r=e.deps;if(r!==null)for(var n=t;n<r.length;n++)B5(e,r[n])}function rd(e){var t=e.f;if((t&16384)===0){wn(e,po);var r=Vt,n=Ih;Vt=e,Ih=(t&96)===0;try{(t&16777232)!==0?N5(e):Gb(e),YC(e);var i=ax(e);e.teardown=typeof i=="function"?i:null,e.wv=ix}finally{Ih=n,Vt=r}}}async function ou(){if(sf)return new Promise(e=>{requestAnimationFrame(()=>e()),setTimeout(()=>e())});await Promise.resolve(),Xe()}function A(e){var t=(e.f&2)!==0;if(D5?.add(e),ar!==null&&!Lo&&!(Vt!==null&&(Vt.f&16384)!==0)&&(Wo===null||!Wo.has(e))){var r=ar.deps;if((ar.f&2097152)!==0)e.rv<hl&&(e.rv=hl,ki===null&&r!==null&&r[Bi]===e?Bi++:ki===null?ki=[e]:ki.push(e));else{var n;(n=ar).deps??(n.deps=[]),Nv.call(ar.deps,e)||ar.deps.push(e);var i=e.reactions;i===null?e.reactions=[ar]:Nv.call(i,ar)||i.push(ar)}}if(Vs&&ws.has(e))return ws.get(e);if(t){var o=e;if(Vs){var s=o.v;return(!(o.f&1024)&&o.reactions!==null||cx(o))&&(s=zb(o)),ws.set(o,s),s}var a=(o.f&512)===0&&!Lo&&ar!==null&&(Ih||(ar.f&512)!==0),l=(o.f&jb)===0;cf(o)&&(a&&(o.f|=512),LC(o)),a&&!l&&(OC(o),lx(o))}if(ci?.has(e))return ci.get(e);if((e.f&8388608)!==0)throw e.v;return e.v}function lx(e){if(e.f|=512,e.deps!==null)for(const t of e.deps)(t.reactions??(t.reactions=[])).push(e),t.f&2&&!(t.f&512)&&(OC(t),lx(t))}function cx(e){if(e.v===xn)return!0;if(e.deps===null)return!1;for(const t of e.deps)if(ws.has(t)||(t.f&2)!==0&&cx(t))return!0;return!1}function Bn(e){var t=Lo;try{return Lo=!0,e()}finally{Lo=t}}var qf=Symbol("events"),F5=new Set,AS=new Set,dg=null,ug=!1;function MS(e){var t=this,r=t.ownerDocument,n=e.type,i=e.composedPath?.()||[],o=i[0]||e.target;dg=e,ug||(ug=!0,setTimeout(()=>{ug=!1,dg=null}));var s=0,a=dg===e&&e[qf];if(a){var l=i.indexOf(a);if(l!==-1&&(t===document||t===window)){e[qf]=t;return}var d=i.indexOf(t);if(d===-1)return;l<=d&&(s=l)}if(o=i[s]||e.target,o!==t){Su(e,"currentTarget",{configurable:!0,get(){return o||r}});var c=ar,u=Vt;go(null),Is(null);try{for(var f,p=[];o!==null&&o!==t;){try{var g=o[qf]?.[n];g!=null&&(!o.disabled||e.target===o)&&g.call(o,e)}catch(v){f?p.push(v):f=v}if(e.cancelBubble)break;s++,o=s<i.length?i[s]:null}if(f){for(let v of p)queueMicrotask(()=>{throw v});throw f}}finally{e[qf]=t,delete e.currentTarget,go(c),Is(u)}}}var H5=globalThis?.window?.trustedTypes&&globalThis.window.trustedTypes.createPolicy("svelte-trusted-html",{createHTML:e=>e});function z5(e){return H5?.createHTML(e)??e}function W5(e){var t=ym("template");return t.innerHTML=z5(e.replaceAll("<!>","<!---->")),t.content}function _l(e,t){var r=Vt;r.nodes===null&&(r.nodes={start:e,end:t,a:null,t:null})}function ea(e,t){var r=(t&1)!==0,n=(t&2)!==0,i,o=!e.startsWith("<!>");return()=>{if(Dr)return _l(Kr,null),Kr;i===void 0&&(i=W5(o?e:"<!>"+e),r||(i=xo(i)));var s=n||qC?document.importNode(i,!0):i.cloneNode(!0);if(r){var a=xo(s),l=s.lastChild;_l(a,l)}else _l(s,s);return s}}function oo(e,t){if(Dr){var r=Vt;(!(r.f&32768)||r.nodes.end===null)&&(r.nodes.end=Kr),Qc();return}e!==null&&e.before(t)}var U5=["touchstart","touchmove"];function q5(e){return U5.includes(e)}function V5(e){let t=0,r=af(0),n;return()=>{Ub()&&(A(r),qb(()=>(t===0&&(n=Bn(()=>e(()=>iu(r)))),t+=1,()=>{ql(()=>{t-=1,t===0&&(n?.(),n=void 0,iu(r))})})))}}var G5=Bb|md;function K5(e,t,r,n){new X5(e,t,r,n)}var Uo=new WeakMap,Uv=new WeakMap,hs=new WeakMap,Eu=new WeakMap,Wi=new WeakMap,qo=new WeakMap,Gi=new WeakMap,Oo=new WeakMap,Ia=new WeakMap,Rc=new WeakMap,Pl=new WeakMap,Vf=new WeakMap,qv=new WeakMap,Vv=new WeakMap,Wa=new WeakMap,$S=new WeakMap,Pn=new WeakSet,X5=class{constructor(e,t,r,n){Wb(this,Pn),Te(this,"parent",void 0),Te(this,"is_pending",!1),Te(this,"transform_error",void 0),Mt(this,Uo,void 0),Mt(this,Uv,Dr?Kr:null),Mt(this,hs,void 0),Mt(this,Eu,void 0),Mt(this,Wi,void 0),Mt(this,qo,null),Mt(this,Gi,null),Mt(this,Oo,null),Mt(this,Ia,null),Mt(this,Rc,0),Mt(this,Pl,0),Mt(this,Vf,!1),Mt(this,qv,new Set),Mt(this,Vv,new Set),Mt(this,Wa,null),Mt(this,$S,V5(()=>(St(Wa,this,af(Q(Rc,this))),()=>{St(Wa,this,null)}))),St(Uo,this,e),St(hs,this,t),St(Eu,this,i=>{var o=Vt;o.b=this,o.f|=128,r(i)}),this.parent=Vt.b,this.transform_error=n??this.parent?.transform_error??(i=>i),St(Wi,this,Vb(()=>{if(Dr){const i=Q(Uv,this);Qc();const o=i.data==="[!";if(i.data.startsWith("[?")){const s=JSON.parse(i.data.slice(2));Wt(Pn,this,Y5).call(this,s)}else o?Wt(Pn,this,J5).call(this):Wt(Pn,this,Z5).call(this)}else Wt(Pn,this,ux).call(this)},G5)),Dr&&St(Uo,this,Kr)}defer_effect(e){AC(e,Q(qv,this),Q(Vv,this))}is_rendered(){return!this.is_pending&&(!this.parent||this.parent.is_rendered())}has_pending_snippet(){return!!Q(hs,this).pending}update_pending_count(e,t){Wt(Pn,this,fx).call(this,e,t),St(Rc,this,Q(Rc,this)+e),Q(Wa,this)&&!Q(Vf,this)&&(St(Vf,this,!0),ql(()=>{St(Vf,this,!1),Q(Wa,this)&&kp(Q(Wa,this),Q(Rc,this))}))}get_effect_pending(){return Q($S,this).call(this),A(Q(Wa,this))}error(e){if(!Q(hs,this).onerror&&!Q(hs,this).failed)throw e;rr?.is_fork?(Q(qo,this)&&rr.skip_effect(Q(qo,this)),Q(Gi,this)&&rr.skip_effect(Q(Gi,this)),Q(Oo,this)&&rr.skip_effect(Q(Oo,this)),rr.oncommit(()=>{Wt(Pn,this,LS).call(this,e)})):Wt(Pn,this,LS).call(this,e)}};function Z5(){try{St(qo,this,qs(()=>Q(Eu,this).call(this,Q(Uo,this))))}catch(e){this.error(e)}}function Y5(e){const t=Q(hs,this).failed,{reset:r,invoke_onerror:n}=Wt(Pn,this,dx).call(this,e);ql(n),t&&St(Oo,this,qs(()=>{t(Q(Uo,this),()=>e,()=>r)}))}function dx(e){var t=!1,r=!1;const n=()=>{if(t){ZD();return}t=!0,r&&d5(),Q(Oo,this)!==null&&lf(Q(Oo,this),()=>{St(Oo,this,null)}),Wt(Pn,this,Kb).call(this,()=>{Wt(Pn,this,ux).call(this)})};return{reset:n,invoke_onerror:()=>{try{r=!0,Q(hs,this).onerror?.(e,n),r=!1}catch(i){Ss(i,Q(Wi,this)&&Q(Wi,this).parent)}}}}function J5(){const e=Q(hs,this).pending;e&&(this.is_pending=!0,St(Gi,this,qs(()=>e(Q(Uo,this)))),ql(()=>{var t=St(Ia,this,document.createDocumentFragment()),r=Vl(),n=!1;if(t.append(r),St(qo,this,Wt(Pn,this,Kb).call(this,()=>{try{return qs(()=>Q(Eu,this).call(this,r))}catch(i){try{this.error(i),n=!0}catch(o){Ss(o,Q(Wi,this).parent)}return null}})),Q(qo,this)===null){St(Ia,this,null),n&&Wt(Pn,this,Tp).call(this,rr);return}Q(Pl,this)===0&&(Q(Uo,this).before(t),St(Ia,this,null),lf(Q(Gi,this),()=>{St(Gi,this,null)}),Wt(Pn,this,Tp).call(this,rr))}))}function ux(){try{if(this.is_pending=this.has_pending_snippet(),St(Pl,this,0),St(Rc,this,0),St(qo,this,qs(()=>{Q(Eu,this).call(this,Q(Uo,this))})),Q(Pl,this)>0){var e=St(Ia,this,document.createDocumentFragment());rx(Q(qo,this),e);const t=Q(hs,this).pending;St(Gi,this,qs(()=>t(Q(Uo,this))))}else Wt(Pn,this,Tp).call(this,rr)}catch(t){this.error(t)}}function Tp(e){this.is_pending=!1,e.transfer_effects(Q(qv,this),Q(Vv,this))}function Kb(e){var t=Vt,r=ar,n=Xr;Is(Q(Wi,this)),go(Q(Wi,this)),ed(Q(Wi,this).ctx);try{return ac.ensure(),e()}finally{Is(t),go(r),ed(n)}}function fx(e,t){if(!this.has_pending_snippet()){if(this.parent){var r;Wt(Pn,r=this.parent,fx).call(r,e,t)}return}St(Pl,this,Q(Pl,this)+e),Q(Pl,this)===0&&(Wt(Pn,this,Tp).call(this,t),Q(Gi,this)&&lf(Q(Gi,this),()=>{St(Gi,this,null)}),Q(Ia,this)&&(Q(Uo,this).before(Q(Ia,this)),St(Ia,this,null)))}function LS(e){Q(qo,this)&&(Ei(Q(qo,this)),St(qo,this,null)),Q(Gi,this)&&(Ei(Q(Gi,this)),St(Gi,this,null)),Q(Oo,this)&&(Ei(Q(Oo,this)),St(Oo,this,null)),Dr&&(mo(Q(Uv,this)),YD(),mo(CC()));let t=Q(hs,this).failed;const r=n=>{const{reset:i,invoke_onerror:o}=Wt(Pn,this,dx).call(this,n);o(),t&&St(Oo,this,Wt(Pn,this,Kb).call(this,()=>{try{return qs(()=>{var s=Vt;s.b=this,s.f|=128,t(Q(Uo,this),()=>n,()=>i)})}catch(s){return Ss(s,Q(Wi,this).parent),null}}))};ql(()=>{var n;try{n=this.transform_error(e)}catch(i){Ss(i,Q(Wi,this)&&Q(Wi,this).parent);return}n!==null&&typeof n=="object"&&typeof n.then=="function"?n.then(r,i=>Ss(i,Q(Wi,this)&&Q(Wi,this).parent)):r(n)})}function pl(e,t){var r=t==null?"":typeof t=="object"?`${t}`:t;r!==(e[Sh]??(e[Sh]=e.nodeValue))&&(e[Sh]=r,e.nodeValue=`${r}`)}function hx(e,t){return px(e,t)}function Q5(e,t){Wv(),t.intro=t.intro??!1;const r=t.target,n=Dr,i=Kr;try{for(var o=xo(r);o&&(o.nodeType!==8||o.data!=="[");)o=Qs(o);if(!o)throw Ul;Lc(!0),mo(o);const s=px(e,{...t,anchor:o});return Lc(!1),s}catch(s){if(s instanceof Error&&s.message.split(`
44
+ `).some(a=>a.startsWith("https://svelte.dev/e/")))throw s;return s!==Ul&&console.warn("Failed to hydrate: ",s),t.recover===!1&&o5(),Wv(),x5(r),Lc(!1),hx(e,t)}finally{Lc(n),mo(i)}}var Gf=new Map;function px(e,{target:t,anchor:r,props:n={},events:i,context:o,intro:s=!0,transformError:a}){Wv();var l=void 0,d=L5(()=>{var c=r??t.appendChild(Vl());K5(c,{pending:()=>{}},p=>{mm({});var g=Xr;if(o&&(g.c=o),i&&(n.$$events=i),Dr&&_l(p,null),l=e(p,n)||Fb(),Dr&&(Vt.nodes.end=Kr,Kr===null||Kr.nodeType!==8||Kr.data!=="]"))throw of(),Ul;gm()},a);var u=new Set,f=p=>{for(var g=0;g<p.length;g++){var v=p[g];if(!u.has(v)){u.add(v);var b=q5(v);for(const x of[t,document]){var w=Gf.get(x);w===void 0&&(w=new Map,Gf.set(x,w));var I=w.get(v);I===void 0?(x.addEventListener(v,MS,{passive:b}),w.set(v,1)):w.set(v,I+1)}}}};return f(jD(F5)),AS.add(f),()=>{for(var p of u)for(const b of[t,document]){var g=Gf.get(b),v=g.get(p);--v==0?(b.removeEventListener(p,MS),g.delete(p),g.size===0&&Gf.delete(b)):g.set(p,v)}AS.delete(f),c!==r&&c.parentNode?.removeChild(c)}});return Gv.set(l,d),l}var Gv=new WeakMap;function ej(e,t){const r=Gv.get(e);return r?(Gv.delete(e),r(t)):Promise.resolve()}var _s=new WeakMap,ca=new WeakMap,Io=new WeakMap,Cd=new WeakMap,fg=new WeakMap,hg=new WeakMap,OS=new WeakMap,mx=class{constructor(e,t=!0){Te(this,"anchor",void 0),Mt(this,_s,new Map),Mt(this,ca,new Map),Mt(this,Io,new Map),Mt(this,Cd,new Set),Mt(this,fg,!0),Mt(this,hg,r=>{if(Q(_s,this).has(r)){var n=Q(_s,this).get(r),i=Q(ca,this).get(n);if(i)xS(i),Q(Cd,this).delete(n);else{var o=Q(Io,this).get(n);o&&(xS(o.effect),Q(ca,this).set(n,o.effect),Q(Io,this).delete(n),o.fragment.lastChild.remove(),this.anchor.before(o.fragment),i=o.effect)}for(const[s,a]of Q(_s,this)){if(Q(_s,this).delete(s),s===r)break;const l=Q(Io,this).get(a);l&&(Ei(l.effect),Q(Io,this).delete(a))}for(const[s,a]of Q(ca,this)){if(s===n||Q(Cd,this).has(s))continue;const l=()=>{if(Array.from(Q(_s,this).values()).includes(s)){var d=document.createDocumentFragment();rx(a,d),d.append(Vl()),Q(Io,this).set(s,{effect:a,fragment:d})}else Ei(a);Q(Cd,this).delete(s),Q(ca,this).delete(s)};Q(fg,this)||!i?(Q(Cd,this).add(s),lf(a,l,!1)):l()}}}),Mt(this,OS,r=>{Q(_s,this).delete(r);const n=Array.from(Q(_s,this).values());for(const[i,o]of Q(Io,this))n.includes(i)||(Ei(o.effect),Q(Io,this).delete(i))}),this.anchor=e,St(fg,this,t)}ensure(e,t){var r=rr,n=R5();if(t&&!Q(ca,this).has(e)&&!Q(Io,this).has(e))if(n){var i=document.createDocumentFragment(),o=Vl();i.append(o),Q(Io,this).set(e,{effect:qs(()=>t(o)),fragment:i})}else Q(ca,this).set(e,qs(()=>t(this.anchor)));if(Q(_s,this).set(r,e),n){for(const[s,a]of Q(ca,this))s===e?r.unskip_effect(a):r.skip_effect(a);for(const[s,a]of Q(Io,this))s===e?r.unskip_effect(a.effect):r.skip_effect(a.effect);r.oncommit(Q(hg,this)),r.ondiscard(Q(OS,this))}else Dr&&(this.anchor=Kr),Q(hg,this).call(this,r)}};function tj(e){Xr===null&&_C("onMount"),gd&&Xr.l!==null?rj(Xr).m.push(e):zr(()=>{const t=Bn(e);if(typeof t=="function")return t})}function Xb(e){Xr===null&&_C("onDestroy"),tj(()=>()=>Bn(e))}function rj(e){var t=e.l;return t.u??(t.u={a:[],b:[],m:[]})}function su(e,t,r=!1){var n;Dr&&(n=Kr,Qc());var i=new mx(e),o=r?Bb:0;function s(a,l){if(Dr){var d=JD(n);if(a!==parseInt(d.substring(1))){var c=CC();mo(c),i.anchor=c,Lc(!1),i.ensure(a,l),Lc(!0);return}}i.ensure(a,l)}Vb(()=>{var a=!1;t((l,d=0)=>{a=!0,s(d,l)}),a||s(-1,null)},o)}var nj=Symbol("NaN");function ij(e,t,r){Dr&&Qc();var n=new mx(e),i=!vd();Vb(()=>{var o=t();o!==o&&(o=nj),i&&o!==null&&typeof o=="object"&&(o={}),n.ensure(o,r)})}function NS(e,t,r=!1,n=!1,i=!1,o=!1){var s=e,a="";if(r){var l=e;Dr&&(s=mo(xo(l)))}Ro(()=>{var d=Vt;if(a===(a=t()??"")){Dr&&Qc();return}if(r&&!Dr){d.nodes=null,l.innerHTML=a,a!==""&&_l(xo(l),l.lastChild);return}if(d.nodes!==null&&(JC(d.nodes.start,d.nodes.end),d.nodes=null),a!==""){if(Dr){for(var c=Kr.data,u=Qc(),f=u;u!==null&&(u.nodeType!==8||u.data!=="");)f=u,u=Qs(u);if(u===null)throw of(),Ul;_l(Kr,f),s=mo(u);return}var p=ym(n?"svg":i?"math":"template",n?LD:i?OD:void 0);p.innerHTML=a;var g=n||i?p:p.content;if(_l(xo(g),g.lastChild),n||i)for(;xo(g);)s.before(xo(g));else s.before(g)}})}function Zb(e,t){ZC(()=>{e=Vt?.parent?.nodes?.start??e;var r=e.getRootNode(),n=r.host?r:r.head??r.ownerDocument.head;if(!n.querySelector("#"+t.hash)){const i=ym("style");i.id=t.hash,i.textContent=t.code,n.appendChild(i)}})}function gx(e){var t,r,n="";if(typeof e=="string"||typeof e=="number")n+=e;else if(typeof e=="object")if(Array.isArray(e)){var i=e.length;for(t=0;t<i;t++)e[t]&&(r=gx(e[t]))&&(n&&(n+=" "),n+=r)}else for(r in e)e[r]&&(n&&(n+=" "),n+=r);return n}function oj(){for(var e,t,r=0,n="",i=arguments.length;r<i;r++)(e=arguments[r])&&(t=gx(e))&&(n&&(n+=" "),n+=t);return n}function pg(e){return typeof e=="object"?oj(e):e??""}var DS=[...`
45
+ \r\f \v\uFEFF`];function sj(e,t,r){var n=e==null?"":""+e;if(t&&(n=n?n+" "+t:t),r){for(var i of Object.keys(r))if(r[i])n=n?n+" "+i:i;else if(n.length)for(var o=i.length,s=0;(s=n.indexOf(i,s))>=0;){var a=s+o;(s===0||DS.includes(n[s-1]))&&(a===n.length||DS.includes(n[a]))?n=(s===0?"":n.substring(0,s))+n.substring(a+1):s=a}}return n===""?null:n}function Bc(e,t,r,n,i,o){var s=e[Dv];if(Dr||s!==r||s===void 0){var a=sj(r,n,o);(!Dr||a!==e.getAttribute("class"))&&(a==null?e.removeAttribute("class"):t?e.className=a:e.setAttribute("class",a)),e[Dv]=r}else if(o&&i!==o)for(var l in o){var d=!!o[l];(i==null||d!==!!i[l])&&e.classList.toggle(l,d)}return o}var vx,_c=new WeakMap,Ep=new WeakMap,mg=new WeakMap,jS=new WeakSet,yx=class{constructor(e){Wb(this,jS),Mt(this,_c,new WeakMap),Mt(this,Ep,void 0),Mt(this,mg,void 0),St(mg,this,e)}observe(e,t){var r=Q(_c,this).get(e)||new Set;return r.add(t),Q(_c,this).set(e,r),Wt(jS,this,aj).call(this).observe(e,Q(mg,this)),()=>{var n=Q(_c,this).get(e);n.delete(t),n.size===0&&(Q(_c,this).delete(e),Q(Ep,this).unobserve(e))}}};vx=yx;function aj(){return Q(Ep,this)??St(Ep,this,new ResizeObserver(e=>{for(var t of e){vx.entries.set(t.target,t);for(var r of Q(_c,this).get(t.target)||[])r(t)}}))}Te(yx,"entries",new WeakMap);function gg(e,t){return e===t||e?.[ru]===t}function au(e=Fb(),t,r,n){var i=Xr.r,o=Vt;return ZC(()=>{var s,a;return qb(()=>{s=a,a=n?.()||[],Bn(()=>{gg(r(...a),e)||(t(e,...a),s&&gg(r(...s),e)&&t(null,...s))})}),()=>{let l=o;for(;l!==i&&l.parent!==null&&l.parent.f&33554432;)l=l.parent;const d=()=>{a&&gg(r(...a),e)&&t(null,...a)},c=l.teardown;l.teardown=()=>{d(),c?.()}}}),e}var Kf=!1;function lj(e){var t=Kf;try{return Kf=!1,[e(),Kf]}finally{Kf=t}}function Ye(e,t,r,n){var i=!gd||(r&2)!==0,o=(r&8)!==0,s=(r&16)!==0,a=n,l=!0,d=void 0,c=()=>s&&i?(d??(d=Iu(n)),A(d)):(l&&(l=!1,a=s?Bn(n):n),a);let u;if(o){var f=ru in e||EC in e;u=Cl(e,t)?.set??(f&&t in e?C=>e[t]=C:void 0)}var p,g=!1;o?[p,g]=lj(()=>e[t]):p=e[t],p===void 0&&n!==void 0&&(p=c(),u&&(i&&s5(t),u(p)));var v;if(i?v=()=>{var C=e[t];return C===void 0?c():(l=!0,C)}:v=()=>{var C=e[t];return C!==void 0&&(a=void 0),C===void 0?a:C},i&&(r&4)===0)return v;if(u){var b=e.$$legacy;return(function(C,L){return arguments.length>0?((!i||!L||b||g)&&u(L?v():C),C):v()})}var w=!1,I=((r&1)!==0?Iu:$C)(()=>(w=!1,v()));o&&A(I);var x=Vt;return(function(C,L){if(arguments.length>0){const E=L?A(I):i&&o?Nc(C):C;return Fe(I,E),w=!0,a!==void 0&&(a=E),C}return Vs&&w||(x.f&16384)!==0?I.v:A(I)})}function cj(e){return new dj(e)}var Ua=new WeakMap,rs=new WeakMap,dj=class{constructor(e){Mt(this,Ua,void 0),Mt(this,rs,void 0);var t=new Map,r=(i,o)=>{var s=E5(o,!1,!1);return t.set(i,s),s};const n=new Proxy({...e.props||{},$$events:{}},{get(i,o){return A(t.get(o)??r(o,Reflect.get(i,o)))},has(i,o){return o===EC?!0:(A(t.get(o)??r(o,Reflect.get(i,o))),Reflect.has(i,o))},set(i,o,s){return Fe(t.get(o)??r(o,s),s),Reflect.set(i,o,s)}});St(rs,this,(e.hydrate?Q5:hx)(e.component,{target:e.target,anchor:e.anchor,props:n,context:e.context,intro:e.intro??!1,recover:e.recover,transformError:e.transformError})),(!e?.props?.$$host||e.sync===!1)&&Xe(),St(Ua,this,n.$$events);for(const i of Object.keys(Q(rs,this)))i==="$set"||i==="$destroy"||i==="$on"||Su(this,i,{get(){return Q(rs,this)[i]},set(o){Q(rs,this)[i]=o},enumerable:!0});Q(rs,this).$set=i=>{Object.assign(n,i)},Q(rs,this).$destroy=()=>{ej(Q(rs,this))}}$set(e){Q(rs,this).$set(e)}$on(e,t){Q(Ua,this)[e]=Q(Ua,this)[e]||[];const r=(...n)=>t.call(this,...n);return Q(Ua,this)[e].push(r),()=>{Q(Ua,this)[e]=Q(Ua,this)[e].filter(n=>n!==r)}}$destroy(){Q(rs,this).$destroy()}},bx;typeof HTMLElement=="function"&&(bx=class extends HTMLElement{constructor(e,t,r){super(),Te(this,"$$ctor",void 0),Te(this,"$$s",void 0),Te(this,"$$c",void 0),Te(this,"$$cn",!1),Te(this,"$$d",{}),Te(this,"$$r",!1),Te(this,"$$p_d",{}),Te(this,"$$l",{}),Te(this,"$$l_u",new Map),Te(this,"$$me",void 0),Te(this,"$$shadowRoot",null),this.$$ctor=e,this.$$s=t,r&&(this.$$shadowRoot=this.attachShadow(r))}addEventListener(e,t,r){if(this.$$l[e]=this.$$l[e]||[],this.$$l[e].push(t),this.$$c){const n=this.$$c.$on(e,t);this.$$l_u.set(t,n)}super.addEventListener(e,t,r)}removeEventListener(e,t,r){if(super.removeEventListener(e,t,r),this.$$c){const n=this.$$l_u.get(t);n&&(n(),this.$$l_u.delete(t))}}async connectedCallback(){if(this.$$cn=!0,!this.$$c){let e=function(n){return i=>{const o=ym("slot");n!=="default"&&(o.name=n),oo(i,o)}};if(await Promise.resolve(),!this.$$cn||this.$$c)return;const t={},r=uj(this);for(const n of this.$$s)n in r&&(n==="default"&&!this.$$d.children?(this.$$d.children=e(n),t.default=!0):t[n]=e(n));for(const n of this.attributes){const i=this.$$g_p(n.name);i in this.$$d||(this.$$d[i]=kh(i,n.value,this.$$p_d,"toProp"))}for(const n in this.$$p_d)!(n in this.$$d)&&this[n]!==void 0&&(this.$$d[n]=this[n],delete this[n]);this.$$c=cj({component:this.$$ctor,target:this.$$shadowRoot||this,props:{...this.$$d,$$slots:t,$$host:this}}),this.$$me=$5(()=>{qb(()=>{this.$$r=!0;for(const n of mp(this.$$c)){if(!this.$$p_d[n]?.reflect)continue;this.$$d[n]=this.$$c[n];const i=kh(n,this.$$d[n],this.$$p_d,"toAttribute");i==null?this.removeAttribute(this.$$p_d[n].attribute||n):this.setAttribute(this.$$p_d[n].attribute||n,i)}this.$$r=!1})});for(const n in this.$$l)for(const i of this.$$l[n]){const o=this.$$c.$on(n,i);this.$$l_u.set(i,o)}this.$$l={}}}attributeChangedCallback(e,t,r){this.$$r||(e=this.$$g_p(e),this.$$d[e]=kh(e,r,this.$$p_d,"toProp"),this.$$c?.$set({[e]:this.$$d[e]}))}disconnectedCallback(){this.$$cn=!1,Promise.resolve().then(()=>{!this.$$cn&&this.$$c&&(this.$$c.$destroy(),this.$$me(),this.$$c=void 0)})}$$g_p(e){return mp(this.$$p_d).find(t=>this.$$p_d[t].attribute===e||!this.$$p_d[t].attribute&&t.toLowerCase()===e)||e}});function kh(e,t,r,n){const i=r[e]?.type;if(t=i==="Boolean"&&typeof t!="boolean"?t!=null:t,!n||!r[e])return t;if(n==="toAttribute")switch(i){case"Object":case"Array":return t==null?null:JSON.stringify(t);case"Boolean":return t?"":null;case"Number":return t??null;default:return t}else switch(i){case"Object":case"Array":return t&&JSON.parse(t);case"Boolean":return t;case"Number":return t!=null?+t:t;default:return t}}function uj(e){const t={};return e.childNodes.forEach(r=>{t[r.slot||"default"]=!0}),t}function Yb(e,t,r,n,i,o){let s=class extends bx{constructor(){super(e,r,i),this.$$p_d=t}static get observedAttributes(){return mp(t).map(a=>(t[a].attribute||a).toLowerCase())}};return mp(t).forEach(a=>{Su(s.prototype,a,{get(){return this.$$c&&a in this.$$c?this.$$c[a]:this.$$d[a]},set(l){l=kh(a,l,t),this.$$d[a]=l;var d=this.$$c;d&&(Cl(d,a)?.get?d[a]=l:d.$set({[a]:l}))}})}),n.forEach(a=>{Su(s.prototype,a,{get(){return this.$$c?.[a]}})}),o&&(s=o(s)),e.element=s,s}function fj(e,t=!1){if(typeof e=="boolean")return e;if(e==null)return t;const r=String(e).trim().toLowerCase();return r===""?t:["false","0","off","no"].includes(r)?!1:["true","1","on","yes"].includes(r)?!0:!!r}function hj(e){return e!==null&&fj(e,!0)}var pj=(e,t)=>{const r=e.$$p_d;return r?Object.entries(r).some(([n,i])=>i.type==="Boolean"&&(i.attribute??n.toLowerCase())===t):!1};function mj(e){const t=e.prototype.attributeChangedCallback;return class extends e{attributeChangedCallback(r,n,i){const o=i!==null&&pj(this,r)&&!hj(i)?null:i;t?.call(this,r,n,o)}}}function gj(e){const t=new Set,r=/<\/?([a-zA-Z][a-zA-Z0-9._-]*)(?=[\t\n\f\r />])/g;let n=null;for(;(n=r.exec(e))!==null;){const i=String(n[1]||"").trim();i&&i.includes("-")&&t.add(i)}return t}var wx=e=>{const t=[],r=[];if(!e||typeof e!="object"||Array.isArray(e))return{valid:!1,errors:["Config must be an object."],warnings:r};const n=e,i=n.markup,o=n.elements,s=n.models;if(typeof i!="string"&&t.push("`markup` must be a string."),(!o||typeof o!="object"||Array.isArray(o))&&t.push("`elements` must be an object."),Array.isArray(s)||t.push("`models` must be an array."),t.length>0)return{valid:!1,errors:t,warnings:r};const a=o,l=s,d=Object.keys(a);for(const[p,g]of Object.entries(a)){if(typeof p!="string"||p.trim().length===0){t.push("`elements` contains an empty tag name.");continue}if(typeof g!="string"||g.trim().length===0){t.push(`Element "${p}" must map to a non-empty package spec.`);continue}try{pk(p,g)}catch{t.push(`Element "${p}" has invalid package spec "${g}".`)}}const c=new Set;for(const[p,g]of l.entries()){const v=g?.element;if(typeof v!="string"||v.trim().length===0){t.push(`Model at index ${p} is missing a valid "element" reference.`);continue}c.add(v),v in a||t.push(`Model element "${v}" is not declared in \`elements\`.`)}const u=gj(i);for(const p of u)p in a||t.push(`Markup tag "${p}" is not declared in \`elements\`.`);const f=new Set([...c,...u]);for(const p of d)f.has(p)||r.push(`Element "${p}" is declared in \`elements\` but not referenced by models or markup.`);return{valid:t.length===0,errors:t,warnings:r}},vj=e=>{const t=wx(e);if(!t.valid)throw new Error(`Invalid PIE config contract: ${t.errors.join(" | ")}`)},yj=e=>{const t=Object.entries(e.config.elements).reduce((a,[l,d])=>{const c=pk(l,d);return{...a,[l]:{versionedName:c,package:d}}},{}),r=a=>a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),n=(a,l,d)=>{const c=new RegExp(`(<\\/?)${r(l)}(?=[\\t\\n\\f\\r />])`,"g");return a.replace(c,(u,f)=>`${f}${d}`)},i=Object.entries(t).reduce((a,[l,{versionedName:d}])=>l!==d?n(a,l,d):a,e.config.markup),o=Object.values(t).reduce((a,{versionedName:l,package:d})=>({...a,[l]:d}),{}),s=e.config.models.map(a=>{const l=a.element,d=t[l];if(d&&d.versionedName!==l)return{...a,element:d.versionedName};if(o[l])return a;const c=Object.entries(t).filter(([u])=>{const{baseName:f,existingEncodedVersion:p}=du(u);return p!==void 0&&f===l});if(c.length===1){const[,{versionedName:u}]=c[0];return{...a,element:u}}return a});return{...e,config:{...e.config,elements:o,markup:i,models:s}}},Ni=Lu("pie-scoring",()=>Ou()),Sx=(e,t)=>{if(t===To.player){Ni.debug(`[findPieController] ℹ️ ${e} delivered as player.js; using server-processed models`);return}const r=Bp();Ni.debug(`[findPieController] Looking for controller for: ${e}`),Ni.debug("[findPieController] Registry has entries for:",Object.keys(r));const n=r[e];if(!n){Ni.error(`[findPieController] ❌ No registry entry found for element: ${e}`),Ni.error("[findPieController] Available element names:",Object.keys(r)),Ni.error("[findPieController] Full registry:",r);return}Ni.debug(`[findPieController] Found registry entry for ${e}:`,{package:n.package,tagName:n.tagName,hasController:!!n.controller,controllerKeys:n.controller?Object.keys(n.controller):[],bundleType:n.bundleType});const i=n.controller??void 0;return i?Ni.debug(`[findPieController] ✅ Controller found for ${e} with functions:`,Object.keys(i)):Ni.debug(`[findPieController] ℹ️ No controller for ${e}; its model is used as given`),i},bj=e=>e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\a ").replace(/\r/g,"\\d "),wj=(e,t)=>{const r=bj(t);return e.querySelector(`[id="${r}"]`)||e.querySelector(`[pie-id="${r}"]`)},Sj=async(e,t,r,n,i)=>i==="model-session-env"?e.outcome.call(e,t,r,n):e.outcome.call(e,r,n);async function Ij(e,t,r={}){const n=r.container??document,i=r.models??e.models??[],o=r.outcomeArguments??"session-env",s={...r.env,mode:"evaluate",partialScoring:r.env?.partialScoring},a=await Promise.all(i.map(async l=>{const d=wj(n,l.id);Ni.debug("found pieEl %O for model id %s",d,l.id);const c=hk(t,l.id,l.element);if(d){const u=Sx(d.localName,r.bundleType);if(u?.outcome)return{...c,...await Sj(u,l,c,s,o)};Ni.debug("ignore %s (no controller)",d.localName)}else Ni.debug("ignore %s (no element found for %s)",l.id)}));return Ni.debug("scorePieItem result",a),{results:r.includeMissingResults?a:a.filter(Boolean)}}var Kv="data-pie-content-styles",Ix="--pie-content-styles",kj=new Set(["inherit","initial","revert","revert-layer","unset"]),kx=e=>{const t=e.style?.getPropertyValue(Ix).trim().toLowerCase();if(t)return!kj.has(t);const r=e.cssRules;if(!r)return!1;for(const n of Array.from(r))if(kx(n))return!0;return!1},Cp="data-pie-content-styles",Tx="host",bm=()=>typeof document<"u"&&!!document.head;function Jb(){return bm()?document.documentElement.getAttribute(Cp)===Tx:!1}function Tj(){return bm()?getComputedStyle(document.documentElement).getPropertyValue(Ix).trim()!==""?!0:Ex({excludeInstalled:!1})>0:!1}function Ej(e,t){if(!bm())return"no-document";if(Jb())return"opted-out";if(document.querySelector(`style[${Kv}]`))return"already-installed";if(Cx()>0)return"host-supplied";if(!e)return"no-document";const r=document.createElement("style");return r.setAttribute(Kv,t),r.textContent=e,document.head.prepend(r),Cj(r),"installed"}var Xf=null,Cj=e=>{if(Xf?.(),typeof MutationObserver>"u")return;const t=()=>{n.disconnect(),document.removeEventListener("load",i,!0),Xf===t&&(Xf=null)},r=()=>{if(!e.isConnected){t();return}(Jb()||Cx()>0)&&(e.remove(),t())},n=new MutationObserver(o=>{o.some(s=>s.type==="attributes"||Array.from(s.addedNodes).some(a=>a.nodeName==="STYLE"||a.nodeName==="LINK"))&&r()}),i=o=>{o.target?.nodeName==="LINK"&&r()};n.observe(document.head,{childList:!0}),n.observe(document.documentElement,{attributes:!0,attributeFilter:[Cp]}),document.addEventListener("load",i,!0),Xf=t},Ex=({excludeInstalled:e})=>{const t=e?`:not([${Kv}])`:"",r=document.querySelectorAll(`style${t}, link[rel~="stylesheet"]${t}`);let n=0;for(const i of Array.from(r)){let o;try{o=i.sheet?.cssRules}catch{continue}if(o){for(const s of Array.from(o))if(kx(s)){n+=1;break}}}return n},Cx=()=>Ex({excludeInstalled:!0}),vg=!1,xj=[];function Rj(e){if(!bm()||vg)return;const t=()=>{vg||Jb()&&!Tj()&&(vg=!0,console.warn(`[${e}] No PIE content stylesheet found. This document sets ${Cp}="${Tx}", so ${e} did not install one. Authored content that relies on shared classes (.numbered-paragraph, .p-number, div.passage-title, the kds-* families, answer-eliminator styles) will render unstyled. Either import "@pie-players/pie-theme/components.css" in the host app, or drop the ${Cp} attribute to let the player install it.`))};if(typeof requestAnimationFrame!="function"){t();return}requestAnimationFrame(()=>requestAnimationFrame(t)),typeof window<"u"&&document.readyState!=="complete"&&window.addEventListener("load",()=>t(),{once:!0}),typeof setTimeout=="function"&&xj.push(setTimeout(t,1e3))}var _j={"nl-NL":()=>br(()=>import("./chunks/nl-NL-8b7e6d4b.js"),[],import.meta.url)},Pj=["en-US","nl-NL"];async function Aj(e){const t=_j[e];if(!t)throw new Error(`No bundled i18n catalog for locale: ${e}`);return(await t()).default}function Cu(e){return e?e.trim().replace(/_/g,"-").split(/[.@]/)[0].toLowerCase():""}function Mj(e){const t=Cu(e);if(!t)return[];const r=t.split("-"),n=[];for(let i=r.length;i>0;i--){const o=r.slice(0,i);o.length>1&&o[o.length-1].length===1||n.push(o.join("-"))}return n}function $j(e,t){for(const r of Mj(e)){const n=t.find(i=>Cu(i)===r);if(n!=null)return n}}var Lj={common:{close:"Close",cancel:"Cancel",save:"Save",reset:"Reset",retry:"Retry",back:"Back",next:"Next",previous:"Previous",submit:"Submit",continue:"Continue",finish:"Finish",yes:"Yes",no:"No",ok:"OK",any:"Any",off:"Off",auto:"Auto",all:"All",none:"None",loading:"Loading…",error:"Error",settings:"Settings",language:"Language",theme:"Theme",preview:"Preview",author:"Author",unknown:"Unknown",untitled:"Untitled",apply:"Apply",enabled:"Enabled",disabled:"Disabled",closeA11y:"Close",settingsA11y:"Open settings menu"},player:{passage:"Passage",passages:"Passages",question:"Question",questionNumbered:"Question {position}",questions:"Questions",items:"Items",section:"Section",loadingSection:"Loading section content…",sectionLoadError:"Section content could not be loaded.",loadingPassage:"Loading passage content…",configurationError:"Configuration Error",playerError:"Player Error",authoringBackendError:"Authoring Backend Configuration Error",itemLoadError:"Question could not be loaded.",sectionTabsA11y:"Section content tabs",passagesRegionA11y:"Passages",itemsRegionA11y:"Items",sectionToolsA11y:"Section tools",scrollDownA11y:"Scroll down",resizePanels:"Resize panels",resizePassagesAndItemsA11y:"Resize passages and items panels",resizeMediaRegion:"Resize media region",resizeQuestionAndMediaA11y:"Resize question and media panels",resizePassageAndMediaA11y:"Resize passage and media panels",assessment:{sectionPosition:"Section {position} of {total}",noSections:"No sections",loadFailed:"The assessment could not be loaded. Try again.",restoreFailed:"Your saved answers for this section could not be restored. Try again."},formative:{checkAnswer:"Check answer",tryAgain:"Try again",answerRecorded:"Answer recorded.",correct:"Correct.",partlyCorrect:"Partly correct.",notCorrect:"Not correct.",notAutoScored:"Answer recorded. This question is not scored automatically.",checkFailed:"This question could not be checked. Try again.",triesLeft:{one:"{count} try left.",other:"{count} tries left."}},timedMedia:{waitingForMedia:"Questions will appear as the media plays.",questionAvailable:"Question {position} is now available.",playbackPaused:"Playback paused. Answer question {position} to continue.",playbackAdvisory:"Answer question {position} before continuing with the media.",playbackReleased:"Answer accepted. Continue playing the media."}},toolkit:{toolsA11y:"Assessment tools",toolbarInitError:"Unable to initialize assessment toolkit.",settingsTitle:"Settings",closeSettingsA11y:"Close settings",dragPanelA11y:"Drag panel",closePanelA11y:"Close panel",resizeWindow:"Resize window",minimize:"Minimize",maximize:"Maximize",minimizePanelA11y:"Minimize panel",maximizePanelA11y:"Maximize panel",window:{moveLeftA11y:"Move tool left",moveRightA11y:"Move tool right",moveUpA11y:"Move tool up",moveDownA11y:"Move tool down",shrinkA11y:"Shrink tool window",growA11y:"Grow tool window",centerA11y:"Center tool window",closeA11y:"Close tool"},placement:{controlsA11y:"Move and rotate",rotateClockwiseA11y:"Rotate {degrees}° clockwise",rotateCounterclockwiseA11y:"Rotate {degrees}° counterclockwise"},announce:{movedUp:"Moved up to {position}",movedDown:"Moved down to {position}",movedLeft:"Moved left to {position}",movedRight:"Moved right to {position}",rotatedTo:"Rotated to {degrees} degrees"}},tools:{calculator:{name:"Calculator",nameBasic:"Basic Calculator",nameScientific:"Scientific Calculator",nameGraphing:"Graphing Calculator",description:"Multi-type calculator (basic, scientific, graphing)",openedBasic:"Basic calculator opened",openedScientific:"Scientific calculator opened",openedGraphing:"Graphing calculator opened",closedBasic:"Basic calculator closed",closedScientific:"Scientific calculator closed",closedGraphing:"Graphing calculator closed",toolA11y:"Calculator tool",loading:"Loading calculator…",providerUnavailable:"The calculator is unavailable."},graph:{name:"Graph",description:"Coordinate plane",buttonA11y:"Graph, coordinate plane",tooltip:"Graph",toolA11y:"Graph tool — draw points and lines on a coordinate grid",canvasA11y:"Graph canvas — use tools to add points and draw lines",grid:"Grid:",gridOpacityA11y:"Grid opacity",pointA11y:"Graph point {id}",modeSelector:"Selector",modeSelectorHint:"Selector: click and drag points to move them or associated lines.",modePoint:"Point",modePointHint:"Point: click on the grid to add points.",modeLine:"Line",modeLineHint:"Line: click a starting point, then an ending point to draw a line.",modeDelete:"Delete",modeDeleteHint:"Delete: click on a point to delete it and any connected lines."},periodicTable:{name:"Periodic Table",description:"Chemistry periodic table reference",buttonA11y:"Periodic Table, chemistry reference",tooltip:"Periodic Table",toolA11y:"Periodic table — select an element to view its details",elementsA11y:"Periodic table elements",showAllA11y:"Show all elements",allElements:"All Elements",atomicMass:"Atomic Mass",atomicNumber:"Atomic No",electronConfig:"Electron Config",phase:"Phase",filterByA11y:"Filter by {category}",elementA11y:"{name}, Symbol: {symbol}, Atomic number: {number}, Atomic mass: {mass}, Category: {category}",outsideFilterA11y:", outside the current filter",category:{unknown:"Unknown",alkaliMetal:"Alkali Metal",alkalineEarthMetal:"Alkaline Earth Metal",transitionMetal:"Transition Metal",postTransitionMetal:"Post-transition Metal",metalloid:"Metalloid",diatomicNonmetal:"Diatomic Nonmetal",polyatomicNonmetal:"Polyatomic Nonmetal",nobleGas:"Noble Gas",lanthanide:"Lanthanide",actinide:"Actinide"}},ruler:{name:"Ruler",description:"On-screen ruler for measurements",buttonA11y:"Ruler",tooltip:"Ruler",toolA11y:"Draggable and rotatable ruler measurement tool",unitSelectionA11y:"Ruler unit selection",inches:"Inches",centimeters:"Centimeters",inchesInSentence:"inches",centimetersInSentence:"centimeters",switchToInchesA11y:"Switch to inches",switchToCentimetersA11y:"Switch to centimeters",switchedTo:"Switched to {unit}",applicationA11y:"Ruler tool. Use arrow keys to move, Shift+arrows to rotate, PageUp or PageDown for fine rotation, U to toggle units. Current unit: {unit}",imageAlt:"Ruler showing {unit}"},protractor:{name:"Protractor",description:"On-screen protractor for angle measurements",buttonA11y:"Protractor",tooltip:"Protractor",toolA11y:"Protractor tool. Use arrow keys to move, Shift+arrows to rotate, and PageUp or PageDown for fine rotation.",roleA11y:"Draggable and rotatable protractor measurement tool",imageAlt:"Protractor with 180-degree semicircular scale marked from 0 to 180 degrees in both directions, with degree markings every 10 degrees"},dictionary:{name:"Dictionary",description:"Look up word definitions",buttonA11y:"Dictionary, look up word definitions",tooltip:"Dictionary",toolA11y:"Dictionary"},pictureDictionary:{name:"Picture Dictionary",description:"Look up pictures for words",buttonA11y:"Picture Dictionary, look up pictures for words",tooltip:"Picture Dictionary",toolA11y:"Picture Dictionary"},dictionarySpanish:{name:"Spanish Dictionary",description:"Look up word definitions in Spanish",buttonA11y:"Spanish Dictionary, look up word definitions in Spanish",tooltip:"Spanish Dictionary",toolA11y:"Spanish Dictionary"},pictureDictionarySpanish:{name:"Spanish Picture Dictionary",description:"Look up pictures for words in Spanish",buttonA11y:"Spanish Picture Dictionary, look up pictures for words in Spanish",tooltip:"Spanish Picture Dictionary",toolA11y:"Spanish Picture Dictionary"},lineReader:{name:"Line Reader",description:"Reading guide overlay",buttonA11y:"Line Reader, reading guide",tooltip:"Line Reader",roleA11y:"Draggable and resizable reading guide overlay",close:"Close line reader",resizeWindowA11y:"Drag to resize the reading window",resizeFrameA11y:"Drag to resize the frame and window width",windowHeightAnnounce:"Reading window height {pixels} pixels",frameHeightAnnounce:"Frame height {pixels} pixels",widthAnnounce:"Width {pixels} pixels",applicationA11y:"Line Reader tool. A clear reading window inside an obscuring frame. Use arrow keys to move, +/- to resize the reading window, Escape to close. Reading window height: {paneHeight} pixels, Frame height: {frameHeight} pixels",resizeWindowFullA11y:"Resize the reading window. Drag, or use the up and down arrow keys to change its height. Current height {paneHeight} pixels",resizeFrameFullA11y:"Resize the frame. Drag, or use the up and down arrow keys to change the frame height and the left and right arrow keys to change the width. Current frame height {frameHeight} pixels, width {width} pixels"},answerEliminator:{name:"Answer Eliminator",description:"Strike through answer choices",buttonA11y:"Strike Through, eliminate answer choices",tooltip:"Strike Through"},highlighter:{name:"Highlighter",description:"Highlight and annotate text",buttonA11y:"Highlight text",tooltip:"Highlight"},annotationToolbar:{name:"Annotation",description:"Highlight and annotate text",buttonA11y:"Annotate, highlight and mark up text",tooltip:"Annotate",toolbarA11y:"Text annotation toolbar",underline:"Underline",underlineA11y:"Underline selected text",readAloud:"Read Aloud",readAloudA11y:"Read selected text aloud",remove:"Remove",removeA11y:"Remove this annotation",clearAll:"Clear All",clearAllA11y:"Clear all annotations from document",highlightYellowA11y:"Yellow highlight",highlightPinkA11y:"Pink highlight",highlightBlueA11y:"Blue highlight",highlightGreenA11y:"Green highlight"},theme:{name:"Theme",description:"Accessible themes and contrast",buttonA11y:"Theme, change colors and contrast",tooltip:"Theme",selectorA11y:"Theme selector",hint:"Select a theme to improve readability and reduce eye strain.",selectA11y:"Select theme",selectCurrentA11y:"Select theme. Current theme: {name}",optionUnavailableA11y:"{name}, unavailable",unavailableName:"Unavailable theme: {id}",unavailableDescription:"PIE's managed base theme remains active until this theme becomes available again.",unavailableStatus:"The selected theme is unavailable. PIE's managed base theme is active until it becomes available again."},textToSpeech:{name:"Text to Speech",description:"Read content aloud",toolA11y:"Text-to-speech tool",title:"Text-to-Speech",initializing:"Initializing…",initFailed:"Failed to initialize text-to-speech.",selectText:"Select text on the page to read it aloud.",speed:"Speed:",play:"Play",pause:"Pause",resume:"Resume",stop:"Stop",speaking:"Speaking…",paused:"Paused",charactersSelected:{one:"{count} character selected",other:"{count} characters selected"},rate:{slow:"Slow",slower:"Slower",normal:"Normal",faster:"Faster",fast:"Fast",veryFast:"Very Fast"},inline:{controlsA11y:"Reading controls",playbackSpeedA11y:"Playback speed",rewindA11y:"Rewind",fastForwardA11y:"Fast-forward",stopA11y:"Stop reading",initializing:"Initializing text-to-speech",initFailed:"Unable to initialize text-to-speech. Try again.",starting:"Starting reading",started:"Reading started",resumed:"Reading resumed",pausedAnnouncement:"Reading paused",stopped:"Reading stopped",switchedSection:"Reading switched to another section",startFailed:"Unable to start reading",skippedForward:"Skipped forward",skipForwardFailed:"Unable to skip forward",skippedBackward:"Skipped backward",skipBackwardFailed:"Unable to skip backward",speedChangeFailed:"Unable to change playback speed",speedAnnounce:"Playback speed {label}",playA11y:"Play reading",pauseA11y:"Pause reading",resumeA11y:"Resume reading"}},signLanguage:{name:"Sign Language",description:"Signed alternate for authored content",generic:"Sign language",unknown:"Sign language ({code})",ase:"American Sign Language",bfi:"British Sign Language",fsl:"French Sign Language",gss:"Greek Sign Language",mfs:"Mexican Sign Language",signedEnglish:"Signed English",regionA11y:"{language} translation"},audioTranscript:{name:"Audio Transcript",description:"Text transcript of audio content",regionA11y:"Transcript"}},debug:{session:"Session",sessionData:"Session Data",sessionDataPersistent:"PIE Session Data (Persistent)",noItemSessionYet:"No item session data yet. Interact with the item to see updates here.",itemSessionsSnapshot:"Item Sessions Snapshot",sectionControllerUnavailable:"Section controller not available for this section yet.",filteredModel:"Filtered Model",environment:"Environment",events:"Events",controllerEvents:"Controller Events",instrumentation:"Instrumentation",databaseState:"Database state",sessionDb:"Session DB (Server)",noRows:"No rows",noRecords:"No instrumentation records yet.",selectRecord:"Select a record to inspect details.",selectEvent:"Select an event to inspect payload details.",showRawTables:"Show raw tables",showReconstructedSnapshots:"Show reconstructed snapshots",showSectionRequest:"Show section request",showAssessmentRequest:"Show assessment request",liveUpdatesUnsupported:"Live updates are not supported in this browser",liveUpdatesDisconnected:"Live updates disconnected; retrying…",fieldType:"Type:",fieldTarget:"Target:",fieldItem:"Item:",fieldCanonical:"Canonical:",fieldIntent:"Intent:",fieldDuplicates:"Duplicates:",fieldSemanticRepeats:"Semantic Repeats:",dragItemSessionPanelA11y:"Drag item session panel",debuggerTabsA11y:"Debugger tabs",sessionDataJsonA11y:"Session data JSON",environmentJsonA11y:"Environment JSON",filteredModelJsonA11y:"Filtered model JSON",sectionSessionJsonA11y:"Section session snapshot JSON",eventLevelFilterA11y:"Event level filter",controllerEventDetailsA11y:"Controller event details",instrumentationFilterA11y:"Filter instrumentation record type",instrumentationDetailsA11y:"Instrumentation record details",toggleSessionPanelA11y:"Toggle session panel",toggleEventPanelA11y:"Toggle event broadcast panel",toggleDatabasePanelA11y:"Toggle database state panel",toggleInstrumentationPanelA11y:"Toggle instrumentation panel",pnp:{title:"PNP Profile",noAssessmentBound:"No assessment bound",determinationReadOnly:"Determination (read-only)",toolsEditor:"Tools Editor",enforcement:"PNP enforcement",allAvailableTools:"All available tools",clearPlacement:"Clear placement",tool:"Tool",placement:"Placement",provider:"Provider",simulation:"PNP simulation",resolvedTools:"Resolved Tools (toolkit)",provenanceSummary:"Tool Policy Provenance Summary",perToolDecisions:"Per-Tool Decisions",profileReadOnly:"PNP Profile (read-only)"},tts:{title:"TTS settings",closeA11y:"Close TTS settings",toolbarLayoutMode:"Toolbar layout mode",reservedRow:"Reserved row",expandingRow:"Expanding row",floatingOverlay:"Floating overlay",leftAlignedControls:"Left-aligned controls",inlineSpeedButtons:"Inline speed buttons",resetToDefaults:"Reset to defaults",mathHighlighting:"Math highlighting",checkingAvailability:"Checking availability…",recheck:"Recheck",voice:"Voice",bestAvailableVoice:"Best available voice (auto)",unnamedVoice:"Unnamed voice",apiEndpoint:"API endpoint",gender:"Gender",any:"Any",male:"Male",female:"Female",neutral:"Neutral",engine:"Engine",neural:"Neural",standard:"Standard",providerDefault:"Provider default",format:"Format",sampleRate:"Sample rate",speechMarks:"Speech marks",word:"Word",wordAndSentence:"Word + sentence",voiceType:"Voice type",wavenetVoiceType:"WaveNet",studioVoiceType:"Studio",plainText:"Plain text",sampleText:"Sample text",resetSample:"Reset sample",providerAvailable:"Provider available.",providerUnavailable:"Provider unavailable.",providerCheckFailed:"Provider availability check failed.",providerNotChecked:"Provider availability has not been checked yet.",webSpeechUnavailable:"Web Speech API is not available in this browser.",browserNoVoices:"Browser text-to-speech is available, but no voices were returned yet.",browserUnavailable:"Browser text-to-speech is not available.",googleUnavailable:"Google Cloud TTS is not available from the configured API.",pollyUnavailable:"AWS Polly is not available from the configured API.",recommendedVoices:"Recommended voices",allVoices:"All available voices",previewVoice:"Preview voice",stopPreview:"Stop preview",applying:"Applying…",ssmlPreviewUnsupported:"SSML preview is not supported in the Browser backend.",pollySsmlHint:"Some Polly neural voices reject certain SSML tags (for example emphasis). Use basic SSML tags if preview fails.",mathHighlightParts:"Highlighting each part of a formula as it is read, falling back to the whole formula when alignment is uncertain.",mathHighlightBlock:"Highlighting each formula as a single block instead of breaking it into parts.",previewFailed:"Failed to play preview audio.",previewNoAudio:"Preview response did not include audio content.",previewEnterText:"Enter preview text before starting playback.",previewUnavailable:"Cannot preview while this service is unavailable.",browserSynthesisUnavailable:"Browser speech synthesis is unavailable.",browserSynthesisEndedEarly:"Browser speech synthesis ended before audio started. Restart the browser and try again.",browserSynthesisQueueFailed:"Browser speech synthesis failed to queue preview audio.",browserPreviewFailed:"Failed to play browser voice preview.",ssmlWordTrackingDisabled:"Google SSML preview preserves authored SSML, so word tracking is disabled.",applyUnavailable:"Cannot apply settings while this service is unavailable.",coordinatorUnavailable:"Toolkit coordinator is not available for text-to-speech updates."}}},yg="en-US",Oj=new Set(["ar","ckb","dv","fa","he","iw","ks","ku","nqo","ps","sd","syr","ug","ur","yi"]),Nj=new Set(["zero","one","two","few","many","other"]);function BS(e){if(typeof e!="object"||e===null)return!1;const t=Object.keys(e);return t.length>0&&t.every(r=>Nj.has(r))}function FS(e){try{const r=new Intl.Locale(e).textInfo;if(r?.direction==="rtl"||r?.direction==="ltr")return r.direction}catch{}const t=Cu(e).split("-")[0]??"";return Oj.has(t)?"rtl":"ltr"}var xx=class Th{constructor(t={}){Te(this,"locale",void 0),Te(this,"fallbackLocale",void 0),Te(this,"catalogs",void 0),Te(this,"customMessages",void 0),Te(this,"loading",void 0),Te(this,"listeners",new Set),Te(this,"config",void 0),this.config={...t},this.fallbackLocale=Zf(t.fallbackLocale)||"en-US",this.catalogs=new Map([[yg,Lj]]),this.customMessages={...t.customMessages??{}},this.loading=new Map,this.locale=this.resolveLocaleTag(t.locale)??"en-US"}async initialize(t){if(this.config={...this.config,...t},t.customMessages)for(const[r,n]of Object.entries(t.customMessages))this.addCustomMessages(r,n);await this.setLocale(t.locale??this.locale)}getLocale(){return this.locale}async setLocale(t){const r=this.resolveLocaleTag(t);if(!r){this.locale=Zf(t)||"en-US",this.notify();return}if(!this.catalogs.has(r)){const n=this.loading.get(r);if(n)await n;else{const i=this.loadCatalog(r);this.loading.set(r,i);try{await i}finally{this.loading.delete(r)}}}this.locale=r,this.notify()}t(t,r){const n=this.lookup(t);return n===void 0?(this.config.onMissingKey?.(t,this.locale),t):HS(n,r)}plural(t,r){const n=this.lookupNode(t);return n===void 0||!BS(n)?this.t(t,r):HS(n[this.selectPluralCategory(r.count)]??n.other,r)}getDirection(){return FS(this.locale)}getAvailableLocales(){return[...new Set([...this.catalogs.keys(),...this.config.availableLocales??[],...Object.keys(this.customMessages)])]}isLocaleLoaded(t){const r=this.resolveLocaleTag(t);return r!==void 0&&this.catalogs.has(r)}subscribe(t){return this.listeners.add(t),()=>{this.listeners.delete(t)}}hasKey(t){return this.lookup(t)!==void 0}addCustomMessages(t,r){const n=Zf(t);this.customMessages[n]=Rx(this.customMessages[n]??{},r),this.notify()}withLocale(t){const r=this.resolveLocaleTag(t)??Zf(t);if(r===this.locale)return this;const n=new Th({...this.config,locale:r});return n.locale=r||"en-US",n.catalogs=this.catalogs,n.customMessages=this.customMessages,n.loading=this.loading,n}formatNumber(t,r){try{return new Intl.NumberFormat(this.locale,r).format(t)}catch{return new Intl.NumberFormat(yg,r).format(t)}}formatDate(t,r){try{return new Intl.DateTimeFormat(this.locale,r).format(t)}catch{return new Intl.DateTimeFormat(yg,r).format(t)}}getBundle(t=this.locale){const r=this.resolveLocaleTag(t);if(!r)return;const n=this.catalogs.get(r);if(n)return{locale:r,translations:n,direction:FS(r)}}resolveLocaleTag(t){if(!t)return;const r=this.getAvailableLocales(),n=$j(t,r);if(n)return n;const i=Cu(t).split("-")[0];if(i)return r.find(o=>Cu(o).split("-")[0]===i)}async loadCatalog(t){const r=this.config.loadCatalog;if(r)try{this.catalogs.set(t,await r(t))}catch(n){throw new Error(`Failed to load i18n catalog for locale: ${t}`,{cause:n})}}lookupNode(t){const r=[this.customMessages[this.locale],this.catalogs.get(this.locale),this.customMessages[this.fallbackLocale],this.catalogs.get(this.fallbackLocale)];for(const n of r){const i=Dj(n,t);if(i!==void 0)return i}}lookup(t){const r=this.lookupNode(t);if(typeof r=="string")return r;if(r!==void 0&&BS(r))return r.other}selectPluralCategory(t){let r=Th.pluralRules.get(this.locale);if(!r){try{r=new Intl.PluralRules(this.locale)}catch{return t===1?"one":"other"}Th.pluralRules.set(this.locale,r)}return r.select(t)}notify(){for(const t of this.listeners)t()}};Te(xx,"pluralRules",new Map);function Zf(e){return e?e.trim().replace(/_/g,"-"):""}function Dj(e,t){if(!e)return;let r=e;for(const n of t.split("."))if(typeof r!="object"||r===null||(r=r[n],r===void 0))return;return r}function HS(e,t){return t?e.replace(/\{(\w+)\}/g,(r,n)=>{const i=t[n];return i==null?r:String(i)}):e}function Rx(e,t){const r={...e};for(const[n,i]of Object.entries(t)){const o=r[n];i&&typeof i=="object"&&o&&typeof o=="object"?r[n]=Rx(o,i):r[n]=i}return r}function jj(e={}){return new xx({loadCatalog:Aj,availableLocales:Pj,...e})}var Bj=`/* Content classes for authored assessment content, installed as a
46
+ document-level stylesheet by every player (see players-shared
47
+ ui/content-styles.ts).
48
+
49
+ A rule applies inside a \`[data-pie-content]\` element only, which each player
50
+ sets on the root it renders content into. Several selectors are bare
51
+ (\`h1\`-\`h6\`, \`table\`, \`th\`, \`.table\`, \`.center\`), and unscoped they restyled
52
+ the host page around the player. \`:where()\` keeps each selector's
53
+ specificity, and a host that renders authored markup itself marks its
54
+ container with the attribute.
55
+
56
+ The exception is a rule whose selector requires a name only authored
57
+ content carries: a KDS class (\`kds-*\`, \`Kds*\`), MathJax output (\`mjx-*\`,
58
+ \`TEX-*\`) or a legacy content class (\`.frac\`, \`.noprint\`, \`.passage-title\`
59
+ and the rest tests/content-styles-confinement.test.ts lists). Those stay
60
+ document-wide, because elements portal menus and popovers holding authored
61
+ markup to \`<body>\`, outside every \`[data-pie-content]\` root: an
62
+ inline-dropdown's choices keep their KDS fractions and MathJax glyph fixes
63
+ there. The \`:root\` sentinel below stays unscoped too.
64
+
65
+ Colour values resolve through the canonical --pie-* tokens with the original
66
+ literal kept as the no-theme last resort. The literals came from content
67
+ authored against a white page: \`black\` borders, \`lightgray\` table headers and
68
+ a white loading scrim are invisible or illegible the moment the surface is
69
+ not white, and a host that only swaps the theme cannot reach them. Ink takes
70
+ --pie-text (DaisyUI base-content, the one family guaranteed against the
71
+ surface), page-coloured fills take --pie-white, and one-step-off-the-page
72
+ fills take --pie-background-dark. */
73
+ :where([data-pie-content]) .pie-loading {
74
+ /* The Figma indigo is --pie-primary at 90%, so the ring follows the theme's
75
+ primary instead of pinning MD indigo on every page. */
76
+ --pie-loading-accent: color-mix(
77
+ in srgb,
78
+ var(--pie-primary, #3f51b5) 90%,
79
+ transparent
80
+ );
81
+ position: absolute;
82
+ height: 100%;
83
+ width: 100%;
84
+ background-color: var(--pie-white, #fff);
85
+ bottom: 0;
86
+ left: 0;
87
+ right: 0;
88
+ top: 0;
89
+ z-index: 9999;
90
+ opacity: 0.4;
91
+ }
92
+
93
+ :where([data-pie-content]) .pie-loading.fixed {
94
+ position: fixed;
95
+ }
96
+
97
+ :where([data-pie-content]) .pie-loading:before {
98
+ content: "";
99
+ background-color: rgba(0, 0, 0, 0);
100
+ border: 5px solid var(--pie-loading-accent, rgba(63, 81, 181, 0.9));
101
+ opacity: 0.9;
102
+ border-right: 5px solid rgba(0, 0, 0, 0);
103
+ border-left: 5px solid rgba(0, 0, 0, 0);
104
+ border-radius: 50px;
105
+ box-shadow: 0 0 35px var(--pie-loading-accent, rgba(63, 81, 181, 0.9));
106
+ width: 50px;
107
+ height: 50px;
108
+ -moz-animation: spinPulse 1s infinite ease-in-out;
109
+ -webkit-animation: spinPulse 1s infinite linear;
110
+ margin: -25px 0 0 -25px;
111
+ position: absolute;
112
+ top: 50%;
113
+ left: 50%;
114
+ }
115
+
116
+ :where([data-pie-content]) .pie-loading:after {
117
+ content: "";
118
+ background-color: rgba(0, 0, 0, 0);
119
+ border: 5px solid var(--pie-loading-accent, rgba(63, 81, 181, 0.9));
120
+ opacity: 0.9;
121
+ border-left: 5px solid rgba(0, 0, 0, 0);
122
+ border-right: 5px solid rgba(0, 0, 0, 0);
123
+ border-radius: 50px;
124
+ box-shadow: 0 0 15px var(--pie-loading-accent, rgba(63, 81, 181, 0.9));
125
+ width: 30px;
126
+ height: 30px;
127
+ -moz-animation: spinoffPulse 1s infinite linear;
128
+ -webkit-animation: spinoffPulse 1s infinite linear;
129
+ margin: -15px 0 0 -15px;
130
+ position: absolute;
131
+ top: 50%;
132
+ left: 50%;
133
+ }
134
+
135
+ @keyframes spinPulse {
136
+ 0% {
137
+ transform: rotate(160deg);
138
+ opacity: 0;
139
+ box-shadow: 0 0 1px var(--pie-loading-accent, rgba(63, 81, 181, 0.9));
140
+ }
141
+ 50% {
142
+ transform: rotate(145deg);
143
+ opacity: 1;
144
+ }
145
+ 100% {
146
+ transform: rotate(-320deg);
147
+ opacity: 0;
148
+ }
149
+ }
150
+
151
+ @keyframes spinoffPulse {
152
+ 0% {
153
+ transform: rotate(0deg);
154
+ }
155
+ 100% {
156
+ transform: rotate(360deg);
157
+ }
158
+ }
159
+
160
+ :where([data-pie-content]) .pie-api-player img {
161
+ max-width: inherit !important;
162
+ max-height: inherit !important;
163
+ }
164
+
165
+ /*
166
+ * PIE-94: horizontal-scroll wrapper for authored images inside passages and
167
+ * item stems. The shared sanitizer (\`sanitizeItemMarkup\` in
168
+ * \`@pie-players/pie-players-shared\`) wraps every \`<img>\` in
169
+ * \`<span class="pie-image-scroll">\` before injection. When the image fits its
170
+ * column the scrollbar stays hidden (overflow-x: auto); when it doesn't, the
171
+ * wrapper — not the passage or section layout — provides the sideways scroll
172
+ * needed to satisfy WCAG 1.4.10 Reflow at 400% zoom.
173
+ */
174
+ :where([data-pie-content]) .pie-image-scroll {
175
+ display: block;
176
+ max-width: 100%;
177
+ overflow-x: auto;
178
+ overflow-y: hidden;
179
+ }
180
+
181
+ :where([data-pie-content]) .pie-image-scroll > img {
182
+ display: block;
183
+ max-width: none;
184
+ height: auto;
185
+ }
186
+
187
+ :where([data-pie-content]) .pie-image-scroll:focus-visible {
188
+ outline: 2px solid
189
+ var(
190
+ --pie-focus-ring-color,
191
+ var(--pie-focus-outline, var(--pie-button-focus-outline, #1a73e8))
192
+ );
193
+ outline-offset: 2px;
194
+ }
195
+
196
+ /*
197
+ * PIE-558: horizontal-scroll wrapper for authored tables. Mirrors \`.pie-image-scroll\`:
198
+ * the shared sanitizer wraps every \`<table>\` outside a \`pie-*\` custom element
199
+ * in \`<div class="pie-table-scroll">\`. When the table fits its column the
200
+ * scrollbar stays hidden; when it doesn't, the wrapper provides the sideways
201
+ * scroll needed to satisfy WCAG 1.4.10 Reflow at 400% zoom instead of forcing
202
+ * the section layout to scroll horizontally.
203
+ */
204
+ :where([data-pie-content]) .pie-table-scroll {
205
+ display: block;
206
+ max-width: 100%;
207
+ overflow-x: auto;
208
+ overflow-y: hidden;
209
+ }
210
+
211
+ :where([data-pie-content]) .pie-table-scroll > table {
212
+ max-width: none;
213
+ }
214
+
215
+ :where([data-pie-content]) .pie-table-scroll:focus-visible {
216
+ outline: 2px solid
217
+ var(
218
+ --pie-focus-ring-color,
219
+ var(--pie-focus-outline, var(--pie-button-focus-outline, #1a73e8))
220
+ );
221
+ outline-offset: 2px;
222
+ }
223
+
224
+ /* These styles are used in the body content of an item -- they also appear in the item body editor. */
225
+
226
+ .book-title-k5 {
227
+ text-decoration: underline;
228
+ }
229
+
230
+ .book-title {
231
+ font-style: italic;
232
+ }
233
+
234
+ .block-quote {
235
+ font-family: serif;
236
+ margin-left: 20%;
237
+ margin-right: 20%;
238
+ margin-top: 5px;
239
+ margin-bottom: 5px;
240
+ width: 60%;
241
+ border: 1px solid var(--pie-text, black);
242
+ padding: 2px;
243
+ display: block;
244
+ }
245
+
246
+ .text-block {
247
+ font-family: serif;
248
+ margin-left: 20%;
249
+ margin-right: 20%;
250
+ margin-top: 5px;
251
+ margin-bottom: 5px;
252
+ width: 60%;
253
+ border: 1px solid var(--pie-text, black);
254
+ padding: 2px;
255
+ display: block;
256
+ }
257
+
258
+ .short-quote {
259
+ font-weight: bold;
260
+ }
261
+
262
+ span.short-quote:before {
263
+ content: open-quote;
264
+ }
265
+
266
+ span.short-quote:after {
267
+ content: close-quote;
268
+ }
269
+
270
+ .word-callout {
271
+ text-decoration: underline;
272
+ }
273
+
274
+ .relative-emphasis {
275
+ text-transform: uppercase;
276
+ }
277
+
278
+ /* Authored red emphasis. --pie-content-emphasis is mapped from the DaisyUI error
279
+ slot through the legible correction, so it clears 4.5:1 against the page on
280
+ every shipped theme; the \`red\` literal it replaces measures 4:1 on white and
281
+ fails SC 1.4.3 before any theme is involved. */
282
+ .content-emphasis {
283
+ font-weight: bold;
284
+ color: var(--pie-content-emphasis, #b00000);
285
+ }
286
+
287
+ span.passage-title:before {
288
+ content: open-quote;
289
+ }
290
+
291
+ span.passage-title:after {
292
+ content: close-quote;
293
+ }
294
+
295
+ .proper-name {
296
+ font-style: italic;
297
+ }
298
+
299
+ .variable {
300
+ font-style: italic;
301
+ }
302
+
303
+ .equation-block {
304
+ text-align: center;
305
+ margin-left: 20%;
306
+ margin-right: 20%;
307
+ margin-top: 5px;
308
+ margin-bottom: 5px;
309
+ width: 60%;
310
+ padding: 2px;
311
+ display: block;
312
+ }
313
+
314
+ .embedded-error {
315
+ font-style: italic;
316
+ }
317
+
318
+ /*
319
+ * The 20% gutters above are a wide-viewport look. Held at a 320px-equivalent
320
+ * width they leave a ~190px column of very short lines, so they collapse there
321
+ * instead — SC 1.4.10 Reflow.
322
+ */
323
+ @media (max-width: 30rem) {
324
+ .block-quote,
325
+ .text-block,
326
+ .equation-block {
327
+ margin-left: 0;
328
+ margin-right: 0;
329
+ width: auto;
330
+ }
331
+ }
332
+
333
+ /*
334
+ * Presence sentinel. Players install this stylesheet themselves and read this
335
+ * property to detect whether a host that opted out of installation shipped a
336
+ * copy of its own. Not a themeable value — do not consume it for styling.
337
+ */
338
+ :root {
339
+ --pie-content-styles: 1;
340
+ }
341
+
342
+ /* PASSAGES */
343
+
344
+ div.passage-title,
345
+ div.passage-subtitle {
346
+ font-weight: bold;
347
+ text-align: center;
348
+ }
349
+
350
+ div.passage-author {
351
+ text-align: center;
352
+ }
353
+
354
+ .p-number {
355
+ float: left;
356
+ font-size: 0.85em;
357
+ }
358
+
359
+ .numbered-paragraph {
360
+ margin-left: 36px;
361
+ }
362
+
363
+ /* ch5680 - also temporary kds content styles that need to be externalized */
364
+ /* Inspect Styles */
365
+
366
+ @media print {
367
+ .kds-noprint {
368
+ display: none;
369
+ }
370
+
371
+ .noprint {
372
+ display: none;
373
+ }
374
+ }
375
+
376
+ .kds-absolute {
377
+ border-left: 1px solid var(--pie-text, black);
378
+ border-right: 1px solid var(--pie-text, black);
379
+ padding: 0px 0.3em 0px 0.3em;
380
+ }
381
+
382
+ .abs {
383
+ border-left: var(--pie-text, #000000) 1px solid;
384
+ border-right: var(--pie-text, #000000) 1px solid;
385
+ padding: 0px 0.3em 0px 0.3em;
386
+ }
387
+
388
+ .kds-border-1 {
389
+ border: 1px solid var(--pie-text, black);
390
+ }
391
+
392
+ .kds-border-2 {
393
+ border: 2px solid var(--pie-text, black);
394
+ }
395
+
396
+ .kds-center {
397
+ margin: 0px;
398
+ text-align: center;
399
+ }
400
+
401
+ :where([data-pie-content]) .center {
402
+ text-align: center;
403
+ margin: 0;
404
+ }
405
+
406
+ .kds-exponent {
407
+ font-size: 85%;
408
+ margin-left: -0.4em;
409
+ position: relative;
410
+ top: -1.4em;
411
+ }
412
+
413
+ sup.frac {
414
+ position: relative;
415
+ top: -1.4em;
416
+ font-size: 70%;
417
+ margin-left: -0.4em;
418
+ }
419
+
420
+ .kds-fillin {
421
+ border: 1px solid var(--pie-text, black);
422
+ display: inline-block;
423
+ margin: 0em 0.2em;
424
+ padding-left: 1em;
425
+ }
426
+
427
+ .fillin {
428
+ margin: 0em 0.2em;
429
+ padding-left: 1em;
430
+ border: var(--pie-text, #000000) 1px solid;
431
+ display: inline-block;
432
+ }
433
+
434
+ .kds-font-larger {
435
+ font-size: larger;
436
+ }
437
+
438
+ .kds-font-smaller {
439
+ font-size: smaller;
440
+ }
441
+
442
+ table.kds-fraction {
443
+ border: 0px;
444
+ display: inline-block;
445
+ font-size: 85%;
446
+ margin: 0px;
447
+ padding: 0px;
448
+ vertical-align: middle;
449
+ }
450
+
451
+ table.kds-fraction > tbody > tr > td.kds-numerator {
452
+ border-bottom: 1px solid var(--pie-text, black);
453
+ border-left: 0px;
454
+ border-right: 0px;
455
+ border-top: 0px;
456
+ text-align: center;
457
+ }
458
+
459
+ table.kds-fraction > tbody > tr > td.kds-denominator {
460
+ border: 0px;
461
+ text-align: center;
462
+ }
463
+
464
+ table.frac {
465
+ display: inline-block;
466
+ vertical-align: middle;
467
+ font-size: 85%;
468
+ border: 0px;
469
+ margin: 0px;
470
+ padding: 0px;
471
+ }
472
+
473
+ .frac .nu {
474
+ border-left: 0px;
475
+ border-top: 0px;
476
+ border-right: 0px;
477
+ border-bottom: var(--pie-text, #000000) 1px solid;
478
+ text-align: center;
479
+ }
480
+
481
+ .frac .de {
482
+ border: 0px;
483
+ text-align: center;
484
+ }
485
+
486
+ .kds-hanging-indent {
487
+ margin: 0px;
488
+ padding-left: 3em;
489
+ text-indent: -3em;
490
+ }
491
+
492
+ .kds-image-caption {
493
+ font-family: Verdana, Arial, sans-serif;
494
+ text-align: center;
495
+ }
496
+
497
+ .kds-image-left {
498
+ float: left;
499
+ margin-right: 5px;
500
+ }
501
+
502
+ .kds-image-right {
503
+ float: right;
504
+ margin-left: 5px;
505
+ }
506
+
507
+ .kds-indent {
508
+ text-indent: 3em;
509
+ }
510
+
511
+ :where([data-pie-content]) .indent {
512
+ text-indent: 3em;
513
+ }
514
+
515
+ .kds-nowrap {
516
+ display: inline-block;
517
+ white-space: nowrap;
518
+ }
519
+
520
+ .kds-overline {
521
+ text-decoration: overline;
522
+ }
523
+
524
+ .kds-parentheses {
525
+ font-family: "Arial Narrow", Arial, sans-serif;
526
+ font-size: 300%;
527
+ font-weight: normal;
528
+ position: relative;
529
+ top: 8px;
530
+ }
531
+
532
+ b.frac {
533
+ font-weight: normal;
534
+ font-size: 300%;
535
+ font-family: arial narrow;
536
+ position: relative;
537
+ top: +8px;
538
+ }
539
+
540
+ .kds-pi {
541
+ font-family: "Times New Roman", serif;
542
+ font-size: 1.2em;
543
+ }
544
+
545
+ .newradical {
546
+ border-collapse: collapse;
547
+ display: inline-block;
548
+ vertical-align: middle;
549
+ }
550
+
551
+ .newradical td {
552
+ border: 0px;
553
+ padding: 0px;
554
+ vertical-align: top;
555
+ }
556
+
557
+ .newradical td.vinculum {
558
+ border-top: 1px solid var(--pie-text, black);
559
+ padding: 0px;
560
+ vertical-align: top;
561
+ }
562
+
563
+ .newradical div.exp {
564
+ font-size: 0.7em;
565
+ position: relative;
566
+ left: 7px;
567
+ bottom: 5px;
568
+ }
569
+
570
+ .kds-underline {
571
+ text-decoration: underline;
572
+ }
573
+
574
+ :where([data-pie-content]) .under {
575
+ text-decoration: underline;
576
+ }
577
+
578
+ .kds-verdana2t {
579
+ border: 1px solid var(--pie-white, white);
580
+ text-align: left;
581
+ text-decoration: none;
582
+ vertical-align: top;
583
+ }
584
+
585
+ .Verdana2t {
586
+ vertical-align: top;
587
+ text-align: left;
588
+ text-decoration: none;
589
+ border: 1px solid var(--pie-white, white);
590
+ }
591
+
592
+ .kds-whole-number {
593
+ display: inline-block;
594
+ font-size: 120%;
595
+ margin: 0em 0em 0em 0.2em;
596
+ }
597
+
598
+ .whole {
599
+ display: inline-block;
600
+ margin: 0em 0em 0em 0.2em;
601
+ font-size: 120%;
602
+ }
603
+
604
+ table.KdsTable01 {
605
+ border: 1px solid var(--pie-text, black);
606
+ border-collapse: collapse;
607
+ border-spacing: 0px;
608
+ }
609
+
610
+ table.KdsTable01 > tbody > tr > th {
611
+ background-color: var(--pie-background-dark, #d3d3d3);
612
+ border: 1px solid var(--pie-text, black);
613
+ font-weight: normal;
614
+ padding: 2px;
615
+ text-align: center;
616
+ }
617
+
618
+ table.KdsTable01 > tbody > tr > th.bold {
619
+ background-color: var(--pie-background-dark, #d3d3d3);
620
+ border: 1px solid var(--pie-text, black);
621
+ font-weight: bold;
622
+ padding: 2px;
623
+ text-align: center;
624
+ }
625
+
626
+ table.KdsTable01 > tbody > tr > td {
627
+ border: 1px solid var(--pie-text, black);
628
+ padding: 2px;
629
+ text-align: center;
630
+ }
631
+
632
+ table.KdsTable01 > tbody > tr > td.bold {
633
+ border: 1px solid var(--pie-text, black);
634
+ font-weight: bold;
635
+ padding: 2px;
636
+ text-align: center;
637
+ }
638
+
639
+ table.KdsTable02 {
640
+ border: 1px solid var(--pie-text, black);
641
+ border-collapse: collapse;
642
+ border-spacing: 0px;
643
+ }
644
+
645
+ table.KdsTable02 > tbody > tr > th {
646
+ background-color: var(--pie-background-dark, #d3d3d3);
647
+ border: 1px solid var(--pie-text, black);
648
+ font-weight: normal;
649
+ padding: 2px;
650
+ }
651
+
652
+ table.KdsTable02 > tbody > tr > td {
653
+ border: 1px solid var(--pie-text, black);
654
+ padding: 2px;
655
+ }
656
+
657
+ /* The grid rules below are mixed from the ink instead of taken from
658
+ --pie-border-light, which the DaisyUI mapping fills from base-200 — a surface,
659
+ so a border set from it disappears into the page. The 15% mix keeps the
660
+ near-invisible weight #dee2e6 had on white and inverts to a faint light rule
661
+ on a dark surface. Mixed inline, not hoisted to a custom property: a custom
662
+ property substitutes var(--pie-text) where it is declared, so a scoped
663
+ <pie-theme scope="self"> below :root would not reach it. */
664
+ :where([data-pie-content]) .table {
665
+ width: 100%;
666
+ margin-bottom: 1em;
667
+ background-color: transparent;
668
+ border-collapse: collapse;
669
+ }
670
+
671
+ :where([data-pie-content]) .table th,
672
+ :where([data-pie-content]) .table td {
673
+ padding: 0.75em;
674
+ vertical-align: top;
675
+ border-top: 1px solid
676
+ color-mix(in srgb, var(--pie-text, #000) 15%, transparent);
677
+ }
678
+
679
+ :where([data-pie-content]) .table tbody + tbody {
680
+ border-top: 2px solid
681
+ color-mix(in srgb, var(--pie-text, #000) 15%, transparent);
682
+ }
683
+
684
+ :where([data-pie-content]) .table thead th {
685
+ vertical-align: bottom;
686
+ border-bottom: 2px solid
687
+ color-mix(in srgb, var(--pie-text, #000) 15%, transparent);
688
+ }
689
+
690
+ :where([data-pie-content]) th {
691
+ text-align: inherit;
692
+ }
693
+
694
+ :where([data-pie-content]) .table-bordered,
695
+ :where([data-pie-content]) .table-bordered th,
696
+ :where([data-pie-content]) .table-bordered td {
697
+ border: 1px solid color-mix(in srgb, var(--pie-text, #000) 15%, transparent);
698
+ }
699
+
700
+ :where([data-pie-content]) .table-bordered thead td,
701
+ :where([data-pie-content]) .table-bordered thead th {
702
+ border-bottom-width: 2px;
703
+ }
704
+
705
+ :where([data-pie-content]) .table-striped tbody tr:nth-of-type(odd) {
706
+ background-color: color-mix(in srgb, var(--pie-text, #000) 5%, transparent);
707
+ }
708
+
709
+ :where([data-pie-content]) .text-center {
710
+ text-align: center !important;
711
+ }
712
+
713
+ :where([data-pie-content]) .h5,
714
+ :where([data-pie-content]) h5 {
715
+ font-size: 1.25em;
716
+ }
717
+
718
+ :where([data-pie-content]) h1,
719
+ :where([data-pie-content]) h2,
720
+ :where([data-pie-content]) h3,
721
+ :where([data-pie-content]) h4,
722
+ :where([data-pie-content]) h5,
723
+ :where([data-pie-content]) h6 {
724
+ margin-top: 0;
725
+ }
726
+
727
+ /* Spacing and inheritance only: \`font-weight: 500\` used to sit here and flatten
728
+ every authored heading to lighter-than-bold, weakening the visual hierarchy
729
+ a screen-reader user gets from the heading level. */
730
+ :where([data-pie-content]) .h1,
731
+ :where([data-pie-content]) .h2,
732
+ :where([data-pie-content]) .h3,
733
+ :where([data-pie-content]) .h4,
734
+ :where([data-pie-content]) .h5,
735
+ :where([data-pie-content]) .h6,
736
+ :where([data-pie-content]) h1,
737
+ :where([data-pie-content]) h2,
738
+ :where([data-pie-content]) h3,
739
+ :where([data-pie-content]) h4,
740
+ :where([data-pie-content]) h5,
741
+ :where([data-pie-content]) h6 {
742
+ margin-bottom: 0.5em;
743
+ font-family: inherit;
744
+ line-height: 1.2;
745
+ color: inherit;
746
+ }
747
+
748
+ /*
749
+ * Removed: a \`#stimulus\` / \`#item\` pair of 50% left floats, a \`.lrn_feature h3\`
750
+ * margin override and \`.lrn_width_auto.table\`. The float pair hard-coded a
751
+ * two-column layout keyed to two global ids — it cannot reflow at 400% zoom
752
+ * (SC 1.4.10), and it applied to any element in the host document carrying
753
+ * those ids. The other two styled a third-party product's markup that PIE does
754
+ * not render. None of the three could be made correct here, so they are gone
755
+ * rather than patched.
756
+ */
757
+
758
+ .TEX-S3 {
759
+ font-family: MJXZERO, MJXTEX-S3 !important;
760
+ }
761
+
762
+ .TEX-S2 {
763
+ font-family: MJXZERO, MJXTEX-S2 !important;
764
+ }
765
+
766
+ .TEX-S1 {
767
+ font-family: MJXZERO, MJXTEX-S1 !important;
768
+ }
769
+
770
+ .TEX-I {
771
+ font-family: MJXZERO, MJXTEX-I !important;
772
+ }
773
+
774
+ mjx-c.mjx-c2032 {
775
+ font-family: "CerebriSans", serif !important;
776
+ }
777
+
778
+ mjx-c.mjx-c22,
779
+ mjx-c.mjx-c27 {
780
+ font-family: MJXZERO, serif !important;
781
+ }
782
+
783
+ :where([data-pie-content]) table {
784
+ border-collapse: collapse;
785
+ }
786
+
787
+ .evaluate-bottom-border > :first-child::after {
788
+ content: "";
789
+ display: block;
790
+ border-bottom: 1px solid
791
+ color-mix(in srgb, var(--pie-text, #000) 15%, transparent);
792
+ }
793
+
794
+ /* ANSWER ELIMINATOR */
795
+
796
+ :where([data-pie-content]) .pie-answer-eliminator-toggle {
797
+ /* em, not px: PNP font scaling raises the surrounding text size without
798
+ touching px boxes, which left a fixed 28px control under grown text. The
799
+ box is 1.75x the surrounding text and the glyph 1.125x — the 28px/18px the
800
+ control used to pin at a 16px base — and the box stays past SC 2.5.8's 24px
801
+ minimum for any base at or above 14px. The box divides by the glyph factor
802
+ because \`em\` in a length resolves against this element's own font-size, not
803
+ the parent's; a bare 1.75em here measures 31.5px, not 28px. */
804
+ width: calc(1.75em / 1.125);
805
+ height: calc(1.75em / 1.125);
806
+ padding: 0;
807
+ border: 1px solid var(--pie-border, #ccc);
808
+ border-radius: 4px;
809
+ background: var(--pie-white, #fff);
810
+ cursor: pointer;
811
+ font-size: 1.125em;
812
+ line-height: 1;
813
+ display: inline-flex;
814
+ align-items: center;
815
+ justify-content: center;
816
+ color: var(
817
+ --pie-answer-eliminator-toggle-color,
818
+ var(--pie-button-color, #8c8c8c)
819
+ );
820
+ transition: all 0.2s ease;
821
+ z-index: 10;
822
+ }
823
+
824
+ :where([data-pie-content]) .pie-answer-eliminator-toggle:hover {
825
+ background: var(--pie-secondary-background, #f0f0f0);
826
+ border-color: var(--pie-border-dark, #999);
827
+ color: var(--pie-text, #333);
828
+ }
829
+
830
+ :where([data-pie-content]) .pie-answer-eliminator-toggle--active,
831
+ :where([data-pie-content]) .pie-answer-eliminator-toggle--active:hover {
832
+ background: var(--pie-incorrect, #ff9800);
833
+ border-color: var(--pie-incorrect, #ff9800);
834
+ color: var(--pie-white, #fff);
835
+ }
836
+
837
+ :where([data-pie-content]) .pie-answer-eliminator-eliminated-fallback {
838
+ text-decoration: line-through;
839
+ text-decoration-thickness: 2px;
840
+ text-decoration-color: var(
841
+ --pie-answer-eliminator-strike-color,
842
+ var(--pie-incorrect, #ff9800)
843
+ );
844
+ }
845
+
846
+ /*
847
+ * Dims the choice as well as striking it, so elimination survives a strike
848
+ * colour the learner cannot distinguish. Kept at 0.6 rather than lower: the text
849
+ * stays readable, because eliminating a choice is reversible and the learner has
850
+ * to be able to reconsider it.
851
+ *
852
+ * Keyed on the attribute rather than on the fallback class, because the class is
853
+ * added only by the path for browsers without the CSS Highlight API. The
854
+ * attribute is set by both paths, and a highlight pseudo cannot carry \`opacity\`
855
+ * at all — declaring it there dimmed nothing, so the modern path shipped the
856
+ * strike as its only cue.
857
+ */
858
+ :where([data-pie-content]) [data-pie-answer-eliminated="true"] {
859
+ opacity: 0.6;
860
+ }
861
+
862
+ :where([data-pie-content]) .pie-answer-eliminator-image-strike {
863
+ position: relative;
864
+ display: inline-block;
865
+ max-width: 100%;
866
+ /*
867
+ * Collapse the line-box strut so the wrapper hugs the image exactly (no
868
+ * baseline descender gap under it) and the X cannot overhang the artwork.
869
+ * It also keeps the image bottom on the text baseline, as an unwrapped
870
+ * baseline-aligned image sits.
871
+ */
872
+ line-height: 0;
873
+ }
874
+
875
+ :where([data-pie-content]) .pie-answer-eliminator-image-strike-overlay {
876
+ position: absolute;
877
+ inset: 0;
878
+ width: 100%;
879
+ height: 100%;
880
+ pointer-events: none;
881
+ }
882
+
883
+ :where([data-pie-content]) .pie-answer-eliminator-image-strike-line {
884
+ stroke: var(
885
+ --pie-answer-eliminator-strike-color,
886
+ var(--pie-incorrect, #ff9800)
887
+ );
888
+ stroke-width: 3;
889
+ stroke-linecap: square;
890
+ }
891
+
892
+ /* Wider light line under each diagonal so the X stays legible on dark imagery. */
893
+ :where([data-pie-content]) .pie-answer-eliminator-image-strike-casing {
894
+ stroke: var(
895
+ --pie-answer-eliminator-image-strike-casing-color,
896
+ rgba(255, 255, 255, 0.85)
897
+ );
898
+ stroke-width: 6;
899
+ stroke-linecap: square;
900
+ }
901
+
902
+ /*
903
+ * Eliminated math: MathJax's rendered glyphs are generated content, so neither
904
+ * \`::highlight()\` nor \`text-decoration\` reaches them. The eliminator marks the
905
+ * rendered math box instead and the paint happens here, in the same colour and
906
+ * weight as the text line-through so a choice mixing prose and math reads as one
907
+ * strike. Which mark it gets depends on the shape of the expression — the tool
908
+ * measures the box and picks \`--line\` or \`--cross\`.
909
+ */
910
+ :where([data-pie-content]) .pie-answer-eliminator-math-strike {
911
+ position: relative;
912
+ /*
913
+ * Internal: the resolved strike paint, so the rules below need not repeat the
914
+ * fallback chain. Not a themeable knob — set --pie-answer-eliminator-strike-color.
915
+ */
916
+ --pie-answer-eliminator-strike-paint: var(
917
+ --pie-answer-eliminator-strike-color,
918
+ var(--pie-incorrect, #ff9800)
919
+ );
920
+ }
921
+
922
+ /* A single row of symbols takes the same line-through as the surrounding prose. */
923
+ :where([data-pie-content]) .pie-answer-eliminator-math-strike--line::after {
924
+ content: "";
925
+ position: absolute;
926
+ left: 0;
927
+ right: 0;
928
+ top: 50%;
929
+ border-top: 2px solid var(--pie-answer-eliminator-strike-paint);
930
+ pointer-events: none;
931
+ }
932
+
933
+ /*
934
+ * A stacked 2D layout (fraction, radical, matrix) takes the diagonals instead.
935
+ * A centred line would land on the math axis — precisely where the fraction bar
936
+ * already is — and read as a recoloured bar rather than an elimination, so the
937
+ * expression is crossed out the way an eliminated image is. Corner keywords make
938
+ * each gradient's transition run exactly corner to corner at any aspect ratio,
939
+ * with a 1px feather either side of the 1px core for a smooth 2px line.
940
+ */
941
+ :where([data-pie-content]) .pie-answer-eliminator-math-strike--cross::after {
942
+ content: "";
943
+ position: absolute;
944
+ inset: 0;
945
+ pointer-events: none;
946
+ background-image:
947
+ linear-gradient(
948
+ to bottom right,
949
+ transparent calc(50% - 1.5px),
950
+ var(--pie-answer-eliminator-strike-paint) calc(50% - 0.5px),
951
+ var(--pie-answer-eliminator-strike-paint) calc(50% + 0.5px),
952
+ transparent calc(50% + 1.5px)
953
+ ),
954
+ linear-gradient(
955
+ to bottom left,
956
+ transparent calc(50% - 1.5px),
957
+ var(--pie-answer-eliminator-strike-paint) calc(50% - 0.5px),
958
+ var(--pie-answer-eliminator-strike-paint) calc(50% + 0.5px),
959
+ transparent calc(50% + 1.5px)
960
+ );
961
+ }
962
+
963
+ :where([data-pie-content]) .pie-answer-masked-fallback {
964
+ opacity: 0.2;
965
+ filter: blur(2px);
966
+ }
967
+
968
+ :where([data-pie-content]) .pie-answer-eliminator-sr-announcement {
969
+ position: absolute;
970
+ left: -10000px;
971
+ width: 1px;
972
+ height: 1px;
973
+ overflow: hidden;
974
+ }
975
+ `,Fj=class{constructor(){Te(this,"initialized",!1),Te(this,"config",void 0)}trackError(e,t){if(!this.guardedOperation("trackError",e,t)||!this.applyErrorFilter(e,t))return;const r=this.transformAttributes(t);try{this.doTrackError(e,r),this.config?.debug&&console.log(`[${this.providerName}] Tracked error:`,e,r)}catch(n){console.error(`[${this.providerName}] Error tracking error:`,n)}}trackEvent(e,t){if(!this.guardedOperation("trackEvent",e,t)||!this.applyEventFilter(e,t)||!this.applySampling(e))return;let r=this.transformAttributes(t);r.timestamp||(r={...r,timestamp:new Date().toISOString()});try{this.doTrackEvent(e,r),this.config?.debug&&console.log(`[${this.providerName}] Tracked event:`,e,r)}catch(n){console.error(`[${this.providerName}] Error tracking event:`,n)}}trackMetric(e,t,r){this.trackEvent(`metric:${e}`,{...r,metricValue:t,metricName:e})}setUserContext(e,t){if(this.guardedOperation("setUserContext",e,t))try{this.doSetUserContext(e,t),this.config?.debug&&console.log(`[${this.providerName}] Set user context:`,e,t)}catch(r){console.error(`[${this.providerName}] Error setting user context:`,r)}}setGlobalAttributes(e){if(this.guardedOperation("setGlobalAttributes",e))try{this.doSetGlobalAttributes(e),this.config?.debug&&console.log(`[${this.providerName}] Set global attributes:`,e)}catch(t){console.error(`[${this.providerName}] Error setting global attributes:`,t)}}guardedOperation(e,...t){return this.isReady()?!0:(this.config?.debug&&console.warn(`[${this.providerName}] Attempted to ${e} but provider not ready:`,...t),!1)}applyErrorFilter(e,t){return this.config?.errorFilter&&!this.config.errorFilter(e,t)?(this.config?.debug&&console.log(`[${this.providerName}] Error filtered out:`,e,t),!1):!0}applyEventFilter(e,t){return this.config?.eventFilter&&!this.config.eventFilter(e,t)?(this.config?.debug&&console.log(`[${this.providerName}] Event filtered out:`,e,t),!1):!0}applySampling(e){return this.config?.sampleRate!==void 0&&this.config.sampleRate<1&&Math.random()>this.config.sampleRate?(this.config?.debug&&console.log(`[${this.providerName}] Event sampled out:`,e),!1):!0}transformAttributes(e){return this.config?.attributeTransformer?this.config.attributeTransformer(e):e}};function zS(e){const t=e;return typeof t?.noticeError=="function"&&typeof t.addPageAction=="function"}function fc(){if(typeof window>"u")return;const{newrelic:e,NREUM:t}=window;if(zS(e))return e;if(zS(t))return t}var Hj=class extends Fj{constructor(...e){super(...e),Te(this,"providerId","newrelic"),Te(this,"providerName","New Relic")}async initialize(e){this.config=e,this.initialized=!0,this.config?.debug&&console.log(fc()?"[NewRelicProvider] Initialized successfully":"[NewRelicProvider] Initialized; sends once the New Relic agent is on the page")}isReady(){return this.initialized&&fc()!==void 0}destroy(){this.initialized=!1,this.config?.debug&&console.log("[NewRelicProvider] Destroyed")}doTrackError(e,t){fc()?.noticeError(e,t)}doTrackEvent(e,t){fc()?.addPageAction(e,t)}doSetUserContext(e,t){const r=fc();if(typeof r?.setUserId=="function"&&r.setUserId(e),t&&typeof r?.setCustomAttribute=="function")for(const[n,i]of Object.entries(t))r.setCustomAttribute(n,i)}doSetGlobalAttributes(e){const t=fc();if(typeof t?.setCustomAttribute=="function")for(const[r,n]of Object.entries(e))t.setCustomAttribute(r,n)}},xp={retryDelayMs:3e3,timeoutMs:12e4},WS={trackPageActions:!1,instrumentationProvider:void 0,maxResourceRetries:3,resourceRetryDelay:500,iifeBundleRetry:xp};function zj(e,t="iife"){return e==="iife"||e==="esm"||e==="preloaded"?e:t}function Wj(e,t){this.v=e,this.k=t}function US(e,t){(t==null||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function Uj(e){if(Array.isArray(e))return e}function qj(e,t){var r=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(r!=null){var n,i,o,s,a=[],l=!0,d=!1;try{if(o=(r=r.call(e)).next,t===0){if(Object(r)!==r)return;l=!1}else for(;!(l=(n=o.call(r)).done)&&(a.push(n.value),a.length!==t);l=!0);}catch(c){d=!0,i=c}finally{try{if(!l&&r.return!=null&&(s=r.return(),Object(s)!==s))return}finally{if(d)throw i}}return a}}function Vj(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
976
+ In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function Gj(e,t){return Uj(e)||qj(e,t)||Kj(e,t)||Vj()}function Kj(e,t){if(e){if(typeof e=="string")return US(e,t);var r={}.toString.call(e).slice(8,-1);return r==="Object"&&e.constructor&&(r=e.constructor.name),r==="Map"||r==="Set"?Array.from(e):r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?US(e,t):void 0}}function Yf(e){var t,r;function n(o,s){try{var a=e[o](s),l=a.value,d=l instanceof Wj;Promise.resolve(d?l.v:l).then(function(c){if(d){var u=o==="return"&&l.k?o:"next";if(!l.k||c.done)return n(u,c);c=e[u](c).value}i(!!a.done,c)},function(c){n("throw",c)})}catch(c){i(2,c)}}function i(o,s){o===2?t.reject(s):t.resolve({value:s,done:o}),(t=t.next)?n(t.key,t.arg):r=null}this._invoke=function(o,s){return new Promise(function(a,l){var d={key:o,arg:s,resolve:a,reject:l,next:null};r?r=r.next=d:(t=r=d,n(o,s))})},typeof e.return!="function"&&(this.return=void 0)}Yf.prototype[typeof Symbol=="function"&&Symbol.asyncIterator||"@@asyncIterator"]=function(){return this},Yf.prototype.next=function(e){return this._invoke("next",e)},Yf.prototype.throw=function(e){return this._invoke("throw",e)},Yf.prototype.return=function(e){return this._invoke("return",e)};var _x=Object.entries,qS=Object.setPrototypeOf,Xj=Object.isFrozen,Zj=Object.getPrototypeOf,Yj=Object.getOwnPropertyDescriptor,An=Object.freeze,zn=Object.seal,Pc=Object.create,Px=typeof Reflect<"u"&&Reflect,Xv=Px.apply,Zv=Px.construct;An||(An=function(e){return e});zn||(zn=function(e){return e});Xv||(Xv=function(e,t){for(var r=arguments.length,n=new Array(r>2?r-2:0),i=2;i<r;i++)n[i-2]=arguments[i];return e.apply(t,n)});Zv||(Zv=function(e){for(var t=arguments.length,r=new Array(t>1?t-1:0),n=1;n<t;n++)r[n-1]=arguments[n];return new e(...r)});var Qa=Sn(Array.prototype.forEach);Array.prototype.indexOf;var Jj=Sn(Array.prototype.lastIndexOf),VS=Sn(Array.prototype.pop),xd=Sn(Array.prototype.push);Array.prototype.slice;var Qj=Sn(Array.prototype.splice),Fc=Array.isArray,Kd=Sn(String.prototype.toLowerCase),bg=Sn(String.prototype.toString),GS=Sn(String.prototype.match),Rd=Sn(String.prototype.replace),KS=Sn(String.prototype.indexOf),eB=Sn(String.prototype.trim),tB=Sn(Number.prototype.toString),rB=Sn(Boolean.prototype.toString),XS=typeof BigInt>"u"?null:Sn(BigInt.prototype.toString),ZS=typeof Symbol>"u"?null:Sn(Symbol.prototype.toString),yi=Sn(Object.prototype.hasOwnProperty),_d=Sn(Object.prototype.toString),Xn=Sn(RegExp.prototype.test),da=nB(TypeError);function Sn(e){return function(t){t instanceof RegExp&&(t.lastIndex=0);for(var r=arguments.length,n=new Array(r>1?r-1:0),i=1;i<r;i++)n[i-1]=arguments[i];return Xv(e,t,n)}}function nB(e){return function(){for(var t=arguments.length,r=new Array(t),n=0;n<t;n++)r[n]=arguments[n];return Zv(e,r)}}function vr(e,t){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:Kd;if(qS&&qS(e,null),!Fc(t))return e;let n=t.length;for(;n--;){let i=t[n];if(typeof i=="string"){const o=r(i);o!==i&&(Xj(t)||(t[n]=o),i=o)}e[i]=!0}return e}function iB(e){for(let t=0;t<e.length;t++)yi(e,t)||(e[t]=null);return e}function Oi(e){const t=Pc(null);for(const n of _x(e)){var r=Gj(n,2);const i=r[0],o=r[1];yi(e,i)&&(Fc(o)?t[i]=iB(o):o&&typeof o=="object"&&o.constructor===Object?t[i]=Oi(o):t[i]=o)}return t}function oB(e){switch(typeof e){case"string":return e;case"number":return tB(e);case"boolean":return rB(e);case"bigint":return XS?XS(e):"0";case"symbol":return ZS?ZS(e):"Symbol()";case"undefined":return _d(e);case"function":case"object":{if(e===null)return _d(e);const t=e,r=Qi(t,"toString");if(typeof r=="function"){const n=r(t);return typeof n=="string"?n:_d(n)}return _d(e)}default:return _d(e)}}function Qi(e,t){for(;e!==null;){const n=Yj(e,t);if(n){if(n.get)return Sn(n.get);if(typeof n.value=="function")return Sn(n.value)}e=Zj(e)}function r(){return null}return r}function sB(e){try{return Xn(e,""),!0}catch{return!1}}var YS=An(["a","abbr","acronym","address","area","article","aside","audio","b","bdi","bdo","big","blink","blockquote","body","br","button","canvas","caption","center","cite","code","col","colgroup","content","data","datalist","dd","decorator","del","details","dfn","dialog","dir","div","dl","dt","element","em","fieldset","figcaption","figure","font","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","img","input","ins","kbd","label","legend","li","main","map","mark","marquee","menu","menuitem","meter","nav","nobr","ol","optgroup","option","output","p","picture","pre","progress","q","rp","rt","ruby","s","samp","search","section","select","shadow","slot","small","source","spacer","span","strike","strong","style","sub","summary","sup","table","tbody","td","template","textarea","tfoot","th","thead","time","tr","track","tt","u","ul","var","video","wbr"]),wg=An(["svg","a","altglyph","altglyphdef","altglyphitem","animatecolor","animatemotion","animatetransform","circle","clippath","defs","desc","ellipse","enterkeyhint","exportparts","filter","font","g","glyph","glyphref","hkern","image","inputmode","line","lineargradient","marker","mask","metadata","mpath","part","path","pattern","polygon","polyline","radialgradient","rect","stop","style","switch","symbol","text","textpath","title","tref","tspan","view","vkern"]),Sg=An(["feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feDropShadow","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence"]),aB=An(["animate","color-profile","cursor","discard","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","foreignobject","hatch","hatchpath","mesh","meshgradient","meshpatch","meshrow","missing-glyph","script","set","solidcolor","unknown","use"]),Ig=An(["math","menclose","merror","mfenced","mfrac","mglyph","mi","mlabeledtr","mmultiscripts","mn","mo","mover","mpadded","mphantom","mroot","mrow","ms","mspace","msqrt","mstyle","msub","msup","msubsup","mtable","mtd","mtext","mtr","munder","munderover","mprescripts"]),lB=An(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),JS=An(["#text"]),QS=An(["accept","action","align","alt","autocapitalize","autocomplete","autopictureinpicture","autoplay","background","bgcolor","border","capture","cellpadding","cellspacing","checked","cite","class","clear","color","cols","colspan","command","commandfor","controls","controlslist","coords","crossorigin","datetime","decoding","default","dir","disabled","disablepictureinpicture","disableremoteplayback","download","draggable","enctype","enterkeyhint","exportparts","face","for","headers","height","hidden","high","href","hreflang","id","inert","inputmode","integrity","ismap","kind","label","lang","list","loading","loop","low","max","maxlength","media","method","min","minlength","multiple","muted","name","nonce","noshade","novalidate","nowrap","open","optimum","part","pattern","placeholder","playsinline","popover","popovertarget","popovertargetaction","poster","preload","pubdate","radiogroup","readonly","rel","required","rev","reversed","role","rows","rowspan","spellcheck","scope","selected","shape","size","sizes","slot","span","srclang","start","src","srcset","step","style","summary","tabindex","title","translate","type","usemap","valign","value","width","wrap","xmlns"]),kg=An(["accent-height","accumulate","additive","alignment-baseline","amplitude","ascent","attributename","attributetype","azimuth","basefrequency","baseline-shift","begin","bias","by","class","clip","clippathunits","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","cx","cy","d","dx","dy","diffuseconstant","direction","display","divisor","dominant-baseline","dur","edgemode","elevation","end","exponent","fill","fill-opacity","fill-rule","filter","filterunits","flood-color","flood-opacity","font-family","font-size","font-size-adjust","font-stretch","font-style","font-variant","font-weight","fx","fy","g1","g2","glyph-name","glyphref","gradientunits","gradienttransform","height","href","id","image-rendering","in","in2","intercept","k","k1","k2","k3","k4","kerning","keypoints","keysplines","keytimes","lang","lengthadjust","letter-spacing","kernelmatrix","kernelunitlength","lighting-color","local","marker-end","marker-mid","marker-start","markerheight","markerunits","markerwidth","maskcontentunits","maskunits","max","mask","mask-type","media","method","mode","min","name","numoctaves","offset","operator","opacity","order","orient","orientation","origin","overflow","paint-order","path","pathlength","patterncontentunits","patterntransform","patternunits","pointer-events","points","preservealpha","preserveaspectratio","primitiveunits","r","rx","ry","radius","refx","refy","repeatcount","repeatdur","restart","result","rotate","scale","seed","shape-rendering","slope","specularconstant","specularexponent","spreadmethod","startoffset","stddeviation","stitchtiles","stop-color","stop-opacity","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke","stroke-width","style","surfacescale","systemlanguage","tabindex","tablevalues","targetx","targety","transform","transform-origin","text-anchor","text-decoration","text-orientation","text-rendering","textlength","type","u1","u2","unicode","values","vector-effect","viewbox","visibility","version","vert-adv-y","vert-origin-x","vert-origin-y","width","word-spacing","wrap","writing-mode","xchannelselector","ychannelselector","x","x1","x2","xmlns","y","y1","y2","z","zoomandpan"]),e1=An(["accent","accentunder","align","bevelled","close","columnalign","columnlines","columnspacing","columnspan","denomalign","depth","dir","display","displaystyle","encoding","fence","frame","height","href","id","largeop","length","linethickness","lquote","lspace","mathbackground","mathcolor","mathsize","mathvariant","maxsize","minsize","movablelimits","notation","numalign","open","rowalign","rowlines","rowspacing","rowspan","rspace","rquote","scriptlevel","scriptminsize","scriptsizemultiplier","selection","separator","separators","stretchy","subscriptshift","supscriptshift","symmetric","voffset","width","xmlns"]),Jf=An(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),cB=zn(/{{[\w\W]*|^[\w\W]*}}/g),dB=zn(/<%[\w\W]*|^[\w\W]*%>/g),uB=zn(/\${[\w\W]*/g),fB=zn(/^data-[\-\w.\u00B7-\uFFFF]+$/),hB=zn(/^aria-[\-\w]+$/),t1=zn(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),pB=zn(/^(?:\w+script|data):/i),mB=zn(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),gB=zn(/^html$/i),vB=zn(/^[a-z][.\w]*(-[.\w]+)+$/i),r1=zn(/<[/\w!]/g),n1=zn(/<[/\w]/g),yB=zn(/<\/no(script|embed|frames)/i),bB=zn(/\/>/i),Mi={element:1,attribute:2,text:3,cdataSection:4,entityReference:5,entityNode:6,processingInstruction:7,comment:8,document:9,documentType:10,documentFragment:11,notation:12},Ax=["style","script","xmp","iframe","noembed","noframes","plaintext","noscript"],wB=An(vr({},Ax)),SB=(function(){const e={};return Qa(Ax,t=>{e[t]=zn(new RegExp("</"+t+"(?=[\\t\\n\\f\\r />])","i"))}),An(e)})(),IB=function(){return typeof window>"u"?null:window},kB=function(e,t){if(typeof e!="object"||typeof e.createPolicy!="function")return null;let r=null;const n="data-tt-policy-suffix";t&&t.hasAttribute(n)&&(r=t.getAttribute(n));const i="dompurify"+(r?"#"+r:"");try{return e.createPolicy(i,{createHTML(o){return o},createScriptURL(o){return o}})}catch{return console.warn("TrustedTypes policy "+i+" could not be created."),null}},i1=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}},ua=function(e,t,r,n){return yi(e,t)&&Fc(e[t])?vr(n.base?Oi(n.base):{},e[t],n.transform):r},Tg=function(e,t,r){const n=yi(e,t)?e[t]:void 0;return n&&typeof n=="object"?Oi(n):r()};function Mx(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:IB();const t=m=>Mx(m);if(t.version="3.4.16",t.removed=[],!e||!e.document||e.document.nodeType!==Mi.document||!e.Element)return t.isSupported=!1,t;let r=e.document;const n=r,i=n.currentScript;e.DocumentFragment;const o=e.HTMLTemplateElement,s=e.Node,a=e.Element,l=e.NodeFilter;e.NamedNodeMap===void 0&&(e.NamedNodeMap||e.MozNamedAttrMap),e.HTMLFormElement;const d=e.DOMParser,c=e.trustedTypes,u=a.prototype,f=Qi(u,"cloneNode"),p=Qi(u,"remove"),g=Qi(u,"removeAttributeNode"),v=Qi(u,"nextSibling"),b=Qi(u,"childNodes"),w=Qi(u,"parentNode"),I=Qi(u,"shadowRoot"),x=Qi(u,"attributes"),C=s&&s.prototype?Qi(s.prototype,"nodeType"):null,L=s&&s.prototype?Qi(s.prototype,"nodeName"):null,E=s&&s.prototype?Qi(s.prototype,"ownerDocument"):null,M=function(m){return C?C(m):m.nodeType},U=function(m){return L?L(m):m.nodeName};if(typeof o=="function"){const m=r.createElement("template");m.content&&m.content.ownerDocument&&(r=m.content.ownerDocument)}let te,re="",Pe,z=!1,K=0;const oe=function(){if(K>0)throw da('A configured TRUSTED_TYPES_POLICY callback (createHTML or createScriptURL) must not call DOMPurify.sanitize, as that causes infinite recursion. Do not pass a policy whose callbacks wrap DOMPurify as TRUSTED_TYPES_POLICY; see the "DOMPurify and Trusted Types" section of the README.')},ue=function(m){oe(),K++;try{return te.createHTML(m)}finally{K--}},ae=function(m){oe(),K++;try{return te.createScriptURL(m)}finally{K--}},X=function(){return z||(Pe=kB(c,i),z=!0),Pe},j=r,D=j.implementation,Z=j.createNodeIterator,F=j.createDocumentFragment,W=j.getElementsByTagName,O=n.importNode;let $=i1();t.isSupported=typeof _x=="function"&&typeof w=="function"&&D&&D.createHTMLDocument!==void 0;const ie=cB,N=dB,ne=uB,ge=fB,Oe=hB,We=pB,Ne=mB,xe=vB;let et=t1,Ue=null;const Se=vr({},[...YS,...wg,...Sg,...Ig,...JS]);let Re=null;const mt=vr({},[...QS,...kg,...e1,...Jf]);let $t=Object.seal(Pc(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),ve=null,me=null;const Je=Object.seal(Pc(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}}));let Gt=!0,le=!0,Ae=!1,Y=!0,we=!1,_e=!0,Be=!1,it=!1,tt=null,Bt=null,ht=!1,ot=!1,$r=!1,Ur=!1,Lr=!0,ln=!1;const qr="user-content-";let xr=!0,Ar=!1,ye={},vt=null;const kt=vr({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","selectedcontent","style","svg","template","thead","title","video","xmp"]);let Qe=null;const cr=vr({},["audio","video","img","source","image","track"]);let V=null;const ke=vr({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),qe="http://www.w3.org/1998/Math/MathML",Ve="http://www.w3.org/2000/svg",at="http://www.w3.org/1999/xhtml";let Rt=at,Rr=!1,Vr=null;const jr=vr({},[qe,Ve,at],bg),dr=An(["mi","mo","mn","ms","mtext"]);let fe=vr({},dr);const _t=An(["annotation-xml"]);let Gr=vr({},_t);const tn=vr({},["title","style","font","a","script"]);let Wn=null;const ei=["application/xhtml+xml","text/html"],ta="text/html";let Cr=null,ti=null;const Qo=r.createElement("form"),H=function(m){return m instanceof RegExp||m instanceof Function},ce=function(){let m=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(ti&&ti===m)return;(!m||typeof m!="object")&&(m={}),m=Oi(m),Wn=ei.indexOf(m.PARSER_MEDIA_TYPE)===-1?ta:m.PARSER_MEDIA_TYPE,Cr=Wn==="application/xhtml+xml"?bg:Kd,Ue=ua(m,"ALLOWED_TAGS",Se,{transform:Cr}),Re=ua(m,"ALLOWED_ATTR",mt,{transform:Cr}),Vr=ua(m,"ALLOWED_NAMESPACES",jr,{transform:bg}),V=ua(m,"ADD_URI_SAFE_ATTR",ke,{transform:Cr,base:ke}),Qe=ua(m,"ADD_DATA_URI_TAGS",cr,{transform:Cr,base:cr}),vt=ua(m,"FORBID_CONTENTS",kt,{transform:Cr}),ve=ua(m,"FORBID_TAGS",Oi({}),{transform:Cr}),me=ua(m,"FORBID_ATTR",Oi({}),{transform:Cr}),ye=yi(m,"USE_PROFILES")?m.USE_PROFILES&&typeof m.USE_PROFILES=="object"?Oi(m.USE_PROFILES):m.USE_PROFILES:!1,Gt=m.ALLOW_ARIA_ATTR!==!1,le=m.ALLOW_DATA_ATTR!==!1,Ae=m.ALLOW_UNKNOWN_PROTOCOLS||!1,Y=m.ALLOW_SELF_CLOSE_IN_ATTR!==!1,we=m.SAFE_FOR_TEMPLATES||!1,_e=m.SAFE_FOR_XML!==!1,Be=m.WHOLE_DOCUMENT||!1,ot=m.RETURN_DOM||!1,$r=m.RETURN_DOM_FRAGMENT||!1,Ur=m.RETURN_TRUSTED_TYPE||!1,ht=m.FORCE_BODY||!1,Lr=m.SANITIZE_DOM!==!1,ln=m.SANITIZE_NAMED_PROPS||!1,xr=m.KEEP_CONTENT!==!1,Ar=m.IN_PLACE||!1,et=sB(m.ALLOWED_URI_REGEXP)?m.ALLOWED_URI_REGEXP:t1,Rt=typeof m.NAMESPACE=="string"?m.NAMESPACE:at,fe=Tg(m,"MATHML_TEXT_INTEGRATION_POINTS",()=>vr({},dr)),Gr=Tg(m,"HTML_INTEGRATION_POINTS",()=>vr({},_t));const k=Tg(m,"CUSTOM_ELEMENT_HANDLING",()=>Pc(null));if($t=Pc(null),yi(k,"tagNameCheck")&&H(k.tagNameCheck)&&($t.tagNameCheck=k.tagNameCheck),yi(k,"attributeNameCheck")&&H(k.attributeNameCheck)&&($t.attributeNameCheck=k.attributeNameCheck),yi(k,"allowCustomizedBuiltInElements")&&typeof k.allowCustomizedBuiltInElements=="boolean"&&($t.allowCustomizedBuiltInElements=k.allowCustomizedBuiltInElements),zn($t),we&&(le=!1),$r&&(ot=!0),ye&&(Ue=vr({},JS),Re=Pc(null),ye.html===!0&&(vr(Ue,YS),vr(Re,QS)),ye.svg===!0&&(vr(Ue,wg),vr(Re,kg),vr(Re,Jf)),ye.svgFilters===!0&&(vr(Ue,Sg),vr(Re,kg),vr(Re,Jf)),ye.mathMl===!0&&(vr(Ue,Ig),vr(Re,e1),vr(Re,Jf))),Je.tagCheck=null,Je.attributeCheck=null,yi(m,"ADD_TAGS")&&(typeof m.ADD_TAGS=="function"?Je.tagCheck=m.ADD_TAGS:Fc(m.ADD_TAGS)&&(Ue===Se&&(Ue=Oi(Ue)),vr(Ue,m.ADD_TAGS,Cr))),yi(m,"ADD_ATTR")&&(typeof m.ADD_ATTR=="function"?Je.attributeCheck=m.ADD_ATTR:Fc(m.ADD_ATTR)&&(Re===mt&&(Re=Oi(Re)),vr(Re,m.ADD_ATTR,Cr))),yi(m,"ADD_FORBID_CONTENTS")&&Fc(m.ADD_FORBID_CONTENTS)&&(vt===kt&&(vt=Oi(vt)),vr(vt,m.ADD_FORBID_CONTENTS,Cr)),xr&&(Ue["#text"]=!0),Be&&vr(Ue,["html","head","body"]),Ue.table&&(vr(Ue,["tbody"]),delete ve.tbody),m.TRUSTED_TYPES_POLICY){if(typeof m.TRUSTED_TYPES_POLICY.createHTML!="function")throw da('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof m.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw da('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');const B=te;te=m.TRUSTED_TYPES_POLICY;try{re=ue("")}catch(J){throw te=B,J}}else m.TRUSTED_TYPES_POLICY===null?(te=void 0,re=""):(te===void 0&&(te=X()),te&&typeof re=="string"&&(re=ue("")));An&&An(m),ti=m},se=vr({},[...wg,...Sg,...aB]),de=vr({},[...Ig,...lB]),lt=function(m,k,B){return k.namespaceURI===at?m==="svg":k.namespaceURI===qe?m==="svg"&&(B==="annotation-xml"||fe[B]):!!se[m]},nr=function(m,k,B){return k.namespaceURI===at?m==="math":k.namespaceURI===Ve?m==="math"&&Gr[B]:!!de[m]},Ee=function(m,k,B){return k.namespaceURI===Ve&&!Gr[B]||k.namespaceURI===qe&&!fe[B]?!1:!de[m]&&(tn[m]||!se[m])},rt=function(m){let k=w(m);(!k||!k.tagName)&&(k={namespaceURI:Rt,tagName:"template"});const B=Kd(m.tagName),J=Kd(k.tagName);return Vr[m.namespaceURI]?m.namespaceURI===Ve?lt(B,k,J):m.namespaceURI===qe?nr(B,k,J):m.namespaceURI===at?Ee(B,k,J):!!(Wn==="application/xhtml+xml"&&Vr[m.namespaceURI]):!1},sr=function(m){xd(t.removed,{element:m});try{w(m).removeChild(m)}catch{if(p(m),!w(m))throw da("a node selected for removal could not be detached from its tree and cannot be safely returned; refusing to sanitize in place")}},Pt=function(m,k,B){try{g(m,k)}catch{try{m.removeAttribute(B)}catch{}}},$e=function(m){Ir(m);const k=b(m);if(k){const J=[];Qa(k,Me=>{xd(J,Me)}),Qa(J,Me=>{try{p(Me)}catch{}})}const B=x(m);if(B)for(let J=B.length-1;J>=0;--J){const Me=B[J],st=Me&&Me.name;typeof st=="string"&&Pt(m,Me,st)}},wr=function(m,k,B){if(!B)try{B=k.getAttributeNode(m)}catch{B=null}xd(t.removed,{attribute:B||null,from:k});try{B?g(k,B):k.removeAttribute(m)}catch{try{k.removeAttribute(m)}catch{}}if(m==="is")if(ot||$r)try{sr(k)}catch{}else try{k.setAttribute(m,"")}catch{}},hn=function(m){const k=x(m);if(k)for(let B=k.length-1;B>=0;--B){const J=k[B],Me=J&&J.name;typeof Me!="string"||Re[Cr(Me)]||Pt(m,J,Me)}},Ir=function(m){const k=[m];for(;k.length>0;){const B=k.pop();M(B)===Mi.element&&hn(B);const J=b(B);if(J)for(let Me=J.length-1;Me>=0;--Me)k.push(J[Me])}},Br=function(m,k){return _e?m==="patchsrc"?!0:m==="for"&&k!=="label"&&k!=="output":!1},mr=function(m){if(!_e)return;const k=[m];for(;k.length>0;){const B=k.pop(),J=M(B);if(J===Mi.processingInstruction||J===Mi.comment&&Xn(n1,B.data)){try{p(B)}catch{}continue}if(J===Mi.element){const st=B,yt=Cr(U(B));try{st.hasAttribute&&st.hasAttribute("patchsrc")&&st.removeAttribute("patchsrc"),st.hasAttribute&&st.hasAttribute("for")&&Br("for",yt)&&st.removeAttribute("for")}catch{}}const Me=b(B);if(Me)for(let st=Me.length-1;st>=0;--st)k.push(Me[st])}},ur=function(m){let k=null,B=null;if(ht)m="<remove></remove>"+m;else{const st=GS(m,/^[\r\n\t ]+/);B=st&&st[0]}Wn==="application/xhtml+xml"&&Rt===at&&(m='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+m+"</body></html>");const J=te?ue(m):m;if(Rt===at)try{k=new d().parseFromString(J,Wn)}catch{}if(!k||!k.documentElement){k=D.createDocument(Rt,"template",null);try{k.documentElement.innerHTML=Rr?re:J}catch{}}const Me=k.body||k.documentElement;return m&&B&&Me.insertBefore(r.createTextNode(B),Me.childNodes[0]||null),Rt===at?W.call(k,Be?"html":"body")[0]:Be?k.documentElement:Me},Lt=function(m){const k=E?E(m):m.ownerDocument;return Z.call(k||m,m,l.SHOW_ELEMENT|l.SHOW_COMMENT|l.SHOW_TEXT|l.SHOW_PROCESSING_INSTRUCTION|l.SHOW_CDATA_SECTION,null)},gr=function(m){return m=Rd(m,ie," "),m=Rd(m,N," "),m=Rd(m,ne," "),m},Fr=function(m){var k;m.normalize();const B=E?E(m):m.ownerDocument,J=Z.call(B||m,m,l.SHOW_TEXT|l.SHOW_COMMENT|l.SHOW_CDATA_SECTION|l.SHOW_PROCESSING_INSTRUCTION,null);let Me=J.nextNode();for(;Me;)Me.data=gr(Me.data),Me=J.nextNode();const st=(k=m.querySelectorAll)===null||k===void 0?void 0:k.call(m,"template");st&&Qa(st,yt=>{dt(yt.content)&&Fr(yt.content)})},Yt=function(m){const k=L?L(m):null;return typeof k!="string"||Cr(k)!=="form"?!1:typeof m.nodeName!="string"||typeof m.textContent!="string"||typeof m.removeChild!="function"||m.attributes!==x(m)||typeof m.removeAttribute!="function"||typeof m.removeAttributeNode!="function"||typeof m.getAttributeNode!="function"||typeof m.setAttribute!="function"||typeof m.namespaceURI!="string"||typeof m.insertBefore!="function"||typeof m.hasChildNodes!="function"||m.nodeType!==C(m)||m.childNodes!==b(m)},dt=function(m){if(!C||typeof m!="object"||m===null)return!1;try{return C(m)===Mi.documentFragment}catch{return!1}},zt=function(m){if(!C||typeof m!="object"||m===null)return!1;try{return typeof C(m)=="number"}catch{return!1}};function fr(m,k,B){m.length!==0&&Qa(m,J=>{J.call(t,k,B,ti)})}const Kn=function(m,k){return!!(_e&&m.hasChildNodes()&&!zt(m.firstElementChild)&&Xn(r1,m.textContent)&&Xn(r1,m.innerHTML)||_e&&m.namespaceURI===at&&wB[k]&&(zt(m.firstElementChild)||typeof m.textContent=="string"&&Xn(SB[k],m.textContent))||m.nodeType===Mi.processingInstruction||_e&&m.nodeType===Mi.comment&&Xn(n1,m.data))},_r=function(m,k){if(m instanceof RegExp)return Xn(m,k);if(m instanceof Function){for(var B=arguments.length,J=new Array(B>2?B-2:0),Me=2;Me<B;Me++)J[Me-2]=arguments[Me];return!!m(k,...J)}return!1},$n=function(m,k,B){if(!ve[k]&&kr(k)&&_r($t.tagNameCheck,k))return!1;if(xr&&!vt[k]){const J=w(m),Me=b(m);if(Me&&J){const st=Me.length;for(let yt=st-1;yt>=0;--yt){const Jt=m===B?f(Me[yt],!0):Me[yt];J.insertBefore(Jt,v(m))}}}return sr(m),!0},ri=function(m,k,B,J){return m.length===0?k:k===B||k===J?Oi(k):k},pn=function(m,k){return m===k||w(m)!==null?!1:(Ar&&Ir(m),!0)},Zr=function(m,k){if(fr($.beforeSanitizeElements,m,null),pn(m,k))return!0;if(Yt(m))return sr(m),!0;const B=Cr(U(m));if(Ue=ri($.uponSanitizeElement,Ue,Se,tt),fr($.uponSanitizeElement,m,{tagName:B,allowedTags:Ue}),pn(m,k))return!0;if(Kn(m,B))return sr(m),!0;if(ve[B]||!(Je.tagCheck instanceof Function&&Je.tagCheck(B))&&!Ue[B]){const J=$n(m,B,k);return J===!1&&(fr($.afterSanitizeElements,m,null),pn(m,k))?!0:J}if(M(m)===Mi.element&&!rt(m)||(B==="noscript"||B==="noembed"||B==="noframes")&&Xn(yB,m.innerHTML))return sr(m),!0;if(we&&m.nodeType===Mi.text){const J=gr(m.textContent);m.textContent!==J&&(xd(t.removed,{element:m.cloneNode()}),m.textContent=J)}return fr($.afterSanitizeElements,m,null),pn(m,k)},Pr=function(m,k,B){if(me[k]||Br(k,m)||Lr&&(k==="id"||k==="name")&&(B in r||B in Qo))return!1;const J=Re[k]||Je.attributeCheck instanceof Function&&Je.attributeCheck(k,m);return le&&Xn(ge,k)||Gt&&Xn(Oe,k)?!0:J?V[k]||Xn(et,Rd(B,Ne,""))||(k==="src"||k==="xlink:href"||k==="href")&&m!=="script"&&KS(B,"data:")===0&&Qe[m]||Ae&&!Xn(We,Rd(B,Ne,""))?!0:!B:kr(m)&&_r($t.tagNameCheck,m)&&_r($t.attributeNameCheck,k,m)||k==="is"&&$t.allowCustomizedBuiltInElements&&_r($t.tagNameCheck,B)},Or=vr({},["annotation-xml","color-profile","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","missing-glyph"]),kr=function(m){return!Or[Kd(m)]&&Xn(xe,m)},xt=function(m,k,B,J){if(te&&typeof c=="object"&&typeof c.getAttributeType=="function"&&!B)switch(c.getAttributeType(m,k)){case"TrustedHTML":return ue(J);case"TrustedScriptURL":return ae(J)}return J},Tr=function(m,k,B,J){try{return B?m.setAttributeNS(B,k,J):m.setAttribute(k,J),Yt(m)?(sr(m),!1):!0}catch{return wr(k,m),!1}},ni=function(m,k){if(fr($.beforeSanitizeAttributes,m,null),pn(m,k))return;const B=m.attributes;if(!B||Yt(m))return;Re=ri($.uponSanitizeAttribute,Re,mt,Bt);const J={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:Re,forceKeepAttr:void 0};let Me=B.length;const st=Cr(m.nodeName);for(;Me--;){const yt=B[Me],Jt=yt.name,ii=yt.namespaceURI,Un=yt.value,Nr=Cr(Jt),Pa=Un;let Yr=Jt==="value"?Pa:eB(Pa),Aa=!1;if(J.attrName=Nr,J.attrValue=Yr,J.keepAttr=!0,J.forceKeepAttr=void 0,fr($.uponSanitizeAttribute,m,J),Yr=J.attrValue,ln&&(Nr==="id"||Nr==="name")&&KS(Yr,qr)!==0&&(wr(Jt,m,yt),Yr=qr+Yr,Aa=!0),_e&&Xn(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,Yr)){wr(Jt,m,yt);continue}if(Nr==="attributename"&&GS(Yr,"href")){wr(Jt,m,yt);continue}if(!J.forceKeepAttr){if(!J.keepAttr){wr(Jt,m,yt);continue}if(!Y&&Xn(bB,Yr)){wr(Jt,m,yt);continue}if(we&&(Yr=gr(Yr)),!Pr(st,Nr,Yr)){wr(Jt,m,yt);continue}Yr=xt(st,Nr,ii,Yr),Yr!==Pa&&Tr(m,Jt,ii,Yr)&&Aa&&VS(t.removed)}}fr($.afterSanitizeAttributes,m,null),pn(m,k)},Ln=function(m){let k=null;const B=Lt(m);for(fr($.beforeSanitizeShadowDOM,m,null);k=B.nextNode();)if(fr($.uponSanitizeShadowNode,k,null),Zr(k,m),ni(k,m),dt(k.content)&&Ln(k.content),M(k)===Mi.element){const J=I(k);dt(J)&&(On(J),Ln(J))}fr($.afterSanitizeShadowDOM,m,null)},On=function(m){const k=[{node:m,shadow:null}];for(;k.length>0;){const B=k.pop();if(B.shadow){Ln(B.shadow);continue}const J=B.node,Me=M(J)===Mi.element,st=b(J);if(st)for(let yt=st.length-1;yt>=0;--yt)k.push({node:st[yt],shadow:null});if(Me){const yt=L?L(J):null;if(typeof yt=="string"&&Cr(yt)==="template"){const Jt=J.content;dt(Jt)&&k.push({node:Jt,shadow:null})}}if(Me){const yt=I(J);dt(yt)&&k.push({node:null,shadow:yt},{node:yt,shadow:null})}}};return t.sanitize=function(m){let k=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},B=null,J=null,Me=null,st=null;if(Rr=!m,Rr&&(m="<!-->"),typeof m!="string"&&!zt(m)&&(m=oB(m),typeof m!="string"))throw da("dirty is not a string, aborting");if(!t.isSupported)return m;it?(Ue=tt,Re=Bt):ce(k),($.uponSanitizeElement.length>0||$.uponSanitizeAttribute.length>0)&&(Ue=Oi(Ue)),$.uponSanitizeAttribute.length>0&&(Re=Oi(Re)),t.removed=[];const yt=Ar&&typeof m!="string"&&zt(m);if(yt){mr(m);const Un=U(m);if(typeof Un=="string"){const Nr=Cr(Un);if(!Ue[Nr]||ve[Nr])throw $e(m),da("root node is forbidden and cannot be sanitized in-place")}if(Yt(m))throw $e(m),da("root node is clobbered and cannot be sanitized in-place");try{On(m)}catch(Nr){throw $e(m),Nr}}else if(zt(m))B=ur("<!---->"),J=B.ownerDocument.importNode(m,!0),J.nodeType===Mi.element&&J.nodeName==="BODY"||J.nodeName==="HTML"?B=J:B.appendChild(J),On(B);else{if(!ot&&!we&&!Be&&m.indexOf("<")===-1)return te&&Ur?ue(m):m;if(B=ur(m),!B)return ot?null:Ur?re:""}B&&ht&&sr(B.firstChild);const Jt=yt?m:B;try{const Un=Lt(Jt);for(;Me=Un.nextNode();)Zr(Me,Jt),ni(Me,Jt),dt(Me.content)&&Ln(Me.content)}catch(Un){throw yt&&($e(m),Qa(t.removed,Nr=>{Nr.element&&Ir(Nr.element)})),Un}if(yt){let Un=!1;if(Qa(t.removed,Nr=>{Nr.element&&(Nr.element===m&&(Un=!0),Ir(Nr.element))}),Un)throw da("a node selected for removal could not be safely returned; refusing to sanitize in place");return we&&Fr(m),m}if(ot){if(we&&Fr(B),$r)for(st=F.call(B.ownerDocument);B.firstChild;)st.appendChild(B.firstChild);else st=B;return(Re.shadowroot||Re.shadowrootmode)&&(st=O.call(n,st,!0)),st}let ii=Be?B.outerHTML:B.innerHTML;return Be&&Ue["!doctype"]&&B.ownerDocument&&B.ownerDocument.doctype&&B.ownerDocument.doctype.name&&Xn(gB,B.ownerDocument.doctype.name)&&(ii="<!DOCTYPE "+B.ownerDocument.doctype.name+`>
977
+ `+ii),we&&(ii=gr(ii)),te&&Ur?ue(ii):ii},t.setConfig=function(){let m=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};ce(m),it=!0,tt=Ue,Bt=Re},t.clearConfig=function(){ti=null,it=!1,tt=null,Bt=null,te=Pe,re=""},t.isValidAttribute=function(m,k,B){ti||ce({});const J=Cr(m),Me=Cr(k);return Pr(J,Me,B)},t.addHook=function(m,k){typeof k=="function"&&yi($,m)&&xd($[m],k)},t.removeHook=function(m,k){if(yi($,m)){if(k!==void 0){const B=Jj($[m],k);return B===-1?void 0:Qj($[m],B,1)[0]}return VS($[m])}},t.removeHooks=function(m){yi($,m)&&($[m]=[])},t.removeAllHooks=function(){$=i1()},t}var o1=Mx();function TB(e,t={}){if(typeof e!="string"||e.length===0)return{ok:!1,reason:"invalid-url",message:"External stylesheet URL must be a non-empty string."};let r;try{r=t.baseUrl?new URL(e,t.baseUrl):new URL(e)}catch(o){return{ok:!1,reason:"invalid-url",message:`External stylesheet URL could not be parsed: ${String(o)}`}}if(r.protocol!=="http:"&&r.protocol!=="https:")return{ok:!1,reason:"disallowed-protocol",message:`External stylesheet protocol ${r.protocol} is not allowed (only http/https).`};const n=t.allowedOrigins??[];if(n.length>0)return n.includes(r.origin)?{ok:!0,resolvedUrl:r}:{ok:!1,reason:"disallowed-origin",message:`External stylesheet origin ${r.origin} is not in the configured allow-list.`};let i=null;if(t.baseUrl)try{i=new URL(t.baseUrl).origin}catch{i=null}return i===null?{ok:!1,reason:"disallowed-origin",message:"External stylesheet origin cannot be checked: no allow-list is configured and no usable baseUrl was supplied. Pass allowedOrigins to permit a cross-origin stylesheet."}:r.origin!==i?{ok:!1,reason:"disallowed-origin",message:`External stylesheet origin ${r.origin} is cross-origin and no allow-list is configured. Add it to \`allowed-style-origins\` to permit it.`}:{ok:!0,resolvedUrl:r}}function EB(e){return typeof e!="string"||e.length===0?[]:e.split(",").map(t=>t.trim()).filter(t=>t.length>0)}function CB(e){const t=new Map;for(const n of Object.values(e)){const i=String(n),o=jp(i).name,s=t.get(o)??new Set;s.add(i),t.set(o,s)}const r=[...t.entries()].filter(([,n])=>n.size>1).map(([n])=>n).sort();return r.length>0?`IIFE bundles cannot load multiple package specs for: ${r.join(", ")}`:void 0}function xB(e){const t=e.bundleType??To.clientPlayer,r=e.needsControllers??!0;let n=s1;const i=new Map,o={replaceLoadBundleScript(f){n=f,i.clear()},restore(){n=s1,i.clear()}};async function s(f,p){const g=i.get(f);if(g)return g;const v=a(f,p).finally(()=>{i.delete(f)});return i.set(f,v),v}async function a(f,p){const{retryDelayMs:g,timeoutMs:v}=AB(e.bundleRetry),b=Date.now();let w=0;for(;;){w+=1;try{await n(f,p);const I=Date.now()-b;w>1&&(e.onBundleRetryStatus?.({state:"completed",url:f,attempt:w,elapsedMs:I,timeoutMs:v}),d("pie-iife-bundle-retry-success",{url:f,attempt:w,elapsedMs:I,timeoutMs:v}));return}catch(I){const x=Date.now()-b,C=v-x,L=I instanceof Error?I.message:String(I);if(C<=0){const M=new Error(`IIFE bundle load timed out after ${v}ms: ${f}`);throw e.onBundleRetryStatus?.({state:"timeout",url:f,attempt:w,elapsedMs:x,timeoutMs:v,reason:L}),d("pie-iife-bundle-retry-timeout",{url:f,attempt:w,elapsedMs:x,timeoutMs:v,lastError:L}),c(M,{url:f,attempt:w,elapsedMs:x,timeoutMs:v,lastError:L}),M}const E=Math.min(g,C);e.onBundleRetryStatus?.({state:"retrying",url:f,attempt:w,elapsedMs:x,timeoutMs:v,retryDelayMs:E,reason:L}),d("pie-iife-bundle-retry",{url:f,attempt:w,elapsedMs:x,retryDelayMs:E,timeoutMs:v,lastError:L}),await MB(E)}}}function l(){if(!e.trackPageActions)return;const f=e.instrumentationProvider;if(By(f)&&f.isReady())return f}function d(f,p){const g=l();if(g)try{g.trackEvent(f,p)}catch{}}function c(f,p){const g=l();if(g)try{g.trackError(f,{...p,component:"iife-adapter",errorType:"IifeBundleRetryError"})}catch{}}async function u(f,p){if(!f||Object.keys(f).length===0)return;const g=CB(f);if(g){const x=new Map;for(const C of Object.keys(f))x.set(C,{kind:"backend-rejected",tag:C,cause:g});throw new Ac(x)}const v=_B(f,t,e);try{await s(v,p.doc)}catch(x){const C=x instanceof Error?x.message:String(x),L=new Map;for(const E of Object.keys(f))L.set(E,{kind:"bundle-load-failed",tag:E,url:v,cause:C});throw new Ac(L)}const b=RB();if(!b){const x=new Map;for(const C of Object.keys(f))x.set(C,{kind:"bundle-load-failed",tag:C,url:v,cause:"window.pie.default missing after bundle load"});throw new Ac(x)}const w=new Map,I=t===To.editor;for(const[x,C]of Object.entries(f)){const L=EP(C),E=b[L];if(!E){w.set(x,{kind:"package-not-in-bundle",tag:x,packageName:L,availablePackages:Object.keys(b)});continue}const M=I?E.Configure??$B():E.Element;if(!M){w.set(x,{kind:"no-element-class",tag:x,packageName:L});continue}if(!vP(M)){w.set(x,{kind:"not-a-constructor",tag:x,packageName:L});continue}let U;try{U=wP(x,`element tag for ${L}`)}catch(te){w.set(x,{kind:"define-failed",tag:x,cause:te instanceof Error?te.message:String(te)});continue}try{vk(U,class extends M{},`element tag for ${L}`)}catch(te){w.set(x,{kind:"define-failed",tag:x,cause:te instanceof Error?te.message:String(te)});continue}yk({package:C,status:jy.loaded,tagName:U,element:M,controller:r?E.controller??null:null,config:E.config??null,bundleType:t})}if(w.size>0)throw new Ac(w)}return{load:u,get __seams(){return o}}}function s1(e,t){return new Promise((r,n)=>{const i=t.createElement("script");i.src=e,i.defer=!0,i.setAttribute("data-pie-bundle","true"),i.onload=()=>r(),i.onerror=()=>n(new Error(`Failed to load IIFE bundle from: ${e}`)),t.head.appendChild(i)})}function RB(){const e=globalThis.window?.pie?.default;if(!(!e||typeof e!="object"))return e}function _B(e,t,r){const n=Object.keys(e).sort().join(",");if(r.bundleInfo?.url){const s=r.bundleInfo.url.includes("?")?"&":"?";return n?`${r.bundleInfo.url}${s}elements=${encodeURIComponent(n)}`:r.bundleInfo.url}const i=gP(Object.values(e)),o=`${PB(r.bundleHost)}${i}/${t}`;return n?`${o}?elements=${encodeURIComponent(n)}`:o}function PB(e){return`${e.trim().replace(/\/+$/,"")}/`}function AB(e){return{retryDelayMs:typeof e?.retryDelayMs=="number"&&e.retryDelayMs>0?e.retryDelayMs:xp.retryDelayMs,timeoutMs:typeof e?.timeoutMs=="number"&&e.timeoutMs>0?e.timeoutMs:xp.timeoutMs}}function MB(e){return new Promise(t=>setTimeout(t,e))}function $B(){return class extends HTMLElement{constructor(...e){super(...e),Te(this,"_model",void 0),Te(this,"_configuration",void 0)}get model(){return this._model}set model(e){this._model=e}get configuration(){return this._configuration}set configuration(e){this._configuration=e}}}var $x=class extends Error{constructor(e,t,r){super(e),Te(this,"name","ElementLoaderError"),Te(this,"unregisteredTags",void 0),Te(this,"reasons",void 0),this.unregisteredTags=t,this.reasons=r}},LB=e=>{switch(e.kind){case"timeout":return`not defined within ${e.timeoutMs} ms`;case"module-load-failed":return`${e.specifier} failed to load: ${e.cause}`;case"bundle-load-failed":return`${e.url} failed to load: ${e.cause}`;case"define-failed":case"backend-rejected":return e.cause;case"not-a-constructor":return`${e.packageName??"its package"} exports no element constructor`;case"no-element-class":return`${e.packageName} exports no element class`;case"package-not-in-bundle":return`${e.packageName} is not in the bundle, which holds ${e.availablePackages.join(", ")||"no packages"}`}};function OB(e){if(e instanceof $x)return[...e.reasons].map(([t,r])=>`${t} (${r.kind}): ${LB(r)}`).join("; ")}var NB=class extends Error{constructor(e,t,r,n={}){super(DB(e,t,r,n)),Te(this,"name","ElementAssertionError"),Te(this,"expectedTags",void 0),Te(this,"missingTags",void 0),Te(this,"currentlyRegisteredTags",void 0),this.expectedTags=e,this.missingTags=t,this.currentlyRegisteredTags=r}};function DB(e,t,r,n){const i=t.map(o=>{const s=Lx(n[o]),a=du(o).baseName,l=s?r.filter(c=>jB(c)===s):r.filter(c=>du(c).baseName===a);!l.includes(a)&&df(a)&&l.push(a);const d=s??a;return l.length>0?`${d} is registered as [${l.join(", ")}]`:`nothing is registered for ${d}`});return`ElementLoader.assertRegistered: missing [${t.join(", ")}] of [${e.join(", ")}]; ${i.join("; ")}.`}function Lx(e){if(e)try{return jp(e).name||void 0}catch{return}}function jB(e){return Lx(Bp()[e]?.package)}var BB=5e3,FB=xp.timeoutMs,Qf=new Map,a1=new Map,HB=new Map;async function l1(e,t){if(!e||Object.keys(e).length===0)return;gk(e,t.elementPackagePolicy);const r=Object.keys(e),n=t.whenDefinedTimeoutMs??BB,i=t.loadTimeoutMs??FB;if(e7(r))return;const o=GB(t.backend,e),s=Qf.get(o);if(s)return s;const a=zB(e,r,qB(t.backend),{doc:VB(t.doc),whenDefinedTimeoutMs:n},n,i);Qf.set(o,a);try{await a}finally{Qf.get(o)===a&&Qf.delete(o)}}async function zB(e,t,r,n,i,o){let s;try{await WB(r.load(e,n),t,o)}catch(c){s=c instanceof Error?c:new Error(String(c))}const a=await Promise.all(t.map(async c=>{if(df(c))return{tag:c,ok:!0};const u=h1(s,c);if(u&&u.kind!=="timeout")return{tag:c,ok:!1};try{return await t7(c,i),{tag:c,ok:!0}}catch{return{tag:c,ok:!1}}})),l=new Set,d=new Map;for(const c of a){if(c.ok)continue;l.add(c.tag);const u=h1(s,c.tag);d.set(c.tag,u??{kind:"timeout",tag:c.tag,timeoutMs:i})}if(l.size>0)throw new $x(`Element registration failed; missing tags: ${[...l].join(", ")}`,l,d)}async function WB(e,t,r){let n;try{await Promise.race([e,new Promise((i,o)=>{n=setTimeout(()=>{const s=new Map;for(const a of t)s.set(a,{kind:"timeout",tag:a,timeoutMs:r});o(new Ac(s))},r)})])}finally{n&&clearTimeout(n)}}function UB(e){const t=Array.isArray(e)?{}:e??{},r=Array.isArray(e)?e:Object.keys(t);if(r.length===0)return;const n=r.filter(i=>!df(i));if(n.length!==0)throw new NB(r,n,r7(),t)}function qB(e){if(Ox(e))return e;if("kind"in e){if(e.kind==="iife")return xB(e);if(e.kind==="esm"){const t=Nx(e),r=HB.get(t);if(r)return r;const n=a1.get(t);if(n)return n;const i=TP(e);return a1.set(t,i),i}}throw new Error("ElementLoader: invalid backend option")}function Ox(e){return typeof e.load=="function"&&!("kind"in e)}function VB(e){if(e)return e;if(typeof document<"u")return document;throw new Error("ElementLoader: no Document available; pass options.doc explicitly")}function GB(e,t){const r=Nx(e),n=Object.entries(t).sort(([i],[o])=>i.localeCompare(o));return`${r}|${JSON.stringify(n)}`}var c1=new WeakMap,KB=0,d1=new WeakMap,XB=0,u1=new WeakMap,ZB=0;function Nx(e){if(Ox(e)){let t=c1.get(e);return t||(t=`b${++KB}`,c1.set(e,t)),`backend#${t}`}if("kind"in e){if(e.kind==="iife")return`iife#${f1({kind:"iife",bundleHost:e.bundleHost,bundleType:e.bundleType??"",needsControllers:e.needsControllers??!0,bundleInfo:e.bundleInfo??null,debugEnabled:e.debugEnabled??null,bundleRetry:e.bundleRetry??null,onBundleRetryStatus:e.onBundleRetryStatus??null,trackPageActions:e.trackPageActions??!1,instrumentationProvider:e.instrumentationProvider??null})}`;if(e.kind==="esm")return`esm#${f1({kind:"esm",cdnBaseUrl:e.cdnBaseUrl,cdnProvider:e.cdnProvider??null,moduleResolution:e.moduleResolution??"url",view:e.view??"delivery",viewConfig:e.viewConfig??null,loadControllers:e.loadControllers??!0,debugEnabled:e.debugEnabled??null,trackPageActions:e.trackPageActions??!1,instrumentationProvider:e.instrumentationProvider??null})}`}return"unknown"}function f1(e){return JSON.stringify(Yv(e,new Map))}function Yv(e,t){if(e==null)return e;const r=typeof e;if(r==="string"||r==="number"||r==="boolean")return e;if(r==="function")return{__functionRef:JB(e)};if(r!=="object")return String(e);const n=e,i=t.get(n);if(i)return{__cycleRef:i};const o=`cycle#${t.size+1}`;if(t.set(n,o),Array.isArray(e))return e.map(a=>Yv(a,t));if(!YB(e))return{__objectRef:QB(n)};const s={};for(const a of Object.keys(e).sort())s[a]=Yv(e[a],t);return s}function YB(e){if(!e||typeof e!="object")return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function JB(e){let t=d1.get(e);return t||(t=`fn#${++XB}`,d1.set(e,t)),t}function QB(e){let t=u1.get(e);return t||(t=`obj#${++ZB}`,u1.set(e,t)),t}function e7(e){return e.every(t=>df(t))}function df(e){return typeof customElements>"u"?!1:customElements.get(e)!==void 0}async function t7(e,t){if(typeof customElements>"u")throw new Error(`no customElements to await ${e}`);let r;try{return await Promise.race([customElements.whenDefined(e).then(()=>{}),new Promise((n,i)=>{r=setTimeout(()=>i(new Error(`Timeout waiting for ${e}`)),t)})])}finally{r&&clearTimeout(r)}}function r7(){return typeof window>"u"?[]:Object.values(Bp()).filter(e=>e?.status===jy.loaded).map(e=>e.tagName).filter(e=>typeof e=="string"&&df(e)).sort()}function h1(e,t){if(e)return e instanceof Ac?e.reasons.get(t):{kind:"backend-rejected",tag:t,cause:e.message}}function n7(e){return e.loadControllers??(e.author||!e.hosted)}function i7(e,t=s7()){const r=e?.elements;if(!t||!r||typeof r!="object")return e;let n=!1;const i={};for(const[o,s]of Object.entries(r)){const a=String(s),l=o7(a,t);i[o]=l??a,l!==void 0&&l!==a&&(n=!0)}return n?{...e,elements:i}:e}function o7(e,t){let r;try{r=jp(e).name}catch{return}const n=t[r];return typeof n=="string"&&n.length>0?n:void 0}function s7(){if(typeof window>"u")return;const e=window.PIE_PRELOADED_ELEMENTS;return e&&typeof e=="object"?e:void 0}function a7(e){if(typeof window>"u"||typeof customElements>"u")return[];const t=[];for(const[r,n]of Object.entries(e)){if(customElements.get(r))continue;const i=l7(r,n);if(!i)continue;const{entry:o,elementClass:s}=i;vk(r,class extends s{},`preloaded element tag for ${n}`),yk({...o,tagName:r}),t.push(r)}return t}function l7(e,t){const{existingEncodedVersion:r}=du(e);if(!r)return;let n;for(const i of Object.values(Bp())){if(i?.status!==jy.loaded||i.package!==t||typeof i.tagName!="string"||du(i.tagName).existingEncodedVersion!==r)continue;const o=customElements.get(i.tagName);o&&(!n||!n.entry.controller&&i.controller)&&(n={entry:i,elementClass:o})}return n}var Dx=(...e)=>e.reduce((t,r)=>{for(const n in r)Object.hasOwn(r,n)&&r[n]!==null&&r[n]!==void 0&&(t[n]=r[n]);return t},{}),so=Lu("pie-updates",()=>Ou()),jx=e=>{if(!e)return"missing";if(typeof e=="function")return"function";if(typeof e!="object")return typeof e;const t=Object.keys(e),r=e.default,n=r&&typeof r=="object"?Object.keys(r):[];return n.length>0?`object(keys=[${t.join(",")}],defaultKeys=[${n.join(",")}])`:`object(keys=[${t.join(",")}])`},c7=e=>{if(!e)return null;if(typeof e=="function")return e;if(typeof e!="object")return null;const t=e.model;if(typeof t=="function")return(n,i,o,s)=>t.call(e,n,i,o,s);const r=e.default;if(r&&typeof r=="object"){const n=r.model;if(typeof n=="function")return(i,o,s,a)=>n.call(r,i,o,s,a)}return null},d7=(e,t)=>{e.dispatchEvent(new CustomEvent("pie-controller-error",{detail:t,bubbles:!0,composed:!0}))},u7=e=>{const t=e.isConnected;return()=>t&&!e.isConnected},f7=async(e,t,r,n,i,o,s,a)=>{so.debug(`${o} Using controller, env:`,i),so.debug(`${o} Model before filter:`,{id:t.id,element:t.element,hasCorrectResponse:"correctResponse"in t});const l=(d,c,u)=>(so.debug(`${o} updateSession called for ${d} with:`,u),Object.assign(r,u),a?.(t.id,t.element,u),Promise.resolve());try{const d=c7(n);if(!d)throw new Error(`Controller contract mismatch: expected a model() function but received ${jx(n)}`);const c=await d(t,r,i,l),u=c&&typeof c=="object"?c:{},f={id:t.id,element:t.element,...u};if(so.debug(`${o} ✅ Controller filtered model:`,{id:f.id,element:f.element,hasCorrectResponse:"correctResponse"in f,mode:i.mode,role:i.role}),s())return;e.model=f,e.session=r}catch(d){throw so.error(`${o} ❌ Controller error:`,d),d}},h7=e=>{const{config:t,session:r,env:n,eventListeners:i,invokeControllerForModel:o,bundleType:s,onElementSessionUpdate:a}=Dx(mk,e);if(!n)throw new Error("env is required");if(!r)throw new Error("session is required");if(!t)throw new Error("config is required");return{config:t,session:r,env:n,eventListeners:i,invokeControllerForModel:o,bundleType:s,onElementSessionUpdate:a}},p7=async(e,t,r,n)=>{const{config:i,session:o,env:s,eventListeners:a,invokeControllerForModel:l,bundleType:d,onElementSessionUpdate:c}=r,u=i.models?.find(p=>p.id===e.id);if(!u)throw so.error(`${n} Model not found for`,t),new Error(`model not found for ${t}`);const f=hk(o,u.id,u.element);if(a&&Object.entries(a).forEach(([p,g])=>{e.addEventListener(p,g)}),s&&l){const p=Sx(t,d);if(!p){so.debug(`${n} ℹ️ No controller for ${t}, using server-processed model`),e.model=u,e.session=f;return}so.debug(`${n} Invoking controller for ${t}#${e.id}`,{mode:s.mode,role:s.role,hasCorrectResponse:"correctResponse"in u});const g=u7(e);try{await f7(e,u,f,p,s,`${n}(${t}#${e.id})`,g,c)}catch(v){const b=v instanceof Error?v.message:String(v),w=b.includes("Controller contract mismatch");if(so.error(`${n} Controller failed for ${t}#${e.id}:`,v),d7(e,{code:w?"PIE_CONTROLLER_CONTRACT_ERROR":"PIE_CONTROLLER_RUNTIME_ERROR",message:`${t} controller failed while applying model for ${e.id}. ${b}`,recoverable:!0,elementName:t,elementId:e.id,controllerShape:jx(p),cause:b}),g())return;e.model=u,e.session=f}}else so.debug(`${n} Direct model assignment for ${t}#${e.id} (no controller invocation requested)`),e.model=u,e.session=f},m7=(e,t)=>{const r=h7(t),{container:n}=Dx(mk,t),i=(n||document).querySelectorAll(e);return!i||i.length===0?(so.debug(`no elements found for ${e}`),Promise.resolve()):Promise.all(Array.from(i,o=>p7(o,e,r,"[updatePieElement]"))).then(()=>{})},Eg=(e,t,r,n,i,o)=>(so.debug("[updatePieElements] Updating all elements with env:",r),Promise.all(Object.entries(e.elements).map(([s,a])=>m7(s,{config:e,session:t,env:r,container:n,onElementSessionUpdate:i,bundleType:o}))).then(()=>{})),g7=Lu("instrumentation-event-bridge",()=>Ou());function v7(e){return e&&typeof e=="object"?e:typeof e>"u"?{}:{value:e}}function y7(e){g7.warn(`[InstrumentationEventBridge:${e}] Ignoring invalid instrumentation provider; expected InstrumentationProvider contract`)}function b7(e){try{e.provider.trackError(e.error instanceof Error?e.error:new Error(String(e.error??"Unknown instrumentation bridge error")),{component:e.component,errorType:"InstrumentationBridgeError",sourceEventName:e.sourceEventName})}catch{}}function w7(e){if(!e.host||!e.eventMap.length)return()=>{};if(!e.instrumentationProvider)return()=>{};if(!By(e.instrumentationProvider))return e.debug&&y7(e.component),()=>{};const t=e.instrumentationProvider,r=[],n=Math.max(0,e.dedupeWindowMs??0),i=new Map,o=(s,a)=>{const l=[a.assessmentId,a.sectionId,a.attemptId,a.itemId,a.canonicalItemId,a.sourceRuntimeId].map(d=>String(d??"")).join("|");return`${s.instrumentationEventName}|${l}`};for(const s of e.eventMap){const a=l=>{try{if(!t.isReady()||e.shouldTrackEvent&&!e.shouldTrackEvent(l))return;const d=v7(l.detail),c=new Date().toISOString(),u={...d,...e.staticAttributes,component:e.component,sourceEventName:s.sourceEventName,timestamp:c};if(n>0){const f=Date.now(),p=o(s,u),g=i.get(p);if(typeof g=="number"&&f-g<n)return;i.set(p,f)}t.trackEvent(s.instrumentationEventName,{...u})}catch(d){b7({provider:t,component:e.component,error:d,sourceEventName:s.sourceEventName})}};e.host.addEventListener(s.sourceEventName,a),r.push(()=>{e.host?.removeEventListener(s.sourceEventName,a)})}return()=>{for(const s of r)s()}}function p1(e){return e&&typeof e=="object"?e:{}}function m1(e){const t=p1(p1(e).loaderConfig);return Object.keys(t).length>0?t:null}function g1(e){if(!e||!("instrumentationProvider"in e))return{kind:"unset"};const t=e.instrumentationProvider;return t===null?{kind:"null"}:typeof t>"u"?{kind:"unset"}:{kind:"value",value:t}}function v1(e){if(!e||!("trackPageActions"in e))return;const t=e.trackPageActions;return typeof t=="boolean"?t:void 0}function S7(e,t){return e.kind==="value"||e.kind==="null"?e:t}var eh,I7=Lu("instrumentation-provider-resolution",()=>Ou());function k7(){return eh||(eh=new Hj,eh.initialize()),eh}function T7(e){const t=m1(e.runtimePlayer),r=m1(e.player),n=v1(t),i=v1(r),o=n??i??!1,s=S7(g1(t),g1(r));if(s.kind!=="null"){if(s.kind==="unset")return o?k7():void 0;if(By(s.value))return s.value;if(e.debug){const a=e.component?`[${e.component}] `:"";I7.warn(`${a}Ignoring invalid instrumentation provider; expected InstrumentationProvider contract`)}}}var E7=[{sourceEventName:"correct-responses-populated",instrumentationEventName:"pie-item-correct-responses-populated"}],C7=class{constructor(){Te(this,"store",new Map)}load(e){return this.store.get(e)??null}save(e,t){this.store.set(e,t)}clear(e){this.store.delete(e)}},x7="",Jv=new Set(["complete","component","elementId","timestamp","sourceRuntimeId"]),R7=new Set(["id","element",...Jv]);function _7(e,t){if(!e&&!t)return!0;if(!e||!t||(e.id||"")!==(t.id||""))return!1;try{return JSON.stringify(e.data||[])===JSON.stringify(t.data||[])}catch{return!1}}function P7(e,t){return!t||e.id!==""?t:{...t,id:""}}function ka(e,t=x7){if(e&&typeof e=="object"){const r=e;return Array.isArray(r.data)?{id:typeof r.id=="string"?r.id:t,data:r.data}:Array.isArray(e)?{id:t,data:e}:{id:t,data:[e]}}return Array.isArray(e)?{id:t,data:e}:{id:t,data:[]}}function xu(e){if(e==null)return!1;if(Array.isArray(e))return e.some(t=>xu(t));if(typeof e!="object")return!1;for(const[t,r]of Object.entries(e))if(t==="value"&&r!==void 0&&r!==null&&!(typeof r=="string"&&r.trim()==="")&&!(Array.isArray(r)&&r.length===0)||xu(r))return!0;return!1}var A7=new Set(["id","element","complete","component","timestamp","sourceRuntimeId","shuffledValues"]);function Qv(e,t){return e==null?!1:typeof e=="string"?e.trim()!=="":typeof e=="number"||typeof e=="boolean"?!0:Array.isArray(e)?e.some(r=>Qv(r)):typeof e!="object"?!1:Object.entries(e).some(([r,n])=>r==="id"&&t!==void 0&&n===t?!1:Qv(n,r))}function Qb(e){return!e||typeof e!="object"?!1:Array.isArray(e)?e.some(Qb):Object.entries(e).some(([t,r])=>!A7.has(t)&&Qv(r,t))}function Rp(e){if(e==null)return!1;if(Array.isArray(e))return e.some(t=>Rp(t));if(typeof e!="object")return!1;for(const[t,r]of Object.entries(e))if(t==="value"||Rp(r))return!0;return!1}function Al(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function qa(e,t){if(typeof e.component=="string")return e.component;if(typeof t?.component=="string")return t.component}function Va(e,t){if(typeof e.complete=="boolean")return e.complete;if(typeof t?.complete=="boolean")return t.complete}function Ga(e,t){const r=typeof e.elementId=="string"&&e.elementId?e.elementId:typeof t?.id=="string"&&t.id?t.id:void 0;return r?{elementId:r}:{}}function Bx(e){const t=Object.keys(e);return("id"in e||"element"in e)&&!Rp(e)&&t.every(r=>R7.has(r))}function M7(e){return e.data.length>0&&e.data.every(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Bx(t))}function Fx(e,t){const r={...e};for(const[n,i]of Object.entries(t)){const o=r[n];r[n]=Al(o)&&Al(i)?Fx(o,i):i}return r}function Hx(e,t,r,n){const i=ka(t,e),o=[...i.data],s=o.findIndex(a=>!a||typeof a!="object"?!1:a.id===r);if(s>=0){const a=o[s];o[s]=a&&typeof a=="object"?Fx(a,n):n}else o.push(n);return{id:i.id||e,data:o}}function zx(e){const t=$7(e),r=e.sessionDetail?.sessionCommitReason;return typeof r=="string"&&r?{...t,sessionCommitReason:r}:t}function $7(e){const t=e.sessionDetail||{},r=t&&typeof t=="object"&&"session"in t?t.session:e.sessionDetail,n=typeof e.itemId=="string"&&e.itemId?e.itemId:typeof r?.id=="string"?String(r.id):"";if(!r||typeof r!="object")return{itemId:n,session:null,intent:"metadata-only",component:qa(t),...Ga(t),complete:Va(t)};const i=r;if(Array.isArray(i.data)){const l=ka(i,n),d=P7(l,e.previousItemSession!==void 0?ka(e.previousItemSession,n):null),c=Object.keys(t),u=c.length>0&&c.every(p=>p==="session"||Jv.has(p)),f=c.some(p=>p!=="session");return u&&f&&d&&_7(l,d)?{itemId:n,session:null,intent:"metadata-only",component:qa(t),...Ga(t),complete:Va(t)}:u&&M7(l)?{itemId:n,session:null,intent:"metadata-only",component:qa(t),...Ga(t),complete:Va(t)}:{itemId:n,session:l,intent:"replace-item-session",component:qa(t),...Ga(t),complete:Va(t)}}const o=Object.keys(i);if(o.length>0&&o.every(l=>Jv.has(l)))return{itemId:n,session:null,intent:"metadata-only",component:qa(t,i),...Ga(t),complete:Va(t,i)};if(Bx(i))return{itemId:n,session:null,intent:"metadata-only",component:qa(t,i),...Ga(t,i),complete:Va(t,i)};const s=qa(t,i)??"response",a=typeof i.id=="string"&&i.id?i.id:s;return{itemId:n,session:Hx(n,e.previousItemSession,a,{id:a,...i}),intent:"merge-element-session",component:s,...Ga(t,i),complete:Va(t,i)}}function Wx(e){if(!Al(e)||Object.isFrozen(e))return null;const t=e.data;if(Array.isArray(t))return Object.isFrozen(t)?null:t;if(t==null){const r=[];return e.data=r,r}return null}function ey(e){if(!Al(e))return null;const t=e.id;return typeof t=="string"&&t.length>0?t:null}function L7(e,t){const r=Wx(e);if(!r)return!1;let n=!1;for(const i of t)typeof i!="string"||i.length===0||r.some(o=>ey(o)===i)||(r.push({id:i}),n=!0);return n}function O7(e,t){const r=Wx(e);if(!r||!Al(e))return!1;const n=ka(t);let i=!1;typeof e.id!="string"&&(e.id=n.id,i=!0);for(const o of n.data){const s=ey(o);if(!s||!Al(o))continue;const a=r.find(l=>ey(l)===s);if(!Al(a)){r.push({...o}),i=!0;continue}for(const l of Object.keys(a))l in o||(delete a[l],i=!0);for(const[l,d]of Object.entries(o))a[l]!==d&&(a[l]=d,i=!0)}return i}var N7="";function D7(e){try{return structuredClone(e)}catch{return{id:e.id,data:JSON.parse(JSON.stringify(e.data??[]))}}}var j7=class{constructor(e){Te(this,"storage",void 0),Te(this,"session",void 0),Te(this,"storageKey",void 0),Te(this,"sessionId",void 0),Te(this,"itemId",void 0),this.storage=e.storage??new C7,this.itemId=e.itemId,this.storageKey=e.storageKey??`pie:item-controller:v1:${e.itemId}`,this.sessionId=e.sessionId??N7,this.session=ka(e.initialSession,this.sessionId)}async hydrate(){const e=await this.storage.load(this.storageKey);return e&&(this.session=ka(e,this.sessionId)),this.getSession()}async persist(){await this.storage.save(this.storageKey,this.session)}async clearPersisted(){await this.storage.clear?.(this.storageKey)}getSession(){return D7(this.session)}setSession(e,t={}){const r=ka(e,this.sessionId);return!(t.allowMetadataOverwrite??!1)&&xu(this.session)&&!xu(r)&&!Rp(r)?this.getSession():(this.session=r,t.persist!==!1&&this.persist(),this.getSession())}mergeElementSession(e,t,r={}){return this.session=Hx(this.session.id||this.sessionId,this.session,e,{id:e,...t}),r.persist===!0&&this.persist(),this.getSession()}updateFromEventDetail(e,t={}){const r=zx({itemId:this.session.id||this.itemId,sessionDetail:e,previousItemSession:this.session});return r.intent==="metadata-only"||!r.session?this.getSession():this.setSession(r.session,t)}},y1=ka,B7="commitPendingSession",Ux=Symbol.for("pie.sessionCommit.observedSignature");function qx(e){return!!e&&typeof e=="object"}function Vx(e){return e.tagName.includes("-")?"session"in e&&"model"in e:!1}function F7(e){return e?.shadowRoot??null}function H7(e){const t=e;if(typeof t.assignedElements!="function")return[];try{return t.assignedElements({flatten:!0})}catch{return[]}}function ty(e,t,r){const n=F7(e);n&&ty(n,t,r);const i=s=>{t.has(s)||(t.add(s),Vx(s)&&r.push(s),ty(s,t,r))};for(const s of H7(e))i(s);const o=e.children;if(o)for(const s of Array.from(o))i(s)}function z7(e){return!!e&&typeof e=="object"&&typeof e.tagName=="string"}function W7(e){const t=[],r=new Set;return z7(e)&&Vx(e)&&(r.add(e),t.push(e)),ty(e,r,t),t}function U7(e){try{return e.session}catch{return}}function q7(e){try{const t=JSON.stringify(e);return typeof t=="string"?t:null}catch{return null}}function V7(e){const t=e[Ux];return typeof t=="string"?t:void 0}function b1(e,t){try{Object.defineProperty(e,Ux,{value:t,configurable:!0,enumerable:!1,writable:!0})}catch{}}function G7(e,t,r){const n=e;if(typeof n.addEventListener!="function")return r();const i=o=>{const s=o.detail;if(!(!qx(s)||"sessionCommitReason"in s))try{s.sessionCommitReason=t}catch{}};n.addEventListener("session-changed",i,!0);try{return r()}finally{n.removeEventListener("session-changed",i,!0)}}function Eh(e,t={}){const r={committed:0,synthesized:0,skipped:0};if(!e)return r;const n=t.reason??"teardown";return G7(e,n,()=>Gx(e,n,t.logger,r))}function Gx(e,t,r,n){const i=t?"commitPendingSessions":"flushPendingSessionNotifications";for(const o of W7(e)){const s=U7(o);if(!qx(s)){n.skipped+=1;continue}const a=q7(s);if(a===null){n.skipped+=1;continue}const l=V7(o);if(l===a){n.skipped+=1;continue}if(l===void 0&&!Qb(s)){n.skipped+=1;continue}const d=o[B7];if(typeof d=="function"){let c=!1;const u=()=>{c=!0};o.addEventListener("session-changed",u,!0);let f=!1;try{d.call(o)}catch(p){f=!0,r?.warn(`[${i}] ${o.tagName.toLowerCase()} failed to commit its pending session`,p)}finally{o.removeEventListener("session-changed",u,!0)}if(f){n.skipped+=1;continue}if(c){b1(o,a),n.committed+=1;continue}}try{o.dispatchEvent(new CustomEvent("session-changed",{bubbles:!0,composed:!0,detail:{component:o.tagName.toLowerCase(),session:JSON.parse(a),...t?{sessionCommitReason:t}:{}}})),b1(o,a),n.synthesized+=1}catch(c){r?.warn(`[${i}] ${o.tagName.toLowerCase()} session commit dispatch failed`,c),n.skipped+=1}}return n}function K7(e,t={}){const r={committed:0,synthesized:0,skipped:0};return e?Gx(e,null,t.logger,r):r}function X7(e){if(typeof document>"u"||typeof window>"u")return()=>{};const t=i=>{Eh(e.root(),{reason:i,logger:e.logger});try{e.onHidden?.(i)}catch(o){e.logger?.warn("[bindPageLifecycleCommit] onHidden failed",o)}},r=()=>{document.visibilityState==="hidden"&&t("page-hidden")},n=()=>{t("page-hidden")};return document.addEventListener("visibilitychange",r),window.addEventListener("pagehide",n),()=>{document.removeEventListener("visibilitychange",r),window.removeEventListener("pagehide",n)}}var Z7="pie-session-snapshot";function Y7(e){return!!e.sessionId}function J7(e){return`${Z7}:${[e.assignmentId||"",e.sessionId||"",e.itemId||""].join("|")}`}function Q7(){return{read(e){try{return typeof sessionStorage>"u"?null:sessionStorage.getItem(e)}catch{return null}},write(e,t){try{if(typeof sessionStorage>"u")return;sessionStorage.setItem(e,t)}catch{}},clear(e){try{if(typeof sessionStorage>"u")return;sessionStorage.removeItem(e)}catch{}}}}function e3(e){return typeof e=="boolean"?e:e?e.enabled!==!1:!1}function t3(e){if(!e3(e.config))return null;const t=typeof e.config=="object"&&e.config?e.config:{};if(!t.key&&!Y7(e.identity))return null;const r=t.key||J7(e.identity),n=t.store||Q7(),i=()=>{try{return n.read(r)}catch{return null}},o=a=>{try{n.write(r,a)}catch{}},s=()=>{try{n.clear(r)}catch{}};return{key:r,write(a){let l;try{l=JSON.stringify({session:a,timestamp:Date.now()})}catch{return}o(l)},read(){const a=i();if(!a)return null;try{const l=JSON.parse(a);return!l||typeof l!="object"||!("session"in l)?null:{key:r,session:l.session,timestamp:typeof l.timestamp=="number"?l.timestamp:0}}catch{return null}},clear(){s()}}}var r3=new Set(["media","supports","container","layer","scope"]),n3=/^(?::root|html|body)(?![\w-])/,i3=/^@(?:-[a-z]+-)?([\w-]+)/i;function o3(e,t){if(typeof e!="string"||e.length===0)return"";const r=t?.trim();return r?Kx(u3(e),r):e}function s3(e,t){const r=e.trim(),n=t.trim();if(!r||!n)return"";if(r===n||r.startsWith(`${n} `))return r;const i=n3.exec(r);return i?`${n}${r.slice(i[0].length)}`:`${n} ${r}`}function Kx(e,t){let r="",n=0;for(;n<e.length;){const i=l3(e,n);if(i.end<=n)break;r+=a3(i,t),n=i.end}return r}function a3(e,t){if(e.kind==="statement"){const i=e.text.trim();return i===";"?"":`${i}
978
+ `}if(e.kind==="trailing")return e.text.trim()?`${e.text.trim()}
979
+ `:"";const r=e.prelude.trim();if(!r)return"";if(r.startsWith("@")){const i=i3.exec(r)?.[1]?.toLowerCase();if(i&&r3.has(i)){const o=Kx(e.block,t);return o.trim()?`${r} {
980
+ ${o}}
981
+ `:""}return`${r} {${e.block}}
982
+ `}const n=d3(r,",").map(i=>s3(i,t)).filter(Boolean);return n.length===0?"":`${n.join(", ")} {${e.block}}
983
+ `}function l3(e,t){let r=t,n=null,i=0;for(;r<e.length;){const o=e[r];if(n)o==="\\"?r+=1:o===n&&(n=null);else if(o==='"'||o==="'")n=o;else if(o==="(")i+=1;else if(o===")")i>0&&(i-=1);else{if(i===0&&o===";")return{kind:"statement",text:e.slice(t,r+1),end:r+1};if(i===0&&o==="{"){const s=c3(e,r);return{kind:"rule",prelude:e.slice(t,r),block:e.slice(r+1,s.contentEnd),end:s.end}}}r+=1}return{kind:"trailing",text:e.slice(t),end:e.length}}function c3(e,t){let r=0,n=null;for(let i=t;i<e.length;i+=1){const o=e[i];if(n){o==="\\"?i+=1:o===n&&(n=null);continue}if(o==='"'||o==="'"){n=o;continue}if(o==="{")r+=1;else if(o==="}"&&(r-=1,r===0))return{contentEnd:i,end:i+1}}return{contentEnd:e.length,end:e.length}}function d3(e,t){const r=[];let n="",i=null,o=0;for(let s=0;s<e.length;s+=1){const a=e[s];if(i){n+=a,a==="\\"&&s+1<e.length?(n+=e[s+1],s+=1):a===i&&(i=null);continue}if(a==='"'||a==="'"){i=a,n+=a;continue}if(a==="("?o+=1:a===")"&&o>0&&(o-=1),a===t&&o===0){r.push(n),n="";continue}n+=a}return r.push(n),r}function u3(e){let t="",r=null,n=0;for(;n<e.length;){const i=e[n];if(r){if(t+=i,i==="\\"&&n+1<e.length){t+=e[n+1],n+=2;continue}i===r&&(r=null),n+=1;continue}if(i==='"'||i==="'"){r=i,t+=i,n+=1;continue}if(i==="/"&&e[n+1]==="*"){const o=e.indexOf("*/",n+2);n=o===-1?e.length:o+2,t+=" ";continue}t+=i,n+=1}return t}function f3(e,t){return e==="esm"&&t==="on"}var w1=new Set;function h3(e){const t=typeof window>"u"?void 0:window.PIE_REGISTRY,r=e.filter(n=>!t?.[n]?.controller&&!w1.has(n));for(const n of r)w1.add(n);return r}function p3(e){return`${e} is registered without a controller, so this player, which is not hosted, renders its authored model without running model(). Pass the package's ./browser/controller module as controller to registerPreloadedElements, or set hosted when a server processes models.`}function m3(e,t){return t===void 0||!Array.isArray(e?.models)?e:{...e,models:e.models.map(r=>({...r,autoplayAudioEnabled:t}))}}var Cg=new WeakMap,S1=new WeakMap,g3=Math.random().toString(36).slice(2,10),I1=0;function v3(){return I1+=1,`pie-item-player-style-scope-${g3}-${I1.toString(36)}`}function y3(e){let t=S1.get(e);return t||(t=new Map,S1.set(e,t)),t}function b3(e,t){let r=Cg.get(e);r||(r=new Map,Cg.set(e,r));const n=r.get(t);if(n)return n;const i=fetch(t).then(s=>s.text());r.set(t,i);const o=()=>{r.get(t)===i&&(r.delete(t),r.size===0&&Cg.delete(e))};return i.then(o,o),i}async function w3({document:e,resolvedUrl:t,scopeClass:r,signal:n,sourceUrl:i}){if(n.aborted)return null;const o=y3(e),s=JSON.stringify([t,r]),a=o.get(s);if(a)return a.refCount+=1,xg(o,s,a);const l=await b3(e,t);if(n.aborted)return null;const d=o.get(s);if(d)return d.refCount+=1,xg(o,s,d);const c=e.createElement("style");c.setAttribute("data-pie-style",i),c.textContent=o3(l,`.pie-item-player.${r}`);const u={element:c,refCount:1};return o.set(s,u),e.head.appendChild(c),xg(o,s,u)}function xg(e,t,r){let n=!1;return()=>{n||(n=!0,r.refCount-=1,!(r.refCount>0||e.get(t)!==r)&&(e.delete(t),r.element.remove()))}}var S3=(e,t)=>{const r=e.defaultView?.CSS;return typeof r?.escape=="function"?r.escape(t):t.replace(/[^a-zA-Z0-9_-]/g,n=>`\\${n}`)};function I3(e,t,r){const n=S3(e,t);if(e.querySelector(`link[data-pie-style-link="${n}"]`))return;const i=e.createElement("link");i.setAttribute("rel","stylesheet"),i.setAttribute("href",r),i.setAttribute("data-pie-style-link",t),e.head.appendChild(i)}function _p(e){try{const t=new WeakSet;return JSON.stringify(e,(r,n)=>!n||typeof n!="object"||Array.isArray(n)?n:t.has(n)?"[Circular]":(t.add(n),Object.keys(n).sort().reduce((i,o)=>(i[o]=n[o],i),{})))}catch{return String(e)}}function nd(e){const t=e?.authoring;return!t||t.enabled===!1?null:t}function ns(e){const t=nd(e);return t?JSON.stringify({provider:t.provider??(t.client?"custom":"pie-api"),baseUrl:t.baseUrl??"",contentId:t.contentId??"",collectionId:t.collectionId??"",hasClientLoad:typeof t.client?.load=="function",endpoint:t.endpoints?.load??null}):""}function Pp(e,t){return{contentId:t?.contentId??e.contentId,collectionId:t?.collectionId??e.collectionId}}function ew(e){return e.provider==="custom"||!!e.client&&e.provider!=="pie-api"}async function k3(e,t){const r=nd(e);if(!r)throw new Error("Authoring backend is not configured.");if(typeof r.client?.load=="function")return r.client.load({...Pp(r),env:t});if(ew(r))throw new Error("backend.authoring.client.load is not configured.");const{callPieApiAuthoringLoad:n}=await br(async()=>{const{callPieApiAuthoringLoad:i}=await import("./chunks/pie-api-client-687c319a.js");return{callPieApiAuthoringLoad:i}},[],import.meta.url);return n(r,e.auth,{...Pp(r),env:t})}async function T3(e,t){const r=nd(e);if(!r)throw new Error("Authoring backend is not configured.");const n={...Pp(r,t),config:t.config,env:t.env,options:t.options};if(typeof r.client?.saveContent=="function")return r.client.saveContent(n);if(ew(r))throw new Error("backend.authoring.client.saveContent is not configured.");const{callPieApiAuthoringSaveContent:i}=await br(async()=>{const{callPieApiAuthoringSaveContent:o}=await import("./chunks/pie-api-client-687c319a.js");return{callPieApiAuthoringSaveContent:o}},[],import.meta.url);return i(r,e.auth,n)}async function E3(e,t){const r=nd(e);if(!r)throw new Error("Authoring backend is not configured.");const n={...Pp(r,t),env:t.env,options:t.options};if(typeof r.client?.releaseContent=="function")return r.client.releaseContent(n);if(ew(r))throw new Error("backend.authoring.client.releaseContent is not configured.");const{callPieApiAuthoringReleaseContent:i}=await br(async()=>{const{callPieApiAuthoringReleaseContent:o}=await import("./chunks/pie-api-client-687c319a.js");return{callPieApiAuthoringReleaseContent:o}},[],import.meta.url);return i(r,e.auth,n)}var Rg=100;function Ap(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Pd(e){return Ap(e)&&typeof e.markup=="string"&&Ap(e.elements)&&Array.isArray(e.models)}function C3(e){if(Pd(e.config))return e.config;if(Pd(e.item))return e.item;if(Ap(e.item)&&Pd(e.item.config))return e.item.config;if(Ap(e.item)&&Pd(e.item.pie))return{pie:e.item.pie,passage:Pd(e.item.passage)?e.item.passage:void 0};throw new Error("Backend delivery load did not return an item config.")}function x3(e){return e.session?e.session:{id:"",data:[]}}function wi(e){const t=e?.delivery;return!t||t.enabled===!1?null:t}function Xx(e){return!!wi(e)}function R3(e){return e===!0?{enabled:!0,debounceMs:Rg}:e?{enabled:e.enabled!==!1,debounceMs:typeof e.debounceMs=="number"&&e.debounceMs>=0?e.debounceMs:Rg}:{enabled:!1,debounceMs:Rg}}function Ad(e){const t=wi(e);return t?JSON.stringify({provider:t.provider??(t.client?"custom":"pie-api"),baseUrl:t.baseUrl??"",itemId:t.itemId??"",sessionId:t.sessionId??"",assignmentId:t.assignmentId??"",hasClientLoad:typeof t.client?.load=="function",endpoint:t.endpoints?.load??null}):""}function _g(e,t){const r=wi(e);if(!r)return"";const n=typeof r.client?.model=="function",i=!r.client||r.provider==="pie-api"||!!r.baseUrl||!!r.endpoints?.model;return!n&&!i?"":JSON.stringify({provider:r.provider??(r.client?"custom":"pie-api"),baseUrl:r.baseUrl??"",itemId:r.itemId??"",sessionId:r.sessionId??"",assignmentId:r.assignmentId??"",hasClientModel:typeof r.client?.model=="function",endpoint:r.endpoints?.model??null,options:r.options??null,env:t??null})}async function _3(e,t){const r=wi(e);if(!r)throw new Error("Delivery backend is not configured.");if(!r.itemId)throw new Error("backend.delivery.itemId is required to load from backend.");const n={itemId:r.itemId,sessionId:r.sessionId,assignmentId:r.assignmentId,env:t,requestOptions:r.options};let i;if(typeof r.client?.load=="function")i=await r.client.load(n);else{const{callPieApiDeliveryLoad:o}=await br(async()=>{const{callPieApiDeliveryLoad:s}=await import("./chunks/pie-api-client-687c319a.js");return{callPieApiDeliveryLoad:s}},[],import.meta.url);i=await o(r,e.auth,n)}return{config:C3(i),session:x3(i),metadata:i.metadata}}async function P3(e,t){const r=wi(e);if(!r)throw new Error("Delivery backend is not configured.");if(typeof r.client?.model=="function")return r.client.model({...t,requestOptions:r.options});const{callPieApiDeliveryModel:n}=await br(async()=>{const{callPieApiDeliveryModel:i}=await import("./chunks/pie-api-client-687c319a.js");return{callPieApiDeliveryModel:i}},[],import.meta.url);return n(r,e.auth,{...t,requestOptions:r.options})}async function A3(e,t,r){const n=wi(e);if(!n)throw new Error("Delivery backend is not configured.");const i=r?.keepalive===!0,o=i?{...n.options??{},keepalive:!0}:n.options;if(typeof n.client?.saveSession=="function")return n.client.saveSession({...t,requestOptions:o});const{callPieApiDeliverySave:s}=await br(async()=>{const{callPieApiDeliverySave:a}=await import("./chunks/pie-api-client-687c319a.js");return{callPieApiDeliverySave:a}},[],import.meta.url);return s(n,e.auth,{...t,requestOptions:o},{keepalive:i})}async function M3(e,t,r){const n=wi(e);if(!n)throw new Error("Delivery backend is not configured.");const i={...t,requestOptions:n.options,options:r};if(typeof n.client?.score=="function")return n.client.score(i);const{callPieApiDeliveryScore:o}=await br(async()=>{const{callPieApiDeliveryScore:s}=await import("./chunks/pie-api-client-687c319a.js");return{callPieApiDeliveryScore:s}},[],import.meta.url);return o(n,e.auth,i)}function Zx(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function $3(e){return Zx(e)&&typeof e.id=="string"&&typeof e.element=="string"}function L3(e,t){return e.id===t.id&&e.element===t.element}function k1(e,t){if(!e||!t?.length)return{config:e,changed:!1};let r=!1;const n=e.models.map(i=>{const o=t.find(a=>$3(a)&&L3(i,a));if(!o)return i;const s={...o,id:i.id,element:i.element};return JSON.stringify(s)!==JSON.stringify(i)&&(r=!0),s});return{config:r?{...e,models:n}:e,changed:r}}function O3(e){return Array.isArray(e)?{models:e,passageModels:void 0,metadata:void 0}:{models:Array.isArray(e.models)?e.models:void 0,passageModels:Array.isArray(e.passageModels)?e.passageModels:void 0,metadata:Zx(e.metadata)?e.metadata:void 0}}function N3(e){const t=O3(e.result),r=k1(e.itemConfig,t.models),n=k1(e.passageConfig,t.passageModels);return{itemConfig:r.config,passageConfig:n.config,metadata:t.metadata,itemChanged:r.changed,passageChanged:n.changed,changed:r.changed||n.changed}}function D3(e){if(typeof structuredClone=="function")try{return structuredClone(e)}catch{}return JSON.parse(JSON.stringify(e))}var T1=new WeakMap,j3=0;function th(e){if(typeof e!="function")return"none";let t=T1.get(e);return t||(t=j3+=1,T1.set(e,t)),`fn:${t}`}function B3(e){let t=er(null),r=er(null),n=er(0),i=0,o="",s=null,a=Promise.resolve(),l=null,d=0,c="",u=null,f="",p=null,g=0,v=0,b=0;function w(){return g+=1,g}function I(W){return W===g}function x(){return v+=1,v}function C(W){return W===v}function L(){return b+=1,b}function E(W){return W===b}function M(W){const O=e.getSessionContainer();return O.id||!W?O:{...O,id:W}}function U(W){const O=W?.models?.filter($=>typeof $.id=="string"&&typeof $.element=="string").map($=>({id:$.id,element:$.element}));return O&&O.length>0?O:void 0}function te(W,O){e.dispatchPlayerEvent(new CustomEvent(W,{detail:O}))}function re(W,O){te("backend-error",{scope:"delivery",operation:W,message:O instanceof Error?O.message:String(O),error:O})}function Pe(){return nd(e.getBackend())?.media??null}function z(W=ns(e.getBackend())){return p&&f===W?{contentId:p}:{}}async function K(W,O){if(W==="authoring"){const ge=e.getBackend();if(!ge||!nd(ge))throw new Error("backend.authoring is not configured.");const Oe=x(),We=await k3(ge,e.getEnv());if(!C(Oe)||O&&ns(e.getBackend())!==O)return;const Ne=ns(e.getBackend());Fe(t,We.config,!0),u="authoring",Fe(r,{id:"",data:[]},!0),Fe(n,A(n)+1);const xe=await e.loadPlayerConfig(We.config);if(await ou(),!C(Oe)||O&&ns(e.getBackend())!==O)return;if(!xe)throw new Error("Authoring backend config failed to load.");f=Ne,p=typeof We.contentId=="string"?We.contentId:null,te("backend-load-complete",{scope:"authoring",operation:"load",contentId:We.contentId,metadata:We.metadata??{},config:We.config});return}const $=e.getBackend();if(!$||!Xx($))throw new Error("backend.delivery is not configured.");const ie=e.getEnv(),N=_g($,ie),ne=await _3($,ie);O&&Ad(e.getBackend())!==O||u!=="authoring"&&(Fe(t,ne.config,!0),u="delivery",Fe(r,ne.session,!0),Fe(n,A(n)+1),c=N,te("backend-load-complete",{scope:"delivery",operation:"load",metadata:ne.metadata??{},session:ne.session}))}async function oe(W,O,$){const ie=e.getBackend();if(!ie||!wi(ie)||!e.getItemConfig()||u==="authoring")return;const N=wi(ie),ne=e.getEnv(),ge=M(N.sessionId),Oe=_p(ge);let We;try{We=await P3(ie,{itemId:N.itemId,sessionId:N.sessionId,assignmentId:N.assignmentId,session:ge,env:ne,models:U(e.getItemConfig()),passageModels:U(e.getPassageConfig())})}catch(xe){if(!I($))return;throw xe}if(!I($)||W&&_g(e.getBackend(),e.getEnv())!==W||O!==d||_p(M(N.sessionId))!==Oe)return;const Ne=N3({itemConfig:e.getItemConfig(),passageConfig:e.getPassageConfig(),result:We});c=W,Ne.changed&&(d+=1,await e.applyRefreshedConfigs(Ne)),te("backend-model-complete",{scope:"delivery",operation:"model",metadata:Ne.metadata??{}})}async function ue(W,O){const $=e.getBackend();if(!$||!wi($))throw new Error("backend.delivery is not configured.");const ie=wi($),N=O??{itemId:ie.itemId,sessionId:ie.sessionId,assignmentId:ie.assignmentId},ne=N.session??M(N.sessionId);await A3($,{itemId:N.itemId,sessionId:N.sessionId,assignmentId:N.assignmentId,session:ne,env:e.getEnv()},W),te("backend-session-saved",{scope:"delivery",operation:"saveSession",sessionId:ne.id,session:ne})}async function ae(W,O){const $=a.catch(()=>{}).then(()=>ue(W,O));return a=$,$}function X(W){if(!s)return;clearTimeout(s),s=null;const O=l;l=null,ae(W,O?{...O,session:M(O.sessionId)}:null).catch($=>{re("saveSession",$)})}async function j(W){const O=e.getBackend();if(!O||!wi(O))throw new Error("backend.delivery is not configured.");const $=wi(O),ie=M($.sessionId),N=await M3(O,{itemId:$.itemId,sessionId:$.sessionId,assignmentId:$.assignmentId,session:ie,env:e.getEnv()},W);return te("backend-score-complete",{scope:"delivery",operation:"score",sessionId:ie.id,score:N}),N}async function D(W){const O=e.getItemConfig();if(!O)throw new Error("Cannot save content before the item config has loaded.");const $=e.getBackend()??{},ie=ns($),N=L(),ne=await T3($,{...z(ie),config:D3(O),env:e.getEnv(),options:W});return typeof ne.contentId=="string"&&E(N)&&ie===ns(e.getBackend())&&(p=ne.contentId,f=ie),te("backend-content-saved",{scope:"authoring",operation:"saveContent",contentId:ne.contentId}),ne.contentId}async function Z(W){const O=e.getBackend()??{},$=ns(O),ie=L(),N=await E3(O,{...z($),env:e.getEnv(),options:W});return typeof N.contentId=="string"&&E(ie)&&$===ns(e.getBackend())&&(p=N.contentId,f=$),te("backend-content-released",{scope:"authoring",operation:"releaseContent",contentId:N.contentId}),N.contentId}function F(){const W=e.getBackend();if(!W)return;const O=wi(W);if(!O)return;const $=R3(O.autosave);if(!$.enabled)return;s&&clearTimeout(s);const ie=Ad(W),N={itemId:O.itemId,sessionId:O.sessionId,assignmentId:O.assignmentId};l=N,s=setTimeout(()=>{s=null,l=null,ie===Ad(e.getBackend())&&ae(void 0,N).catch(ne=>{re("saveSession",ne)})},$.debounceMs)}return zr(()=>{const W=Ad(e.getBackend());if(!W){queueMicrotask(()=>{Bn(()=>{s&&(clearTimeout(s),s=null),o="",u!=="authoring"&&(Fe(t,null),u=null,Fe(r,null))})});return}W!==o&&(X(),o=W,queueMicrotask(()=>{Bn(()=>{K("delivery",W).catch(O=>{re("load",O)})})}))}),zr(()=>{const W=ns(e.getBackend());(!W||f&&f!==W)&&queueMicrotask(()=>{Bn(()=>{f="",p=null,u==="authoring"&&!W&&(Fe(t,null),u=null,Fe(r,null))})})}),zr(()=>{const W=e.getBackend(),O=e.getEnv(),$=e.getItemConfig(),ie=_g(W,O);if(!ie||!$){c="",w();return}if(ie===c){w();return}const N=d,ne=w();queueMicrotask(()=>{Bn(()=>{oe(ie,N,ne).catch(ge=>{re("model",ge)})})})}),zr(()=>()=>{X()}),{get configOverride(){return A(t)},get sessionOverride(){return A(r)},get authoringMedia(){return Pe()},hasPendingSessionReplacement(){return A(n)!==i},markSessionReplacementApplied(){i=A(n)},noteConfigChanged(){d+=1},load(W="delivery"){return K(W,W==="authoring"?ns(e.getBackend()):Ad(e.getBackend()))},saveSession:ae,flushPendingSave:X,score:j,saveContent:D,releaseContent:Z,scheduleAutosave:F}}var E1={error:"player-error"};function tw(e){if(!e||typeof e!="object")return!1;const t=e;return typeof t.providerId=="string"&&typeof t.providerName=="string"&&typeof t.initialize=="function"&&typeof t.trackError=="function"&&typeof t.trackEvent=="function"&&typeof t.destroy=="function"&&typeof t.isReady=="function"}var Yx={retryDelayMs:3e3,timeoutMs:12e4},Mp={trackPageActions:!1,instrumentationProvider:void 0,maxResourceRetries:3,resourceRetryDelay:500,iifeBundleRetry:Yx},F3=["script","iframe","object","embed","base","form","meta","link","style","foreignobject"],H3=["onerror","onload","onclick","onmouseover","onmouseout","onmouseenter","onmouseleave","onfocus","onblur","onkeydown","onkeyup","onkeypress","onsubmit","onchange","onbeforeunload","formaction","xlink:href"],Jx=/(?:^|[^\w-])(?:url|image-set|-webkit-image-set|src)\s*\(/i,z3=/url\s*\(|image-set\s*\(|src\s*\(|position|\\/i;function Qx(e,t){return Jx.test(t)?!0:e.toLowerCase()==="position"&&/\bfixed\b/i.test(t)}function W3(e,t){const r=t.createElement("span");r.setAttribute("style",e);const n=r.style,i=[];for(let o=0;o<n.length;o+=1){const s=n.item(o);if(!s)continue;const a=n.getPropertyValue(s);if(Qx(s,a))continue;const l=n.getPropertyPriority(s);i.push(`${s}: ${a}${l?` !${l}`:""}`)}return i.join("; ")}function U3(e,t){if(typeof e!="string"||e.length===0)return"";if(!t||!z3.test(e))return e;const r=t.createElement("span");r.setAttribute("style",e);const n=r.style;let i=!1;for(let o=0;o<n.length;o+=1){const s=n.item(o);if(s&&Qx(s,n.getPropertyValue(s))){i=!0;break}}return!i&&!Jx.test(e)?e:W3(e,t)}function q3(e){typeof e.addHook=="function"&&e.addHook("afterSanitizeAttributes",t=>{const r=t;if(!r||typeof r.getAttribute!="function")return;const n=r.getAttribute("style");if(!n)return;const i=U3(n,r.ownerDocument);i!==n&&(i?r.setAttribute("style",i):r.removeAttribute("style"))})}var V3=/^pie-/i,G3='[contenteditable]:not([contenteditable="false" i])';function K3(e,t){let r=e.parentElement;for(;r&&r!==t;){if(V3.test(r.tagName))return!0;r=r.parentElement}return!1}function rw(e,t,r={}){const{skipPieDescendants:n=!1}=r,i=Array.from(e.querySelectorAll(t.selector));if(i.length===0)return 0;const o=e.ownerDocument;if(!o)return 0;let s=0;for(const a of i){const l=a.parentElement;if(!l||l.classList?.contains(t.wrapperClass)||n&&K3(a,e)||a.closest(G3))continue;const d=o.createElement(t.wrapperTag);d.className=t.wrapperClass,d.setAttribute("tabindex","0"),d.setAttribute("role","region"),d.setAttribute("aria-label",t.buildAriaLabel(a)),l.insertBefore(d,a),d.appendChild(a),s+=1}return s}function eR(e,t){if(!e)return"";if(!t.markupProbe.test(e)||typeof window>"u"||!window.document)return e;const r=typeof DOMParser<"u"?DOMParser:window.DOMParser;if(!r)return e;const n=new r().parseFromString(`<!DOCTYPE html><html><body>${e}</body></html>`,"text/html").body;return n&&rw(n,t,{skipPieDescendants:!0})>0?n.innerHTML:e}function tR(e){return e.nodeType===1}function X3(e,t){if(!tR(e)||!e.classList?.contains(t.wrapperClass))return!1;for(const r of Array.from(e.children))if(!r.matches(t.selector))return!1;return!0}function Z3(e,t){return!tR(e)||!e.parentElement?.classList?.contains(t.wrapperClass)?!1:e.matches(t.selector)}function C1(e,t){for(const r of Array.from(e))if(!X3(r,t)&&!Z3(r,t))return!1;return!0}function rR(e,t){return e.type!=="childList"?!1:C1(e.addedNodes,t)&&C1(e.removedNodes,t)}function Y3(e){const t=e.getAttribute("alt"),r=t?t.trim():"";return r?`Scrollable image: ${r}`:"Scrollable image"}var nw={selector:"img",wrapperTag:"span",wrapperClass:"pie-image-scroll",markupProbe:/<img\b/i,buildAriaLabel:Y3};function J3(e,t={}){return rw(e,nw,t)}function Q3(e){return eR(e,nw)}function eF(e){return rR(e,nw)}function tF(e){const t=e.getAttribute("aria-label");if(t?.trim())return`Scrollable table: ${t.trim()}`;const r=e.getAttribute("aria-labelledby");if(r?.trim()){const i=e.ownerDocument,o=r.trim().split(/\s+/),s=[];for(const a of o){const l=i?.getElementById(a)?.textContent?.trim();l&&s.push(l)}if(s.length>0)return`Scrollable table: ${s.join(" ")}`}const n=e.querySelector("caption")?.textContent?.trim();return n?`Scrollable table: ${n}`:"Scrollable table"}var iw={selector:"table",wrapperTag:"div",wrapperClass:"pie-table-scroll",markupProbe:/<table\b/i,buildAriaLabel:tF};function rF(e,t={}){return rw(e,iw,t)}function nF(e){return eR(e,iw)}function iF(e){return rR(e,iw)}var oF=["slot","role","tabindex","id","class","style","href","src","alt","title","hidden","disabled","lang","dir"],sF=["pie-id"],aF=F3,lF=H3,cF=/^pie-[a-z0-9-]+$/i,dF=/^(id|class|style|slot|role|tabindex|hidden|disabled|lang|dir|data-[\w-]+|aria-[\w-]+|pie-[\w-]+|model-[\w-]+|session-[\w-]+|config-[\w-]+|context-[\w-]+)$/i,Md=null;function uF(){if(Md)return Md;if(typeof window>"u"||!window.document)return null;const e=o1;return Md=typeof e=="function"?e(window):o1,q3(Md),Md}function fF(e,t={}){if(!e)return"";const r=uF();if(!r)return"";const n=(t.allowedCustomElements??[]).map(a=>a.toLowerCase()),i=new Set(n),o=r.sanitize(e,{ADD_TAGS:n,ADD_ATTR:oF,ADD_URI_SAFE_ATTR:sF,FORBID_TAGS:aF,FORBID_ATTR:lF,ALLOW_UNKNOWN_PROTOCOLS:!1,SANITIZE_DOM:!0,SANITIZE_NAMED_PROPS:!1,WHOLE_DOCUMENT:!1,ALLOW_DATA_ATTR:!0,ALLOW_ARIA_ATTR:!0,CUSTOM_ELEMENT_HANDLING:{tagNameCheck:a=>{const l=a.toLowerCase();return cF.test(l)||i.has(l)},attributeNameCheck:a=>dF.test(a),allowCustomizedBuiltInElements:!1},RETURN_TRUSTED_TYPE:!1}),s=typeof o=="string"?o:String(o??"");return t.wrapOverwideContent===!1?s:nF(Q3(s))}function hF(e={}){const{allowedCustomElements:t,wrapOverwideContent:r}=e;return n=>fF(n,{allowedCustomElements:t,wrapOverwideContent:r})}function x1(e){const t=new Set;for(const r of e){if(!r)continue;const n=r.toLowerCase();t.add(n),t.add(`${n}-config`)}return[...t]}var pF="-pie-editor--";Te(class nR extends CustomEvent{constructor(t,r=!1){super(nR.TYPE,{bubbles:!0,detail:{update:t,reset:r}}),Te(this,"update",void 0),Te(this,"reset",void 0),this.update=t,this.reset=r}},"TYPE","model.updated");var ry=class iR extends CustomEvent{constructor(t,r){super(iR.TYPE,{bubbles:!0,detail:{src:t,done:r}}),Te(this,"src",void 0),Te(this,"done",void 0),this.src=t,this.done=r}};Te(ry,"TYPE","delete.image");var ny=class oR extends CustomEvent{constructor(t){super(oR.TYPE,{bubbles:!0,detail:t}),Te(this,"handler",void 0),this.handler=t}};Te(ny,"TYPE","insert.image");var iy=class sR extends CustomEvent{constructor(t,r){super(sR.TYPE,{bubbles:!0,detail:{src:t,done:r}}),Te(this,"src",void 0),Te(this,"done",void 0),this.src=t,this.done=r}};Te(iy,"TYPE","delete.sound");var oy=class aR extends CustomEvent{constructor(t){super(aR.TYPE,{bubbles:!0,detail:t}),Te(this,"handler",void 0),this.handler=t}};Te(oy,"TYPE","insert.sound");function Yi(e,t){const r=`[${e}]`;return{debug:(n,...i)=>{t()&&console.debug(r,n,...i)},info:(n,...i)=>console.info(r,n,...i),warn:(n,...i)=>console.warn(r,n,...i),error:(n,...i)=>console.error(r,n,...i)}}function Ci(){return typeof window<"u"&&window.PIE_DEBUG===!0}var Wr=Yi("asset-handler",()=>Ci()),lR=class{constructor(e){Te(this,"onComplete",void 0),Te(this,"cancelled",!1),Te(this,"fileReader",null),this.onComplete=e}cancel(){this.cancelled=!0,this.fileReader&&this.fileReader.abort(),Wr.debug("[DataURLAssetHandler] Upload cancelled")}done(e,t){if(!this.cancelled){if(e){Wr.error("[DataURLAssetHandler] Error during upload:",e);return}t&&(Wr.debug("[DataURLAssetHandler] Upload complete, src:",t.substring(0,50)+"..."),this.onComplete(t))}}fileChosen(e){this.cancelled||(Wr.debug("[DataURLAssetHandler] File chosen:",e.name,e.type,e.size),this.fileReader=new FileReader,this.fileReader.onload=t=>{const r=t.target?.result;Wr.debug("[DataURLAssetHandler] File converted to data URL"),this.done(void 0,r)},this.fileReader.onerror=()=>{Wr.error("[DataURLAssetHandler] FileReader error"),this.done(new Error("Failed to read file"))},this.fileReader.onprogress=t=>{if(t.lengthComputable){const r=t.loaded/t.total*100;this.progress(r,t.loaded,t.total)}},this.fileReader.readAsDataURL(e))}progress(e,t,r){Wr.debug(`[DataURLAssetHandler] Progress: ${e.toFixed(1)}% (${t}/${r} bytes)`)}};function Hc(e,t){return e instanceof Error?e:new Error(String(e??t))}function cR(e,t){let r=!1;const n=e.done,i=e.cancel,o=(a,l)=>{if(!r){if(r=!0,a){try{i?.()}catch(d){Wr.error("[asset-handler] cancel callback failed:",d)}t.cancel()}try{n?.(a,l)}catch(d){Wr.error("[asset-handler] done callback failed:",d)}}},s=()=>{if(!r){r=!0;try{i?.()}catch(a){Wr.error("[asset-handler] cancel callback failed:",a)}t.cancel()}};return e.done=o,e.cancel=s,{done:o,cancel:s,isSettled:()=>r}}function dR(e,t){return new Promise(r=>{const n=document.createElement("input");n.type="file",n.accept=e;let i=!1,o=!1,s=!1;const a=()=>{n.onchange=null,window.removeEventListener("focus",d),n.removeEventListener("cancel",c)},l=u=>{i||(i=!0,a(),r(u))},d=()=>{!s||o||(s=!1,window.setTimeout(()=>{if(o||i)return;const u=n.files?.[0]??null;u||t(),l(u)},300))},c=()=>{t(),l(null)};n.onchange=()=>{o=!0,s=!1,l(n.files?.[0]??null)},n.addEventListener("cancel",c),window.addEventListener("focus",d),s=!0,n.click()})}function uR(e){if(!e.isPasted||typeof e.getChosenFile!="function")return null;try{return e.getChosenFile()??null}catch(t){return Wr.error("[asset-handler] Failed to read pasted file",t),null}}var mF=class{constructor(e,t,r,n,i){Te(this,"element",void 0),Te(this,"onInsertImage",void 0),Te(this,"onDeleteImage",void 0),Te(this,"onInsertSound",void 0),Te(this,"onDeleteSound",void 0),Te(this,"listeners",[]),this.element=e,this.onInsertImage=t,this.onDeleteImage=r,this.onInsertSound=n,this.onDeleteSound=i}attach(){if(Wr.debug("[AssetEventManager] Attaching event listeners"),this.onInsertImage){const e=t=>{const r=t;Wr.debug("[AssetEventManager] InsertImageEvent received"),this.onInsertImage(r.detail)};this.element.addEventListener(ny.TYPE,e),this.listeners.push({type:ny.TYPE,handler:e})}if(this.onDeleteImage){const e=t=>{const r=t;Wr.debug("[AssetEventManager] DeleteImageEvent received, src:",r.detail.src),this.onDeleteImage(r.detail.src,r.detail.done)};this.element.addEventListener(ry.TYPE,e),this.listeners.push({type:ry.TYPE,handler:e})}if(this.onInsertSound){const e=t=>{const r=t;Wr.debug("[AssetEventManager] InsertSoundEvent received"),this.onInsertSound(r.detail)};this.element.addEventListener(oy.TYPE,e),this.listeners.push({type:oy.TYPE,handler:e})}if(this.onDeleteSound){const e=t=>{const r=t;Wr.debug("[AssetEventManager] DeleteSoundEvent received, src:",r.detail.src),this.onDeleteSound(r.detail.src,r.detail.done)};this.element.addEventListener(iy.TYPE,e),this.listeners.push({type:iy.TYPE,handler:e})}Wr.debug("[AssetEventManager] Attached",this.listeners.length,"event listeners")}detach(){Wr.debug("[AssetEventManager] Detaching event listeners"),this.listeners.forEach(({type:e,handler:t})=>{this.element.removeEventListener(e,t)}),this.listeners=[],Wr.debug("[AssetEventManager] All event listeners detached")}};function gF(e){return t=>{Wr.debug("[createDefaultImageInsertHandler] Creating DataURL handler");let r=null;const n=new lR(a=>{e(a),r?.done(void 0,a)});r=cR(t,n);const i=()=>{r?.done(new Error("Image selection cancelled"))},o=a=>{if(!a){i();return}try{t.fileChosen(a)}catch(l){Wr.error("[createDefaultImageInsertHandler] fileChosen failed",l),r?.done(Hc(l,"Image fileChosen failed"));return}try{n.fileChosen(a)}catch(l){r?.done(Hc(l,"Image upload failed"))}},s=uR(t);if(s){o(s);return}if(t.isPasted){r?.done(new Error("Pasted image is unavailable"));return}dR("image/*",i).then(a=>{r?.isSettled()||o(a)}).catch(a=>{r?.done(Hc(a,"Image selection failed"))})}}function vF(e){return t=>{Wr.debug("[createDefaultSoundInsertHandler] Creating DataURL handler");let r=null;const n=new lR(l=>{e(l),r?.done(void 0,l)}),i=t;r=cR(i,n);const o=()=>{r?.done(new Error("Sound selection cancelled"))},s=l=>{if(!l){o();return}const d=i.fileChosen;if(typeof d=="function")try{d(l)}catch(c){Wr.error("[createDefaultSoundInsertHandler] fileChosen failed",c),r?.done(Hc(c,"Sound fileChosen failed"));return}try{n.fileChosen(l)}catch(c){r?.done(Hc(c,"Sound upload failed"))}},a=uR(i);if(a){s(a);return}if(i.isPasted){r?.done(new Error("Pasted sound is unavailable"));return}dR("audio/*",o).then(l=>{r?.isSettled()||s(l)}).catch(l=>{r?.done(Hc(l,"Sound selection failed"))})}}function yF(){return(e,t)=>{Wr.debug("[createDefaultImageDeleteHandler] Delete requested for:",e.substring(0,50)),t()}}function bF(){return(e,t)=>{Wr.debug("[createDefaultSoundDeleteHandler] Delete requested for:",e.substring(0,50)),t()}}var Gl=(function(e){return e.player="player.js",e.clientPlayer="client-player.js",e.editor="editor.js",e.esm="esm",e})({}),sy=(function(e){return e.loading="loading",e.loaded="loaded",e})({}),fR={invokeControllerForModel:!0,env:{mode:"gather",role:"student",partialScoring:!1},eventListeners:{}};function wF(e){return e&&typeof e.pie=="object"}function R1(e){return typeof e=="function"&&"prototype"in e&&e.prototype instanceof HTMLElement}function SF(e){return e&&typeof e.PIE_REGISTRY=="object"}var yd=()=>{let e;return SF(window)?e=window.PIE_REGISTRY:(e={},window.PIE_REGISTRY=e),e};function _1(e){const t=yd(),r=t[e.tagName];if(!r||r.status!==sy.loaded||!IF(e.tagName))return t[e.tagName]=e,e;const n=!r.controller&&!!e.controller,i=r.config==null&&e.config!=null;if(!n&&!i)return r;const o={...r};return n&&(o.controller=e.controller,o.bundleType=e.bundleType),i&&(o.config=e.config),t[e.tagName]=o,o}function IF(e){return typeof customElements<"u"&&customElements.get(e)!==void 0}var hR=e=>{if(!e)throw new Error("Parameter is required: input");const t=e.charAt(0)==="@"?e.match(/^(@[^/]+\/[^/@]+)(?:\/([^@]+))?(?:@([\s\S]+))?/):e.match(/^([^/@]+)(?:\/([^@]+))?(?:@([\s\S]+))?/);if(!t)throw new Error(`[parse-package-name] "${e}" is not a valid string`);return{name:t[1],path:t[2]||"",version:t[3]||""}},kF=e=>e.split("+").map(t=>hR(t).name).join("+"),pR=(e,t,r)=>{if(!e)throw new Error("session data is required");const n=e.find(o=>o.id===t);if(n)return r&&!n.element&&(n.element=r),n;const i=r?{id:t,element:r}:{id:t};return e.push(i),i},Ps=Yi("pie-scoring",()=>Ci()),wm=(e,t)=>{if(t===Gl.player){Ps.debug(`[findPieController] ℹ️ ${e} delivered as player.js; using server-processed models`);return}const r=yd();Ps.debug(`[findPieController] Looking for controller for: ${e}`),Ps.debug("[findPieController] Registry has entries for:",Object.keys(r));const n=r[e];if(!n){Ps.error(`[findPieController] ❌ No registry entry found for element: ${e}`),Ps.error("[findPieController] Available element names:",Object.keys(r)),Ps.error("[findPieController] Full registry:",r);return}Ps.debug(`[findPieController] Found registry entry for ${e}:`,{package:n.package,tagName:n.tagName,hasController:!!n.controller,controllerKeys:n.controller?Object.keys(n.controller):[],bundleType:n.bundleType});const i=n.controller??void 0;return i?Ps.debug(`[findPieController] ✅ Controller found for ${e} with functions:`,Object.keys(i)):Ps.debug(`[findPieController] ℹ️ No controller for ${e}; its model is used as given`),i},As=Yi("authoring",()=>Ci());function zc(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function TF(e){try{return hR(e).name}catch{return e}}function EF(e){return e.split("/").pop()||e}function P1(e,t){if(zc(e)){for(const r of t)if(Object.hasOwn(e,r))return e[r]}}function CF(e,t){return t===void 0?e??{}:zc(e)&&zc(t)?{...e,...t}:t}function mR(e,t,r){const n=TF(r),i=EF(n);return CF(P1(e,[r,n,t]),P1(e?.authoring,[t,r,n,i]))}function gR(e,t){const r=t.id;if(r)return e.find(n=>n.id===r)}function vR(e,t){return Array.from(e.querySelectorAll(t))}function xF(e,t={},r){const n=r.container??document,i=[];if(As.debug("[initializeAuthoringConfigures] Starting initialization"),As.debug("[initializeAuthoringConfigures] Config:",e),As.debug("[initializeAuthoringConfigures] Configuration:",t),As.debug("[initializeAuthoringConfigures] Env:",r.env),!e?.elements||!e?.models)return As.warn("[initializeAuthoringConfigures] Invalid config - missing elements or models"),i;for(const[o,s]of Object.entries(e.elements)){const a=`${o}-config`,l=vR(n,a);As.debug(`[initializeAuthoringConfigures] Found ${l.length} ${a} elements`);for(const d of l){const c=gR(e.models,d);if(!c){As.warn(`[initializeAuthoringConfigures] No model found for ${a}#${d.id||"(missing-id)"}`);continue}const u=d,f=mR(t,o,String(s));u.model=c,u.configuration=f,i.push({id:c.id,element:c.element,configureTag:a,configuration:f}),As.debug(`[initializeAuthoringConfigures] Model and configuration set for ${a}#${c.id}`,f)}}return As.debug("[initializeAuthoringConfigures] Initialization complete"),i}function RF(e){return wm(e.localName)}function _F(e){return zc(e)?zc(e.partA)&&zc(e.partB)?Object.keys(e.partA).length>0||Object.keys(e.partB).length>0:Object.keys(e).length>0:!1}async function A1(e,t={},r={}){const n=r.container??document,i=[];if(!e?.elements||!e?.models)return{hasErrors:!1,validatedModels:i};for(const[o,s]of Object.entries(e.elements)){const a=vR(n,`${o}-config`);for(const l of a){const d=gR(e.models,l);if(!d)continue;const c=RF(l),u=mR(t,o,String(s));if(typeof c?.validate!="function"){i.push(d);continue}const f=await c.validate(d,u),p={...d,errors:f};i.push(p);const g=l;JSON.stringify(g.model?.errors)!==JSON.stringify(f)&&(g.model=p)}}return{hasErrors:i.some(o=>_F(o.errors)),validatedModels:i}}function rh(e){return e instanceof Error?e:new Error(String(e??"Unknown authoring error"))}function PF(e,t,r){return new mF(e,t.onInsertImage?n=>{try{t.onInsertImage?.(n)}catch(i){const o=rh(i);r("onInsertImage",o),n.done(o)}}:void 0,t.onDeleteImage?(n,i)=>{try{t.onDeleteImage?.(n,i)}catch(o){const s=rh(o);r("onDeleteImage",s),i(s)}}:void 0,t.onInsertSound?n=>{try{t.onInsertSound?.(n)}catch(i){const o=rh(i);r("onInsertSound",o),n.done(o)}}:void 0,t.onDeleteSound?(n,i)=>{try{t.onDeleteSound?.(n,i)}catch(o){const s=rh(o);r("onDeleteSound",s),i(s)}}:void 0)}var AF=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");function M1(e,t){return Object.keys(t).reduce((r,n)=>{const i=new RegExp(`(<\\/?)${AF(n)}(?=[\\t\\n\\f\\r />])`,"g");return r.replace(i,(o,s)=>`${s}${n}-config`)},e)}var Pg=Yi("configure-init",()=>Ci());function $1(e,t,r){if(Pg.debug("[initializeConfiguresFromLoadedBundle] Starting initialization"),!e?.elements||!e?.models)return Pg.warn("[initializeConfiguresFromLoadedBundle] Invalid config - missing elements or models"),[];yd();const n=xF(e,t,r);return Pg.debug("[initializeConfiguresFromLoadedBundle] Initialization complete"),n}function ay(e){try{const t=new WeakSet;return JSON.stringify(e,(r,n)=>{if(!n||typeof n!="object"||Array.isArray(n))return n;if(t.has(n))return"[Circular]";t.add(n);const i=n,o={};for(const s of Object.keys(i).sort())o[s]=i[s];return o})??"undefined"}catch{return null}}function MF(){const e=new WeakMap;return({element:t,complete:r,session:n,commit:i})=>{if(!t||typeof t!="object")return!0;const o=ay({complete:r,session:n});return o===null?!0:!i&&e.get(t)===o?!1:(e.set(t,o),!0)}}function $F(e,t){return e===void 0||e===t?!1:ay(e)!==ay(t)}var Ka=Yi("pie-initialize-element",()=>Ci()),yR=(e,t)=>{const{config:r,session:n,env:i,eventListeners:o,bundleType:s}=t;if(e.__pieInitialized)return!0;const a=e.tagName.toLowerCase();Ka.debug(`[initializePieElement] Initializing ${a}#${e.id}`);const l=r?.models?.find(u=>u.id===e.id);if(!l){const u=yd()[a];return u&&u.bundleType===Gl.clientPlayer&&Ka.warn(`[initializePieElement] Model not found for PIE element ${a}#${e.id} (client-player.js bundle)`),!1}const d=pR(n,l.id,l.element);e.session=d,e.__pieInitialized=!0,Ka.debug(`[initializePieElement] Session set for ${a}#${e.id}:`,d);const c=wm(a,s);if(!i)throw Ka.error(`[initializePieElement] ❌ FATAL: No env provided for ${a}`),new Error(`No env provided for ${a}. PIE elements require an env object with mode and role.`);return c?Ka.debug(`[initializePieElement] Controller found for ${a}, will invoke model() function`):(Ka.debug(`[initializePieElement] ℹ️ No controller for ${a}, using server-processed model`),Ka.debug("[initializePieElement] Model already processed by server:",{id:l.id,element:l.element,hasCorrectResponse:"correctResponse"in l,mode:i.mode,role:i.role}),e.model=l),o&&Object.entries(o).forEach(([u,f])=>{e.addEventListener(u,f)}),!0},Ch=Yi("pie-element-observer",()=>Ci()),Ag=new Map,LF=e=>{const t=[];for(const r of e)try{t.push(r())}catch(n){Ch.error("[pieElementObserver] A context source threw; skipping it.",n)}return t},L1=(e,t)=>{const r=e.tagName.toLowerCase();if(yd()[r]){for(const n of t)if(yR(e,{config:n.config,session:n.session,env:n.env,eventListeners:n.eventListeners?.[r],bundleType:n.bundleType}))return}},OF=(e,t)=>{const r=LF(e);if(r.length!==0){for(const n of t)if(n.type==="childList")for(const i of n.addedNodes){if(i.nodeType!==Node.ELEMENT_NODE)continue;const o=i;L1(o,r);for(const s of Array.from(o.querySelectorAll("*")))L1(s,r)}}},O1=(e,t)=>{if(typeof document>"u"||typeof MutationObserver>"u")return()=>{};const r=e??document.body;if(!r)return()=>{};let n=Ag.get(r);if(!n){const a=new Set,l=new MutationObserver(d=>OF(a,d));l.observe(r,{childList:!0,subtree:!0}),n={sources:a,observer:l},Ag.set(r,n),Ch.debug("[observePieElements] Observing a new container")}const{sources:i,observer:o}=n;i.add(t),Ch.debug(`[observePieElements] Container now has ${i.size} registration(s)`);let s=!1;return()=>{s||(s=!0,i.delete(t),!(i.size>0)&&(o.disconnect(),Ag.delete(r),Ch.debug("[observePieElements] Released the last registration, disconnected")))}},NF=e=>e.mode!=="evaluate",DF=e=>({...e,role:"instructor"});function jF(e){try{const t={BASE_URL:"/",DEV:!1,MODE:"production",PROD:!0,SSR:!1}[e];if(typeof t=="string"&&t.length>0)return t}catch{}}var BF=typeof window<"u"&&window.PIE_BUILDER_BUNDLE_URL||jF("PUBLIC_BUILDER_BUNDLE_URL")||"https://proxy.pie-api.com/bundles/",ow=(...e)=>e.reduce((t,r)=>{for(const n in r)Object.hasOwn(r,n)&&r[n]!==null&&r[n]!==void 0&&(t[n]=r[n]);return t},{}),FF="@pie-lib/math-rendering";Yi("math-rendering",()=>Ci());var HF=()=>typeof window>"u"?null:window[FF]||null,zF=new Set(["annotation-xml","color-profile","font-face","font-face-src","font-face-uri","font-face-format","font-face-name","missing-glyph"]),WF=/^[a-z][a-z0-9._-]*-[a-z0-9._-]*$/,sw=(e,t="custom element tag")=>{if(!e||typeof e!="string")throw new Error(`Invalid ${t}: expected a non-empty string`);const r=e.trim();if(!r)throw new Error(`Invalid ${t}: tag is empty`);if(r!==r.toLowerCase())throw new Error(`Invalid ${t} "${r}": custom element names must be lowercase`);if(!r.includes("-"))throw new Error(`Invalid ${t} "${r}": custom element names must include a hyphen`);if(zF.has(r))throw new Error(`Invalid ${t} "${r}": this name is reserved by the HTML spec`);if(!WF.test(r))throw new Error(`Invalid ${t} "${r}": allowed characters are lowercase letters, numbers, ".", "_" and "-"`);return r},UF=e=>typeof DOMException<"u"&&e instanceof DOMException?e.name==="NotSupportedError"||e.code===DOMException.NOT_SUPPORTED_ERR:(typeof e=="object"&&e!==null&&"name"in e?String(e.name):"")==="NotSupportedError",qF=(e,t,r="custom element tag",n={})=>{const i=sw(e,r);if(customElements.get(i))return{outcome:"already-defined",tagName:i};try{return customElements.define(i,t),{outcome:"defined",tagName:i}}catch(o){if(!UF(o))return{outcome:"error",tagName:i,error:o};if(customElements.get(i))return{outcome:"already-defined",tagName:i};if(!n.allowWrappedFallback)return{outcome:"error",tagName:i,error:o};try{return customElements.define(i,class extends t{}),{outcome:"defined-wrapped",tagName:i}}catch(s){return{outcome:"wrapped-error",tagName:i,error:s}}}},N1=(e,t,r="custom element tag")=>{const n=qF(e,t,r);if(n.outcome==="error"||n.outcome==="wrapped-error")throw n.error;return{status:n.outcome==="already-defined"?"already-defined":"defined",tagName:n.tagName}},ao=Yi("pie-updates",()=>Ci()),bR=e=>{if(!e)return"missing";if(typeof e=="function")return"function";if(typeof e!="object")return typeof e;const t=Object.keys(e),r=e.default,n=r&&typeof r=="object"?Object.keys(r):[];return n.length>0?`object(keys=[${t.join(",")}],defaultKeys=[${n.join(",")}])`:`object(keys=[${t.join(",")}])`},VF=e=>{if(!e)return null;if(typeof e=="function")return e;if(typeof e!="object")return null;const t=e.model;if(typeof t=="function")return(n,i,o,s)=>t.call(e,n,i,o,s);const r=e.default;if(r&&typeof r=="object"){const n=r.model;if(typeof n=="function")return(i,o,s,a)=>n.call(r,i,o,s,a)}return null},GF=(e,t)=>{e.dispatchEvent(new CustomEvent("pie-controller-error",{detail:t,bubbles:!0,composed:!0}))},KF=e=>{const t=e.isConnected;return()=>t&&!e.isConnected},XF=async(e,t,r,n,i,o,s,a)=>{ao.debug(`${o} Using controller, env:`,i),ao.debug(`${o} Model before filter:`,{id:t.id,element:t.element,hasCorrectResponse:"correctResponse"in t});const l=(d,c,u)=>(ao.debug(`${o} updateSession called for ${d} with:`,u),Object.assign(r,u),a?.(t.id,t.element,u),Promise.resolve());try{const d=VF(n);if(!d)throw new Error(`Controller contract mismatch: expected a model() function but received ${bR(n)}`);const c=await d(t,r,i,l),u=c&&typeof c=="object"?c:{},f={id:t.id,element:t.element,...u};if(ao.debug(`${o} ✅ Controller filtered model:`,{id:f.id,element:f.element,hasCorrectResponse:"correctResponse"in f,mode:i.mode,role:i.role}),s())return;e.model=f,e.session=r}catch(d){throw ao.error(`${o} ❌ Controller error:`,d),d}},ZF=e=>{const{config:t,session:r,env:n,eventListeners:i,invokeControllerForModel:o,bundleType:s,onElementSessionUpdate:a}=ow(fR,e);if(!n)throw new Error("env is required");if(!r)throw new Error("session is required");if(!t)throw new Error("config is required");return{config:t,session:r,env:n,eventListeners:i,invokeControllerForModel:o,bundleType:s,onElementSessionUpdate:a}},YF=async(e,t,r,n)=>{const{config:i,session:o,env:s,eventListeners:a,invokeControllerForModel:l,bundleType:d,onElementSessionUpdate:c}=r,u=i.models?.find(p=>p.id===e.id);if(!u)throw ao.error(`${n} Model not found for`,t),new Error(`model not found for ${t}`);const f=pR(o,u.id,u.element);if(a&&Object.entries(a).forEach(([p,g])=>{e.addEventListener(p,g)}),s&&l){const p=wm(t,d);if(!p){ao.debug(`${n} ℹ️ No controller for ${t}, using server-processed model`),e.model=u,e.session=f;return}ao.debug(`${n} Invoking controller for ${t}#${e.id}`,{mode:s.mode,role:s.role,hasCorrectResponse:"correctResponse"in u});const g=KF(e);try{await XF(e,u,f,p,s,`${n}(${t}#${e.id})`,g,c)}catch(v){const b=v instanceof Error?v.message:String(v),w=b.includes("Controller contract mismatch");if(ao.error(`${n} Controller failed for ${t}#${e.id}:`,v),GF(e,{code:w?"PIE_CONTROLLER_CONTRACT_ERROR":"PIE_CONTROLLER_RUNTIME_ERROR",message:`${t} controller failed while applying model for ${e.id}. ${b}`,recoverable:!0,elementName:t,elementId:e.id,controllerShape:bR(p),cause:b}),g())return;e.model=u,e.session=f}}else ao.debug(`${n} Direct model assignment for ${t}#${e.id} (no controller invocation requested)`),e.model=u,e.session=f},wR=(e,t)=>{const r=ZF(t),{container:n}=ow(fR,t),i=(n||document).querySelectorAll(e);return!i||i.length===0?(ao.debug(`no elements found for ${e}`),Promise.resolve()):Promise.all(Array.from(i,o=>YF(o,e,r,"[updatePieElement]"))).then(()=>{})},hc=(e,t,r,n,i,o)=>(ao.debug("[updatePieElements] Updating all elements with env:",r),Promise.all(Object.entries(e.elements).map(([s,a])=>wR(s,{config:e,session:t,env:r,container:n,onElementSessionUpdate:i,bundleType:o}))).then(()=>{})),Tn=Yi("pie-initialization",()=>Ci());Yx.timeoutMs;var JF={buildServiceBase:BF,bundleType:Gl.player,env:{mode:"gather",role:"student"}},D1=(e,t)=>sw(e+pF,`editor element tag for ${t}`),j1=(e,t,r,n,i=!1)=>{wR(e,{config:t,session:r,...i?{}:{env:n.env},bundleType:n.bundleType,container:n.container,...n.eventListeners?.[e]&&{eventListeners:n.eventListeners[e]}})},B1=(e,t,r,n,i)=>{const o=[];return e?Tn.debug("[registerPieElementsFromBundle] Available packages in bundle:",Object.keys(e)):Tn.debug("[registerPieElementsFromBundle] No bundle module supplied; will only update tags already registered with customElements."),Tn.debug("[registerPieElementsFromBundle] config.elements:",t.elements),Object.entries(t.elements).forEach(([s,a])=>{const l=sw(s,`element tag in config.elements for ${String(a)}`);if(Tn.debug(`[registerPieElementsFromBundle] Processing element: ${l} -> ${a}`),customElements.get(l)){j1(l,t,r,i),i.bundleType===Gl.editor&&j1(D1(l,String(a)),t,r,i,!0);return}if(!e){Tn.warn(`[registerPieElementsFromBundle] Skipping "${l}" — no bundle module available and the tag is not yet registered. Will bind on next update if the host's loader registers it.`);return}const d=kF(a);Tn.debug(`[registerPieElementsFromBundle] Package without version: "${d}"`);const c=e[d];if(Tn.debug("[registerPieElementsFromBundle] elementData result:",c?"FOUND":"UNDEFINED"),!c)throw Tn.error(`[registerPieElementsFromBundle] ❌ Package "${d}" not found in bundle!`),Tn.error(`[registerPieElementsFromBundle] Lookup key: "${d}"`),Tn.error("[registerPieElementsFromBundle] Available packages:",Object.keys(e)),new Error(`pie ${d} not found in ${Object.keys(e)}`);if(Tn.debug(`[registerPieElementsFromBundle] elementData for ${d}:`,{hasController:!!c.controller,hasElement:!!c.Element,hasConfig:!!c.config,controllerKeys:c.controller?Object.keys(c.controller):[],bundleType:i.bundleType}),Tn.debug(`[registerPieElementsFromBundle] Registering ${s} in registry${c.controller?" with controller":" (no controller; its model is used as given)"}`),_1({package:a,status:sy.loading,tagName:l,controller:c.controller||null,config:c.config,bundleType:i.bundleType}),R1(c.Element)){N1(l,c.Element,`element tag in config.elements for ${String(a)}`);const u=(i.container||document).querySelectorAll(l);if(Tn.debug(`[registerPieElementsFromBundle] Found ${u.length} elements for tag '${l}'`),u.forEach(f=>{yR(f,{config:t,session:r,env:i.env,eventListeners:i.eventListeners?.[l],bundleType:i.bundleType})}),_1({...n[l],status:sy.loaded}),o.push(customElements.whenDefined(l).then(()=>{Tn.debug("[registerPieElementsFromBundle] defined custom PIE element: %s",l)})),i.bundleType===Gl.editor)if(R1(c.Configure)){const f=D1(l,String(a));N1(f,c.Configure,`editor element tag for ${String(a)}`),o.push(customElements.whenDefined(f).then(()=>{Tn.debug(`[registerPieElementsFromBundle] defined custom PIE editor element: ${f}`)}))}else Tn.error(`[registerPieElementsFromBundle] pie.Configure for ${d} is not a valid custom element constructor.`,c.configure)}else Tn.error(`[registerPieElementsFromBundle] pie.Element for ${d} is not a valid custom element constructor.`)}),o},F1=(e,t,r={})=>{const n=yd(),i=ow(JF,r);if(wF(window)){Tn.debug("[initializePiesFromLoadedBundle] window.pie available");const o=window.pie.default;B1(o,e,t,n,i);return}Tn.debug("[initializePiesFromLoadedBundle] window.pie not present; using update-only path. Already-registered tags will be bound now; missing tags are expected to be registered by the host's loader and will bind on the next update pass."),B1(null,e,t,n,i)},QF=/\\\(|\\\[|\$\$|\\\$|\\begin\{|\\(?:eq)?ref\{/,eH=/\\\(|\\\[|\$|\\begin\{|\\(?:eq)?ref\{/,tH=new Set(["script","noscript","style","textarea","pre","code","annotation","annotation-xml","mjx-container","mjx-assistive-mml"]),rH=/(?:^|\s)mathjax_ignore(?:\s|$)/,nH="http://www.w3.org/1999/xhtml";function iH(){return globalThis["@pie-lib/math-rendering@2"]?.opts?.useSingleDollar?eH:QF}function oH(e){return tH.has(e.localName)||rH.test(e.getAttribute("class")??"")}function SR(e){return e.localName==="math"||e.hasAttribute("data-latex")&&!e.hasAttribute("data-math-handled")}function H1(e,t){if(SR(e)||e.querySelector("[data-latex]:not([data-math-handled])"))return!0;for(const r of e.getElementsByTagName("math"))if(!r.closest("mjx-assistive-mml"))return!0;return t.test(e.textContent??"")}function z1(e){const t=(e.ownerDocument??document).createElement("span");return e.replaceWith(t),t.append(e),t}function sH(e,t){const r=iH(),n=new Set;for(const s of t)for(const a of e.getElementsByTagName(s))for(let l=a.parentElement;l&&!n.has(l)&&(n.add(l),l!==e);l=l.parentElement);if(!n.has(e))return H1(e,r)?[e]:[];const i=[],o=s=>{for(const a of[...s.childNodes]){if(a.nodeType===Node.TEXT_NODE){r.test(a.data)&&i.push(z1(a));continue}if(a.nodeType!==Node.ELEMENT_NODE)continue;const l=a;t.has(l.localName)||oH(l)||(n.has(l)?o(l):H1(l,r)&&(SR(l)?i.push(z1(l)):l.namespaceURI===nH&&i.push(l)))}};return o(e),i}async function aH(e,t,r){const n=[...e].flatMap(i=>sH(i,t));for(const i of n)await r(i)}var nh=null;async function lH(e){nh??(nh=br(()=>import("./chunks/browser-a3c32178.js"),[],import.meta.url));let t;try{t=await nh}catch(r){throw nh=null,r}await t.renderMath(e)}function W1(e){const t=e;return typeof t?.noticeError=="function"&&typeof t.addPageAction=="function"}function pc(){if(typeof window>"u")return;const{newrelic:e,NREUM:t}=window;if(W1(e))return e;if(W1(t))return t}var cH=class{constructor(){Te(this,"initialized",!1),Te(this,"config",void 0)}trackError(e,t){if(!this.guardedOperation("trackError",e,t)||!this.applyErrorFilter(e,t))return;const r=this.transformAttributes(t);try{this.doTrackError(e,r),this.config?.debug&&console.log(`[${this.providerName}] Tracked error:`,e,r)}catch(n){console.error(`[${this.providerName}] Error tracking error:`,n)}}trackEvent(e,t){if(!this.guardedOperation("trackEvent",e,t)||!this.applyEventFilter(e,t)||!this.applySampling(e))return;let r=this.transformAttributes(t);r.timestamp||(r={...r,timestamp:new Date().toISOString()});try{this.doTrackEvent(e,r),this.config?.debug&&console.log(`[${this.providerName}] Tracked event:`,e,r)}catch(n){console.error(`[${this.providerName}] Error tracking event:`,n)}}trackMetric(e,t,r){this.trackEvent(`metric:${e}`,{...r,metricValue:t,metricName:e})}setUserContext(e,t){if(this.guardedOperation("setUserContext",e,t))try{this.doSetUserContext(e,t),this.config?.debug&&console.log(`[${this.providerName}] Set user context:`,e,t)}catch(r){console.error(`[${this.providerName}] Error setting user context:`,r)}}setGlobalAttributes(e){if(this.guardedOperation("setGlobalAttributes",e))try{this.doSetGlobalAttributes(e),this.config?.debug&&console.log(`[${this.providerName}] Set global attributes:`,e)}catch(t){console.error(`[${this.providerName}] Error setting global attributes:`,t)}}guardedOperation(e,...t){return this.isReady()?!0:(this.config?.debug&&console.warn(`[${this.providerName}] Attempted to ${e} but provider not ready:`,...t),!1)}applyErrorFilter(e,t){return this.config?.errorFilter&&!this.config.errorFilter(e,t)?(this.config?.debug&&console.log(`[${this.providerName}] Error filtered out:`,e,t),!1):!0}applyEventFilter(e,t){return this.config?.eventFilter&&!this.config.eventFilter(e,t)?(this.config?.debug&&console.log(`[${this.providerName}] Event filtered out:`,e,t),!1):!0}applySampling(e){return this.config?.sampleRate!==void 0&&this.config.sampleRate<1&&Math.random()>this.config.sampleRate?(this.config?.debug&&console.log(`[${this.providerName}] Event sampled out:`,e),!1):!0}transformAttributes(e){return this.config?.attributeTransformer?this.config.attributeTransformer(e):e}},dH=class extends cH{constructor(...e){super(...e),Te(this,"providerId","newrelic"),Te(this,"providerName","New Relic")}async initialize(e){this.config=e,this.initialized=!0,this.config?.debug&&console.log(pc()?"[NewRelicProvider] Initialized successfully":"[NewRelicProvider] Initialized; sends once the New Relic agent is on the page")}isReady(){return this.initialized&&pc()!==void 0}destroy(){this.initialized=!1,this.config?.debug&&console.log("[NewRelicProvider] Destroyed")}doTrackError(e,t){pc()?.noticeError(e,t)}doTrackEvent(e,t){pc()?.addPageAction(e,t)}doSetUserContext(e,t){const r=pc();if(typeof r?.setUserId=="function"&&r.setUserId(e),t&&typeof r?.setCustomAttribute=="function")for(const[n,i]of Object.entries(t))r.setCustomAttribute(n,i)}doSetGlobalAttributes(e){const t=pc();if(typeof t?.setCustomAttribute=="function")for(const[r,n]of Object.entries(e))t.setCustomAttribute(r,n)}};function U1(e){return e&&typeof e=="object"?e:{}}function q1(e){const t=U1(U1(e).loaderConfig);return Object.keys(t).length>0?t:null}function V1(e){if(!e||!("instrumentationProvider"in e))return{kind:"unset"};const t=e.instrumentationProvider;return t===null?{kind:"null"}:typeof t>"u"?{kind:"unset"}:{kind:"value",value:t}}function G1(e){if(!e||!("trackPageActions"in e))return;const t=e.trackPageActions;return typeof t=="boolean"?t:void 0}function uH(e,t){return e.kind==="value"||e.kind==="null"?e:t}var ih,fH=Yi("instrumentation-provider-resolution",()=>Ci());function hH(){return ih||(ih=new dH,ih.initialize()),ih}function IR(e){const t=q1(e.runtimePlayer),r=q1(e.player),n=G1(t),i=G1(r),o=n??i??!1,s=uH(V1(t),V1(r));if(s.kind!=="null"){if(s.kind==="unset")return o?hH():void 0;if(tw(s.value))return s.value;if(e.debug){const a=e.component?`[${e.component}] `:"";fH.warn(`${a}Ignoring invalid instrumentation provider; expected InstrumentationProvider contract`)}}}var pH=Symbol.for("pie.sessionCommit.observedSignature");function kR(e){return e.tagName.includes("-")?"session"in e&&"model"in e:!1}function mH(e){return e?.shadowRoot??null}function gH(e){const t=e;if(typeof t.assignedElements!="function")return[];try{return t.assignedElements({flatten:!0})}catch{return[]}}function ly(e,t,r){const n=mH(e);n&&ly(n,t,r);const i=s=>{t.has(s)||(t.add(s),kR(s)&&r.push(s),ly(s,t,r))};for(const s of gH(e))i(s);const o=e.children;if(o)for(const s of Array.from(o))i(s)}function TR(e){return!!e&&typeof e=="object"&&typeof e.tagName=="string"}function vH(e){const t=[],r=new Set;return TR(e)&&kR(e)&&(r.add(e),t.push(e)),ly(e,r,t),t}function ER(e){try{return e.session}catch{return}}function CR(e){try{const t=JSON.stringify(e);return typeof t=="string"?t:null}catch{return null}}function xR(e,t){try{Object.defineProperty(e,pH,{value:t,configurable:!0,enumerable:!1,writable:!0})}catch{}}function yH(e){if(!TR(e))return;const t=CR(ER(e));t!==null&&xR(e,t)}function bH(e){if(e)for(const t of vH(e)){const r=CR(ER(t));r!==null&&xR(t,r)}}var mc={trackPageActions:!1,manageProviderLifecycle:!1,maxRetries:3,initialRetryDelay:500,maxRetryDelay:5e3,debug:!1},wH=80,SH=1200,IH=75,kH=class{constructor(e={}){Te(this,"config",void 0),Te(this,"logger",void 0),Te(this,"observer",null),Te(this,"mutationObserver",null),Te(this,"errorHandler",null),Te(this,"retryAttempts",new Map),Te(this,"retryTargets",new Map),Te(this,"container",null),Te(this,"isBrowser",void 0),Te(this,"containerResources",new Set),Te(this,"provider",void 0),Te(this,"started",!1),Te(this,"lifecycleVersion",0),Te(this,"pendingRetryTimers",new Map),Te(this,"retryInFlight",new Set),Te(this,"pendingMediaChecks",new Map),this.config={trackPageActions:e.trackPageActions??mc.trackPageActions,manageProviderLifecycle:e.manageProviderLifecycle??mc.manageProviderLifecycle,maxRetries:e.maxRetries??mc.maxRetries,initialRetryDelay:e.initialRetryDelay??mc.initialRetryDelay,maxRetryDelay:e.maxRetryDelay??mc.maxRetryDelay,debug:e.debug??mc.debug},this.logger=Yi("resource-monitor",()=>this.isDebugEnabled()),this.provider=tw(e.instrumentationProvider)?e.instrumentationProvider:void 0,e.instrumentationProvider&&!this.provider&&this.isDebugEnabled()&&this.logger.warn("Ignoring invalid instrumentation provider; expected InstrumentationProvider shape"),this.provider&&this.config.manageProviderLifecycle?this.provider.initialize().catch(t=>{this.isDebugEnabled()&&this.logger.warn("Failed to initialize instrumentation provider:",t)}):this.provider&&this.isDebugEnabled()&&this.logger.debug("Skipping provider lifecycle management for injected provider"),this.isBrowser=typeof window<"u"&&typeof document<"u"}isDebugEnabled(){return this.config.debug||Ci()}truncateUrl(e){return e.length>wH?"..."+e.slice(-77):e}getOriginalUrl(e){try{const t=new URL(e);return t.searchParams.delete("retry"),t.searchParams.delete("t"),t.toString()}catch{return e}}withRetryParams(e,t){const r=String(t),n=Date.now().toString();try{const i=new URL(e);return i.searchParams.set("retry",r),i.searchParams.set("t",n),i.toString()}catch{return`${e}${e.includes("?")?"&":"?"}retry=${encodeURIComponent(r)}&t=${encodeURIComponent(n)}`}}getMediaErrorName(e){switch(e){case 1:return"MEDIA_ERR_ABORTED";case 2:return"MEDIA_ERR_NETWORK";case 3:return"MEDIA_ERR_DECODE";case 4:return"MEDIA_ERR_SRC_NOT_SUPPORTED";default:return}}buildResourceErrorDiagnostics(e,t){const r={eventType:t.eventType,tagName:e.tagName.toLowerCase(),resourceUrl:t.resourceUrl,originalUrl:t.originalUrl,currentRetries:t.currentRetries,remainingRetries:t.remainingRetries,willRetry:t.willRetry,cacheBypassActive:t.resourceUrl.includes("retry=")||t.resourceUrl.includes("t=")};if(e instanceof HTMLAudioElement||e instanceof HTMLVideoElement){const n=e.error,i=n?.code;r.currentSrc=e.currentSrc||e.src,r.readyState=e.readyState,r.networkState=e.networkState,r.paused=e.paused,r.ended=e.ended,r.currentTime=e.currentTime,r.duration=Number.isFinite(e.duration)?e.duration:null,r.mediaErrorCode=i,r.mediaErrorName=this.getMediaErrorName(i),r.mediaErrorMessage=typeof n?.message=="string"?n.message:void 0}return r}trackInstrumentationEvent(e,t){!this.config.trackPageActions||!this.provider?.isReady()||this.provider.trackEvent(e,{...t,component:"resource-monitor",timestamp:new Date().toISOString()})}trackInstrumentationError(e,t){!this.config.trackPageActions||!this.provider?.isReady()||this.provider.trackError(e,{...t,component:"resource-monitor",errorType:t.errorType||"ResourceError"})}start(e){if(this.started){if(this.container===e)return;this.stop()}if(!this.isBrowser){this.logger.debug("Not in browser environment, skipping resource monitoring");return}this.container=e,this.lifecycleVersion+=1,this.setupMutationObserver(),this.scanContainerResources(),this.setupPerformanceObserver(),this.setupErrorHandler(),this.started=!0,this.logger.info("✅ Resource monitoring started")}stop(){if(this.started){this.lifecycleVersion+=1,this.observer&&(this.observer.disconnect(),this.observer=null),this.mutationObserver&&(this.mutationObserver.disconnect(),this.mutationObserver=null),this.errorHandler&&this.container&&(this.container.removeEventListener("error",this.errorHandler,!0),this.errorHandler=null),this.retryAttempts.clear(),this.retryTargets.clear(),this.retryInFlight.clear();for(const e of this.pendingRetryTimers.values())clearTimeout(e);this.pendingRetryTimers.clear();for(const e of this.pendingMediaChecks.values())e.cleanup();if(this.pendingMediaChecks.clear(),this.containerResources.clear(),this.container=null,this.started=!1,this.provider&&this.config.manageProviderLifecycle)try{this.provider.destroy()}catch(e){this.isDebugEnabled()&&this.logger.warn("Failed to destroy instrumentation provider:",e)}this.logger.info("Resource monitoring stopped")}}setupMutationObserver(){if(!this.isBrowser||typeof MutationObserver>"u"||!this.container){this.logger.debug("MutationObserver not available or no container");return}try{this.mutationObserver=new MutationObserver(e=>{for(const t of e)if(t.addedNodes.forEach(r=>{r instanceof HTMLElement&&this.scanElementForResources(r)}),t.type==="attributes"&&t.target instanceof HTMLElement){const r=t.target;if(this.isResourceElement(r)){const n=this.getResourceSrc(r);n&&(this.containerResources.add(n),this.isDebugEnabled()&&this.logger.debug(`📌 Tracked resource attribute change: ${n}`))}}}),this.mutationObserver.observe(this.container,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","href"]}),this.logger.debug("MutationObserver set up successfully")}catch(e){this.logger.warn("Failed to set up MutationObserver:",e)}}scanElementForResources(e){if(this.isResourceElement(e)){const t=this.getResourceSrc(e);t&&(this.containerResources.add(t),this.isDebugEnabled()&&this.logger.debug(`📌 Tracked new resource in container: ${t}`))}["img","audio","video",'link[rel="stylesheet"]',"source"].forEach(t=>{e.querySelectorAll(t).forEach(r=>{if(this.isResourceElement(r)){const n=this.getResourceSrc(r);n&&this.containerResources.add(n)}})})}scanContainerResources(){this.container&&(this.scanElementForResources(this.container),this.isDebugEnabled()&&(this.logger.debug(`📊 Initial container scan found ${this.containerResources.size} resources`),this.containerResources.size>0&&this.containerResources.forEach(e=>{this.logger.debug(` - ${this.truncateUrl(e)}`)})))}setupPerformanceObserver(){if(!this.isBrowser||typeof PerformanceObserver>"u"){this.logger.debug("PerformanceObserver not available");return}try{this.observer=new PerformanceObserver(e=>{for(const t of e.getEntries())t.entryType==="resource"&&this.handleResourceTiming(t)}),this.observer.observe({type:"resource",buffered:!0}),this.logger.debug("PerformanceObserver set up successfully")}catch(e){this.logger.warn("Failed to set up PerformanceObserver:",e)}}handleResourceTiming(e){if(!this.isRelevantResource(e)){this.isDebugEnabled()&&(e.initiatorType==="img"||e.initiatorType==="audio"||e.initiatorType==="video")&&this.logger.debug(`⏭️ Skipping non-container resource: ${this.truncateUrl(e.name)}`);return}const t=e.duration,r=e.transferSize,n=e.name,i=this.getOriginalUrl(n),o=e.responseEnd===0&&e.duration>0,s=this.retryAttempts.has(i),a=this.retryAttempts.get(i)||0;if(this.isDebugEnabled()){const l=this.truncateUrl(n),d=(r/1024).toFixed(2),c=o?"❌ FAILED":"✅ SUCCESS",u={total:`${t.toFixed(2)}ms`,dns:e.domainLookupEnd>0?`${(e.domainLookupEnd-e.domainLookupStart).toFixed(2)}ms`:"n/a",tcp:e.connectEnd>0?`${(e.connectEnd-e.connectStart).toFixed(2)}ms`:"n/a",request:e.responseStart>0?`${(e.responseStart-e.requestStart).toFixed(2)}ms`:"n/a",response:e.responseEnd>0?`${(e.responseEnd-e.responseStart).toFixed(2)}ms`:"n/a",size:r>0?`${d} KB`:"0 KB",type:e.initiatorType,protocol:e.nextHopProtocol||"unknown"},f=s&&!o?`
984
+ 🔄 Retry Success: Succeeded after ${a} ${a===1?"retry":"retries"}`:"";this.logger.info(`📊 PIE Resource Load ${c}
985
+ URL: ${l}
986
+ Type: ${u.type} | Protocol: ${u.protocol}
987
+ ⏱️ Total Time: ${u.total}
988
+ └─ DNS Lookup: ${u.dns}
989
+ └─ TCP Connect: ${u.tcp}
990
+ └─ Request Time: ${u.request}
991
+ └─ Response Time: ${u.response}
992
+ 📦 Transfer Size: ${u.size}${f}`)}else this.logger.debug(`Resource loaded: ${e.name}`,{duration:`${t.toFixed(2)}ms`,size:`${r} bytes`,type:e.initiatorType,failed:o,wasRetried:s,retryCount:a});o||this.handleSuccessfulLoad(i,e,t,r,a,s),this.trackInstrumentationEvent("pie-resource-load",{url:e.name,duration:Math.round(t),size:r,type:e.initiatorType,failed:o,wasRetried:s,retryCount:a}),o&&this.handleFailedLoad(i,e,t,a,s)}isLifecycleActive(e){return this.started&&this.lifecycleVersion===e}clearRetryTracking(e){this.retryAttempts.delete(e),this.retryTargets.delete(e),this.retryInFlight.delete(e)}clearPendingMediaCheck(e){const t=this.pendingMediaChecks.get(e);t&&(t.cleanup(),this.pendingMediaChecks.delete(e))}getRetryTargets(e){let t=this.retryTargets.get(e);return t||(t=new Set,this.retryTargets.set(e,t)),t}getPrimaryRetryTarget(e){const t=this.retryTargets.get(e);if(!t||t.size===0)return null;for(const r of t)return r;return null}handleSuccessfulLoad(e,t,r,n,i,o){const s={url:e,resourceType:t.initiatorType,duration:r,size:n,retryCount:i,maxRetries:this.config.maxRetries},a=t.initiatorType==="audio"||t.initiatorType==="video"||t.initiatorType==="source";if(o&&a){this.reconcileMediaRetrySuccess(e,s);return}this.dispatchEvent("pie-resource-load-success",s),o&&this.finalizeRetrySuccess(e,s)}resolveMediaTarget(e){if(e instanceof HTMLAudioElement)return{mediaEl:e,mediaTag:"audio"};if(e instanceof HTMLVideoElement)return{mediaEl:e,mediaTag:"video"};if(e instanceof HTMLSourceElement){const t=e.parentElement;if(t instanceof HTMLAudioElement)return{mediaEl:t,mediaTag:"audio"};if(t instanceof HTMLVideoElement)return{mediaEl:t,mediaTag:"video"}}return null}resolveMediaTargetsForUrl(e){const t=this.retryTargets.get(e);if(!t||t.size===0)return[];const r=new Set,n=[];for(const i of t){const o=this.resolveMediaTarget(i);if(!o)continue;const{mediaEl:s,mediaTag:a}=o;if(r.has(s))continue;const l=s.currentSrc||s.src;l&&this.getOriginalUrl(l)!==e||(r.add(s),n.push({mediaEl:s,mediaTag:a}))}return n}normalizeRetrySuccessResourceType(e,t){if(t!=="source")return t;const r=this.resolveMediaTargetsForUrl(e);return r.length===0?t:r[0].mediaTag}isMediaRetryRecovered(e){const t=this.resolveMediaTargetsForUrl(e);if(t.length===0)return!1;for(const{mediaEl:r}of t){const n=!!r.error,i=r.networkState===HTMLMediaElement.NETWORK_NO_SOURCE,o=r.readyState>=HTMLMediaElement.HAVE_METADATA;if(!n&&!i&&o)return!0}return!1}finalizeRetrySuccess(e,t){if(!this.retryAttempts.has(e))return;const r={...t,resourceType:this.normalizeRetrySuccessResourceType(e,t.resourceType)},n=this.truncateUrl(e);this.logger.info(`✅ PIE Resource Retry Succeeded!
993
+ URL: ${n}
994
+ Retry Attempt: ${r.retryCount}
995
+ Load Time: ${(r.duration||0).toFixed(2)}ms
996
+ Result: Resource now available to user`),this.dispatchEvent("pie-resource-retry-success",r),this.dispatchMediaRetryReady(e,r),this.clearPendingMediaCheck(e),this.clearRetryTracking(e)}reconcileMediaRetrySuccess(e,t){if(this.clearPendingMediaCheck(e),this.isMediaRetryRecovered(e)){this.dispatchEvent("pie-resource-load-success",t),this.finalizeRetrySuccess(e,t);return}this.isDebugEnabled()&&this.logger.debug(`⏳ Waiting for media readiness before retry success: ${this.truncateUrl(e)}`);const r=this.lifecycleVersion,n=this.resolveMediaTargetsForUrl(e),i=[],o=setInterval(()=>{if(!this.isLifecycleActive(r)){this.clearPendingMediaCheck(e);return}if(!this.retryAttempts.has(e)){this.clearPendingMediaCheck(e);return}this.isMediaRetryRecovered(e)&&(this.dispatchEvent("pie-resource-load-success",t),this.finalizeRetrySuccess(e,t))},IH),s=setTimeout(()=>{if(!this.isLifecycleActive(r)){this.clearPendingMediaCheck(e);return}if(!this.retryAttempts.has(e)){this.clearPendingMediaCheck(e);return}this.clearPendingMediaCheck(e),this.handleMediaRetryReconciliationTimeout(e,t)},SH);for(const{mediaEl:a}of n){const l=()=>{this.isLifecycleActive(r)&&this.retryAttempts.has(e)&&this.isMediaRetryRecovered(e)&&(this.dispatchEvent("pie-resource-load-success",t),this.finalizeRetrySuccess(e,t))};a.addEventListener("loadedmetadata",l),a.addEventListener("canplay",l),i.push({mediaEl:a,handler:l})}this.pendingMediaChecks.set(e,{cleanup:()=>{clearInterval(o),clearTimeout(s);for(const{mediaEl:a,handler:l}of i)a.removeEventListener("loadedmetadata",l),a.removeEventListener("canplay",l)}})}handleMediaRetryReconciliationTimeout(e,t){const r=this.truncateUrl(e);this.logger.warn(`⚠️ PIE Resource Retry Ready Timeout
997
+ URL: ${r}
998
+ Retry Attempt: ${t.retryCount}
999
+ Status: Media did not become healthy after fetch success`),this.dispatchEvent("pie-resource-retry-failed",{...t,error:"Media fetch succeeded but did not become ready before timeout"}),this.trackInstrumentationError(new Error(`Resource retry reconciliation timed out before media was healthy: ${e}`),{resourceUrl:e,resourceType:t.resourceType,retryCount:t.retryCount,errorType:"MediaRetryReadyTimeout"});const n=this.getPrimaryRetryTarget(e);if(n){this.retryResourceLoad(n,e);return}this.handlePermanentFailure(e,t.resourceType,t.retryCount)}dispatchMediaRetryReady(e,t){const r=this.resolveMediaTargetsForUrl(e);if(r.length!==0)for(const{mediaEl:n,mediaTag:i}of r){const o=new CustomEvent("pie-media-retry-ready",{detail:{...t,mediaTag:i},bubbles:!0,composed:!0});n.dispatchEvent(o)}}handleFailedLoad(e,t,r,n,i){const o=this.truncateUrl(e);i?(this.logger.warn(`⚠️ PIE Resource Retry Failed
1000
+ URL: ${o}
1001
+ Retry Attempt: ${n}
1002
+ Remaining Attempts: ${this.config.maxRetries-n}
1003
+ Status: Will ${n>=this.config.maxRetries?"give up":"retry again"}`),this.dispatchEvent("pie-resource-retry-failed",{url:e,resourceType:t.initiatorType,duration:r,retryCount:n,maxRetries:this.config.maxRetries,error:"Resource load failed after retry"})):(this.logger.warn(`⚠️ PIE Resource Initial Load Failed
1004
+ URL: ${o}
1005
+ Status: Will attempt ${this.config.maxRetries} ${this.config.maxRetries===1?"retry":"retries"}`),this.dispatchEvent("pie-resource-load-failed",{url:e,resourceType:t.initiatorType,duration:r,retryCount:0,maxRetries:this.config.maxRetries,error:"Initial resource load failed"})),this.trackInstrumentationError(new Error(`Resource load failed: ${t.name}`),{resourceUrl:t.name,resourceType:t.initiatorType,duration:Math.round(r),wasRetried:i,retryCount:n})}isRelevantResource(e){const t=e.name;let r=this.containerResources.has(t);if(!r){for(const n of this.containerResources)if(t.endsWith(n)||n.endsWith(t))return!0;if(this.container&&this.isResourceInContainer(t,e.initiatorType))return this.containerResources.add(t),this.isDebugEnabled()&&this.logger.debug(`📌 Retroactively tracked resource: ${this.truncateUrl(t)}`),!0}return r}isResourceInContainer(e,t){if(!this.container)return!1;try{const r=new URL(e),n=r.pathname+r.search;if(t==="img"||t==="audio"||t==="video"){const i=this.container.querySelectorAll(`${t}[src]`);for(const o of i){const s=o;if(s.src&&(s.src===e||s.src.endsWith(n)))return!0}}if(t==="link"){const i=this.container.querySelectorAll("link[href]");for(const o of i){const s=o;if(s.href&&(s.href===e||s.href.endsWith(n)))return!0}}if(t==="source"){const i=this.container.querySelectorAll("source[src]");for(const o of i){const s=o;if(s.src&&(s.src===e||s.src.endsWith(n)))return!0}}}catch(r){this.isDebugEnabled()&&this.logger.debug(`Error checking if resource is in container: ${r}`)}return!1}setupErrorHandler(){this.container&&(this.errorHandler=e=>{const t=e.target;if(!this.isResourceElement(t))return;const r=t.tagName.toLowerCase(),n=this.getResourceSrc(t);if(!n)return;const i=this.getOriginalUrl(n),o=this.retryAttempts.get(i)||0,s=this.config.maxRetries-o,a=s>0,l=this.buildResourceErrorDiagnostics(t,{eventType:e.type,resourceUrl:n,originalUrl:i,currentRetries:o,remainingRetries:s,willRetry:a});if(this.isDebugEnabled()){const d=this.truncateUrl(n);(a?this.logger.warn.bind(this.logger):this.logger.error.bind(this.logger))(`${a?"⚠️":"❌"} PIE Resource Load Error
1006
+ Element: <${r}>
1007
+ URL: ${d}
1008
+ Current Attempts: ${o}
1009
+ Remaining Retries: ${s}/${this.config.maxRetries}
1010
+ Action: ${a?"Will retry with exponential backoff":"Max retries reached, giving up"}`,l)}else(a?this.logger.warn.bind(this.logger):this.logger.error.bind(this.logger))(`${a?"⚠️":"❌"} Resource error: ${r} failed to load ${n}`);this.trackInstrumentationEvent("pie-resource-load-error",l),this.trackInstrumentationError(new Error(`Resource load error: ${i}`),{resourceType:r,...l}),this.retryResourceLoad(t,i)},this.container.addEventListener("error",this.errorHandler,!0),this.logger.debug("Error handler attached to container"))}isResourceElement(e){if(!e||!(e instanceof HTMLElement))return!1;const t=e.tagName.toLowerCase();return["img","audio","video","link","source"].includes(t)}getResourceSrc(e){return e instanceof HTMLLinkElement?e.href:"src"in e&&e.src?e.src:null}handlePermanentFailure(e,t,r){if(this.clearPendingMediaCheck(e),this.clearRetryTracking(e),this.isDebugEnabled()){const n=this.truncateUrl(e);this.logger.error(`❌ PIE Resource Permanently Failed
1011
+ URL: ${n}
1012
+ Total Attempts: ${r+1} (initial + ${r} retries)
1013
+ Status: Giving up after ${this.config.maxRetries} retries
1014
+ ⚠️ This resource will not be available to the user`)}else this.logger.error(`❌ Failed to load resource after ${this.config.maxRetries} retries: ${e}`);this.dispatchEvent("pie-resource-load-error",{url:e,resourceType:t,retryCount:r,maxRetries:this.config.maxRetries,error:`Resource permanently failed after ${this.config.maxRetries} retries`}),this.trackInstrumentationError(new Error(`Resource permanently failed after ${this.config.maxRetries} retries: ${e}`),{resourceUrl:e,retryCount:r,resourceType:t})}logRetrySchedule(e,t,r,n){if(this.isDebugEnabled()){const i=this.truncateUrl(e),o=Math.min(this.config.initialRetryDelay*Math.pow(2,t+1),this.config.maxRetryDelay),s=n==="img"?"Cache-busting URL":n==="audio"||n==="video"?"element.load()":n==="link"?"Cache-busting URL":"URL update";this.logger.info(`🔄 PIE Resource Retry Scheduled
1015
+ URL: ${i}
1016
+ Attempt: ${t+1}/${this.config.maxRetries}
1017
+ ⏰ Wait Time: ${r}ms (exponential backoff)
1018
+ Next Retry Delay: ${o}ms (if this fails)
1019
+ Strategy: ${s}`)}else this.logger.info(`🔄 Retrying resource load (attempt ${t+1}/${this.config.maxRetries}) after ${r}ms: ${e}`)}performRetryLoadAttempt(e,t,r){try{if(e instanceof HTMLAudioElement||e instanceof HTMLVideoElement){const n=this.withRetryParams(t,r);if(e.src)e.src=n;else{const i=Array.from(e.querySelectorAll("source")).find(o=>typeof o.src=="string"&&this.getOriginalUrl(o.src)===t);i&&(i.src=n)}e.load(),this.isDebugEnabled()&&this.logger.debug(`✓ Triggered load() on <${e.tagName.toLowerCase()}> with cache-busting params`)}else if(e instanceof HTMLSourceElement){e.src=this.withRetryParams(t,r);const n=e.parentElement;(n instanceof HTMLAudioElement||n instanceof HTMLVideoElement)&&n.load(),this.isDebugEnabled()&&this.logger.debug(`✓ Updated <source> src with cache-busting params and reloaded parent media: retry=${r}`)}else e instanceof HTMLImageElement?(e.src=this.withRetryParams(t,r),this.isDebugEnabled()&&this.logger.debug(`✓ Updated <img> src with cache-busting params: retry=${r}, t=${Date.now()}`)):e instanceof HTMLLinkElement&&(e.href=this.withRetryParams(t,r),this.isDebugEnabled()&&this.logger.debug(`✓ Updated <link> href with cache-busting params: retry=${r}, t=${Date.now()}`))}catch(n){const i=this.buildResourceErrorDiagnostics(e,{eventType:"retry",resourceUrl:this.getResourceSrc(e)||t,originalUrl:t,currentRetries:r,remainingRetries:Math.max(0,this.config.maxRetries-r),willRetry:r<this.config.maxRetries});this.isDebugEnabled()?this.logger.error(`❌ Error during retry attempt for ${t}:`,n,i):this.logger.error(`Error during retry for ${t}:`,n),this.trackInstrumentationError(new Error(`Retry attempt error for resource: ${t}`),{...i})}}retryResourceLoad(e,t){if(this.getRetryTargets(t).add(e),!this.started)return;if(this.retryInFlight.has(t)){this.isDebugEnabled()&&this.logger.debug(`Retry already scheduled for ${this.truncateUrl(t)}; skipping duplicate error-triggered schedule`);return}const r=this.retryAttempts.get(t)||0;if(r>=this.config.maxRetries){this.handlePermanentFailure(t,e.tagName.toLowerCase(),r);return}const n=Math.min(this.config.initialRetryDelay*Math.pow(2,r),this.config.maxRetryDelay),i=r+1;this.retryInFlight.add(t),this.retryAttempts.set(t,i),this.logRetrySchedule(t,r,n,e.tagName.toLowerCase()),this.trackInstrumentationEvent("pie-resource-retry",{url:t,attempt:i,delay:n});const o=this.lifecycleVersion,s=setTimeout(()=>{if(this.pendingRetryTimers.delete(t),this.retryInFlight.delete(t),!this.isLifecycleActive(o))return;const a=this.getPrimaryRetryTarget(t);a&&(this.isDebugEnabled()&&this.logger.debug(`⏱️ Retry wait completed (${n}ms), attempting reload now...`),this.performRetryLoadAttempt(a,t,i))},n);this.pendingRetryTimers.set(t,s)}dispatchEvent(e,t){if(!this.container)return;const r=new CustomEvent(e,{detail:t,bubbles:!0,composed:!0});this.container.dispatchEvent(r)}getStats(){const e=[];return this.retryAttempts.forEach((t,r)=>{e.push({url:r,attempts:t})}),{activeRetries:this.retryAttempts.size,failedResources:e.sort((t,r)=>r.attempts-t.attempts)}}},TH=5e3;function EH(e,t,r,n="pie-player"){const i=Yi("use-resource-monitor",r);let o=er(null),s=er(!1),a=er(null),l=er(""),d=er(void 0);return zr(()=>{e(),t(),r(),Bn(()=>{const c=e(),u=t(),f=r(),p=u?.trackPageActions??!1,g=u?.maxResourceRetries??Mp.maxResourceRetries,v=u?.resourceRetryDelay??Mp.resourceRetryDelay,b=IR({player:{loaderConfig:u},component:n,debug:f}),w=JSON.stringify({trackPageActions:p,maxRetries:g,retryDelay:v,debugEnabled:f}),I=A(d)!==b,x=A(a)!==c,C=A(l)!==w,L=c&&A(s)&&(x||C||I);if(!c&&A(o)){i.debug(`Host element removed, stopping resource monitor for ${n}`),A(o).stop(),Fe(o,null),Fe(s,!1),Fe(a,null),Fe(d,void 0),Fe(l,"");return}L&&A(o)&&(i.debug(`Reinitializing resource monitor for ${n}`,{hostChanged:x,configChanged:C,providerChanged:I}),A(o).stop(),Fe(o,null),Fe(s,!1)),c&&!A(s)&&(i.debug(`Initializing resource monitor for ${n}`,{trackPageActions:p,maxRetries:g,retryDelay:v,provider:b?.providerId,hasContainer:!!c}),Fe(o,new kH({trackPageActions:p,instrumentationProvider:b,maxRetries:g,initialRetryDelay:v,maxRetryDelay:TH,debug:f}),!0),A(o).start(c),Fe(s,!0),Fe(a,c,!0),Fe(d,b,!0),Fe(l,w,!0),i.info(`✅ Resource monitoring enabled for ${n}`+(p&&b?` (tracking via ${b.providerName})`:" (retry only)")))})}),Xb(()=>{if(A(o)){const c=A(o).getStats();i.debug(`Resource monitor stats at cleanup for ${n}:`,c),A(o).stop(),Fe(o,null),Fe(s,!1),Fe(a,null),Fe(d,void 0),Fe(l,"")}}),{get instance(){return A(o)},getStats(){return A(o)?.getStats()??{activeRetries:0,failedResources:[]}},get isActive(){return A(s)&&A(o)!==null}}}function Ru(e){return e?e.trim().replace(/_/g,"-").split(/[.@]/)[0].toLowerCase():""}function CH(e){const t=Ru(e);if(!t)return[];const r=t.split("-"),n=[];for(let i=r.length;i>0;i--){const o=r.slice(0,i);o.length>1&&o[o.length-1].length===1||n.push(o.join("-"))}return n}function xH(e,t){for(const r of CH(e)){const n=t.find(i=>Ru(i)===r);if(n!=null)return n}}var RH={common:{close:"Close",cancel:"Cancel",save:"Save",reset:"Reset",retry:"Retry",back:"Back",next:"Next",previous:"Previous",submit:"Submit",continue:"Continue",finish:"Finish",yes:"Yes",no:"No",ok:"OK",any:"Any",off:"Off",auto:"Auto",all:"All",none:"None",loading:"Loading…",error:"Error",settings:"Settings",language:"Language",theme:"Theme",preview:"Preview",author:"Author",unknown:"Unknown",untitled:"Untitled",apply:"Apply",enabled:"Enabled",disabled:"Disabled",closeA11y:"Close",settingsA11y:"Open settings menu"},player:{passage:"Passage",passages:"Passages",question:"Question",questionNumbered:"Question {position}",questions:"Questions",items:"Items",section:"Section",loadingSection:"Loading section content…",sectionLoadError:"Section content could not be loaded.",loadingPassage:"Loading passage content…",configurationError:"Configuration Error",playerError:"Player Error",authoringBackendError:"Authoring Backend Configuration Error",itemLoadError:"Question could not be loaded.",sectionTabsA11y:"Section content tabs",passagesRegionA11y:"Passages",itemsRegionA11y:"Items",sectionToolsA11y:"Section tools",scrollDownA11y:"Scroll down",resizePanels:"Resize panels",resizePassagesAndItemsA11y:"Resize passages and items panels",resizeMediaRegion:"Resize media region",resizeQuestionAndMediaA11y:"Resize question and media panels",resizePassageAndMediaA11y:"Resize passage and media panels",assessment:{sectionPosition:"Section {position} of {total}",noSections:"No sections",loadFailed:"The assessment could not be loaded. Try again.",restoreFailed:"Your saved answers for this section could not be restored. Try again."},formative:{checkAnswer:"Check answer",tryAgain:"Try again",answerRecorded:"Answer recorded.",correct:"Correct.",partlyCorrect:"Partly correct.",notCorrect:"Not correct.",notAutoScored:"Answer recorded. This question is not scored automatically.",checkFailed:"This question could not be checked. Try again.",triesLeft:{one:"{count} try left.",other:"{count} tries left."}},timedMedia:{waitingForMedia:"Questions will appear as the media plays.",questionAvailable:"Question {position} is now available.",playbackPaused:"Playback paused. Answer question {position} to continue.",playbackAdvisory:"Answer question {position} before continuing with the media.",playbackReleased:"Answer accepted. Continue playing the media."}},toolkit:{toolsA11y:"Assessment tools",toolbarInitError:"Unable to initialize assessment toolkit.",settingsTitle:"Settings",closeSettingsA11y:"Close settings",dragPanelA11y:"Drag panel",closePanelA11y:"Close panel",resizeWindow:"Resize window",minimize:"Minimize",maximize:"Maximize",minimizePanelA11y:"Minimize panel",maximizePanelA11y:"Maximize panel",window:{moveLeftA11y:"Move tool left",moveRightA11y:"Move tool right",moveUpA11y:"Move tool up",moveDownA11y:"Move tool down",shrinkA11y:"Shrink tool window",growA11y:"Grow tool window",centerA11y:"Center tool window",closeA11y:"Close tool"},placement:{controlsA11y:"Move and rotate",rotateClockwiseA11y:"Rotate {degrees}° clockwise",rotateCounterclockwiseA11y:"Rotate {degrees}° counterclockwise"},announce:{movedUp:"Moved up to {position}",movedDown:"Moved down to {position}",movedLeft:"Moved left to {position}",movedRight:"Moved right to {position}",rotatedTo:"Rotated to {degrees} degrees"}},tools:{calculator:{name:"Calculator",nameBasic:"Basic Calculator",nameScientific:"Scientific Calculator",nameGraphing:"Graphing Calculator",description:"Multi-type calculator (basic, scientific, graphing)",openedBasic:"Basic calculator opened",openedScientific:"Scientific calculator opened",openedGraphing:"Graphing calculator opened",closedBasic:"Basic calculator closed",closedScientific:"Scientific calculator closed",closedGraphing:"Graphing calculator closed",toolA11y:"Calculator tool",loading:"Loading calculator…",providerUnavailable:"The calculator is unavailable."},graph:{name:"Graph",description:"Coordinate plane",buttonA11y:"Graph, coordinate plane",tooltip:"Graph",toolA11y:"Graph tool — draw points and lines on a coordinate grid",canvasA11y:"Graph canvas — use tools to add points and draw lines",grid:"Grid:",gridOpacityA11y:"Grid opacity",pointA11y:"Graph point {id}",modeSelector:"Selector",modeSelectorHint:"Selector: click and drag points to move them or associated lines.",modePoint:"Point",modePointHint:"Point: click on the grid to add points.",modeLine:"Line",modeLineHint:"Line: click a starting point, then an ending point to draw a line.",modeDelete:"Delete",modeDeleteHint:"Delete: click on a point to delete it and any connected lines."},periodicTable:{name:"Periodic Table",description:"Chemistry periodic table reference",buttonA11y:"Periodic Table, chemistry reference",tooltip:"Periodic Table",toolA11y:"Periodic table — select an element to view its details",elementsA11y:"Periodic table elements",showAllA11y:"Show all elements",allElements:"All Elements",atomicMass:"Atomic Mass",atomicNumber:"Atomic No",electronConfig:"Electron Config",phase:"Phase",filterByA11y:"Filter by {category}",elementA11y:"{name}, Symbol: {symbol}, Atomic number: {number}, Atomic mass: {mass}, Category: {category}",outsideFilterA11y:", outside the current filter",category:{unknown:"Unknown",alkaliMetal:"Alkali Metal",alkalineEarthMetal:"Alkaline Earth Metal",transitionMetal:"Transition Metal",postTransitionMetal:"Post-transition Metal",metalloid:"Metalloid",diatomicNonmetal:"Diatomic Nonmetal",polyatomicNonmetal:"Polyatomic Nonmetal",nobleGas:"Noble Gas",lanthanide:"Lanthanide",actinide:"Actinide"}},ruler:{name:"Ruler",description:"On-screen ruler for measurements",buttonA11y:"Ruler",tooltip:"Ruler",toolA11y:"Draggable and rotatable ruler measurement tool",unitSelectionA11y:"Ruler unit selection",inches:"Inches",centimeters:"Centimeters",inchesInSentence:"inches",centimetersInSentence:"centimeters",switchToInchesA11y:"Switch to inches",switchToCentimetersA11y:"Switch to centimeters",switchedTo:"Switched to {unit}",applicationA11y:"Ruler tool. Use arrow keys to move, Shift+arrows to rotate, PageUp or PageDown for fine rotation, U to toggle units. Current unit: {unit}",imageAlt:"Ruler showing {unit}"},protractor:{name:"Protractor",description:"On-screen protractor for angle measurements",buttonA11y:"Protractor",tooltip:"Protractor",toolA11y:"Protractor tool. Use arrow keys to move, Shift+arrows to rotate, and PageUp or PageDown for fine rotation.",roleA11y:"Draggable and rotatable protractor measurement tool",imageAlt:"Protractor with 180-degree semicircular scale marked from 0 to 180 degrees in both directions, with degree markings every 10 degrees"},dictionary:{name:"Dictionary",description:"Look up word definitions",buttonA11y:"Dictionary, look up word definitions",tooltip:"Dictionary",toolA11y:"Dictionary"},pictureDictionary:{name:"Picture Dictionary",description:"Look up pictures for words",buttonA11y:"Picture Dictionary, look up pictures for words",tooltip:"Picture Dictionary",toolA11y:"Picture Dictionary"},dictionarySpanish:{name:"Spanish Dictionary",description:"Look up word definitions in Spanish",buttonA11y:"Spanish Dictionary, look up word definitions in Spanish",tooltip:"Spanish Dictionary",toolA11y:"Spanish Dictionary"},pictureDictionarySpanish:{name:"Spanish Picture Dictionary",description:"Look up pictures for words in Spanish",buttonA11y:"Spanish Picture Dictionary, look up pictures for words in Spanish",tooltip:"Spanish Picture Dictionary",toolA11y:"Spanish Picture Dictionary"},lineReader:{name:"Line Reader",description:"Reading guide overlay",buttonA11y:"Line Reader, reading guide",tooltip:"Line Reader",roleA11y:"Draggable and resizable reading guide overlay",close:"Close line reader",resizeWindowA11y:"Drag to resize the reading window",resizeFrameA11y:"Drag to resize the frame and window width",windowHeightAnnounce:"Reading window height {pixels} pixels",frameHeightAnnounce:"Frame height {pixels} pixels",widthAnnounce:"Width {pixels} pixels",applicationA11y:"Line Reader tool. A clear reading window inside an obscuring frame. Use arrow keys to move, +/- to resize the reading window, Escape to close. Reading window height: {paneHeight} pixels, Frame height: {frameHeight} pixels",resizeWindowFullA11y:"Resize the reading window. Drag, or use the up and down arrow keys to change its height. Current height {paneHeight} pixels",resizeFrameFullA11y:"Resize the frame. Drag, or use the up and down arrow keys to change the frame height and the left and right arrow keys to change the width. Current frame height {frameHeight} pixels, width {width} pixels"},answerEliminator:{name:"Answer Eliminator",description:"Strike through answer choices",buttonA11y:"Strike Through, eliminate answer choices",tooltip:"Strike Through"},highlighter:{name:"Highlighter",description:"Highlight and annotate text",buttonA11y:"Highlight text",tooltip:"Highlight"},annotationToolbar:{name:"Annotation",description:"Highlight and annotate text",buttonA11y:"Annotate, highlight and mark up text",tooltip:"Annotate",toolbarA11y:"Text annotation toolbar",underline:"Underline",underlineA11y:"Underline selected text",readAloud:"Read Aloud",readAloudA11y:"Read selected text aloud",remove:"Remove",removeA11y:"Remove this annotation",clearAll:"Clear All",clearAllA11y:"Clear all annotations from document",highlightYellowA11y:"Yellow highlight",highlightPinkA11y:"Pink highlight",highlightBlueA11y:"Blue highlight",highlightGreenA11y:"Green highlight"},theme:{name:"Theme",description:"Accessible themes and contrast",buttonA11y:"Theme, change colors and contrast",tooltip:"Theme",selectorA11y:"Theme selector",hint:"Select a theme to improve readability and reduce eye strain.",selectA11y:"Select theme",selectCurrentA11y:"Select theme. Current theme: {name}",optionUnavailableA11y:"{name}, unavailable",unavailableName:"Unavailable theme: {id}",unavailableDescription:"PIE's managed base theme remains active until this theme becomes available again.",unavailableStatus:"The selected theme is unavailable. PIE's managed base theme is active until it becomes available again."},textToSpeech:{name:"Text to Speech",description:"Read content aloud",toolA11y:"Text-to-speech tool",title:"Text-to-Speech",initializing:"Initializing…",initFailed:"Failed to initialize text-to-speech.",selectText:"Select text on the page to read it aloud.",speed:"Speed:",play:"Play",pause:"Pause",resume:"Resume",stop:"Stop",speaking:"Speaking…",paused:"Paused",charactersSelected:{one:"{count} character selected",other:"{count} characters selected"},rate:{slow:"Slow",slower:"Slower",normal:"Normal",faster:"Faster",fast:"Fast",veryFast:"Very Fast"},inline:{controlsA11y:"Reading controls",playbackSpeedA11y:"Playback speed",rewindA11y:"Rewind",fastForwardA11y:"Fast-forward",stopA11y:"Stop reading",initializing:"Initializing text-to-speech",initFailed:"Unable to initialize text-to-speech. Try again.",starting:"Starting reading",started:"Reading started",resumed:"Reading resumed",pausedAnnouncement:"Reading paused",stopped:"Reading stopped",switchedSection:"Reading switched to another section",startFailed:"Unable to start reading",skippedForward:"Skipped forward",skipForwardFailed:"Unable to skip forward",skippedBackward:"Skipped backward",skipBackwardFailed:"Unable to skip backward",speedChangeFailed:"Unable to change playback speed",speedAnnounce:"Playback speed {label}",playA11y:"Play reading",pauseA11y:"Pause reading",resumeA11y:"Resume reading"}},signLanguage:{name:"Sign Language",description:"Signed alternate for authored content",generic:"Sign language",unknown:"Sign language ({code})",ase:"American Sign Language",bfi:"British Sign Language",fsl:"French Sign Language",gss:"Greek Sign Language",mfs:"Mexican Sign Language",signedEnglish:"Signed English",regionA11y:"{language} translation"},audioTranscript:{name:"Audio Transcript",description:"Text transcript of audio content",regionA11y:"Transcript"}},debug:{session:"Session",sessionData:"Session Data",sessionDataPersistent:"PIE Session Data (Persistent)",noItemSessionYet:"No item session data yet. Interact with the item to see updates here.",itemSessionsSnapshot:"Item Sessions Snapshot",sectionControllerUnavailable:"Section controller not available for this section yet.",filteredModel:"Filtered Model",environment:"Environment",events:"Events",controllerEvents:"Controller Events",instrumentation:"Instrumentation",databaseState:"Database state",sessionDb:"Session DB (Server)",noRows:"No rows",noRecords:"No instrumentation records yet.",selectRecord:"Select a record to inspect details.",selectEvent:"Select an event to inspect payload details.",showRawTables:"Show raw tables",showReconstructedSnapshots:"Show reconstructed snapshots",showSectionRequest:"Show section request",showAssessmentRequest:"Show assessment request",liveUpdatesUnsupported:"Live updates are not supported in this browser",liveUpdatesDisconnected:"Live updates disconnected; retrying…",fieldType:"Type:",fieldTarget:"Target:",fieldItem:"Item:",fieldCanonical:"Canonical:",fieldIntent:"Intent:",fieldDuplicates:"Duplicates:",fieldSemanticRepeats:"Semantic Repeats:",dragItemSessionPanelA11y:"Drag item session panel",debuggerTabsA11y:"Debugger tabs",sessionDataJsonA11y:"Session data JSON",environmentJsonA11y:"Environment JSON",filteredModelJsonA11y:"Filtered model JSON",sectionSessionJsonA11y:"Section session snapshot JSON",eventLevelFilterA11y:"Event level filter",controllerEventDetailsA11y:"Controller event details",instrumentationFilterA11y:"Filter instrumentation record type",instrumentationDetailsA11y:"Instrumentation record details",toggleSessionPanelA11y:"Toggle session panel",toggleEventPanelA11y:"Toggle event broadcast panel",toggleDatabasePanelA11y:"Toggle database state panel",toggleInstrumentationPanelA11y:"Toggle instrumentation panel",pnp:{title:"PNP Profile",noAssessmentBound:"No assessment bound",determinationReadOnly:"Determination (read-only)",toolsEditor:"Tools Editor",enforcement:"PNP enforcement",allAvailableTools:"All available tools",clearPlacement:"Clear placement",tool:"Tool",placement:"Placement",provider:"Provider",simulation:"PNP simulation",resolvedTools:"Resolved Tools (toolkit)",provenanceSummary:"Tool Policy Provenance Summary",perToolDecisions:"Per-Tool Decisions",profileReadOnly:"PNP Profile (read-only)"},tts:{title:"TTS settings",closeA11y:"Close TTS settings",toolbarLayoutMode:"Toolbar layout mode",reservedRow:"Reserved row",expandingRow:"Expanding row",floatingOverlay:"Floating overlay",leftAlignedControls:"Left-aligned controls",inlineSpeedButtons:"Inline speed buttons",resetToDefaults:"Reset to defaults",mathHighlighting:"Math highlighting",checkingAvailability:"Checking availability…",recheck:"Recheck",voice:"Voice",bestAvailableVoice:"Best available voice (auto)",unnamedVoice:"Unnamed voice",apiEndpoint:"API endpoint",gender:"Gender",any:"Any",male:"Male",female:"Female",neutral:"Neutral",engine:"Engine",neural:"Neural",standard:"Standard",providerDefault:"Provider default",format:"Format",sampleRate:"Sample rate",speechMarks:"Speech marks",word:"Word",wordAndSentence:"Word + sentence",voiceType:"Voice type",wavenetVoiceType:"WaveNet",studioVoiceType:"Studio",plainText:"Plain text",sampleText:"Sample text",resetSample:"Reset sample",providerAvailable:"Provider available.",providerUnavailable:"Provider unavailable.",providerCheckFailed:"Provider availability check failed.",providerNotChecked:"Provider availability has not been checked yet.",webSpeechUnavailable:"Web Speech API is not available in this browser.",browserNoVoices:"Browser text-to-speech is available, but no voices were returned yet.",browserUnavailable:"Browser text-to-speech is not available.",googleUnavailable:"Google Cloud TTS is not available from the configured API.",pollyUnavailable:"AWS Polly is not available from the configured API.",recommendedVoices:"Recommended voices",allVoices:"All available voices",previewVoice:"Preview voice",stopPreview:"Stop preview",applying:"Applying…",ssmlPreviewUnsupported:"SSML preview is not supported in the Browser backend.",pollySsmlHint:"Some Polly neural voices reject certain SSML tags (for example emphasis). Use basic SSML tags if preview fails.",mathHighlightParts:"Highlighting each part of a formula as it is read, falling back to the whole formula when alignment is uncertain.",mathHighlightBlock:"Highlighting each formula as a single block instead of breaking it into parts.",previewFailed:"Failed to play preview audio.",previewNoAudio:"Preview response did not include audio content.",previewEnterText:"Enter preview text before starting playback.",previewUnavailable:"Cannot preview while this service is unavailable.",browserSynthesisUnavailable:"Browser speech synthesis is unavailable.",browserSynthesisEndedEarly:"Browser speech synthesis ended before audio started. Restart the browser and try again.",browserSynthesisQueueFailed:"Browser speech synthesis failed to queue preview audio.",browserPreviewFailed:"Failed to play browser voice preview.",ssmlWordTrackingDisabled:"Google SSML preview preserves authored SSML, so word tracking is disabled.",applyUnavailable:"Cannot apply settings while this service is unavailable.",coordinatorUnavailable:"Toolkit coordinator is not available for text-to-speech updates."}}},Mg="en-US",_H=new Set(["ar","ckb","dv","fa","he","iw","ks","ku","nqo","ps","sd","syr","ug","ur","yi"]),PH=new Set(["zero","one","two","few","many","other"]);function K1(e){if(typeof e!="object"||e===null)return!1;const t=Object.keys(e);return t.length>0&&t.every(r=>PH.has(r))}function X1(e){try{const r=new Intl.Locale(e).textInfo;if(r?.direction==="rtl"||r?.direction==="ltr")return r.direction}catch{}const t=Ru(e).split("-")[0]??"";return _H.has(t)?"rtl":"ltr"}var RR=class xh{constructor(t={}){Te(this,"locale",void 0),Te(this,"fallbackLocale",void 0),Te(this,"catalogs",void 0),Te(this,"customMessages",void 0),Te(this,"loading",void 0),Te(this,"listeners",new Set),Te(this,"config",void 0),this.config={...t},this.fallbackLocale=oh(t.fallbackLocale)||"en-US",this.catalogs=new Map([[Mg,RH]]),this.customMessages={...t.customMessages??{}},this.loading=new Map,this.locale=this.resolveLocaleTag(t.locale)??"en-US"}async initialize(t){if(this.config={...this.config,...t},t.customMessages)for(const[r,n]of Object.entries(t.customMessages))this.addCustomMessages(r,n);await this.setLocale(t.locale??this.locale)}getLocale(){return this.locale}async setLocale(t){const r=this.resolveLocaleTag(t);if(!r){this.locale=oh(t)||"en-US",this.notify();return}if(!this.catalogs.has(r)){const n=this.loading.get(r);if(n)await n;else{const i=this.loadCatalog(r);this.loading.set(r,i);try{await i}finally{this.loading.delete(r)}}}this.locale=r,this.notify()}t(t,r){const n=this.lookup(t);return n===void 0?(this.config.onMissingKey?.(t,this.locale),t):Z1(n,r)}plural(t,r){const n=this.lookupNode(t);return n===void 0||!K1(n)?this.t(t,r):Z1(n[this.selectPluralCategory(r.count)]??n.other,r)}getDirection(){return X1(this.locale)}getAvailableLocales(){return[...new Set([...this.catalogs.keys(),...this.config.availableLocales??[],...Object.keys(this.customMessages)])]}isLocaleLoaded(t){const r=this.resolveLocaleTag(t);return r!==void 0&&this.catalogs.has(r)}subscribe(t){return this.listeners.add(t),()=>{this.listeners.delete(t)}}hasKey(t){return this.lookup(t)!==void 0}addCustomMessages(t,r){const n=oh(t);this.customMessages[n]=_R(this.customMessages[n]??{},r),this.notify()}withLocale(t){const r=this.resolveLocaleTag(t)??oh(t);if(r===this.locale)return this;const n=new xh({...this.config,locale:r});return n.locale=r||"en-US",n.catalogs=this.catalogs,n.customMessages=this.customMessages,n.loading=this.loading,n}formatNumber(t,r){try{return new Intl.NumberFormat(this.locale,r).format(t)}catch{return new Intl.NumberFormat(Mg,r).format(t)}}formatDate(t,r){try{return new Intl.DateTimeFormat(this.locale,r).format(t)}catch{return new Intl.DateTimeFormat(Mg,r).format(t)}}getBundle(t=this.locale){const r=this.resolveLocaleTag(t);if(!r)return;const n=this.catalogs.get(r);if(n)return{locale:r,translations:n,direction:X1(r)}}resolveLocaleTag(t){if(!t)return;const r=this.getAvailableLocales(),n=xH(t,r);if(n)return n;const i=Ru(t).split("-")[0];if(i)return r.find(o=>Ru(o).split("-")[0]===i)}async loadCatalog(t){const r=this.config.loadCatalog;if(r)try{this.catalogs.set(t,await r(t))}catch(n){throw new Error(`Failed to load i18n catalog for locale: ${t}`,{cause:n})}}lookupNode(t){const r=[this.customMessages[this.locale],this.catalogs.get(this.locale),this.customMessages[this.fallbackLocale],this.catalogs.get(this.fallbackLocale)];for(const n of r){const i=AH(n,t);if(i!==void 0)return i}}lookup(t){const r=this.lookupNode(t);if(typeof r=="string")return r;if(r!==void 0&&K1(r))return r.other}selectPluralCategory(t){let r=xh.pluralRules.get(this.locale);if(!r){try{r=new Intl.PluralRules(this.locale)}catch{return t===1?"one":"other"}xh.pluralRules.set(this.locale,r)}return r.select(t)}notify(){for(const t of this.listeners)t()}};Te(RR,"pluralRules",new Map);function oh(e){return e?e.trim().replace(/_/g,"-"):""}function AH(e,t){if(!e)return;let r=e;for(const n of t.split("."))if(typeof r!="object"||r===null||(r=r[n],r===void 0))return;return r}function Z1(e,t){return t?e.replace(/\{(\w+)\}/g,(r,n)=>{const i=t[n];return i==null?r:String(i)}):e}function _R(e,t){const r={...e};for(const[n,i]of Object.entries(t)){const o=r[n];i&&typeof i=="object"&&o&&typeof o=="object"?r[n]=_R(o,i):r[n]=i}return r}var $g;function MH(){return $g||($g=new RR),$g}function $H(e){const t=e?.i18n??MH();return{getLocale:()=>t.getLocale(),setLocale:r=>t.setLocale(r),t:(r,n)=>t.t(r,n),plural:(r,n)=>t.plural?.(r,n)??t.t(r,n),getDirection:()=>t.getDirection?.()??"ltr",hasKey:r=>t.hasKey?.(r)??!1,subscribe:r=>t.subscribe?.(r)??(()=>{})}}var Y1=ea(`<div class="pie-player-error svelte-udi90b" style="
1020
+ padding: 20px;
1021
+ margin: 20px 0;
1022
+ border-radius: 4px;
1023
+ font-family: sans-serif;
1024
+ "><h3 style="margin: 0 0 10px 0"> </h3> <p style="margin: 0"> </p></div>`),J1=ea("<div></div>"),LH=ea("<div><!> <!> <!></div>"),OH={hash:"svelte-udi90b",code:`.pie-item-player.svelte-udi90b {display:block;width:100%;}.pie-passage-container.svelte-udi90b,
1025
+ .pie-item-container.svelte-udi90b {display:block;width:100%;}.pie-item-player--resize-allowed.svelte-udi90b .pie-passage-container:where(.svelte-udi90b) {max-width:100%;overflow:auto;resize:horizontal;}
1026
+
1027
+ /*
1028
+ * The error banner carries a fixed red encoding, so it behaves like any other
1029
+ * fixed hue: exact at 0% collapse, which is every Base Theme, folded into the
1030
+ * palette at 100%, which is every scheme. Pinned, a learner on White on Black
1031
+ * or Yellow on Navy got a pale pink box in the middle of the palette they
1032
+ * chose.
1033
+ *
1034
+ * The collapsed ink is \`--pie-text\`, not \`--pie-incorrect\`: that pairs with
1035
+ * this tint at 4.14:1 under Black on White, where the page's own ink holds at
1036
+ * 6.18:1 or better on every scheme, now a declared relationship. The tint
1037
+ * itself sits about 1.1:1 from the page, so the \`--pie-incorrect\` edge is what
1038
+ * makes this read as a banner at all -- the same division of labour the
1039
+ * periodic table's collapsed cells use, and that edge clears 4.53:1 against
1040
+ * every scheme's page.
1041
+ */.pie-player-error.svelte-udi90b {border:2px solid
1042
+ color-mix(
1043
+ in srgb,
1044
+ var(--pie-incorrect, #d32f2f) var(--pie-fixed-hue-collapse, 0%),
1045
+ #d32f2f
1046
+ );background-color:color-mix(
1047
+ in srgb,
1048
+ var(--pie-incorrect-secondary, #ffebee) var(--pie-fixed-hue-collapse, 0%),
1049
+ #ffebee
1050
+ );color:color-mix(
1051
+ in srgb,
1052
+ var(--pie-text, #c62828) var(--pie-fixed-hue-collapse, 0%),
1053
+ #c62828
1054
+ );}`};function PR(e,t){mm(t,!0),Zb(e,OH);const r=Yi("pie-item-player",()=>Ci());let n=Ye(t,"itemConfig",7),i=Ye(t,"passageConfig",7,null),o=Ye(t,"env",23,()=>({mode:"gather",role:"student"})),s=Ye(t,"session",23,()=>[]),a=Ye(t,"addCorrectResponse",7,!1),l=Ye(t,"onCorrectResponsesPopulated",7),d=Ye(t,"allowedResize",7,!1),c=Ye(t,"customClassName",7,""),u=Ye(t,"passageContainerClass",7,""),f=Ye(t,"containerClass",7,""),p=Ye(t,"bundleType",23,()=>Gl.player),g=Ye(t,"loaderConfig",7,Mp),v=Ye(t,"mode",7,"view"),b=Ye(t,"configuration",23,()=>({})),w=Ye(t,"authoringBackend",7,"demo"),I=Ye(t,"trustMarkup",7,!1),x=Ye(t,"sanitizeMarkup",7),C=Ye(t,"onInsertImage",7),L=Ye(t,"onDeleteImage",7),E=Ye(t,"onInsertSound",7),M=Ye(t,"onDeleteSound",7),U=Ye(t,"onLoadComplete",7),te=Ye(t,"onPlayerError",7),re=Ye(t,"onSessionChanged",7),Pe=Ye(t,"onModelUpdated",7),z=Ye(t,"onModelLoaded",7),K=Ye(t,"onElementSessionUpdate",7),oe=Ye(t,"baseHeadingLevel",7,void 0),ue=Ye(t,"includeSrHeading",7,!0),ae=Ye(t,"i18n",7);const X=Et(()=>$H({i18n:ae()}));let j=er(!1),D=er(null),Z=er(null),F=er(null),W=er(null);const O=Et(()=>{const V=n()?.elements??{};return x1(Object.keys(V))}),$=Et(()=>{const V=i()?.elements??{};return x1(Object.keys(V))});function ie(V,ke){return V?I()?V:x()?x()(V):hF({allowedCustomElements:ke})(V):""}const N=Et(()=>n()?.markup?ie(v()==="author"&&n().elements?M1(n().markup,n().elements):n().markup,A(O)):""),ne=Et(()=>i()?.markup?ie(v()==="author"&&i().elements?M1(i().markup,i().elements):i().markup,A($)):"");function ge(V,ke="ITEM_PLAYER_RUNTIME_ERROR"){if(V&&typeof V=="object"){const qe=V,Ve=typeof qe.message=="string"&&qe.message.trim().length>0?qe.message:"Unknown PIE runtime error",at=typeof qe.code=="string"&&qe.code.trim().length>0?qe.code:ke,Rt=qe.recoverable===!0;return{...qe,message:Ve,code:at,recoverable:Rt}}return{code:ke,message:typeof V=="string"&&V.trim().length>0?V:"Unknown PIE runtime error",recoverable:!1}}function Oe(V){const ke=IR({player:{loaderConfig:g()},component:"pie-item-player",debug:Ci()});!tw(ke)||!ke.isReady()||ke.trackError(new Error(V.message),{component:"pie-item-player",errorType:V.code,...V})}function We(V,ke="ITEM_PLAYER_RUNTIME_ERROR"){const qe=ge(V,ke);Fe(W,qe.message,!0),r.error("[PieItemPlayer] Runtime error:",qe),Oe(qe),Ne("player-error",qe)}const Ne=(V,ke)=>{V==="load-complete"&&typeof U()=="function"?U()(ke):V==="player-error"&&typeof te()=="function"?te()(ke):V==="session-changed"&&typeof re()=="function"?re()(ke):V==="model-updated"&&typeof Pe()=="function"?Pe()(ke):V==="model-loaded"&&typeof z()=="function"&&z()(ke)},xe=["onInsertImage","onDeleteImage","onInsertSound","onDeleteSound"];function et(V){A(F)!==V&&(Fe(F,V,!0),We({code:"AUTHORING_BACKEND_CONFIG_ERROR",message:V}))}function Ue(){if(w()==="required"){const V=[];if(C()||V.push("onInsertImage"),L()||V.push("onDeleteImage"),E()||V.push("onInsertSound"),M()||V.push("onDeleteSound"),V.length>0){const ke=`Authoring backend is required but missing handlers: ${V.join(", ")}. Provide all ${xe.join(", ")} callbacks.`;return Fe(Z,ke),et(ke),null}return{onInsertImage:C(),onDeleteImage:L(),onInsertSound:E(),onDeleteSound:M()}}return C()||L()||E()||M()?{onInsertImage:C(),onDeleteImage:L(),onInsertSound:E(),onDeleteSound:M()}:(r.warn("[PieItemPlayer] Authoring backend mode is 'demo'. Using non-production media handlers."),{onInsertImage:gF(V=>{r.debug("[PieItemPlayer] Demo image insert completed:",V)}),onDeleteImage:yF(),onInsertSound:vF(V=>{r.debug("[PieItemPlayer] Demo sound insert completed:",V)}),onDeleteSound:bF()})}async function Se(){if(v()!=="author"||!n())return{hasErrors:!1,validatedModels:[]};const V=await Promise.all([A1(n(),b(),{container:A(Y)??void 0}),i()?A1(i(),b(),{container:A(Y)??void 0}):Promise.resolve({hasErrors:!1,validatedModels:[]})]);return{hasErrors:V.some(ke=>ke.hasErrors),validatedModels:V.flatMap(ke=>ke.validatedModels)}}async function Re(V=!1){if(!a()||!n()||A(j)&&!V)return;if(!NF(o())){r.debug("[PieItemPlayer] Skipping populateCorrectResponses - env not suitable (mode=%s)",o().mode);return}const ke=DF(o()),qe=[];for(const Ve of n().models){const at=wm(Ve.element,p());if(r.debug("[PieItemPlayer] Controller lookup for %s: %s (createCorrectResponseSession=%s)",Ve.element,at?"FOUND":"NOT FOUND",at?"YES":"NO"),at&&at.createCorrectResponseSession)try{const Rt=await at.createCorrectResponseSession(Ve,ke);if(!Rt){r.debug("[PieItemPlayer] createCorrectResponseSession returned null for %s (env=%j)",Ve.element,ke);continue}const{id:Rr,...Vr}=Rt;qe.push({id:Ve.id,element:Ve.element,...Vr})}catch(Rt){r.warn("[PieItemPlayer] Failed to create correct response for %s",Ve.element,Rt)}}if(s().length=0,s().push(...qe),qe.length>0){Fe(j,!0);try{hc(n(),s(),o(),A(Y)??void 0,K(),p()),i()&&hc(i(),s(),o(),A(Y)??void 0,K(),p())}catch(Ve){r.warn("[PieItemPlayer] Failed to update PIE elements after populating correct responses",Ve)}r.debug("[PieItemPlayer] Correct responses added to session:",s());for(const Ve of qe)Ne("session-changed",{component:Ve.element,complete:!0,elementId:Ve.id,session:{id:"",data:s()}});l()?.({itemId:n().id,mode:o()?.mode,role:o()?.role,bundleType:p(),populatedCount:qe.length,elements:qe.map(Ve=>String(Ve.element??""))})}else r.debug("[PieItemPlayer] No correct responses returned (likely wrong env). Will retry if env/addCorrectResponse changes.")}const mt=Et(()=>["pie-passage-container",c(),u()].filter(Boolean).join(" ")),$t=Et(()=>["pie-item-container",c(),f()].filter(Boolean).join(" ")),ve=Et(()=>["pie-item-player",d()?"pie-item-player--resize-allowed":""].filter(Boolean).join(" "));let me=er(!1);function Je(V){if(!V||typeof V!="object"||Array.isArray(V))return;const ke=V;if(Array.isArray(ke.data))return;const qe=typeof ke.id=="string"?ke.id:"";if(!qe)return;const Ve=s().find(at=>at&&typeof at=="object"&&at.id===qe);if(Ve!==ke){if(Ve){Object.assign(Ve,ke);return}s().push({...ke})}}function Gt(V){const ke=V,qe=typeof ke?.id=="string"?ke.id:"";return qe&&[n(),i()].some(Ve=>Ve?.models?.some(at=>at?.id===qe))?qe:""}function le(V){try{return V?.session}catch{return}}function Ae(V){return s().find(ke=>ke&&typeof ke=="object"&&ke.id===V)}let Y=er(null),we=er(null),_e=er(null);const Be=new WeakSet,it=MF();function tt(V){!A(me)||Be.has(V)||(Be.add(V),r.debug("[PieItemPlayer] model-updated event received from configure element"),Ne("model-updated",V.detail))}function Bt(V){if(V.stopPropagation(),Be.has(V))return;Be.add(V);const ke=V;r.debug("[PieItemPlayer] session-changed event received from PIE element",ke.detail);const qe=V.target,Ve=Gt(qe),at=!!ke.detail?.sessionCommitReason;if(!A(me)&&!at&&Ve&&$F(le(qe),Ae(Ve)))return;Je(ke.detail?.session),A(me)&&Ve&&Je(le(qe)),yH(qe);const Rt=Ve?le(qe)??Ae(Ve):le(qe)??ke.detail?.session??s();it({element:qe,complete:ke.detail?.complete,session:Rt,commit:at})&&Ne("session-changed",{...ke.detail||{},...Ve?{elementId:Ve}:{},session:{id:"",data:s()}})}zr(()=>{if(!A(Y))return;const V=A(Y);return v()==="author"?(V.addEventListener("model.updated",tt,!0),()=>{V.removeEventListener("model.updated",tt,!0)}):(V.addEventListener("session-changed",Bt),()=>{V.removeEventListener("session-changed",Bt)})}),EH(()=>A(Y),()=>g(),()=>Ci(),"pie-item-player"),zr(()=>{!n()||A(me)||(r.debug("[PieItemPlayer] Item config received, initializing after DOM renders..."),r.debug("[PieItemPlayer] Mode:",v()),ou().then(async()=>{try{if(Fe(W,null),r.debug("[PieItemPlayer] DOM ready, initializing PIE elements"),r.debug("[PieItemPlayer] Config:",{itemElements:Object.keys(n().elements||{}),itemModels:(n().models||[]).length,passageElements:i()?Object.keys(i().elements||{}):[],passageModels:i()?(i().models||[]).length:0,sessionLength:s().length,addCorrectResponse:a(),env:o(),mode:v()}),v()==="author"){r.debug("[PieItemPlayer] Initializing in authoring mode"),Fe(Z,null);const V=Ue();if(A(Z)||!V){Fe(me,!1);return}const ke={...o(),mode:"author",configuration:b()},qe=$1(n(),b(),{env:ke,container:A(Y)??void 0});r.debug("[PieItemPlayer] Configure elements initialized"),i()&&(qe.push(...$1(i(),b(),{env:ke,container:A(Y)??void 0})),r.debug("[PieItemPlayer] Passage configure elements initialized")),Ne("model-loaded",{models:qe,configuration:b()}),A(Y)&&V&&(Fe(D,PF(A(Y),V,(Ve,at)=>{r.error(`[PieItemPlayer] ${Ve} failed:`,at)}),!0),A(D).attach(),r.debug("[PieItemPlayer] Asset event manager attached"))}else r.debug("[PieItemPlayer] Initializing in view mode"),F1(n(),[],{env:o(),bundleType:p(),container:A(Y)??void 0}),r.debug("[PieItemPlayer] Item bundle initialized (bundle type: %s)",p()),i()&&(F1(i(),[],{env:o(),bundleType:p(),container:A(Y)??void 0}),r.debug("[PieItemPlayer] Passage bundle initialized (bundle type: %s)",p())),r.debug("[PieItemPlayer] Updating elements with session (length="+s().length+")"),await hc(n(),s(),o(),A(Y)??void 0,K(),p()),i()&&await hc(i(),s(),o(),A(Y)??void 0,K(),p()),bH(A(Y)??void 0);Fe(me,!0),r.debug("[PieItemPlayer] Initialization complete, dispatching load-complete event"),Ne("load-complete")}catch(V){We({code:"ITEM_PLAYER_INITIALIZATION_ERROR",message:V instanceof Error?V.message:String(V),cause:V instanceof Error?V.stack||V.message:String(V)},"ITEM_PLAYER_INITIALIZATION_ERROR")}}))}),Xb(()=>{try{A(D)?.detach()}catch{}}),zr(()=>{A(me)&&(o(),a()&&!A(j)?Bn(async()=>{await Re()}):!a()&&A(j)&&Bn(()=>{s().length=0,Fe(j,!1)}))});let ht=!1,ot=!1;function $r(){if(A(Y)?.isConnected){if(ht){ot=!0;return}ht=!0,Bn(()=>{hc(n(),s(),o(),A(Y)??void 0,K(),p()).then(()=>i()?hc(i(),s(),o(),A(Y)??void 0,K(),p()):void 0).catch(V=>{We({code:"ITEM_PLAYER_UPDATE_ERROR",message:V instanceof Error?V.message:String(V),recoverable:!0,cause:V instanceof Error?V.stack||V.message:String(V)},"ITEM_PLAYER_UPDATE_ERROR")}).finally(()=>{ht=!1,ot&&(ot=!1,setTimeout(()=>{$r()},0))})})}}zr(()=>{!A(me)||!o()||!n()||!s()||(r.debug("[PieItemPlayer] Dependencies changed, updating elements"),r.debug("[PieItemPlayer] Env:",o()),r.debug("[PieItemPlayer] Session (length="+s().length+"):",s()),$r())}),zr(()=>{if(!A(Y))return;const V=ke=>{We(ke.detail,"PIE_CONTROLLER_RUNTIME_ERROR")};return A(Y).addEventListener("pie-controller-error",V),()=>{A(Y)?.removeEventListener("pie-controller-error",V)}}),zr(()=>{if(!A(Y)||v()==="author")return;const V=A(Y);let ke=!1;const qe=()=>{const Rr=J3(V)+rF(V);ke=Rr>0,r.debug("[PieItemPlayer] Post-render wrap pass wrapped",Rr)};if(qe(),typeof MutationObserver>"u")return;let Ve=null;const at=()=>{Ve===null&&(Ve=setTimeout(()=>{Ve=null,qe()},0))},Rt=new MutationObserver(Rr=>{ke&&(ke=!1,Rr.every(Vr=>eF(Vr)||iF(Vr)))||at()});return Rt.observe(V,{childList:!0,subtree:!0}),ke=!1,()=>{Rt.disconnect(),Ve!==null&&(clearTimeout(Ve),Ve=null)}}),zr(()=>{if(!A(Y)||v()==="author"||!n())return;const V=A(Y),ke=!!i(),qe=Bn(()=>{const Ve=[O1(V,()=>({config:n(),session:s(),env:o(),bundleType:p()}))];return ke&&Ve.push(O1(V,()=>({config:i(),session:s(),env:o(),bundleType:p()}))),Ve});return()=>{for(const Ve of qe)Ve()}});const Ur=Et(()=>[...new Set([...A(O),...A($)])].join(" "));let Lr=Promise.resolve();zr(()=>{if(!A(me)||v()==="author")return;const V=[A(we),A(_e)].filter(qe=>qe!==null);if(!(A(ne)+A(N))||V.length===0)return;const ke=new Set(A(Ur).split(" ").filter(Boolean));Lr=Lr.then(()=>{const qe=HF();return aH(V.filter(Ve=>Ve.isConnected),ke,typeof qe?.renderMath=="function"?Ve=>qe.renderMath(Ve):lH)}).catch(qe=>{r.warn("[PieItemPlayer] Typesetting the markup's math failed:",qe)})});var ln={validateModels:Se,get itemConfig(){return n()},set itemConfig(V){n(V),Xe()},get passageConfig(){return i()},set passageConfig(V=null){i(V),Xe()},get env(){return o()},set env(V={mode:"gather",role:"student"}){o(V),Xe()},get session(){return s()},set session(V=[]){s(V),Xe()},get addCorrectResponse(){return a()},set addCorrectResponse(V=!1){a(V),Xe()},get onCorrectResponsesPopulated(){return l()},set onCorrectResponsesPopulated(V){l(V),Xe()},get allowedResize(){return d()},set allowedResize(V=!1){d(V),Xe()},get customClassName(){return c()},set customClassName(V=""){c(V),Xe()},get passageContainerClass(){return u()},set passageContainerClass(V=""){u(V),Xe()},get containerClass(){return f()},set containerClass(V=""){f(V),Xe()},get bundleType(){return p()},set bundleType(V=Gl.player){p(V),Xe()},get loaderConfig(){return g()},set loaderConfig(V=Mp){g(V),Xe()},get mode(){return v()},set mode(V="view"){v(V),Xe()},get configuration(){return b()},set configuration(V={}){b(V),Xe()},get authoringBackend(){return w()},set authoringBackend(V="demo"){w(V),Xe()},get trustMarkup(){return I()},set trustMarkup(V=!1){I(V),Xe()},get sanitizeMarkup(){return x()},set sanitizeMarkup(V){x(V),Xe()},get onInsertImage(){return C()},set onInsertImage(V){C(V),Xe()},get onDeleteImage(){return L()},set onDeleteImage(V){L(V),Xe()},get onInsertSound(){return E()},set onInsertSound(V){E(V),Xe()},get onDeleteSound(){return M()},set onDeleteSound(V){M(V),Xe()},get onLoadComplete(){return U()},set onLoadComplete(V){U(V),Xe()},get onPlayerError(){return te()},set onPlayerError(V){te(V),Xe()},get onSessionChanged(){return re()},set onSessionChanged(V){re(V),Xe()},get onModelUpdated(){return Pe()},set onModelUpdated(V){Pe(V),Xe()},get onModelLoaded(){return z()},set onModelLoaded(V){z(V),Xe()},get onElementSessionUpdate(){return K()},set onElementSessionUpdate(V){K(V),Xe()},get baseHeadingLevel(){return oe()},set baseHeadingLevel(V=void 0){oe(V),Xe()},get includeSrHeading(){return ue()},set includeSrHeading(V=!0){ue(V),Xe()},get i18n(){return ae()},set i18n(V){ae(V),Xe()}},qr=LH(),xr=va(qr),Ar=V=>{var ke=Y1(),qe=va(ke),Ve=fl(qe,!0),at=Dc(qe,2),Rt=fl(at,!0);fs(ke),Ro(Rr=>{pl(Ve,Rr),pl(Rt,A(W))},[()=>A(X).t("player.playerError")]),oo(V,ke)};su(xr,V=>{A(W)&&V(Ar)});var ye=Dc(xr,2),vt=V=>{var ke=Y1(),qe=va(ke),Ve=fl(qe,!0),at=Dc(qe,2),Rt=fl(at,!0);fs(ke),Ro(Rr=>{pl(Ve,Rr),pl(Rt,A(Z))},[()=>A(X).t("player.authoringBackendError")]),oo(V,ke)},kt=V=>{var ke=J1();NS(ke,()=>A(ne),!0),fs(ke),au(ke,qe=>Fe(we,qe),()=>A(we)),Ro(()=>Bc(ke,1,pg(A(mt)),"svelte-udi90b")),oo(V,ke)};su(ye,V=>{A(Z)?V(vt):A(ne)&&V(kt,1)});var Qe=Dc(ye,2),cr=V=>{var ke=J1();NS(ke,()=>A(N),!0),fs(ke),au(ke,qe=>Fe(_e,qe),()=>A(_e)),Ro(()=>Bc(ke,1,pg(A($t)),"svelte-udi90b")),oo(V,ke)};return su(Qe,V=>{!A(Z)&&A(N)&&V(cr)}),fs(qr),au(qr,V=>Fe(Y,V),()=>A(Y)),Ro(()=>Bc(qr,1,pg(A(ve)),"svelte-udi90b")),oo(e,qr),gm(ln)}Yb(PR,{itemConfig:{},passageConfig:{},env:{},session:{},addCorrectResponse:{},onCorrectResponsesPopulated:{},allowedResize:{},customClassName:{},passageContainerClass:{},containerClass:{},bundleType:{},loaderConfig:{},mode:{},configuration:{},authoringBackend:{},trustMarkup:{},sanitizeMarkup:{},onInsertImage:{},onDeleteImage:{},onInsertSound:{},onDeleteSound:{},onLoadComplete:{},onPlayerError:{},onSessionChanged:{},onModelUpdated:{},onModelLoaded:{},onElementSessionUpdate:{},baseHeadingLevel:{},includeSrHeading:{},i18n:{}},[],["validateModels"],{mode:"open"});u5();var NH=ea("<div></div>"),DH={hash:"svelte-18lyvta",code:`.pie-loading.svelte-18lyvta {
1055
+ /* Same spinner as the .pie-loading rules in pie-theme components.css.
1056
+ The Figma indigo is --pie-primary at 90%, so the ring follows the
1057
+ theme's primary instead of pinning MD indigo on every page. */--pie-loading-accent: color-mix(in srgb, var(--pie-primary, #3f51b5) 90%, transparent);position:absolute;height:100%;width:100%;background-color:var(--pie-white, #fff);bottom:0;left:0;right:0;top:0;z-index:9999;opacity:0.4;}.pie-loading.fixed.svelte-18lyvta {position:fixed;}.pie-loading.svelte-18lyvta:before {content:"";background-color:rgba(0, 0, 0, 0);border:5px solid var(--pie-loading-accent, rgba(63, 81, 181, 0.9));opacity:0.9;border-right:5px solid rgba(0, 0, 0, 0);border-left:5px solid rgba(0, 0, 0, 0);border-radius:50px;box-shadow:0 0 35px var(--pie-loading-accent, rgba(63, 81, 181, 0.9));width:50px;height:50px;
1058
+ animation: svelte-18lyvta-spinPulse 1s infinite linear;margin:-25px 0 0 -25px;position:absolute;top:50%;left:50%;}.pie-loading.svelte-18lyvta:after {content:"";background-color:rgba(0, 0, 0, 0);border:5px solid var(--pie-loading-accent, rgba(63, 81, 181, 0.9));opacity:0.9;border-left:5px solid rgba(0, 0, 0, 0);border-right:5px solid rgba(0, 0, 0, 0);border-radius:50px;box-shadow:0 0 15px var(--pie-loading-accent, rgba(63, 81, 181, 0.9));width:30px;height:30px;
1059
+ animation: svelte-18lyvta-spinoffPulse 1s infinite linear;margin:-15px 0 0 -15px;position:absolute;top:50%;left:50%;}
1060
+
1061
+ @keyframes svelte-18lyvta-spinPulse {
1062
+ 0% {
1063
+ transform: rotate(160deg);
1064
+ opacity: 0;
1065
+ box-shadow: 0 0 1px var(--pie-loading-accent, rgba(63, 81, 181, 0.9));
1066
+ }
1067
+ 50% {
1068
+ transform: rotate(145deg);
1069
+ opacity: 1;
1070
+ }
1071
+ 100% {
1072
+ transform: rotate(-320deg);
1073
+ opacity: 0;
1074
+ }
1075
+ }
1076
+
1077
+ @keyframes svelte-18lyvta-spinoffPulse {
1078
+ 0% {
1079
+ transform: rotate(0deg);
1080
+ }
1081
+ 100% {
1082
+ transform: rotate(360deg);
1083
+ }
1084
+ }`};function AR(e,t){mm(t,!1),Zb(e,DH);let r=Ye(t,"fixed",12,!1);var n={get fixed(){return r()},set fixed(o){r(o),Xe()}},i=NH();return Ro(()=>Bc(i,1,`pie-loading ${r()?"fixed":""}`,"svelte-18lyvta")),oo(e,i),gm(n)}Yb(AR,{fixed:{}},[],[],{mode:"open"});function id(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function cy(e){if(e==null)return!1;if(Array.isArray(e))return e.some(t=>cy(t));if(!id(e))return!1;for(const[t,r]of Object.entries(e))if(t==="value"||cy(r))return!0;return!1}function jH(e,t){return e.id||!t.id?e:{...e,id:t.id}}function BH(e,t){if(!id(e)||"session"in e)return e;let r;try{r=t?.session}catch{return e}if(!id(r))return e;let n;try{n=JSON.parse(JSON.stringify(r))}catch{return e}return{...e,session:n}}function FH(e,t,r){const n=BH(e,t);return!id(n)||"sessionCommitReason"in n?n:{...n,sessionCommitReason:r}}function HH(e){const t=id(e.detail)?e.detail:null;if(!t)return{action:"ignore"};if(!("session"in t)&&!xu(t)&&!cy(t))return{action:"ignore"};const r=zx({itemId:e.itemId,sessionDetail:t,previousItemSession:e.currentSession}),n=r.intent==="metadata-only",i=jH(r.session??e.currentSession,e.currentSession),o=JSON.stringify(i),s=o!==e.currentSignature;if(!s&&!n)return{action:"ignore"};const a=r.elementId&&!("elementId"in t)?{...t,elementId:r.elementId}:t;return{action:"forward",changed:s,detail:n&&!s?{...a,intent:"metadata-only",session:null}:{...a,session:i},metadataOnly:n,session:i,signature:o}}function zH(e,t){if(!e||!Array.isArray(e.data))return;const r=e.data.filter(id);return typeof t=="string"&&t?r.find(n=>n.id===t):r.length===1?r[0]:void 0}function WH(e,t,r){const n=typeof e.component=="string",i=typeof e.complete=="boolean";if(n&&i)return e;const o=typeof e.elementId=="string"&&e.elementId?e.elementId:void 0,s=zH(t,o),a=typeof s?.id=="string"?s.id:o;return{...e,...n?{}:{component:typeof s?.element=="string"&&s.element||r(a)||""},...i?{}:{complete:Qb(s??t?.data??null)}}}var UH=ea(`<div class="pie-player-error svelte-r0yfjj" style="
1085
+ padding: 20px;
1086
+ margin: 20px;
1087
+ border-radius: 4px;
1088
+ font-family: sans-serif;
1089
+ "><h3 style="margin: 0 0 10px 0"> </h3> <p style="margin: 0"> </p></div>`),qH=ea('<p class="pie-item-player-build-warning svelte-r0yfjj" role="status" aria-live="polite" aria-atomic="true"> </p>'),VH=ea('<div class="pie-item-player-loading svelte-r0yfjj"><!> <!></div>'),GH=ea("<div><!></div>"),KH=ea('<div data-pie-content=""><!></div>'),XH={hash:"svelte-r0yfjj",code:`:host {display:block;}.pie-item-player {width:100%;}.pie-player-item-container {width:100%;}.pie-item-player-loading.svelte-r0yfjj {display:flex;flex-direction:column;align-items:center;gap:12px;}.pie-item-player-build-warning.svelte-r0yfjj {margin:0;
1090
+ /* A learner can be the one reading this, so it follows the accommodation
1091
+ like any other text. Stated explicitly rather than left to inherit from
1092
+ the scaled host, to match the other content-path rules. */font-size:calc(0.95rem * var(--pie-font-scale, 1));color:var(--pie-missing, #9a6700);text-align:center;}
1093
+
1094
+ /*
1095
+ * Fixed red encoding, folded into the palette once a scheme asks for one: exact
1096
+ * pinned values at 0% collapse, which is every Base Theme. The ink collapses to
1097
+ * \`--pie-text\` rather than \`--pie-incorrect\`, which pairs with this tint at only
1098
+ * 4.14:1 under Black on White; the tint is roughly 1.1:1 from the page, so the
1099
+ * \`--pie-incorrect\` edge is what marks the banner out. Kept in step with the
1100
+ * same rule in \`players-shared\`'s \`PieItemPlayer\`.
1101
+ */.pie-player-error.svelte-r0yfjj {border:2px solid
1102
+ color-mix(
1103
+ in srgb,
1104
+ var(--pie-incorrect, #d32f2f) var(--pie-fixed-hue-collapse, 0%),
1105
+ #d32f2f
1106
+ );background-color:color-mix(
1107
+ in srgb,
1108
+ var(--pie-incorrect-secondary, #ffebee) var(--pie-fixed-hue-collapse, 0%),
1109
+ #ffebee
1110
+ );color:color-mix(
1111
+ in srgb,
1112
+ var(--pie-text, #c62828) var(--pie-fixed-hue-collapse, 0%),
1113
+ #c62828
1114
+ );}`};function MR(e,t){mm(t,!0),Zb(e,XH);let r=Ye(t,"config",7,null),n=Ye(t,"session",23,()=>({id:"",data:[]})),i=Ye(t,"env",23,()=>({mode:"gather",role:"student"})),o=Ye(t,"addCorrectResponse",7,!1),s=Ye(t,"showBottomBorder",7,!1),a=Ye(t,"hosted",7,void 0),l=Ye(t,"debug",7,""),d=Ye(t,"customClassName",7,""),c=Ye(t,"customClassname",7,""),u=Ye(t,"containerClass",7,""),f=Ye(t,"passageContainerClass",7,""),p=Ye(t,"externalStyleUrls",7,""),g=Ye(t,"renderStimulus",7,!0),v=Ye(t,"allowedResize",7,!1),b=Ye(t,"autoplayAudioEnabled",7,void 0),w=Ye(t,"baseHeadingLevel",7,void 0),I=Ye(t,"locale",7,""),x=Ye(t,"includeSrHeading",7,!0),C=Ye(t,"bundleHost",7,""),L=Ye(t,"bundleEndpoints",7,null),E=Ye(t,"disableBundler",7,!1),M=Ye(t,"reFetchBundle",7,!1),U=Ye(t,"loaderConfig",7,WS),te=Ye(t,"strategy",7,void 0),re=Ye(t,"mode",7,"view"),Pe=Ye(t,"configuration",23,()=>({})),z=Ye(t,"authoringBackend",7,"demo"),K=Ye(t,"backend",7,null),oe=Ye(t,"sessionSnapshot",7,null),ue=Ye(t,"allowedStyleOrigins",7,""),ae=Ye(t,"loaderOptions",23,()=>({})),X=Ye(t,"trustMarkup",7,!1),j=Ye(t,"sanitizeMarkup",7,null),D=Ye(t,"onInsertImage",7,null),Z=Ye(t,"onDeleteImage",7,null),F=Ye(t,"onInsertSound",7,null),W=Ye(t,"onDeleteSound",7,null);const O=typeof window<"u"&&typeof document<"u",$=Et(()=>te()??(E()?"preloaded":"iife")),ie=Et(()=>zj(A($),"iife")),N=Et(()=>re()==="author"?"author":"view"),ne=Et(()=>d()||c()||""),ge=Et(()=>ae()?.bundleHost||C()||"https://proxy.pie-api.com/bundles/"),Oe=Et(()=>ae()?.esmCdnUrl||"https://cdn.jsdelivr.net/npm"),We=Et(()=>JSON.stringify(U()?.iifeBundleRetry||{})),Ne=3e4,xe=new Map,et=new Map;function Ue(P,pe="off"){return P==="off"||P==="on"?P:pe}function Se(P){return bP(P,{cdnBaseUrl:A(Oe),cdnProvider:ae()?.esmCdnProvider})}function Re(P,pe,De){const Ge=P.supports?.[pe];if(!Ge)return!0;const ut=Ge[De];return ut===void 0?!0:ut}function mt(P){const pe=String(P||"").toLowerCase();return pe.includes("cannot find module")||pe.includes("failed to fetch dynamically imported module")||pe.includes("404")||pe.includes("runtime-support")}async function $t(P,pe){if(pe!=="on")return;const De=P,Ge=xe.get(De);if(Ge)return Ge;const ut=et.get(De);if(ut&&Date.now()-ut<Ne)return;const Dt=Se(P);if(Dt)try{const At=await br(()=>import(Dt),[],import.meta.url),yr=At.default||At.runtimeSupport||At;if(!yr||typeof yr!="object")throw new Error(`Invalid runtime-support export for ${P}`);return xe.set(De,yr),et.delete(De),yr}catch(At){if(mt(At)){et.set(De,Date.now());return}return}}async function ve(P,pe,De){if(De!=="on")return{unsupportedPackages:[]};const Ge=[];for(const ut of Object.values(P||{})){const Dt=await $t(ut,De);if(!Dt||Re(Dt,"esm",pe))continue;const{name:At}=jp(ut);Ge.push(At)}return{unsupportedPackages:Ge}}const me=Et(()=>{if(l()!==void 0&&l()!==null){const P=String(l()),pe=!(P.toLowerCase()==="false"||P==="0"||P==="");if(O)try{window.PIE_DEBUG=pe}catch{}return pe}return Ou()}),Je=Lu("pie-item-player",()=>A(me)),Gt=Et(()=>T7({player:{loaderConfig:U()},component:"pie-item-player",debug:A(me)}));let le=er(!0),Ae=er(null),Y=er(null),we=er(null),_e=er(null),Be=er(null),it=er(null),tt=er(null),Bt=er("pie-item-player"),ht=er(""),ot=er(0),$r=!1,Ur=0,Lr=null,ln="",qr=null,xr=null,Ar=null;function ye(P){let pe=P.parentElement;for(;pe;){if(pe.tagName.includes("-"))return pe;pe=pe.parentElement}return null}zr(()=>{!A(Be)||xr||(xr=ye(A(Be)))});function vt(P){const pe=A(Be);if(!pe)return;const De=[],Ge=ut=>{ut.stopPropagation(),De.push(FH(ut.detail,ut.target,P))};pe.addEventListener("session-changed",Ge,!0);try{Eh(pe,{reason:P,logger:Je})}finally{pe.removeEventListener("session-changed",Ge,!0)}Ar=xr??A(Be);try{for(const ut of De)try{Aa(ut)}catch(Dt){Je.warn("[pie-item-player] forwarding a committed session failed",Dt)}}finally{Ar=null}}Xb(()=>{try{vt("teardown")}catch(P){Je.warn("[pie-item-player] session commit on teardown failed",P)}});const kt=B3({getBackend:()=>K(),getItemConfig:()=>A(we),getPassageConfig:()=>A(_e),getEnv:()=>mr(i()),getSessionContainer:()=>kr(),loadPlayerConfig:P=>ri(P),dispatchPlayerEvent:P=>Zr(P),applyRefreshedConfigs:ni}),Qe=Et(()=>kt.configOverride??r()),cr=Et(()=>kt.sessionOverride??n());function V(P){const pe=P?.resources;return pe&&typeof pe=="object"?pe:null}const ke=Et(()=>V(A(we))),qe=Et(()=>typeof A(ke)?.containerClass=="string"?A(ke).containerClass:u()),Ve=Et(()=>typeof A(ke)?.passageContainerClass=="string"?A(ke).passageContainerClass:f());function at(){return Ur+=1,Ur}function Rt(P){return P===Ur}const Rr=Et(()=>{const P=A(Y)?.state;if(!A(Y)||P!=="retrying")return null;const pe=Math.max(1,Math.ceil(A(Y).elapsedMs/1e3)),De=Math.max(1,Math.ceil(A(Y).timeoutMs/1e3));return`Bundle is still building. Retrying load attempt ${A(Y).attempt} (elapsed ${pe}s of ${De}s).`});function Vr(P){if(typeof P=="string")try{return JSON.parse(P)}catch{return{id:"",data:[]}}return P}function jr(P,pe){return(!A(tt)||A(Bt)!==P)&&(Fe(tt,new j7({itemId:P,initialSession:pe}),!0),Fe(Bt,P,!0),Fe(ht,JSON.stringify(A(tt).getSession()),!0),$r=!1),A(tt)}function dr(P,pe,De){const Ge=P.setSession(pe,{persist:!1,allowMetadataOverwrite:De.allowMetadataOverwrite}),ut=JSON.stringify(Ge);return ut===A(ht)?!1:(Fe(ht,ut,!0),Fe(ot,A(ot)+1),$r=!1,!0)}function fe(P){if(!$e(P))return!1;const pe=P.shuffledValues;if(!$e(pe))return!1;const De="partA"in pe,Ge="partB"in pe;return(De||Ge)&&!(De&&Ge)}function _t(P){let pe=!1;const De=P.map(Ge=>{if(!fe(Ge)||!$e(Ge))return Ge;const{shuffledValues:ut,...Dt}=Ge;return pe=!0,Dt});return pe?De:P}const Gr=Et(()=>(A(ot),_t(A(tt)?A(tt).getSession().data:y1(Vr(A(cr))).data)));function tn(P){return P?.markup??""}const Wn=Et(()=>D()??kt.authoringMedia?.onInsertImage??null),ei=Et(()=>Z()??kt.authoringMedia?.onDeleteImage??null),ta=Et(()=>F()??kt.authoringMedia?.onInsertSound??null),Cr=Et(()=>W()??kt.authoringMedia?.onDeleteSound??null),ti=Et(()=>A(N)!=="author"?"":[_p(Pe()),z(),th(A(Wn)),th(A(ei)),th(A(ta)),th(A(Cr))].join("|")),Qo=Et(()=>[tn(A(we)),g()?tn(A(_e)):"",g()?"stimulus":"item-only",A(N),A(ti)].join("|")),H=Et(()=>A(ne).trim()),ce=v3(),se=Et(()=>A(ne)?A(H):ce),de=Et(()=>A(se)===A(H)?"":A(se));let lt="",nr="",Ee="",rt="",sr="";function Pt(P){if(!O||A(ie)!=="preloaded")return P;const pe=i7(P);return pe!==P&&Je.debug("[pie-item-player] Normalized preloaded config.elements to bundled versions"),pe}function $e(P){return!!P&&typeof P=="object"&&!Array.isArray(P)}function wr(P){return $e(P)?typeof P.markup=="string"&&$e(P.elements)&&Array.isArray(P.models):!1}function hn(P){return wr(P)?{item:P,passage:null}:$e(P)&&wr(P.pie)?{item:P.pie,passage:wr(P.passage)?P.passage:null}:{item:P,passage:null}}function Ir(P){const pe=m3(Pt(P),b());return yj({config:pe}).config}function Br(...P){return P.reduce((pe,De)=>De?.elements?{...pe,...De.elements}:pe,{})}function mr(P){if(typeof P=="string")try{return JSON.parse(P)}catch{return{mode:"gather",role:"student"}}return P||{mode:"gather",role:"student"}}const ur=jj();let Lt=er(0);zr(()=>ur.subscribe(()=>{Fe(Lt,A(Lt)+1)})),zr(()=>{const P=typeof I()=="string"?I().trim():"";Bn(()=>{Promise.resolve(ur.setLocale(P||"en-US")).catch(()=>{})})});const gr=Et(()=>(A(Lt),ur)),Fr=Et(()=>{if(typeof w()=="number"&&Number.isInteger(w())&&w()>=1&&w()<=6)return w()}),Yt=Et(()=>a()??Xx(K()));function dt(){return A(N)==="author"?To.editor:A(Yt)?To.player:To.clientPlayer}function zt(){return n7({loadControllers:ae()?.loadControllers,author:A(N)==="author",hosted:A(Yt)})}function fr(P,pe){const De=P===To.editor||P===To.clientPlayer&&!A(Yt);return{kind:"iife",bundleHost:A(ge),bundleType:P,needsControllers:De,debugEnabled:()=>A(me),bundleRetry:U()?.iifeBundleRetry,trackPageActions:U()?.trackPageActions,instrumentationProvider:A(Gt),onBundleRetryStatus:Ge=>{Rt(pe)&&(Fe(Y,Ge,!0),Zr(new CustomEvent("bundle-retry-status",{detail:Ge})))}}}function Kn(P){const pe=ae()?.moduleResolution==="import-map"?"import-map":"url";return{kind:"esm",cdnBaseUrl:A(Oe),cdnProvider:ae()?.esmCdnProvider,moduleResolution:pe,view:P||"delivery",loadControllers:zt(),trackPageActions:U()?.trackPageActions,instrumentationProvider:A(Gt)}}function _r(){return ae()?.view||(A(N)==="author"?"author":"delivery")}function $n(P,pe){return pe!==To.editor?P:Object.fromEntries(Object.entries(P).map(([De,Ge])=>[`${De}-config`,Ge]))}async function ri(P){const pe=_p(P),De=JSON.stringify({bundleHost:A(ge),esmCdnUrl:A(Oe),loadControllers:zt(),moduleResolution:ae()?.moduleResolution??"url",runtimeSupportCheck:ae()?.runtimeSupportCheck??"off",view:ae()?.view??null,elementPackagePolicy:ae()?.elementPackagePolicy??null,disableBundler:E(),bundleEndpoints:L(),reFetchBundle:M()});if(pe===lt&&A(ie)===nr&&A(N)===Ee&&A(We)===rt&&De===sr)return!0;Eh(A(Be),{reason:"navigate",logger:Je});const Ge=at(),ut=yr=>Rt(Ge)?(yr(),!0):!1;if(!P)return lt=pe,nr=A(ie),Ee=A(N),rt=A(We),sr=De,ut(()=>{Fe(we,null),Fe(_e,null),kt.noteConfigChanged(),Fe(le,!0),Fe(Ae,null),Fe(Y,null)}),!0;lt=pe,nr=A(ie),Ee=A(N),rt=A(We),sr=De,ut(()=>{Fe(le,!0),Fe(Ae,null),Fe(Y,null)});let Dt="start",At=null;try{Dt="parse-config";const yr=hn(typeof P=="string"?JSON.parse(P):P);Dt="validate-config";for(const[Pi,he]of[["item",yr.item],["passage",yr.passage]]){if(!he)continue;vj(he);const ze=wx(he).warnings,pt=Array.isArray(ze)?ze.filter(Ke=>typeof Ke=="string"):[];for(const Ke of pt)Je.warn(`[pie-item-player] ${Pi}: ${Ke}`)}Dt="normalize-config",(L()||M())&&Je.warn("[pie-item-player] bundleEndpoints/reFetchBundle are accepted for legacy host compatibility but are not used by the current loader boundary.");const mi=Ir(yr.item),qn=yr.passage?Ir(yr.passage):null,$a=Ue(ae()?.runtimeSupportCheck,"off"),La=f3(A(ie),$a)?$a:"off",ra=_r(),cn=Br(mi,qn);gk(cn,ae()?.elementPackagePolicy);const yf=await ve(cn,ra,La);if(!Rt(Ge)||(At=yf.unsupportedPackages.length>0?` Runtime support metadata indicates esm/${ra} is unsupported for ${yf.unsupportedPackages.join(", ")}.`:null,A(ie)==="iife"&&(Dt="math-rendering-init",await SP(),!Rt(Ge))))return!1;if(A(ie)==="preloaded"){Dt="preloaded-readiness";const Pi=dt(),he=$n(cn,ra==="author"?To.editor:Pi);if(a7(he),UB(he),Pi===To.clientPlayer)for(const ze of h3(Object.keys(he)))Je.warn(p3(ze))}else if(A(ie)==="iife"){Dt="iife-load";const Pi=dt();await l1($n(cn,Pi),{backend:fr(Pi,Ge),elementPackagePolicy:ae()?.elementPackagePolicy})}else{Dt="esm-load";const Pi=_r();await l1(kP(cn,Pi),{backend:Kn(Pi),elementPackagePolicy:ae()?.elementPackagePolicy})}return Rt(Ge)?(Dt="set-item-config",ut(()=>{Fe(we,mi,!0),Fe(_e,qn,!0),kt.noteConfigChanged(),Fe(le,!1),Fe(Ae,null),Fe(Y,null)}),!0):!1}catch(yr){if(!Rt(Ge))return!1;const mi=`${yr?.message||String(yr)}${At||""}`;ut(()=>{Fe(Ae,`Error loading elements (${Dt}): ${mi}`),Fe(le,!1),Fe(Y,null)}),Je.error("[pie-item-player] failed loading:",yr);const qn=OB(yr);return Zr(new CustomEvent(E1.error,{detail:{code:"ITEM_PLAYER_LOAD_ERROR",message:mi,recoverable:!1,stage:Dt,strategy:A(ie),mode:A(N),...qn?{cause:qn}:{}}})),!1}}zr(()=>{const P=A(Qe);A(ie),A(N),A(ge),A(Oe),A(We),ae(),E(),v(),b(),L(),M(),queueMicrotask(()=>{Bn(()=>{ri(P)})})}),zr(()=>{const P=Vr(A(cr)),pe=kt.hasPendingSessionReplacement(),De=A(we)?.id||"pie-item-player";Bn(()=>{dr(jr(De,P),P,{allowMetadataOverwrite:pe}),pe&&kt.markSessionReplacementApplied()})});const pn=Et(()=>EB(ue()));zr(()=>{if(!O)return;const P=typeof p()=="string"?p().split(",").map(At=>At.trim()):[],pe=A(we)?.resources?.stylesheets;if(Array.isArray(pe))for(const At of pe)typeof At?.url=="string"&&P.push(At.url);const De=new AbortController,Ge=new Set,ut=new Set,Dt=A(se);for(const At of P){if(!At)continue;const yr=TB(At,{baseUrl:window.location.href,allowedOrigins:A(pn)});if(!yr.ok){Je.error(`[pie-item-player] ${yr.message} (url=${At})`);continue}const mi=yr.resolvedUrl.toString();if(!ut.has(mi)){if(ut.add(mi),yr.resolvedUrl.origin!==window.location.origin){I3(document,At,mi);continue}w3({document,resolvedUrl:mi,scopeClass:Dt,signal:De.signal,sourceUrl:At}).then(qn=>{if(qn){if(De.signal.aborted){qn();return}Ge.add(qn)}}).catch(qn=>{De.signal.aborted||Je.error(`Failed to load external stylesheet: ${At}`,qn)})}}return()=>{De.abort();for(const At of Ge)At();Ge.clear()}}),zr(()=>{if(!A(Be))return;const P=A(Be);return w7({host:P,instrumentationProvider:A(Gt),component:"pie-item-player",eventMap:E7,staticAttributes:{instrumentationLayer:"item"},shouldTrackEvent:pe=>pe.target===P,debug:A(me)})}),zr(()=>{const P=A(we);s()&&i().mode==="evaluate"&&P?.elements&&ou().then(()=>{const pe=Object.keys(P.elements);for(const De of pe){const Ge=A(Be)?.querySelectorAll(De)??[];for(const ut of Ge)ut instanceof HTMLElement&&(ut.style.borderBottom="1px solid var(--pie-border-light, #ddd)",ut.style.paddingBottom="20px",ut.style.marginBottom="20px")}})});const Zr=P=>{P.type==="backend-session-saved"&&(Lr?.clear(),qr=null);const pe=new CustomEvent(P.type,{detail:P.detail,bubbles:!0,composed:!0});(Ar??A(Be))?.dispatchEvent(pe)};function Pr(P){try{O7(n(),P)}catch(pe){Je.warn("[pie-item-player] could not project the session onto the host container",pe)}}function Or(){const P=(A(we)?.models??[]).map(pe=>typeof pe?.id=="string"?pe.id:"").filter(pe=>pe.length>0);if(P.length!==0)try{L7(n(),P)}catch(pe){Je.warn("[pie-item-player] could not seed host session entries",pe)}}function kr(){const P=y1(Vr(A(cr)));return A(tt)?A(tt).getSession():P}function xt(){const P=K()?.delivery;return{itemId:P?.itemId||A(we)?.id||"",sessionId:P?.sessionId||"",assignmentId:P?.assignmentId||""}}function Tr(){if(Lr)try{Lr.write(kr())}catch(P){Je.warn("[pie-item-player] session snapshot write failed",P)}}zr(()=>{const P=oe(),pe=xt();Bn(()=>{const De=t3({config:P,identity:pe});if(Lr=De,!De||De.key===ln)return;ln=De.key;const Ge=De.read();Ge&&(qr=Ge,Zr(new CustomEvent("session-snapshot-available",{detail:{key:Ge.key,session:Ge.session,timestamp:Ge.timestamp}})))})}),zr(()=>{if(!O)return;const P=A(Be);if(P)return X7({root:()=>P,onHidden:()=>{Tr(),kt.flushPendingSave({keepalive:!0})},logger:Je})}),zr(()=>{if(!O)return;const P=A(Be);if(!P)return;const pe=De=>{const Ge=De.relatedTarget;Ge instanceof Node&&P.contains(Ge)||K7(P,{logger:Je})};return P.addEventListener("focusout",pe),()=>P.removeEventListener("focusout",pe)});async function ni(P){Fe(we,P.itemConfig,!0),Fe(_e,P.passageConfig,!0),await ou(),P.itemChanged&&A(we)&&Eg(A(we),A(Gr),mr(i()),A(Be)??void 0,Nr,dt()),P.passageChanged&&A(_e)&&Eg(A(_e),A(Gr),mr(i()),A(Be)??void 0,Nr,dt())}async function Ln(P="delivery"){return kt.load(P)}function On(){return qr}function m(){Eh(A(Be),{reason:"teardown",logger:Je})}async function k(){return kt.saveSession()}async function B(P){return kt.score(P)}async function J(P){return kt.saveContent(P)}async function Me(P){return kt.releaseContent(P)}async function st(){const P=A(we);if(!P?.models?.length)return!1;const pe=mr(i()),{results:De}=await Ij(P,A(Gr),{container:A(Be)??document,env:{...pe,mode:"evaluate",partialScoring:pe.partialScoring},outcomeArguments:"model-session-env",includeMissingResults:!0,bundleType:dt()});return De}function yt(P,pe=!1){if(!A(we))throw new Error("Cannot update element model before the item config has loaded.");const De=typeof P?.id=="string"?P.id:"";if(!De)throw new Error("updateElementModel(update) requires update.id.");const Ge=A(we).models?.findIndex(yr=>yr.id===De)??-1;if(Ge<0)throw new Error(`No PIE model found for id "${De}".`);const ut=A(we).models[Ge],Dt=[...A(we).models];Dt[Ge]=pe?{...P,id:ut.id,element:ut.element}:{...ut,...P,id:ut.id,element:ut.element};const At={...A(we),models:Dt};return Fe(we,At,!0),At}async function Jt(P){const pe=yt(P);await ou(),Eg(pe,A(Gr),mr(i()),A(Be)??void 0,Nr,dt())}function ii(P){const pe=P&&typeof P=="object"?P:null;if(pe?.update&&typeof pe.update=="object")try{yt(pe.update,pe.reset===!0)}catch(De){Je.warn("[pie-item-player] ignored model-updated state sync:",De)}Zr(new CustomEvent("model-updated",{detail:P}))}async function Un(){if(A(N)!=="author")return{hasErrors:!1,validatedModels:[]};if(typeof A(it)?.validateModels!="function")throw new Error("Cannot validate models before the authoring player has loaded.");return A(it).validateModels()}const Nr=(P,pe,De)=>{const Ge=jr(A(we)?.id||"pie-item-player",Vr(A(cr))),ut=A(ht),Dt=Ge.mergeElementSession(P,De,{persist:!1}),At=JSON.stringify(Dt);At!==ut&&(Fe(ht,At,!0),Pr(Dt),$r=!0)};function Pa(P){const pe=[...A(we)?.models??[],...A(_e)?.models??[]],De=P?pe.find(Ge=>Ge.id===P):pe.length===1?pe[0]:void 0;return typeof De?.element=="string"?De.element:void 0}const Yr=(P,pe)=>{Zr(new CustomEvent("session-changed",{detail:WH(P,pe,Pa)}))},Aa=P=>{const pe=A(we)?.id||"pie-item-player",De=jr(pe,Vr(A(cr))),Ge=HH({detail:P,itemId:pe,currentSession:De.getSession(),currentSignature:A(ht)});if(Ge.action!=="ignore"){if(Ge.changed){const ut=De.setSession(Ge.session,{persist:!1,allowMetadataOverwrite:!1});Fe(ht,JSON.stringify(ut),!0),Fe(ot,A(ot)+1),$r=!1,Pr(ut),Yr({...Ge.detail,session:ut},ut),Tr(),kt.scheduleAutosave();return}if($r){$r=!1;const{intent:ut,...Dt}=Ge.detail,At=De.getSession();Yr({...Dt,session:At},At);return}Yr(Ge.detail,De.getSession())}};var cc={loadFromBackend:Ln,getPendingSessionSnapshot:On,commitPendingElementSessions:m,saveSession:k,score:B,saveContent:J,releaseContent:Me,provideScore:st,updateElementModel:Jt,validateModels:Un,get config(){return r()},set config(P=null){r(P),Xe()},get session(){return n()},set session(P={id:"",data:[]}){n(P),Xe()},get env(){return i()},set env(P={mode:"gather",role:"student"}){i(P),Xe()},get addCorrectResponse(){return o()},set addCorrectResponse(P=!1){o(P),Xe()},get showBottomBorder(){return s()},set showBottomBorder(P=!1){s(P),Xe()},get hosted(){return a()},set hosted(P=void 0){a(P),Xe()},get debug(){return l()},set debug(P=""){l(P),Xe()},get customClassName(){return d()},set customClassName(P=""){d(P),Xe()},get customClassname(){return c()},set customClassname(P=""){c(P),Xe()},get containerClass(){return u()},set containerClass(P=""){u(P),Xe()},get passageContainerClass(){return f()},set passageContainerClass(P=""){f(P),Xe()},get externalStyleUrls(){return p()},set externalStyleUrls(P=""){p(P),Xe()},get renderStimulus(){return g()},set renderStimulus(P=!0){g(P),Xe()},get allowedResize(){return v()},set allowedResize(P=!1){v(P),Xe()},get autoplayAudioEnabled(){return b()},set autoplayAudioEnabled(P=void 0){b(P),Xe()},get baseHeadingLevel(){return w()},set baseHeadingLevel(P=void 0){w(P),Xe()},get locale(){return I()},set locale(P=""){I(P),Xe()},get includeSrHeading(){return x()},set includeSrHeading(P=!0){x(P),Xe()},get bundleHost(){return C()},set bundleHost(P=""){C(P),Xe()},get bundleEndpoints(){return L()},set bundleEndpoints(P=null){L(P),Xe()},get disableBundler(){return E()},set disableBundler(P=!1){E(P),Xe()},get reFetchBundle(){return M()},set reFetchBundle(P=!1){M(P),Xe()},get loaderConfig(){return U()},set loaderConfig(P=WS){U(P),Xe()},get strategy(){return te()},set strategy(P=void 0){te(P),Xe()},get mode(){return re()},set mode(P="view"){re(P),Xe()},get configuration(){return Pe()},set configuration(P={}){Pe(P),Xe()},get authoringBackend(){return z()},set authoringBackend(P="demo"){z(P),Xe()},get backend(){return K()},set backend(P=null){K(P),Xe()},get sessionSnapshot(){return oe()},set sessionSnapshot(P=null){oe(P),Xe()},get allowedStyleOrigins(){return ue()},set allowedStyleOrigins(P=""){ue(P),Xe()},get loaderOptions(){return ae()},set loaderOptions(P={}){ae(P),Xe()},get trustMarkup(){return X()},set trustMarkup(P=!1){X(P),Xe()},get sanitizeMarkup(){return j()},set sanitizeMarkup(P=null){j(P),Xe()},get onInsertImage(){return D()},set onInsertImage(P=null){D(P),Xe()},get onDeleteImage(){return Z()},set onDeleteImage(P=null){Z(P),Xe()},get onInsertSound(){return F()},set onInsertSound(P=null){F(P),Xe()},get onDeleteSound(){return W()},set onDeleteSound(P=null){W(P),Xe()}},pi=KH(),dc=va(pi),gf=P=>{var pe=UH(),De=va(pe),Ge=fl(De,!0),ut=Dc(De,2),Dt=fl(ut,!0);fs(pe),Ro(At=>{pl(Ge,At),pl(Dt,A(Ae))},[()=>A(gr).t("player.configurationError")]),oo(P,pe)},vf=P=>{var pe=VH(),De=va(pe);AR(De,{});var Ge=Dc(De,2),ut=Dt=>{var At=qH(),yr=fl(At,!0);Ro(()=>pl(yr,A(Rr))),oo(Dt,At)};su(Ge,Dt=>{A(Rr)&&Dt(ut)}),fs(pe),oo(P,pe)},Ma=P=>{var pe=GH(),De=va(pe);ij(De,()=>A(Qo),Ge=>{{let ut=Et(()=>g()?A(_e):null),Dt=Et(()=>mr(i())),At=Et(dt),yr=Et(()=>j()??void 0),mi=Et(()=>typeof Pe()=="string"?JSON.parse(Pe()):Pe()),qn=Et(()=>A(Wn)??void 0),$a=Et(()=>A(ei)??void 0),La=Et(()=>A(ta)??void 0),ra=Et(()=>A(Cr)??void 0);au(PR(Ge,{get itemConfig(){return A(we)},get passageConfig(){return A(ut)},get env(){return A(Dt)},get session(){return A(Gr)},get addCorrectResponse(){return o()},get allowedResize(){return v()},get customClassName(){return A(H)},get passageContainerClass(){return A(Ve)},get baseHeadingLevel(){return A(Fr)},get includeSrHeading(){return x()},get i18n(){return A(gr)},get bundleType(){return A(At)},get loaderConfig(){return U()},get mode(){return A(N)},get authoringBackend(){return z()},get trustMarkup(){return X()},get sanitizeMarkup(){return A(yr)},get configuration(){return A(mi)},get onInsertImage(){return A(qn)},get onDeleteImage(){return A($a)},get onInsertSound(){return A(La)},get onDeleteSound(){return A(ra)},onLoadComplete:cn=>{Or(),Zr(new CustomEvent("load-complete",{detail:cn}))},onPlayerError:cn=>Zr(new CustomEvent(E1.error,{detail:cn})),onSessionChanged:cn=>Aa(cn),onElementSessionUpdate:Nr,onModelUpdated:cn=>ii(cn),onModelLoaded:cn=>Zr(new CustomEvent("model-loaded",{detail:cn})),onCorrectResponsesPopulated:cn=>Zr(new CustomEvent("correct-responses-populated",{detail:cn}))}),cn=>Fe(it,cn,!0),()=>A(it))}}),fs(pe),Ro(()=>Bc(pe,1,`pie-player-item-container ${A(qe)??""}`,"svelte-r0yfjj")),oo(P,pe)};return su(dc,P=>{A(Ae)?P(gf):A(le)||!A(we)?P(vf,1):P(Ma,-1)}),fs(pi),au(pi,P=>Fe(Be,P),()=>A(Be)),Ro(()=>Bc(pi,1,`pie-item-player ${A(H)??""} ${A(de)??""}`,"svelte-r0yfjj")),oo(e,pi),gm(cc)}Yb(MR,{config:{attribute:"config",type:"Object"},session:{attribute:"session",type:"Object"},env:{attribute:"env",type:"Object"},addCorrectResponse:{attribute:"add-correct-response",type:"Boolean"},showBottomBorder:{attribute:"show-bottom-border",type:"Boolean"},hosted:{attribute:"hosted",type:"Boolean"},debug:{attribute:"debug",type:"String"},customClassName:{attribute:"custom-class-name",type:"String"},customClassname:{attribute:"custom-classname",type:"String"},containerClass:{attribute:"container-class",type:"String"},passageContainerClass:{attribute:"passage-container-class",type:"String"},externalStyleUrls:{attribute:"external-style-urls",type:"String"},renderStimulus:{attribute:"render-stimulus",type:"Boolean"},allowedResize:{attribute:"allowed-resize",type:"Boolean"},autoplayAudioEnabled:{attribute:"autoplay-audio-enabled",type:"Boolean"},baseHeadingLevel:{attribute:"base-heading-level",reflect:!0,type:"Number"},includeSrHeading:{attribute:"include-sr-heading",reflect:!0,type:"Boolean"},locale:{attribute:"locale",type:"String"},bundleHost:{attribute:"bundle-host",type:"String"},bundleEndpoints:{attribute:"bundle-endpoints",type:"Object"},disableBundler:{attribute:"disable-bundler",type:"Boolean"},reFetchBundle:{attribute:"re-fetch-bundle",type:"Boolean"},loaderConfig:{attribute:"loader-config",type:"Object"},strategy:{attribute:"strategy",type:"String"},mode:{attribute:"mode",type:"String"},configuration:{attribute:"configuration",type:"Object"},authoringBackend:{attribute:"authoring-backend",type:"String"},backend:{type:"Object"},sessionSnapshot:{attribute:"session-snapshot",type:"Object"},allowedStyleOrigins:{attribute:"allowed-style-origins",type:"String"},loaderOptions:{type:"Object"},trustMarkup:{attribute:"trust-markup",type:"Boolean"},sanitizeMarkup:{type:"Object"},onInsertImage:{type:"Object"},onDeleteImage:{type:"Object"},onInsertSound:{type:"Object"},onDeleteSound:{type:"Object"}},[],["loadFromBackend","getPendingSessionSnapshot","commitPendingElementSessions","saveSession","score","saveContent","releaseContent","provideScore","updateElementModel","validateModels"],void 0,mj);Ej(Bj,"pie-item-player");Rj("pie-item-player");var ZH="pie-item-player";function YH(e=ZH){const t=yP(e,MR.element,"pie-item-player tagName",{allowWrappedFallback:!0});if(t.outcome==="error"||t.outcome==="wrapped-error")throw t.error}YH();var Rh=class extends Error{constructor(e,t){super(Sm(t)),this.name="PreloadStageError",this.stage=e,this.cause=t}};function $R(e){return Ys(e,()=>Yl())}function dy(e,t){return String(e?.mode??"").toLowerCase()==="author"||t?.mode==="author"}function LR(e,t){const r=e?.loaderOptions?.view;return typeof r=="string"&&r?r:dy(e,t)?"author":"delivery"}function JH(e){const t=r=>{const n=r.config?.elements||{};return!n||typeof n!="object"?"":Object.entries(n).filter(([i,o])=>typeof i=="string"&&i.trim().length>0&&typeof o=="string"&&o.trim().length>0).sort(([i],[o])=>i.localeCompare(o)).map(([i,o])=>`${i}=${o}`).join(",")};return e.map((r,n)=>{const i=r?.entity||{};return`${typeof i.id=="string"&&i.id||`renderable-${n}`}:${typeof i.version=="string"&&i.version||(typeof i.version=="number"?String(i.version):"")||(typeof i.config?.version=="string"?i.config.version:"")}:${t(i)}`}).join("|")}function uy(e,t){return`Error loading elements (${e}): ${Sm(t)}`}function Sm(e){return e instanceof Error?e.message:String(e)}function QH(e){for(const[t,r]of e.entries())try{RM(r?.config)}catch(n){const i=typeof r?.id=="string"?r.id:`renderable-${t}`,o=Sm(n);throw new Error(`${i}: ${o}`)}}function ez(e,t){for(const[r,n]of e.entries()){const i=typeof n?.id=="string"?n.id:`renderable-${r}`,o=AT(n?.config).warnings,s=Array.isArray(o)?o.filter(a=>typeof a=="string"):[];for(const a of s)t.warn(uy("validate-config",`${i}: ${a}`))}}function fy(e){const t=e.resolvedPlayerProps?.loaderOptions,r=e.resolvedPlayerProps?.loaderConfig,n={trackPageActions:r?.trackPageActions,instrumentationProvider:ud({player:{loaderConfig:r},component:"pie-section-player"})};if(e.strategy==="esm"){const s=tz(t?.esmCdnProvider),a=LR(e.resolvedPlayerProps,e.resolvedPlayerEnv);return{kind:"esm",cdnBaseUrl:String(t?.esmCdnUrl||"https://cdn.jsdelivr.net/npm"),cdnProvider:s,moduleResolution:t?.moduleResolution==="import-map"?"import-map":"url",view:a,loadControllers:WO({loadControllers:typeof t?.loadControllers=="boolean"?t.loadControllers:void 0,author:dy(e.resolvedPlayerProps,e.resolvedPlayerEnv),hosted:e.resolvedPlayerProps?.hosted===!0}),...n}}const i=String(t?.bundleHost||e.iifeBundleHost||"").trim();if(!i)throw new Error("Missing iifeBundleHost for element preloading");const o=dy(e.resolvedPlayerProps,e.resolvedPlayerEnv)?$s.editor:e.resolvedPlayerProps?.hosted===!0?$s.player:$s.clientPlayer;return{kind:"iife",bundleHost:i,bundleType:o,needsControllers:o!==$s.player,bundleRetry:r?.iifeBundleRetry,onBundleRetryStatus:e.onBundleRetryStatus,...n}}function tz(e){if(typeof e=="string")return e;if(!e||typeof e!="object")return;const t=e;return typeof t.name=="string"&&typeof t.packageJsonUrl=="function"&&typeof t.browserViewUrl=="function"&&typeof t.browserControllerUrl=="function"&&typeof t.sharedDependencyUrl=="function"?e:void 0}function Q1(e){return!e||e.kind!=="iife"?null:e.bundleType?String(e.bundleType):null}function eI(e){return!e||e.kind!=="iife"?"":e.bundleHost}async function rz(e){const t=e.logger??$R("pie-section-player-items-pane");try{QH(e.renderables),ez(e.renderables,t)}catch(s){throw new Rh("validate-config",s)}if(e.renderables.length===0)return;const r=e.resolvedPlayerProps?.loaderOptions?.elementPackagePolicy;if(e.strategy==="preloaded"){try{const s=T0(e.renderables.map(nz));ZT(s,r);const a=LR(e.resolvedPlayerProps,e.resolvedPlayerEnv)==="author"?Object.fromEntries(Object.entries(s).map(([l,d])=>[Q_(l,"author"),d])):s;GO(a),PO(a)}catch(s){throw new Rh("preloaded-assert",s)}return}const n=T0(e.renderables),i=fy({strategy:e.strategy,resolvedPlayerProps:e.resolvedPlayerProps,resolvedPlayerEnv:e.resolvedPlayerEnv,iifeBundleHost:e.iifeBundleHost,onBundleRetryStatus:e.onBundleRetryStatus}),o=e.strategy==="esm"?"esm-load":"iife-load";try{e.strategy==="iife"&&await IP(),await xO(n,{backend:i,elementPackagePolicy:r})}catch(s){throw new Rh(o,s)}}function nz(e){const t=e?.config;if(!t)return e;const r=UO(t);return r===t?e:{...e,config:r}}function aw(){return{phase:"idle",cohort:null,controllerResolved:!1,readinessSignals:{sectionReady:!1,interactionReady:!1,allLoadingComplete:!1,runtimeError:!1},effectiveRuntime:null,effectiveToolsConfig:null,loadingCompleteEmitted:!1,lastFrameworkError:null,itemCount:0,loadedCount:0}}function hy(e,t){return e===t?!0:!e||!t?!1:e.sectionId===t.sectionId&&e.attemptId===t.attemptId}function iz(e){const t=e.sectionId??"";return t?{sectionId:t,attemptId:e.attemptId??""}:null}function oz(e){return e.runtimeError?"error":e.allLoadingComplete?"ready":e.interactionReady?"interaction-ready":e.sectionReady?"loading":"bootstrapping"}function OR(e){const t=e.signals.sectionReady&&e.signals.allLoadingComplete,r=e.mode==="strict"?t:e.signals.interactionReady;return{phase:oz({...e.signals,allLoadingComplete:t,interactionReady:r}),interactionReady:r,allLoadingComplete:t,reason:e.reason}}function sz(e){switch(e){case"idle":return null;case"booting-section":return"composed";case"engine-ready":return"engine-ready";case"interactive":return"interactive";case"disposed":return"disposed"}}function $p(e,t,r,n="entered"){const i=sz(t);i&&e.push({kind:"stage-change",stage:i,status:n,cohort:r})}function tI(e){const t={...aw(),phase:"booting-section",cohort:e.cohort,effectiveRuntime:e.effectiveRuntime,effectiveToolsConfig:e.effectiveToolsConfig,itemCount:e.itemCount},r=[];return $p(r,"booting-section",e.cohort),{state:t,outputs:r}}function az(e,t){if(e.phase==="idle"||e.phase==="disposed")return{state:e,outputs:[]};const r=OR({mode:t.mode,signals:t.signals}),n=[];let i=e.phase,o=e.loadingCompleteEmitted;return i==="engine-ready"&&r.interactionReady&&(i="interactive",$p(n,i,e.cohort)),r.allLoadingComplete&&e.cohort&&!o&&(o=!0,n.push({kind:"loading-complete",cohort:e.cohort,itemCount:t.itemCount,loadedCount:t.loadedCount})),{state:{...e,phase:i,readinessSignals:t.signals,loadedCount:t.loadedCount,itemCount:t.itemCount,loadingCompleteEmitted:o},outputs:n}}function _h(e,t){switch(t.kind){case"initialize":return e.phase==="disposed"?{state:e,outputs:[]}:e.phase!=="idle"?hy(e.cohort,t.cohort)?_h(e,{kind:"update-runtime",effectiveRuntime:t.effectiveRuntime,effectiveToolsConfig:t.effectiveToolsConfig}):_h(e,{kind:"cohort-change",cohort:t.cohort,effectiveRuntime:t.effectiveRuntime,effectiveToolsConfig:t.effectiveToolsConfig,itemCount:t.itemCount}):tI({state:e,cohort:t.cohort,effectiveRuntime:t.effectiveRuntime,effectiveToolsConfig:t.effectiveToolsConfig,itemCount:t.itemCount});case"update-runtime":return e.phase==="idle"||e.phase==="disposed"?{state:e,outputs:[]}:{state:{...e,effectiveRuntime:t.effectiveRuntime,effectiveToolsConfig:t.effectiveToolsConfig},outputs:[]};case"cohort-change":{if(e.phase==="disposed")return{state:e,outputs:[]};if(hy(e.cohort,t.cohort))return _h(e,{kind:"update-runtime",effectiveRuntime:t.effectiveRuntime,effectiveToolsConfig:t.effectiveToolsConfig});const r=[];e.phase!=="idle"&&r.push({kind:"stage-change",stage:"disposed",status:"entered",cohort:e.cohort});const n=tI({state:e,cohort:t.cohort,effectiveRuntime:t.effectiveRuntime,effectiveToolsConfig:t.effectiveToolsConfig,itemCount:t.itemCount});return{state:n.state,outputs:[...r,...n.outputs]}}case"section-controller-resolved":{if(e.phase!=="booting-section")return{state:{...e,controllerResolved:!0},outputs:[]};const r=[];return $p(r,"engine-ready",e.cohort),{state:{...e,phase:"engine-ready",controllerResolved:!0},outputs:r}}case"update-readiness-signals":return az(e,{signals:t.signals,mode:t.mode,loadedCount:t.loadedCount,itemCount:t.itemCount});case"framework-error":return{state:{...e,lastFrameworkError:t.error,readinessSignals:{...e.readinessSignals,runtimeError:t.error.recoverable===!0?e.readinessSignals.runtimeError:!0}},outputs:[{kind:"framework-error",error:t.error}]};case"dispose":{if(e.phase==="disposed")return{state:e,outputs:[]};const r=[];return e.phase!=="idle"&&$p(r,"disposed",e.cohort),{state:{...e,phase:"disposed"},outputs:r}}default:return{state:e,outputs:[]}}}var lz=class{constructor(){T(this,"state",aw()),T(this,"listeners",new Set)}getState(){return this.state}dispatch(e){const t=_h(this.state,e);return this.state=t.state,t.outputs.length>0&&this.fanOut(t.outputs),t.outputs}subscribe(e){this.listeners.add(e);let t=!0;return()=>{t&&(t=!1,this.listeners.delete(e))}}disposeListeners(){this.listeners.clear()}fanOut(e){const t=Array.from(this.listeners),r=Object.freeze(e.slice());for(const n of t)try{n(r)}catch(i){console.warn("[SectionEngineCore] listener failed:",i)}}};function cz(e){const{coordinator:t,dispatchCoreInput:r}=e;let n=0,i=null,o=null,s=!1;const a=t.subscribeFrameworkErrors(u=>{try{r({kind:"framework-error",error:u})}catch(f){console.warn("[CoordinatorBridge] framework-error dispatch failed:",f)}});function l(){if(o){try{o()}catch(u){console.warn("[CoordinatorBridge] controller unsubscribe failed:",u)}o=null}}async function d(u){if(s)return;n+=1;const f=n;i=u.cohort;const p=await t.getOrCreateSectionController({sectionId:u.cohort.sectionId,attemptId:u.cohort.attemptId||void 0,input:{section:u.section,sectionId:u.cohort.sectionId,assessmentId:u.assessmentId,view:u.view},updateExisting:!0,createDefaultController:u.createDefaultController});if(f!==n||s)return;l(),u.onControllerResolved?.(p);const g=p.getCompositionModel;u.onCompositionChanged?.(g?.()),typeof p.subscribe=="function"&&(o=p.subscribe(v=>{f!==n||s||u.onCompositionChanged?.(g?.())})),r({kind:"section-controller-resolved"})}async function c(){if(s)return;s=!0,n+=1,l();try{a()}catch(f){console.warn("[CoordinatorBridge] framework-error unsubscribe failed:",f)}const u=i;if(i=null,u)try{await t.disposeSectionController({sectionId:u.sectionId,attemptId:u.attemptId||void 0})}catch(f){console.warn("[CoordinatorBridge] section-controller dispose failed:",f)}}return{resolveSectionController:d,dispose:c}}function dz(e){const{runtimeId:t,sourceCe:r}=e;let n=e.host;const i=e.now??(()=>new Date().toISOString());function o(c){const u={stage:c.stage,status:c.status,runtimeId:t,sectionId:c.cohort?.sectionId,attemptId:c.cohort?.attemptId?c.cohort.attemptId:void 0,timestamp:i(),sourceCe:r};n.dispatchEvent(new CustomEvent("pie-stage-change",{detail:u}))}function s(c){const u={runtimeId:t,sectionId:c.cohort.sectionId,attemptId:c.cohort.attemptId?c.cohort.attemptId:void 0,itemCount:c.itemCount,loadedCount:c.loadedCount,timestamp:i(),sourceCe:r};n.dispatchEvent(new CustomEvent("pie-loading-complete",{detail:u}))}function a(c){n.dispatchEvent(new CustomEvent("framework-error",{detail:c.error}))}function l(c){switch(c.kind){case"stage-change":o(c);return;case"loading-complete":s(c);return;case"framework-error":a(c);return;default:return}}function d(c){n=c}return{dispatch:l,setHost:d}}function uz(e){const{bus:t}=e;function r(n){switch(n.kind){case"framework-error":t.reportFrameworkError(n.error);return;case"stage-change":case"loading-complete":return;default:return}}return{dispatch:r}}function fz(e={}){let t=e.hook;function r(i){if(t)try{t(i)}catch(o){console.warn("[InstrumentationBridge] hook failed:",o)}}function n(i){t=i}return{dispatch:r,setHook:n}}function hz(){const e=new Set;function t(o){if(o.length===0)return;const s=Array.from(e),a=Object.freeze(o.slice());for(const l of s)try{l(a)}catch(d){console.warn("[SubscriberFanout] listener failed:",d)}}function r(o){e.add(o);let s=!0;return()=>{s&&(s=!1,e.delete(o))}}function n(){e.clear()}function i(){return e.size}return{emit:t,subscribe:r,dispose:n,getListenerCount:i}}var pz=class{constructor(e){T(this,"core",void 0),T(this,"domEventBridge",void 0),T(this,"frameworkErrorBridge",void 0),T(this,"instrumentationBridge",void 0),T(this,"subscriberFanout",void 0),T(this,"coordinatorBridge",void 0),T(this,"unsubscribeCore",void 0),T(this,"disposed",!1),this.core=e.core??new lz,this.domEventBridge=dz({host:e.host,runtimeId:e.runtimeId,sourceCe:e.sourceCe,now:e.now}),this.frameworkErrorBridge=uz({bus:e.frameworkErrorBus}),this.instrumentationBridge=fz({hook:e.instrumentationHook}),this.subscriberFanout=hz(),this.coordinatorBridge=e.coordinator?cz({coordinator:e.coordinator,dispatchCoreInput:t=>this.dispatchInput(t)}):null,this.unsubscribeCore=this.core.subscribe(t=>{this.routeOutputs(t)})}getState(){return this.core.getState()}dispatchInput(e){return this.disposed?[]:this.core.dispatch(e)}subscribe(e){return this.subscriberFanout.subscribe(e)}setHost(e){this.domEventBridge.setHost(e)}setInstrumentationHook(e){this.instrumentationBridge.setHook(e)}resolveSectionController(e){if(!this.coordinatorBridge)throw new Error("[SectionEngineAdapter] resolveSectionController called without a coordinator.");return this.coordinatorBridge.resolveSectionController(e)}async dispose(){this.disposed||(this.disposed=!0,this.core.dispatch({kind:"dispose"}),this.unsubscribeCore(),this.subscriberFanout.dispose(),this.coordinatorBridge&&await this.coordinatorBridge.dispose())}routeOutputs(e){for(const t of e)this.routeOne(t);this.subscriberFanout.emit(e)}routeOne(e){switch(e.kind){case"stage-change":case"loading-complete":this.domEventBridge.dispatch(e);break;case"framework-error":this.domEventBridge.dispatch(e),this.frameworkErrorBridge.dispatch(e);break;default:return}this.instrumentationBridge.dispatch(e)}},rI="section-demo-direct";var NR={mode:"gather",role:"student"};function sh(e,t){return e!==void 0?e:t}function DR(e){const t=e.runtime??{};return t.onFrameworkError!==void 0?t.onFrameworkError:e.onFrameworkError}function mz(e){const t=e.runtime?.tools||{},r=t.placement||{};return{...t,placement:{...r}}}function gz(e){const t=e.runtime||{},r=t.player?{...t.player}:null;return{...t,assessmentId:sh(t.assessmentId,e.assessmentId),playerType:t.playerType??"iife",player:r,lazyInit:t.lazyInit??!0,accessibility:t.accessibility??null,coordinator:t.coordinator??null,createSectionController:t.createSectionController,isolation:t.isolation??"inherit",env:t.env??NR,toolConfigStrictness:sh(t.toolConfigStrictness,e.toolConfigStrictness)??"error",onFrameworkError:DR({runtime:e.runtime,onFrameworkError:e.onFrameworkError}),onStageChange:sh(t.onStageChange,e.onStageChange),onLoadingComplete:sh(t.onLoadingComplete,e.onLoadingComplete),tools:e.effectiveToolsConfig}}function jR(e,t){const r=e.assessmentId??"section-demo-direct",n=mz({runtime:e.runtime}),i=gz({assessmentId:r,runtime:e.runtime,effectiveToolsConfig:n,toolConfigStrictness:e.toolConfigStrictness,onFrameworkError:e.onFrameworkError,onStageChange:e.onStageChange,onLoadingComplete:e.onLoadingComplete});return{effectiveToolsConfig:n,effectiveRuntime:i,playerRuntime:t.resolvePlayerRuntime({effectiveRuntime:i,playerType:String(i.playerType??"iife"),env:i.env??null})}}var nI={iife:{tagName:"pie-item-player",ensureDefined:()=>Promise.resolve(),attributes:{strategy:"iife"},props:{loaderOptions:{bundleHost:_M}}},esm:{tagName:"pie-item-player",ensureDefined:()=>Promise.resolve(),attributes:{strategy:"esm"},props:{loaderOptions:{esmCdnUrl:PM}}},preloaded:{tagName:"pie-item-player",ensureDefined:()=>Promise.resolve(),attributes:{strategy:"preloaded"}}};function vz(e){return e.hosted!==void 0}function yz(e){const t=e.backend;return!!t?.delivery&&t.delivery.enabled!==!1}function bz(e){const t=String(e.effectiveRuntime?.playerType||e.playerType||"iife"),r=nI[t]||nI.iife,n=r?.tagName||"pie-item-player",i=r?.attributes||{},o=r?.props||{},s=e.effectiveRuntime?.player||{},a=o.loaderOptions||{},l=s.loaderOptions||{},d=!vz(s)&&yz(s)?{hosted:!0}:{};return{effectivePlayerType:t,resolvedPlayerDefinition:r,resolvedPlayerTag:n,resolvedPlayerAttributes:i,resolvedPlayerProps:{...o,...d,...s,loaderOptions:{...a,...l}},resolvedPlayerEnv:e.effectiveRuntime?.env||e.env||{},strategy:hL(i?.strategy||t,"iife")}}function wz(e){return e.map(t=>t?.entity)}function Sz(e){return jR(e,{resolvePlayerRuntime:bz})}function lw(e,t){const r={};return t.ndsIcons!==void 0&&(r.ndsIcons=t.ndsIcons),t.locale&&(r.locale=t.locale),Object.keys(r).length===0?e:{...r,...e??{}}}function py(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Gs(e){return e&&{...e}}function Iz(e){return e&&typeof e=="object"&&!Array.isArray(e)?{...e}:e}function od(e){return e&&Object.fromEntries(Object.entries(e).map(([t,r])=>[t,Iz(r)]))}function fa(e){if(e)return{...e,auth:Gs(e.auth),endpoints:od(e.endpoints),request:e.request?{...e.request,headers:e.request.headers?{...e.request.headers}:void 0}:void 0,options:e.options?{...e.options,overrides:e.options.overrides?{...e.options.overrides}:void 0}:void 0,autosave:e.autosave&&typeof e.autosave=="object"?{...e.autosave}:e.autosave,client:e.client?{...e.client}:void 0}}function Xd(e){if(e)return{...e,auth:Gs(e.auth),endpoints:od(e.endpoints),request:e.request?{...e.request,headers:e.request.headers?{...e.request.headers}:void 0}:void 0,media:e.media?{...e.media}:void 0,client:e.client?{...e.client}:void 0}}function _u(e){return{...e,auth:Gs(e.auth),delivery:fa(e.delivery),authoring:Xd(e.authoring)}}function kz(e,t){if(!e)return fa(t);if(!t)return fa(e);const r=e.client,n=t.client,i=r||n?{...r||{},...n||{}}:void 0;return{...fa(e),...fa(t),auth:t.auth?Gs(t.auth):Gs(e.auth),endpoints:{...od(e.endpoints)||{},...od(t.endpoints)||{}},request:e.request||t.request?{...e.request||{},...t.request||{},headers:{...e.request?.headers||{},...t.request?.headers||{}}}:void 0,options:e.options||t.options?{...e.options||{},...t.options||{},overrides:{...e.options?.overrides||{},...t.options?.overrides||{}}}:void 0,autosave:t.autosave!==void 0?fa({autosave:t.autosave})?.autosave:fa({autosave:e.autosave})?.autosave,client:i}}function Tz(e,t){return e?t?{...Xd(e),...Xd(t),auth:t.auth?Gs(t.auth):Gs(e.auth),endpoints:{...od(e.endpoints)||{},...od(t.endpoints)||{}},request:e.request||t.request?{...e.request||{},...t.request||{},headers:{...e.request?.headers||{},...t.request?.headers||{}}}:void 0,media:e.media||t.media?{...e.media||{},...t.media||{}}:void 0,client:e.client||t.client?{...e.client||{},...t.client||{}}:void 0}:Xd(e):Xd(t)}function Ez(e,t){return{..._u(e),..._u(t),auth:t.auth?Gs(t.auth):Gs(e.auth),delivery:kz(e.delivery,t.delivery),authoring:Tz(e.authoring,t.authoring)}}function Cz(e){const t=_u(e.backend);if(!t.delivery||t.delivery.enabled===!1)return t;const r=fa(t.delivery);r.itemId=e.canonicalItemId||e.itemId;const n=e.itemSession?.id;return typeof n=="string"&&n?r.sessionId=n:delete r.sessionId,t.delivery=r,t}function xz(e){const{backend:t,resolveBackend:r,...n}=e.resolvedPlayerProps;if(!t||!py(t))return n;const i=String(e.item?.id||""),o=Cz({backend:t,itemId:i,canonicalItemId:e.canonicalItemId,itemSession:e.itemSession});let s=o;if(typeof r=="function"){const a=_u(o),l=r({itemId:i,canonicalItemId:e.canonicalItemId,item:e.item,itemIndex:e.itemIndex??0,itemSession:e.itemSession,sectionId:e.sectionId,env:e.env,baseBackend:a},a);l&&py(l)&&(s=Ez(o,l))}return{...n,backend:s}}function Rz(e){const{backend:t,resolveBackend:r,...n}=e;if(!t||!py(t))return n;const{delivery:i,...o}=_u(t);return Object.keys(o).length===0?n:{...n,backend:o}}var _z=4,iI=new Set;function cw(e){const t=typeof e=="number"?e:Number.parseInt(String(e??""),10);return!Number.isInteger(t)||t<1||t>6?2:(t>_z&&!iI.has(t)&&(iI.add(t),console.warn(`[pie-section-player] baseHeadingLevel=${t} leaves no room to nest: passage sub-content clamps at h6 and the outline flattens. Levels 1-4 keep the full structure.`)),t)}function Pz(e){return{baseHeadingLevel:e,includeSrHeading:!1}}function Az(e){return{baseHeadingLevel:Math.min(6,e+1)}}function Mz(e){return e.detail?.composition||bC}function BR(e){const t=wz(e.renderables||[]);return{compositionModel:e,passages:e.passages||[],items:e.items||[],renderables:t,renderablesSignature:JH(e.renderables||[])}}function $z(e){return BR(Mz(e))}function Lz(e){return{config:e.passage.config||{},env:e.resolvedPlayerEnv,attributes:{...e.resolvedPlayerAttributes||{},strategy:e.playerStrategy},props:{...Az(e.baseHeadingLevel??2),...Rz(e.resolvedPlayerProps||{})}}}function Oz(e){const t=e.compositionModel?.formative;if(!t?.enabled)return null;const r=t.policies?.[e.canonicalItemId];return r?.enabled?kD({policy:r,state:t.states?.[e.canonicalItemId]}):null}function Nz(e){const t=e.compositionModel?.timedMedia;if(!t)return null;const r=t.sequencedItemIds.includes(e.canonicalItemId)&&!t.revealedItemIds.includes(e.canonicalItemId),n=t.gate,i=n?.holding===!0&&n.itemRefs.includes(e.canonicalItemId);return{pending:r,isGateTarget:i,gateEnforced:i&&n?.enforcement==="enforced"}}function Dz(e,t){const r=t?.envOverride;return r?{...e,...r}:e}function jz(e){const t=Array.isArray(e.data)?e.data:[];return{...e,data:t.map(r=>r&&typeof r=="object"?{...r}:r)}}function Bz(e){const t=SC(e.compositionModel,e.item),r=$D(e.compositionModel,e.item),n=wC(e.compositionModel,e.item),i=Dz(e.resolvedPlayerEnv,e.formativeView);return{config:e.item.config||{},env:i,session:jz(r),attributes:{...e.resolvedPlayerAttributes||{},strategy:e.playerStrategy},props:xz({resolvedPlayerProps:{...Pz(e.baseHeadingLevel??2),...e.resolvedPlayerProps||{}},item:e.item,canonicalItemId:n,itemSession:t&&typeof t=="object"?t:void 0,itemIndex:e.itemIndex,sectionId:e.compositionModel.section?.identifier,env:e.resolvedPlayerEnv})}}function oI(e){return wC(e.compositionModel,e.item)}var FR=Zl(Symbol.for("@pie-players/pie-section-player/card-render-context"));function Pu(e){if(!e)return null;const t=e.getRootNode();return t&&"host"in t?t.host:e.parentElement}function HR(e,t){return $u(e,FR,t)}function Fz(e,t){const r=new Ws(e,{context:FR,initialValue:t});r.connect();const n=new Bl(e);return n.attach(),{setValue:i=>r.setValue(i),disconnect:()=>{n.detach(),r.disconnect()}}}var sI="content-media",zR="content-lead";function Au(e,t=20,r=55){return Number.isFinite(e)?Math.max(t,Math.min(r,e)):34}function Hz(e){const t=e.containerWidthPx;if(!Number.isFinite(t)||t<=0)return Au(e.startPercent,e.min,e.max);const r=e.deltaX/t*100;return Au(e.startPercent-r,e.min,e.max)}var zz=Ht('<div role="separator" aria-orientation="vertical" tabindex="0"><span class="pie-section-player-card-split-divider__handle svelte-xekreg"></span></div>'),Wz={hash:"svelte-xekreg",code:`.pie-section-player-card-split-divider.svelte-xekreg {align-self:stretch;position:relative;display:flex;align-items:center;justify-content:center;
1115
+ /* Wide enough for a 24px pointer target while the visible rule stays
1116
+ hairline; the grid track is sized to match. */min-width:24px;cursor:col-resize;background:transparent;user-select:none;touch-action:none;}.pie-section-player-card-split-divider.svelte-xekreg:focus {outline:none;}.pie-section-player-card-split-divider.svelte-xekreg:focus-visible {outline:3px solid var(--pie-section-player-focus-outline, var(--pie-focus-outline, #146eb3));outline-offset:-2px;border-radius:999px;}.pie-section-player-card-split-divider__handle.svelte-xekreg {width:4px;height:48px;max-height:60%;border-radius:2px;background:var(--pie-border-light, #e5e7eb);transition:background 0.2s ease;pointer-events:none;}.pie-section-player-card-split-divider.svelte-xekreg:hover .pie-section-player-card-split-divider__handle:where(.svelte-xekreg),
1117
+ .pie-section-player-card-split-divider.svelte-xekreg:focus-visible .pie-section-player-card-split-divider__handle:where(.svelte-xekreg),
1118
+ .pie-section-player-card-split-divider--dragging.svelte-xekreg .pie-section-player-card-split-divider__handle:where(.svelte-xekreg) {background:var(--pie-section-player-focus-outline, var(--pie-focus-outline, #146eb3));}
1119
+
1120
+ @media (prefers-reduced-motion: reduce) {.pie-section-player-card-split-divider__handle.svelte-xekreg {transition:none;}
1121
+ }`};function WR(e,t){un(t,!0),Mn(e,Wz);let r=_(t,"value",7,34),n=_(t,"min",7,20),i=_(t,"max",7,55),o=_(t,"step",7,5),s=_(t,"container",7,null),a=_(t,"ariaLabel",7,"Resize media region"),l=_(t,"ariaControls",7,""),d=_(t,"ariaValueText",7,""),c=_(t,"onresize",7,(M,U)=>{}),u=He(!1),f=0,p=0,g=0,v=0;function b(M){M.button!==0&&M.pointerType==="mouse"||(M.preventDefault(),be(u,!0),f=M.clientX,p=r(),v=r(),g=s()?.getBoundingClientRect().width??0,M.currentTarget?.setPointerCapture?.(M.pointerId))}function w(M){h(u)&&c()(Hz({startPercent:p,deltaX:M.clientX-f,containerWidthPx:g,min:n(),max:i()}),"pointer")}function I(){h(u)&&be(u,!1)}function x(){h(u)&&(be(u,!1),c()(Au(v,n(),i()),"pointer"))}function C(M){if(M.key!=="ArrowLeft"&&M.key!=="ArrowRight"&&M.key!=="Home"&&M.key!=="End"&&M.key!=="Escape")return;if(M.preventDefault(),M.key==="Escape"){x();return}let U=r();M.key==="Home"?U=i():M.key==="End"?U=n():U=Au(r()+(M.key==="ArrowLeft"?o():-o()),n(),i()),c()(U,"keyboard")}ct(()=>{if(!(!h(u)||typeof window>"u"))return window.addEventListener("pointermove",w),window.addEventListener("pointerup",I),window.addEventListener("pointercancel",x),()=>{window.removeEventListener("pointermove",w),window.removeEventListener("pointerup",I),window.removeEventListener("pointercancel",x)}});var L={get value(){return r()},set value(M=34){r(M),R()},get min(){return n()},set min(M=20){n(M),R()},get max(){return i()},set max(M=55){i(M),R()},get step(){return o()},set step(M=5){o(M),R()},get container(){return s()},set container(M=null){s(M),R()},get ariaLabel(){return a()},set ariaLabel(M="Resize media region"){a(M),R()},get ariaControls(){return l()},set ariaControls(M=""){l(M),R()},get ariaValueText(){return d()},set ariaValueText(M=""){d(M),R()},get onresize(){return c()},set onresize(M=(U,te)=>{}){c(M),R()}},E=zz();return q(M=>{gn(E,1,`pie-section-player-card-split-divider ${h(u)?"pie-section-player-card-split-divider--dragging":""}`,"svelte-xekreg"),nt(E,"aria-label",a()),nt(E,"aria-controls",l()||void 0),nt(E,"aria-valuemin",n()),nt(E,"aria-valuemax",i()),nt(E,"aria-valuenow",M),nt(E,"aria-valuetext",d()||void 0)},[()=>Math.round(r())]),lo("pointerdown",E,b),lo("keydown",E,C),ft(e,E),fn(L)}cd(["pointerdown","keydown"]);In(WR,{value:{},min:{},max:{},step:{},container:{},ariaLabel:{},ariaControls:{},ariaValueText:{},onresize:{}},[],[],{mode:"open"});var Uz={calculator:'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M7 2h10a2 2 0 0 1 2 2v16a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2Zm0 2v4h10V4H7Zm0 6v2h2v-2H7Zm4 0v2h2v-2h-2Zm4 0v2h2v-2h-2Zm-8 4v2h2v-2H7Zm4 0v2h2v-2h-2Zm4 0v2h2v-2h-2Zm-8 4v2h2v-2H7Zm4 0v2h2v-2h-2Zm4 0v2h2v-2h-2Z" fill="currentColor"/></svg>',"volume-up":'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M14 3.23v2.06A7.002 7.002 0 0 1 19 12a7 7 0 0 1-5 6.71v2.06c4.01-.91 7-4.49 7-8.77s-2.99-7.86-7-8.77Zm-2 17.75V3L7 8H3v8h4l5 5Zm4.5-9a4.5 4.5 0 0 0-2.5-4.03v8.05A4.5 4.5 0 0 0 16.5 12Z" fill="currentColor"/></svg>',swatch:'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M12 3a9 9 0 1 0 9 9c0-.55-.45-1-1-1h-2.5a1.5 1.5 0 0 1 0-3H20a1 1 0 0 0 1-1 8.99 8.99 0 0 0-9-4Zm-5.5 9A1.5 1.5 0 1 1 8 13.5 1.5 1.5 0 0 1 6.5 12Zm3-4A1.5 1.5 0 1 1 11 9.5 1.5 1.5 0 0 1 9.5 8Zm5 0A1.5 1.5 0 1 1 16 9.5 1.5 1.5 0 0 1 14.5 8Z" fill="currentColor"/></svg>',"chart-bar":'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M4.75 5a.76.76 0 0 1 .75.75v11c0 .438.313.75.75.75h13a.76.76 0 0 1 .696 1.039.74.74 0 0 1-.696.461h-13C5 19 4 18 4 16.75v-11A.74.74 0 0 1 4.75 5ZM8 8.25a.74.74 0 0 1 .75-.75h6.5a.76.76 0 0 1 .696 1.039.74.74 0 0 1-.696.461h-6.5A.722.722 0 0 1 8 8.25Zm.75 2.25h4.5a.76.76 0 0 1 .696 1.039.74.74 0 0 1-.696.461h-4.5a.723.723 0 0 1-.75-.75.74.74 0 0 1 .75-.75Zm0 3h8.5a.76.76 0 0 1 .696 1.039.74.74 0 0 1-.696.461h-8.5a.723.723 0 0 1-.75-.75.74.74 0 0 1 .75-.75Z" fill="currentColor"/></svg>',beaker:'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M5 21c-.85 0-1.454-.38-1.813-1.137-.358-.759-.27-1.463.263-2.113L9 11V5H8a.968.968 0 0 1-.713-.287A.968.968 0 0 1 7 4c0-.283.096-.52.287-.712A.968.968 0 0 1 8 3h8c.283 0 .52.096.712.288.192.191.288.429.288.712s-.096.52-.288.713A.968.968 0 0 1 16 5h-1v6l5.55 6.75c.533.65.62 1.354.262 2.113C20.454 20.62 19.85 21 19 21H5Zm2-3h10l-3.4-4h-3.2L7 18Zm-2 1h14l-6-7.3V5h-2v6.7L5 19Z" fill="currentColor"/></svg>',protractor:'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="m6.75 21-.25-2.2 2.85-7.85a3.95 3.95 0 0 0 1.75.95l-2.75 7.55L6.75 21Zm10.5 0-1.6-1.55-2.75-7.55a3.948 3.948 0 0 0 1.75-.95l2.85 7.85-.25 2.2ZM12 11a2.893 2.893 0 0 1-2.125-.875A2.893 2.893 0 0 1 9 8c0-.65.188-1.23.563-1.737A2.935 2.935 0 0 1 11 5.2V3h2v2.2c.583.2 1.063.554 1.438 1.063C14.812 6.77 15 7.35 15 8c0 .833-.292 1.542-.875 2.125A2.893 2.893 0 0 1 12 11Zm0-2c.283 0 .52-.096.713-.287A.967.967 0 0 0 13 8a.967.967 0 0 0-.287-.713A.968.968 0 0 0 12 7a.968.968 0 0 0-.713.287A.967.967 0 0 0 11 8c0 .283.096.52.287.713.192.191.43.287.713.287Z" fill="currentColor"/></svg>',"bars-3":'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M6.85 15c.517 0 .98-.15 1.388-.45.408-.3.695-.692.862-1.175l.375-1.15c.267-.8.2-1.537-.2-2.213C8.875 9.337 8.3 9 7.55 9H4.025l.475 3.925c.083.583.346 1.075.787 1.475.442.4.963.6 1.563.6Zm10.3 0c.6 0 1.12-.2 1.563-.6.441-.4.704-.892.787-1.475L19.975 9h-3.5c-.75 0-1.325.342-1.725 1.025-.4.683-.467 1.425-.2 2.225l.35 1.125c.167.483.454.875.862 1.175.409.3.871.45 1.388.45Zm-10.3 2c-1.1 0-2.063-.363-2.887-1.088a4.198 4.198 0 0 1-1.438-2.737L2 9H1V7h6.55c.733 0 1.404.18 2.013.537A3.906 3.906 0 0 1 11 9h2.025c.35-.617.83-1.104 1.438-1.463A3.892 3.892 0 0 1 16.474 7H23v2h-1l-.525 4.175a4.198 4.198 0 0 1-1.438 2.737A4.238 4.238 0 0 1 17.15 17c-.95 0-1.804-.27-2.562-.813A4.234 4.234 0 0 1 13 14.026l-.375-1.125a21.35 21.35 0 0 1-.1-.363 4.926 4.926 0 0 1-.1-.537h-.85c-.033.2-.067.363-.1.488a21.35 21.35 0 0 1-.1.362L11 14a4.3 4.3 0 0 1-1.588 2.175A4.258 4.258 0 0 1 6.85 17Z" fill="currentColor"/></svg>',ruler:'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="m8.8 10.95 2.15-2.175-1.4-1.425-1.1 1.1-1.4-1.4 1.075-1.1L7 4.825 4.825 7 8.8 10.95Zm8.2 8.225L19.175 17l-1.125-1.125-1.1 1.075-1.4-1.4 1.075-1.1-1.425-1.4-2.15 2.15L17 19.175ZM7.25 21H3v-4.25l4.375-4.375L2 7l5-5 5.4 5.4 3.775-3.8c.2-.2.425-.35.675-.45a2.068 2.068 0 0 1 1.55 0c.25.1.475.25.675.45L20.4 4.95c.2.2.35.425.45.675.1.25.15.508.15.775a1.975 1.975 0 0 1-.6 1.425l-3.775 3.8L22 17l-5 5-5.375-5.375L7.25 21ZM5 19h1.4l9.8-9.775L14.775 7.8 5 17.6V19Z" fill="currentColor"/></svg>',"book-open":'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M12 6.25a6.6 6.6 0 0 0-2.3-1.32A8.6 8.6 0 0 0 7 4.5c-.63 0-1.25.06-1.85.18-.6.12-1.19.3-1.76.54a1.5 1.5 0 0 0-.93 1.4v10.1c0 .52.26.98.68 1.24.42.26.92.28 1.35.06.36-.18.75-.31 1.18-.4.42-.09.86-.13 1.33-.13.78 0 1.53.14 2.24.42.7.28 1.35.7 1.93 1.24l.83-.75.83.75c.58-.54 1.22-.96 1.93-1.24a6.1 6.1 0 0 1 2.24-.42c.47 0 .91.04 1.33.13.43.09.82.22 1.18.4.43.22.93.2 1.35-.06.42-.26.68-.72.68-1.24V6.62c0-.6-.36-1.15-.93-1.4a9.3 9.3 0 0 0-1.76-.54A9.8 9.8 0 0 0 17 4.5a8.6 8.6 0 0 0-2.7.43A6.6 6.6 0 0 0 12 6.25Zm1 10.06V8.02c.55-.5 1.16-.88 1.84-1.13A6 6 0 0 1 17 6.5c.45 0 .89.04 1.32.11.43.08.85.19 1.26.34v9.24a8.2 8.2 0 0 0-1.28-.24A10 10 0 0 0 17 15.85c-.72 0-1.42.09-2.09.26a7.7 7.7 0 0 0-1.91.8Zm-2 0a7.7 7.7 0 0 0-1.91-.8 8.4 8.4 0 0 0-2.09-.26c-.44 0-.87.02-1.3.07-.43.05-.86.13-1.28.24V6.95c.41-.15.83-.26 1.26-.34A7.7 7.7 0 0 1 7 6.5c.76 0 1.48.13 2.16.39.68.25 1.29.63 1.84 1.13Z" fill="currentColor"/></svg>',photo:'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M4 21c-.55 0-1.02-.2-1.41-.59A1.93 1.93 0 0 1 2 19V5c0-.55.2-1.02.59-1.41A1.93 1.93 0 0 1 4 3h16c.55 0 1.02.2 1.41.59.39.39.59.86.59 1.41v14c0 .55-.2 1.02-.59 1.41-.39.39-.86.59-1.41.59H4Zm0-2h16V5H4v14Zm1.5-2.5h13l-4.1-5.47-3.4 4.47-2.5-3.25L5.5 16.5ZM8.5 10a1.5 1.5 0 1 0 0-3 1.5 1.5 0 0 0 0 3Z" fill="currentColor"/></svg>'};function qz(e){return Uz[e]||null}var Vz=e=>e.pnpSupportIds?.length?e.pnpSupportIds:[e.toolId];function Gz(e,t){const r=Vz(e);for(const n of r){const i=t.policyFor(n);if(i.outcome==="denied")return{grant:null,denied:!0};if(i.outcome==="granted")return{grant:i,denied:!1}}return r.includes(e.toolId)?{grant:null,denied:!1}:{grant:null,denied:t.policyFor(e.toolId).outcome==="denied"}}function Kz(e,t){let r=null;try{const o=Gz(e,t);if(o.denied)return null;r=o.grant}catch(o){return t.onError?.(e,"policy",o),null}if(!r&&!e.resolvesWithoutGrant)return null;if(!e.requiresAuthoredContent)return r?{registration:e,featureId:r.featureId,parameters:r.parameters,content:null}:null;const n={featureId:r?.featureId??"",parameters:r?.parameters,catalogs:t.catalogs,granted:!!r};let i;try{i=e.requiresAuthoredContent.resolve(n)}catch(o){return t.onError?.(e,"content",o),null}return i==null?null:{registration:e,featureId:n.featureId,parameters:n.parameters,content:i}}function Xz(e){return e.registrations.flatMap(t=>{const r=Kz(t,e);return r?[r]:[]})}var Zz=["section","item","passage"];function UR(e){const t=new Set;function r(i,o){if(i===null||typeof i=="string"||typeof i=="boolean")return i;if(typeof i=="number")return Number.isFinite(i)?i:null;if(!(typeof i>"u")){if(typeof i=="function"||typeof i=="symbol")throw new TypeError(`${o} is not JSON-serializable`);if(typeof i=="bigint")throw new TypeError(`${o} is not JSON-serializable`);if(typeof i!="object")throw new TypeError(`${o} is not JSON-serializable`);if(t.has(i))throw new TypeError(`${o} contains a cycle`);t.add(i);try{if(Array.isArray(i))return i.map((d,c)=>r(d,`${o}[${c}]`)??null);const s=Object.getPrototypeOf(i);if(s!==Object.prototype&&s!==null)throw new TypeError(`${o} must contain only plain objects and arrays`);const a=i,l={};for(const d of Object.keys(a).sort()){const c=r(a[d],`${o}.${d}`);c!==void 0&&(l[d]=c)}return l}finally{t.delete(i)}}}const n=JSON.stringify(r(e,"content"));if(n===void 0)throw new TypeError("content is not JSON-serializable");return n}function qR(e,t){if(e.kind!==t.kind)return!1;if(e.kind==="section"&&t.kind==="section")return e.assessmentId===t.assessmentId&&e.sectionId===t.sectionId;if(e.kind==="content"&&t.kind==="content"){const r=e.ownerContext,n=t.ownerContext;return r.ownerKind===n.ownerKind&&r.assessmentId===n.assessmentId&&r.sectionId===n.sectionId&&r.canonicalItemId===n.canonicalItemId&&r.itemId===n.itemId&&r.passageId===n.passageId&&r.modelId===n.modelId}return!1}function Yz(e,t){return e.anchor===t.anchor&&e.surface===t.surface&&e.registry===t.registry&&e.services.toolkitCoordinator===t.services.toolkitCoordinator&&e.services.ttsService===t.services.ttsService&&e.services.catalogResolver===t.services.catalogResolver&&qR(e.scope,t.scope)}function Jz(e,t){return e.registry===t.registry&&e.services.toolkitCoordinator===t.services.toolkitCoordinator&&e.services.catalogResolver===t.services.catalogResolver&&qR(e.scope,t.scope)}function aI(e){try{return UR({toolId:e.toolId,featureId:e.featureId,surface:e.surface,parameters:e.parameters??null,content:e.content??null})}catch{return null}}function Qz(e,t){return e.contextSignature===null||t.contextSignature===null||e.contextSignature!==t.contextSignature?!1:e.context.services.toolkitCoordinator===t.context.services.toolkitCoordinator&&e.context.services.ttsService===t.context.services.ttsService&&e.context.services.catalogResolver===t.context.services.catalogResolver}function dw(e,t){const{hostLabel:r}=t;let n=null,i=!1,o={mountable:!1,occupied:!1},s=null,a=null,l=null,d=null;const c=new Map,u=new Map,f=new Map,p=new Set;function g(z){z.mountable===o.mountable&&z.occupied===o.occupied||(o=z,e({...z}))}function v(z,K,oe,ue){const ae=n,X=`${ae?.surface??"unknown"}\0${z}\0${K}\0${oe}`;if(p.has(X))return;p.add(X);const j=HT({kind:"tool-surface",severity:"warning",source:`${r}/tool-surface-host`,message:oe,details:[`surface=${ae?.surface??"unknown"}`,`toolId=${z}`,`phase=${K}`],recoverable:!0,cause:ue}),D=ae?.services.toolkitCoordinator;if(typeof D?.reportFrameworkError=="function")try{D.reportFrameworkError(j);return}catch(Z){console.warn(`[${r}] tool surface warning reporter failed:`,Z)}if(ae?.anchor&&typeof CustomEvent=="function"){ae.anchor.dispatchEvent(new CustomEvent("framework-error",{detail:j,bubbles:!0,composed:!0}));return}console.warn(`[${r}] ${oe}`,ue)}function b(z){const K=c.get(z);if(K){c.delete(z);try{K.destroy?.()}catch(oe){v(z,"destroy",`Tool "${z}" failed while leaving the "${n?.surface??"unknown"}" surface.`,oe)}finally{try{K.element.remove()}catch(oe){try{K.element.parentNode?.removeChild(K.element)}catch{}v(z,"destroy",`Tool "${z}" failed DOM removal from the "${n?.surface??"unknown"}" surface.`,oe)}}}}function w(){for(const z of[...c.keys()])b(z)}function I(z,K,oe){if(z.scope.kind!=="content")return null;const ue=z.services.toolkitCoordinator,[ae]=Xz({registrations:[K],catalogs:oe,policyFor:j=>{const D=ue?.decideFeaturePolicy?.(j);return iL(D)?{outcome:"denied"}:D?.granted===!0?{outcome:"granted",featureId:j,parameters:D.parameters}:{outcome:"silent"}},onError:(j,D,Z)=>{v(j.toolId,"resolve",D==="policy"?`Tool "${j.toolId}" failed policy resolution for the "${z.surface}" surface.`:`Tool "${j.toolId}" failed authored-content resolution for the "${z.surface}" surface.`,Z)}});if(!ae)return null;if(ae.content!==null)try{UR(ae.content)}catch(j){return v(K.toolId,"resolve",`Tool "${K.toolId}" failed authored-content resolution for the "${z.surface}" surface.`,j),null}const X={toolId:K.toolId,featureId:ae.featureId,surface:z.surface,parameters:ae.parameters,content:ae.content,services:z.services};return{registration:K,context:X,contextSignature:aI(X)}}function x(z,K){if(z.scope.kind!=="section")return null;if(K.requiresAuthoredContent)return v(K.toolId,"resolve",`Tool "${K.toolId}" declares authored content that the section-scoped "${z.surface}" surface cannot resolve.`),null;const oe=z.services.toolkitCoordinator;if(!oe)return null;const ue=K.pnpSupportIds?.length?K.pnpSupportIds:[K.toolId];let ae="",X;try{if(K.activation==="region"){for(const D of ue){const Z=oe.decideFeaturePolicy?.(D);if(Z?.granted===!0){ae=D,X=Z.parameters;break}}if(!ae)return null}else{const D=z.scope.sectionId||"*";for(const Z of Zz){const F=oe.decideToolPolicy({level:Z,scope:{level:Z,scopeId:D,assessmentId:z.scope.assessmentId,sectionId:z.scope.sectionId||void 0}}).visibleTools.find(W=>W.toolId===K.toolId);if(F){ae=ue[0]??K.toolId,X=F.settings;break}}if(!ae)return null}}catch(D){return v(K.toolId,"resolve",`Tool "${K.toolId}" failed policy resolution for the "${z.surface}" surface.`,D),null}const j={toolId:K.toolId,featureId:ae,surface:z.surface,parameters:X,services:z.services};return{registration:K,context:j,contextSignature:aI(j)}}function C(z){const K=z.registry;if(!K||!z.surface)return[];let oe;try{oe=K.getToolsBySurface(z.surface)}catch(ae){return v("registry","resolve",`The tool registry failed discovery for the "${z.surface}" surface.`,ae),[]}let ue=null;if(z.scope.kind==="content"&&d&&oe.some(ae=>ae.requiresAuthoredContent))try{ue=d.snapshot()}catch(ae){v("catalog-owner","resolve",`Catalog owner resolution failed for the "${z.surface}" surface; catalog-dependent capabilities were omitted.`,ae)}return oe.flatMap(ae=>{const X=z.scope.kind==="content"?I(z,ae,ue):x(z,ae);return X?[X]:[]})}function L(z,K){const oe=z.registry;if(!oe)return!1;const ue=K.registration.toolId;if(u.get(ue)===K.registration)return!0;const ae=f.get(ue);if(ae?.registry===oe&&ae.registration===K.registration)return!1;const X=oe.ensureToolModuleLoaded(ue),j={registry:oe,registration:K.registration};return f.set(ue,j),X.then(()=>{f.get(ue)===j&&f.delete(ue),!(i||n?.registry!==oe)&&oe.get(ue)===K.registration&&(u.set(ue,K.registration),M())}).catch(D=>{f.get(ue)===j&&f.delete(ue),!(i||n?.registry!==oe)&&oe.get(ue)===K.registration&&v(ue,"load",`Tool "${ue}" failed to load for the "${z.surface}" surface.`,D)}),!1}function E(z,K){const oe=z.registry,ue=z.anchor;if(!oe||!ue)return;const ae=K.registration.toolId;let X=null;try{if(X=oe.renderForSurface(ae,K.context),!X?.element)return;X.ariaLabel&&X.element.setAttribute("aria-label",X.ariaLabel),ue.appendChild(X.element),c.set(ae,{registration:K.registration,element:X.element,sync:X.sync,destroy:X.destroy,context:K.context,contextSignature:K.contextSignature})}catch(j){if(X?.element.parentNode===ue)try{ue.removeChild(X.element)}catch{}v(ae,"render",`Tool "${ae}" failed to render into the "${z.surface}" surface.`,j);return}}function M(){if(i||!n)return;const z=n,K=C(z),oe=new Map(K.map(ue=>[ue.registration.toolId,ue]));for(const[ue,ae]of[...c]){const X=oe.get(ue);(!z.anchor||!X||X.registration!==ae.registration)&&b(ue)}if(z.anchor&&z.registry){for(const ue of K){const ae=ue.registration.toolId,X=c.get(ae);if(X){if(Qz(X,ue))continue;try{X.sync?.(ue.context),X.context=ue.context,X.contextSignature=ue.contextSignature}catch(j){v(ae,"sync",`Tool "${ae}" failed to synchronize in the "${z.surface}" surface.`,j)}continue}L(z,ue)&&E(z,ue)}for(const ue of K){const ae=c.get(ue.registration.toolId);if(ae)try{z.anchor.appendChild(ae.element)}catch(X){v(ue.registration.toolId,"sync",`Tool "${ue.registration.toolId}" failed DOM reconciliation in the "${z.surface}" surface.`,X)}}}g({mountable:K.length>0,occupied:!!(z.anchor&&c.size>0)})}function U(){i||(p.clear(),M())}function te(z){if(z.kind==="module-loaders")for(const K of z.toolIds)u.delete(K);z.kind==="component-overrides"&&w(),U()}function re(){for(const z of[s,a,l])try{z?.()}catch{}s=null,a=null,l=null,d=null}function Pe(z){re(),s=typeof z.registry?.onRegistryChange=="function"?z.registry.onRegistryChange(te):null;const K=z.services.toolkitCoordinator;K&&(a=typeof K.onPolicyChange=="function"?K.onPolicyChange(U):null),z.scope.kind==="content"&&z.services.catalogResolver&&(d=z.services.catalogResolver.forOwner(z.scope.ownerContext),l=d.onChange(U))}return{update(z){if(i)return;const K=n;let oe=!0;try{oe=K?!Yz(K,z):!0}catch{oe=!0}const ue=K?!Jz(K,z):!0;n=z,ue&&Pe(z),oe&&(p.clear(),M())},destroy(){i||(re(),w(),i=!0,n=null,f.clear(),u.clear())}}}function uw(e,t){const r=sb(e,t.scope.level,t.scope.scopeId);return{fullToolId:r,isActive:()=>t.isToolVisible(r),subscribeActive:n=>t.subscribeVisibility?t.subscribeVisibility(()=>{n(t.isToolVisible(r))}):()=>{}}}function fw(e){const t=e.isActive();e.button.active=t,e.overlay.visible=t,e.onActiveChange?.(t)}function e4(e,t){e.setAttribute("data-pie-tool-surface",t)}var t4=Ht('<div class="pie-section-player-card-media svelte-1ms6ug7" data-region="media"><div class="pie-section-player-card-media-surface svelte-1ms6ug7"></div></div>'),r4=Ht("<div><!> <!> <!></div>"),n4={hash:"svelte-1ms6ug7",code:`
1122
+ /* Content and its docked catalog media, side by side. One column until a media
1123
+ card resolves, so the content region keeps its position in the layout either
1124
+ way. */.pie-section-player-card-media-split.svelte-1ms6ug7 {display:grid;align-items:start;min-width:0;min-height:0;}
1125
+
1126
+ /* \`:global\` because the content body is authored by the card and arrives here
1127
+ as a snippet, so it carries the card's scoping rather than this component's. */.pie-section-player-card-media-split.svelte-1ms6ug7 > * {min-width:0;min-height:0;}
1128
+
1129
+ /* Below the stacking breakpoint the grid is single-column, so the media region
1130
+ flows under the content instead of being squeezed beside it. */.pie-section-player-card-media-split--stacked.svelte-1ms6ug7 {grid-template-columns:minmax(0, 1fr);}.pie-section-player-card-media.svelte-1ms6ug7 {padding:1rem 1rem 1rem 0;}
1131
+
1132
+ /* Granted but nothing mounted: the region is in the DOM only to give the
1133
+ capability an anchor, so it must not claim a grid column or reach the
1134
+ accessibility tree. */.pie-section-player-card-media.svelte-1ms6ug7:not([data-occupied]) {display:none;}
1135
+
1136
+ /* Layout-transparent, so the capability's element is a direct child of the
1137
+ region as it was before the region became a host surface. An anchor that
1138
+ generated its own box broke any \`height: 100%\` chain through it, and the
1139
+ sizing tokens hosts set on the region are being tested against that chain. */.pie-section-player-card-media-surface.svelte-1ms6ug7 {display:contents;}.pie-section-player-card-media-split--stacked.svelte-1ms6ug7 .pie-section-player-card-media:where(.svelte-1ms6ug7) {padding:0 1rem 1rem;}
1140
+
1141
+ /* A docked alternate is consulted while an answer is being formed, not read
1142
+ once beforehand, so it follows long content down the scroll rather than
1143
+ disappearing above it. */.pie-section-player-card-media-split--with-media.svelte-1ms6ug7:not(
1144
+ .pie-section-player-card-media-split--stacked
1145
+ )
1146
+ .pie-section-player-card-media:where(.svelte-1ms6ug7) {position:sticky;top:0;align-self:start;}`};function hw(e,t){un(t,!0),Mn(e,n4);let r=_(t,"regionId",7),n=_(t,"ownerContext",7),i=_(t,"runtimeContext",7,null),o=_(t,"toolRegistry",7,null),s=_(t,"dividerAriaLabel",7),a=_(t,"dividerValueTextSuffix",7,"% media width"),l=_(t,"content",7),d=He(null),c=He(null),u=He(0),f=He(Ti(34)),p=He(Ti({mountable:!1,occupied:!1}));const g=dw(z=>{be(p,z,!0)},{hostLabel:"pie-section-player"});ct(()=>{g.update({anchor:h(d),surface:sI,registry:o(),services:{toolkitCoordinator:i()?.toolkitCoordinator??null,ttsService:i()?.ttsService??null,catalogResolver:i()?.catalogResolver??null,i18n:xa(i())},scope:{kind:"content",ownerContext:n()}})}),Xp(()=>g.destroy()),ct(()=>{const z=h(c);if(!z||typeof ResizeObserver>"u")return;const K=()=>{be(u,z.getBoundingClientRect().width,!0)};K();const oe=new ResizeObserver(K);return oe.observe(z),()=>oe.disconnect()});const v=ee(()=>h(p).mountable),b=ee(()=>h(p).occupied),w=ee(()=>h(u)>0&&h(u)<560),I=ee(()=>h(b)&&!h(w)),x=ee(()=>h(I)?`minmax(0, ${100-h(f)}fr) auto minmax(0, ${h(f)}fr)`:"minmax(0, 1fr)");function C(z){be(f,Au(z),!0)}var L={get regionId(){return r()},set regionId(z){r(z),R()},get ownerContext(){return n()},set ownerContext(z){n(z),R()},get runtimeContext(){return i()},set runtimeContext(z=null){i(z),R()},get toolRegistry(){return o()},set toolRegistry(z=null){o(z),R()},get dividerAriaLabel(){return s()},set dividerAriaLabel(z){s(z),R()},get dividerValueTextSuffix(){return a()},set dividerValueTextSuffix(z="% media width"){a(z),R()},get content(){return l()},set content(z){l(z),R()}},E=r4(),M=Xt(E);iM(M,l);var U=lr(M,2),te=z=>{{let K=ee(()=>`${Math.round(h(f))}${a()}`);WR(z,{get value(){return h(f)},get min(){return 20},get max(){return 55},get container(){return h(c)},get ariaLabel(){return s()},get ariaControls(){return r()},get ariaValueText(){return h(K)},onresize:C})}};vn(U,z=>{h(I)&&z(te)});var re=lr(U,2),Pe=z=>{var K=t4(),oe=Xt(K);Er(oe,ue=>be(d,ue),()=>h(d)),Kt(K),q(()=>{nt(K,"id",r()),nt(K,"data-occupied",h(b)?"":void 0),nt(oe,"data-pie-tool-surface",sI)}),ft(z,K)};return vn(re,z=>{h(v)&&z(Pe)}),Kt(E),Er(E,z=>be(c,z),()=>h(c)),q(()=>{gn(E,1,`pie-section-player-card-media-split ${h(b)?"pie-section-player-card-media-split--with-media":""} ${h(w)?"pie-section-player-card-media-split--stacked":""}`,"svelte-1ms6ug7"),Dl(E,`grid-template-columns: ${h(x)};`)}),ft(e,E),fn(L)}In(hw,{regionId:{},ownerContext:{},runtimeContext:{},toolRegistry:{},dividerAriaLabel:{},dividerValueTextSuffix:{},content:{}},[],[],{mode:"open"});var i4=Ht('<div class="pie-section-player-card-surface-stack svelte-mqy0q4" data-region="surface-stack"><div class="pie-section-player-card-surface-stack-anchor svelte-mqy0q4"></div></div>'),o4={hash:"svelte-mqy0q4",code:`.pie-section-player-card-surface-stack.svelte-mqy0q4 {padding:1rem 1rem 0;}
1147
+
1148
+ /* Granted but nothing mounted: in the DOM only to give the capability an
1149
+ anchor, so it must not claim space or reach the accessibility tree. */.pie-section-player-card-surface-stack.svelte-mqy0q4:not([data-occupied]) {display:none;}
1150
+
1151
+ /* Layout-transparent, so a capability's element is a direct child of the
1152
+ region and any height chain through it stays intact. */.pie-section-player-card-surface-stack-anchor.svelte-mqy0q4 {display:contents;}`};function pw(e,t){un(t,!0),Mn(e,o4);let r=_(t,"regionId",7),n=_(t,"surface",7),i=_(t,"ownerContext",7),o=_(t,"runtimeContext",7,null),s=_(t,"toolRegistry",7,null),a=He(null),l=He(Ti({mountable:!1,occupied:!1}));const d=dw(v=>{be(l,v,!0)},{hostLabel:"pie-section-player"});ct(()=>{d.update({anchor:h(a),surface:n(),registry:s(),services:{toolkitCoordinator:o()?.toolkitCoordinator??null,ttsService:o()?.ttsService??null,catalogResolver:o()?.catalogResolver??null,i18n:xa(o())},scope:{kind:"content",ownerContext:i()}})}),Xp(()=>d.destroy());const c=ee(()=>h(l).mountable);var u={get regionId(){return r()},set regionId(v){r(v),R()},get surface(){return n()},set surface(v){n(v),R()},get ownerContext(){return i()},set ownerContext(v){i(v),R()},get runtimeContext(){return o()},set runtimeContext(v=null){o(v),R()},get toolRegistry(){return s()},set toolRegistry(v=null){s(v),R()}},f=Nl(),p=jn(f),g=v=>{var b=i4(),w=Xt(b);Er(w,I=>be(a,I),()=>h(a)),Kt(b),q(()=>{nt(b,"id",r()),nt(b,"data-pie-tool-surface",n()),nt(b,"data-occupied",h(l).occupied?"":void 0)}),ft(v,b)};return vn(p,v=>{h(c)&&v(g)}),ft(e,f),fn(u)}In(pw,{regionId:{},surface:{},ownerContext:{},runtimeContext:{},toolRegistry:{}},[],[],{mode:"open"});var s4=Ht('<div class="pie-section-player-content-card-body pie-section-player-item-content pie-section-player__item-content svelte-1rzb80u" data-region="content"><!></div>'),a4=Ht('<button type="button" class="pie-section-player-formative__button svelte-1rzb80u"> </button>'),l4=Ht('<div class="pie-section-player-formative svelte-1rzb80u"><p class="pie-section-player-formative__status svelte-1rzb80u" data-pie-formative-status="" aria-live="polite"> </p> <!></div>'),c4=Ht('<div class="pie-section-player-item-card-anchor svelte-1rzb80u" aria-hidden="true"></div> <pie-item-shell><div class="pie-section-player-content-card svelte-1rzb80u" data-section-item-card="" data-pie-tool-overlay-boundary=""><div class="pie-section-player-content-card-header pie-section-player-item-header pie-section-player__item-header svelte-1rzb80u" data-region="header"><!> <pie-item-toolbar></pie-item-toolbar></div> <!> <!> <div data-region="footer"><!></div></div></pie-item-shell>',3),d4={hash:"svelte-1rzb80u",code:`.pie-section-player-item-card-anchor.svelte-1rzb80u {display:none;}pie-section-player-item-card {display:block;border-radius:var(--pie-section-player-card-radius, 8px);}
1153
+
1154
+ /* A cue-gated card stays mounted and is hidden, which keeps its shell
1155
+ registration, its session and the section's loading accounting intact —
1156
+ mounting on the cue instead would tear an item player down on every seek
1157
+ backwards. The rule is needed because the \`display: block\` above would
1158
+ otherwise beat the UA stylesheet's \`[hidden]\`. */pie-section-player-item-card[hidden] {display:none;}.pie-section-player-content-card.svelte-1rzb80u {
1159
+ /*
1160
+ * Containing block for frameless tool overlays. The toolkit appends them to
1161
+ * this element (see \`resolveOverlayMountParent\` in the assessment toolkit),
1162
+ * so the card's box is the frame a line reader or a ruler positions and
1163
+ * clamps against. Without it those overlays resolve against whichever
1164
+ * ancestor happens to be positioned, and a tool placed on this card can open
1165
+ * outside it.
1166
+ */position:relative;border:1px solid var(--pie-border-light, #e5e7eb);border-radius:var(--pie-section-player-card-radius, 8px);background:var(--pie-background, #fff);color:var(--pie-text, #111827);}.pie-section-player-content-card-header.svelte-1rzb80u {position:relative;display:flex;flex-wrap:wrap;align-items:center;gap:0.75rem;padding:0.75rem 1rem;overflow:visible;border-bottom:1px solid var(--pie-border-light, #e5e7eb);
1167
+
1168
+ /* Header fill is intentionally transparent by default. Hosts/themes
1169
+ opt-in to a solid color via --pie-section-player-card-header-background
1170
+ (e.g. a brand Bluegreen tint) without this framework encoding a palette. */background:var(--pie-section-player-card-header-background, transparent);
1171
+ /* Default just inside the card radius to avoid a double-radius effect with the border. */border-top-left-radius:var(
1172
+ --pie-section-player-card-header-radius,
1173
+ calc(var(--pie-section-player-card-radius, 8px) - 1px)
1174
+ );border-top-right-radius:var(
1175
+ --pie-section-player-card-header-radius,
1176
+ calc(var(--pie-section-player-card-radius, 8px) - 1px)
1177
+ );}
1178
+
1179
+ /*
1180
+ * Dark themes get their own opt-in fill: a host's light-theme brand tint
1181
+ * surviving into a dark theme is the failure this avoids. Unset, it falls
1182
+ * back to the single light hook, so a host that sets only that one is
1183
+ * unaffected. Keyed off the selectors the theme package writes its dark
1184
+ * tokens under — see renderTokensCss in packages/theme/src/theme-css.ts.
1185
+ */[data-theme="dark"] .pie-section-player-content-card-header.svelte-1rzb80u,
1186
+ pie-theme[theme="dark"] .pie-section-player-content-card-header.svelte-1rzb80u {background:var(
1187
+ --pie-section-player-card-header-background-dark,
1188
+ var(--pie-section-player-card-header-background, transparent)
1189
+ );}
1190
+
1191
+ /* Any heading level, not \`h2\`: the card renders at \`base-heading-level\`, so
1192
+ the tag is composition context rather than a fixed choice, and a host that
1193
+ nests the player deeper got an unstyled title. */.pie-section-player-content-card-header.svelte-1rzb80u :is(h1:where(.svelte-1rzb80u), h2:where(.svelte-1rzb80u), h3:where(.svelte-1rzb80u), h4:where(.svelte-1rzb80u), h5:where(.svelte-1rzb80u), h6:where(.svelte-1rzb80u)) {position:relative;
1194
+ /* Was supplied by the content stylesheet's heading reset, which now
1195
+ applies inside a player's content root only. */line-height:1.2;min-width:0;overflow-wrap:anywhere;z-index:0;margin:0;
1196
+ /* Reads the scale rather than inheriting it: the card wraps the item shell
1197
+ that \`font-sizes.css\` scales, so nothing above this rule carries the
1198
+ scaled size. Root-relative, so it does not compound with the shell. */font-size:calc(0.95rem * var(--pie-font-scale, 1));font-weight:600;
1199
+ /* Default to the themed body text color so titles stay legible across
1200
+ DaisyUI themes; --pie-header-text remains a host opt-in override. */color:var(--pie-header-text, var(--pie-text, #111827));}.pie-section-player-content-card-header.svelte-1rzb80u pie-item-toolbar:where(.svelte-1rzb80u) {position:relative;min-width:0;max-width:100%;z-index:1;margin-left:auto;}
1201
+
1202
+ /* Floating reading controls must paint above the pane's scroll hint (10). */.pie-section-player-content-card-header.svelte-1rzb80u pie-item-toolbar[data-pie-header-overlay-active="true"] {z-index:11;}.pie-section-player-content-card-body.svelte-1rzb80u {padding:1rem;color:var(--pie-text, #111827);}
1203
+
1204
+ /* Formative control. Painted only from \`--pie-*\` chains so it follows every
1205
+ base theme, provider and colour scheme without a hook of its own. */.pie-section-player-formative.svelte-1rzb80u {display:flex;align-items:center;justify-content:space-between;gap:0.75rem;flex-wrap:wrap;padding:0.75rem 1rem;border-top:1px solid var(--pie-border-light, #e5e7eb);}.pie-section-player-formative__status.svelte-1rzb80u {margin:0;
1206
+ /* Tries remaining and correctness, and the only signal carrying either —
1207
+ the note below is why no colour accompanies it. So it follows the font
1208
+ accommodation for the same reason the item body does. */font-size:calc(0.9rem * var(--pie-font-scale, 1));
1209
+ /* Correctness is carried by the text itself, so no state colour is needed
1210
+ and none is applied — a colour here would be the only signal at exactly
1211
+ the moment it must not be (WCAG 1.4.1). */color:var(--pie-text, #111827);}
1212
+
1213
+ /* Empty until a Try lands; collapse so the footer does not reserve a blank
1214
+ row before there is anything to announce. */.pie-section-player-formative__status.svelte-1rzb80u:empty {display:none;}
1215
+
1216
+ /* Canonical button-family chains, no component-scoped hook: this control is an
1217
+ ordinary button and a host that restyles ordinary buttons should get it for
1218
+ free. Geometry stays literal, as it does on the scroll hint — the contract
1219
+ certifies colour pairs, not radii. */.pie-section-player-formative__button.svelte-1rzb80u {
1220
+ /* Comfortably past the 24x24 minimum in WCAG 2.5.8, and the padding keeps
1221
+ it there at the smallest supported text size. */min-height:2.25rem;padding:0.4rem 0.9rem;margin-left:auto;border:1px solid var(--pie-button-border, var(--pie-border, #8f8f8f));border-radius:4px;background:var(--pie-button-bg, var(--pie-white, #fff));color:var(--pie-button-color, var(--pie-text, #374151));font:inherit;cursor:pointer;}.pie-section-player-formative__button.svelte-1rzb80u:hover {background:var(--pie-button-hover-bg, var(--pie-background-dark, #f9fafb));border-color:var(--pie-button-hover-border, var(--pie-border, #8b919c));color:var(--pie-button-hover-color, var(--pie-text, #111827));}.pie-section-player-formative__button.svelte-1rzb80u:active {
1222
+ /* \`--pie-button-color\` is the only ink the contract certifies against this
1223
+ fill, so the pair stays together. */background:var(--pie-button-active-bg, var(--pie-background-dark, #f3f4f6));color:var(--pie-button-color, var(--pie-text, #374151));}.pie-section-player-formative__button.svelte-1rzb80u:focus-visible {outline:2px solid
1224
+ var(--pie-button-focus-outline, var(--pie-primary, #3b82f6));outline-offset:2px;}.pie-section-player-formative__button[aria-busy="true"].svelte-1rzb80u {cursor:progress;}`};function u4(e,t){un(t,!0),Mn(e,d4);let r=_(t,"item",7),n=_(t,"itemIndex",7,0),i=_(t,"itemCount",7,1),o=_(t,"isCurrent",7,!1),s=_(t,"canonicalItemId",7),a=_(t,"baseHeadingLevel",7,2),l=_(t,"resolvedPlayerTag",7,"div"),d=_(t,"playerAction",7,(Y,we)=>{}),c=_(t,"playerParams",7),u=_(t,"itemToolbarTools",7),f=_(t,"toolRegistry",7,null),p=_(t,"hostButtons",23,()=>[]),g=_(t,"formativeView",7,null),v=_(t,"timedMediaView",7,null);const b=ee(()=>cw(a()));let w=He(null);const I=ee(()=>xa(h(w)));let x=He(null),C=He(null),L=He(null),E=He(null),M=He(!1);const U=on(()=>`pie-section-player-item-card-heading-${r()?.id??s()??Math.random().toString(36).slice(2,10)}`),te=ee(()=>(h(M)?h(C):null)||l()),re=ee(()=>(h(M)?h(L):null)||d()),Pe=ee(()=>Number.isFinite(n())?Math.max(0,Number(n()))+1:1),z=ee(()=>Number.isFinite(i())?Math.max(1,Number(i())):1),K=ee(()=>h(z)>1?h(I).t("player.questionNumbered",{position:h(Pe)}):h(I).t("player.question")),oe=ee(()=>(h(M)?h(E):null)||null),ue=ee(()=>{if(!h(oe))return h(K);try{const Y=h(oe)({kind:"item",item:r(),itemIndex:h(Pe)-1,itemCount:h(z),canonicalItemId:s(),defaultTitle:h(K)});return typeof Y!="string"?h(K):Y.trim()||h(K)}catch{return h(K)}}),ae=ee(()=>`${U}-media`),X=ee(()=>`${U}-lead`),j=ee(()=>fk({kind:"item",itemId:r()?.id??"",canonicalItemId:s(),assessmentId:h(w)?.assessmentId,sectionId:h(w)?.sectionId}));ct(()=>{if(h(x))return Oy(h(x),Y=>{be(w,Y,!0)})});function D(){be(M,!1),be(C,null),be(L,null),be(E,null)}function Z(Y){!Y||typeof Y!="object"||(typeof Y.resolvedPlayerTag=="string"&&Y.resolvedPlayerTag.trim()&&be(C,Y.resolvedPlayerTag,!0),typeof Y.playerAction=="function"&&be(L,Y.playerAction,!0),typeof Y.cardTitleFormatter=="function"&&be(E,Y.cardTitleFormatter,!0))}let F=He(null),W=He(!1),O=He(!1);const $=ee(()=>g()?.enabled===!0),ie=ee(()=>h($)&&(g()?.canCheck||g()?.canRetry)),N=ee(()=>h(I).t(g()?.canRetry?"player.formative.tryAgain":"player.formative.checkAnswer"));function ne(Y){return Y.triesRemaining==="unlimited"||Y.triesRemaining<=0?"":h(I).plural?.("player.formative.triesLeft",{count:Y.triesRemaining})??""}function ge(Y){if(!Y.revealed)return Y.tryCount>0?h(I).t("player.formative.answerRecorded"):"";switch(Y.lastOutcome?.correctness){case"correct":return h(I).t("player.formative.correct");case"partial":return h(I).t("player.formative.partlyCorrect");case"incorrect":return h(I).t("player.formative.notCorrect");case"unknown":return h(I).t("player.formative.notAutoScored");default:return h(I).t("player.formative.answerRecorded")}}const Oe=ee(()=>{if(h(O))return h(I).t("player.formative.checkFailed");if(!g()?.enabled)return"";const Y=ge(g());if(!Y)return"";const we=g().canRetry?ne(g()):"";return we?`${Y} ${we}`:Y});function We(Y,we){const _e=Pu(h(x));if(!_e||!r()?.id)return;const Be={itemId:r().id,canonicalItemId:s()||r().id,action:Y,outcomes:we};Ms(_e,m$,Be)}async function Ne(){if(!g()?.enabled||h(W))return;if(be(O,!1),g().canRetry){We("retry");return}if(!g().canCheck)return;const Y=h(F)?.provideScore;if(typeof Y!="function"){be(O,!0);return}be(W,!0);try{const we=await Y.call(h(F));We("check",Array.isArray(we)?we:[])}catch(we){be(O,!0),console.warn(`[pie-section-player] provideScore() failed for item ${r()?.id}:`,we)}finally{be(W,!1)}}Kp(()=>{const Y=Pu(h(x));if(!Y)return;be(M,!0);const we=HR(Y,Z);return()=>{we(),D()}});var xe={get item(){return r()},set item(Y){r(Y),R()},get itemIndex(){return n()},set itemIndex(Y=0){n(Y),R()},get itemCount(){return i()},set itemCount(Y=1){i(Y),R()},get isCurrent(){return o()},set isCurrent(Y=!1){o(Y),R()},get canonicalItemId(){return s()},set canonicalItemId(Y){s(Y),R()},get baseHeadingLevel(){return a()},set baseHeadingLevel(Y=2){a(Y),R()},get resolvedPlayerTag(){return l()},set resolvedPlayerTag(Y="div"){l(Y),R()},get playerAction(){return d()},set playerAction(Y=(we,_e)=>{}){d(Y),R()},get playerParams(){return c()},set playerParams(Y){c(Y),R()},get itemToolbarTools(){return u()},set itemToolbarTools(Y){u(Y),R()},get toolRegistry(){return f()},set toolRegistry(Y=null){f(Y),R()},get hostButtons(){return p()},set hostButtons(Y=[]){p(Y),R()},get formativeView(){return g()},set formativeView(Y=null){g(Y),R()},get timedMediaView(){return v()},set timedMediaView(Y=null){v(Y),R()}},et=c4(),Ue=jn(et);Er(Ue,Y=>be(x,Y),()=>h(x));var Se=lr(Ue,2);q(()=>G(Se,"item-id",r().id)),q(()=>G(Se,"canonical-item-id",s())),G(Se,"content-kind","assessment-item"),q(()=>G(Se,"item",r()));var Re=Xt(Se),mt=Xt(Re),$t=Xt(mt);Kh($t,()=>`h${h(b)}`,!1,(Y,we)=>{CT(Y,()=>({id:U,"data-pie-tool-overlay-protect":!0,class:""}),void 0,void 0,void 0,"svelte-1rzb80u");var _e=fT();q(()=>vs(_e,h(ue))),ft(we,_e)});var ve=lr($t,2);q(()=>G(ve,"item-id",r().id)),q(()=>G(ve,"catalog-id",r().id)),q(()=>G(ve,"tools",u())),G(ve,"content-kind","assessment-item"),G(ve,"size","md"),G(ve,"language","en-US"),q(()=>G(ve,"toolRegistry",f())),q(()=>G(ve,"hostButtons",p())),gn(ve,1,"svelte-1rzb80u"),Kt(mt);var me=lr(mt,2);pw(me,{get regionId(){return h(X)},get surface(){return zR},get ownerContext(){return h(j)},get runtimeContext(){return h(w)},get toolRegistry(){return f()}});var Je=lr(me,2);{const Y=_e=>{var Be=s4(),it=Xt(Be);Kh(it,()=>h(te),!1,(tt,Bt)=>{Er(tt,ht=>be(F,ht,!0),()=>h(F)),bT(tt,(ht,ot)=>h(re)?.(ht,ot),c),gn(tt,0,"svelte-1rzb80u")}),Kt(Be),ft(_e,Be)};let we=ee(()=>h(I).t("player.resizeQuestionAndMediaA11y"));hw(Je,{get regionId(){return h(ae)},get ownerContext(){return h(j)},get runtimeContext(){return h(w)},get toolRegistry(){return f()},get dividerAriaLabel(){return h(we)},content:Y,$$slots:{content:!0}})}var Gt=lr(Je,2),le=Xt(Gt),Ae=Y=>{var we=l4(),_e=Xt(we),Be=Ta(_e,!0),it=lr(_e,2),tt=Bt=>{var ht=a4(),ot=Ta(ht,!0);q(()=>{nt(ht,"data-pie-formative-action",g()?.canRetry?"retry":"check"),nt(ht,"aria-busy",h(W)?"true":void 0),vs(ot,h(N))}),lo("click",ht,Ne),ft(Bt,ht)};vn(it,Bt=>{h(ie)&&Bt(tt)}),Kt(we),q(()=>vs(Be,h(Oe))),ft(Y,we)};return vn(le,Y=>{h($)&&Y(Ae)}),Kt(Gt),Kt(Re),Kt(Se),q(()=>{nt(Re,"data-canonical-item-id",s()),nt(Re,"aria-current",o()?"true":void 0),nt(Re,"data-pie-timed-media-gate",v()?.isGateTarget?"holding":void 0),nt(Re,"tabindex",v()?.isGateTarget?-1:void 0)}),ft(e,et),fn(xe)}cd(["click"]);f4("pie-section-player-item-card",In(u4,{item:{type:"Object"},itemIndex:{attribute:"item-index",type:"Number"},itemCount:{attribute:"item-count",type:"Number"},isCurrent:{attribute:"is-current",reflect:!0,type:"Boolean"},canonicalItemId:{attribute:"canonical-item-id",type:"String"},baseHeadingLevel:{attribute:"base-heading-level",type:"Number"},resolvedPlayerTag:{attribute:"resolved-player-tag",type:"String"},playerAction:{type:"Object"},playerParams:{attribute:"player-params",type:"Object"},itemToolbarTools:{attribute:"item-toolbar-tools",type:"String"},toolRegistry:{type:"Object"},hostButtons:{type:"Object"},formativeView:{attribute:"formative-view",type:"Object"},timedMediaView:{attribute:"timed-media-view",type:"Object"}},[],[],void 0,Zs));function f4(e,t){customElements.get(e)||customElements.define(e,t)}var h4=Ht('<div class="pie-passage-shell-anchor svelte-1fzqxck" aria-hidden="true"></div> <!>',1),p4={hash:"svelte-1fzqxck",code:".pie-passage-shell-anchor.svelte-1fzqxck {display:none;}"};function m4(e,t){un(t,!0),Mn(e,p4);const r="pie-content-loaded",n="pie-item-player-error";let i=_(t,"itemId",7,""),o=_(t,"canonicalItemId",7,""),s=_(t,"contentKind",7,"rubric-block-stimulus"),a=_(t,"regionPolicy",7,"default"),l=_(t,"scopeElement",7,null),d=_(t,"ttsHighlightTargetResolver",7,null),c=_(t,"item",7,null),u=He(null);const f=Date.now();let p=null,g=null,v=null,b=null;function w(){if(!h(u))return null;const oe=h(u).getRootNode();return oe&&"host"in oe?oe.host:h(u).parentElement}const I=ee(()=>w()),x=ee(()=>l()||h(I)||null),C=ee(()=>h(x)?{scopeElement:h(x),ttsHighlightTargetResolver:d()}:null),L=ee(()=>{if(!h(I))return null;const oe=o()||i();return{kind:"passage",itemId:i(),canonicalItemId:oe,contentKind:s(),regionPolicy:a(),scopeElement:h(x),item:c(),contextVersion:f}}),E=cE();function M(){return!h(I)||!i()?null:{kind:"passage",host:h(I),itemId:i(),canonicalItemId:o()||i(),contentKind:s(),item:c()}}function U(oe){if(!h(I)||!i())return;const ue={itemId:i(),canonicalItemId:o()||i(),contentKind:s(),detail:oe};Ms(h(I),r,ue)}function te(oe){if(!h(I)||!i())return;const ue={itemId:i(),canonicalItemId:o()||i(),contentKind:s(),error:oe};Ms(h(I),n,ue)}ct(()=>{if(!h(I))return;const oe=X=>{X.stopPropagation()};h(I).addEventListener("session-changed",oe);const ue=X=>{X.stopPropagation(),U(X.detail)},ae=X=>{X.stopPropagation(),te(X.detail)};return h(I).addEventListener("load-complete",ue),h(I).addEventListener("player-error",ae),()=>{h(I)?.removeEventListener("session-changed",oe),h(I)?.removeEventListener("load-complete",ue),h(I)?.removeEventListener("player-error",ae),E.retire()}}),ct(()=>{E.sync(M())}),ct(()=>{h(I)&&(h(I).setAttribute("data-item-id",i()),h(I).setAttribute("data-canonical-item-id",o()||i()),h(I).setAttribute("data-pie-shell-root","passage"),h(I).setAttribute("data-region-policy",a()))}),ct(()=>{if(!(!h(I)||!h(L)))return p=new Ws(h(I),{context:dk,initialValue:h(L)}),p.connect(),g=new Bl(h(I)),g.attach(),()=>{g?.detach(),g=null,p?.disconnect(),p=null}}),ct(()=>{h(L)&&p?.setValue(h(L))}),ct(()=>{if(!(!h(I)||!h(C)))return v=new Ws(h(I),{context:lk,initialValue:h(C)}),v.connect(),b=new Bl(h(I)),b.attach(),()=>{b?.detach(),b=null,v?.disconnect(),v=null}}),ct(()=>{h(C)&&v?.setValue(h(C))});var re={get itemId(){return i()},set itemId(oe=""){i(oe),R()},get canonicalItemId(){return o()},set canonicalItemId(oe=""){o(oe),R()},get contentKind(){return s()},set contentKind(oe="rubric-block-stimulus"){s(oe),R()},get regionPolicy(){return a()},set regionPolicy(oe="default"){a(oe),R()},get scopeElement(){return l()},set scopeElement(oe=null){l(oe),R()},get ttsHighlightTargetResolver(){return d()},set ttsHighlightTargetResolver(oe=null){d(oe),R()},get item(){return c()},set item(oe=null){c(oe),R()}},Pe=h4(),z=jn(Pe);Er(z,oe=>be(u,oe),()=>h(u));var K=lr(z,2);return dd(K,t,"default",{},null),ft(e,Pe),fn(re)}g4("pie-passage-shell",In(m4,{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"}},["default"],[],{mode:"open"}));function g4(e,t){customElements.get(e)||customElements.define(e,t)}var $d={allowSeekAhead:!1,pauseOnRequiredCue:!0,requireMediaCompletion:!1},lI=["reveal","gate","metadata"],cI=["responded","correct","partial-or-better"],v4=["release","hold"],dI=["sum-child-outcomes","average-child-outcomes","host-defined"];function y4(e){return e==="correct"||e==="partial-or-better"}function Lg(e){return typeof e=="string"?e.trim():""}function b4(e){if(e==null)return{policy:{...$d},error:null};if(typeof e!="object")return{policy:{...$d},error:{code:"invalid-playback-policy",message:"timedMedia.playbackPolicy must be an object."}};const t=e;return{policy:{allowSeekAhead:typeof t.allowSeekAhead=="boolean"?t.allowSeekAhead:$d.allowSeekAhead,pauseOnRequiredCue:typeof t.pauseOnRequiredCue=="boolean"?t.pauseOnRequiredCue:$d.pauseOnRequiredCue,requireMediaCompletion:typeof t.requireMediaCompletion=="boolean"?t.requireMediaCompletion:$d.requireMediaCompletion},error:null}}function w4(e){if(e==null)return{policy:void 0,error:null};const t=e&&typeof e=="object"?e.strategy:void 0,r=dI.find(n=>n===t);return r?{policy:{strategy:r},error:null}:{policy:void 0,error:{code:"invalid-scoring-policy",message:`timedMedia.scoringPolicy.strategy must be one of ${dI.join(", ")}.`}}}function S4(e){const t=[];if(!e.timedMedia||typeof e.timedMedia!="object")return{data:null,errors:[{code:"missing-stimulus-ref",message:"timedMedia must be an object carrying a stimulusRef."}]};const r=e.timedMedia,n=Lg(r.stimulusRef);n||t.push({code:"missing-stimulus-ref",message:"timedMedia.stimulusRef is required."});const i=n?e.resolveStimulusRenderableId(n):void 0;n&&!i&&t.push({code:"unresolved-stimulus-ref",message:`timedMedia.stimulusRef "${n}" does not name a renderable in this section.`});const{policy:o,error:s}=b4(r.playbackPolicy);s&&t.push(s);const{policy:a,error:l}=w4(r.scoringPolicy);l&&t.push(l);const d=new Set(e.itemIdentifiers),c=Array.isArray(r.cues)?r.cues:[];c.length===0&&t.push({code:"no-cues",message:"timedMedia.cues must hold at least one cue."});const u=new Set,f=[];for(const[p,g]of c.entries()){const v=g??{},b=Lg(v.identifier);if(!b){t.push({code:"invalid-cue-identifier",message:`timedMedia.cues[${p}] has no identifier.`});continue}if(u.has(b)){t.push({code:"duplicate-cue-identifier",message:`Cue identifier "${b}" appears more than once.`,cueIdentifier:b});continue}u.add(b);const w=WT(v.range);if(!w){t.push({code:"invalid-cue-range",message:`Cue "${b}" needs a range with a finite, non-negative startSeconds.`,cueIdentifier:b});continue}const I=v.policy??{},x=lI.find(U=>U===I.activation);if(!x){t.push({code:"invalid-cue-activation",message:`Cue "${b}" needs policy.activation of ${lI.join(", ")}.`,cueIdentifier:b});continue}const C=Array.isArray(v.itemRefs)?v.itemRefs:[],L=[];for(const U of C){const te=Lg(U);if(te){if(!d.has(te)){t.push({code:"unknown-item-ref",message:`Cue "${b}" names item ref "${te}", which is not in this section.`,cueIdentifier:b});continue}L.includes(te)||L.push(te)}}if(L.length===0&&x!=="metadata"){t.push({code:"missing-item-refs",message:`Cue "${b}" activates no item; only a metadata cue may name none.`,cueIdentifier:b});continue}let E,M;if(x==="gate"){if(E=cI.find(U=>U===I.releaseOn),!E){t.push({code:"missing-release-condition",message:`Gate cue "${b}" needs policy.releaseOn of ${cI.join(", ")}.`,cueIdentifier:b});continue}if(y4(E)){if(M=v4.find(te=>te===I.onUnknownCorrectness),!M){t.push({code:"missing-unknown-correctness",message:`Gate cue "${b}" releases on correctness, so policy.onUnknownCorrectness must state "release" or "hold" for an item no controller can score.`,cueIdentifier:b});continue}const U=L.filter(te=>e.resolveItemTryBudget(te)!=="unlimited");if(U.length>0){t.push({code:"gate-requires-unlimited-tries",message:`Gate cue "${b}" releases on correctness, so every item it names needs formative delivery with maxTries: "unlimited" — otherwise a learner who runs out of Tries can never release playback. Offending item refs: ${U.join(", ")}.`,cueIdentifier:b});continue}}}f.push({identifier:b,range:w,itemRefs:L,activation:x,releaseOn:E,onUnknownCorrectness:M,holdsPlayback:x==="gate"&&o.pauseOnRequiredCue})}return t.length>0?{data:null,errors:t}:{data:{stimulusRef:n,stimulusRenderableId:i??"",cues:f,playbackPolicy:o,scoringPolicy:a},errors:[]}}var I4=.5,k4=.001,T4=10;function Ph(){return{version:1,mediaCurrentTime:0,maxPositionSeconds:0,mediaCompleted:!1,visitedCueIdentifiers:[],completedCueIdentifiers:[],aggregateComplete:!1}}function Og(e,t){const r=Number(e);return!Number.isFinite(r)||r<0?t:r}function E4(e,t){return t+k4>=e.range.startSeconds}function C4(e,t,r){if(e.releaseOn==="responded")return r.respondedByItemId[t]===!0;const n=r.correctnessByItemId[t];return n===void 0?!1:n==="unknown"?e.onUnknownCorrectness==="release":e.releaseOn==="correct"?n==="correct":n==="correct"||n==="partial"}function VR(e,t){return e.itemRefs.length===0?!0:e.itemRefs.every(r=>C4(e,r,t))}function uI(e,t){return e.length!==t.length?!1:e.every((r,n)=>r===t[n])}function x4(e){const{state:t,data:r,delivery:n,input:i}=e,o={pause:!1};let s=t.mediaCurrentTime,a=t.mediaCompleted;switch(i.kind){case"time":s=Og(i.currentTimeSeconds,t.mediaCurrentTime);break;case"seek":{const I=Og(i.currentTimeSeconds,t.mediaCurrentTime);!r.playbackPolicy.allowSeekAhead&&I>t.maxPositionSeconds+I4?(o.seekToSeconds=t.maxPositionSeconds,s=t.maxPositionSeconds):s=I;break}case"ended":s=Og(i.currentTimeSeconds,t.mediaCurrentTime),a=!0}const l=Math.max(t.maxPositionSeconds,s),d=[...t.visitedCueIdentifiers],c=new Set(d);for(const I of r.cues)c.has(I.identifier)||E4(I,s)&&(c.add(I.identifier),d.push(I.identifier),o.activatedCueIdentifier=I.identifier);const u=new Set(t.completedCueIdentifiers);let f=null;for(const I of r.cues)if(c.has(I.identifier)&&!u.has(I.identifier)){if(!I.holdsPlayback){u.add(I.identifier);continue}if(VR(I,n)){u.add(I.identifier),o.releasedCueIdentifier=I.identifier;continue}f||(f=I)}const p=r.cues.map(I=>I.identifier).filter(I=>u.has(I));o.pause=f!==null;const g=f?.identifier??d[d.length-1],v=p.length===r.cues.length&&n.itemsComplete&&(r.playbackPolicy.requireMediaCompletion?a:!0),b={version:1,mediaCurrentTime:s,maxPositionSeconds:l,mediaCompleted:a,visitedCueIdentifiers:d,completedCueIdentifiers:p,activeCueIdentifier:g,aggregateComplete:v},w=b.mediaCurrentTime!==t.mediaCurrentTime||b.maxPositionSeconds!==t.maxPositionSeconds||b.mediaCompleted!==t.mediaCompleted||b.activeCueIdentifier!==t.activeCueIdentifier||b.aggregateComplete!==t.aggregateComplete||!uI(b.visitedCueIdentifiers,t.visitedCueIdentifiers)||!uI(b.completedCueIdentifiers,t.completedCueIdentifiers);return{state:w?b:t,effects:o,changed:w}}function GR(e){const t=[],r=e.playbackPolicy.pauseOnRequiredCue&&e.hasGate,n=!e.playbackPolicy.allowSeekAhead,i=e.capabilities?e.capabilities.canPause:!0,o=e.capabilities?e.capabilities.canRestrictSeeking:!0;return r&&!i&&t.push({policy:"pause-on-required-cue",capability:"canPause",message:"The media time source cannot pause, so gate cues are advisory: they fire and record state, and playback continues."}),n&&!o&&t.push({policy:"restrict-seek-ahead",capability:"canRestrictSeeking",message:"The media time source cannot restrict seeking, so allowSeekAhead: false is advisory: a learner can seek past cues."}),{pause:r&&!i?"advisory":"enforced",seek:n&&!o?"advisory":"enforced",degradations:t}}function R4(e){const t=new Set(e.state.visitedCueIdentifiers),r=new Set(e.state.completedCueIdentifiers);for(const n of e.data.cues)if(!(!n.holdsPlayback||!n.releaseOn)&&t.has(n.identifier)&&!r.has(n.identifier))return{cueIdentifier:n.identifier,itemRefs:[...n.itemRefs],releaseOn:n.releaseOn,holding:!VR(n,e.delivery),enforcement:e.pauseEnforcement};return null}function KR(e){return e.activation!=="metadata"}function _4(e){const t=[];for(const r of e.cues)if(KR(r))for(const n of r.itemRefs)t.includes(n)||t.push(n);return t}function P4(e,t){const r=new Set(t.visitedCueIdentifiers),n=[];for(const i of e.cues)if(KR(i)&&r.has(i.identifier))for(const o of i.itemRefs)n.includes(o)||n.push(o);return n}function A4(e){const t=e.data.cues.some(n=>n.activation==="gate"),r=GR({playbackPolicy:e.data.playbackPolicy,capabilities:e.capabilities,hasGate:t});return{version:1,stimulusRenderableId:e.data.stimulusRenderableId,cues:e.data.cues,playbackPolicy:e.data.playbackPolicy,mediaAttached:e.capabilities!==null,enforcement:{pause:r.pause,seek:r.seek},degradations:r.degradations,revealedItemIds:P4(e.data,e.state),sequencedItemIds:_4(e.data),activeCueIdentifier:e.state.activeCueIdentifier,gate:R4({data:e.data,state:e.state,delivery:e.delivery,pauseEnforcement:r.pause}),visitedCueIdentifiers:[...e.state.visitedCueIdentifiers],completedCueIdentifiers:[...e.state.completedCueIdentifiers],mediaCurrentTime:e.state.mediaCurrentTime,maxPositionSeconds:e.state.maxPositionSeconds,mediaCompleted:e.state.mediaCompleted,aggregateComplete:e.state.aggregateComplete===!0}}function XR(e){return e?[(e.visitedCueIdentifiers??[]).join(","),(e.completedCueIdentifiers??[]).join(","),(e.revealedItemIds??[]).join(","),e.activeCueIdentifier??"",e.gate?.cueIdentifier??"",e.gate?.holding===!0?"1":"0",e.enforcement?.pause??"",e.enforcement?.seek??"",e.mediaAttached===!0?"1":"0",e.mediaCompleted===!0?"1":"0",e.aggregateComplete===!0?"1":"0",String(Math.floor((e.maxPositionSeconds??0)/T4))].join(":"):""}function fI(e){const t=typeof e=="number"?e:NaN;if(!(!Number.isFinite(t)||t<0))return t}function hI(e,t){if(!Array.isArray(e))return[];const r=[];for(const n of e){if(typeof n!="string")continue;const i=n.trim();!i||!t.has(i)||r.includes(i)||r.push(i)}return r}function M4(e){return{...e,version:1,visitedCueIdentifiers:[...e.visitedCueIdentifiers],completedCueIdentifiers:[...e.completedCueIdentifiers]}}function $4(e){const{slice:t,data:r}=e;if(!r||!t||typeof t!="object")return null;const n=t;if(n.version!==1)return null;const i=new Set(r.cues.map(c=>c.identifier)),o=Ph(),s=fI(n.mediaCurrentTime)??o.mediaCurrentTime,a=hI(n.visitedCueIdentifiers,i),l=hI(n.completedCueIdentifiers,i),d=typeof n.activeCueIdentifier=="string"&&i.has(n.activeCueIdentifier)?n.activeCueIdentifier:void 0;return{version:1,mediaCurrentTime:s,maxPositionSeconds:Math.max(fI(n.maxPositionSeconds)??0,s),mediaCompleted:n.mediaCompleted===!0,visitedCueIdentifiers:a,completedCueIdentifiers:l.filter(c=>a.includes(c)),activeCueIdentifier:d,aggregateComplete:n.aggregateComplete===!0}}var L4={canPause:!0,canRestrictSeeking:!0},O4=[{name:"timeupdate",type:"time"},{name:"seeking",type:"seek"},{name:"seeked",type:"seek"},{name:"play",type:"play"},{name:"pause",type:"pause"},{name:"ended",type:"ended"}];function N4(e,t={}){const r={...L4,...t.capabilities??{}},n=new Set;function i(){const a=e.currentTime;return Number.isFinite(a)&&a>=0?a:0}function o(a){const l={type:a,currentTime:i()};for(const d of Array.from(n))try{d(l)}catch{}}const s=O4.map(a=>({name:a.name,handler:()=>o(a.type)}));return{get currentTime(){return i()},get duration(){return e.duration},get paused(){return e.paused},get seekable(){return e.seekable??null},capabilities:r,play(){return e.play()},pause(){e.pause()},seekTo(a){!Number.isFinite(a)||a<0||(e.currentTime=a)},subscribe(a){if(n.add(a),n.size===1)for(const l of s)e.addEventListener(l.name,l.handler);return()=>{if(n.delete(a)&&!(n.size>0))for(const l of s)e.removeEventListener(l.name,l.handler)}}}}function D4(e){return e?e.querySelector("video, audio")??null:null}var j4=Ht('<div class="pie-section-player-content-card-body pie-section-player-passage-content pie-section-player__passage-content svelte-1qmzs9f" data-region="content"><!></div>'),B4=Ht('<div class="pie-section-player-passage-card-anchor svelte-1qmzs9f" aria-hidden="true"></div> <pie-passage-shell><div class="pie-section-player-content-card svelte-1qmzs9f" data-pie-tool-overlay-boundary=""><div class="pie-section-player-content-card-header pie-section-player-passage-header pie-section-player__passage-header svelte-1qmzs9f" data-region="header"><!> <pie-item-toolbar></pie-item-toolbar></div> <!> <!></div></pie-passage-shell>',3),F4={hash:"svelte-1qmzs9f",code:`.pie-section-player-passage-card-anchor.svelte-1qmzs9f {display:none;}pie-section-player-passage-card {display:block;border-radius:var(--pie-section-player-card-radius, 8px);
1225
+ /* Bridge for the hosted passage-player custom element, which reads its
1226
+ own --pie-passage-header-background token and lives outside this
1227
+ package's control. Resolving it here keeps the passage header in
1228
+ sync with the section-player card header without either side
1229
+ hardcoding the other's token name. */--pie-passage-header-background: var(--pie-section-player-card-header-background);}
1230
+
1231
+ /* Same bridge under a dark theme, so the hosted element follows the dark hook. */[data-theme="dark"] pie-section-player-passage-card,
1232
+ pie-theme[theme="dark"] pie-section-player-passage-card {--pie-passage-header-background: var(
1233
+ --pie-section-player-card-header-background-dark,
1234
+ var(--pie-section-player-card-header-background)
1235
+ );}.pie-section-player-content-card.svelte-1qmzs9f {
1236
+ /*
1237
+ * Containing block for frameless tool overlays. The toolkit appends them to
1238
+ * this element (see \`resolveOverlayMountParent\` in the assessment toolkit),
1239
+ * so the card's box is the frame a line reader or a ruler positions and
1240
+ * clamps against. Without it those overlays resolve against whichever
1241
+ * ancestor happens to be positioned, and a tool placed on this card can open
1242
+ * outside it.
1243
+ */position:relative;border:1px solid var(--pie-border-light, #e5e7eb);border-radius:var(--pie-section-player-card-radius, 8px);background:var(--pie-background, #fff);color:var(--pie-text, #111827);}pie-section-player-passage-card .pie-section-player-content-card:has(.pie-section-player-passage-content :focus-visible) {outline:3px solid var(--pie-section-player-focus-outline, var(--pie-focus-outline, #146eb3));outline-offset:2px;}
1244
+
1245
+ /* Multi-passage sets render their own tab strip (role="tablist") as the
1246
+ first thing inside the body, which already reads as a header. Drop the
1247
+ gap and duplicate rule above it so the two headers blend into one band;
1248
+ a single passage has no tablist and keeps the default spacing. */pie-section-player-passage-card .pie-section-player-content-card:has(.pie-section-player-content-card-body [role="tablist"]) .pie-section-player-content-card-header {border-bottom:none;}pie-section-player-passage-card .pie-section-player-content-card:has(.pie-section-player-content-card-body [role="tablist"]) .pie-section-player-content-card-body {padding:0 0 1rem;}.pie-section-player-content-card-header.svelte-1qmzs9f {position:relative;display:flex;flex-wrap:wrap;align-items:center;gap:0.75rem;padding:0.75rem 1rem;overflow:visible;border-bottom:1px solid var(--pie-border-light, #e5e7eb);
1249
+ /* Header fill is intentionally transparent by default. Hosts/themes
1250
+ opt-in to a solid color via --pie-section-player-card-header-background
1251
+ (e.g. a brand Bluegreen tint) without this framework encoding a palette. */background:var(--pie-section-player-card-header-background, transparent);
1252
+ /* Default just inside the card radius to avoid a double-radius effect with the border. */border-top-left-radius:var(
1253
+ --pie-section-player-card-header-radius,
1254
+ calc(var(--pie-section-player-card-radius, 8px) - 1px)
1255
+ );border-top-right-radius:var(
1256
+ --pie-section-player-card-header-radius,
1257
+ calc(var(--pie-section-player-card-radius, 8px) - 1px)
1258
+ );}
1259
+
1260
+ /*
1261
+ * Dark themes get their own opt-in fill: a host's light-theme brand tint
1262
+ * surviving into a dark theme is the failure this avoids. Unset, it falls
1263
+ * back to the single light hook, so a host that sets only that one is
1264
+ * unaffected. Keyed off the selectors the theme package writes its dark
1265
+ * tokens under — see renderTokensCss in packages/theme/src/theme-css.ts.
1266
+ */[data-theme="dark"] .pie-section-player-content-card-header.svelte-1qmzs9f,
1267
+ pie-theme[theme="dark"] .pie-section-player-content-card-header.svelte-1qmzs9f {background:var(
1268
+ --pie-section-player-card-header-background-dark,
1269
+ var(--pie-section-player-card-header-background, transparent)
1270
+ );}
1271
+
1272
+ /* Any heading level, not \`h2\`: the card renders at \`base-heading-level\`, so
1273
+ the tag is composition context rather than a fixed choice, and a host that
1274
+ nests the player deeper got an unstyled title. */.pie-section-player-content-card-header.svelte-1qmzs9f :is(h1:where(.svelte-1qmzs9f), h2:where(.svelte-1qmzs9f), h3:where(.svelte-1qmzs9f), h4:where(.svelte-1qmzs9f), h5:where(.svelte-1qmzs9f), h6:where(.svelte-1qmzs9f)) {position:relative;
1275
+ /* Was supplied by the content stylesheet's heading reset, which now
1276
+ applies inside a player's content root only. */line-height:1.2;min-width:0;overflow-wrap:anywhere;z-index:0;margin:0;
1277
+ /* Reads the scale rather than inheriting it: the card wraps the passage
1278
+ shell that \`font-sizes.css\` scales, so nothing above this rule carries
1279
+ the scaled size. Root-relative, so it does not compound with the shell. */font-size:calc(0.95rem * var(--pie-font-scale, 1));font-weight:600;
1280
+ /* Default to the themed body text color so titles stay legible across
1281
+ DaisyUI themes; --pie-header-text remains a host opt-in override. */color:var(--pie-header-text, var(--pie-text, #111827));}.pie-section-player-content-card-header.svelte-1qmzs9f pie-item-toolbar:where(.svelte-1qmzs9f) {position:relative;min-width:0;max-width:100%;z-index:1;margin-left:auto;}
1282
+
1283
+ /* Match item-card overlay layering above the pane's scroll hint (10). */.pie-section-player-content-card-header.svelte-1qmzs9f pie-item-toolbar[data-pie-header-overlay-active="true"] {z-index:11;}.pie-section-player-content-card-body.svelte-1qmzs9f {padding:1rem;color:var(--pie-text, #111827);}`};function H4(e,t){un(t,!0),Mn(e,F4);let r=_(t,"passage",7),n=_(t,"baseHeadingLevel",7,2),i=_(t,"resolvedPlayerTag",7,"div"),o=_(t,"playerAction",7,(N,ne)=>{}),s=_(t,"playerParams",7),a=_(t,"passageToolbarTools",7),l=_(t,"toolRegistry",7,null),d=_(t,"hostButtons",23,()=>[]),c=_(t,"timedMediaStimulus",7,!1);const u=ee(()=>cw(n()));let f=He(null);const p=ee(()=>xa(h(f)));let g=He(null),v=He(null),b=He(null),w=He(null),I=He(!1);const x=on(()=>`pie-section-player-passage-card-heading-${r()?.id??Math.random().toString(36).slice(2,10)}`),C=ee(()=>(h(I)?h(v):null)||i()),L=ee(()=>(h(I)?h(b):null)||o()),E=ee(()=>(h(I)?h(w):null)||null),M=ee(()=>{const N=h(p).t("player.passage");if(!h(E))return N;try{const ne=h(E)({kind:"passage",passage:r(),defaultTitle:N});return typeof ne!="string"?N:ne.trim()||N}catch{return N}}),U=ee(()=>`${x}-media`),te=ee(()=>`${x}-lead`),re=ee(()=>fk({kind:"passage",itemId:r()?.id??"",assessmentId:h(f)?.assessmentId,sectionId:h(f)?.sectionId}));ct(()=>{if(h(g))return Oy(h(g),N=>{be(f,N,!0)})});function Pe(){be(I,!1),be(v,null),be(b,null),be(w,null)}function z(N){!N||typeof N!="object"||(typeof N.resolvedPlayerTag=="string"&&N.resolvedPlayerTag.trim()&&be(v,N.resolvedPlayerTag,!0),typeof N.playerAction=="function"&&be(b,N.playerAction,!0),typeof N.cardTitleFormatter=="function"&&be(w,N.cardTitleFormatter,!0))}let K=He(null),oe=null;function ue(N){const ne=Pu(h(g));ne&&Ms(ne,g$,N)}ct(()=>{if(!c())return;const N=h(K),ne=r()?.id;if(!N||!ne)return;const ge=()=>{const Ne=D4(N);if(Ne!==oe){if(oe&&!Ne){oe=null,ue({renderableId:ne,action:"detach",origin:"native-adapter"});return}Ne&&(oe=Ne,ue({renderableId:ne,action:"attach",source:N4(Ne),origin:"native-adapter"}))}};let Oe=!1;queueMicrotask(()=>{Oe||on(()=>ge())});const We=new MutationObserver(()=>on(()=>ge()));return We.observe(N,{childList:!0,subtree:!0}),()=>{Oe=!0,We.disconnect(),oe&&(oe=null,ue({renderableId:ne,action:"detach",origin:"native-adapter"}))}}),Kp(()=>{const N=Pu(h(g));if(!N)return;be(I,!0);const ne=HR(N,z);return()=>{ne(),Pe()}});var ae={get passage(){return r()},set passage(N){r(N),R()},get baseHeadingLevel(){return n()},set baseHeadingLevel(N=2){n(N),R()},get resolvedPlayerTag(){return i()},set resolvedPlayerTag(N="div"){i(N),R()},get playerAction(){return o()},set playerAction(N=(ne,ge)=>{}){o(N),R()},get playerParams(){return s()},set playerParams(N){s(N),R()},get passageToolbarTools(){return a()},set passageToolbarTools(N){a(N),R()},get toolRegistry(){return l()},set toolRegistry(N=null){l(N),R()},get hostButtons(){return d()},set hostButtons(N=[]){d(N),R()},get timedMediaStimulus(){return c()},set timedMediaStimulus(N=!1){c(N),R()}},X=B4(),j=jn(X);Er(j,N=>be(g,N),()=>h(g));var D=lr(j,2);q(()=>G(D,"item-id",r().id)),G(D,"content-kind","rubric-block-stimulus"),q(()=>G(D,"item",r()));var Z=Xt(D),F=Xt(Z),W=Xt(F);Kh(W,()=>`h${h(u)}`,!1,(N,ne)=>{CT(N,()=>({id:x,"data-pie-tool-overlay-protect":!0,class:""}),void 0,void 0,void 0,"svelte-1qmzs9f");var ge=fT();q(()=>vs(ge,h(M))),ft(ne,ge)});var O=lr(W,2);q(()=>G(O,"item-id",r().id)),q(()=>G(O,"catalog-id",r().id)),q(()=>G(O,"tools",a())),G(O,"content-kind","rubric-block-stimulus"),G(O,"size","md"),G(O,"language","en-US"),q(()=>G(O,"toolRegistry",l())),q(()=>G(O,"hostButtons",d())),gn(O,1,"svelte-1qmzs9f"),Kt(F);var $=lr(F,2);pw($,{get regionId(){return h(te)},get surface(){return zR},get ownerContext(){return h(re)},get runtimeContext(){return h(f)},get toolRegistry(){return l()}});var ie=lr($,2);{const N=ge=>{var Oe=j4(),We=Xt(Oe);Kh(We,()=>h(C),!1,(Ne,xe)=>{bT(Ne,(et,Ue)=>h(L)?.(et,Ue),s),gn(Ne,0,"svelte-1qmzs9f")}),Kt(Oe),Er(Oe,Ne=>be(K,Ne),()=>h(K)),ft(ge,Oe)};let ne=ee(()=>h(p).t("player.resizePassageAndMediaA11y"));hw(ie,{get regionId(){return h(U)},get ownerContext(){return h(re)},get runtimeContext(){return h(f)},get toolRegistry(){return l()},get dividerAriaLabel(){return h(ne)},content:N,$$slots:{content:!0}})}return Kt(Z),Kt(D),ft(e,X),fn(ae)}z4("pie-section-player-passage-card",In(H4,{passage:{type:"Object"},baseHeadingLevel:{attribute:"base-heading-level",type:"Number"},resolvedPlayerTag:{attribute:"resolved-player-tag",type:"String"},playerAction:{type:"Object"},playerParams:{attribute:"player-params",type:"Object"},passageToolbarTools:{attribute:"passage-toolbar-tools",type:"String"},timedMediaStimulus:{attribute:"timed-media-stimulus",type:"Boolean"},toolRegistry:{type:"Object"},hostButtons:{type:"Object"}},[],[],void 0,Zs));function z4(e,t){customElements.get(e)||customElements.define(e,t)}function W4(e){let t=He(Ti({status:"idle"})),r=0;return ct(()=>{const n=e();if(!n){be(t,{status:"idle"},!0);return}const i=++r;be(t,{status:"pending"},!0),n.then(o=>{i===r&&be(t,{status:"resolved",data:o},!0)},o=>{i===r&&be(t,{status:"rejected",error:o},!0)})}),{get current(){return h(t)}}}var U4=Ht('<p class="pie-section-player-timed-media-status svelte-potd9r" data-pie-timed-media-status="" aria-live="polite"> </p>'),q4=Ht('<div class="pie-section-player-content-card svelte-potd9r"><div class="pie-section-player-content-card-body pie-section-player-item-content pie-section-player__item-content svelte-potd9r"> </div></div>'),V4=Ht("<pie-section-player-item-card></pie-section-player-item-card>",2),G4=Ht("<nds-icon-button></nds-icon-button>",2),K4=Ht('<button type="button" class="pie-section-player-scroll-hint__button svelte-potd9r"><svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true" focusable="false"><path d="M4 6l4 4 4-4" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"></path></svg></button>'),X4=Ht('<div style="display:none" aria-hidden="true"></div> <!> <!> <div class="pie-section-player-scroll-hint svelte-potd9r"><!></div>',1),Z4={hash:"svelte-potd9r",code:`:host {display:flex;flex-direction:column;gap:1rem;min-height:0;min-width:0;}.pie-section-player-scroll-hint.svelte-potd9r {position:sticky;bottom:0;height:56px;margin-top:calc(-56px - 1rem);background:linear-gradient(to bottom, rgba(255, 255, 255, 0) 0%, var(--pie-white, #fff) 100%);display:flex;align-items:flex-start;justify-content:center;padding-top:4px;z-index:10;
1284
+ /* so the buttons behind are still clickable, but the hint itself is not */pointer-events:none;}
1285
+
1286
+ /* so the "scroll down" button still works */.pie-section-player-scroll-hint.svelte-potd9r nds-icon-button:where(.svelte-potd9r),
1287
+ .pie-section-player-scroll-hint__button.svelte-potd9r {pointer-events:auto;}.pie-section-player-scroll-hint.svelte-potd9r nds-icon-button:where(.svelte-potd9r) {
1288
+ /* NDS palette bridge — keep in sync with the copies in tool-tts-inline
1289
+ and assessment-toolkit ItemToolBar (asserted by
1290
+ scripts/check-theme-tokens.mjs). The vendored button paints its glyph,
1291
+ fill, hover ring and focus ring from the NDS design-system palette,
1292
+ which no PIE theme sets, so this scroll-down control kept a #146eb3
1293
+ glyph on a #f3f5f7 pill under every theme while the fallback button
1294
+ beside it followed the tokens. */--color-interactive-blue: var(--pie-button-color, var(--pie-text, #222));--color-new-gray: var(--pie-background-dark, #f3f5f7);--color-primary-white: var(--pie-white, #ffffff);--color-primary-black: var(--pie-text, #000000);--color-focus-blue: var(--pie-button-focus-outline, #2b87ff);}
1295
+
1296
+ /* Non-NDS fallback button: a compact circular control mirroring the NDS
1297
+ tertiary icon button's footprint. */.pie-section-player-scroll-hint__button.svelte-potd9r {display:inline-flex;align-items:center;justify-content:center;width:2rem;height:2rem;padding:0;border:1px solid var(--pie-border, #c6c6c6);border-radius:50%;background:var(--pie-white, #fff);color:var(--pie-text, #222);cursor:pointer;}.pie-section-player-scroll-hint__button.svelte-potd9r:focus-visible {outline:2px solid var(--pie-button-focus-outline, var(--pie-primary, #0066cc));outline-offset:2px;}
1298
+
1299
+ /* Keep content readable when space is scarce, including browser zoom.
1300
+ The chevron retains its full target size; window width ratios are not zoom. */
1301
+ @media (max-width: 839px), (max-height: 480px) {.pie-section-player-scroll-hint.svelte-potd9r {background:none;}
1302
+ }.pie-section-player-content-card.svelte-potd9r {border:1px solid var(--pie-border-light, #e5e7eb);border-radius:8px;background:var(--pie-background, #fff);}
1303
+
1304
+ /* Painted only from \`--pie-*\` chains, so it follows every base theme and colour
1305
+ scheme without a hook of its own — same rule as the formative status line, and
1306
+ colour is never the only signal here either. */.pie-section-player-timed-media-status.svelte-potd9r {margin:0;padding:0.5rem 0.75rem;border:1px solid var(--pie-border-light, #e5e7eb);border-radius:var(--pie-section-player-card-radius, 8px);background:var(--pie-background, #fff);color:var(--pie-text, #111827);font-size:calc(0.9rem * var(--pie-font-scale, 1));}
1307
+
1308
+ /* Collapsed, not removed: \`display: none\` takes the element out of the
1309
+ accessibility tree, and a live region that did not exist when its first message
1310
+ arrived does not announce it (WCAG 4.1.3). The region is rendered before it has
1311
+ content for exactly that reason. */.pie-section-player-timed-media-status.svelte-potd9r:empty {padding:0;border:0;block-size:0;overflow:hidden;}
1312
+
1313
+ /* The gated card takes focus, so it needs a visible focus indicator of its own;
1314
+ the card is not otherwise focusable. */pie-section-player-item-card [data-pie-timed-media-gate="holding"]:focus-visible {outline:3px solid
1315
+ var(--pie-section-player-focus-outline, var(--pie-focus-outline, #146eb3));outline-offset:2px;}.pie-section-player-content-card-body.svelte-potd9r {padding:1rem;}`};function Y4(e,t){un(t,!0),Mn(e,Z4);let r=_(t,"items",23,()=>[]),n=_(t,"compositionModel",7),i=_(t,"resolvedPlayerEnv",23,()=>({})),o=_(t,"resolvedPlayerAttributes",23,()=>({})),s=_(t,"resolvedPlayerProps",23,()=>({})),a=_(t,"playerStrategy",7,"preloaded"),l=_(t,"baseHeadingLevel",7,2),d=_(t,"itemToolbarTools",7,""),c=_(t,"toolRegistry",7,null),u=_(t,"hostButtons",23,()=>[]),f=_(t,"iifeBundleHost",7,""),p=_(t,"preloadedRenderables",23,()=>[]),g=_(t,"preloadedRenderablesSignature",7,""),v=_(t,"preloadComponentTag",7,"pie-section-player-items-pane"),b=_(t,"preloadEnabled",7,!0);const w=tc(),I=ee(()=>$R(v())),x=ee(()=>JSON.stringify(p().map((le,Ae)=>{const Y=le??{},we=typeof Y.id=="string"&&Y.id?Y.id:`renderable-${Ae}`,_e=Y.config?.elements??{};return`${we}:${Object.entries(_e??{}).filter(([Be,it])=>typeof Be=="string"&&Be.length>0&&typeof it=="string"&&it.length>0).sort(([Be],[it])=>Be.localeCompare(it)).map(([Be,it])=>`${Be}=${it}`).join(",")}`}))),C=ee(()=>JSON.stringify({preloadEnabled:b(),strategy:a(),renderables:h(x),iifeBundleHost:f(),mode:s()?.mode??null,hosted:s()?.hosted??null,envMode:i()?.mode??null,loaderOptions:s()?.loaderOptions??null})),L=W4(()=>(h(C),b()?on(()=>rz({strategy:a(),renderables:p(),resolvedPlayerProps:s(),resolvedPlayerEnv:i(),iifeBundleHost:f(),logger:h(I),onBundleRetryStatus:le=>{let Ae=null;try{Ae=fy({strategy:a(),resolvedPlayerProps:s(),resolvedPlayerEnv:i(),iifeBundleHost:f()})}catch{Ae=null}const Y=Math.max(le.retryDelayMs??0,1),we=Math.max(1,Math.ceil(le.timeoutMs/Y));w("element-preload-retry",{componentTag:v(),stage:"iife-load",attempt:le.attempt,maxRetries:we,error:le.reason??le.state,strategy:a(),bundleType:Q1(Ae),bundleHost:eI(Ae),renderablesCount:p().length})}})):on(()=>Promise.resolve()))),E=ee(()=>L.current.status==="resolved");let M=He(null);ct(()=>{L.current.status==="resolved"&&be(M,h(x),!0)});const U=ee(()=>h(E)||h(M)===h(x));ct(()=>{w("elements-loaded-change",{elementsLoaded:h(E),renderablesSignature:g()})});function te(le){return le instanceof Rh?{stage:le.stage,cause:le.cause}:{stage:a()==="esm"?"esm-load":"iife-load",cause:le}}function re(le){const{stage:Ae,cause:Y}=te(le),we=HT({kind:"element-preload",source:v(),message:uy(Ae,Y),details:[`stage=${Ae}`,`strategy=${a()}`,`renderablesCount=${p().length}`],recoverable:!1,cause:Y});try{h(N)?.reportSectionError?.(we)}catch(it){h(I).warn("element-preload section error report failed:",it)}const _e=h(N)?.toolkitCoordinator;if(typeof _e?.reportFrameworkError=="function")try{_e.reportFrameworkError(we);return}catch(it){h(I).warn("element-preload framework error report failed:",it)}const Be=h(F)?.parentElement;if(Be){Be.dispatchEvent(new CustomEvent("framework-error",{detail:we,bubbles:!0,composed:!0}));return}h(I).warn(we.message,Y)}function Pe(le){const{stage:Ae,cause:Y}=te(le);h(I).error(uy(Ae,Y));let we=null;try{we=fy({strategy:a(),resolvedPlayerProps:s(),resolvedPlayerEnv:i(),iifeBundleHost:f()})}catch{we=null}w("element-preload-error",{componentTag:v(),stage:Ae,error:Sm(Y),strategy:a(),bundleType:Q1(we),bundleHost:eI(we),renderablesCount:p().length})}ct(()=>{const le=L.current;le.status==="rejected"&&on(()=>{re(le.error),Pe(le.error)})});const z=ee(()=>Number.isFinite(n()?.currentItemIndex)?Math.max(0,Number(n().currentItemIndex)):-1),K=ee(()=>n()?.timedMedia??null),oe=ee(()=>h(K)?.gate??null),ue=ee(()=>h(oe)?.holding===!0);function ae(le){const Ae=r().findIndex(Y=>oI({compositionModel:n(),item:Y})===le);return Ae>=0?Ae+1:1}let X=He(""),j=null,D=0,Z=null;ct(()=>{const le=h(K),Ae=h(ue)?h(oe)?.cueIdentifier??null:null,Y=le?.revealedItemIds.length??0,we=h(oe)?.enforcement==="enforced",_e=h(oe)?.itemRefs[0]??"",Be=le?.revealedItemIds[Y-1]??"";on(()=>{if(!le){be(X,""),j=null,D=0;return}if(Ae&&Ae!==j){j=Ae,D=Y,Z=Ae,be(X,h(ne).t(we?"player.timedMedia.playbackPaused":"player.timedMedia.playbackAdvisory",{position:ae(_e)}),!0);return}if(!Ae&&j){j=null,D=Y,be(X,h(ne).t("player.timedMedia.playbackReleased"),!0);return}if(h(X)===""){D=Y,be(X,Y===0?h(ne).t("player.timedMedia.waitingForMedia"):h(ne).t("player.timedMedia.questionAvailable",{position:ae(Be)}),!0);return}Y!==D&&(D=Y,be(X,Y===0?h(ne).t("player.timedMedia.waitingForMedia"):h(ne).t("player.timedMedia.questionAvailable",{position:ae(Be)}),!0))})}),ct(()=>{const le=h(ue)?h(oe)?.cueIdentifier??null:null;le&&on(()=>{Z===le&&(Z=null,queueMicrotask(()=>{(h(F)?.parentElement??null)?.querySelector('[data-pie-timed-media-gate="holding"]')?.focus()}))})});let F=He(null),W=He(!1),O=He(null),$=He(void 0);const ie=ee(()=>h($)===!0);let N=He(void 0);const ne=ee(()=>xa(h(N)));ct(()=>{if(h(F))return Oy(h(F),le=>{be($,le?.ndsIcons,!0),be(N,le,!0)})});const ge=()=>h(O)?.scrollBy({top:150,behavior:"smooth"}),Oe=le=>{for(let Ae=le;Ae&&Ae!==document.body;Ae=Ae.parentElement){const{overflowY:Y}=getComputedStyle(Ae);if(Y==="auto"||Y==="scroll"||Y==="overlay")return Ae}return null};Kp(()=>{const le=h(F)?.parentElement??null;if(!le)return;let Ae=null,Y=null,we=null,_e=null;const Be=()=>{const ot=Ae;if(!ot)return;const $r=ot.scrollHeight,Ur=ot.clientHeight,Lr=$r-ot.scrollTop<=Ur+1,ln=$r>Ur&&!Lr;ln!==h(W)&&be(W,ln,!0)},it=()=>{const ot=Oe(le.parentElement);ot&&(Ae=ot,be(O,ot,!0),we=new ResizeObserver(Bt),we.observe(ot),ot.addEventListener("scroll",Bt,{passive:!0}),_e=()=>ot.removeEventListener("scroll",Bt))},tt=()=>{Y=null,Ae||it(),Be()},Bt=()=>{Y===null&&(Y=setTimeout(tt,0))},ht=new MutationObserver(Bt);return ht.observe(le,{childList:!0,subtree:!0,characterData:!0}),Bt(),()=>{Y!==null&&(clearTimeout(Y),Y=null),ht.disconnect(),we?.disconnect(),_e?.()}});var We={get items(){return r()},set items(le=[]){r(le),R()},get compositionModel(){return n()},set compositionModel(le){n(le),R()},get resolvedPlayerEnv(){return i()},set resolvedPlayerEnv(le={}){i(le),R()},get resolvedPlayerAttributes(){return o()},set resolvedPlayerAttributes(le={}){o(le),R()},get resolvedPlayerProps(){return s()},set resolvedPlayerProps(le={}){s(le),R()},get playerStrategy(){return a()},set playerStrategy(le="preloaded"){a(le),R()},get baseHeadingLevel(){return l()},set baseHeadingLevel(le=2){l(le),R()},get itemToolbarTools(){return d()},set itemToolbarTools(le=""){d(le),R()},get toolRegistry(){return c()},set toolRegistry(le=null){c(le),R()},get hostButtons(){return u()},set hostButtons(le=[]){u(le),R()},get iifeBundleHost(){return f()},set iifeBundleHost(le=""){f(le),R()},get preloadedRenderables(){return p()},set preloadedRenderables(le=[]){p(le),R()},get preloadedRenderablesSignature(){return g()},set preloadedRenderablesSignature(le=""){g(le),R()},get preloadComponentTag(){return v()},set preloadComponentTag(le="pie-section-player-items-pane"){v(le),R()},get preloadEnabled(){return b()},set preloadEnabled(le=!0){b(le),R()}},Ne=X4(),xe=jn(Ne);Er(xe,le=>be(F,le),()=>h(F));var et=lr(xe,2),Ue=le=>{var Ae=U4(),Y=Ta(Ae,!0);q(()=>vs(Y,h(X))),ft(le,Ae)};vn(et,le=>{h(K)&&le(Ue)});var Se=lr(et,2),Re=le=>{var Ae=q4(),Y=Xt(Ae),we=Ta(Y,!0);Kt(Ae),q(_e=>vs(we,_e),[()=>h(ne).t(L.current.status==="rejected"?"player.sectionLoadError":"player.loadingSection")]),ft(le,Ae)},mt=le=>{var Ae=Nl(),Y=jn(Ae);yT(Y,19,r,(we,_e)=>we.id||_e,(we,_e,Be)=>{const it=ee(()=>oI({compositionModel:n(),item:h(_e)})),tt=ee(()=>Oz({compositionModel:n(),canonicalItemId:h(it)})),Bt=ee(()=>Nz({compositionModel:n(),canonicalItemId:h(it)}));var ht=V4();q(()=>G(ht,"hidden",h(Bt)?.pending===!0)),q(()=>G(ht,"item",h(_e))),q(()=>G(ht,"itemIndex",h(Be))),q(()=>G(ht,"itemCount",r().length)),q(()=>G(ht,"isCurrent",h(Be)===h(z))),q(()=>G(ht,"canonicalItemId",h(it))),q(()=>G(ht,"baseHeadingLevel",l())),q(ot=>G(ht,"playerParams",ot),[()=>Bz({item:h(_e),compositionModel:n(),resolvedPlayerEnv:i(),resolvedPlayerAttributes:o(),resolvedPlayerProps:s(),playerStrategy:a(),itemIndex:h(Be),baseHeadingLevel:l(),formativeView:h(tt)})]),q(()=>G(ht,"formativeView",h(tt))),q(()=>G(ht,"timedMediaView",h(Bt))),q(()=>G(ht,"itemToolbarTools",d())),q(()=>G(ht,"toolRegistry",c())),q(()=>G(ht,"hostButtons",u())),ft(we,ht)}),ft(le,Ae)};vn(Se,le=>{h(U)?le(mt,-1):le(Re)});var $t=lr(Se,2);let ve;var me=Xt($t),Je=le=>{var Ae=G4();G(Ae,"variant","tertiary"),G(Ae,"size","small"),G(Ae,"icon-name","chevron-down"),q(Y=>G(Ae,"button-aria-label",Y),[()=>h(ne).t("player.scrollDownA11y")]),gn(Ae,1,"svelte-potd9r"),lo("click",Ae,ge),ft(le,Ae)},Gt=le=>{var Ae=K4();q(Y=>nt(Ae,"aria-label",Y),[()=>h(ne).t("player.scrollDownA11y")]),lo("click",Ae,ge),ft(le,Ae)};return vn(me,le=>{h(ie)?le(Je):le(Gt,-1)}),Kt($t),q(()=>ve=Dl($t,"",ve,{visibility:h(W)?"visible":"hidden"})),ft(e,Ne),fn(We)}cd(["click"]);J4("pie-section-player-items-pane",In(Y4,{items:{type:"Object"},compositionModel:{attribute:"composition-model",type:"Object"},resolvedPlayerEnv:{attribute:"resolved-player-env",type:"Object"},resolvedPlayerAttributes:{attribute:"resolved-player-attributes",type:"Object"},resolvedPlayerProps:{attribute:"resolved-player-props",type:"Object"},playerStrategy:{attribute:"player-strategy",type:"String"},baseHeadingLevel:{attribute:"base-heading-level",type:"Number"},itemToolbarTools:{attribute:"item-toolbar-tools",type:"String"},toolRegistry:{type:"Object"},hostButtons:{type:"Object"},iifeBundleHost:{attribute:"iife-bundle-host",type:"String"},preloadedRenderables:{attribute:"preloaded-renderables",type:"Object"},preloadedRenderablesSignature:{attribute:"preloaded-renderables-signature",type:"String"},preloadComponentTag:{attribute:"preload-component-tag",type:"String"},preloadEnabled:{attribute:"preload-enabled",type:"Boolean"}},[],[],void 0,Zs));function J4(e,t){customElements.get(e)||customElements.define(e,t)}function uf(e){let t=He(null);ct(()=>{const n=e();if(n)return ck(n,i=>{be(t,i,!0)})});const r=ee(()=>xa(h(t)));return{get provider(){return h(r)},get locale(){return h(r).getLocale()},get direction(){return h(r).getDirection?.()??"ltr"},t(n,i){return h(r).t(n,i)},plural(n,i){return h(r).plural?.(n,i)??h(r).t(n,i)}}}var Q4=Ht('<div class="pie-section-player-content-card svelte-1mpods8"><div class="pie-section-player-content-card-body pie-section-player-passage-content pie-section-player__passage-content svelte-1mpods8"> </div></div>'),e8=Ht("<pie-section-player-passage-card></pie-section-player-passage-card>",2),t8={hash:"svelte-1mpods8",code:":host {display:flex;flex-direction:column;gap:1rem;min-height:0;min-width:0;}.pie-section-player-content-card.svelte-1mpods8 {border:1px solid var(--pie-border-light, #e5e7eb);border-radius:8px;background:var(--pie-background, #fff);}.pie-section-player-content-card-body.svelte-1mpods8 {padding:1rem;}"};function r8(e,t){un(t,!0),Mn(e,t8);let r=_(t,"passages",23,()=>[]),n=_(t,"elementsLoaded",7,!1),i=_(t,"resolvedPlayerEnv",23,()=>({})),o=_(t,"resolvedPlayerAttributes",23,()=>({})),s=_(t,"resolvedPlayerProps",23,()=>({})),a=_(t,"playerStrategy",7,"preloaded"),l=_(t,"baseHeadingLevel",7,2),d=_(t,"passageToolbarTools",7,""),c=_(t,"toolRegistry",7,null),u=_(t,"hostButtons",23,()=>[]),f=_(t,"compositionModel",7,null),p=He(null);const g=uf(()=>h(p)),v=ee(()=>f()?.timedMedia?.stimulusRenderableId??""),b=ee(()=>{if(!h(v))return r();const E=r().filter(M=>M.id===h(v));return E.length===0?r():[...E,...r().filter(M=>M.id!==h(v))]});var w={get passages(){return r()},set passages(E=[]){r(E),R()},get elementsLoaded(){return n()},set elementsLoaded(E=!1){n(E),R()},get resolvedPlayerEnv(){return i()},set resolvedPlayerEnv(E={}){i(E),R()},get resolvedPlayerAttributes(){return o()},set resolvedPlayerAttributes(E={}){o(E),R()},get resolvedPlayerProps(){return s()},set resolvedPlayerProps(E={}){s(E),R()},get playerStrategy(){return a()},set playerStrategy(E="preloaded"){a(E),R()},get baseHeadingLevel(){return l()},set baseHeadingLevel(E=2){l(E),R()},get passageToolbarTools(){return d()},set passageToolbarTools(E=""){d(E),R()},get toolRegistry(){return c()},set toolRegistry(E=null){c(E),R()},get hostButtons(){return u()},set hostButtons(E=[]){u(E),R()},get compositionModel(){return f()},set compositionModel(E=null){f(E),R()}},I=Nl(),x=jn(I),C=E=>{var M=Q4(),U=Xt(M),te=Ta(U,!0);Kt(M),Er(M,re=>be(p,re),()=>h(p)),q(re=>vs(te,re),[()=>g.t("player.loadingPassage")]),ft(E,M)},L=E=>{var M=Nl(),U=jn(M);yT(U,19,()=>h(b),(te,re)=>te.id||re,(te,re)=>{var Pe=e8();q(()=>G(Pe,"passage",h(re))),q(()=>G(Pe,"baseHeadingLevel",l())),q(()=>G(Pe,"timedMediaStimulus",!!h(v)&&h(re).id===h(v))),q(z=>G(Pe,"playerParams",z),[()=>Lz({passage:h(re),resolvedPlayerEnv:i(),resolvedPlayerAttributes:o(),resolvedPlayerProps:s(),playerStrategy:a(),baseHeadingLevel:l()})]),q(()=>G(Pe,"passageToolbarTools",d())),q(()=>G(Pe,"toolRegistry",c())),q(()=>G(Pe,"hostButtons",u())),ft(te,Pe)}),ft(E,M)};return vn(x,E=>{n()?E(L,-1):E(C)}),ft(e,I),fn(w)}n8("pie-section-player-passages-pane",In(r8,{passages:{type:"Object"},elementsLoaded:{attribute:"elements-loaded",type:"Boolean"},resolvedPlayerEnv:{attribute:"resolved-player-env",type:"Object"},resolvedPlayerAttributes:{attribute:"resolved-player-attributes",type:"Object"},resolvedPlayerProps:{attribute:"resolved-player-props",type:"Object"},playerStrategy:{attribute:"player-strategy",type:"String"},baseHeadingLevel:{attribute:"base-heading-level",type:"Number"},passageToolbarTools:{attribute:"passage-toolbar-tools",type:"String"},compositionModel:{attribute:"composition-model",type:"Object"},toolRegistry:{type:"Object"},hostButtons:{type:"Object"}},[],[],void 0,Zs));function n8(e,t){customElements.get(e)||customElements.define(e,t)}function i8(e){const t=e;return typeof t?.canRequestTool!="function"||typeof t.requestTool!="function"?null:t}var o8=[{toolId:"dictionary",label:"Look up selected text in dictionary",tooltip:"Look up",icon:"book-open"},{toolId:"pictureDictionary",label:"Show pictures for selected text",tooltip:"Show pictures",icon:"photo"}];function s8(e){const t=i8(e.toolkitCoordinator);return t?o8.map(r=>{const n=qz(r.icon)??void 0;return{id:r.toolId,label:r.label,tooltip:r.tooltip,iconSvg:n,isAvailable:()=>t.canRequestTool(r.toolId),run:i=>{const o=i.text.trim();o&&t.requestTool({toolId:r.toolId,params:{term:o}})}}}):[]}var a8=async()=>(await br(async()=>{const{ServerTTSProvider:e}=await import("./chunks/dist-ca9b9622.js");return{ServerTTSProvider:e}},[],import.meta.url)).ServerTTSProvider,Ld=new Map,ZR="__pieToolElementUnmount",pI="pie-tool-active-change",l8={toolId:"textToSpeech",name:"Text to Speech",description:"Read content aloud",nameKey:"tools.textToSpeech.name",descriptionKey:"tools.textToSpeech.description",icon:"volume-up",provider:{getProviderId:()=>"tts",createProvider:e=>{const t=Am(e);return new nL(Nw(t),{loadServerProvider:a8})},getInitConfig:e=>{const t=Am(e),r=Nw(t),n=tP(t,r);return{backend:r,serverProvider:n,transportMode:rP(t,n),...oP(t)}},getAuthFetcher:e=>{const t=e?.provider?.runtime?.authFetcher;return typeof t=="function"?t:void 0},sanitizeConfig:e=>{const t=e.settings&&typeof e.settings=="object"?{...e.settings}:void 0;t&&"layoutMode"in t&&(t.layoutMode=Dw(t.layoutMode)),t&&"speedOptions"in t&&(t.speedOptions=Mm(t.speedOptions));const r={...e};return"layoutMode"in r&&(r.layoutMode=Dw(r.layoutMode)),"speedOptions"in r&&(r.speedOptions=Mm(r.speedOptions)),t&&(r.settings=t),r},lazy:!0},supportedLevels:["item","passage"],pnpSupportIds:["textToSpeech","readAloud"],isVisibleInContext(e){return Ku(e)},renderToolbar(e,t){const r=()=>Am(t.toolkitCoordinator?.getToolConfig(this.toolId)||void 0),n=()=>{const c=r();return Mm(c.speedOptions)},i=()=>iP(r()),o=()=>nP(r()),s=sb(this.toolId,t.scope.level,t.scope.scopeId),a=()=>{const c=t.ui?.size;return c==="sm"||c==="lg"?c:"md"},l=()=>{let c=Ld.get(s);return c&&typeof c.isConnected=="boolean"&&!c.isConnected&&(Ld.delete(s),c=void 0),c||(c=document.createElement("pie-tool-tts-inline"),c[ZR]=()=>{Ld.get(s)===c&&Ld.delete(s)},Ld.set(s,c)),c.setAttribute("catalog-id",t.catalogId||t.itemId),c.setAttribute("language",t.language||"en-US"),c.setAttribute("size",a()),c.setAttribute("layout-mode",i()),c.speedOptions=n(),c.showSingleSpeedOption=r().showSingleSpeedOption===!0,c},d=o();return{toolId:this.toolId,button:null,elements:[{element:l(),mount:d.mount,layoutHints:{controlsRow:{reserveSpace:d.controlsRow.reserveSpace,showWhenToolActive:d.controlsRow.expandWhenToolActive},headerOverlay:{showWhenToolActive:d.headerOverlay.expandWhenToolActive}}}],subscribeActive:c=>{const u=l(),f=p=>{const g=p.detail;c(g?.active===!0)};return u.addEventListener(pI,f),()=>{u.removeEventListener(pI,f)}},sync:()=>{const c=l();c.setAttribute("tool-id",s),c.setAttribute("catalog-id",t.catalogId||t.itemId),c.setAttribute("language",t.language||"en-US"),c.setAttribute("size",a()),c.setAttribute("layout-mode",i()),c.speedOptions=n(),c.showSingleSpeedOption=r().showSingleSpeedOption===!0}}}},mI=new WeakMap;function Im(e,t,r){const n=e.toolCoordinator;if(!n)return r();let i=mI.get(n);const o=i?.get(t);if(o?.isConnected)return o;const s=r();return i||(i=new Map,mI.set(n,i)),i.set(t,s),s[ZR]=()=>{queueMicrotask(()=>{!s.isConnected&&i.get(t)===s&&i.delete(t)})},s}function lc(e,t,r,n={}){const{toolId:i}=e,o=uw(i,r),s={toolId:i,label:e.name,icon:typeof e.icon=="function"?e.icon(t):e.icon,disabled:!1,ariaLabel:r.i18n.t(`tools.${i}.buttonA11y`),tooltip:r.i18n.t(`tools.${i}.tooltip`),onClick:()=>r.toggleTool(i),active:o.isActive()},a=r.componentOverrides??{},l=Im(r,o.fullToolId,()=>Qp(i,t,r,a));return l.setAttribute("tool-id",o.fullToolId),n.surface==="frameless"&&e4(l,"frameless"),{toolId:i,button:s,elements:[{element:l,mount:"after-buttons",...n.surface==="frameless"?{container:"content-boundary"}:{},...n.shell?{shell:{title:k$(e,r.i18n),draggable:!0,closeable:!0,...n.shell}}:{}}],sync:()=>{fw({button:s,overlay:l,isActive:o.isActive}),n.handsOverCoordinator&&r.toolkitCoordinator&&(l.toolkitCoordinator=r.toolkitCoordinator)},subscribeActive:o.subscribeActive}}var c8={toolId:"lineReader",name:"Line Reader",description:"Reading guide overlay",nameKey:"tools.lineReader.name",descriptionKey:"tools.lineReader.description",icon:"bars-3",supportedLevels:["section","passage","rubric","item"],pnpSupportIds:["readingMask","readingGuide","readingRuler"],isVisibleInContext(e){return Ku(e)},renderToolbar(e,t){return lc(this,e,t,{surface:"frameless",handsOverCoordinator:!0})}},d8={toolId:"theme",name:"Theme",description:"Accessible themes and contrast",nameKey:"tools.theme.name",descriptionKey:"tools.theme.description",icon:"swatch",supportedLevels:["assessment","section"],pnpSupportIds:["highContrastDisplay","colorContrast","invertColors","theme"],isVisibleInContext(e){return!0},renderToolbar(e,t){return lc(this,e,t,{shell:{resizable:!1,initialWidth:520,initialHeight:380,minWidth:420,minHeight:300},handsOverCoordinator:!0})}},u8={toolId:"annotationToolbar",name:"Highlighter",description:"Highlight and annotate text",nameKey:"tools.annotationToolbar.name",descriptionKey:"tools.annotationToolbar.description",icon:"highlighter",activation:"selection-gateway",singletonScope:"section",surfaces:["section-overlay"],supportedLevels:["passage","rubric","item","element"],pnpSupportIds:["highlighting","annotations"],isVisibleInContext(e){return Ku(e)},renderSurface(e){const t=e.componentOverrides??{},r=zT(e.toolId,t);if(typeof customElements<"u"&&!customElements.get(r))return null;const n=document.createElement(r),i=o=>{n.enabled=!0,n.ttsService=o.services.ttsService,n.highlightCoordinator=o.services.toolkitCoordinator?.highlightCoordinator??null,n.selectionActions=s8(o.services)};return i(e),{element:n,sync:i}},renderToolbar(e,t){return lc(this,e,t,{handsOverCoordinator:!0})}},gI="transcript";var my="pie-tool-audio-transcript",f8="always",h8=e=>!!e&&e.catalog==="transcript",p8=e=>typeof e.visibility=="string"&&e.visibility.trim().toLowerCase()===f8,m8=e=>typeof e.content=="string"?e.content.trim():"";function g8(e){if(!e.catalogs)return null;let t=null;for(const{catalogId:r,card:n}of e.catalogs.cards){if(!h8(n))continue;const i=m8(n);if(!i)continue;const o={catalogId:r,text:i,language:typeof n.language=="string"?n.language:void 0,always:p8(n)};if(o.always)return o;t??(t=o)}return t&&e.granted?t:null}var v8="content-lead";function y8(){const e=document.createElement("section");e.className=my,e.setAttribute("role","region");const t=document.createElement("p");return t.className=`${my}__text`,e.appendChild(t),e}var vI=(e,t)=>{const r=e.querySelector(`.${my}__text`);r&&(r.textContent=t?.text??"",t?.language?e.setAttribute("lang",t.language):e.removeAttribute("lang"),e.dataset.transcriptVisibility=t?.always?"always":"onGrant")},b8={toolId:gI,name:"Audio Transcript",description:"Text of an audio prompt, read before the content it transcribes",nameKey:"tools.audioTranscript.name",descriptionKey:"tools.audioTranscript.description",supportedLevels:["item","passage"],pnpSupportIds:[gI],activation:"region",surfaces:[v8],requiresAuthoredContent:{resolve(e){return g8(e)},description:"An accessibility catalog card of type `transcript` on the item or passage"},resolvesWithoutGrant:!0,renderSurface(e){const t=e.content;if(!t)return null;const r=y8();return vI(r,t),{element:r,ariaLabel:e.services.i18n?.t("tools.audioTranscript.regionA11y")??"Transcript",sync:n=>vI(r,n.content)}}},mw=class{constructor(){T(this,"category","calculator"),T(this,"calculatorProvider",null),T(this,"initializationPromise",null),T(this,"lifecycleGeneration",0)}async emitTelemetry(e,t,r){try{await e.onTelemetry?.(t,r)}catch(n){console.warn(`[${this.providerName}] telemetry callback failed:`,n)}}async initialize(e={}){if(this.calculatorProvider)return;if(this.initializationPromise)return this.initializationPromise;const t=++this.lifecycleGeneration,r=this.initializeProvider(e,t);this.initializationPromise=r;try{await r}finally{this.initializationPromise===r&&(this.initializationPromise=null)}}async initializeProvider(e,t){const r=this.getDefinition(),n=Date.now();await this.emitTelemetry(e,"pie-tool-library-load-start",{toolId:"calculator",operation:r.moduleImportOperation,backend:r.backend});let i;try{i=await r.loadProvider(),await this.emitTelemetry(e,"pie-tool-library-load-success",{toolId:"calculator",operation:r.moduleImportOperation,backend:r.backend,duration:Date.now()-n})}catch(s){throw await this.emitTelemetry(e,"pie-tool-library-load-error",{toolId:"calculator",operation:r.moduleImportOperation,backend:r.backend,duration:Date.now()-n,errorType:"ToolLibraryLoadError",message:s instanceof Error?s.message:String(s)}),new Error(r.initializationErrorMessage,{cause:s})}if(t!==this.lifecycleGeneration)throw new Error(`${this.providerName} initialization was cancelled`);const o=new i;try{if(await o.initialize(e),t!==this.lifecycleGeneration)throw new Error(`${this.providerName} initialization was cancelled`);this.calculatorProvider=o}catch(s){throw o.destroy(),new Error(r.initializationErrorMessage,{cause:s})}}async createInstance(){if(!this.calculatorProvider)throw new Error(`[${this.providerName}] Provider not initialized. Call initialize() first.`);return this.calculatorProvider}isReady(){return this.calculatorProvider!==null}destroy(){this.lifecycleGeneration+=1,this.initializationPromise=null,this.calculatorProvider?.destroy(),this.calculatorProvider=null}},w8=class extends mw{constructor(...e){super(...e),T(this,"providerId","cortex-calculator"),T(this,"providerName","PIE Open-Source Calculator"),T(this,"version","1"),T(this,"requiresAuth",!1)}getDefinition(){return{backend:"cortex",moduleImportOperation:"cortex-provider-module-import",loadProvider:async()=>(await br(()=>import("./chunks/dist-41b39e7f.js").then(e=>e.t),[],import.meta.url)).CortexCalculatorProvider,initializationErrorMessage:"Failed to initialize the PIE open-source calculator provider. Confirm that this browser supports module workers and that the bundled worker assets are available."}}getCapabilities(){return{supportsOffline:!0,requiresAuth:!1,maxInstances:null,features:{basic:!0,scientific:!0,graphing:!0,fourFunction:!0}}}},S8=class extends mw{constructor(...e){super(...e),T(this,"providerId","desmos-calculator"),T(this,"providerName","Desmos Calculator"),T(this,"version","1.12"),T(this,"requiresAuth",!0)}getDefinition(){return{backend:"desmos",moduleImportOperation:"desmos-provider-module-import",loadProvider:async()=>(await br(()=>import("./chunks/dist-59132a53.js"),[],import.meta.url)).DesmosCalculatorProvider,initializationErrorMessage:"Failed to initialize Desmos calculator provider. Check the application key, preloaded API, runtime endpoint, or network access."}}getCapabilities(){return{supportsOffline:!1,requiresAuth:!0,maxInstances:null,features:{basic:!0,scientific:!0,graphing:!0,fourFunction:!0}}}},I8=class extends mw{constructor(...e){super(...e),T(this,"providerId","geogebra-calculator"),T(this,"providerName","GeoGebra Calculator"),T(this,"version","6"),T(this,"requiresAuth",!1)}getDefinition(){return{backend:"geogebra",moduleImportOperation:"geogebra-provider-module-import",loadProvider:async()=>(await br(()=>import("./chunks/dist-60d7afef.js"),[],import.meta.url)).GeoGebraCalculatorProvider,initializationErrorMessage:"Failed to initialize GeoGebra calculator provider. Confirm that the deployment may load GeoGebra and that its script URL is reachable."}}getCapabilities(){return{supportsOffline:!1,requiresAuth:!1,maxInstances:null,features:{basic:!0,scientific:!0,graphing:!0,fourFunction:!1}}}},k8="calculator-desmos";function Lp(e){const t=e?.provider?.id;if(t===void 0||t==="")return k8;if(t==="calculator-desmos"||t==="calculator-geogebra"||t==="calculator-cortex")return t;throw new Error(`Unsupported calculator provider "${String(t)}". Expected "calculator-desmos", "calculator-geogebra", or "calculator-cortex".`)}function T8(e){switch(Lp(e)){case"calculator-cortex":return new w8;case"calculator-geogebra":return new I8;default:return new S8}}function E8(e){const t=e?.theme;return{settings:e?.settings&&typeof e.settings=="object"?{...e.settings}:{},restrictedMode:e?.restrictedMode===!0,locale:typeof e?.locale=="string"?e.locale:void 0,theme:t==="light"||t==="dark"||t==="auto"?t:void 0}}function yI(e){return e==="basic"||e==="scientific"||e==="graphing"?e:null}function C8(e){const t=e.getToolRenderParams?.("calculator")??{},r=yI(t.calculatorType),n=t.availableTypes;return{calculatorType:r,availableTypes:Array.isArray(n)?n.map(i=>yI(i)).filter(i=>i!==null):r?[r]:null,displayName:e.i18n.t(x8[r??"untyped"])}}var x8={basic:"tools.calculator.nameBasic",scientific:"tools.calculator.nameScientific",graphing:"tools.calculator.nameGraphing",untyped:"tools.calculator.name"};function bI(e,t,r,n,i){const o=e;o.providerId=n,o.calculatorConfig=i,e.setAttribute("provider-id",n),t?(o.calculatorType=t,e.setAttribute("calculator-type",t)):(delete o.calculatorType,e.removeAttribute("calculator-type")),r&&r.length>0?o.availableTypes=r:delete o.availableTypes}var R8={toolId:"calculator",name:"Calculator",description:"Multi-type calculator (basic, scientific, graphing)",nameKey:"tools.calculator.name",descriptionKey:"tools.calculator.description",icon:"calculator",provider:{getProviderId:Lp,createProvider:T8,getInitConfig:e=>e?.provider?.init??{},getAuthFetcher:e=>{const t=e?.provider?.runtime?.authFetcher;return typeof t=="function"?t:void 0},lazy:!0},supportedLevels:["item"],pnpSupportIds:["calculator","graphingCalculator"],isVisibleInContext(e){return Jp(e)},renderToolbar(e,t){const{calculatorType:r,availableTypes:n,displayName:i}=C8(t),o=t.toolkitCoordinator?.getToolConfig(this.toolId)||void 0,s=Lp(o),a=E8(o),l=sb(this.toolId,t.scope.level,t.scope.scopeId),d=t.componentOverrides,c=Im(t,l,()=>Qp(this.toolId,e,t,d));c.setAttribute("tool-id",l),c.toolkitCoordinator=t.toolkitCoordinator,bI(c,r,n,s,a);const u={toolId:this.toolId,label:i,icon:typeof this.icon=="function"?this.icon(e):this.icon,faIconName:"calculator",disabled:!1,ariaLabel:i,tooltip:i,onClick:()=>t.toggleTool(this.toolId),active:t.isToolVisible(l)};let f=u.active;return c.visible!==u.active&&(c.visible=u.active),{toolId:this.toolId,elements:[{element:c,mount:"after-buttons",shell:{title:i,draggable:!0,resizable:!0,closeable:!0,initialWidth:r==="graphing"?720:380,initialHeight:r==="graphing"?660:r==="basic"?500:560,minWidth:380,minHeight:480,initialAlign:"bottom-left",initialMargin:16,ndsHeaderControls:!0,pageTabOrder:!0,content:{overflowY:"auto",preserveMinHeight:!0}}}],button:u,sync:()=>{const p=t.isToolVisible(l);u.active=p,u.label=i,u.ariaLabel=i,u.tooltip=i,f!==p&&(c.visible=p,f=p),c.toolkitCoordinator!==t.toolkitCoordinator&&(c.toolkitCoordinator=t.toolkitCoordinator),bI(c,r,n,s,a)},subscribeActive:p=>t.subscribeVisibility?t.subscribeVisibility(()=>{p(t.isToolVisible(l))}):()=>{}}}};function wI(e,t,r,n){const i=r.getToolRenderParams?.(t)??{};typeof i.endpoint=="string"&&(e.endpoint=i.endpoint),typeof i.lookup=="function"&&(e.lookup=i.lookup),typeof i.headers=="function"&&(e.headers=i.headers),typeof i.credentials=="string"&&(e.credentials=i.credentials),typeof i.term=="string"&&i.term&&(e.term=i.term),(typeof i.toolRequestId=="string"||typeof i.toolRequestId=="number")&&(e.termRequestId=i.toolRequestId);const o=typeof i.language=="string"?i.language:n??r.language;typeof o=="string"&&o&&(e.language=o)}function YR(e){const{registration:t,context:r,toolbarContext:n}=e,i=uw(t.toolId,n),o={toolId:t.toolId,label:t.name,icon:typeof t.icon=="function"?t.icon(r):t.icon,disabled:!1,ariaLabel:n.i18n.t(e.buttonA11yKey),tooltip:n.i18n.t(e.tooltipKey),onClick:()=>n.toggleTool(t.toolId),active:i.isActive()},s=n.componentOverrides??{},a=Im(n,i.fullToolId,()=>Qp(t.toolId,r,n,s));return a.setAttribute("tool-id",i.fullToolId),wI(a,t.toolId,n,e.lookupLanguage),{toolId:t.toolId,button:o,elements:[{element:a,mount:"after-buttons",shell:{title:n.i18n.t(e.shellTitleKey),draggable:!0,resizable:!0,closeable:!0,initialWidth:e.initialWidth,initialHeight:e.initialHeight,minWidth:e.minWidth,minHeight:e.minHeight}}],sync:()=>{fw({button:o,overlay:a,isActive:i.isActive}),wI(a,t.toolId,n,e.lookupLanguage)},subscribeActive:i.subscribeActive}}function JR(e={}){const t=e.toolId??"dictionary",r=e.messageKeyPrefix??`tools.${t}`;return{toolId:t,name:e.name??"Dictionary",description:e.description??"Look up word definitions",nameKey:`${r}.name`,descriptionKey:`${r}.description`,icon:"book-open",supportedLevels:["section","item","passage","rubric"],pnpSupportIds:e.pnpSupportIds??["dictionary","englishDictionary","glossary","definitions"],isVisibleInContext(n){return Ku(n)},renderToolbar(n,i){return YR({registration:this,context:n,toolbarContext:i,buttonA11yKey:`${r}.buttonA11y`,tooltipKey:`${r}.tooltip`,shellTitleKey:`${r}.name`,lookupLanguage:e.lookupLanguage,initialWidth:420,initialHeight:380,minWidth:300,minHeight:240})}}}var _8=JR();function QR(e={}){const t=e.toolId??"pictureDictionary",r=e.messageKeyPrefix??`tools.${t}`;return{toolId:t,name:e.name??"Picture Dictionary",description:e.description??"Look up pictures for words",nameKey:`${r}.name`,descriptionKey:`${r}.description`,icon:"photo",supportedLevels:["section","item","passage","rubric"],pnpSupportIds:e.pnpSupportIds??["pictureDictionary","illustratedGlossary","symbolDictionary","pictureSupport"],isVisibleInContext(n){return Ku(n)},renderToolbar(n,i){return YR({registration:this,context:n,toolbarContext:i,buttonA11yKey:`${r}.buttonA11y`,tooltipKey:`${r}.tooltip`,shellTitleKey:`${r}.name`,lookupLanguage:e.lookupLanguage,initialWidth:520,initialHeight:460,minWidth:320,minHeight:280})}}}var P8=QR(),A8=JR({toolId:"dictionarySpanish",name:"Spanish Dictionary",description:"Look up word definitions in Spanish",pnpSupportIds:["spanishDictionary"],lookupLanguage:"es"}),M8=QR({toolId:"pictureDictionarySpanish",name:"Spanish Picture Dictionary",description:"Look up pictures for words in Spanish",pnpSupportIds:["spanishPictureDictionary"],lookupLanguage:"es"}),$8={toolId:"answerEliminator",name:"Answer Eliminator",description:"Strike through answer choices",nameKey:"tools.answerEliminator.name",descriptionKey:"tools.answerEliminator.description",icon:"strikethrough",supportedLevels:["item"],pnpSupportIds:["answerMasking","answerEliminator","strikethrough"],isVisibleInContext(e){return S0(e)},isApplicableToContent(e){return S0(e)},renderToolbar(e,t){const r=uw(this.toolId,t),n=t.componentOverrides??{},i=Im(t,r.fullToolId,()=>Qp(this.toolId,e,t,n));i.setAttribute("tool-id",r.fullToolId),i.setAttribute("strategy","strikethrough"),i.setAttribute("button-alignment","inline");const o={toolId:this.toolId,label:this.name,icon:'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="20" height="20" fill="currentColor" aria-hidden="true"><path d="M19,3H16.3H7.7H5A2,2 0 0,0 3,5V7.7V16.4V19A2,2 0 0,0 5,21H7.7H16.4H19A2,2 0 0,0 21,19V16.3V7.7V5A2,2 0 0,0 19,3M15.6,17L12,13.4L8.4,17L7,15.6L10.6,12L7,8.4L8.4,7L12,10.6L15.6,7L17,8.4L13.4,12L17,15.6L15.6,17Z"/></svg>',disabled:!1,ariaLabel:t.i18n.t("tools.answerEliminator.buttonA11y"),tooltip:t.i18n.t("tools.answerEliminator.tooltip"),onClick:()=>t.toggleTool(this.toolId),active:r.isActive()};return{toolId:this.toolId,button:o,elements:[{element:i,mount:"after-buttons"}],sync:()=>{fw({button:o,overlay:i,isActive:r.isActive}),t.toolCoordinator&&(i.coordinator=t.toolCoordinator),i.scopeElement=t.getScopeElement?.()||null,t.elementToolStateStore&&(i.elementToolStateStore=t.elementToolStateStore);const s=t.getGlobalElementId?.();s&&(i.globalElementId=s)},subscribeActive:r.subscribeActive}}},L8={toolId:"ruler",name:"Ruler",description:"On-screen ruler for measurements",nameKey:"tools.ruler.name",descriptionKey:"tools.ruler.description",icon:"ruler",supportedLevels:["section","item","element"],pnpSupportIds:["ruler"],isVisibleInContext(e){return Jp(e)},renderToolbar(e,t){return lc(this,e,t,{surface:"frameless",handsOverCoordinator:!0})}},O8={toolId:"protractor",name:"Protractor",description:"On-screen protractor for angle measurements",nameKey:"tools.protractor.name",descriptionKey:"tools.protractor.description",icon:"protractor",supportedLevels:["section","item","element"],pnpSupportIds:["protractor"],isVisibleInContext(e){return Jp(e)},renderToolbar(e,t){return lc(this,e,t,{surface:"frameless",handsOverCoordinator:!0})}},N8={toolId:"graph",name:"Graph",description:"Coordinate plane",nameKey:"tools.graph.name",descriptionKey:"tools.graph.description",icon:"chart-bar",supportedLevels:["section","item"],pnpSupportIds:["graph"],isVisibleInContext(e){return Jp(e)},renderToolbar(e,t){return lc(this,e,t,{shell:{resizable:!0,initialWidth:920,initialHeight:680,minWidth:640,minHeight:500}})}},D8={toolId:"periodicTable",name:"Periodic Table",description:"Chemistry periodic table reference",nameKey:"tools.periodicTable.name",descriptionKey:"tools.periodicTable.description",icon:"beaker",supportedLevels:["section","item"],pnpSupportIds:["periodicTable"],isVisibleInContext(e){return D$(e)},renderToolbar(e,t){return lc(this,e,t,{shell:{resizable:!0,initialWidth:1160,initialHeight:760,minWidth:920,minHeight:620}})}},yo=e=>e().then(()=>{});function gw(e,t){return typeof globalThis<"u"&&"customElements"in globalThis&&globalThis.customElements?.get(e)?Promise.resolve():yo(t)}var j8=()=>gw("pie-tool-calculator",()=>br(()=>import("./chunks/calculator-element-271c142f.js"),[],import.meta.url)),B8=()=>gw("pie-tool-calculator-geogebra",()=>br(()=>import("./chunks/pie-tool-calculator-geogebra-561236cb.js"),[],import.meta.url)),F8=()=>gw("pie-tool-calculator-cortex",()=>br(()=>import("./chunks/pie-tool-calculator-cortex-0626bc24.js"),[],import.meta.url)),gy={"calculator-desmos":{tagName:"pie-tool-calculator",loadModule:j8},"calculator-geogebra":{tagName:"pie-tool-calculator-geogebra",loadModule:B8},"calculator-cortex":{tagName:"pie-tool-calculator-cortex",loadModule:F8}};function SI(e){return gy[Lp(e)]}var H8=()=>yo(()=>br(()=>import("./chunks/tool-tts-inline-98c2ce7a.js"),[],import.meta.url)),z8=()=>yo(()=>br(()=>import("./chunks/tool-ruler-1d9a03a6.js"),[],import.meta.url)),W8=()=>yo(()=>br(()=>import("./chunks/tool-protractor-23f77028.js"),[],import.meta.url)),U8=()=>yo(()=>br(()=>import("./chunks/tool-answer-eliminator-35483abd.js"),[],import.meta.url)),q8=()=>yo(()=>br(()=>import("./chunks/tool-annotation-toolbar-997438b4.js"),[],import.meta.url)),V8=()=>yo(()=>br(()=>import("./chunks/tool-line-reader-f8ef3c6a.js"),[],import.meta.url)),G8=()=>yo(()=>br(()=>import("./chunks/tool-color-scheme-b7de5cdf.js"),[],import.meta.url)),K8=()=>yo(()=>br(()=>import("./chunks/tool-graph-cb0338e8.js"),[],import.meta.url)),X8=()=>yo(()=>br(()=>import("./chunks/tool-periodic-table-43b133b8.js"),[],import.meta.url)),II=()=>yo(()=>br(()=>import("./chunks/tool-dictionary-cecff3b4.js"),[],import.meta.url)),kI=()=>yo(()=>br(()=>import("./chunks/tool-picture-dictionary-33721e91.js"),[],import.meta.url)),Z8=[{registration:R8,tagName:gy["calculator-desmos"].tagName,loadModule:gy["calculator-desmos"].loadModule,loaderTargets:["item","section"],placementOrder:{element:10},preferredPlacementOrder:{item:10},toolbarOrder:20,universalSupportIds:["calculator","graphingCalculator"]},{registration:l8,tagName:"pie-tool-tts-inline",loadModule:H8,loaderTargets:["item"],placementOrder:{item:10,passage:10,rubric:10,element:30},preferredPlacementOrder:{item:20,passage:10},toolbarOrder:30,universalSupportIds:["textToSpeech","readAloud"]},{registration:L8,tagName:"pie-tool-ruler",loadModule:z8,loaderTargets:["section"],placementOrder:{element:40},preferredPlacementOrder:{section:50},toolbarOrder:80,universalSupportIds:["ruler"]},{registration:O8,tagName:"pie-tool-protractor",loadModule:W8,loaderTargets:["section"],placementOrder:{element:50},preferredPlacementOrder:{section:60},toolbarOrder:90,universalSupportIds:["protractor"]},{registration:$8,tagName:"pie-tool-answer-eliminator",loadModule:U8,loaderTargets:["item"],placementOrder:{element:20},preferredPlacementOrder:{item:30},toolbarOrder:70,universalSupportIds:["answerMasking","answerEliminator","strikethrough"]},{registration:c8,tagName:"pie-tool-line-reader",loadModule:V8,loaderTargets:["section"],placementOrder:{passage:40,rubric:40},preferredPlacementOrder:{section:40},toolbarOrder:40,universalSupportIds:["readingMask","readingGuide","readingRuler"]},{registration:d8,tagName:"pie-tool-theme",loadModule:G8,loaderTargets:["item"],placementOrder:{assessment:10,section:10},preferredPlacementOrder:{section:10},toolbarOrder:10,universalSupportIds:["highContrastDisplay","colorContrast","invertColors","theme"]},{registration:u8,tagName:"pie-tool-annotation-toolbar",loadModule:q8,loaderTargets:["item"],placementOrder:{item:30,passage:30,rubric:30,element:70},preferredPlacementOrder:{item:40,passage:20},toolbarOrder:50,universalSupportIds:["highlighting","annotations"]},{registration:N8,tagName:"pie-tool-graph",loadModule:K8,loaderTargets:["section"],placementOrder:{item:40,element:80},preferredPlacementOrder:{section:20},toolbarOrder:100,universalSupportIds:["graph"]},{registration:D8,tagName:"pie-tool-periodic-table",loadModule:X8,loaderTargets:["section"],placementOrder:{item:50,element:90},preferredPlacementOrder:{section:30},toolbarOrder:110,universalSupportIds:["periodicTable"]},{registration:_8,tagName:"pie-tool-dictionary",loadModule:II,loaderTargets:["section"],placementOrder:{item:60,element:100},preferredPlacementOrder:{section:70},toolbarOrder:120,universalSupportIds:[]},{registration:P8,tagName:"pie-tool-picture-dictionary",loadModule:kI,loaderTargets:["section"],placementOrder:{item:70,element:110},preferredPlacementOrder:{section:80},toolbarOrder:130,universalSupportIds:[]},{registration:A8,tagName:"pie-tool-dictionary",loadModule:II,loaderTargets:["section"],placementOrder:{item:80,element:120},preferredPlacementOrder:{section:90},toolbarOrder:140,universalSupportIds:[]},{registration:M8,tagName:"pie-tool-picture-dictionary",loadModule:kI,loaderTargets:["section"],placementOrder:{item:90,element:130},preferredPlacementOrder:{section:100},toolbarOrder:150,universalSupportIds:[]},{registration:b8,universalSupportIds:[]}],Y8=["assessment","section","item","passage","rubric","element"],J8=["section","item","passage"];function TI(e,t,r){return e.flatMap(n=>{const i=r(n)?.[t];return i===void 0?[]:[{definition:n,order:i}]}).sort((n,i)=>n.order-i.order).map(({definition:n})=>n.registration.toolId)}var Q8=class{constructor(e){T(this,"definitions",void 0),T(this,"registrations",void 0),T(this,"toolTagMap",void 0),T(this,"itemModuleLoaders",void 0),T(this,"sectionModuleLoaders",void 0),T(this,"defaultModuleLoaders",void 0),T(this,"placement",void 0),T(this,"preferredPlacement",void 0),T(this,"toolbarOrder",void 0),T(this,"universalSupportIds",void 0),this.definitions=e,this.registrations=Object.freeze(e.map(({registration:t})=>t)),this.toolTagMap=Object.freeze(Object.fromEntries(e.flatMap(t=>t.tagName?[[t.registration.toolId,t.tagName]]:[]))),this.itemModuleLoaders=this.projectModuleLoaders("item"),this.sectionModuleLoaders=this.projectModuleLoaders("section"),this.defaultModuleLoaders=Object.freeze({...this.itemModuleLoaders,...this.sectionModuleLoaders}),this.placement=Object.freeze(Object.fromEntries(Y8.map(t=>[t,Object.freeze(TI(e,t,r=>r.placementOrder))]))),this.preferredPlacement=Object.freeze(Object.fromEntries(J8.map(t=>[t,Object.freeze(TI(e,t,r=>r.preferredPlacementOrder))]))),this.toolbarOrder=Object.freeze(e.filter(t=>t.toolbarOrder!==void 0).slice().sort((t,r)=>t.toolbarOrder-r.toolbarOrder).map(({registration:t})=>t.toolId)),this.universalSupportIds=Object.freeze(e.flatMap(({universalSupportIds:t})=>[...t]).sort())}projectModuleLoaders(e){return Object.freeze(Object.fromEntries(this.definitions.flatMap(t=>t.loadModule&&t.loaderTargets?.includes(e)?[[t.registration.toolId,t.loadModule]]:[])))}selectRegistrations(e){if(!e?.length)return this.registrations;const t=new Set(e);return this.registrations.filter(({toolId:r})=>t.has(r))}registerTools(e,t={}){const r=t.applyOverrides??(n=>n);for(const n of this.selectRegistrations(t.toolIds))e.register(r(n))}createRegistry(e={}){const t=new R$;if(this.registerTools(t,{toolIds:e.toolIds,applyOverrides:n=>e.overrides?.[n.toolId]??n}),e.toolModuleLoaders&&Object.keys(e.toolModuleLoaders).length>0){const n={...e.toolModuleLoaders},i=SI(e.calculatorProviderConfig);e.calculatorProviderConfig&&n.calculator===this.defaultModuleLoaders.calculator&&(n.calculator=i.loadModule),t.setToolModuleLoaders(n)}const r=e.calculatorProviderConfig?{calculator:SI(e.calculatorProviderConfig).tagName}:{};return t.setComponentOverrides({toolTagMap:{...this.toolTagMap,...r,...e.toolTagMap??{}},toolComponentFactory:e.toolComponentFactory,toolComponentFactories:e.toolComponentFactories}),t}createUniversalPersonalNeedsProfile(){return{supports:[...this.universalSupportIds],prohibitedSupports:[],activateAtInit:[]}}},Vn=new Q8(Z8),PV=[...Vn.registrations],AV={...Vn.toolTagMap},MV={...Vn.itemModuleLoaders},$V={...Vn.sectionModuleLoaders},e_={...Vn.defaultModuleLoaders},LV={assessment:[...Vn.placement.assessment],section:[...Vn.placement.section],item:[...Vn.placement.item],passage:[...Vn.placement.passage],rubric:[...Vn.placement.rubric],element:[...Vn.placement.element]},OV={section:[...Vn.preferredPlacement.section],item:[...Vn.preferredPlacement.item],passage:[...Vn.preferredPlacement.passage]},NV=[...Vn.toolbarOrder],DV=Vn.universalSupportIds;function t_(e={}){return Vn.createRegistry(e)}function eW(e,t){if(e===t)return 0;const r=e.compareDocumentPosition(t);return r&Node.DOCUMENT_POSITION_PRECEDING?1:r&Node.DOCUMENT_POSITION_FOLLOWING?-1:0}var tW=class{constructor(){T(this,"shellsByElement",new Map)}register(e){const t=this.shellsByElement.get(e.element),r={...e,sortKey:Date.now()};return t&&t.kind===r.kind&&t.itemId===r.itemId&&t.canonicalItemId===r.canonicalItemId?!1:(this.shellsByElement.set(e.element,r),!0)}unregister(e){return this.shellsByElement.delete(e)}getOrderedShells(e){const t=Array.from(this.shellsByElement.values()).filter(r=>!e||r.kind===e);return t.sort((r,n)=>eW(r.element,n.element)),t}getCanonicalIdMap(){const e={};for(const t of this.getOrderedShells("item"))t.itemId&&(e[t.itemId]=t.canonicalItemId||t.itemId);return e}clear(){this.shellsByElement.clear()}};function rW(e="runtime"){return`${e}-${Math.random().toString(16).slice(2)}-${Date.now()}`}var nW=Ys("section-runtime-engine",()=>Yl()),iW=class{constructor(){T(this,"registry",new tW),T(this,"runtimeId",rW("section-engine")),T(this,"adapter",null),T(this,"controller",null),T(this,"coordinator",null),T(this,"sectionId",""),T(this,"attemptId",void 0),T(this,"unsubscribeController",null),T(this,"activeInitToken",0),T(this,"loadedRenderableKeys",new Set)}attachHost(e){if(this.adapter){this.adapter.setHost(e.host),e.instrumentationHook!==void 0&&this.adapter.setInstrumentationHook(e.instrumentationHook);return}this.adapter=new pz({host:e.host,runtimeId:this.runtimeId,sourceCe:e.sourceCe,frameworkErrorBus:e.frameworkErrorBus,coordinator:e.coordinator,instrumentationHook:e.instrumentationHook,now:e.now})}dispatchInput(e){return this.adapter?.dispatchInput(e)??[]}subscribe(e){return this.adapter?.subscribe(e)??oW}getState(){return this.adapter?.getState()??aw()}getEffectiveRuntime(e,t){return jR(e,t).effectiveRuntime}setInstrumentationHook(e){this.adapter?.setInstrumentationHook(e)}getRuntimeId(){return this.runtimeId}async initialize(e){this.activeInitToken+=1;const t=this.activeInitToken;this.coordinator=e.coordinator,this.sectionId=e.sectionId,this.attemptId=e.attemptId;const r=await e.coordinator.getOrCreateSectionController({sectionId:e.sectionId,attemptId:e.attemptId,input:{section:e.section,sectionId:e.sectionId,assessmentId:e.assessmentId,view:e.view},updateExisting:!0,createDefaultController:e.createDefaultController});t===this.activeInitToken&&(this.unsubscribeController?.(),this.controller=r,this.replayRegisteredShellsIntoController(r),e.onCompositionChanged?.(r.getCompositionModel?.()),this.unsubscribeController=r.subscribe?.(n=>{try{e.onControllerEvent?.(n)}catch(i){nW.warn("onControllerEvent handler threw",i)}e.onCompositionChanged?.(r.getCompositionModel?.())})||null)}replayRegisteredShellsIntoController(e){if(!e.handleContentRegistered)return;const t=this.registry.getOrderedShells();if(t.length===0)return;for(const n of t){const i=n.canonicalItemId||n.itemId;e.handleContentRegistered({itemId:n.itemId,canonicalItemId:i,contentKind:n.contentKind||n.kind})}const r=Date.now();for(const n of t){const i=n.canonicalItemId||n.itemId,o=this.getLoadedKey(i,n.contentKind);this.loadedRenderableKeys.has(o)&&e.handleContentLoaded?.({itemId:n.itemId,canonicalItemId:i,contentKind:n.contentKind||n.kind,timestamp:r})}}getLoadedKey(e,t){return`${t??""}:${e}`}register(e){return this.registry.register(e)}unregister(e){return this.registry.unregister(e)}getCompositionModel(){return this.controller?.getCompositionModel?.()??null}getCanonicalItemId(e){return this.registry.getCanonicalIdMap()[e]||this.controller?.getCanonicalItemId?.(e)||e}handleContentRegistered(e){this.controller?.handleContentRegistered?.({itemId:e.itemId,canonicalItemId:e.canonicalItemId||e.itemId,contentKind:e.contentKind||e.kind})}handleContentUnregistered(e){const t=e.canonicalItemId||e.itemId;this.loadedRenderableKeys.delete(this.getLoadedKey(t,e.contentKind)),this.controller?.handleContentUnregistered?.({itemId:e.itemId,canonicalItemId:t,contentKind:e.contentKind||e.kind})}handleContentLoaded(e){const t=e.canonicalItemId||e.itemId;this.loadedRenderableKeys.add(this.getLoadedKey(t,e.contentKind)),this.controller?.handleContentLoaded?.(e)}handleItemPlayerError(e){this.controller?.handleItemPlayerError?.(e)}reportSectionError(e){this.controller?.reportSectionError?.(e)}updateItemSession(e,t){const r=this.getCanonicalItemId(e);return this.controller?.updateItemSession?.(r,t)??null}navigateToItem(e){return this.controller?.navigateToItem?.(e)??null}handleFormativeAction(e){if(!e?.itemId)return;const t=this.getCanonicalItemId(e.itemId);if(e.action==="retry"){this.controller?.retryFormativeItem?.({itemId:t});return}this.controller?.recordFormativeTry?.({itemId:t,outcomes:e.outcomes})}handleMediaTimeSource(e){if(e?.action==="detach"){this.controller?.detachMediaTimeSource?.({origin:e.origin??"host"});return}e?.source&&this.controller?.attachMediaTimeSource?.(e.source,{origin:e.origin??"host",renderableId:e.renderableId})}requestMediaPauseForCompetingAudio(){return this.controller?.pauseMediaForCompetingAudio?.()??!0}async persist(){await this.controller?.persist?.()}async hydrate(){await this.controller?.hydrate?.()}getRegistry(){return this.registry}async dispose(){if(this.activeInitToken+=1,this.unsubscribeController?.(),this.unsubscribeController=null,this.coordinator&&this.sectionId&&await this.coordinator.disposeSectionController({sectionId:this.sectionId,attemptId:this.attemptId}),this.registry.clear(),this.loadedRenderableKeys.clear(),this.controller=null,this.coordinator=null,this.adapter){const e=this.adapter;this.adapter=null,await e.dispose()}}},oW=()=>{},sW=Symbol("@pie-players/section-runtime-engine"),aW=Zl(Symbol.for("pie.sectionRuntimeEngineHostContext")),vy={readiness:{mode:"progressive"},preload:{enabled:!0},telemetry:{enabled:!0}};function lW(e){return e?.preload?.enabled!==!1}function ff(e){return e?.telemetry?.enabled!==!1}function cW(e){const t=e?.readiness?.mode;return{readiness:{mode:t==="strict"||t==="progressive"?t:vy.readiness.mode},preload:{enabled:lW(e)},telemetry:{enabled:ff(e)}}}var Mu=new WeakMap;function dW(e){if(!e)return"";try{return JSON.stringify(e)}catch{return String(e?.id||"")}}function EI(e){if(e==null)return"";try{return JSON.stringify(e)}catch{return String(e)}}function uW(e){return(t,r)=>(CI(t,r,e),{update(n){CI(t,n,e)},destroy(){pW(t,e.stateKey)}})}function CI(e,t,r){const n=e,i=fW(e,r.stateKey),o=Object.keys(t.attributes||{}),s=Object.keys(t.props||{}),a=i.attributeKeys||[],l=i.propKeys||[];for(const f of a)o.includes(f)||e.removeAttribute(f);for(const f of l)s.includes(f)||delete n[f];const d=EI(t.config);i.configSignature!==d&&(n.config=t.config);const c=EI(t.env);i.envSignature!==c&&(n.env=t.env);const u=dW(t.session);t.session!==void 0&&i.sessionSignature!==u&&(n.session=t.session);for(const[f,p]of Object.entries(t.attributes||{}))e.setAttribute(f,String(p));for(const[f,p]of Object.entries(t.props||{}))n[f]=p;hW(e,r.stateKey,{config:t.config,configSignature:d,env:t.env,envSignature:c,session:r.includeSessionRefInState?t.session:void 0,sessionSignature:u,attributeKeys:o,propKeys:s})}function fW(e,t){return Mu.get(e)?.get(t)||{}}function hW(e,t,r){const n=Mu.get(e)||new Map;n.set(t,r),Mu.set(e,n)}function pW(e,t){const r=Mu.get(e);r&&(r.delete(t),r.size===0&&Mu.delete(e))}function mW(e){const{host:t,getOnStageChange:r,getOnLoadingComplete:n,onError:i}=e,o=a=>{const l=a.detail,d=r();if(d)try{d(l)}catch(c){i?.("onStageChange",c)}},s=a=>{const l=a.detail,d=n();if(d)try{d(l)}catch(c){i?.("onLoadingComplete",c)}};return t.addEventListener("pie-stage-change",o),t.addEventListener("pie-loading-complete",s),()=>{t.removeEventListener("pie-stage-change",o),t.removeEventListener("pie-loading-complete",s)}}function yy(e){return{kind:e.kind,severity:e.severity??"error",source:e.source,message:e.message,details:[...e.details||[]],recoverable:e.recoverable===!0,cause:e.cause}}function r_(e){let t=e.error instanceof Error&&e.error.message.trim().length>0?e.error.message:String(e.error||"Unknown framework error");return yy({kind:e.kind,source:e.source,message:t,recoverable:e.recoverable,cause:e.error})}var gW={"coordinator-ready":"coordinator-init","state-load":"tool-state-load","state-save":"tool-state-save","provider-register":"provider-register","provider-init":"provider-init","tts-init":"tts-init","section-controller-init":"section-controller-init","section-controller-dispose":"section-controller-dispose"};function vW(e){let t=gW[e.context.phase];return r_({kind:t,source:e.context.providerId?`pie-toolkit-coordinator/${e.context.providerId}`:`pie-toolkit-coordinator:${e.context.phase}`,error:e.error,recoverable:e.recoverable})}function yW(e){let t=`[pie-framework:${e.kind}:${e.source}]`;return e.details.length===0?`${t} ${e.message}`:`${t} ${e.message}
1316
+ - ${e.details.join(`
1317
+ - `)}`}var bW="error";function n_(e){return e==="off"||e==="warn"||e==="error"?e:bW}function wW(e){return e?new Map(e.getAllTools().slice().sort((t,r)=>t.toolId.localeCompare(r.toolId)).map(t=>[t.toolId,t])):new Map}function SW(e,t,r,n){if(!t||!r?.provider?.sanitizeConfig)return t;try{let i=r.provider.sanitizeConfig(t);return!i||typeof i!="object"||Array.isArray(i)?(n.push({code:"tools.providerSanitizeFailed",severity:"error",path:`providers.${e}`,message:`Provider sanitizer for "${e}" must return an object.`,providerId:e,toolId:e}),t):i}catch(i){return n.push({code:"tools.providerSanitizeFailed",severity:"error",path:`providers.${e}`,message:`Provider sanitizer failed for "${e}": ${i instanceof Error?i.message:String(i)}`,providerId:e,toolId:e}),t}}function IW(e,t,r,n){if(!(!t||!r?.provider?.validateConfig))try{let i=r.provider.validateConfig(t);if(!Array.isArray(i)){n.push({code:"tools.invalidProviderValidation",severity:"error",path:`providers.${e}`,message:`Provider validator for "${e}" must return an array.`,providerId:e,toolId:e});return}for(let o of i)n.push({...o,path:o.path||`providers.${e}`,providerId:o.providerId||e,toolId:o.toolId||e})}catch(i){n.push({code:"tools.providerValidateFailed",severity:"error",path:`providers.${e}`,message:`Provider validator failed for "${e}": ${i instanceof Error?i.message:String(i)}`,providerId:e,toolId:e})}}function kW(e,t,r){if(t.size!==0)for(let n of["section","item","passage"])for(let i of e.placement[n]){let o=t.get(i);if(!o){r.push({code:"tools.unknownToolId",severity:"error",path:`placement.${n}`,message:`Unknown tool id "${i}" in placement.${n}.`,toolId:i});continue}if(o.activation==="region"){r.push({code:"tools.unplaceableActivation",severity:"error",path:`placement.${n}`,message:`Tool "${i}" renders into a host surface (activation "region") and cannot be placed on the ${n} toolbar. Remove it from placement.${n}; its availability comes from policy plus its content dependency.`,toolId:i});continue}let s=o.supportedLevels.includes(n),a=n==="item"&&o.supportedLevels.includes("section");!s&&!a&&r.push({code:"tools.unsupportedLevel",severity:"error",path:`placement.${n}`,message:`Tool "${i}" does not support level "${n}".`,toolId:i})}}function TW(e,t,r){if(t.size!==0){for(let n of e.policy.allowed||[])t.has(n)||r.push({code:"tools.unknownToolId",severity:"error",path:"policy.allowed",message:`Unknown tool id "${n}" in policy.allowed.`,toolId:n});for(let n of e.policy.blocked||[])t.has(n)||r.push({code:"tools.unknownToolId",severity:"error",path:"policy.blocked",message:`Unknown tool id "${n}" in policy.blocked.`,toolId:n})}}function EW(e,t,r,n){r&&n.push({code:"tools.removedProviderKey",severity:"error",path:"providers.tts",message:'Provider key "tts" is no longer supported. Use "providers.textToSpeech".',providerId:"tts",toolId:"textToSpeech"});for(let i of Object.keys(e.providers).sort())t.size===0||t.has(i)||n.push({code:"tools.unknownProviderKey",severity:"error",path:`providers.${i}`,message:`Unknown provider key "${i}".`,providerId:i,toolId:i})}function xI(e,t){if(e.length!==0)for(let r of e){let n=`[tool-config-validation:${t}]`;console.warn(`${n} ${r.path} - ${r.message}`)}}function RI(e,t){let r=e.map(n=>`- ${n.path}: ${n.message}`).join(`
1318
+ `);throw Error(`[tool-config-validation:${t}] Invalid tools config:
1319
+ ${r}`)}function CW(e,t={}){let r=i_(e,t.toolRegistry);return o_(r.diagnostics,t),r}function i_(e,t){let r=wW(t),n=Lb(e),i=[],o=Object.values(n.placement).some(d=>d.length>0)||Object.keys(n.providers).length>0||(n.policy.allowed?.length??0)>0||(n.policy.blocked?.length??0)>0;r.size===0&&o&&i.push({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 s=Object.hasOwn(n.providers,"tts"),a={...n.providers||{}};for(let d of Object.keys(a).sort()){if(d==="tts"){delete a.tts;continue}let c=r.get(d);a[d]=SW(d,a[d],c,i),IW(d,a[d],c,i)}let l={...n,providers:a};return kW(l,r,i),TW(l,r,i),EW(l,r,s,i),{config:l,diagnostics:i}}function o_(e,t={}){let r=n_(t.strictness),n=t.source??"tools",i=e.filter(s=>s.code==="tools.removedProviderKey");i.length>0&&RI(i,n),r==="warn"&&xI(e,n);let o=e.filter(s=>s.severity==="error");r==="error"&&o.length>0&&RI(o,n),r==="error"&&o.length===0&&xI(e,n)}var Ng=e=>Array.isArray(e)&&e.length>0;function s_(e){return e.kind==="passage"?{ownerKind:"passage",assessmentId:e.assessmentId,sectionId:e.sectionId,passageId:e.canonicalItemId||e.itemId}:{ownerKind:"itemModel",assessmentId:e.assessmentId,sectionId:e.sectionId,itemId:e.itemId,canonicalItemId:e.canonicalItemId||e.itemId}}function xW(e,t){if(!e)return[];let r=s_(t),n=[];if(Ng(e.accessibilityCatalogs)&&n.push({context:r,catalogs:e.accessibilityCatalogs}),Ng(e.config?.extractedCatalogs)&&n.push({context:r,catalogs:e.config.extractedCatalogs}),t.kind==="passage"||r.ownerKind!=="itemModel")return n;for(let i of e.config?.models??[])Ng(i.accessibilityCatalogs)&&n.push({context:{...r,modelId:i.id},catalogs:i.accessibilityCatalogs});return n}var vw=new Set(["speak","break","prosody","emphasis","say-as","sub","mark","phoneme","lang","p","s","voice","audio","lexicon"]),a_=new Set(["script","style","iframe","object","embed","foreignobject","noscript","template"]),l_=new Set(["alphabet","ph","time","strength","rate","pitch","volume","name","interpret-as","format","detail","language","xml:lang","lang","gender","src"]),c_=new Set(["break","mark","lexicon"]);function RW(e){let t=e;for(let r of c_){let n=new RegExp(`<${r}\\b([^>/]*?)\\s*/>`,"gi");t=t.replace(n,(i,o)=>{let s=o?o.replace(/\s+$/,""):"";return`<${r}${s}></${r}>`})}return t}var _W=[/^localhost$/i,/^127(?:\.\d{1,3}){3}$/,/^0(?:\.\d{1,3}){3}$/,/^10(?:\.\d{1,3}){3}$/,/^192\.168(?:\.\d{1,3}){2}$/,/^172\.(?:1[6-9]|2\d|3[01])(?:\.\d{1,3}){2}$/,/^169\.254(?:\.\d{1,3}){2}$/,/^::1$/,/^fe80:/i,/^fc00:/i,/^fd[0-9a-f]{2}:/i,/^metadata\.google\.internal$/i,/^metadata\.azure\.internal$/i,/^metadata\.packet\.net$/i];function PW(e){if(typeof e!="string"||e.length===0)return!1;let t;try{t=new URL(e)}catch{return!1}if(t.protocol!=="http:"&&t.protocol!=="https:")return!1;let r=t.hostname.replace(/^\[|\]$/g,"").replace(/\.$/,"");return!_W.some(n=>n.test(r))}function by(e){let t=Array.from(e.children);for(let n of t){let i=n.tagName.toLowerCase();if(a_.has(i)){n.remove();continue}if(by(n),!vw.has(i)){let o=e.ownerDocument.createTextNode(n.textContent??"");n.replaceWith(o)}}let r=Array.from(e.attributes).map(n=>n.name);for(let n of r)l_.has(n.toLowerCase())||e.removeAttribute(n);if(e.tagName.toLowerCase()==="audio"){let n=e.getAttribute("src");n!==null&&!PW(n)&&e.removeAttribute("src")}}function wy(e){let t=e.tagName.toLowerCase(),r=Array.from(e.attributes).filter(i=>l_.has(i.name.toLowerCase())).map(i=>` ${i.name}="${AW(i.value)}"`).join("");if(c_.has(t))return`<${t}${r}/>`;let n=[];for(let i of Array.from(e.childNodes))if(i.nodeType===3)n.push(Op(i.nodeValue??""));else if(i.nodeType===1){let o=i,s=o.tagName.toLowerCase();if(a_.has(s))continue;vw.has(s)?n.push(wy(o)):n.push(Op(o.textContent??""))}return`<${t}${r}>${n.join("")}</${t}>`}function _I(e){let t=String(e||"").trim();if(!t||!t.includes("<")||typeof DOMParser>"u")return e;let r=new DOMParser().parseFromString(RW(t),"text/html"),n=r.querySelector("speak");if(n)return by(n),wy(n);let i=r.createElement("speak");for(let o of Array.from(r.body.childNodes))i.appendChild(o);return by(i),Array.from(i.childNodes).map(o=>{if(o.nodeType===3)return Op(o.nodeValue??"");if(o.nodeType===1){let s=o;return vw.has(s.tagName.toLowerCase())?wy(s):Op(s.textContent??"")}return""}).join("")}function Op(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function AW(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}var d_=new Set(["spoken","sign-language","transcript","braille","tactile","simplified-language","audio-description","extended-description"]),Sy="ext:";function PI(e){return d_.has(e)?!0:e.startsWith(Sy)&&e.length>Sy.length}var AI=new Set;function Iy(e,t=new Set){if(e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean"||typeof e>"u")return e;if(typeof e!="object")throw TypeError("catalog cards must contain JSON-compatible values");if(t.has(e))throw TypeError("catalog cards must not contain cycles");t.add(e);try{if(Array.isArray(e))return Object.freeze(e.map(i=>Iy(i,t)));let r=Object.getPrototypeOf(e);if(r!==Object.prototype&&r!==null)throw TypeError("catalog cards must contain only plain objects and arrays");let n={};for(let[i,o]of Object.entries(e))n[i]=Iy(o,t);return Object.freeze(n)}finally{t.delete(e)}}function MI(e,t,r){let n=`${t}|${e}`;if(AI.has(n))return;AI.add(n);let i=`${Array.from(d_).join(", ")}, or an "${Sy}" prefixed vendor extension`;if(t==="card"){console.warn(`[AccessibilityCatalogResolver] catalog "${r}" has a card of unknown type "${e}"; it is stored but no reader asks for that type, so the alternate will never be shown. Expected one of: ${i}.`);return}console.warn(`[AccessibilityCatalogResolver] lookup for unknown catalog type "${e}" on "${r}" cannot match any card. Expected one of: ${i}.`)}var $I=e=>e.payload!==void 0?"payload":"content",MW=class{constructor(e,t="en-US"){T(this,"assessmentCatalogs",new Map),T(this,"itemCatalogs",new Map),T(this,"scopedCatalogs",new Map),T(this,"defaultLanguage","en-US"),T(this,"sanitizedSpokenCache",new Map),T(this,"catalogChangeListeners",new Set),T(this,"reportedSnapshotProblems",new Set),this.defaultLanguage=t,this.indexCatalogs(e??[],"assessment")}setDefaultLanguage(e){this.defaultLanguage=e}onCatalogsChange(e){return this.catalogChangeListeners.add(e),()=>{this.catalogChangeListeners.delete(e)}}emitCatalogsChange(e){for(let t of Array.from(this.catalogChangeListeners))try{t(e)}catch{}}getDefaultLanguage(){return this.defaultLanguage}indexCatalogs(e,t){let r=t==="assessment"?this.assessmentCatalogs:this.itemCatalogs;for(let n of this.sanitizeCatalogs(e)){if(r.has(n.identifier)){console.warn(`[AccessibilityCatalogResolver] Duplicate ${t} catalog "${n.identifier}" ignored`);continue}r.set(n.identifier,n)}}insertScopedCatalogs(e,t){if(!t||t.length===0)return null;let r=this.getOwnerKey(e),n=this.scopedCatalogs.get(r),i=n?.catalogs??new Map,o=[];for(let s of this.sanitizeCatalogs(t)){if(i.has(s.identifier)){console.warn(`[AccessibilityCatalogResolver] Duplicate scoped catalog "${s.identifier}" ignored for ${r}`);continue}i.set(s.identifier,s),o.push(s.identifier)}return!n&&o.length>0&&this.scopedCatalogs.set(r,{context:{...e},catalogs:i}),{key:r,context:{...e},catalogs:i,insertedIds:o}}removeScopedInsertion(e){let t=this.scopedCatalogs.get(e.key);if(t?.catalogs!==e.catalogs)return!1;let r=!1;for(let n of e.insertedIds)r=t.catalogs.delete(n)||r;return t.catalogs.size===0&&this.scopedCatalogs.delete(e.key),r}registerCatalogs(e,t){let r=this.insertScopedCatalogs(e,t);r&&r.insertedIds.length>0&&this.emitCatalogsChange({reason:"scoped-registered",context:e});let n=!0;return()=>{n&&(n=!1,r&&this.removeScopedInsertion(r)&&this.emitCatalogsChange({reason:"scoped-removed",context:e}))}}registerOwner(e){let{owner:t,entity:r}=e,n=s_(t),i=[],o=[];try{o=xW(r,t)}catch(a){console.warn("[AccessibilityCatalogResolver] A mounted content owner could not be traversed for catalogs; the primary content remains available.",a)}for(let a of o)try{let l=this.insertScopedCatalogs(a.context,a.catalogs);l&&i.push(l)}catch(l){console.warn("[AccessibilityCatalogResolver] Invalid catalogs on a mounted content owner were ignored; the primary content and other valid catalogs remain available.",l)}i.some(a=>a.insertedIds.length>0)&&this.emitCatalogsChange({reason:"scoped-registered",context:n});let s=!0;return()=>{if(!s)return;s=!1;let a=!1;for(let l of i)a=this.removeScopedInsertion(l)||a;a&&this.emitCatalogsChange({reason:"scoped-removed",context:n})}}forOwner(e){let t={...e};return Object.freeze({snapshot:()=>this.createOwnerSnapshot(t),onChange:r=>this.onCatalogsChange(n=>{this.catalogChangeAffectsOwner(n,t)&&r()})})}addItemCatalogs(e){!e||e.length===0||(this.indexCatalogs(e,"item"),this.emitCatalogsChange({reason:"item-added"}))}clearItemCatalogs(){this.itemCatalogs.size!==0&&(this.itemCatalogs.clear(),this.emitCatalogsChange({reason:"item-cleared"}))}hasCatalog(e){return this.itemCatalogs.has(e)||this.assessmentCatalogs.has(e)||Array.from(this.scopedCatalogs.values()).some(t=>t.catalogs.has(e))}getAlternative(e,t){PI(t.type)||MI(t.type,"lookup",e);let r=t.context?this.scopedCatalogs.get(this.getOwnerKey(t.context))?.catalogs.get(e):null;if(r){let o=this.findMatchingCard(r,t);if(o)return this.resolveCard(e,o,"item")}if(t.context){let o=this.findScopedCandidates(e,t.context);if(o.length===1){let s=this.findMatchingCard(o[0],t);if(s)return this.resolveCard(e,s,"item")}else if(o.length>1)return console.warn(`[AccessibilityCatalogResolver] Ambiguous scoped catalog "${e}" for owner context`,t.context),null}let n=this.itemCatalogs.get(e);if(n){let o=this.findMatchingCard(n,t);if(o)return this.resolveCard(e,o,"item")}let i=this.assessmentCatalogs.get(e);if(i){let o=this.findMatchingCard(i,t);if(o)return this.resolveCard(e,o,"assessment")}return null}resolveCard(e,t,r){return{catalogId:e,type:t.catalog,language:t.language,content:t.catalog==="spoken"&&t.content!==void 0?this.ensureSpokenSanitized(t.content):t.content,payload:t.payload,source:r}}ensureSpokenSanitized(e){let t=this.sanitizedSpokenCache.get(e);if(t!==void 0)return t;let r=_I(e);return this.sanitizedSpokenCache.set(e,r),r}getOwnerKey(e){return[e.ownerKind,e.assessmentId||"",e.sectionId||"",e.canonicalItemId||"",e.itemId||"",e.passageId||"",e.modelId||""].join("|")}scopedCatalogEntries(){let e=[];for(let t of this.scopedCatalogs.values())for(let r of t.catalogs.entries())e.push(r);return e}findScopedCandidates(e,t){return Array.from(this.scopedCatalogs.values()).filter(r=>this.isCompatibleOwnerContext(r.context,t)).map(r=>r.catalogs.get(e)).filter(r=>!!r)}isCompatibleOwnerContext(e,t){return!(e.ownerKind!==t.ownerKind||t.assessmentId&&e.assessmentId!==t.assessmentId||t.sectionId&&e.sectionId!==t.sectionId||t.canonicalItemId&&e.canonicalItemId!==t.canonicalItemId||t.itemId&&e.itemId!==t.itemId||t.passageId&&e.passageId!==t.passageId||t.modelId&&e.modelId!==t.modelId)}ownerScopedCatalogEntries(e){let t=[],r=this.scopedCatalogs.get(this.getOwnerKey(e));r&&t.push(...r.catalogs.entries());for(let n of this.scopedCatalogs.values())n!==r&&this.isCompatibleOwnerContext(n.context,e)&&t.push(...n.catalogs.entries());return t}createOwnerSnapshot(e){let t=[],r=this.ownerScopedCatalogEntries(e);e.ownerKind==="global"&&r.push(...this.assessmentCatalogs.entries());for(let[n,i]of r)for(let o of i.cards)try{t.push(Object.freeze({catalogId:n,card:Iy(o)}))}catch(s){let a=`${this.getOwnerKey(e)}\0${n}`;this.reportedSnapshotProblems.has(a)||(this.reportedSnapshotProblems.add(a),console.warn(`[AccessibilityCatalogResolver] Catalog "${n}" contains a card that cannot be exposed in an owner snapshot; that card was ignored.`,s))}return Object.freeze({cards:Object.freeze(t)})}catalogChangeAffectsOwner(e,t){return e.context?this.isCompatibleOwnerContext(e.context,t)?!0:t.ownerKind==="itemModel"&&t.modelId&&e.context.ownerKind==="itemModel"&&!e.context.modelId?this.isCompatibleOwnerContext({...e.context,modelId:t.modelId},t):!1:!1}sanitizeCatalogs(e){return e.map(t=>({...t,cards:t.cards.map(r=>(PI(r.catalog)||MI(r.catalog,"card",t.identifier),{...r,content:r.catalog==="spoken"&&r.content!==void 0?_I(r.content):r.content}))}))}findMatchingCard(e,t){let{type:r,language:n,useFallback:i=!0,form:o}=t,s=[],a=l=>{for(let d of sP(l))s.push(c=>jw(c.language)===d)};n&&a(n),i&&(a(this.defaultLanguage),s.push(()=>!0));for(let l of s){let d=e.cards.filter(c=>c.catalog===r&&l(c));if(d.length!==0){if(o){let c=d.find(u=>$I(u)===o);if(c)return c}return d[0]}}return null}getAllAlternatives(e){let t=[],r=new Set,n=(s,a)=>{let l=`${s.catalog}|${jw(s.language)}|${$I(s)}`;r.has(l)||(r.add(l),t.push(this.resolveCard(e,s,a)))},i=this.itemCatalogs.get(e);if(i)for(let s of i.cards)n(s,"item");let o=this.assessmentCatalogs.get(e);if(o)for(let s of o.cards)n(s,"assessment");for(let[s,a]of this.scopedCatalogEntries())if(s===e)for(let l of a.cards)n(l,"item");return t}getAllCatalogIds(){let e=this.scopedCatalogEntries().map(([t])=>t);return Array.from(new Set([...this.itemCatalogs.keys(),...this.assessmentCatalogs.keys(),...e]))}getStatistics(){let e=new Set,t=new Set;for(let r of this.assessmentCatalogs.values())for(let n of r.cards)e.add(n.catalog),n.language&&t.add(n.language);for(let r of this.itemCatalogs.values())for(let n of r.cards)e.add(n.catalog),n.language&&t.add(n.language);for(let r of this.scopedCatalogs.values())for(let n of r.catalogs.values())for(let i of n.cards)e.add(i.catalog),i.language&&t.add(i.language);return{totalCatalogs:this.assessmentCatalogs.size+this.itemCatalogs.size+Array.from(this.scopedCatalogs.values()).reduce((r,n)=>r+n.catalogs.size,0),assessmentCatalogs:this.assessmentCatalogs.size,itemCatalogs:this.itemCatalogs.size+Array.from(this.scopedCatalogs.values()).reduce((r,n)=>r+n.catalogs.size,0),availableTypes:e,availableLanguages:t}}hasAlternativeType(e,t){return this.getAllAlternatives(e).some(r=>r.type===t)}getCatalogsByType(e){let t=new Set;for(let[r,n]of this.assessmentCatalogs.entries())n.cards.some(i=>i.catalog===e)&&t.add(r);for(let[r,n]of this.itemCatalogs.entries())n.cards.some(i=>i.catalog===e)&&t.add(r);for(let[r,n]of this.scopedCatalogEntries())n.cards.some(i=>i.catalog===e)&&t.add(r);return Array.from(t)}reset(){this.assessmentCatalogs.clear(),this.itemCatalogs.clear(),this.scopedCatalogs.clear(),this.sanitizedSpokenCache.clear(),this.reportedSnapshotProblems.clear()}destroy(){this.reset()}},$W=class{constructor(){T(this,"elementStates",new Map),T(this,"listeners",new Set),T(this,"onStateChange",null)}getGlobalElementId(e,t,r,n){return`${e}:${t}:${r}:${n}`}parseGlobalElementId(e){let t=e.split(":");return t.length!==4?null:{assessmentId:t[0],sectionId:t[1],itemId:t[2],elementId:t[3]}}setState(e,t,r){let n=this.elementStates.get(e);n||(n=new Map,this.elementStates.set(e,n)),n.set(t,r),this._notifyListeners(),this._notifyStateChange()}getState(e,t){return this.elementStates.get(e)?.get(t)}getElementState(e){let t=this.elementStates.get(e);return t?Object.fromEntries(t.entries()):{}}getAllState(){let e={};for(let[t,r]of this.elementStates.entries())e[t]=Object.fromEntries(r.entries());return e}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}_notifyListeners(){for(let e of this.listeners)e(this.elementStates)}setOnStateChange(e){this.onStateChange=e}_notifyStateChange(){this.onStateChange&&this.onStateChange(this.getAllState())}loadState(e){this.elementStates.clear();for(let[t,r]of Object.entries(e)){let n=new Map(Object.entries(r));this.elementStates.set(t,n)}this._notifyListeners()}clearElement(e){this.elementStates.delete(e),this._notifyListeners(),this._notifyStateChange()}clearTool(e){for(let t of this.elementStates.values())t.delete(e);this._notifyListeners(),this._notifyStateChange()}clearSection(e,t){let r=`${e}:${t}:`,n=[];for(let i of this.elementStates.keys())i.startsWith(r)&&n.push(i);for(let i of n)this.elementStates.delete(i);this._notifyListeners(),this._notifyStateChange()}clearAll(){this.elementStates.clear(),this._notifyListeners(),this._notifyStateChange()}},u_=class{constructor(){T(this,"listeners",new Set)}subscribeFrameworkErrors(e){this.listeners.add(e);let t=!0;return()=>{t&&(t=!1,this.listeners.delete(e))}}reportFrameworkError(e){let t=Array.from(this.listeners);for(let r of t)try{r(e)}catch(n){console.warn("[FrameworkErrorBus] listener failed:",n)}}dispose(){this.listeners.clear()}getListenerCount(){return this.listeners.size}},LW=class{serialize(e,t){return{startContainer:this.getNodePath(e.startContainer,t),startOffset:e.startOffset,endContainer:this.getNodePath(e.endContainer,t),endOffset:e.endOffset,text:e.toString()}}deserialize(e,t){let r=this.findNodeByPath(e.startContainer,t),n=this.findNodeByPath(e.endContainer,t);if(!r||!n)return null;try{let i=new Range;return i.setStart(r,e.startOffset),i.setEnd(n,e.endOffset),i.toString()===e.text?i:null}catch(i){return console.warn("Failed to deserialize range:",i),null}}getNodePath(e,t){if(e===t)return"";if(e.nodeType===Node.TEXT_NODE){let r=e.parentElement;if(!r)throw Error("Text node has no parent");let n=Array.from(r.childNodes).filter(i=>i.nodeType===Node.TEXT_NODE).indexOf(e);return`${this.getElementPath(r,t)}::text[${n}]`}if(e.nodeType===Node.ELEMENT_NODE)return this.getElementPath(e,t);throw Error(`Unsupported node type: ${e.nodeType}`)}getElementPath(e,t){if(e===t)return"";let r=[],n=e;for(;n&&n!==t;){if(n.id){r.unshift(`#${n.id}`);break}let i=n.parentElement;if(!i)break;let o=Array.from(i.children).filter(l=>l.tagName===n.tagName),s=o.indexOf(n),a=o.length>1?`${n.tagName.toLowerCase()}:nth-of-type(${s+1})`:n.tagName.toLowerCase();r.unshift(a),n=i}return r.join(" > ")}findNodeByPath(e,t){if(e==="")return t;if(e.includes("::text[")){let[r,n]=e.split("::text["),i=Number.parseInt(n.replace("]",""),10),o=r?t.querySelector(r):t;return o&&Array.from(o.childNodes).filter(s=>s.nodeType===Node.TEXT_NODE)[i]||null}try{return t.querySelector(e)}catch(r){return console.warn("Invalid selector path:",e,r),null}}serializeMany(e,t){return e.map(r=>this.serialize(r,t))}deserializeMany(e,t){return e.map(r=>this.deserialize(r,t))}},si;(function(e){e.TTS_WORD="tts-word",e.TTS_SENTENCE="tts-sentence",e.ANNOTATION="annotation"})(si||(si={}));var Wc;(function(e){e.YELLOW="yellow",e.GREEN="green",e.BLUE="blue",e.PINK="pink",e.ORANGE="orange",e.UNDERLINE="underline"})(Wc||(Wc={}));var yw=class ky{constructor(){if(T(this,"ttsWordHighlight",null),T(this,"ttsSentenceHighlight",null),T(this,"ttsWordElementHighlights",new Set),T(this,"ttsSentenceElementHighlights",new Set),T(this,"annotations",new Map),T(this,"colorHighlights",new Map),T(this,"nextAnnotationId",1),T(this,"supported",!1),T(this,"rangeSerializer",void 0),T(this,"themeObserver",null),T(this,"explicitTTSColorOverride",null),this.rangeSerializer=new LW,typeof CSS>"u"||!("highlights"in CSS)){console.warn("CSS Custom Highlight API not supported (SSR or unsupported browser)");return}this.supported=!0,this.initializeHighlights(),this.registerStyles(),this.applyAdaptiveTTSStyle(),this.setupThemeObservation()}setupThemeObservation(){if(typeof document>"u"||typeof MutationObserver>"u")return;let t=()=>this.applyAdaptiveTTSStyle();this.themeObserver=new MutationObserver(t),this.themeObserver.observe(document.documentElement,{attributes:!0,attributeFilter:["style","data-theme","data-color-scheme","class"]});for(let r of document.querySelectorAll("pie-theme"))this.themeObserver.observe(r,{attributes:!0,attributeFilter:["theme","scheme","provider","variables","style","data-theme","data-color-scheme"]})}parseColor(t){if(!t)return null;let r=t.trim();if(!r)return null;let n=/^#([a-f\d]{3}|[a-f\d]{6})$/i.exec(r);if(n){let o=n[1];return o.length===3?[parseInt(o[0]+o[0],16),parseInt(o[1]+o[1],16),parseInt(o[2]+o[2],16)]:[parseInt(o.slice(0,2),16),parseInt(o.slice(2,4),16),parseInt(o.slice(4,6),16)]}let i=/^rgba?\((.+)\)$/i.exec(r);if(i){let o=i[1].replace(/\//g,",").split(/[,\s]+/).map(d=>d.trim()).filter(Boolean),s=Number(o[0]),a=Number(o[1]),l=Number(o[2]);if(Number.isFinite(s)&&Number.isFinite(a)&&Number.isFinite(l))return[s,a,l]}if(typeof document<"u"){let o=document.createElement("span");if(o.style.color=r,typeof o.style.color=="string"&&o.style.color){document.body?.appendChild(o);let s=typeof getComputedStyle=="function"?getComputedStyle(o).color:"";o.remove();let a=s.trim();if(a&&a!==r)return this.parseColor(s)}}return null}relativeLuminance([t,r,n]){let i=l=>{let d=l/255;return d<=.03928?d/12.92:((d+.055)/1.055)**2.4},o=i(t),s=i(r),a=i(n);return .2126*o+.7152*s+.0722*a}contrastRatio(t,r){let n=this.relativeLuminance(t),i=this.relativeLuminance(r),o=Math.max(n,i),s=Math.min(n,i);return(o+.05)/(s+.05)}blend(t,r,n){return[Math.round(t[0]*n+r[0]*(1-n)),Math.round(t[1]*n+r[1]*(1-n)),Math.round(t[2]*n+r[2]*(1-n))]}resolveAdaptiveTTSStyle(t){let r=[255,235,59],n=[17,24,39],i=[255,255,255],o=t||(typeof document<"u"?document.documentElement:null),s=o&&typeof getComputedStyle=="function"?getComputedStyle(o):null,a=this.parseColor(s?.getPropertyValue("--pie-background")||s?.backgroundColor)||i,l=this.parseColor(s?.getPropertyValue("--pie-text"))||n,d=this.explicitTTSColorOverride?this.parseColor(this.explicitTTSColorOverride.color)||r:this.parseColor(s?.getPropertyValue("--pie-missing"))||r,c=this.explicitTTSColorOverride?[Math.max(.3,Math.min(.95,this.explicitTTSColorOverride.opacity))]:[.8,.72,.68,.62,.56,.5],u=c[c.length-1],f=-1/0;for(let L of c){let E=this.blend(d,a,L),M=this.contrastRatio(E,a),U=this.contrastRatio(E,l),te=M*1.2+U*.8;if(M>=1.25&&U>=2.4){u=L;break}te>f&&(f=te,u=L)}let p=Math.max(.24,Math.min(.85,u*.55)),g=Math.max(.55,Math.min(.95,u+.2)),v=Math.max(.22,Math.min(.6,u*.45)),b=l,w=this.blend(b,a,g),I=this.contrastRatio(w,a),x=this.relativeLuminance(a)>.45?[0,0,0]:[255,255,255],C=I>=1.35?b:x;return{wordHighlight:`rgba(${d[0]}, ${d[1]}, ${d[2]}, ${u})`,sentenceHighlight:`rgba(${d[0]}, ${d[1]}, ${d[2]}, ${p})`,wordUnderline:`rgba(${C[0]}, ${C[1]}, ${C[2]}, ${g})`,wordShadow:`rgba(${C[0]}, ${C[1]}, ${C[2]}, ${v})`}}applyAdaptiveTTSStyle(t){if(typeof document>"u")return;let r=this.resolveAdaptiveTTSStyle(t);document.documentElement.style.setProperty("--pie-tts-word-highlight",r.wordHighlight),document.documentElement.style.setProperty("--pie-tts-sentence-highlight",r.sentenceHighlight),document.documentElement.style.setProperty("--pie-tts-line-highlight",r.sentenceHighlight),document.documentElement.style.setProperty("--pie-tts-word-underline",r.wordUnderline),document.documentElement.style.setProperty("--pie-tts-word-shadow",r.wordShadow)}initializeHighlights(){if(this.supported){this.ttsWordHighlight=new Highlight,this.ttsSentenceHighlight=new Highlight,CSS.highlights.set("tts-word",this.ttsWordHighlight),CSS.highlights.set("tts-sentence",this.ttsSentenceHighlight);for(let t of Object.values(Wc)){let r=new Highlight;this.colorHighlights.set(t,r),CSS.highlights.set(`annotation-${t}`,r)}}}registerStyles(){if(!this.supported||typeof document>"u"||document.getElementById("pie-highlight-styles"))return;let t=document.createElement("style");t.id="pie-highlight-styles",t.textContent=`
1320
+ /* TTS highlights - temporary */
1321
+ ::highlight(tts-word) {
1322
+ background-color: var(--pie-tts-word-highlight, color-mix(in srgb, var(--pie-missing, #ffeb3b) 68%, transparent));
1323
+ text-decoration: underline 2px solid var(--pie-tts-word-underline, color-mix(in srgb, var(--pie-text, #111827) 70%, transparent));
1324
+ text-underline-offset: 2px;
1325
+ text-shadow: 0 0 1px var(--pie-tts-word-shadow, color-mix(in srgb, var(--pie-text, #111827) 35%, transparent));
1326
+ color: inherit;
1327
+ }
1328
+
1329
+ /* tts-sentence registry id: coarse read-along band (visual line boxes in layout) */
1330
+ ::highlight(tts-sentence) {
1331
+ background-color: var(--pie-tts-line-highlight, var(--pie-tts-sentence-highlight, color-mix(in srgb, var(--pie-missing, #ffeb3b) 38%, transparent)));
1332
+ color: inherit;
1333
+ }
1334
+
1335
+ [data-pie-tts-sentence-element="true"] {
1336
+ background-color: var(--pie-tts-line-highlight, var(--pie-tts-sentence-highlight, color-mix(in srgb, var(--pie-missing, #ffeb3b) 38%, transparent)));
1337
+ border-radius: 0.12em;
1338
+ box-decoration-break: clone;
1339
+ -webkit-box-decoration-break: clone;
1340
+ }
1341
+
1342
+ [data-pie-tts-word-element="true"] {
1343
+ background-color: var(--pie-tts-word-highlight, color-mix(in srgb, var(--pie-missing, #ffeb3b) 68%, transparent));
1344
+ text-decoration: underline 2px solid var(--pie-tts-word-underline, color-mix(in srgb, var(--pie-text, #111827) 70%, transparent));
1345
+ text-underline-offset: 2px;
1346
+ text-shadow: 0 0 1px var(--pie-tts-word-shadow, color-mix(in srgb, var(--pie-text, #111827) 35%, transparent));
1347
+ border-bottom: 2px solid var(--pie-tts-word-underline, color-mix(in srgb, var(--pie-text, #111827) 70%, transparent));
1348
+ padding-bottom: 1px;
1349
+ border-radius: 0.12em;
1350
+ box-decoration-break: clone;
1351
+ -webkit-box-decoration-break: clone;
1352
+ }
1353
+
1354
+ /* Annotation highlights - persistent */
1355
+ ::highlight(annotation-yellow) {
1356
+ background-color: var(--pie-annotation-yellow-highlight, rgba(253, 233, 149, 0.5));
1357
+ color: inherit;
1358
+ }
1359
+
1360
+ ::highlight(annotation-green) {
1361
+ background-color: var(--pie-annotation-green-highlight, rgba(166, 225, 197, 0.5));
1362
+ color: inherit;
1363
+ }
1364
+
1365
+ ::highlight(annotation-blue) {
1366
+ background-color: var(--pie-annotation-blue-highlight, rgba(167, 224, 246, 0.5));
1367
+ color: inherit;
1368
+ }
1369
+
1370
+ ::highlight(annotation-pink) {
1371
+ background-color: var(--pie-annotation-pink-highlight, rgba(255, 159, 174, 0.5));
1372
+ color: inherit;
1373
+ }
1374
+
1375
+ ::highlight(annotation-orange) {
1376
+ background-color: var(--pie-annotation-orange-highlight, rgba(255, 165, 0, 0.5));
1377
+ color: inherit;
1378
+ }
1379
+
1380
+ /* The base light/dark pair is fixed: #4221d5 on light, #9c89ec on dark.
1381
+ One value cannot serve both -- #4221d5 is 2.41:1 on black and #9c89ec is
1382
+ 2.85:1 on white -- so neither of those two consults the theme accent,
1383
+ which is chosen against one background and illegible on the other.
1384
+
1385
+ Each state has its own token so overriding one never silently moves the
1386
+ other, and so either can beat a host-set pie-primary: a var() fallback
1387
+ can never override a value the host actually set. */
1388
+ ::highlight(annotation-underline) {
1389
+ background-color: transparent;
1390
+ text-decoration: underline 2px solid var(--pie-annotation-underline, #4221d5);
1391
+ text-underline-offset: 2px;
1392
+ color: inherit;
1393
+ }
1394
+
1395
+ /* The blocks below cover annotation swatches, print, and reduced motion.
1396
+ They deliberately do NOT retune the TTS layers: applyAdaptiveTTSStyle()
1397
+ writes the pie-tts custom properties inline on documentElement on every
1398
+ paint and on theme change, so a media query that only varies a var()
1399
+ fallback for those can never take effect. Annotation colours have no such
1400
+ adaptive path -- they are fixed swatches a student chose -- so a media
1401
+ query is the only way to adjust them, and each keeps its var() so a host
1402
+ override still wins.
1403
+
1404
+ The names above are spelled without their leading dashes on purpose.
1405
+ check-theme-tokens scans comments, and its token pattern stops at the
1406
+ first non-alphanumeric character, so writing the wildcard form reads as
1407
+ consumption of a shorter token that is not in the registry and fails the
1408
+ check. Spell property names in full, or omit the dashes. */
1409
+
1410
+ @media (prefers-color-scheme: dark) {
1411
+ ::highlight(annotation-yellow) {
1412
+ background-color: var(--pie-annotation-yellow-highlight, rgba(139, 117, 0, 0.6));
1413
+ }
1414
+ ::highlight(annotation-green) {
1415
+ background-color: var(--pie-annotation-green-highlight, rgba(45, 92, 63, 0.6));
1416
+ }
1417
+ ::highlight(annotation-blue) {
1418
+ background-color: var(--pie-annotation-blue-highlight, rgba(0, 102, 170, 0.6));
1419
+ }
1420
+ ::highlight(annotation-pink) {
1421
+ background-color: var(--pie-annotation-pink-highlight, rgba(139, 51, 74, 0.6));
1422
+ }
1423
+ ::highlight(annotation-orange) {
1424
+ background-color: var(--pie-annotation-orange-highlight, rgba(154, 99, 0, 0.6));
1425
+ }
1426
+ ::highlight(annotation-underline) {
1427
+ text-decoration-color: var(--pie-annotation-underline-dark, #9c89ec);
1428
+ }
1429
+ }
1430
+
1431
+ /* The media query above reports the OS preference, which is only a guess
1432
+ at what the page is actually showing. An app that declares a theme has
1433
+ the final say, so the rules below override it. pie-theme always stamps
1434
+ data-theme on documentElement (scope="document") or on its own host, and
1435
+ resolves to a dark palette only for the literal value "dark" -- every
1436
+ other value, including DaisyUI theme ids, maps to a light base.
1437
+
1438
+ The three cases are mutually exclusive, so they never fight each other.
1439
+ All carry attribute selectors, which outrank the bare ::highlight() rules
1440
+ above -- including the one inside the media query, since a media query
1441
+ adds no specificity -- whatever the source order. */
1442
+ [data-theme="light"] ::highlight(annotation-underline) {
1443
+ text-decoration-color: var(--pie-annotation-underline, #4221d5);
1444
+ }
1445
+
1446
+ [data-theme="dark"] ::highlight(annotation-underline) {
1447
+ text-decoration-color: var(--pie-annotation-underline-dark, #9c89ec);
1448
+ }
1449
+
1450
+ /* A host or DaisyUI palette: follow its accent so the mark belongs to that
1451
+ theme, falling back to the light default when it declares none. */
1452
+ [data-theme]:not([data-theme="light"]):not([data-theme="dark"]) ::highlight(annotation-underline) {
1453
+ text-decoration-color: var(--pie-annotation-underline, var(--pie-primary, #4221d5));
1454
+ }
1455
+
1456
+ /* WCAG 2.2 SC 1.4.11 non-text contrast: a highlight is the only indication
1457
+ that text is annotated, so the swatches saturate and the underline
1458
+ thickens when the user asks for more contrast.
1459
+
1460
+ The value is "more", not "high". The stylesheet this was recovered from
1461
+ used prefers-contrast: high, which is not a valid value for the feature
1462
+ -- the keywords are no-preference, more, less, custom. An invalid query
1463
+ evaluates to "not all", so that block could never have matched in any
1464
+ browser even had the file been loaded. Verified with matchMedia under
1465
+ emulation: "high" stays false where "more" flips true. */
1466
+ @media (prefers-contrast: more) {
1467
+ ::highlight(annotation-yellow) {
1468
+ background-color: var(--pie-annotation-yellow-highlight, rgba(255, 255, 0, 0.7));
1469
+ }
1470
+ ::highlight(annotation-green) {
1471
+ background-color: var(--pie-annotation-green-highlight, rgba(0, 255, 127, 0.7));
1472
+ }
1473
+ ::highlight(annotation-blue) {
1474
+ background-color: var(--pie-annotation-blue-highlight, rgba(0, 191, 255, 0.7));
1475
+ }
1476
+ ::highlight(annotation-pink) {
1477
+ background-color: var(--pie-annotation-pink-highlight, rgba(255, 105, 180, 0.7));
1478
+ }
1479
+ ::highlight(annotation-orange) {
1480
+ background-color: var(--pie-annotation-orange-highlight, rgba(255, 165, 0, 0.85));
1481
+ }
1482
+ ::highlight(annotation-underline) {
1483
+ text-decoration-thickness: 3px;
1484
+ }
1485
+ }
1486
+
1487
+ @media print {
1488
+ /* TTS highlighting is a transient read-along cue, not content. */
1489
+ ::highlight(tts-word),
1490
+ ::highlight(tts-sentence),
1491
+ [data-pie-tts-word-element="true"],
1492
+ [data-pie-tts-sentence-element="true"] {
1493
+ background-color: transparent;
1494
+ text-decoration: none;
1495
+ text-shadow: none;
1496
+ border-bottom: none;
1497
+ }
1498
+
1499
+ /* Annotations are student work and must survive printing, but a fill
1500
+ that reads fine on screen can print as an illegible wash, so each
1501
+ becomes an underline that keeps its colour coding. */
1502
+ ::highlight(annotation-yellow),
1503
+ ::highlight(annotation-green),
1504
+ ::highlight(annotation-blue),
1505
+ ::highlight(annotation-pink),
1506
+ ::highlight(annotation-orange) {
1507
+ background-color: transparent;
1508
+ border-bottom: 2px solid currentColor;
1509
+ }
1510
+ ::highlight(annotation-yellow) { border-bottom-color: #ffeb3b; }
1511
+ ::highlight(annotation-green) { border-bottom-color: #a6e1c5; }
1512
+ ::highlight(annotation-blue) { border-bottom-color: #a7e0f6; }
1513
+ ::highlight(annotation-pink) { border-bottom-color: #ff9fae; }
1514
+ ::highlight(annotation-orange) { border-bottom-color: #ffa500; }
1515
+ ::highlight(annotation-underline) {
1516
+ text-decoration-color: #000;
1517
+ border-bottom: none;
1518
+ }
1519
+ }
1520
+
1521
+ /* text-shadow is a direct property rather than a var(), so unlike the
1522
+ other TTS rules this one is not overridden by the adaptive path. */
1523
+ @media (prefers-reduced-motion: reduce) {
1524
+ ::highlight(tts-word),
1525
+ [data-pie-tts-word-element="true"] {
1526
+ text-shadow: none;
1527
+ }
1528
+ }
1529
+ `,document.head.appendChild(t)}highlightTTSWord(t,r,n){if(!this.ttsWordHighlight)return;this.applyAdaptiveTTSStyle(t.parentElement),this.clearTTSWord();let i=document.createRange();i.setStart(t,r),i.setEnd(t,n),this.ttsWordHighlight.add(i)}highlightTTSWordElement(t){this.ttsWordHighlight&&(this.applyAdaptiveTTSStyle(t),this.clearTTSWord(),t.setAttribute("data-pie-tts-word-element","true"),this.ttsWordElementHighlights.add(t))}highlightTTSSentence(t){if(!this.ttsSentenceHighlight)return;let r=t[0]?.startContainer,n=r?.nodeType===Node.ELEMENT_NODE?r:r?.parentElement;this.applyAdaptiveTTSStyle(n),this.clearTTSSentence();for(let i of t)this.ttsSentenceHighlight.add(i);this.highlightTTSElementFallbacks(t)}highlightTTSSentenceElements(t){if(this.ttsSentenceHighlight){this.applyAdaptiveTTSStyle(t[0]||null),this.clearTTSSentence();for(let r of t)r.setAttribute("data-pie-tts-sentence-element","true"),this.ttsSentenceElementHighlights.add(r)}}highlightTTSElementFallbacks(t){typeof Element>"u"||this.highlightElementFallbacks(t,"data-pie-tts-sentence-element",this.ttsSentenceElementHighlights,ky.SENTENCE_FALLBACK_SELECTOR)}highlightTTSWordElementFallbacks(t){typeof Element>"u"||this.highlightElementFallbacks(t,"data-pie-tts-word-element",this.ttsWordElementHighlights,ky.WORD_FALLBACK_SELECTOR)}highlightElementFallbacks(t,r,n,i){for(let o of t){let s=o.commonAncestorContainer.nodeType===Node.ELEMENT_NODE?o.commonAncestorContainer:o.commonAncestorContainer.parentElement;if(!s)continue;let a=[],l=o.startContainer.nodeType===Node.ELEMENT_NODE?o.startContainer:o.startContainer.parentElement,d=o.endContainer.nodeType===Node.ELEMENT_NODE?o.endContainer:o.endContainer.parentElement;for(let c of[l,d]){let u=c;for(;u;)u.matches?.(i)&&a.push(u),u=u.parentElement}s.matches?.(i)&&a.push(s),a.push(...Array.from(s.querySelectorAll(i)));for(let c of new Set(a)){try{if(!o.intersectsNode(c)&&!c.contains(l)&&!c.contains(d))continue}catch{continue}c.setAttribute(r,"true"),n.add(c)}}}clearTTSWord(){if(this.ttsWordHighlight){this.ttsWordHighlight.clear();for(let t of this.ttsWordElementHighlights)t.removeAttribute("data-pie-tts-word-element");this.ttsWordElementHighlights.clear()}}clearTTSSentence(){if(this.ttsSentenceHighlight){this.ttsSentenceHighlight.clear();for(let t of this.ttsSentenceElementHighlights)t.removeAttribute("data-pie-tts-sentence-element");this.ttsSentenceElementHighlights.clear()}}clearTTS(){this.clearTTSWord(),this.clearTTSSentence()}addAnnotation(t,r=Wc.YELLOW){let n=`annotation-${this.nextAnnotationId++}`,i=t.cloneRange(),o={id:n,range:i,type:si.ANNOTATION,color:r,timestamp:Date.now()};this.annotations.set(n,o);let s=this.colorHighlights.get(r);return s&&s.add(i),n}removeAnnotation(t){let r=this.annotations.get(t);if(!r){console.warn(`[HighlightCoordinator] Annotation ${t} not found`);return}console.log(`[HighlightCoordinator] Removing annotation ${t} (color: ${r.color})`);let n=this.colorHighlights.get(r.color);if(n){let i=n.delete(r.range);console.log("[HighlightCoordinator] Highlight.delete() returned:",i)}this.annotations.delete(t),console.log(`[HighlightCoordinator] Annotation ${t} removed from map. Remaining:`,this.annotations.size)}clearAnnotations(){for(let t of this.colorHighlights.values())t.clear();this.annotations.clear()}getAnnotations(){return Array.from(this.annotations.values())}getAnnotation(t){return this.annotations.get(t)??null}changeAnnotationColor(t,r){let n=this.annotations.get(t);if(!n)return;let i=n.color;if(i===r)return;let o=this.colorHighlights.get(i);o&&o.delete(n.range),n.color=r;let s=this.colorHighlights.get(r);s&&s.add(n.range)}exportAnnotations(t=document.body){return this.getAnnotations().map(r=>({...this.rangeSerializer.serialize(r.range,t),id:r.id,color:r.color,timestamp:r.timestamp}))}importAnnotations(t,r=document.body){let n=0;for(let i of t){let o=this.rangeSerializer.deserialize(i,r);o&&(this.addAnnotation(o,i.color),n++)}return n}highlightRange(t,r,n=Wc.YELLOW){if(this.supported)switch(r){case si.TTS_WORD:case si.TTS_SENTENCE:{let i=r===si.TTS_WORD?this.ttsWordHighlight:this.ttsSentenceHighlight;if(i&&(i.clear(),i.add(t),r===si.TTS_WORD)){for(let o of this.ttsWordElementHighlights)o.removeAttribute("data-pie-tts-word-element");this.ttsWordElementHighlights.clear(),this.highlightTTSWordElementFallbacks([t])}break}case si.ANNOTATION:this.addAnnotation(t,n)}}clearHighlights(t){if(this.supported)switch(t){case si.TTS_WORD:this.clearTTSWord();break;case si.TTS_SENTENCE:this.clearTTSSentence();break;case si.ANNOTATION:this.clearAnnotations()}}clearAll(){this.supported&&(this.clearTTS(),this.clearAnnotations())}isSupported(){return this.supported}updateTTSHighlightStyle(t,r){if(!this.supported||typeof document>"u"||!document.getElementById("pie-highlight-styles"))return;let n=(i=>{let o=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(i);return o?{r:parseInt(o[1],16),g:parseInt(o[2],16),b:parseInt(o[3],16)}:null})(t);n&&(this.explicitTTSColorOverride={color:`rgb(${n.r}, ${n.g}, ${n.b})`,opacity:Math.max(.2,Math.min(.95,r))},this.applyAdaptiveTTSStyle())}destroy(){this.supported&&(this.clearTTS(),this.clearAnnotations(),this.themeObserver?.disconnect(),this.themeObserver=null)}};T(yw,"SENTENCE_FALLBACK_SELECTOR","math, mjx-container, svg, img, canvas, [role='img']");T(yw,"WORD_FALLBACK_SELECTOR","svg, img, canvas, [role='img']");function OW(e){return(...t)=>{console.debug(`[${e}]`,...t)}}var is=OW("ToolCoordinator"),ha;(function(e){e[e.BASE=0]="BASE",e[e.TOOL=1e3]="TOOL",e[e.MODAL=2e3]="MODAL",e[e.CONTROL=3e3]="CONTROL",e[e.HIGHLIGHT=4e3]="HIGHLIGHT"})(ha||(ha={}));var NW=class{constructor(){T(this,"tools",new Map),T(this,"layerCounters",new Map),T(this,"listeners",new Set),T(this,"visibilityState",new Map),this.layerCounters.set(ha.BASE,0),this.layerCounters.set(ha.TOOL,0),this.layerCounters.set(ha.MODAL,0),this.layerCounters.set(ha.CONTROL,0),this.layerCounters.set(ha.HIGHLIGHT,0)}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}notifyListeners(){this.listeners.forEach(e=>e())}registerTool(e,t,r,n=ha.MODAL){if(is("registerTool called:",{id:e,name:t,hasElement:!!r,layer:n}),this.tools.has(e)){is(`Tool ${e} is already registered`);return}let i=this.visibilityState.get(e)??!1;if(!r){this.tools.set(e,{id:e,name:t,element:null,layer:n,isVisible:i,baseZIndex:n}),is("Tool registered without element:",e);return}let o=n+this.getNextLayerOffset(n);r.style.zIndex=String(o),r.style.display=i?"":"none";let s=()=>this.bringToFront(r);r.addEventListener("mousedown",s),this.tools.set(e,{id:e,name:t,element:r,layer:n,isVisible:i,baseZIndex:o,mouseDownHandler:s}),i&&this.bringToFront(r),is("Tool registered with element:",e)}unregisterTool(e){let t=this.tools.get(e);t&&(t.element&&t.mouseDownHandler&&t.element.removeEventListener("mousedown",t.mouseDownHandler),this.tools.delete(e))}releaseTool(e){this.unregisterTool(e),this.visibilityState.delete(e)}showTool(e){let t=this.tools.get(e);if(!t){is(`Tool ${e} not found`);return}t.element&&(t.element.style.display="",this.bringToFront(t.element)),t.isVisible=!0,this.visibilityState.set(e,!0),this.notifyListeners()}hideTool(e){let t=this.tools.get(e);if(!t){is(`Tool ${e} not found`);return}t.element&&(t.element.style.display="none"),t.isVisible=!1,this.visibilityState.set(e,!1),this.notifyListeners()}toggleTool(e){is("toggleTool called for:",e);let t=this.tools.get(e);if(!t){is(`Tool ${e} not found. Registered tools:`,Array.from(this.tools.keys()));return}is("Tool found, current visibility:",t.isVisible),t.isVisible?this.hideTool(e):this.showTool(e)}isToolVisible(e){let t=this.tools.get(e);return t?t.isVisible:this.visibilityState.get(e)??!1}bringToFront(e){let t=Array.from(this.tools.values()).find(i=>i.element===e);if(!t)return;let r=this.getMaxZIndexInLayer(t.layer),n=Math.max(r+1,t.layer+1);e.style.zIndex=String(n),t.baseZIndex=n}getRegisteredTools(){return Array.from(this.tools.keys())}getToolElement(e){return this.tools.get(e)?.element??null}getNextLayerOffset(e){let t=this.layerCounters.get(e)??0;return this.layerCounters.set(e,t+1),t}getMaxZIndexInLayer(e){let t=e;for(let r of this.tools.values())r.layer===e&&(t=Math.max(t,r.baseZIndex));return t}resetZIndices(){for(let e of this.tools.values())e.element&&(e.element.style.zIndex=String(e.baseZIndex))}updateToolElement(e,t){let r=this.tools.get(e);if(!r){is(`Tool ${e} not found`);return}r.element&&r.mouseDownHandler&&r.element.removeEventListener("mousedown",r.mouseDownHandler);let n=()=>this.bringToFront(t);t.addEventListener("mousedown",n),r.element=t,r.mouseDownHandler=n,t.style.zIndex=String(r.baseZIndex),r.isVisible?t.style.display="":t.style.display="none"}hideAllTools(){for(let e of this.tools.keys())this.hideTool(e);this.notifyListeners()}getToolState(e){let t=this.tools.get(e);if(t)return{id:t.id,name:t.name,isVisible:t.isVisible,element:t.element??null,layer:t.layer}}getVisibleTools(){return Array.from(this.tools.values()).filter(e=>e.isVisible).map(e=>({id:e.id,name:e.name,isVisible:e.isVisible,element:e.element??null,layer:e.layer}))}};function DW(e){if(!e)return null;let t=e.payload;if(!t||typeof t!="object")return null;let r=t.media;if(!r||typeof r!="object")return console.warn("[spoken-audio] card carries a `payload` with no `media`; recorded speech needs `media.sources`, so this card is ignored and read-aloud falls back to the script or generated speech"),null;if(H$(r.version))return console.warn(`[spoken-audio] card's media declares version ${String(r.version)}, which this build does not render; the card is ignored and read-aloud falls back to the script or generated speech`),null;if(r.kind!==void 0&&r.kind!=="audio")return console.warn(`[spoken-audio] card's media is kind "${r.kind}", not "audio"; a spoken card carries recorded speech, so this card is ignored`),null;let n=W$(r.sources);return n.length===0?(console.warn("[spoken-audio] card's `media.sources` yielded no usable URL; read-aloud falls back to the script or generated speech"),null):{sources:n,fragment:WT(t.fragment),label:U$(r.label)}}var bw=(e,t)=>{let r=t?.useSentenceSegmenter!==!1;try{if(!r)throw Error("Segmenter disabled by policy");let s=globalThis.Intl?.Segmenter;if(typeof s=="function"){let a=new s(t?.locale,{granularity:"sentence"}),l=Array.from(a.segment(e)).map(d=>({text:d.segment,offset:d.index})).filter(d=>d.text.trim().length>0);if(l.length>0)return l}}catch{}let n=e.match(/[^.!?]+(?:[.!?]+|$)/g)||[e],i=[],o=0;for(let s of n){let a=e.indexOf(s,o);a!==-1&&(i.push({text:s,offset:a}),o=a+s.length)}return i.length>0?i:[{text:e,offset:0}]},LI=5e3,OI=2e3,f_=e=>String(e||"").trim().toLowerCase(),jW=()=>f_((typeof navigator<"u"?navigator.language||navigator.languages?.[0]:"")||"en-US"),BW=(e,t)=>{if(t)return e.find(s=>s.voiceURI===t)||e.find(s=>s.name===t)||null;let r=jW(),n=r.split("-")[0]||"en",i=s=>{let a=f_(s.lang);return a===r||a.startsWith(`${n}-`)},o=[s=>s.localService&&i(s),s=>s.default&&i(s),s=>i(s),s=>s.localService,s=>s.default];for(let s of o){let a=e.find(s);if(a)return a}return e[0]||null},FW=e=>!e.default,h_=class{constructor(){T(this,"providerId","browser"),T(this,"providerName","Browser Speech Synthesis"),T(this,"version","1.0.0")}async initialize(e){if(typeof window>"u")throw Error("BrowserTTSProvider requires browser environment");if(!("speechSynthesis"in window))throw Error("Browser does not support Speech Synthesis API");return new HW(e)}supportsFeature(e){return!0}getCapabilities(){return{supportsPause:!0,supportsResume:!0,supportsWordBoundary:!0,supportsVoiceSelection:!0,supportsRateControl:!0,supportsPitchControl:!0,supportsSSML:!1}}destroy(){}},HW=class{constructor(e){T(this,"utterance",null),T(this,"config",null),T(this,"_isPlaying",!1),T(this,"_isPaused",!1),T(this,"speakRunId",0),T(this,"settlePendingVoiceWait",null),T(this,"settlePendingChunk",null),T(this,"onPlaybackStart",void 0),T(this,"onWordBoundary",void 0),this.config=e}waitForBrowserVoices(e,t){return new Promise((r,n)=>{let i=speechSynthesis,o=typeof i.addEventListener=="function"&&typeof i.removeEventListener=="function",s=o?null:i.onvoiceschanged,a=!1,l=null,d=null,c=()=>{l!==null&&(clearTimeout(l),l=null),o?i.removeEventListener("voiceschanged",p):i.onvoiceschanged===g&&(i.onvoiceschanged=s),d&&this.settlePendingVoiceWait===d&&(this.settlePendingVoiceWait=null)},u=(v,b)=>{a||(a=!0,c(),b?n(b):r(v))},f=()=>{if(e!==this.speakRunId){u(!1);return}i.getVoices().length>0&&u(!0)},p=()=>f(),g=v=>{try{s?.call(i,v)}finally{f()}};d=()=>u(!1),this.settlePendingVoiceWait=d,l=setTimeout(()=>u(!1,Error(`Configured browser voice "${t}" could not be resolved because the browser did not publish its voice inventory within ${OI/1e3} seconds.`)),OI),o?i.addEventListener("voiceschanged",p):i.onvoiceschanged=g,f()})}async resolveBrowserVoice(e){let t=typeof this.config?.voice=="string"?this.config.voice.trim():"",r=speechSynthesis.getVoices();if(t&&r.length===0){if(!await this.waitForBrowserVoices(e,t)||e!==this.speakRunId)return{shouldContinue:!1,voice:null};r=speechSynthesis.getVoices()}if(e!==this.speakRunId)return{shouldContinue:!1,voice:null};let n=BW(r,t||void 0);if(t&&!n)throw Error(`Configured browser voice "${t}" is unavailable. Select a voice exposed by this browser using its voiceURI or name.`);return{shouldContinue:!0,voice:n}}async speak(e){if(!this.config)throw Error("TTS not initialized");this.stop();let t=this.speakRunId,r=await this.resolveBrowserVoice(t);if(!r.shouldContinue)return;let n=this.splitIntoChunks(e);for(let i of n)if(t!==this.speakRunId||!await this.speakChunk(i.text,i.offset,t,r.voice))break}async speakSegments(e){if(!this.config)throw Error("TTS not initialized");this.stop();let t=this.speakRunId,r=await this.resolveBrowserVoice(t);if(r.shouldContinue)for(let n of e){if(t!==this.speakRunId)break;let i=this.splitIntoChunks(n.text);for(let s of i)if(t!==this.speakRunId||!await this.speakChunk(s.text,n.startOffset+s.offset,t,r.voice))break;let o=Math.max(0,Number(n.pauseMsAfter||0));if(o>0&&t===this.speakRunId&&!await this.waitForPause(o,t))break}}async waitForPause(e,t){return await new Promise(r=>setTimeout(r,e)),t===this.speakRunId}splitIntoChunks(e){if(e.length<=260)return[{text:e,offset:0}];let t=this.segmentSentences(e),r=[],n="",i=0;for(let o of t){let s=o.text.trim();if(!s)continue;let a=o.text.search(/\S/),l=o.offset+(a===-1?0:a);if(!n){n=s,i=l;continue}let d=`${n} ${s}`;d.length<=260?n=d:(r.push({text:n,offset:i}),n=s,i=l)}return n&&r.push({text:n,offset:i}),r.length?r:[{text:e,offset:0}]}getHighlightMode(){return(this.config?.providerOptions||{}).highlightMode==="word"?"word":"sentence"}getSegmentationPolicy(){let e=this.config?.providerOptions||{},t=e.segmenter||{},r=t.mode!=="regexOnly";return{useSentenceSegmenter:r,useWordSegmenter:r,locale:typeof t.locale=="string"&&t.locale.trim().length>0?t.locale:typeof e.locale=="string"&&e.locale.trim().length>0?e.locale:void 0}}segmentSentences(e){let t=this.getSegmentationPolicy();return bw(e,{locale:t.locale,useSentenceSegmenter:t.useSentenceSegmenter})}inferWordLength(e,t){let r=Math.max(0,Math.min(t,Math.max(0,e.length-1)));return e.slice(r).match(/^\s*([^\s]+)/)?.[1]?.length||1}async speakChunk(e,t,r,n){return new Promise((i,o)=>{if(r!==this.speakRunId){i(!1);return}let s=new SpeechSynthesisUtterance(e);this.utterance=s,n&&FW(n)&&(s.voice=n),this.config?.rate&&(s.rate=this.config.rate),this.config?.pitch&&(s.pitch=this.config.pitch);let a=!1,l=!1,d=null,c=null,u=()=>{this.utterance===s&&(this.utterance=null)},f=()=>{d!==null&&(clearTimeout(d),d=null)},p=()=>{s.onstart=null,s.onend=null,s.onerror=null,s.onpause=null,s.onresume=null,s.onboundary=null},g=(b,w)=>{l||(l=!0,f(),p(),u(),c&&this.settlePendingChunk===c&&(this.settlePendingChunk=null),r===this.speakRunId&&(this._isPlaying=!1,this._isPaused=!1),w?o(w):i(b))},v=b=>Error(b==="ended"?"Browser speech synthesis ended before audio started. The browser speech engine may be unavailable or stuck; try another voice or restart the browser.":`Browser speech synthesis did not start within ${LI/1e3} seconds. The browser speech engine may be unavailable or stuck; try another voice or restart the browser.`);c=()=>g(!1),this.settlePendingChunk=c,s.onstart=()=>{if(r!==this.speakRunId){g(!1);return}a=!0,f(),this._isPlaying=!0,this._isPaused=!1;try{this.onPlaybackStart?.()}catch(b){console.error("Browser TTS playback-start callback failed",b)}},s.onend=()=>{if(r!==this.speakRunId){g(!1);return}if(!a){g(!1,v("ended"));return}g(!0)},s.onerror=b=>{if(r!==this.speakRunId){g(!1);return}if(b.error==="interrupted"||b.error==="canceled"){g(!1);return}g(!1,Error(`Speech synthesis error: ${b.error}`))},s.onpause=()=>{r===this.speakRunId&&(this._isPaused=!0)},s.onresume=()=>{r===this.speakRunId&&(this._isPaused=!1)},s.onboundary=b=>{if(r!==this.speakRunId||(console.log("[BrowserProvider] Boundary event:",b.name,"charIndex:",b.charIndex,"charLength:",b.charLength),b.name!=="word"||!this.onWordBoundary)||this.getHighlightMode()==="sentence")return;let w=Math.max(0,Math.min(b.charIndex,Math.max(0,e.length-1))),I=Number(b.charLength||0),x=this.inferWordLength(e,w),C=Number.isFinite(I)&&I>0&&I<=80&&w+I<=e.length?I:x,L=e.substring(w,Math.min(e.length,w+C)).trim(),E=t+w;console.log("[BrowserProvider] Calling onWordBoundary with word:",L,"at position:",E),this.onWordBoundary(L,E,C)},d=setTimeout(()=>{l||a||r!==this.speakRunId||(g(!1,v("timedOut")),speechSynthesis.cancel())},LI);try{speechSynthesis.speak(s)}catch(b){g(!1,b instanceof Error?b:Error("Browser speech synthesis failed to queue speech"))}})}pause(){this._isPlaying&&!this._isPaused&&speechSynthesis.pause()}resume(){this._isPlaying&&this._isPaused&&speechSynthesis.resume()}stop(){let e=this.utterance,t=this._isPlaying||e!==null;this.speakRunId+=1,this.settlePendingVoiceWait?.(),this.settlePendingChunk?.(),t&&speechSynthesis.cancel(),this.utterance=null,this._isPlaying=!1,this._isPaused=!1}isPlaying(){return this._isPlaying&&!this._isPaused}isPaused(){return this._isPaused}updateSettings(e){this.config||(this.config={}),e.rate!==void 0&&(this.config.rate=e.rate),e.pitch!==void 0&&(this.config.pitch=e.pitch),e.voice!==void 0&&(this.config.voice=e.voice),e.providerOptions!==void 0&&(this.config.providerOptions={...this.config.providerOptions||{},...e.providerOptions||{}})}},nn=e=>e.trim().replace(/\s+/g," "),zW=()=>/[\p{L}]+|\d+(?:\.\d+)?|[±√=+\-*/()²³^×÷≤≥≠≈<>|%°'′\u2062]/gu,p_=e=>{if(e.hidden||e.tagName?.toLowerCase()==="mjx-assistive-mml"||e.getAttribute("aria-hidden")==="true"||e.hasAttribute("inert"))return!0;let t=e.classList;if(t?.contains("sr-only")||t?.contains("pie-sr-only")||t?.contains("visually-hidden"))return!0;if(typeof window<"u"){let r=window.getComputedStyle(e);if(r.display==="none"||r.visibility==="hidden")return!0;let n=Number.parseFloat(r.width||"0"),i=Number.parseFloat(r.height||"0"),o=Number.isFinite(n)&&Number.isFinite(i)&&n<=1&&i<=1,s=r.clipPath.includes("inset(50%")||r.clipPath.includes("inset(100%")||r.clip.includes("rect(0px, 0px, 0px, 0px)")||r.clip.includes("rect(0 0 0 0)");if((r.position==="absolute"||r.position==="fixed")&&o&&(r.overflow==="hidden"||s)||r.opacity==="0"&&o)return!0}return!1},km=(e,t)=>{let r=e.nodeType===1?e:e.parentElement;for(;r;){if(p_(r))return!0;if(t&&r===t)break;r=r.parentElement}return!1},m_=new Set(["computer-read-aloud","all"]),NI=new Set([...m_,"screen-reader"]),DI=new Set,WW=e=>{let t=e.getAttribute?.("data-tts-suppress");if(t==null)return!1;let r=t.trim().toLowerCase();return m_.has(r)?!0:NI.has(r)?!1:(DI.has(r)||(DI.add(r),console.warn(`[tts] data-tts-suppress="${t}" is not one of ${Array.from(NI).join(", ")}; suppressing read-aloud for this content anyway, because a suppression attribute that fails open would leak the answer to items where reading is the construct. Correct the value to silence this.`)),!0)},Ty=(e,t)=>{let r=e.nodeType===1?e:e.parentElement;for(;r;){if(WW(r))return!0;if(t&&r===t)break;r=r.parentElement}return!1},hf=(e,t)=>km(e,t)||Ty(e),jI=(e,t)=>{if(typeof document>"u"||typeof document.createTreeWalker!="function"||typeof NodeFilter>"u"||typeof e.intersectsNode!="function")return{text:e.toString(),filtered:!1};let r=[],n=!1,i=document.createTreeWalker(t,NodeFilter.SHOW_TEXT),o=i.nextNode();for(;o;){let s=o;if(e.intersectsNode(s))if(hf(s,t))n=!0;else{let a=s.textContent||"",l=s===e.startContainer?e.startOffset:0,d=s===e.endContainer?e.endOffset:a.length;r.push(a.slice(l,d))}o=i.nextNode()}return{text:r.join(""),filtered:n}},g_=(e,t,r)=>{if(!e||!t||/\s/.test(e)||/\s/.test(t))return!1;let n=r?.boundarySpacingMode??"segmenterPreferred";if(n==="none")return!1;if(n==="segmenterPreferred")try{let s=globalThis.Intl?.Segmenter;if(typeof s=="function"){let a=new s(r?.locale,{granularity:"word"});if(Array.from(a.segment(`${e}${t}`)).filter(l=>l.isWordLike!==!1&&l.segment.trim().length>0).length>=2)return!0}}catch{}let i=/[A-Za-z0-9]/.test(e),o=/[A-Za-z0-9]/.test(t);return i&&o},lu=(e,t)=>{let r=new Map;if(typeof document>"u"||typeof document.createTreeWalker!="function"||typeof NodeFilter>"u")return{text:"",map:r};let n=[],i=0,o=!0,s=!1,a=null,l=null,d=document.createTreeWalker(e,NodeFilter.SHOW_TEXT),c=d.nextNode();for(;c;){let f=c;if(f.parentElement&&!hf(f,e)){let p=f.textContent||"",g=p.match(/\S/),v=g?g[0]:null;!o&&!s&&g_(l,v,t)&&(n.push(" "),a&&r.set(i,a),i++,s=!0);for(let b=0;b<p.length;b++){let w=p[b],I=/\s/.test(w);o?I||(o=!1,n.push(w),r.set(i,{node:f,offset:b}),a={node:f,offset:b},i++,s=!1,l=w):I?(s||(n.push(" "),r.set(i,{node:f,offset:b}),a={node:f,offset:b},i++),s=!0):(n.push(w),r.set(i,{node:f,offset:b}),a={node:f,offset:b},i++,s=!1,l=w)}}c=d.nextNode()}let u=n.join("").trimEnd();for(;r.has(u.length);)r.delete(u.length);return{text:u,map:r}},UW=new Set(["speak","p","s","emphasis","prosody","say-as","voice","lang"]),BI=new Set(["audio","phoneme"]),v_=e=>e.replace(/&quot;/g,'"').replace(/&apos;/g,"'").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&nbsp;/g," ").replace(/&#160;/g," ").replace(/&amp;/g,"&"),Ah=(e,t,r)=>{for(let n=0;n<t.length;n++)e.push({char:t[n],rawOffset:r===null?null:r+n})},qW=(e,t,r)=>{let n=t.slice(r).match(/^&(quot|apos|lt|gt|nbsp|amp|#160);/i);return n?(Ah(e,v_(n[0]),r),n[0].length):0},FI=e=>{e.push({char:" ",rawOffset:null})},VW=e=>{let t=new Map,r=[],n=!0;for(let i of e){if(/\s/.test(i.char)){!n&&r.length>0&&(r.push(" "),i.rawOffset!==null&&t.set(i.rawOffset,r.length-1)),n=!0;continue}r.push(i.char),i.rawOffset!==null&&t.set(i.rawOffset,r.length-1),n=!1}for(;r.length>0&&r[r.length-1]===" ";)r.pop();for(let[i,o]of t)o>=r.length&&t.delete(i);return{text:r.join(""),rawToSpokenOffsetMap:t}},GW=e=>e.match(/^<\/?\s*([A-Za-z0-9:-]+)/)?.[1]?.toLowerCase()||"",KW=(e,t)=>{let r=new RegExp(`${t}\\s*=\\s*("([^"]*)"|'([^']*)')`,"i"),n=e.match(r);return v_(n?.[2]??n?.[3]??"")||null},XW=e=>{let t=[],r=!1,n=!1,i=0;for(;i<e.length;){let s=e[i];if(s!=="<"){if(s==="&"){let f=qW(t,e,i);if(f>0){i+=f;continue}}Ah(t,s,i),i++;continue}let a=e.indexOf(">",i+1);if(a<0){Ah(t,s,i),i++;continue}n=!0;let l=e.slice(i,a+1),d=GW(l),c=/^<\s*\//.test(l),u=/\/\s*>$/.test(l);if(!c&&d==="sub"){let f=KW(l,"alias");if(!f){r=!0,i=a+1;continue}Ah(t,f,null);let p=e.toLowerCase().indexOf("</sub>",a+1);i=p>=0?p+6:a+1;continue}if(!c&&d==="break"){FI(t),i=a+1;continue}if(!c&&BI.has(d)&&(r=!0,u)){i=a+1;continue}d&&!UW.has(d)&&!BI.has(d)&&d!=="break"&&d!=="sub"&&(r=!0),!c&&(d==="p"||d==="s")&&FI(t),i=a+1}let o=VW(t);return{spokenText:nn(o.text),rawToSpokenOffsetMap:o.rawToSpokenOffsetMap,unsupportedSemantic:r,hasMarkup:n}},ZW=zW(),YW=new Map([["zero","0"],["one","1"],["two","2"],["three","3"],["four","4"],["five","5"],["six","6"],["seven","7"],["eight","8"],["nine","9"],["ten","10"]]),JW=e=>{let t=e.toLowerCase();return YW.get(t)||t},y_=e=>{let t=[];for(let r of e.matchAll(ZW)){let n=r[0],i=r.index??0;t.push({text:n,normalized:JW(n),start:i,end:i+n.length})}return t},QW=e=>y_(e).map((t,r)=>({...t,id:`speech-token-${r}`,sourceStart:t.start,sourceEnd:t.end,coordinateSystem:"normalized-speech"})),Tm=e=>{let t=XW(e.speechText);return{speechText:e.speechText,spokenText:t.spokenText,tokens:QW(t.spokenText),rawToSpokenOffsetMap:t.rawToSpokenOffsetMap,boundaryOffsetSpace:t.unsupportedSemantic?"unsupported":t.hasMarkup?"raw-ssml":"plain-spoken-text",unsupportedSemantic:t.unsupportedSemantic,hasMarkup:t.hasMarkup}},ww=e=>!!(e&&/^<[^>]+>$/.test(e.trim())),Em=e=>!e||ww(e)?null:Tm({speechText:e}).tokens[0]?.normalized??null,e6=(e,t)=>e.find(r=>r.start<=t&&t<r.end)||null,t6=(e,t)=>{let r=e.rawToSpokenOffsetMap.get(t);if(r!==void 0)return r;for(let n=t;n<e.speechText.length;n++){let i=e.rawToSpokenOffsetMap.get(n);if(i!==void 0)return i;if(e.speechText[n]===">")break}return null},Ey=(e,t,r)=>{if(t===null)return null;let n=e6(e.tokens,t);return n?{token:n,start:t,length:Math.max(1,Math.min(r,n.end-t)),confidence:.75}:null},Cy=(e,t)=>!!(e&&t&&e.token.normalized===t),r6=e=>{if(e.tokenization.boundaryOffsetSpace==="unsupported"||!Number.isFinite(e.position)||ww(e.boundaryWord))return null;let t=Math.max(1,Number.isFinite(e.length)?e.length:1),r=Em(e.boundaryWord),n=Ey(e.tokenization,t6(e.tokenization,e.position),t),i=Ey(e.tokenization,e.position>=0&&e.position<e.tokenization.spokenText.length?e.position:null,t);return Cy(n,r)?{...n,confidence:1}:Cy(i,r)?{...i,confidence:1}:r?null:e.tokenization.boundaryOffsetSpace==="raw-ssml"?n||i:i||n},n6=e=>{if(e.tokenization.boundaryOffsetSpace==="unsupported"||!Number.isFinite(e.position)||ww(e.boundaryWord))return null;let t=Math.max(1,Number.isFinite(e.length)?e.length:1),r=Em(e.boundaryWord),n=Ey(e.tokenization,e.position>=0&&e.position<e.tokenization.spokenText.length?e.position:null,t);return Cy(n,r)?{...n,confidence:1}:r?null:n},i6=[{phrase:["plus","or","minus"],visible:"±",score:8},{phrase:["square","root"],visible:"√",score:8},{phrase:["divided","by"],visible:"/",score:7},{phrase:["all","over"],visible:"/",score:7},{phrase:["equals"],visible:"=",score:7},{phrase:["equal"],visible:"=",score:7},{phrase:["times"],visible:"⁢",score:7},{phrase:["multiplied","by"],visible:"⁢",score:7},{phrase:["over"],visible:"/",score:6},{phrase:["squared"],visible:"²",score:6},{phrase:["squared"],visible:"2",score:4},{phrase:["negative"],visible:"-",score:5},{phrase:["minus"],visible:"-",score:5},{phrase:["plus"],visible:"+",score:5}],o6=(e,t)=>{let r=[];for(let n=0;n<e.length;n++){for(let i=0;i<t.length;i++)e[n].normalized===t[i].normalized&&r.push({spokenStartToken:n,spokenEndToken:n+1,visibleToken:i,score:10});for(let i of i6){let o=e.slice(n,n+i.phrase.length);if(o.length===i.phrase.length&&o.every((s,a)=>s.normalized===i.phrase[a]))for(let s=0;s<t.length;s++)t[s].text===i.visible&&r.push({spokenStartToken:n,spokenEndToken:n+i.phrase.length,visibleToken:s,score:i.score})}}return r},s6=(e,t)=>{let r=o6(e,t).sort((l,d)=>e[l.spokenStartToken].start-e[d.spokenStartToken].start||t[l.visibleToken].start-t[d.visibleToken].start),n=Array(r.length).fill(0),i=Array(r.length).fill(-1);for(let l=0;l<r.length;l++){let d=r[l];n[l]=d.score;for(let c=0;c<l;c++){let u=r[c];if(u.spokenEndToken<=d.spokenStartToken&&u.visibleToken<d.visibleToken){let f=d.spokenStartToken-u.spokenEndToken,p=d.visibleToken-u.visibleToken-1,g=Math.max(0,Math.abs(f-p)-2),v=n[c]+d.score-g;v>n[l]&&(n[l]=v,i[l]=c)}}}let o=-1;for(let l=0;l<n.length;l++)(o<0||n[l]>n[o])&&(o=l);if(o<0)return[];let s=[],a=o;for(;a>=0;)s.unshift(r[a]),a=i[a];return s.map(l=>{let d=e[l.spokenStartToken],c=e[l.spokenEndToken-1],u=t[l.visibleToken];return{spokenStart:d.start,spokenEnd:c.end,visibleStart:u.start,visibleEnd:u.end,score:l.score}})},a6=(e,t,r)=>{if(e.length===0)return 0;let n=e.length/Math.max(1,Math.min(t.length,r.length)),i=e.reduce((o,s)=>o+s.score,0)/e.length/10;return Math.min(1,n*i)},b_=e=>{let t=Tm({speechText:e.speechText}),r=nn(e.visibleText),n=t.tokens,i=y_(r),o=t.unsupportedSemantic?[]:s6(n,i),s=a6(o,n,i),a=t.spokenText===r&&t.spokenText.length>0,l=o.length===1&&o[0].score===10&&n.length<=2&&i.length<=2;return{speech:t,visibleText:r,playbackMode:t.unsupportedSemantic?"region-fallback":a?"exact-word":(o.length>=2||l)&&s>=.12?"anchor-span":"region-fallback",anchors:o,confidence:s}},l6=(e,t)=>{if(e.playbackMode==="region-fallback")return null;let r=e.anchors.find(o=>o.spokenStart<=t&&t<o.spokenEnd);if(r)return{start:r.visibleStart,end:r.visibleEnd};let n=null,i=null;for(let o of e.anchors){if(o.spokenEnd<=t){n=o;continue}if(o.spokenStart>t){i=o;break}}return n&&i?{start:Math.min(n.visibleStart,i.visibleStart),end:Math.max(n.visibleEnd,i.visibleEnd)}:null},c6=new Map([["+",["plus"]],["-",["minus","negative"]],["−",["minus","negative"]],["×",["times","multiplied by"]],["÷",["divided by"]],["=",["equals","equal to"]],["≠",["is not equal to","not equal to"]],["≈",["approximately equals"]],["≤",["less than or equal to"]],["≥",["greater than or equal to"]],["<",["less than"]],[">",["greater than"]],["∠",["angle"]],["△",["triangle"]],["□",["box"]],["○",["circle"]],["°",["degrees","degree"]],["%",["percent"]],["'",["prime"]],["′",["prime"]],["•",["times"]],["·",["times"]],["⁢",["times","multiplied by"]]]),d6=new Map([["⁡","function-application"],["⁢","implicit-multiply"],["⁣","invisible-separator"],["⁤","invisible-plus"]]),w_=new Map([["2",["squared"]],["3",["cubed"]]]),u6=new Map([["msqrt","radical"],["mroot","radical"],["msub","subscript"],["msubsup","subsupscript"],["munder","underscript"],["mover","overscript"],["munderover","underoverscript"],["mmultiscripts","multiscript"],["menclose","enclosure"]]),f6=e=>e.replace(/\s+/g," ").trim(),Ml=e=>(e.localName||e.tagName||"").toLowerCase(),h6=e=>e.nodeType===Node.ELEMENT_NODE,sd=e=>Array.from(e.childNodes).filter(h6),Sw=e=>f6(e.textContent||""),Ks=(e,t)=>({type:"element-range",quality:t,element:e}),p6=e=>{switch(e){case"mi":return"identifier";case"mn":return"number";case"mo":return"operator";case"mtext":case"ms":return"text";case"mspace":return"space";default:return"unknown"}},m6=(e,t)=>t==="operator"?e==="−"?"-":e:e.toLowerCase(),g6=(e,t,r)=>r==="fraction"?["over","divided by"]:r==="superscript"?w_.get(e)??[]:e==="|"?["absolute value"]:t==="operator"?c6.get(e)||[]:[],Kl=e=>{let t=e.normalized??m6(e.text,e.kind||"unknown");return{id:`math-token-${e.state.nextId++}`,kind:e.kind,role:e.role,text:e.text,normalized:t,spokenAliases:g6(e.text,e.kind,e.role),sourceElement:e.sourceElement,path:e.path,target:e.target||Ks(e.sourceElement,"element-range"),optional:e.optional}},Xl=(e,t,r="tokens")=>{e[r].push(t)},S_=(e,t,r)=>{sd(e).forEach((n,i)=>Xs(n,t,`${r}/${Ml(n)}[${i}]`))},v6=(e,t,r)=>{let n=sd(e);n[0]&&Xs(n[0],t,`${r}/numerator`),Xl(t,Kl({state:t,kind:"structure",role:"fraction",text:"/",sourceElement:e,path:r,target:Ks(e,"element-range")})),n[1]&&Xs(n[1],t,`${r}/denominator`)},y6=(e,t,r)=>{let n=e.getAttribute("open")||"(",i=e.getAttribute("close")||")";Xl(t,Kl({state:t,kind:"operator",role:n==="|"?"absolute-value-fence":"open-fence",text:n,sourceElement:e,path:`${r}/open`,target:Ks(e,"element-range")})),S_(e,t,r),Xl(t,Kl({state:t,kind:"operator",role:i==="|"?"absolute-value-fence":"close-fence",text:i,sourceElement:e,path:`${r}/close`,target:Ks(e,"element-range")}))},b6=(e,t,r)=>{let n=sd(e);n[0]&&Xs(n[0],t,`${r}/base`);let i=n[1];if(!i)return;let o=Sw(i);if(w_.has(o)){Xl(t,Kl({state:t,kind:"structure",role:"superscript",text:o,normalized:o,sourceElement:i,path:`${r}/exponent`,target:Ks(e,"element-range")}));return}Xs(i,t,`${r}/exponent`)},w6=(e,t,r,n)=>{Xl(t,Kl({state:t,kind:"structure",role:n,text:Sw(e)||n,normalized:`\0${n}`,sourceElement:e,path:r,target:Ks(e,"element-range")}))},S6=(e,t,r)=>{let n=0;for(let i of sd(e))(Ml(i)==="mtr"||Ml(i)==="mlabeledtr")&&(n++,Xl(t,Kl({state:t,kind:"layout",role:"table-row",text:`row-${n}`,normalized:`row-${n}`,sourceElement:i,path:`${r}/row[${n}]`,target:Ks(i,"region-fallback")}),"layoutTargets")),Xs(i,t,`${r}/${Ml(i)}[${n}]`)},I6=(e,t,r)=>{let n=Sw(e);if(!n)return;let i=p6(Ml(e)),o=i==="operator"?d6.get(n):void 0,s=o??(i==="operator"&&(n==="("||n===")")?"grouping-fence":i);Xl(t,Kl({state:t,kind:i,role:s,text:n,sourceElement:e,path:r,target:o&&e.parentElement?Ks(e.parentElement,"region-fallback"):void 0,optional:!!o||s==="grouping-fence"}))},Xs=(e,t,r)=>{let n=Ml(e);switch(n){case"annotation":case"annotation-xml":return;case"semantics":{let i=sd(e).find(o=>{let s=Ml(o);return s!=="annotation"&&s!=="annotation-xml"});i&&Xs(i,t,`${r}/presentation`);return}case"mi":case"mn":case"mo":case"mtext":case"ms":case"mspace":I6(e,t,r);return;case"mfrac":v6(e,t,r);return;case"msup":b6(e,t,r);return;case"mfenced":y6(e,t,r);return;case"mtable":S6(e,t,r);return;case"mphantom":return;case"maction":{let i=sd(e)[0];i&&Xs(i,t,`${r}/action`);return}default:{let i=u6.get(n);if(i){w6(e,t,r,i);return}S_(e,t,r)}}},k6=e=>{let t={tokens:[],layoutTargets:[],nextId:0};return Xs(e,t,"/math"),{tokens:t.tokens,layoutTargets:t.layoutTargets,expressionTarget:Ks(e,"region-fallback")}},T6=e=>e.boundary&&e.alignment.segments.find(t=>t.speechTokenIds.includes(e.boundary.token.id))?.target||null,E6=e=>{let t=[],r=new Set,n=i=>{let o=i.toLowerCase().trim().split(/\s+/).filter(Boolean);if(o.length===0)return;let s=o.join(" ");r.has(s)||(r.add(s),t.push(o))};n(e.normalized);for(let i of e.spokenAliases)n(i);return t},HI=(e,t,r)=>{let n=0;for(let i of r){if(i.length<=n)continue;let o=!0;for(let s=0;s<i.length;s++){let a=e[t+s];if(!a||a.normalized.toLowerCase()!==i[s]){o=!1;break}}o&&(n=i.length)}return n},C6=(e,t)=>{let r=[],n=0;for(let i of t){let o=E6(i);if(i.optional){let s=HI(e,n,o);s>0&&(r.push({speechTokens:e.slice(n,n+s),math:i}),n+=s);continue}for(;n<e.length;){let s=HI(e,n,o);if(s>0){r.push({speechTokens:e.slice(n,n+s),math:i}),n+=s;break}n++}}return r},x6=(e,t,r)=>{let n=r.filter(s=>!s.optional).length,i=e.filter(s=>!s.math.optional).length,o=e.reduce((s,a)=>s+a.speechTokens.length,0);return n>0&&i===n&&o===t.length},R6=e=>e.map(({speechTokens:t,math:r})=>({speechTokenIds:t.map(n=>n.id),mathTokenIds:[r.id],score:1,confidence:1,target:r.target})),_6=e=>{let t=e.minExactWordConfidence??.95,r=C6(e.speech.tokens,e.math.tokens),n=x6(r,e.speech.tokens,e.math.tokens)?1:0;return{segments:n>=t?R6(r):[],confidence:n,fallbackTarget:e.math.expressionTarget}},Np=e=>{let t=Tm({speechText:e.speechText}),r=k6(e.mathElement);return{speech:t,math:r,result:_6({speech:t,math:r})}},P6=(e,t)=>{let r=n6({tokenization:e.speech,position:t.position,length:t.length,boundaryWord:t.boundaryWord});return T6({alignment:e.result,boundary:r})},A6=(e,t)=>{let r=Em(t.boundaryWord);if(!r)return null;let n=e.math.tokens.filter(i=>i.normalized.toLowerCase()===r||i.spokenAliases.some(o=>o.toLowerCase()===r));return n.length===1?n[0].target:null},M6=new Set(["math","maction","menclose","merror","mfenced","mfrac","mi","mmultiscripts","mn","mo","mover","mpadded","mphantom","mprescripts","mroot","mrow","ms","mspace","msqrt","mstyle","msub","msubsup","msup","mtable","mtd","mtext","mtr","munder","munderover","none","semantics","annotation","annotation-xml"]),$6=new Set(["accent","accentunder","align","bevelled","class","close","columnalign","columnlines","columnspacing","columnspan","denomalign","depth","dir","display","encoding","fence","height","href","id","largeop","length","linethickness","lspace","mathbackground","mathcolor","mathsize","mathvariant","maxsize","minsize","movablelimits","notation","numalign","open","rowalign","rowlines","rowspacing","rowspan","rspace","scriptlevel","scriptminsize","scriptsizemultiplier","selection","separator","separators","stretchy","subscriptshift","supscriptshift","symmetric","width","xmlns","xml:lang"]),I_=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),L6=e=>I_(e).replace(/"/g,"&quot;"),O6=(e,t)=>{let r=e.toLowerCase(),n=t.trim().toLowerCase();return!!(r.startsWith("on")||!$6.has(r)||n.includes("javascript:")||n.includes("data:text/html"))},N6=e=>{let t=e.localName.toLowerCase();if(!M6.has(t))return!1;let r=e.namespaceURI;return!r||r==="http://www.w3.org/1998/Math/MathML"||r==="http://www.w3.org/1999/xhtml"},k_=e=>{if(e.nodeType===Node.TEXT_NODE)return I_(e.textContent||"");if(e.nodeType===Node.COMMENT_NODE)return"";if(e.nodeType!==Node.ELEMENT_NODE)return null;let t=e;if(!N6(t))return null;let r=t.localName.toLowerCase(),n=[];for(let o of Array.from(t.attributes)){let s=o.name.toLowerCase();if(!O6(s,o.value)){if(s==="xmlns"&&o.value!=="http://www.w3.org/1998/Math/MathML")return null;n.push(`${s}="${L6(o.value)}"`)}}r==="math"&&!n.some(o=>o.startsWith("xmlns="))&&n.unshift('xmlns="http://www.w3.org/1998/Math/MathML"');let i=[];for(let o of Array.from(t.childNodes)){let s=k_(o);if(s===null)return null;i.push(s)}return`<${r}${n.length>0?` ${n.join(" ")}`:""}>${i.join("")}</${r}>`},D6=e=>typeof DOMParser<"u"?new DOMParser().parseFromString(e,"application/xml"):null,Dg=e=>{let t=String(e||"").trim();if(!t)return null;let r=D6(t);if(!r||r.getElementsByTagName("parsererror").length>0)return null;let n=r.documentElement;return!n||n.localName.toLowerCase()!=="math"?null:k_(n)},T_=e=>({chars:[],map:new Map,position:0,inLeadingWhitespace:!0,lastCharWasWhitespace:!1,lastMapped:null,options:e}),Iw=e=>e.classList?.contains("MathJax")||e.tagName?.toLowerCase()==="mjx-container",E_=e=>e.tagName?.toLowerCase()==="mjx-assistive-mml",kw=e=>{let t=e.tagName?.toLowerCase();return t==="annotation"||t==="annotation-xml"},j6=e=>{let t=e.getAttribute("data-mathml");return t&&t.trim()?t:null},B6=e=>e.querySelector("mjx-assistive-mml math")?.outerHTML||null,F6=e=>{if(e.tagName.toLowerCase()==="math")return Dg(e.outerHTML);let t=j6(e);if(t){let r=Dg(t);if(r)return r}if(Iw(e)){let r=B6(e);if(r){let n=Dg(r);if(n)return n}}return null},H6=new Set(["P","H1","H2","H3","H4","H5","H6","LI","TD","TH","DD","DT","FIGCAPTION","LABEL","BUTTON"]),z6=new Set(["heading","listitem","option","radio","row","cell","columnheader","rowheader"]),W6=(e,t)=>{let r=e.parentElement,n=null;for(;r&&r!==t;){let i=(r.getAttribute("role")||"").toLowerCase(),o=r.tagName.toUpperCase();if(H6.has(o)||z6.has(i)){n=r;break}r=r.parentElement}return n||t},U6=e=>!!(typeof e.querySelector=="function"&&e.querySelector("math, [data-mathml], .MathJax, mjx-container, mjx-assistive-mml"))||e.tagName?.toLowerCase()==="math"||e.hasAttribute?.("data-mathml")||Iw(e),ml=(e,t,r)=>{/[.,;:!?]/.test(t)&&e.chars.length>0&&e.chars[e.chars.length-1]===" "&&(e.chars.pop(),e.position--,e.map.delete(e.position)),e.chars.push(t),r?(e.map.set(e.position,r),e.lastMapped=r):e.lastMapped&&e.map.set(e.position,e.lastMapped),e.position++},C_=(e,t)=>{if(e.inLeadingWhitespace||e.lastCharWasWhitespace||e.chars.length===0)return!1;let r=e.chars[e.chars.length-1];return g_(r,t,e.options)},x_=(e,t)=>{let r=t.textContent||"",n=!1;for(let i=0;i<r.length;i++){let o=r[i],s=/\s/.test(o);if(e.inLeadingWhitespace){s||(e.inLeadingWhitespace=!1,ml(e,o,{node:t,offset:i}),n=!0,e.lastCharWasWhitespace=!1);continue}if(s){e.lastCharWasWhitespace||ml(e," ",{node:t,offset:i}),e.lastCharWasWhitespace=!0;continue}!n&&C_(e,o)&&ml(e," ",{node:t,offset:i}),ml(e,o,{node:t,offset:i}),n=!0,e.lastCharWasWhitespace=!1}},q6=(e,t)=>{for(let r=0;r<t.text.length;r++){let n=t.text[r],i=/\s/.test(n),o=t.map.get(r)||null,s=o?.node||e.lastMapped?.node||null,a=o?.offset??e.lastMapped?.offset??0,l=o?{node:o.node,offset:o.offset}:s?{node:s,offset:a}:null;if(e.inLeadingWhitespace){if(i)continue;e.inLeadingWhitespace=!1}if(i){e.lastCharWasWhitespace||ml(e," ",l),e.lastCharWasWhitespace=!0;continue}r===0&&C_(e,n)&&ml(e," ",l),ml(e,n,l),e.lastCharWasWhitespace=!1,o?(e.map.set(e.position-1,{node:o.node,offset:o.offset}),e.lastMapped={node:o.node,offset:o.offset}):s&&e.map.set(e.position-1,{node:s,offset:a})}},V6=e=>{if(typeof DOMParser>"u")return"";let t=new DOMParser().parseFromString(e,"application/xml");if(t.getElementsByTagName("parsererror").length>0)return"";let r=[],n=i=>{if(i.nodeType===3){let s=i.textContent||"";s.trim()&&r.push(s);return}if(i.nodeType!==1)return;let o=i;if(!kw(o))for(let s of Array.from(o.childNodes))n(s)};return n(t.documentElement),nn(r.join(" "))},G6=(e,t)=>{let r=new Map,n=Iw(e)?e.querySelector("mjx-assistive-mml math"):null;if(!n)return r;let i=[],o=a=>{if(a.nodeType===3){let l=a.textContent||"";for(let d=0;d<l.length;d++)/\s/.test(l[d])||i.push({node:a,offset:d});return}if(!(a.nodeType!==1||kw(a)))for(let l of Array.from(a.childNodes))o(l)};o(n);let s=0;for(let a=0;a<t.length;a++){if(/\s/.test(t[a]))continue;let l=i[s];if(l?.node.textContent?.[l.offset]!==t[a])return new Map;r.set(a,l),s++}return s===i.length?r:new Map},K6=(e,t,r)=>{let n=T_(r),i=a=>{if(hf(a,e))return;if(a.nodeType===3){x_(n,a);return}if(a.nodeType!==1)return;let l=a;if(!(E_(l)||kw(l)))for(let d of Array.from(l.childNodes))i(d)};i(e),R_(n);let o=nn(n.chars.join(""));if(o)return{text:o,map:n.map};let s=V6(t);return s?{text:s,map:G6(e,s)}:lu(e,r)},R_=e=>{for(;e.chars.length>0&&/\s/.test(e.chars[e.chars.length-1]);)e.chars.pop(),e.position--,e.map.delete(e.position)},X6=(e,t)=>{let r=T_(t),n=[],i=0,o,s=!1,a=()=>{let c=nn(r.chars.slice(i,r.chars.length).join(""));c&&n.push({type:"text",text:c,sourceElement:o}),i=r.chars.length,o=void 0},l=c=>{if(hf(c,e))return;if(c.nodeType===Node.TEXT_NODE){let p=W6(c,e);o&&p!==o&&a(),o=p,x_(r,c);return}if(c.nodeType!==Node.ELEMENT_NODE)return;let u=c;if(E_(u))return;let f=F6(u);if(f){a();let p=K6(u,f,t);q6(r,p);let g=nn(p.text);n.push({type:"math",mathml:f,fallbackText:g,sourceElement:u}),i=r.chars.length,s=!0;return}for(let p of Array.from(u.childNodes))l(p)};for(let c of Array.from(e.childNodes))l(c);R_(r),a();let d=r.chars.join("");for(;r.map.has(d.length);)r.map.delete(d.length);return{visibleText:d,map:r.map,chunks:n,containsMathMarkup:s}},Zd=(e,t)=>{if(!U6(e)){let{text:r,map:n}=lu(e,t);return{visibleText:r,map:n,chunks:r?[{type:"text",text:r}]:[],containsMathMarkup:!1}}return X6(e,t)},jg=null,zI=Promise.resolve(),Z6=e=>(e||"en").split("-")[0].toLowerCase()||"en",Y6=async e=>(jg||(mP(e),jg=br(async()=>{const{default:t}=await import("./chunks/sre-engine-wf9s43gg-f09289c5.js");return{default:t}},[],import.meta.url).then(({default:t})=>{if(!t||typeof t.toSpeech!="function")throw Error("speech-rule-engine did not expose toSpeech");return t})),jg),J6=e=>e==="en"?"clearspeak":"mathspeak",WI=e=>!!e&&typeof e=="object"&&!Array.isArray(e),UI=e=>typeof e=="string"&&e.trim()?e.trim():void 0,pf=e=>{if(!WI(e))return;let t=UI(e.domain),r=UI(e.style),n=WI(e.engineOptions)?e.engineOptions:void 0;if(!(!t&&!r&&!n))return{...t?{domain:t}:{},...r?{style:r}:{},...n?{engineOptions:n}:{}}},Q6=async(e,t,r,n)=>{let i=Z6(t),o=pf(n),s=o?.engineOptions||{};await e.setupEngine?.({...pP(s),...s,locale:i,domain:o?.domain||J6(i),...o?.style?{style:o.style}:{},modality:"speech",markup:r}),await e.engineReady?.()},eU=async e=>{let t=zI.then(e,e);return zI=t.then(()=>{},()=>{}),t},__=async(e,t,r,n,i)=>eU(async()=>(await Q6(e,r,n,i),e.toSpeech(t))),tU=e=>e.replace(/^\s*<\?xml[^>]*\?>\s*/i,""),rU=async(e,t,r,n)=>{try{let i=tU(await __(e,t,r,"ssml",n));return i.includes("<speak")?i:null}catch(i){return console.debug("[TTSService] Math SSML generation failed; using plain",{message:i instanceof Error?i.message:String(i)}),null}},P_=async(e,t={})=>{if(!e.some(d=>d.type==="math"))return{speechText:nn(e.map(d=>d.type==="text"?d.text:d.fallbackText).join(" ")),usedMathSpeech:!1,usedFallback:!1};let r=null,n=!1,i=!1,o=t.loadSre||(()=>Y6(pf(t.mathSpeech)?.engineOptions)),s=[];for(let d of e){if(d.type==="text"){s.push(d.text);continue}try{r||(r=await o());let c=nn(await __(r,d.mathml,t.language,"none",t.mathSpeech));if(c){s.push(c),n=!0;continue}i=!0,s.push(d.fallbackText)}catch(c){i=!0,console.debug("[TTSService] Math speech generation failed; using visible fallback",{message:c instanceof Error?c.message:String(c)}),s.push(d.fallbackText)}}let a=nn(s.join(" ")),l;return t.produceSsml&&r&&n&&e.length===1&&e[0].type==="math"&&(l=await rU(r,e[0].mathml,t.language,t.mathSpeech)??void 0),{speechText:a,usedMathSpeech:n,usedFallback:i,ssml:l}},nU=e=>(e||"en").split("-")[0].toLowerCase()||"en",iU="sre-v1",oU=256,xy=e=>Array.isArray(e)?`array:[${e.map(xy).join(",")}]`:e&&typeof e=="object"?`object:{${Object.entries(e).sort(([t],[r])=>t.localeCompare(r)).map(([t,r])=>`${JSON.stringify(t)}:${xy(r)}`).join(",")}}`:e===null?"null:null":typeof e>"u"?"undefined:":typeof e=="function"?`function:${e.name||"anonymous"}`:typeof e=="symbol"?`symbol:${String(e)}`:typeof e=="bigint"?`bigint:${e.toString()}`:typeof e=="number"?Number.isFinite(e)?`number:${e}`:`number:${String(e)}`:`${typeof e}:${JSON.stringify(e)}`,qI=(e,t,r,n)=>`${iU}\0${nU(e)}\0${t?"ssml":"plain"}\0${xy(r??null)}\0${n}`,sU=(e={})=>{let t=Math.max(1,e.maxEntries??oU),r=e.resolve??((o,s)=>P_([o],s)),n=new Map,i=(o,s)=>{for(n.delete(o),n.set(o,s);n.size>t;){let a=n.keys().next().value;a!==void 0&&n.delete(a)}};return async(o,s)=>{let a=pf(s.mathSpeech),l=s.produceSsml===!0,d=qI(s.language,l,a,o.mathml),c=n.get(d);if(c)return n.delete(d),n.set(d,c),c;let u=await r(o,{...s,mathSpeech:a});return l&&u.ssml&&t>1&&i(qI(s.language,!1,a,o.mathml),{speechText:u.speechText,usedMathSpeech:u.usedMathSpeech,usedFallback:u.usedFallback}),i(d,u),u}},aU=(e,t)=>{let r=Em(t.word);if(e.id!==t.chunkId)return{chunkId:t.chunkId,normalizedWord:r,chunkSpokenStart:null,chunkSpokenEnd:null,confidence:0,reason:"boundary chunk id did not match highlight chunk"};if(t.providerOffsetSpace==="unknown"||e.offsetSpace==="unsupported")return{chunkId:e.id,normalizedWord:r,chunkSpokenStart:null,chunkSpokenEnd:null,confidence:0,reason:"boundary offset space is unsupported"};let n=r6({tokenization:e.catalogAlignment?.speech??Tm({speechText:e.speechText}),position:t.position,length:t.length,boundaryWord:t.word});return n?{chunkId:e.id,normalizedWord:r,chunkSpokenStart:n.start,chunkSpokenEnd:n.start+n.length,confidence:n.confidence,reason:e.catalogAlignment?"resolved through catalog alignment":"resolved through speech tokenization"}:{chunkId:e.id,normalizedWord:r,chunkSpokenStart:null,chunkSpokenEnd:null,confidence:0,reason:"could not resolve provider boundary to chunk speech"}},gc=e=>e.semanticTarget?{activeTarget:e.semanticTarget,regionTarget:e.regionTarget,quality:e.semanticTarget.quality==="exact-word"?"exact-word":e.semanticTarget.quality==="expression"?"expression":"semantic-token",confidence:e.confidence,reason:e.reason}:e.expressionTarget?{activeTarget:e.expressionTarget,regionTarget:e.regionTarget,quality:"expression",confidence:e.confidence,reason:e.reason}:{activeTarget:null,regionTarget:e.regionTarget,quality:"region",confidence:e.confidence,reason:e.reason},A_=new Map([["mi","mjx-mi"],["mn","mjx-mn"],["mo","mjx-mo"],["mtext","mjx-mtext"]]),Ry="mi,mn,mo,mtext",M_="mjx-mi,mjx-mn,mjx-mo,mjx-mtext",$_=["mjx-mfrac","mjx-msqrt","mjx-mroot","mjx-mtable","mjx-munder","mjx-mover","mjx-munderover"].join(","),L_=e=>e.type==="text-range"?e.node.parentElement:e.element,Cm=e=>{let t=e;for(;t;){if(t.localName?.toLowerCase()==="mjx-container")return t;t=t.parentElement}return null},VI=e=>!e||Cm(e)?!1:!km(e),O_=e=>{let t=e.getBoundingClientRect?.();return!!(t&&t.width>0&&t.height>0)},_y=e=>{let t=e;for(;t;){if(t.localName?.toLowerCase()==="math")return t;t=t.parentElement}return null},N_=(e,t)=>{if(e.length===0||e.length!==t.length)return!1;for(let r=0;r<e.length;r+=1){let n=A_.get(e[r].localName.toLowerCase());if(!n||t[r].localName.toLowerCase()!==n)return!1}return!0},lU=(e,t)=>{if(!e||!A_.has(e.localName.toLowerCase())||t.querySelector($_))return null;let r=_y(e),n=t.querySelector("mjx-math");if(!r||!n)return null;let i=Array.from(r.querySelectorAll(Ry)),o=i.indexOf(e);if(o<0)return null;let s=Array.from(n.querySelectorAll(M_));if(!N_(i,s))return null;let a=s[o];return!a||!O_(a)?null:a},cU=e=>{let t=Cm(e);if(t){if(t.querySelector($_))return"expression";let n=_y(e)??e,i=t.querySelector("mjx-math");if(!i)return"expression";let o=Array.from(n.querySelectorAll(Ry)),s=Array.from(i.querySelectorAll(M_));return N_(o,s)&&s.some(a=>O_(a))?"token":"expression"}let r=_y(e)??e;return Array.from(r.querySelectorAll(Ry)).some(n=>!km(n))?"token":"expression"},Py=e=>{let t=L_(e),r=Cm(t);if(r){let n=lU(t,r);return n?{type:"element",quality:"semantic-token",element:n}:{type:"element",quality:"expression",element:r}}return e.type==="text-range"?VI(e.node.parentElement)?{type:"text-range",quality:"semantic-token",node:e.node,startOffset:e.startOffset,endOffset:e.endOffset}:null:VI(e.element)?{type:"element",quality:e.quality==="region-fallback"?"expression":"semantic-token",element:e.element}:null},dU=Py,uU=()=>{let e=new WeakMap;return t=>{let r=L_(t),n=Cm(r);if(!r||!n)return Py(t);if(e.has(r))return e.get(r)??null;let i=Py(t);return e.set(r,i),i}},fU=(e,t,r,n=e.mathAlignments,i=dU)=>{if(t.chunkSpokenStart===null||t.chunkSpokenEnd===null)return null;let o=null;for(let s of n){let a=P6(s.alignment,{position:t.chunkSpokenStart,length:Math.max(1,t.chunkSpokenEnd-t.chunkSpokenStart),boundaryWord:r.word})||A6(s.alignment,{boundaryWord:r.word});if(!a)continue;let l=i(a);if(l){if(l.quality==="semantic-token")return l;o??(o=l)}}return o},D_=(e,t,r)=>{if(!e||typeof document>"u"||r<=t)return null;let n=e.get(t),i=e.get(Math.max(t,r-1));if(!n)return null;i||(i=n);try{let o=document.createRange();return o.setStart(n.node,n.offset),o.setEnd(i.node,i.offset+1),o}catch{return null}},hU=(e,t)=>{if(!e.catalogAlignment||t.chunkSpokenStart===null)return null;let r=l6(e.catalogAlignment,t.chunkSpokenStart);if(!r)return null;let n=D_(e.visibleMap,r.start,r.end);return n?{type:"range",quality:e.catalogAlignment.playbackMode==="exact-word"?"exact-word":"semantic-token",range:n}:null},pU=e=>e.regionRange?{type:"range",quality:"region",range:e.regionRange}:e.regionElement?{type:"element",quality:"region",element:e.regionElement}:null,GI=(e,t=e.chunk.mathAlignments)=>{if(t.length!==1)return null;let r=t[0]?.alignment.result.fallbackTarget;return r?e.renderedMathTargetResolver(r):null},mU=(e,t)=>e?t.mathAlignments.filter(({element:r})=>{try{return e.type==="range"?e.range.intersectsNode(r):e.type==="element"?e.element===r||e.element.contains(r):e.node.parentElement?.contains(r)||!1}catch{return!1}}):t.mathAlignments,KI=()=>({activeTarget:null,regionTarget:null,quality:"region",confidence:0,reason:"boundary chunk id was not found"}),XI=e=>e.length===1?e[0].element:null,gU=(e,t)=>t.length>0&&t.every(({element:r})=>e.mathCapabilityByElement.get(r)==="token"),j_=3,vU=(e,t,r)=>{if(!t||t.type!=="range")return!1;let{startContainer:n,endContainer:i}=t.range;return n===i&&n.nodeType===j_?!1:r.some(({element:o})=>e.mathCapabilityByElement.get(o)==="token"&&o.contains(n)&&o.contains(i))},B_=e=>e?.type==="range"&&km(e.range.startContainer),yU=(e,t)=>{if(!B_(t))return null;let{startContainer:r,endContainer:n,startOffset:i,endOffset:o}=t.range;return r!==n||r.nodeType!==j_?null:e.renderedMathTargetResolver({type:"text-range",quality:"exact-word",node:r,startOffset:i,endOffset:o})},bU=(e,t)=>({chunk:e,regionTarget:pU(e),renderedMathTargetResolver:uU(),mathCapabilityByElement:new Map(e.mathAlignments.map(({element:r})=>[r,t?cU(r):"expression"])),heldTokenByElement:new Map}),wU=e=>{let t=e.mathTokenHighlighting!==!1,r=new Map(e.chunks.map(n=>[n.id,bU(n,t)]));return{chunks:e.chunks,resolveInitial(n){let i=r.get(n);if(!i)return KI();let o=i.chunk.mathAlignments,s=o.length===1?o[0].element:null,a=s?i.mathCapabilityByElement.get(s):null;return gc(a==="expression"?{semanticTarget:null,expressionTarget:GI(i),regionTarget:i.regionTarget,confidence:.5,reason:"initial expression (sticky expression mode)"}:{semanticTarget:null,expressionTarget:null,regionTarget:i.regionTarget,confidence:0,reason:a==="token"?"initial region (sticky token mode, awaiting first token)":"initial region fallback"})},resolveBoundary(n){let i=r.get(n.chunkId);if(!i)return KI();let{chunk:o}=i,s=aU(o,n),a=hU(o,s),l=mU(a,o),d=(!a||l.length>0?fU(o,s,n,l,i.renderedMathTargetResolver):null)||null,c=d?.quality==="semantic-token"?d:yU(i,a)??d,u=t&&c&&c.quality!=="expression"?c:null,f=c&&c.quality==="expression"?c:null;if(u){let p=XI(l);return p&&i.heldTokenByElement.set(p,u),gc({semanticTarget:u,expressionTarget:null,regionTarget:i.regionTarget,confidence:s.confidence,reason:s.reason})}if(a&&!B_(a)&&(t?!vU(i,a,l):l.length===0))return gc({semanticTarget:a,expressionTarget:null,regionTarget:i.regionTarget,confidence:s.confidence,reason:s.reason});if(gU(i,l)){let p=XI(l),g=p?i.heldTokenByElement.get(p)??null:null;return gc({semanticTarget:g,expressionTarget:null,regionTarget:i.regionTarget,confidence:s.confidence,reason:g?"hold last token (sticky token mode)":"region (sticky token mode, awaiting first token)"})}return gc({semanticTarget:null,expressionTarget:f??GI(i,l),regionTarget:i.regionTarget,confidence:s.confidence,reason:s.reason})}}},SU=e=>e.alignment?.speech.boundaryOffsetSpace??e.mathAlignment?.speech.boundaryOffsetSpace??"plain-spoken-text",IU=e=>e.mathAlignments?.length?e.mathAlignments:e.mathAlignment&&e.sourceElement?[{element:e.sourceElement,alignment:e.mathAlignment}]:[],kU=e=>(e.chunks&&e.chunks.length?e.chunks:[{speechText:e.speechText||"",visibleText:e.visibleText||e.speechText||"",sourceElement:e.sourceElement||e.contentRoot,regionElement:e.regionElement||e.sourceElement||e.contentRoot,regionRange:e.regionRange,visibleMap:e.visibleMap}]).map((t,r)=>({id:`tts-chunk-${r}`,speechText:t.speechText,visibleText:t.visibleText,sourceElement:t.sourceElement,contentRoot:e.contentRoot,regionElement:t.regionElement??t.sourceElement,regionRange:t.regionRange,visibleMap:t.visibleMap,catalogAlignment:t.alignment,mathAlignments:IU(t),offsetSpace:SU(t)})),TU=["[data-pie-tts-region]","[data-catalog-region]","li","p","label","section","[role='group']","[role='region']","div"].join(","),F_=(e,t)=>{let r=e.closest(TU);return r&&t.contains(r)?r:e},EU=(e,t)=>P_([e],t),CU=e=>(e||"en").split("-")[0].toLowerCase()||"en",xU=new Set(["H1","H2","H3","H4","H5","H6","LI","LABEL","BUTTON"]),RU=new Set(["heading","listitem","option","radio"]),_U=e=>{if(e.type!=="text"||!e.sourceElement)return!1;let t=e.sourceElement.tagName.toUpperCase(),r=(e.sourceElement.getAttribute("role")||"").toLowerCase();return xU.has(t)||RU.has(r)},PU=async e=>{let t=e.resolveMathSpeech??EU,{visibleText:r}=e,n=[],i=0,o=a=>{let l=nn(a),d=r.indexOf(l,i),c=d>=0?d:i,u=c+l.length;return i=u,{start:c,end:u}},s=[];for(let a=0;a<e.chunks.length;a++){let l=e.chunks[a];if(l.type==="text"){let p=_U(l)?[{text:l.text,offset:0}]:bw(l.text,{locale:e.language});for(let g of p){let v=nn(g.text);if(!v)continue;let b=o(v);n.push({sourceChunkIndex:a,segment:{kind:"prose",spokenText:v,visibleText:v,visibleSpan:b}}),s.push(v)}continue}let d=o(l.fallbackText),c=await t(l,{language:e.language,produceSsml:e.produceSsml,mathSpeech:e.mathSpeech}),u=!c.speechText,f=c.speechText||l.fallbackText;n.push({sourceChunkIndex:a,segment:{kind:"math",spokenText:f,mathml:l.mathml,fallbackText:l.fallbackText,visibleSpan:d,usedFallback:u,ssml:c.ssml}}),s.push(f)}return{segments:n,locale:CU(e.language),visibleText:r,plainSpeechText:nn(s.join(" "))}},AU=(e,t,r)=>{let n=new Map;for(let i=t;i<r;i++){let o=e.get(i);o&&n.set(i-t,o)}return n},MU=async e=>{let t=Zd(e.contentRoot,e.textProcessingOptions),r=await PU({chunks:t.chunks,visibleText:t.visibleText,language:e.language,mathSpeech:e.mathSpeech,produceSsml:e.produceSsml,resolveMathSpeech:e.resolveMathSpeech});return{plan:{items:r.segments.map(({segment:n,sourceChunkIndex:i})=>{let o=t.chunks[i];if(n.kind==="prose"){let a=o?.type==="text"?o.sourceElement??e.contentRoot:e.contentRoot;return{segment:n,anchor:{sourceElement:a,regionElement:F_(a,e.contentRoot),visibleMap:AU(t.map,n.visibleSpan.start,n.visibleSpan.end)}}}let s=o?.type==="math"?o.sourceElement??null:null;return{segment:n,anchor:{sourceElement:s,regionElement:s}}}),locale:r.locale,visibleText:r.visibleText,plainSpeechText:r.plainSpeechText},containsMathMarkup:t.containsMathMarkup,visibleText:t.visibleText}},$U=(e,t)=>{let r=b_({speechText:e.spokenText,visibleText:e.spokenText});return{speechText:e.spokenText,visibleText:e.visibleText,sourceElement:t.sourceElement,regionElement:t.regionElement,regionRange:D_(t.visibleMap,0,e.visibleText.length)??void 0,speechMatchesVisibleText:!0,playbackMode:r.playbackMode,alignment:r,visibleMap:t.visibleMap}},H_=(e,t)=>{let r=t.sourceElement;return{speechText:e.spokenText,visibleText:e.fallbackText,sourceElement:r,regionElement:t.regionElement,speechMatchesVisibleText:e.spokenText===e.fallbackText,mathAlignment:r?Np({mathElement:r,speechText:e.spokenText}):void 0}},LU=(e,t,r)=>{let n=t.sourceElement;return{speechText:r,visibleText:e.fallbackText,sourceElement:n,regionElement:t.regionElement,speechMatchesVisibleText:!1,mathAlignment:n?Np({mathElement:n,speechText:r}):void 0,plainFallback:H_(e,t)}},OU=(e,t={})=>e.items.map(({segment:r,anchor:n})=>r.kind==="prose"?$U(r,n):t.format==="ssml"&&r.ssml?LU(r,n,r.ssml):H_(r,n)),NU="pie-tts-control-handoff",hr;(function(e){e.IDLE="idle",e.LOADING="loading",e.PLAYING="playing",e.PAUSED="paused",e.ERROR="error"})(hr||(hr={}));var z_=(e,t)=>e===t||e.startContainer===t.startContainer&&e.startOffset===t.startOffset&&e.endContainer===t.endContainer&&e.endOffset===t.endOffset,DU=(e,t)=>e===t?!0:!e||!t||e.type!==t.type||e.quality!==t.quality?!1:e.type==="range"&&t.type==="range"?z_(e.range,t.range):e.type==="element"&&t.type==="element"?e.element===t.element:e.type==="text-range"&&t.type==="text-range"?e.node===t.node&&e.startOffset===t.startOffset&&e.endOffset===t.endOffset:!1,W_=class Ay{constructor(){T(this,"currentProvider",null),T(this,"provider",null),T(this,"highlightCoordinator",null),T(this,"highlightTargetResolverProvider",null),T(this,"catalogResolver",null),T(this,"state",hr.IDLE),T(this,"ttsConfig",{}),T(this,"currentText",null),T(this,"currentContentElement",null),T(this,"normalizedToDOM",new Map),T(this,"listeners",new Map),T(this,"lastError",null),T(this,"speakRunId",0),T(this,"currentBoundaryOffset",0),T(this,"activeWordBoundaryOffset",0),T(this,"seekSegments",[]),T(this,"playbackChunks",[]),T(this,"activeRecordedAudio",null),T(this,"sentenceHighlightSegments",[]),T(this,"activeSentenceStartOffset",null),T(this,"playbackStartDeferredRunId",null),T(this,"pendingPlaybackStartHighlights",[]),T(this,"playbackStartBarrierCleanup",null),T(this,"playbackRateWriteQueue",Promise.resolve()),T(this,"playbackRateRequestId",0),T(this,"pendingPlaybackRateRequest",null),T(this,"activePlaybackRate",null),T(this,"activeHighlightMode","word"),T(this,"lastRenderedRegionTarget",null),T(this,"telemetryReporter",null),T(this,"generatedMathSpeechResolver",sU())}debugLog(t,r){Ay.debugEnabled&&(r===void 0?console.debug(t):console.debug(t,r))}clearPlaybackStartBarrier(t=this.playbackStartBarrierCleanup){t?.(),this.playbackStartBarrierCleanup===t&&(this.playbackStartBarrierCleanup=null)}notifyPlaybackStarted(t){if(this.playbackStartDeferredRunId!==t||t!==this.speakRunId)return;this.setState(hr.PLAYING);let r=this.pendingPlaybackStartHighlights.splice(0);for(let n of r)n()}installPlaybackStartBarrier(t,r=!1){this.clearPlaybackStartBarrier();let n=this.provider,i=n&&"onPlaybackStart"in n?n:null;if(!i&&!r)return null;let o=i?.onPlaybackStart,s=()=>{try{this.notifyPlaybackStarted(t)}finally{o?.()}};i&&(i.onPlaybackStart=s),this.playbackStartDeferredRunId=t;let a=()=>{i?.onPlaybackStart===s&&(i.onPlaybackStart=o),this.playbackStartDeferredRunId===t&&(this.playbackStartDeferredRunId=null,this.pendingPlaybackStartHighlights=[])};return this.playbackStartBarrierCleanup=a,a}runWhenPlaybackStarts(t,r){if(this.playbackStartDeferredRunId===t){this.pendingPlaybackStartHighlights.push(r);return}r()}async emitTelemetry(t,r){try{await this.telemetryReporter?.(t,r)}catch(n){console.warn("[TTSService] telemetry callback failed:",n)}}async initialize(t,r={}){this.currentProvider=t,this.ttsConfig={...r};let n=r.providerOptions&&typeof r.providerOptions=="object"?r.providerOptions:{};this.telemetryReporter=typeof n.__pieTelemetry=="function"?n.__pieTelemetry:null;try{this.provider=await t.initialize(r)}catch(i){if(t.providerId.toLowerCase()==="browser"||!this.isBrowserSpeechFallbackAvailable()||!await this.switchProviderToBrowser(i,{operation:"tts-initialize"}))throw i}}async updateSettings(t){if(!this.provider)throw Error("TTSService not initialized. Call initialize() first.");let r=this.provider;if(typeof r.updateSettings=="function"){let n={...t,...t.providerOptions?{providerOptions:{...this.ttsConfig.providerOptions||{},...t.providerOptions}}:{}};await r.updateSettings(n),this.ttsConfig={...this.ttsConfig,...n}}else console.warn("[TTSService] Provider does not support dynamic settings updates. Some settings may require reinitialization.")}setHighlightCoordinator(t){this.highlightCoordinator=t}setHighlightTargetResolverProvider(t){return this.highlightTargetResolverProvider=t,()=>{this.highlightTargetResolverProvider===t&&(this.highlightTargetResolverProvider=null)}}setCatalogResolver(t){this.catalogResolver=t}hasSpokenAlternate(t,r="en-US"){return!t||!this.catalogResolver?!1:this.catalogResolver.getAlternative(t,{type:"spoken",language:r,useFallback:!0,form:"content"})?.content!==void 0}getHighlightResolverRuntime(){let t=null;try{t=this.highlightTargetResolverProvider?.()??null}catch{t=null}let r=t?.context??{},n=typeof HTMLElement<"u"&&this.currentContentElement instanceof HTMLElement?this.currentContentElement:null;return{context:{...r,scopeElement:r.scopeElement??n},resolver:t?.resolver??null}}getNodeElement(t){return t?t.nodeType===Node.ELEMENT_NODE?t:t.parentElement:null}isElementWithinScope(t,r){return r?t===r||r.contains(t):!0}isRangeWithinScope(t,r){let n=this.getNodeElement(t.startContainer),i=this.getNodeElement(t.endContainer);return!n||!i?!1:this.isElementWithinScope(n,r)&&this.isElementWithinScope(i,r)}resolveWordHighlightRange(t){let{context:r,resolver:n}=this.getHighlightResolverRuntime(),i=r.scopeElement??this.currentContentElement;try{let o=n?.resolveWordRange?.(t,r);if(o&&this.isRangeWithinScope(o,i))return{range:o,remapped:!z_(t,o)}}catch{}return{range:t,remapped:!1}}resolveSentenceHighlightTargets(t){let{context:r,resolver:n}=this.getHighlightResolverRuntime(),i=r.scopeElement??this.currentContentElement;try{let o=n?.resolveSentenceRanges?.(t,r);if(!o)return{ranges:t,elements:[]};let s=[],a=[];for(let l of o){if(typeof Range<"u"&&l instanceof Range){if(!this.isRangeWithinScope(l,i))return{ranges:t,elements:[]};s.push(l);continue}if(typeof Element<"u"&&l instanceof Element){if(!this.isElementWithinScope(l,i))return{ranges:t,elements:[]};a.push(l);continue}return{ranges:t,elements:[]}}return{ranges:s,elements:a}}catch{return{ranges:t,elements:[]}}}createTextRange(t,r,n){if(typeof document>"u"||typeof document.createRange!="function")return null;try{let i=document.createRange();return i.setStart(t,r),i.setEnd(t,n),i.startContainer!==t||i.endContainer!==t?null:i}catch{return null}}paintTTSWordRange(t){if(this.highlightCoordinator){try{if(t.startContainer===t.endContainer&&t.startContainer.nodeType===Node.TEXT_NODE){this.highlightCoordinator.highlightTTSWord(t.startContainer,t.startOffset,t.endOffset);return}}catch{}this.highlightCoordinator.highlightRange(t,si.TTS_WORD,Wc.YELLOW)}}paintTTSSentenceRanges(t){if(!this.highlightCoordinator)return;let{ranges:r,elements:n}=this.resolveSentenceHighlightTargets(t);if(n.length>0&&r.length===0&&this.highlightCoordinator.highlightTTSSentenceElements){this.highlightCoordinator.highlightTTSSentenceElements(n);return}let i=[...r];for(let o of n){let s=document.createRange();s.selectNodeContents(o),i.push(s)}this.highlightCoordinator.highlightTTSSentence(i)}getCapabilities(){return this.currentProvider?.getCapabilities()||null}getTextProcessingOptions(t){let r=(this.ttsConfig.providerOptions||{}).textNormalization||{},n=r.boundarySpacingMode,i=n==="none"||n==="alnum"||n==="segmenterPreferred"?n:void 0;return{locale:t||(typeof r.locale=="string"?r.locale:void 0),boundarySpacingMode:i}}getMathSpeechOptions(){let t=(this.ttsConfig.providerOptions||{}).mathSpeech;return pf(t)}buildPositionMap(t,r,n){this.normalizedToDOM.clear();let{text:i,map:o}=lu(t,this.getTextProcessingOptions(n));this.normalizedToDOM=o,Ay.debugEnabled&&(this.debugLog("[TTSService] Text comparison:",{spokenLength:r.length,normalizedDomLength:i.length,match:r===i,spokenPreview:r.substring(0,150),normalizedPreview:i.substring(0,150),differAtIndex:r===i?null:(()=>{for(let s=0;s<Math.min(r.length,i.length);s++)if(r[s]!==i[s])return{index:s,spokenChar:r[s],normalizedChar:i[s],spokenContext:r.substring(Math.max(0,s-20),s+20),normalizedContext:i.substring(Math.max(0,s-20),s+20)};return null})()}),this.debugLog("[TTSService] Position map built:",{entries:this.normalizedToDOM.size,spokenTextLength:r.length,normalizedDomLength:i.length,mapLengthMatchesSpoken:this.normalizedToDOM.size===r.length,firstFewMappings:Array.from(this.normalizedToDOM.entries()).slice(0,10).map(([s,{node:a,offset:l}])=>({pos:s,offset:l,char:a.textContent?.[l],expected:r[s]}))}))}getStructuralPauseProfile(){let t=(this.ttsConfig.providerOptions||{}).structuralPauses||{},r=t.units||{},n=(i,o)=>{if(typeof i=="number"&&Number.isFinite(i))return i;if(typeof i=="string"&&i.trim()){let s=Number(i);return Number.isFinite(s)?s:o}return o};return{baseMs:n(t.baseMs,280),units:{minor:n(r.minor,.65),section:n(r.section,1),major:n(r.major,1.35)},minMs:n(t.minMs,120),maxMs:n(t.maxMs,900)}}resolvePauseMsFromUnits(t){let r=this.getStructuralPauseProfile(),n=Math.max(.25,Math.min(4,Number(this.ttsConfig.rate||1))),i=r.baseMs*Math.max(0,t)/n;return Math.max(r.minMs,Math.min(r.maxMs,Math.round(i)))}resolveHighlightMode(){let t=(this.ttsConfig.providerOptions||{}).highlightMode;return t==="word"||t==="sentence"?t:(this.currentProvider?.providerId||"").toLowerCase()==="browser"?"sentence":this.currentProvider?.getCapabilities().supportsWordBoundary??!1?"word":"sentence"}hasExplicitBreakSemantics(t){return t.includes("<")?/<\s*break\b|<\s*speak\b|<\s*prosody\b|<\s*p\b|<\s*s\b/i.test(t):!1}isElementHidden(t){return p_(t)}getBoundaryStrength(t){let r=Number(t.getAttribute("data-tts-break-ms"));if(Number.isFinite(r)&&r>0)return"major";let n=t.tagName.toUpperCase();if(n.match(/^H[1-6]$/))return"major";let i=(t.getAttribute("role")||"").toLowerCase();if(i==="heading")return"major";if(i==="listitem"||i==="row"||i==="option"||i==="radio"||n==="LI")return"section";if(typeof window<"u"){let o=window.getComputedStyle(t).display;if(o==="block"||o==="list-item"||o.startsWith("table")||o==="flex"||o==="grid")return"minor"}return"minor"}getBoundaryAnchor(t,r){let n=t.parentElement,i=null;for(;n&&n!==r;){if(this.isElementHidden(n))return null;let s=Number(n.getAttribute("data-tts-break-ms"));if(Number.isFinite(s)&&s>0)return{anchor:n,units:s/this.getStructuralPauseProfile().baseMs};let a=(n.getAttribute("role")||"").toLowerCase(),l=n.tagName.toUpperCase();if(l.match(/^H[1-6]$/)||a==="heading"||a==="listitem"||l==="LI"){i=n;break}if(!i&&typeof window<"u"){let d=window.getComputedStyle(n).display;(d==="block"||d==="list-item"||d.startsWith("table")||d==="flex"||d==="grid")&&(i=n)}n=n.parentElement}if(!i)return null;let o=this.getBoundaryStrength(i);return{anchor:i,units:this.getStructuralPauseProfile().units[o]}}createSpeechPlan(t,r,n=0){let i=this.collectSpeechPlanBoundaries(t,r);if(n===0)return this.createSpeechPlanSegments(r,i);let o=new Map;for(let[s,a]of i)o.set(s-n,a);return this.createSpeechPlanSegments(r,o)}collectSpeechPlanBoundaries(t,r){let n=new Map,{map:i}=lu(t,this.getTextProcessingOptions()),o=this.createNodeStartOffsets(i),s=document.createTreeWalker(t,NodeFilter.SHOW_TEXT),a=s.nextNode(),l=null;for(;a;){let d=a,c=d.parentElement;if(c&&!this.isElementHidden(c)&&!Ty(d)){let u=this.getBoundaryAnchor(d,t),f=o.get(d);u&&f!==void 0&&u.anchor!==l&&f>0&&(n.set(f,Math.max(n.get(f)||0,u.units)),l=u.anchor)}a=s.nextNode()}return n}createNodeStartOffsets(t){let r=new Map;for(let[n,i]of t.entries())r.has(i.node)||r.set(i.node,n);return r}createSpeechPlanSegments(t,r){let n=Array.from(r.keys()).filter(l=>l>0&&l<t.length).sort((l,d)=>l-d),i=[],o=0;for(let l of n){let d=t.substring(o,l),c=d.match(/^\s*/)?.[0].length||0,u=d.match(/\s*$/)?.[0].length||0,f=o+c,p=l-u;if(p>f){let g=t.substring(f,p);i.push({text:g,startOffset:f,pauseMsAfter:this.resolvePauseMsFromUnits(r.get(l)||0)})}o=l}let s=t.substring(o).match(/^\s*/)?.[0].length||0,a=o+s;return a<t.length&&i.push({text:t.substring(a).trimEnd(),startOffset:a,pauseMsAfter:0}),i.filter(l=>l.text.trim().length>0)}segmentSentences(t){return bw(t,{locale:this.ttsConfig.providerOptions?.locale||void 0})}createSeekSegmentsFromText(t){return this.segmentSentences(t).map(r=>{let n=r.text.match(/^\s*/)?.[0].length||0;return{text:r.text.trim(),startOffset:r.offset+n,pauseMsAfter:0}}).filter(r=>r.text.length>0)}splitSegmentsAtBoundaries(t,r,n){if(t.length===0||r.length===0)return t;let i=Array.from(new Set(r)).filter(s=>Number.isFinite(s)&&s>0).sort((s,a)=>s-a);if(i.length===0)return t;let o=[];for(let s of t){let a=s.startOffset,l=s.startOffset+s.text.length,d=i.filter(u=>u>a&&u<l);if(d.length===0){o.push(s);continue}let c=a;for(let u of[...d,l]){let f=n.substring(c,u),p=f.match(/^\s*/)?.[0].length||0,g=f.match(/\s*$/)?.[0].length||0,v=c+p,b=u-g;b>v&&o.push({text:n.substring(v,b),startOffset:v,pauseMsAfter:0}),c=u}}return o}createSentenceHighlightSegments(t){let r=this.createSeekSegmentsFromText(t.contentToSpeak);if(!t.shouldUsePlan||t.playbackSegments.length===0)return r;let n=t.playbackSegments.map(i=>i.startOffset).filter(i=>i>0);return this.splitSegmentsAtBoundaries(r,n,t.contentToSpeak)}createSeekSegmentsFromSpeechChunks(t){let r=0;return t.map(n=>{let i=nn(n.plainFallback?.speechText||(this.hasExplicitBreakSemantics(n.speechText)?n.visibleText:n.speechText)||n.visibleText)||n.visibleText||"",o={text:i,startOffset:r,pauseMsAfter:0};return r+=Math.max(1,i.length+1),o})}getCurrentSeekSegmentIndex(){if(this.seekSegments.length===0)return 0;let t=0;for(let r=0;r<this.seekSegments.length&&this.seekSegments[r].startOffset<=this.currentBoundaryOffset;r++)t=r;return t}async speakWithPlan(t,r,n){if(!this.provider||t.length===0)return;let i=n?.highlightMode==="sentence",o=this.provider;if(!i&&typeof o.speakSegments=="function"){this.currentBoundaryOffset=0;let s=this.provider.onWordBoundary;this.provider.onWordBoundary=(a,l,d)=>{s?.(a,l,d),Number.isFinite(l)&&(this.currentBoundaryOffset=l)};try{await o.speakSegments(t)}finally{r===this.speakRunId&&this.provider===o&&(this.provider.onWordBoundary=s)}return}this.configureWordBoundaryHighlighting({highlightMode:n?.highlightMode||"word",wordBoundaryOffset:this.activeWordBoundaryOffset});for(let s of t){if(r!==this.speakRunId)return;this.currentBoundaryOffset=s.startOffset,i&&this.runWhenPlaybackStarts(r,()=>{this.highlightSentenceSegment(s.startOffset,s.text)}),await this.provider.speak(s.text);let a=s.pauseMsAfter??0;a>0&&await new Promise(l=>setTimeout(l,a))}}highlightSentenceSegment(t,r){if(!this.highlightCoordinator||typeof document>"u")return;let n=r.trimEnd().length;if(n<=0)return;let i=t+this.activeWordBoundaryOffset,o=this.normalizedToDOM.get(i),s=this.normalizedToDOM.get(i+n-1);if(!o||!s)return;let a=document.createRange();a.setStart(o.node,o.offset),a.setEnd(s.node,s.offset+1),this.paintTTSSentenceRanges([a]),this.activeSentenceStartOffset=t}getSegmentIndexForOffset(t,r){if(t.length===0)return-1;let n=-1;for(let i=0;i<t.length&&t[i].startOffset<=r;i++)n=i;return n}highlightSentenceForOffset(t){let r=this.sentenceHighlightSegments;if(!this.highlightCoordinator||r.length===0)return;let n=this.getSegmentIndexForOffset(r,t);if(n<0)return;let i=r[n];i&&this.activeSentenceStartOffset!==i.startOffset&&this.highlightSentenceSegment(i.startOffset,i.text)}findHighlightRange(t,r){let n=this.normalizedToDOM.get(t);if(!n)return console.warn(`[TTSService] No mapping found for start position ${t}`,{totalMappings:this.normalizedToDOM.size,nearbyMappings:Array.from(this.normalizedToDOM.entries()).filter(([s])=>Math.abs(s-t)<5).map(([s,{offset:a,node:l}])=>({pos:s,offset:a,char:l.textContent?.[a]}))}),null;let i=t+r-1,o=this.normalizedToDOM.get(i);return o?n.node!==o.node?(console.warn("[TTSService] Word spans multiple nodes, highlighting in first node only"),{node:n.node,start:n.offset,end:(n.node.textContent||"").length}):{node:n.node,start:n.offset,end:o.offset+1}:(console.warn(`[TTSService] No mapping found for end position ${i}`,{startChar:t,length:r,totalMappings:this.normalizedToDOM.size}),null)}async speak(t,r){if(!this.provider)throw Error("TTS service not initialized");let n=++this.speakRunId;this.clearPlaybackStartBarrier();let i=null;try{if(await this.applyLanguageSettings(r),n!==this.speakRunId)return;let o=await this.resolveSpeechContent(t,r);if(n!==this.speakRunId)return;let{contentToSpeak:s,speechText:a,highlightText:l,normalizedText:d,usedCatalogSpoken:c,speechSource:u,speechMatchesVisibleText:f,speechChunks:p}=o;this.logResolvedSpeechContent({contentToSpeak:s,speechSource:u,catalogId:r?.catalogId}),this.initializeSpeakTracking(l,r);let g=r?.highlightModeOverride||(f?this.resolveHighlightMode():"sentence");this.activeHighlightMode=g,this.activeWordBoundaryOffset=r?.wordBoundaryOffset||0;let v=this.hasExplicitBreakSemantics(s),b=!!this.currentContentElement&&!c&&!v&&f;if(this.playbackChunks=p?.length?p:[],this.seekSegments=this.playbackChunks.length?this.createSeekSegmentsFromSpeechChunks(this.playbackChunks):v||!f?[]:b&&this.currentContentElement?this.createSpeechPlan(this.currentContentElement,d,r?.wordBoundaryOffset||0):this.createSeekSegmentsFromText(l),this.sentenceHighlightSegments=v?[]:this.createSentenceHighlightSegments({contentToSpeak:l,shouldUsePlan:b,playbackSegments:this.seekSegments}),this.setState(hr.LOADING),i=this.installPlaybackStartBarrier(n,!!this.playbackChunks[0]?.audio),this.prepareHighlightsForSpeak({contentToSpeak:l,options:r,highlightMode:g,shouldUsePlan:b,runId:n}),f?this.configureWordBoundaryHighlighting({highlightMode:g,wordBoundaryOffset:r?.wordBoundaryOffset||0}):this.clearWordBoundaryHighlighting(),i||this.setState(hr.PLAYING),this.activePlaybackRate=this.normalizePlaybackRate(Number(this.ttsConfig.rate??1)),await this.executeSpeakPlayback({shouldUsePlan:b,runId:n,highlightMode:g,contentToSpeak:a,speechChunks:p}),n!==this.speakRunId)return;this.setState(hr.IDLE),this.clearHighlightsAndTracking()}catch(o){let s=o;if(console.error("TTS error:",s),this.lastError=s instanceof Error?s.message:String(s),n!==this.speakRunId)return;throw this.setState(hr.ERROR),this.clearHighlightsAndTracking(),s}finally{this.clearPlaybackStartBarrier(i)}}async switchProviderToBrowser(t,r){if(!this.currentProvider)return!1;let n=new h_,i=this.currentProvider.providerId,o={};this.ttsConfig.rate!==void 0&&(o.rate=this.ttsConfig.rate),this.ttsConfig.pitch!==void 0&&(o.pitch=this.ttsConfig.pitch),this.ttsConfig.mathTokenHighlighting!==void 0&&(o.mathTokenHighlighting=this.ttsConfig.mathTokenHighlighting);let s=r?.operation||"tts-initialize",a=r?.contentToSpeak??"",l=a.replace(/\s+/g," ").trim().slice(0,120),d=a.length>0?{textLength:a.length,textPreview:l.length<a.length?`${l}…`:l}:{};try{return this.provider?.stop(),this.currentProvider.destroy(),this.currentProvider=n,this.provider=await n.initialize(o),this.ttsConfig=o,await this.emitTelemetry("pie-tool-runtime-fallback",{toolId:"textToSpeech",operation:s,fromProvider:i,toProvider:n.providerId,reason:t instanceof Error?t.message:String(t),...d}),console.warn("[TTSService] TTS provider initialization failed; switched to browser fallback",{fromProvider:i,reason:t,...d}),!0}catch(c){return await this.emitTelemetry("pie-tool-runtime-fallback-error",{toolId:"textToSpeech",operation:s,fromProvider:i,toProvider:"browser",errorType:"TTSRuntimeFallbackError",message:c instanceof Error?c.message:String(c)}),console.error("[TTSService] Failed to switch to browser fallback provider",c),!1}}isBrowserSpeechFallbackAvailable(){return typeof window>"u"||!("speechSynthesis"in window)?!1:typeof globalThis.SpeechSynthesisUtterance=="function"}async applyLanguageSettings(t){if(!t?.language||!this.provider)return;let r=this.ttsConfig.providerOptions||{},n=r.textNormalization||{},i=r.segmenter||{},o={...r,locale:t.language,textNormalization:{...n,locale:t.language},segmenter:{...i,locale:t.language}};this.ttsConfig={...this.ttsConfig,providerOptions:o},"updateSettings"in this.provider&&typeof this.provider.updateSettings=="function"&&await this.provider.updateSettings({providerOptions:o})}async resolveSpeechContent(t,r){let n=nn(t);if(r?.ignoreCatalogs)return{contentToSpeak:n,speechText:n,visibleText:n,highlightText:n,usedCatalogSpoken:!1,speechSource:"dom-or-input",normalizedText:n,containsMathMarkup:!1,speechMatchesVisibleText:!0};if(r?.catalogId&&this.catalogResolver){let o=this.catalogResolver.getAlternative(r.catalogId,{type:"spoken",language:r.language||"en-US",useFallback:!0,context:r.catalogContext,form:"content"}),s=o?.content;if(o&&s!==void 0){let a=r?.contentElement&&Zd(r.contentElement,this.getTextProcessingOptions(r.language)).visibleText||n,l=nn(s);return this.debugLog(`[TTSService] Using catalog content for "${r.catalogId}" (${o.language})`),{contentToSpeak:s,speechText:s,visibleText:a,highlightText:a,usedCatalogSpoken:!0,speechSource:"catalog-spoken",normalizedText:a,containsMathMarkup:!1,speechMatchesVisibleText:l===a}}this.debugLog(`[TTSService] No catalog found for "${r.catalogId}", falling back to generated TTS`)}let i=r?.contentElement?this.resolveCatalogComposedSpeechContent(r.contentElement,n,r):null;return i||{...r?.contentElement?await this.resolveGeneratedSpeechContent(r.contentElement,n,r.language):{contentToSpeak:n,speechText:n,visibleText:n,highlightText:n,normalizedText:n,containsMathMarkup:!1,speechMatchesVisibleText:!0},usedCatalogSpoken:!1,speechSource:"dom-or-input"}}resolveCatalogComposedSpeechContent(t,r,n){if(!this.catalogResolver)return null;let i=this.collectCatalogSpeechChunks(t,n);if(!i.some(a=>a.sourceElement))return null;let o=nn(i.map(a=>a.speechText).join(" ")),s=Zd(t,this.getTextProcessingOptions(n.language)).visibleText||r;return{contentToSpeak:o,speechText:o,visibleText:s,highlightText:s,usedCatalogSpoken:!0,speechSource:"catalog-spoken",normalizedText:s,containsMathMarkup:!1,speechMatchesVisibleText:i.every(a=>a.speechMatchesVisibleText),speechChunks:i}}collectCatalogSpeechChunks(t,r){let n=[],i="",o=()=>{let c=nn(i);i="",c&&n.push({speechText:c,visibleText:c,sourceElement:null,speechMatchesVisibleText:!0})},s=c=>{let u=c.getAttribute("data-catalog-idref");if(!u)return null;let f={type:"spoken",language:r.language||"en-US",useFallback:!0,context:r.catalogContext},p=this.catalogResolver.getAlternative(u,{...f,form:"payload"}),g=p?.payload?DW({payload:p.payload})??void 0:void 0,v=this.catalogResolver.getAlternative(u,{...f,form:"content"})?.content;return g===void 0&&v===void 0?null:{script:v,audio:g}},a=(c,u)=>{let f=l(c);if(f.length!==1)return null;let p=f[0],g=Zd(p,this.getTextProcessingOptions(r.language)).visibleText||nn(p.textContent||""),v=b=>nn(b).replace(/\s+/g,"");return v(g)===v(u)?p:null},l=c=>{let u=Array.from(c.querySelectorAll("math"));return c.localName?.toLowerCase()==="math"?[c,...u]:u},d=c=>{if(hf(c,t))return;if(c.nodeType===Node.TEXT_NODE){i+=` ${c.textContent||""}`;return}if(c.nodeType!==Node.ELEMENT_NODE)return;let u=c,f=s(u);if(f){o();let p=Zd(u,this.getTextProcessingOptions(r.language)),g=p.visibleText||nn(u.textContent||""),v=F_(u,t),b=f.script!==void 0?(()=>{let w=f.script,I=b_({speechText:w,visibleText:g}),x=a(u,g),C=x?Np({mathElement:x,speechText:w}):void 0,L=C?void 0:l(u).map(E=>({element:E,alignment:Np({mathElement:E,speechText:w})}));return{speechText:w,visibleText:g,sourceElement:u,regionElement:v,speechMatchesVisibleText:nn(w)===g,playbackMode:I.playbackMode,alignment:I,mathAlignment:C,mathAlignments:L,visibleMap:p.map}})():null;if(f.audio){n.push(b?{...b,audio:f.audio,plainFallback:b}:{speechText:g,visibleText:g,sourceElement:u,regionElement:v,speechMatchesVisibleText:!1,visibleMap:p.map,audio:f.audio});return}b&&n.push(b);return}for(let p of Array.from(u.childNodes))d(p)};return d(t),o(),n}resolveGeneratedPlaybackFormat(){let t=this.currentProvider;return!t||t.providerId?.toLowerCase()==="browser"?"plain":t.getCapabilities?.().supportsSSML?"ssml":"plain"}async resolveGeneratedSpeechContent(t,r,n){let i=this.resolveGeneratedPlaybackFormat(),{plan:o,containsMathMarkup:s,visibleText:a}=await MU({contentRoot:t,language:n,mathSpeech:this.getMathSpeechOptions(),textProcessingOptions:this.getTextProcessingOptions(n),produceSsml:i==="ssml",resolveMathSpeech:this.generatedMathSpeechResolver}),l=a||r;if(!s)return{contentToSpeak:l,speechText:l,visibleText:l,highlightText:l,normalizedText:l,containsMathMarkup:!1,speechMatchesVisibleText:!0};let d=OU(o,{format:i}),c=o.plainSpeechText;return{contentToSpeak:c,speechText:c,visibleText:l,highlightText:l,normalizedText:l,containsMathMarkup:!0,speechMatchesVisibleText:c===l,speechChunks:d}}logResolvedSpeechContent(t){let r=t.contentToSpeak.replace(/\s+/g," ").trim().slice(0,200);this.debugLog("[TTSService] Speak resolved content",{source:t.speechSource,catalogId:t.catalogId||null,length:t.contentToSpeak.length,preview:r})}initializeSpeakTracking(t,r){this.currentText=t,this.currentContentElement=r?.contentElement||null,this.lastError=null,this.currentBoundaryOffset=0,this.playbackChunks=[],this.activeSentenceStartOffset=null}prepareHighlightsForSpeak(t){if(!this.currentContentElement||!this.highlightCoordinator||(this.buildPositionMap(this.currentContentElement,t.contentToSpeak,t.options?.language),t.highlightMode==="sentence"&&t.shouldUsePlan))return;let r=this.sentenceHighlightSegments[0]||this.seekSegments[0];this.runWhenPlaybackStarts(t.runId,()=>{if(r)this.highlightSentenceSegment(r.startOffset,r.text),this.debugLog("[TTSService] Applied initial sentence highlighting");else try{let n=document.createRange();n.selectNodeContents(this.currentContentElement),this.paintTTSSentenceRanges([n])}catch{}})}configureWordBoundaryHighlighting(t){!this.provider||t.highlightMode!=="word"||!this.highlightCoordinator||!this.currentContentElement||(this.provider.onWordBoundary=(r,n,i)=>{let o=i||r.length,s=n+this.currentBoundaryOffset,a=s+t.wordBoundaryOffset;this.highlightSentenceForOffset(s);let l=this.findHighlightRange(a,o);if(l&&this.highlightCoordinator){let d=l.node.textContent?.substring(l.start,l.end)||"";this.debugLog(`[TTSService] Highlighting "${d}" (word: "${r}") at position ${a}`);let c=this.createTextRange(l.node,l.start,l.end);c?this.paintTTSWordRange(this.resolveWordHighlightRange(c).range):this.highlightCoordinator.highlightTTSWord(l.node,l.start,l.end)}else console.warn(`[TTSService] Could not find highlight range for position ${a}, length ${o}`)})}clearWordBoundaryHighlighting(){this.provider&&(this.provider.onWordBoundary=void 0)}highlightCatalogRegion(t){let r=t.regionElement||t.sourceElement;if(!(!r&&!t.regionRange||!this.highlightCoordinator))try{if(this.lastRenderedRegionTarget=null,t.regionRange){this.highlightCoordinator.clearHighlights?.(si.TTS_WORD),this.paintTTSSentenceRanges([t.regionRange]);return}if(!r)return;let n=document.createRange();n.selectNodeContents(r),this.highlightCoordinator.clearHighlights?.(si.TTS_WORD),this.paintTTSSentenceRanges([n])}catch{}}highlightCatalogActiveRange(t){this.highlightCoordinator&&this.paintTTSWordRange(this.resolveWordHighlightRange(t).range)}highlightRenderableRegionTarget(t){if(!(!this.highlightCoordinator||!t||typeof document>"u")&&!(!this.highlightTargetResolverProvider&&DU(this.lastRenderedRegionTarget,t)))try{let r=document.createRange();if(t.type==="element")r.selectNodeContents(t.element);else if(t.type==="range"){this.paintTTSSentenceRanges([t.range]),this.lastRenderedRegionTarget=t;return}else r.setStart(t.node,t.startOffset),r.setEnd(t.node,t.endOffset);this.paintTTSSentenceRanges([r]),this.lastRenderedRegionTarget=t}catch{}}highlightRenderableActiveTarget(t){if(!this.highlightCoordinator||typeof document>"u")return;if(!t){this.highlightCoordinator.clearHighlights(si.TTS_WORD);return}if(t.type==="text-range"){let o=this.createTextRange(t.node,t.startOffset,t.endOffset);o?this.paintTTSWordRange(this.resolveWordHighlightRange(o).range):this.highlightCoordinator.highlightTTSWord(t.node,t.startOffset,t.endOffset);return}if(t.type==="range"){this.highlightCatalogActiveRange(t.range);return}let r=document.createRange();r.selectNodeContents(t.element);let n=this.resolveWordHighlightRange(r);if(n.remapped){this.paintTTSWordRange(n.range);return}let i=t.element.childNodes.length===1?t.element.firstChild:null;if(t.quality==="semantic-token"&&i?.nodeType===Node.TEXT_NODE){this.highlightCoordinator.highlightTTSWord(i,0,i.textContent?.length||0);return}this.highlightCoordinator.highlightTTSWordElement?.(t.element)}renderHighlightDecision(t){this.highlightRenderableRegionTarget(t.regionTarget),this.highlightRenderableActiveTarget(t.activeTarget)}async speakCatalogChunk(t,r){try{await this.speakCatalogChunkOnce(t,r)}catch(n){if(t.plainFallback&&r===this.speakRunId){this.debugLog("[TTSService] SSML chunk speak failed; retrying plain text",{message:n instanceof Error?n.message:String(n)}),this.playbackStartDeferredRunId===r&&this.provider&&!("onPlaybackStart"in this.provider)&&(this.pendingPlaybackStartHighlights=[],this.clearPlaybackStartBarrier(),this.setState(hr.PLAYING)),await this.speakCatalogChunkOnce(t.plainFallback,r);return}throw n}}async playRecordedAudio(t,r){if(typeof document>"u")throw Error("[tts] no document available to play recorded audio");let n=t.sources[0],i=document.createElement("audio");i.preload="auto",i.src=K$(n.src,t.fragment),i.playbackRate=this.normalizePlaybackRate(Number(this.ttsConfig.rate||1)),await new Promise((o,s)=>{let a,l=!1,d=!1,c=()=>{d||l||(l=!0,r?.())},u=()=>{i.removeEventListener("ended",f),i.removeEventListener("error",p),i.removeEventListener("playing",c),a?.(),this.activeRecordedAudio?.element===i&&(this.activeRecordedAudio=null)},f=()=>{d||(d=!0,u(),o())},p=()=>{d||(d=!0,u(),s(Error(`[tts] recorded audio failed to play: ${n.src}`)))};this.activeRecordedAudio={element:i,cancel:()=>{d||(d=!0,u(),i.pause(),o())}},i.addEventListener("ended",f),i.addEventListener("error",p),i.addEventListener("playing",c),a=G$(i,t.fragment,f),Promise.resolve(i.play()).then(c).catch(p)}).finally(()=>{this.activeRecordedAudio?.element===i&&(this.activeRecordedAudio=null),i.pause(),i.removeAttribute("src")})}cancelRecordedAudio(){let t=this.activeRecordedAudio;t&&(this.activeRecordedAudio=null,t.cancel())}async speakCatalogChunkOnce(t,r){if(!this.provider)return;if(this.lastRenderedRegionTarget=null,t.audio){this.runWhenPlaybackStarts(r,()=>{this.highlightCatalogRegion(t)}),await this.playRecordedAudio(t.audio,()=>{this.notifyPlaybackStarted(r)});return}let n=t.regionElement||t.sourceElement||this.currentContentElement,i=n?kU({contentRoot:n,chunks:[t]})[0]:null,o=this.ttsConfig.mathTokenHighlighting!==!1,s=i?wU({chunks:[i],mathTokenHighlighting:o}):null;if(this.runWhenPlaybackStarts(r,()=>{s&&i&&t.mathAlignment?this.renderHighlightDecision(s.resolveInitial(i.id)):this.highlightCatalogRegion(t)}),!(t.sourceElement&&(t.mathAlignment&&t.mathAlignment.speech.tokens.length>0||t.mathAlignments&&t.mathAlignments.length>0||t.alignment&&t.visibleMap&&(t.playbackMode==="exact-word"||t.playbackMode==="anchor-span")))){let c=this.provider,u=c.onWordBoundary;c.onWordBoundary=void 0;try{await c.speak(t.speechText)}finally{this.provider===c&&r===this.speakRunId&&c.onWordBoundary===void 0&&(c.onWordBoundary=u)}return}let a=this.provider,l=a.onWordBoundary,d=(c,u,f)=>{if(r===this.speakRunId&&s&&i){let p=i.offsetSpace==="unsupported"?"unknown":i.offsetSpace;this.renderHighlightDecision(s.resolveBoundary({chunkId:i.id,word:c,position:u,length:f,providerOffsetSpace:p}));return}};a.onWordBoundary=d;try{await a.speak(t.speechText)}finally{this.provider===a&&r===this.speakRunId&&a.onWordBoundary===d&&(a.onWordBoundary=l)}}async executeSpeakPlayback(t){if(t.speechChunks?.length&&this.provider){for(let r=0;r<t.speechChunks.length;r++){if(t.runId!==this.speakRunId)return;let n=this.seekSegments[r];n&&(this.currentBoundaryOffset=n.startOffset);let i=t.speechChunks[r];await this.speakCatalogChunk(i,t.runId)}return}if(t.shouldUsePlan&&this.currentContentElement){let r=this.seekSegments;r.length>0?await this.speakWithPlan(r,t.runId,{highlightMode:t.highlightMode}):this.provider&&await this.provider.speak(t.contentToSpeak);return}this.provider&&await this.provider.speak(t.contentToSpeak)}clearHighlightsAndTracking(){this.pendingPlaybackStartHighlights=[],this.activePlaybackRate=null,this.highlightCoordinator&&this.highlightCoordinator.clearTTS(),this.lastRenderedRegionTarget=null,this.currentContentElement=null,this.normalizedToDOM.clear(),this.currentBoundaryOffset=0,this.activeWordBoundaryOffset=0,this.seekSegments=[],this.playbackChunks=[],this.sentenceHighlightSegments=[],this.activeSentenceStartOffset=null}selectMappedRangeText(t,r){if(typeof t.comparePoint!="function")return null;let{text:n,map:i}=lu(r,this.getTextProcessingOptions()),o=-1,s=-1;for(let[c,{node:u,offset:f}]of i){if(c>=n.length)continue;let p=!1;try{p=t.comparePoint(u,f)===0&&t.comparePoint(u,Math.min(f+1,u.length))===0}catch{p=!1}p&&((o===-1||c<o)&&(o=c),c>s&&(s=c))}if(o===-1)return null;let a=n.slice(o,s+1),l=a.length-a.trimStart().length,d=a.trim();return d?{text:d,offset:o+l}:null}async speakRange(t,r){if(!this.provider)throw Error("TTS service not initialized");if(Ty(t.commonAncestorContainer)){console.warn("[tts] selection lies inside content marked not-to-be-spoken; nothing was spoken. Selecting a node and pressing read-aloud must not become a way around suppression.");return}let n=r?.contentRoot||null;if(!n){let d=t.commonAncestorContainer;n=d.nodeType===Node.ELEMENT_NODE?d:d.parentElement}if(!n)return;let i=jI(t,n),o=i.text.trim();if(!o){i.filtered&&console.warn("[tts] every part of the selection is either hidden or marked not-to-be-spoken; nothing was spoken.");return}let s=this.selectMappedRangeText(t,n),a=o,l=s?.offset??0;if(s)a=s.text;else{let d=document.createRange();d.selectNodeContents(n),d.setEnd(t.startContainer,t.startOffset);let c=jI(d,n).text,u=nn(c);l=u.length+(/\s$/.test(c)&&u?1:0)}this.debugLog("[TTSService] speakRange offset calculation:",{selectedText:a,mapped:!!s,offset:l,rootTag:n.tagName}),await this.speak(a,{contentElement:n,ignoreCatalogs:!0,wordBoundaryOffset:l})}pause(){this.provider&&this.state===hr.PLAYING&&(this.activeRecordedAudio?.element.pause(),this.provider.pause(),this.setState(hr.PAUSED))}resume(){if(this.provider&&this.state===hr.PAUSED){let t=this.activeRecordedAudio?.element;t&&Promise.resolve(t.play()).catch(()=>{}),this.provider.resume(),this.setState(hr.PLAYING)}}normalizePlaybackRate(t){return Number.isFinite(t)?Math.max(.25,Math.min(4,t)):1}async restartFromSeekIndex(t){if(!this.provider||this.seekSegments.length===0)return;let r=Math.max(0,Math.min(this.seekSegments.length-1,t)),n=this.playbackChunks.length?this.playbackChunks.slice(r):null;this.speakRunId+=1,this.clearPlaybackStartBarrier(),this.cancelRecordedAudio(),this.provider.onWordBoundary=void 0,this.provider.stop();let i=++this.speakRunId,o=this.seekSegments.slice(r);this.highlightCoordinator?.clearTTS(),this.activeSentenceStartOffset=null,this.setState(hr.LOADING);let s=this.installPlaybackStartBarrier(i,!!n?.[0]?.audio);s||this.setState(hr.PLAYING),this.activePlaybackRate=this.normalizePlaybackRate(Number(this.ttsConfig.rate??1));try{if(this.configureWordBoundaryHighlighting({highlightMode:this.activeHighlightMode,wordBoundaryOffset:this.activeWordBoundaryOffset}),n)for(let a=0;a<n.length;a++){if(i!==this.speakRunId)return;let l=r+a,d=this.seekSegments[l];d&&(this.currentBoundaryOffset=d.startOffset),await this.speakCatalogChunk(n[a],i)}else await this.speakWithPlan(o,i,{highlightMode:this.activeHighlightMode});if(i!==this.speakRunId)return;this.setState(hr.IDLE),this.clearHighlightsAndTracking()}catch(a){if(i!==this.speakRunId)return;throw this.lastError=a instanceof Error?a.message:String(a),this.setState(hr.ERROR),this.clearHighlightsAndTracking(),a}finally{this.clearPlaybackStartBarrier(s)}}async setPlaybackRate(t){if(!this.provider)throw Error("TTSService not initialized. Call initialize() first.");let r=this.normalizePlaybackRate(t),n=this.pendingPlaybackRateRequest;if(n?.rate===r){await n.promise;return}let i=++this.playbackRateRequestId,o=this.playbackRateWriteQueue.then(async()=>{let l=this.speakRunId;if(i!==this.playbackRateRequestId)return{didUpdate:!1,playbackRunId:l};let d=this.normalizePlaybackRate(Number(this.ttsConfig.rate??1));return r===d?{didUpdate:!1,playbackRunId:l}:(await this.updateSettings({rate:r}),{didUpdate:!0,playbackRunId:l})});this.playbackRateWriteQueue=o.then(()=>{},()=>{});let s=o.then(async l=>{if(i!==this.playbackRateRequestId||l.playbackRunId!==this.speakRunId)return;let d=this.activePlaybackRate!==null&&this.activePlaybackRate!==r;!l.didUpdate&&!d||this.state!==hr.PLAYING&&this.state!==hr.LOADING||!this.currentText||this.seekSegments.length===0||this.hasExplicitBreakSemantics(this.currentText)||await this.restartFromSeekIndex(this.getCurrentSeekSegmentIndex())}),a;a=s.finally(()=>{this.pendingPlaybackRateRequest?.promise===a&&(this.pendingPlaybackRateRequest=null)}),this.pendingPlaybackRateRequest={rate:r,promise:a},await a}async seekBy(t){if(!this.provider||!this.currentText||this.state!==hr.PLAYING&&this.state!==hr.PAUSED||this.hasExplicitBreakSemantics(this.currentText)||this.seekSegments.length===0)return;let r=Number.isFinite(t)?Math.trunc(t):0;if(r===0)return;let n=this.getCurrentSeekSegmentIndex(),i=Math.max(0,Math.min(this.seekSegments.length-1,n+r));i!==n&&await this.restartFromSeekIndex(i)}async seekForward(t=1){let r=Number.isFinite(t)?Math.max(1,Math.trunc(t)):1;await this.seekBy(r)}async seekBackward(t=1){let r=Number.isFinite(t)?Math.max(1,Math.trunc(t)):1;await this.seekBy(-r)}stop(){this.provider&&(this.speakRunId+=1,this.clearPlaybackStartBarrier(),this.cancelRecordedAudio(),this.provider.onWordBoundary=void 0,this.provider.stop(),this.setState(hr.IDLE),this.currentText=null,this.highlightCoordinator&&this.highlightCoordinator.clearTTS(),this.lastRenderedRegionTarget=null,this.currentContentElement=null,this.normalizedToDOM.clear(),this.currentBoundaryOffset=0,this.activeWordBoundaryOffset=0,this.seekSegments=[],this.playbackChunks=[],this.sentenceHighlightSegments=[],this.activeSentenceStartOffset=null,this.activePlaybackRate=null)}requestControlHandoff(){typeof window>"u"||window.dispatchEvent(new CustomEvent(NU,{detail:{source:"host"}}))}isPlaying(){return this.state===hr.PLAYING}isPaused(){return this.state===hr.PAUSED}getState(){return this.state}getCurrentText(){return this.currentText}getLastError(){return this.lastError}onStateChange(t,r){this.listeners.has(t)||this.listeners.set(t,new Set),this.listeners.get(t).add(r)}offStateChange(t,r){let n=this.listeners.get(t);n&&(n.delete(r),n.size===0&&this.listeners.delete(t))}setState(t){if(this.state===t)return;let r=this.state;this.state=t;for(let n of this.listeners.values())for(let i of n)i(t);if(this.emitTelemetry("pie-tool-playback-state-changed",{toolId:"textToSpeech",providerId:"tts",previousState:r,state:t}),t===hr.PLAYING){let n=r===hr.PAUSED?"pie-tool-playback-resume":"pie-tool-playback-start";this.emitTelemetry(n,{toolId:"textToSpeech",providerId:"tts",previousState:r,state:t});return}if(t===hr.PAUSED){this.emitTelemetry("pie-tool-playback-pause",{toolId:"textToSpeech",providerId:"tts",previousState:r,state:t});return}if(t===hr.ERROR){this.emitTelemetry("pie-tool-playback-error",{toolId:"textToSpeech",providerId:"tts",previousState:r,state:t,message:this.lastError||void 0});return}t===hr.IDLE&&(r===hr.PLAYING||r===hr.PAUSED||r===hr.LOADING)&&this.emitTelemetry("pie-tool-playback-stop",{toolId:"textToSpeech",providerId:"tts",previousState:r,state:t})}};T(W_,"debugEnabled",(()=>{try{if(typeof process<"u"&&{}.PIE_TTS_DEBUG==="1")return!0}catch{}return globalThis.__PIE_TTS_DEBUG__===!0})());var jU=new Set(["reserved-row","expanding-row","floating-overlay","left-aligned"]),My=e=>e&&typeof e=="object"?e:{},BU=e=>e==="polly"||e==="google"||e==="server",Ji=(e,t)=>e===void 0?t:e,FU=(e,t="left-aligned")=>typeof e=="string"&&jU.has(e)?e:t;Object.freeze([.8,1.25]);Object.freeze([{rate:.8,label:"Slow",ariaLabel:"Slow speed"},{rate:1,label:"Normal",ariaLabel:"Normal speed",default:!0},{rate:1.25,label:"Fast",ariaLabel:"Fast speed"}]);Object.freeze([.8,1,1.25]);var HU=e=>{let t={...e,layoutMode:FU(e.layoutMode)},r=e.backend||"browser";if(!BU(r))return t;let n={...t,apiEndpoint:Ji(t.apiEndpoint,"/api/tts"),transportMode:Ji(t.transportMode,"pie"),endpointValidationMode:Ji(t.endpointValidationMode,"voices"),validateEndpoint:Ji(t.validateEndpoint,!0),includeAuthOnAssetFetch:Ji(t.includeAuthOnAssetFetch,!1),rate:Ji(t.rate,1),language:Ji(t.language,"en-US")};return r==="polly"?{...n,defaultVoice:Ji(n.defaultVoice,"Joanna"),engine:Ji(n.engine,"neural"),format:Ji(n.format,"mp3"),speechMarksMode:Ji(n.speechMarksMode,"word+sentence")}:r==="google"?{...n,defaultVoice:Ji(n.defaultVoice,"en-US-Wavenet-A")}:n},zU=e=>{let t=My(e),r=My(t.settings),{provider:n,...i}={...t,...r};return HU({...i,...typeof n=="string"?{provider:n}:{}})},U_=e=>e.backend||"browser",WU=(e,t)=>t==="polly"||t==="google"?t:e.serverProvider||e.provider,UU=(e,t)=>e.transportMode||(t==="custom"?"custom":"pie"),qU=e=>{let t=U_(e),r=WU(e,t),n=UU(e,r),i=pf(e.mathSpeech);return{voice:e.defaultVoice,rate:e.rate,pitch:e.pitch,providerOptions:{...My(e.providerOptions),...e.language?{locale:e.language}:{},...t==="polly"&&e.engine?{engine:e.engine}:{},...t==="polly"&&typeof e.sampleRate=="number"?{sampleRate:e.sampleRate}:{},...t==="polly"&&e.format?{format:e.format}:{},...t==="polly"?{speechMarkTypes:e.speechMarksMode==="word+sentence"?["word","sentence"]:["word"]}:{},...n==="custom"&&typeof e.cache=="boolean"?{cache:e.cache}:{},...n==="custom"&&e.speedRate?{speedRate:e.speedRate}:{},...n==="custom"&&e.lang_id?{lang_id:e.lang_id}:{},...i?{mathSpeech:i}:{}},apiEndpoint:e.apiEndpoint,provider:r,language:e.language,transportMode:n,endpointMode:e.endpointMode,endpointValidationMode:e.endpointValidationMode,includeAuthOnAssetFetch:e.includeAuthOnAssetFetch,assetOrigins:e.assetOrigins,credentials:e.credentials,headers:e.headers,validateEndpoint:e.validateEndpoint,...typeof e.mathTokenHighlighting=="boolean"?{mathTokenHighlighting:e.mathTokenHighlighting}:{}}},VU=class{constructor(){T(this,"providers",new Map),T(this,"configs",new Map),T(this,"initialized",new Map),T(this,"initializationPromises",new Map)}async emitTelemetry(e,t,r){try{await e.onTelemetry?.(t,r)}catch(n){console.warn("[ToolProviderRegistry] Telemetry callback failed:",n)}}register(e,t){if(this.providers.has(e)){console.warn(`[ToolProviderRegistry] Provider "${e}" already registered, skipping`);return}this.providers.set(e,t.provider),this.configs.set(e,t),this.initialized.set(e,!1),console.log(`[ToolProviderRegistry] Registered provider "${e}" (${t.provider.providerName})`),t.lazy===!1&&this.initialize(e).catch(r=>{console.error(`[ToolProviderRegistry] Failed to initialize provider "${e}":`,r)})}async initialize(e){if(this.initialized.get(e))return;let t=this.initializationPromises.get(e);if(t)return t;let r=this._doInitialize(e);this.initializationPromises.set(e,r);try{await r}finally{this.initializationPromises.delete(e)}}async _doInitialize(e){let t=this.providers.get(e),r=this.configs.get(e);if(!t||!r)throw Error(`[ToolProviderRegistry] Provider "${e}" not registered`);let n={...r.config},i=s=>{if(!s||typeof s!="object")return"unknown";let a=s;return(typeof a.backend=="string"?a.backend:typeof a.provider=="string"?a.provider:typeof a.serverProvider=="string"?a.serverProvider:typeof a.providerId=="string"?a.providerId:"")||"unknown"},o=Date.now();if(await this.emitTelemetry(r,"pie-tool-init-start",{toolId:e,providerId:e,backend:i(n),operation:"provider-initialize"}),t.requiresAuth&&r.authFetcher){let s=Date.now();await this.emitTelemetry(r,"pie-tool-backend-call-start",{toolId:e,providerId:e,backend:i(n),operation:"auth-fetch"}),console.log(`[ToolProviderRegistry] Fetching auth for "${e}"...`);try{let a=await r.authFetcher();n={...n,...a},await this.emitTelemetry(r,"pie-tool-backend-call-success",{toolId:e,providerId:e,backend:i(n),operation:"auth-fetch",duration:Date.now()-s})}catch(a){throw await this.emitTelemetry(r,"pie-tool-backend-call-error",{toolId:e,providerId:e,backend:i(n),operation:"auth-fetch",duration:Date.now()-s,errorType:"ProviderAuthFetchError",message:a instanceof Error?a.message:String(a)}),console.error(`[ToolProviderRegistry] Auth fetch failed for "${e}":`,a),Error(`Failed to fetch auth credentials for provider "${e}"`)}}try{await t.initialize(n),this.initialized.set(e,!0),await this.emitTelemetry(r,"pie-tool-init-success",{toolId:e,providerId:e,backend:i(n),operation:"provider-initialize",duration:Date.now()-o}),console.log(`[ToolProviderRegistry] Provider "${e}" initialized`)}catch(s){throw await this.emitTelemetry(r,"pie-tool-init-error",{toolId:e,providerId:e,backend:i(n),operation:"provider-initialize",duration:Date.now()-o,errorType:"ProviderInitializationError",message:s instanceof Error?s.message:String(s)}),console.error(`[ToolProviderRegistry] Initialization failed for "${e}":`,s),s}}async getProvider(e,t=!0){let r=this.providers.get(e);if(!r)throw console.error("[ToolProviderRegistry] Provider not found:",{requestedId:e,availableProviders:Array.from(this.providers.keys())}),Error(`[ToolProviderRegistry] Provider "${e}" not registered`);return t&&!this.initialized.get(e)&&(console.log("[ToolProviderRegistry] Auto-initializing provider:",e),await this.initialize(e)),r}getProvidersByCategory(e){return Array.from(this.providers.entries()).filter(([t,r])=>r.category===e).map(([t])=>t)}getProviderIds(){return Array.from(this.providers.keys())}has(e){return this.providers.has(e)}isInitialized(e){return this.initialized.get(e)===!0}isInitializing(e){return this.initializationPromises.has(e)}async unregister(e){let t=this.providers.get(e);if(t){let r=this.initializationPromises.get(e);if(r)try{await r}catch{}t.destroy(),this.providers.delete(e),this.configs.delete(e),this.initialized.delete(e),this.initializationPromises.delete(e),console.log(`[ToolProviderRegistry] Unregistered provider "${e}"`)}}async destroy(){let e=Array.from(this.providers.keys());await Promise.all(e.map(t=>this.unregister(t))),console.log("[ToolProviderRegistry] Registry destroyed")}},GU=class{constructor(){T(this,"targets",new Set),T(this,"changeListeners",new Set)}registerTarget(e){return this.targets.add(e),this.notifyChange(),()=>{this.targets.delete(e)&&this.notifyChange()}}canRequest(e,t){return this.findTarget(e,t)!==null}request(e){let t=this.findTarget(e.toolId,e.level);if(!t)return!1;try{t.open(e.toolId,e.params)}catch(r){return console.error(`[ToolRequestRegistry] Target failed to open "${e.toolId}":`,r),!1}return!0}onTargetsChange(e){return this.changeListeners.add(e),()=>{this.changeListeners.delete(e)}}findTarget(e,t){let r=this.findTargetAtLevel(e,t??"section");if(r||t!==void 0)return r;for(let n of this.targets)if(n.level!=="section"&&this.hostsTool(n,e))return n;return null}findTargetAtLevel(e,t){for(let r of this.targets)if(r.level===t&&this.hostsTool(r,e))return r;return null}hostsTool(e,t){try{return e.hostsTool(t)===!0}catch(r){return console.warn(`[ToolRequestRegistry] Target at level "${e.level}" failed the host check for "${t}":`,r),!1}}notifyChange(){for(let e of this.changeListeners)try{e()}catch(t){console.warn("[ToolRequestRegistry] Target change listener threw:",t)}}dispose(){this.targets.clear(),this.changeListeners.clear()}},KU=e=>`No assessment is bound, so no policy source could grant "${e}"`;function ZI(e,t,r,n){return{featureId:e,granted:!1,action:"block",rule:t,precedence:0,sourceType:"host",reason:t==="host-blocked"?"Listed in tools.policy.blocked":`Not listed in tools.policy.allowed (${r.join(", ")})`,required:!1,assessmentBound:n.assessmentBound}}function XU(e,t,r){let n=t.decisions[0],i=Array.from(t.perToolFlags.values())[0],o=n?.action==="enable",s=n?.reason??`Feature "${e}" not configured`;return{featureId:e,granted:o,action:n?.action??"skip",rule:n?.rule??"pnp-support",precedence:n?.precedence??6,sourceType:n?.sourceType??"system",reason:r.assessmentBound||o?s:KU(e),required:!!i?.required,parameters:i?.settings,assessmentBound:r.assessmentBound}}var ZU=class{constructor(e){T(this,"provenance",void 0),T(this,"stepCounter",0),this.provenance={contextId:e,resolvedAt:new Date,sources:{},features:new Map,decisionLog:[],summary:{totalFeatures:0,enabled:0,blocked:0,notConfigured:0,bySource:{},byRule:{}}}}addSource(e,t){let r={id:t.id,name:t.name??t.id};switch(e){case"organization":this.provenance.sources.organization={...r,pnpDefaults:t.config};break;case"assessment":this.provenance.sources.assessment={...r,settings:t.config};break;case"section":this.provenance.sources.section={...r,settings:t.config};break;case"item":this.provenance.sources.item={...r,settings:t.config};break;case"student":this.provenance.sources.student={id:t.id,pnpProfile:t.config};break;case"host":this.provenance.sources.host={id:t.id,config:t.config}}return this}addDecision(e){let t={step:++this.stepCounter,precedence:e.precedence,rule:e.rule,featureId:e.featureId,action:e.action,source:{type:e.sourceType,id:e.sourceId,name:e.sourceName},reason:e.reason,value:e.value,timestamp:new Date};this.provenance.decisionLog.push(t);let r=this.provenance.features.get(e.featureId);return r||(r={featureId:e.featureId,finalState:"not-configured",allDecisions:[],explanation:""},this.provenance.features.set(e.featureId,r)),r.allDecisions.push(t),e.action==="advisory"?r.finalState==="not-configured"&&(r.finalState="advisory-only"):e.action!=="skip"&&(!r.winningDecision||t.precedence<r.winningDecision.precedence)&&(r.winningDecision=t,r.finalState=t.action==="enable"?"enabled":"blocked"),this.provenance.summary.bySource[e.sourceType]=(this.provenance.summary.bySource[e.sourceType]||0)+1,this.provenance.summary.byRule[e.rule]=(this.provenance.summary.byRule[e.rule]||0)+1,this}reconcileFinalStates(e){for(let t of e){let r=this.provenance.features.get(t);if(!r){r={featureId:t,finalState:"enabled",allDecisions:[],explanation:""},this.provenance.features.set(t,r);continue}r.finalState="enabled"}for(let t of this.provenance.features.values()){if(e.has(t.featureId))continue;let r=t.allDecisions.some(i=>i.action!=="skip"&&i.action!=="advisory"),n=t.allDecisions.some(i=>i.action==="advisory");r?t.finalState="blocked":n?t.finalState="advisory-only":t.finalState="not-configured"}return this}build(){for(let e of this.provenance.features.values())e.explanation=YU(e);for(let e of this.provenance.features.values())this.provenance.summary.totalFeatures++,e.finalState==="enabled"?this.provenance.summary.enabled++:e.finalState==="blocked"?this.provenance.summary.blocked++:this.provenance.summary.notConfigured++;return this.provenance}};function YU(e){if(!e.winningDecision){if(e.finalState==="advisory-only"){let o=e.allDecisions.find(s=>s.action==="advisory");return o?`Feature "${e.featureId}" was kept in its host-decided state; ${o.reason}`:`Feature "${e.featureId}" carries an advisory note.`}return`Feature "${e.featureId}" was not configured at any level.`}let t=e.winningDecision,r=t.source.name||t.source.type,n=`Feature "${e.featureId}" is ${e.finalState}.
1530
+
1531
+ `;n+=`**Primary Reason** (${t.rule}):
1532
+ `,n+=`${t.reason}
1533
+ `,n+=`Source: ${r} (${t.source.type})
1534
+ `;let i=e.allDecisions.filter(o=>o.step!==t.step&&o.action!=="skip"&&o.action!=="advisory"&&o.precedence>t.precedence);if(i.length>0){n+=`
1535
+ **Overridden Rules**:
1536
+ `;for(let o of i)n+=`- ${o.rule}: ${o.reason}
1537
+ `}return n}function JU(e){let{request:t,tools:r,pnpPolicy:n,customSources:i,contextId:o}=e,s=new ZU(o);s.addSource("host",{id:t.scope.scopeId,name:`${t.level}:${t.scope.scopeId}`,config:{placement:r.placement,policy:r.policy}});let a=bi(r.placement[t.level]),l=bi(r.policy.allowed),d=new Set(bi(r.policy.blocked)),c=[];for(let w of a)c.push(w),s.addDecision({precedence:0,rule:"placement-membership",featureId:w,action:"skip",sourceType:"host",reason:`Listed in tools.placement.${t.level}`});if(c=c.filter(w=>r.providers?.[w]?.enabled===!1?(s.addDecision({precedence:0,rule:"provider-disabled",featureId:w,action:"block",sourceType:"host",reason:`tools.providers.${w}.enabled === false`,value:!1}),!1):!0),l.length>0){let w=new Set(l);c=c.filter(I=>w.has(I)?!0:(s.addDecision({precedence:0,rule:"host-allowlist",featureId:I,action:"block",sourceType:"host",reason:"Not present in tools.policy.allowed",value:l}),!1))}c=c.filter(w=>d.has(w)?(s.addDecision({precedence:0,rule:"host-blocked",featureId:w,action:"block",sourceType:"host",reason:"Listed in tools.policy.blocked",value:r.policy.blocked}),!1):!0);let u=[],f=new Map;for(let w of c)f.set(w,["placement"]);let p=new Set(c),g=null;if(n.enforcement==="on"&&n.source&&(n.assessment||n.currentItemRef)){g=n.source.apply({assessment:n.assessment,currentItemRef:n.currentItemRef}),g.sources.assessment&&s.addSource("assessment",g.sources.assessment),g.sources.student&&s.addSource("student",g.sources.student),g.sources.item&&s.addSource("item",g.sources.item);for(let w of g.decisions)s.addDecision({precedence:w.precedence,rule:w.rule,featureId:w.featureId,action:w.action,sourceType:w.sourceType,reason:w.reason,value:w.value});for(let w of g.unmappedSupportIds)u.push({code:"tool-policy.unknownSupportId",level:t.level,toolId:w,message:`No registered tool claims PNP support id "${w}"; it was carried through as a feature id and matched nothing. Expected an AfA 3.0 / QTI 3.0 access feature id.`,source:"pnp.pnp-support"});c=c.filter(w=>!g.blockedToolIds.has(w));for(let w of Array.from(f.keys()))g.blockedToolIds.has(w)&&f.delete(w);for(let w of g.mandatedToolIds){if(p.has(w))continue;let I=g.perToolFlags.get(w)?.rule??"required-tool",x=QU(w,{placement:a,allowed:l,blocked:d,providers:r.providers}),C={rule:I,hostRule:x.hostRule,hostValue:x.hostValue};u.push({code:"tool-policy.requiredToolBlocked",level:t.level,toolId:w,message:`Profile policy mandates "${w}" (${I}) but host policy removed it from level "${t.level}" via ${x.hostRule}.`,details:C}),s.addDecision({precedence:0,rule:"required-tool-blocked",featureId:w,action:"advisory",sourceType:"host",reason:`Host removed required tool "${w}" via ${x.hostRule}`,value:C})}for(let w of c){let I=g.perToolFlags.get(w);if(I){let x=f.get(w)??[];x.push(`pnp.${I.rule}`),f.set(w,x)}}}for(let w=0;w<i.length;w++){let I=i[w],x=c.slice(),C=I.refine({request:t,candidates:x}),L=new Set(C.refinedCandidates);for(let M of C.refinedCandidates)x.includes(M)||(u.push({code:"tool-policy.placementMissing",level:t.level,toolId:M,message:`Custom source "${I.id}" tried to add tool "${M}" that was not in candidates; ignored.`,source:`custom.${I.id}`}),L.delete(M));c=x.filter(M=>L.has(M));let E=new Set;if(C.decisions)for(let M of C.decisions)s.addDecision({precedence:M.precedence??100+w,rule:M.rule,featureId:M.featureId,action:M.action,sourceType:M.sourceType,reason:M.reason,value:M.value}),M.action==="block"&&E.add(M.featureId);for(let M of x)L.has(M)||E.has(M)||s.addDecision({precedence:100+w,rule:"custom-source",featureId:M,action:"block",sourceType:"custom",reason:`Custom policy source "${I.id}" removed tool "${M}" from candidates without emitting a decision; auto-logged for trail completeness.`,value:{customSourceId:I.id}});for(let M of c){let U=f.get(M)??["placement"];U.push(`custom.${I.id}`),f.set(M,U)}for(let M of x)L.has(M)||f.delete(M)}let v=new Set(c),b=c.map(w=>{let I=g?.perToolFlags.get(w);return{toolId:w,required:I?.required??!1,alwaysAvailable:I?.alwaysAvailable??!1,settings:I?.settings,sources:f.get(w)??["placement"]}});return s.reconcileFinalStates(v),{visibleTools:b,diagnostics:u,provenance:s.build()}}function QU(e,t){return t.placement.includes(e)?t.providers?.[e]?.enabled===!1?{hostRule:"provider-disabled",hostValue:!1}:t.allowed.length>0&&!t.allowed.includes(e)?{hostRule:"host-allowlist",hostValue:t.allowed}:t.blocked.has(e)?{hostRule:"host-blocked",hostValue:Array.from(t.blocked)}:{hostRule:"placement-missing",hostValue:t.placement}:{hostRule:"placement-missing",hostValue:t.placement}}function e9(e){if(!e)return!1;let t=e.personalNeedsProfile;if(t&&(Array.isArray(t.supports)&&t.supports.length>0||Array.isArray(t.prohibitedSupports)&&t.prohibitedSupports.length>0||Array.isArray(t.activateAtInit)&&t.activateAtInit.length>0))return!0;let r=e.settings;if(r){let n=r.districtPolicy;if(n&&(Array.isArray(n.blockedTools)&&n.blockedTools.length>0||Array.isArray(n.requiredTools)&&n.requiredTools.length>0||n.policies&&typeof n.policies=="object"&&Object.keys(n.policies).length>0))return!0;let i=r.testAdministration;if(i&&typeof i=="object")for(let o of Object.keys(i)){let s=i[o];if(s!=null&&!(Array.isArray(s)&&s.length===0)&&!(typeof s=="object"&&!Array.isArray(s)&&Object.keys(s).length===0))return!0}}return!1}function t9(e){let t=e?.settings;return t?!!(Array.isArray(t.requiredTools)&&t.requiredTools.length>0||Array.isArray(t.restrictedTools)&&t.restrictedTools.length>0||t.toolParameters&&typeof t.toolParameters=="object"&&Object.keys(t.toolParameters).length>0):!1}function q_(e){return e9(e.assessment)||t9(e.currentItemRef)?"on":"off"}var YI=class{constructor(e){T(this,"id","pnp"),T(this,"toolRegistry",void 0),this.toolRegistry=e}apply(e){let{ctx:t,result:r}=this.prepare(e),{pnp:n,districtPolicy:i,itemSettings:o}=t,s=new Set;n?.supports?.forEach(a=>s.add(a)),n?.prohibitedSupports?.forEach(a=>s.add(a)),i?.blockedTools?.forEach(a=>s.add(a)),i?.requiredTools?.forEach(a=>s.add(a)),o?.requiredTools?.forEach(a=>s.add(a)),o?.restrictedTools?.forEach(a=>s.add(a));for(let a of s)this.resolveSupport(a,t,r);return r}resolveFeature(e,t){let{ctx:r,result:n}=this.prepare(t);return this.resolveSupport(e,r,n),n}prepare(e){let{assessment:t,currentItemRef:r}=e,n=t?.personalNeedsProfile,i=t?.settings,o=r?.settings,s={blockedToolIds:new Set,mandatedToolIds:new Set,perToolFlags:new Map,decisions:[],unmappedSupportIds:new Set,sources:{}};return(i?.districtPolicy||i?.testAdministration)&&(s.sources.assessment={id:t?.id||"unknown",name:t?.name||t?.id||"Assessment",config:i}),n&&(s.sources.student={id:"student",name:"Student PNP Profile",config:n}),r&&o&&(s.sources.item={id:r.identifier,name:r.identifier,config:o}),{ctx:{pnp:n,districtPolicy:i?.districtPolicy,testAdmin:i?.testAdministration,itemSettings:o,toolConfigs:i?.toolConfigs},result:s}}resolveSupport(e,t,r){if(t.districtPolicy?.blockedTools?.includes(e)){let i=this.mapSupportToToolId(e,r);r.blockedToolIds.add(i),r.decisions.push({precedence:1,rule:"district-block",featureId:i,action:"block",sourceType:"assessment",reason:`District policy blocks "${e}" for all assessments`,value:t.districtPolicy.blockedTools});return}if(t.testAdmin?.toolOverrides?.[e]===!1){let i=this.mapSupportToToolId(e,r);r.blockedToolIds.add(i),r.decisions.push({precedence:2,rule:"test-admin-override",featureId:i,action:"block",sourceType:"assessment",reason:`Test administrator disabled "${e}" for this session`,value:t.testAdmin.toolOverrides});return}if(t.itemSettings?.restrictedTools?.includes(e)){let i=this.mapSupportToToolId(e,r);r.blockedToolIds.add(i),r.decisions.push({precedence:3,rule:"item-restriction",featureId:i,action:"block",sourceType:"item",reason:`Item restricts "${e}" (e.g., mental math question blocks calculator)`,value:t.itemSettings.restrictedTools});return}if(t.itemSettings?.requiredTools?.includes(e)){let i=this.mapSupportToToolId(e,r);r.mandatedToolIds.add(i),r.perToolFlags.set(i,{required:!0,alwaysAvailable:!1,settings:this.resolveToolSettings(e,t),rule:"item-requirement",sourceType:"item"}),r.decisions.push({precedence:4,rule:"item-requirement",featureId:i,action:"enable",sourceType:"item",reason:`Item requires "${e}" for this question`,value:t.itemSettings.requiredTools});return}if(t.districtPolicy?.requiredTools?.includes(e)){let i=this.mapSupportToToolId(e,r);r.mandatedToolIds.add(i),r.perToolFlags.set(i,{required:!0,alwaysAvailable:!1,settings:this.resolveToolSettings(e,t),rule:"district-requirement",sourceType:"assessment"}),r.decisions.push({precedence:5,rule:"district-requirement",featureId:i,action:"enable",sourceType:"assessment",reason:`District policy requires "${e}" for all assessments`,value:t.districtPolicy.requiredTools});return}if(t.pnp?.prohibitedSupports?.includes(e)){let i=this.mapSupportToToolId(e,r);r.blockedToolIds.add(i),r.decisions.push({precedence:6,rule:"pnp-prohibited",featureId:i,action:"block",sourceType:"student",reason:`Student PNP profile prohibits "${e}"`,value:t.pnp.prohibitedSupports});return}if(t.pnp?.supports?.includes(e)){let i=this.mapSupportToToolId(e,r);r.perToolFlags.set(i,{required:!1,alwaysAvailable:!0,settings:this.resolveToolSettings(e,t),rule:"pnp-support",sourceType:"student"}),r.decisions.push({precedence:6,rule:"pnp-support",featureId:i,action:"enable",sourceType:"student",reason:`Student PNP profile requests "${e}"`,value:t.pnp.supports});return}let n=this.mapSupportToToolId(e,r);r.decisions.push({precedence:6,rule:"pnp-support",featureId:n,action:"skip",sourceType:"system",reason:`Feature "${e}" not configured at any level`,value:{supportId:e}})}mapSupportToToolId(e,t){let r=this.toolRegistry.getToolsByPNPSupport(e);return r.size===0?(this.toolRegistry.getAllTools().length>0&&t.unmappedSupportIds.add(e),e):Array.from(r)[0]}resolveToolSettings(e,t){return t.itemSettings?.toolParameters?.[e]??t.toolConfigs?.[e]}},JI=Lb({policy:{allowed:[],blocked:[]},placement:{section:[],item:[],passage:[]},providers:{}}),r9=class{constructor(e){T(this,"toolRegistry",void 0),T(this,"contextId",void 0),T(this,"pnpPolicySource",void 0),T(this,"customSources",void 0),T(this,"listeners",new Set),T(this,"tools",void 0),T(this,"assessment",void 0),T(this,"currentItemRef",void 0),T(this,"pnpEnforcement",void 0),T(this,"disposed",!1),this.toolRegistry=e.toolRegistry,this.contextId=e.contextId??"tool-policy",this.pnpPolicySource=new YI(this.toolRegistry),this.customSources=e.customSources?[...e.customSources]:[];let t=e.inputs??{};this.tools=t.tools??JI,this.assessment=t.assessment??null,this.currentItemRef=t.currentItemRef??null,this.pnpEnforcement=t.pnpEnforcement??q_({assessment:this.assessment,currentItemRef:this.currentItemRef})}decide(e){this.assertNotDisposed();let t=e.scope.scopeId?`${this.contextId}:${e.level}:${e.scope.scopeId}`:`${this.contextId}:${e.level}`;return JU({request:e,tools:this.tools,pnpPolicy:{source:this.pnpPolicySource,assessment:this.assessment??void 0,currentItemRef:this.currentItemRef??void 0,enforcement:this.pnpEnforcement},customSources:this.customSources,contextId:t})}decideFeature(e){this.assertNotDisposed();let t=this.hostFeatureGate(e);return t||XU(e,this.pnpPolicySource.resolveFeature(e,{assessment:this.assessment??void 0,currentItemRef:this.currentItemRef??void 0}),{assessmentBound:this.assessment!==null})}hostFeatureGate(e){let t={assessmentBound:this.assessment!==null},r=bi(this.tools.policy.blocked);if(r.includes(e))return ZI(e,"host-blocked",r,t);let n=bi(this.tools.policy.allowed);return n.length>0&&!n.includes(e)?ZI(e,"host-allowlist",n,t):null}getVisibleToolIds(e,t){return this.decide({level:e,scope:{level:e,scopeId:t}}).visibleTools.map(r=>r.toolId)}updateInputs(e){this.assertNotDisposed();let t=!1,r=!1;if("tools"in e){let n=e.tools??JI;Object.is(this.tools,n)||(this.tools=n,t=!0)}if("assessment"in e){let n=e.assessment??null;Object.is(this.assessment,n)||(this.assessment=n,t=!0)}if("currentItemRef"in e){let n=e.currentItemRef??null;Object.is(this.currentItemRef,n)||(this.currentItemRef=n,t=!0)}"pnpEnforcement"in e&&e.pnpEnforcement&&this.pnpEnforcement!==e.pnpEnforcement&&(this.pnpEnforcement=e.pnpEnforcement,r=!0),(t||r)&&this.emit({reason:r&&!t?"pnp-enforcement":"inputs",inputs:this.snapshotInputs()})}replaceToolRegistry(e,t){this.assertNotDisposed(),this.toolRegistry=e,this.pnpPolicySource=new YI(e),this.tools=t,this.emit({reason:"inputs",inputs:this.snapshotInputs()})}registerPolicySource(e){return this.assertNotDisposed(),this.customSources.push(e),this.emit({reason:"policy-source-added",inputs:this.snapshotInputs()}),()=>{let t=this.customSources.indexOf(e);t!==-1&&(this.customSources.splice(t,1),!this.disposed&&this.emit({reason:"policy-source-removed",inputs:this.snapshotInputs()}))}}onPolicyChange(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}getInputs(){return this.snapshotInputs()}dispose(){this.disposed||(this.disposed=!0,this.emit({reason:"disposed",inputs:this.snapshotInputs()}),this.listeners.clear(),this.customSources.length=0)}snapshotInputs(){return Object.freeze({tools:this.tools,assessment:this.assessment,currentItemRef:this.currentItemRef,pnpEnforcement:this.pnpEnforcement})}emit(e){for(let t of Array.from(this.listeners))try{t(e)}catch{}}assertNotDisposed(){if(this.disposed)throw Error("ToolPolicyEngine has been disposed.")}},ko=class extends Error{constructor(){super("ToolkitCoordinator has been disposed."),this.name="ToolkitCoordinatorDisposedError"}},QI=class extends Error{constructor(){super("Section controller acquisition was retired during initialization."),this.name="SectionControllerRetiredError"}},ah=e=>!!e&&typeof e=="object"&&!Array.isArray(e),n9=(e,t,r)=>{let n={...t,...r};return e==="textToSpeech"&&ah(t.settings)&&ah(r.settings)&&(n.settings={...t.settings,...r.settings},ah(t.settings.mathSpeech)&&ah(r.settings.mathSpeech)&&(n.settings.mathSpeech={...t.settings.mathSpeech,...r.settings.mathSpeech})),n},i9=["item-selected","item-session-data-changed","item-session-meta-changed","item-complete-changed","content-loaded","item-player-error"],o9=["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"],s9=class{resolveConfig(e){let t=n_(e.toolConfigStrictness),r=e.toolRegistry??new Lv,n=e.deferToolConfigValidation===!0?Lb(e.tools):this.validateToolsConfig(e.tools,{strictness:t,source:"ToolkitCoordinator.init",toolRegistry:r});return{...e,toolConfigStrictness:t,toolRegistry:r,tools:{...n,providers:{textToSpeech:{enabled:!0,backend:"browser"},annotationToolbar:{enabled:!0},...n.providers}},accessibility:{language:"en-US",...e.accessibility??{},catalogs:e.accessibility?.catalogs??[]}}}validateToolsConfig(e,t){let{config:r,diagnostics:n}=i_(e,t.toolRegistry),i=this.reportedRegistryUnavailable||!this.toolRegistrySettled?n.filter(o=>o.code!=="tools.registryUnavailable"):n;return o_(i,t),t.strictness!=="off"&&i.some(o=>o.code==="tools.registryUnavailable")&&(this.reportedRegistryUnavailable=!0),r}constructor(e){if(T(this,"assessmentId",void 0),T(this,"config",void 0),T(this,"ttsService",void 0),T(this,"toolCoordinator",void 0),T(this,"highlightCoordinator",void 0),T(this,"elementToolStateStore",void 0),T(this,"catalogResolver",void 0),T(this,"toolProviderRegistry",void 0),T(this,"hooks",void 0),T(this,"lazyInit",void 0),T(this,"ttsInitialized",!1),T(this,"ttsInitPromise",void 0),T(this,"ttsReconfigurePromise",void 0),T(this,"stateLoaded",!1),T(this,"stateLoadPromise",void 0),T(this,"coordinatorReadyPromise",void 0),T(this,"coordinatorReadyNotified",!1),T(this,"providerInitPromises",new Map),T(this,"toolRegistry",void 0),T(this,"toolRegistrySupplied",void 0),T(this,"toolRegistrySettled",void 0),T(this,"toolContextResolvers",new Map),T(this,"toolContextResolverChangeListeners",new Set),T(this,"toolRequests",new GU),T(this,"sectionControllers",new Map),T(this,"sectionControllerKeys",new Map),T(this,"sectionControllerInitEntries",new Map),T(this,"sectionControllerDisposePromises",new Map),T(this,"sectionPersistenceStrategies",new Map),T(this,"sectionControllerLifecycleListeners",new Set),T(this,"activeSubscriptions",new Map),T(this,"activeCohortMapKey",null),T(this,"latestRequestedActiveCohortMapKey",null),T(this,"telemetryListeners",new Set),T(this,"frameworkErrorBus",void 0),T(this,"ownsFrameworkErrorBus",void 0),T(this,"frameworkErrorHookUnsubscribe",null),T(this,"disposePromise",null),T(this,"policyEngine",void 0),T(this,"pnpEnforcementOverride",null),T(this,"boundAssessment",null),T(this,"boundCurrentItemRef",null),T(this,"reportedUnboundFeaturePolicy",!1),T(this,"reportedMissingTTSProvider",!1),T(this,"heldMissingTTSProviderBackend",null),T(this,"reportedRegistryUnavailable",!1),!e.assessmentId)throw Error("ToolkitCoordinator requires assessmentId in config");this.toolRegistrySupplied=e.toolRegistry!=null,this.toolRegistrySettled=this.toolRegistrySupplied;let t=this.resolveConfig(e);this.assessmentId=t.assessmentId,this.config=t,this.toolRegistry=t.toolRegistry??new Lv,this.installToolContextResolvers(t.toolContextResolvers),this.hooks=t.hooks??{},this.lazyInit=e.lazyInit===!0,this.pnpEnforcementOverride=this.resolveConfiguredPnpEnforcement(),this.frameworkErrorBus=e.frameworkErrorBus??new u_,this.ownsFrameworkErrorBus=!e.frameworkErrorBus,this.subscribeFrameworkErrorHookAdapters(),this.toolCoordinator=new NW,this.highlightCoordinator=new yw,this.elementToolStateStore=new $W,this.catalogResolver=new MW(t.accessibility?.catalogs||[],t.accessibility?.language||"en-US"),this.toolProviderRegistry=new VU,this._registerToolProviders(),this.ttsService=new W_,this.ttsService.setHighlightCoordinator(this.highlightCoordinator),this.setupStatePersistenceHooks(),this.policyEngine=new r9({toolRegistry:this.toolRegistry,contextId:`toolkit-coordinator:${this.assessmentId}`,inputs:{tools:this.config.tools,assessment:null,currentItemRef:null,pnpEnforcement:this.resolveEffectivePnpEnforcement()}}),!this.lazyInit&&this.waitUntilReady().catch(r=>{r instanceof ko||(console.error("[ToolkitCoordinator] Failed eager initialization:",r),this.handleError(r,{phase:"coordinator-ready"}))})}assertNotDisposed(){if(this.disposePromise!==null)throw new ko}subscribeFrameworkErrorHookAdapters(){this.frameworkErrorHookUnsubscribe=this.frameworkErrorBus.subscribeFrameworkErrors(e=>{let t=this.hooks.onFrameworkError;if(t)try{t(e)}catch(r){console.warn("[ToolkitCoordinator] onFrameworkError hook failed:",r)}})}async emitTelemetry(e,t){try{await this.hooks.onTelemetry?.(e,t)}catch(n){console.warn("[ToolkitCoordinator] telemetry hook failed:",n)}let r=t?{...t}:void 0;for(let n of this.telemetryListeners)try{n({eventName:e,payload:r?{...r}:void 0})}catch(i){console.warn("[ToolkitCoordinator] telemetry listener failed:",i)}}emitSectionControllerLifecycle(e){for(let t of this.sectionControllerLifecycleListeners)try{t(e)}catch(r){console.warn("[ToolkitCoordinator] section controller lifecycle listener failed:",r)}}handleError(e,t){let r=vW({error:e,context:t});this.frameworkErrorBus.reportFrameworkError(r)}subscribeFrameworkErrors(e){return this.frameworkErrorBus.subscribeFrameworkErrors(e)}reportFrameworkError(e){this.frameworkErrorBus.reportFrameworkError(e)}getSectionControllerMapKey(e){return`${e.assessmentId}::${e.sectionId}::${e.attemptId||""}`}createDefaultSectionPersistence(){let e=(()=>{try{return typeof window>"u"?null:window.localStorage}catch{return null}})(),t=r=>{let{assessmentId:n,sectionId:i,attemptId:o}=r.key;return`pie:section-controller:v1:${n}:${i}:${o||"default"}`};return{async loadSession(r){if(!e)return null;let n=e.getItem(t(r));if(!n)return null;try{return JSON.parse(n)}catch{return null}},async saveSession(r,n){e&&e.setItem(t(r),JSON.stringify(n))},async clearSession(r){e&&e.removeItem(t(r))}}}async resolveSectionPersistence(e){let t=this.getSectionControllerMapKey(e.key),r=this.sectionPersistenceStrategies.get(t);if(r)return r;let n={createDefaultPersistence:()=>this.createDefaultSectionPersistence()},i=await this.hooks.createSectionSessionPersistence?.(e,n)??await n.createDefaultPersistence();return this.sectionPersistenceStrategies.set(t,i),i}setupStatePersistenceHooks(){this.elementToolStateStore.setOnStateChange(e=>{this.hooks.saveToolState&&Promise.resolve(this.hooks.saveToolState(e)).catch(t=>{this.handleError(t,{phase:"state-save"})})})}async ensureStateLoaded(){if(!this.stateLoaded)return this.stateLoadPromise?this.stateLoadPromise:(this.stateLoadPromise=(async()=>{let e=this.hooks.loadToolState;if(e)try{let t=await e();this.assertNotDisposed(),t&&typeof t=="object"&&this.elementToolStateStore.loadState(t),this.stateLoaded=!0,await this.emitTelemetry("pie-toolkit-tool-state-loaded",{hasState:!!t})}catch(t){if(t instanceof ko)throw t;this.handleError(t,{phase:"state-load"})}})().finally(()=>{this.stateLoadPromise=void 0}),this.stateLoadPromise)}reportMissingTTSProvider(e){if(!this.toolRegistrySettled){this.heldMissingTTSProviderBackend=e;return}this.reportedMissingTTSProvider||(this.reportedMissingTTSProvider=!0,console.warn(`[ToolkitCoordinator] Text-to-speech is configured for the "${e}" backend but falls back to browser speech: no "tts" tool provider is registered. A coordinator registers tool providers only from its \`toolRegistry\`, or from its toolkit's when constructed without one, so supply one that carries the text-to-speech registration — for the packaged capability set, \`createPackagedToolRegistry()\` from "@pie-players/pie-default-tool-loaders". Reported once per coordinator.`))}adoptToolRegistry(e){if(this.disposePromise!==null||this.toolRegistrySettled)return!1;this.toolRegistrySettled=!0;let t=this.heldMissingTTSProviderBackend;this.heldMissingTTSProviderBackend=null;let r=this.config.toolConfigStrictness??"error",n="ToolkitCoordinator.adoptToolRegistry";if(!e)return this.validateToolsConfig(this.config.tools,{strictness:r,source:n,toolRegistry:this.toolRegistry}),t&&this.reportMissingTTSProvider(t),!1;this.toolRegistry=e,this.config.toolRegistry=e;try{this.config.tools=this.validateToolsConfig(this.config.tools,{strictness:r==="off"?"off":"warn",source:n,toolRegistry:e})}catch(o){console.warn("[ToolkitCoordinator] Tool config does not validate against the adopted tool registry:",o)}this.policyEngine.replaceToolRegistry(e,this.config.tools);let i=this.ttsInitialized||this.ttsInitPromise!==void 0||this.ttsReconfigurePromise!==void 0;for(let o of this.getProviderDescriptorTools())i&&o.toolId==="textToSpeech"||this.registerProviderFromTool(o);return i&&this.scheduleTTSReconfigure(),!0}_registerToolProviders(){let e=this.getProviderDescriptorTools();for(let t of e)this.registerProviderFromTool(t)}getProviderDescriptorTools(){return this.toolRegistry.getAllTools().filter(e=>!!e.provider)}async registerProviderFromTool(e){let t=e.provider;if(!t)return;let r=null,n;try{let i=this.getToolConfig(e.toolId)||void 0;if(i?.enabled===!1||(r=iS(e,i),!r||this.toolProviderRegistry.has(r)))return;let o=t.createProvider(i),s=t.getInitConfig?.(i)??i?.provider?.init??{},a=this.addToolTelemetryReporter({toolId:e.toolId,providerId:r,initConfig:s}),l=this.createToolTelemetryForwarder({toolId:e.toolId,providerId:r}),d=t.getAuthFetcher?.(i)??i?.provider?.runtime?.authFetcher;n={provider:o,config:a,lazy:t.lazy??!0,authFetcher:d,onTelemetry:l}}catch(i){this.reportProviderRegisterFailure(i,r,e.toolId);return}await this.registerProvider(r,n)}createToolTelemetryForwarder(e){return async(t,r)=>{await this.emitTelemetry(t,{...r||{},toolId:e.toolId,providerId:e.providerId})}}addToolTelemetryReporter(e){let t=e.initConfig&&typeof e.initConfig=="object"?{...e.initConfig}:{},r=typeof t.onTelemetry=="function"?t.onTelemetry:null,n=this.createToolTelemetryForwarder({toolId:e.toolId,providerId:e.providerId});return t.onTelemetry=async(i,o)=>{r&&await r(i,o),await n(i,o)},t}async registerProvider(e,t){try{this.toolProviderRegistry.register(e,t);let r={providerId:e,providerName:t.provider.providerName};await this.hooks.onProviderRegistered?.(e,r),await this.emitTelemetry("pie-toolkit-provider-registered",{providerId:e,providerName:t.provider.providerName})}catch(r){this.reportProviderRegisterFailure(r,e)}}reportProviderRegisterFailure(e,t,r){console.warn(t?`[ToolkitCoordinator] Failed to register provider "${t}":`:`[ToolkitCoordinator] Failed to register the provider of tool "${r}":`,e),this.handleError(e,{phase:"provider-register",providerId:t??void 0})}async ensureProviderReady(e){this.assertNotDisposed();let t=this.providerInitPromises.get(e);if(t)return t;let r=(async()=>{let n=await this.toolProviderRegistry.getProvider(e,!1);this.assertNotDisposed();let i={providerId:e,providerName:n.providerName};try{return await this.hooks.onProviderInitStart?.(e,i),this.assertNotDisposed(),await this.toolProviderRegistry.initialize(e),this.assertNotDisposed(),await this.hooks.onProviderReady?.(e,i),this.assertNotDisposed(),await this.emitTelemetry("pie-toolkit-provider-ready",{providerId:e}),this.assertNotDisposed(),n}catch(o){if(o instanceof ko)throw o;let s=o instanceof Error?o:Error(String(o));throw this.handleError(s,{phase:"provider-init",providerId:e}),s}})().finally(()=>{this.providerInitPromises.delete(e)});return this.providerInitPromises.set(e,r),r}setHooks(e){Object.assign(this.hooks,e),this.setupStatePersistenceHooks(),this.disposePromise===null&&e.onCoordinatorReady&&this.isReady()&&Promise.resolve(e.onCoordinatorReady(this)).catch(t=>{this.handleError(t,{phase:"coordinator-ready"})})}subscribeTelemetry(e){return this.telemetryListeners.add(e),()=>{this.telemetryListeners.delete(e)}}getSectionController(e){let t={assessmentId:this.assessmentId,sectionId:e.sectionId,attemptId:e.attemptId};return this.sectionControllers.get(this.getSectionControllerMapKey(t))}subscribeSectionEvents(e){if(this.activeCohortMapKey===null)throw Error("[ToolkitCoordinator] subscribeSectionEvents requires an active section cohort; call getOrCreateSectionController first.");let t=this.activeSubscriptions.get(e.listener);t&&(t.unsubscribeCurrent?.(),t.unsubscribeCurrent=null);let r={listener:e.listener,eventTypes:e.eventTypes,itemIds:e.itemIds,unsubscribeCurrent:null};this.activeSubscriptions.set(e.listener,r);let n=this.sectionControllers.get(this.activeCohortMapKey);n&&this.bindSubscriptionToController(r,n);let i=!1;return()=>{i||(i=!0,r.unsubscribeCurrent?.(),r.unsubscribeCurrent=null,this.activeSubscriptions.get(e.listener)===r&&this.activeSubscriptions.delete(e.listener))}}bindSubscriptionToController(e,t){e.unsubscribeCurrent?.(),e.unsubscribeCurrent=null;let r=t.subscribe;if(typeof r!="function")return;let n=this.buildSectionEventPredicate(e);e.unsubscribeCurrent=r.call(t,s=>{n(s)&&this.deliverSectionEventSafely(e.listener,s)});let i=this.buildContentLoadedReplayEvents(t);for(let s of i)n(s)&&this.deliverSectionEventSafely(e.listener,s);let o=this.buildLoadingCompleteReplayEvent(t);o&&n(o)&&this.deliverSectionEventSafely(e.listener,o)}deliverSectionEventSafely(e,t){try{e(t)}catch(r){console.warn("[ToolkitCoordinator] section-event listener failed:",r)}}setActiveCohort(e){if(this.activeCohortMapKey===e)return;this.activeCohortMapKey=e;let t=this.sectionControllers.get(e);if(t)for(let r of Array.from(this.activeSubscriptions.values()))this.bindSubscriptionToController(r,t)}setActiveCohortIfLatestRequest(e){this.latestRequestedActiveCohortMapKey===e&&this.setActiveCohort(e)}suspendActiveCohortIfSuperseded(e){if(this.activeCohortMapKey!==null&&this.activeCohortMapKey!==e){this.activeCohortMapKey=null;for(let t of Array.from(this.activeSubscriptions.values()))t.unsubscribeCurrent?.(),t.unsubscribeCurrent=null}}clearActiveCohortIfMatches(e){if(this.activeCohortMapKey===e){this.activeCohortMapKey=null;for(let t of Array.from(this.activeSubscriptions.values()))t.unsubscribeCurrent?.(),t.unsubscribeCurrent=null}}buildSectionEventPredicate(e){let t=e.eventTypes?new Set(e.eventTypes):null,r=e.itemIds?new Set(e.itemIds):null;return n=>{if(t||r){let i=n?.type||null;if(t&&(!i||!t.has(i))||r&&!Array.from(this.collectEventItemIds(n)).some(o=>r.has(o)))return!1}return!0}}collectEventItemIds(e){let t=new Set;return"itemId"in e&&typeof e.itemId=="string"&&t.add(e.itemId),"canonicalItemId"in e&&typeof e.canonicalItemId=="string"&&t.add(e.canonicalItemId),"currentItemId"in e&&typeof e.currentItemId=="string"&&t.add(e.currentItemId),"previousItemId"in e&&typeof e.previousItemId=="string"&&t.add(e.previousItemId),t}buildContentLoadedReplayEvents(e){let t=e.getRuntimeState?.(),r=t?.loadedRenderables;if(!Array.isArray(r)||r.length===0)return[];let n=typeof t?.currentItemIndex=="number"&&Number.isFinite(t.currentItemIndex)?t.currentItemIndex:0,i=Date.now(),o=[];for(let s of r){if(!s)continue;let a=s.itemId,l=typeof s.canonicalItemId=="string"&&s.canonicalItemId?s.canonicalItemId:a;typeof a!="string"||!a||o.push({type:"content-loaded",contentKind:s.contentKind??"unknown",itemId:a,canonicalItemId:l,currentItemIndex:n,timestamp:i})}return o}buildLoadingCompleteReplayEvent(e){let t=e.getRuntimeState?.();if(t?.loadingComplete!==!0)return null;let r=typeof t.totalRegistered=="number"&&Number.isFinite(t.totalRegistered)?Math.max(0,t.totalRegistered):0;return{type:"section-loading-complete",totalRegistered:r,totalLoaded:typeof t.totalLoaded=="number"&&Number.isFinite(t.totalLoaded)?Math.max(0,t.totalLoaded):r,currentItemIndex:t.currentItemIndex,timestamp:Date.now()}}subscribeItemEvents(e){return this.subscribeSectionEvents({eventTypes:e.eventTypes||i9,itemIds:e.itemIds,listener:e.listener})}subscribeSectionLifecycleEvents(e){return this.subscribeSectionEvents({eventTypes:e.eventTypes||o9,listener:e.listener})}onSectionControllerLifecycle(e){return this.sectionControllerLifecycleListeners.add(e),()=>{this.sectionControllerLifecycleListeners.delete(e)}}async getOrCreateSectionController(e){if(this.disposePromise!==null)throw new ko;let t={assessmentId:this.assessmentId,sectionId:e.sectionId,attemptId:e.attemptId},r=this.getSectionControllerMapKey(t);this.latestRequestedActiveCohortMapKey=r,this.suspendActiveCohortIfSuperseded(r);let n=await this.resolveExistingSectionController({mapKey:r,key:t,input:e.input,updateExisting:e.updateExisting});if(n){if(this.disposePromise!==null)throw new ko;return n}let i=this.sectionControllerDisposePromises.get(r);if(i&&await Promise.allSettled([i]),this.disposePromise!==null)throw new ko;let o=this.sectionControllerInitEntries.get(r);if(o)return o.promise;let s={retired:!1,candidateClaimed:!1},a=this.initializeNewSectionController({args:e,key:t,mapKey:r,token:s}).catch(l=>{throw this.handleSectionControllerInitError(l,e),l}).finally(()=>{this.sectionControllerInitEntries.get(r)?.token===s&&this.sectionControllerInitEntries.delete(r)});return this.sectionControllerInitEntries.set(r,{key:t,token:s,promise:a}),a}async resolveExistingSectionController(e){let t=this.sectionControllers.get(e.mapKey);if(t&&(this.sectionControllerKeys.set(e.mapKey,e.key),e.updateExisting!==!1&&await t.updateInput?.(e.input),this.sectionControllers.get(e.mapKey)===t))return this.setActiveCohortIfLatestRequest(e.mapKey),t}createSectionControllerContext(e){return{key:e.key,coordinator:this,input:e.input}}async initializeNewSectionController(e){let t=this.createSectionControllerContext({key:e.key,input:e.args.input}),r=await this.resolveSectionPersistence(t);if(this.disposePromise!==null||e.token.retired)throw this.sectionPersistenceStrategies.get(e.mapKey)===r&&this.sectionPersistenceStrategies.delete(e.mapKey),this.createSectionControllerRetirementError();let n={createDefaultController:e.args.createDefaultController},i=await this.hooks.createSectionController?.(t,n)??await n.createDefaultController(),o={mapKey:e.mapKey,key:e.key,controller:i,persistence:r,token:e.token};try{return await this.retireUnpublishedSectionControllerIfNeeded(o),await i.configureSessionPersistence?.({strategy:r,context:t}),await this.retireUnpublishedSectionControllerIfNeeded(o),await i.initialize?.(e.args.input),await this.retireUnpublishedSectionControllerIfNeeded(o),await i.hydrate?.(),await this.finalizeSectionControllerReady({...o,context:t}),i}catch(s){throw await this.cleanupUnpublishedSectionController(o),s}}createSectionControllerRetirementError(){return this.disposePromise!==null?new ko:new QI}async retireUnpublishedSectionControllerIfNeeded(e){if(!(this.disposePromise===null&&!e.token.retired))throw await this.cleanupUnpublishedSectionController(e),this.createSectionControllerRetirementError()}async cleanupUnpublishedSectionController(e){if(!e.token.candidateClaimed){e.token.candidateClaimed=!0;try{await e.controller.dispose?.()}catch(t){this.handleError(t,{phase:"section-controller-dispose",details:{sectionId:e.key.sectionId,attemptId:e.key.attemptId}})}finally{this.sectionPersistenceStrategies.get(e.mapKey)===e.persistence&&this.sectionPersistenceStrategies.delete(e.mapKey)}}}retirePublishedSectionControllerIfNeeded(e){if(this.disposePromise!==null&&!e.token.retired&&this.disposeSectionController({sectionId:e.key.sectionId,attemptId:e.key.attemptId}),e.token.retired)throw this.createSectionControllerRetirementError()}async finalizeSectionControllerReady(e){await this.retireUnpublishedSectionControllerIfNeeded(e),this.sectionControllers.set(e.mapKey,e.controller),this.sectionControllerKeys.set(e.mapKey,e.key),e.token.candidateClaimed=!0,this.setActiveCohortIfLatestRequest(e.mapKey),this.emitSectionControllerLifecycle({type:"ready",key:e.key,controller:e.controller}),await this.hooks.onSectionControllerReady?.(e.context,e.controller),this.retirePublishedSectionControllerIfNeeded(e),await this.emitTelemetry("pie-toolkit-section-controller-ready",{assessmentId:e.key.assessmentId,sectionId:e.key.sectionId,attemptId:e.key.attemptId}),this.retirePublishedSectionControllerIfNeeded(e)}handleSectionControllerInitError(e,t){e instanceof ko||e instanceof QI||this.handleError(e,{phase:"section-controller-init",details:{sectionId:t.sectionId,attemptId:t.attemptId}})}disposeSectionController(e){let t={assessmentId:this.assessmentId,sectionId:e.sectionId,attemptId:e.attemptId},r=this.getSectionControllerMapKey(t),n=this.sectionControllerInitEntries.get(r);n&&(n.token.retired=!0);let i=this.sectionControllers.get(r);if(!i){let d=this.sectionControllerDisposePromises.get(r);if(d)return d;if(!n)return Promise.resolve();let c=Promise.allSettled([n.promise]).then(()=>{});return this.trackSectionControllerDisposal(r,c)}let o=this.sectionPersistenceStrategies.get(r);this.clearActiveCohortIfMatches(r),this.sectionControllers.get(r)===i&&(this.sectionControllers.delete(r),this.sectionControllerKeys.delete(r),this.sectionPersistenceStrategies.delete(r),this.emitSectionControllerLifecycle({type:"disposed",key:t}));let s=this.createSectionControllerContext({key:t,input:void 0}),a=this.disposeSectionControllerEntry({args:e,key:t,context:s,controller:i,persistenceStrategy:o}),l=n?Promise.allSettled([n.promise]).then(()=>a):a;return this.trackSectionControllerDisposal(r,l)}trackSectionControllerDisposal(e,t){this.sectionControllerDisposePromises.set(e,t);let r=()=>{this.sectionControllerDisposePromises.get(e)===t&&this.sectionControllerDisposePromises.delete(e)};return t.then(r,r),t}async disposeSectionControllerEntry(e){try{await this.runSectionControllerDisposePipeline({key:e.key,context:e.context,controller:e.controller,persistBeforeDispose:e.args.persistBeforeDispose})}catch(t){this.handleError(t,{phase:"section-controller-dispose",details:{sectionId:e.args.sectionId,attemptId:e.args.attemptId}})}finally{await this.finalizeSectionControllerDispose({context:e.context,persistenceStrategy:e.persistenceStrategy,clearPersistence:e.args.clearPersistence})}}async runSectionControllerDisposePipeline(e){let t=[];if(e.persistBeforeDispose!==!1)try{await e.controller.persist?.()}catch(r){t.push(r)}try{await e.controller.dispose?.()}catch(r){t.push(r)}if(t.length===1)throw t[0];if(t.length>1)throw AggregateError(t,"Section controller persistence and disposal both failed.");await this.hooks.onSectionControllerDispose?.(e.context,e.controller),await this.emitTelemetry("pie-toolkit-section-controller-disposed",{assessmentId:e.key.assessmentId,sectionId:e.key.sectionId,attemptId:e.key.attemptId})}async finalizeSectionControllerDispose(e){e.clearPersistence&&await e.persistenceStrategy?.clearSession?.(e.context)}dispose(){return this.disposePromise?this.disposePromise:(this.disposePromise=Promise.resolve().then(()=>this.disposeOwnedResources()),this.disposePromise)}async disposeOwnedResources(){let e=[],t=async n=>{try{await n()}catch(i){e.push(i)}};await this.waitForAdmittedInitialization();let r=new Map;for(let[n,i]of this.sectionControllerInitEntries)r.set(n,i.key);for(let[n,i]of this.sectionControllerKeys)r.set(n,i);for(let n of r.values())this.disposeSectionController({sectionId:n.sectionId,attemptId:n.attemptId});await Promise.allSettled(Array.from(this.sectionControllerDisposePromises.values())),this.sectionControllers.clear(),this.sectionControllerKeys.clear(),this.sectionControllerInitEntries.clear(),this.sectionPersistenceStrategies.clear();for(let n of this.activeSubscriptions.values())await t(()=>n.unsubscribeCurrent?.()),n.unsubscribeCurrent=null;this.activeSubscriptions.clear(),this.activeCohortMapKey=null,this.latestRequestedActiveCohortMapKey=null,await t(()=>this.ttsService.stop()),await t(()=>this.toolProviderRegistry.destroy()),await t(()=>this.highlightCoordinator.destroy());for(let n of this.toolCoordinator.getRegisteredTools())await t(()=>this.toolCoordinator.releaseTool(n));if(await t(()=>this.catalogResolver.destroy()),await t(()=>this.toolRequests.dispose()),await t(()=>this.policyEngine.dispose()),this.toolContextResolvers.clear(),this.toolContextResolverChangeListeners.clear(),this.sectionControllerLifecycleListeners.clear(),this.telemetryListeners.clear(),this.frameworkErrorHookUnsubscribe?.(),this.frameworkErrorHookUnsubscribe=null,this.ownsFrameworkErrorBus&&this.frameworkErrorBus.dispose(),e.length===1)throw e[0];if(e.length>1)throw AggregateError(e,"ToolkitCoordinator cleanup failed for multiple owned resources.")}async waitForAdmittedInitialization(){let e=new Set;this.coordinatorReadyPromise&&e.add(this.coordinatorReadyPromise),this.ttsInitPromise&&e.add(this.ttsInitPromise),this.ttsReconfigurePromise&&e.add(this.ttsReconfigurePromise);for(let t of this.providerInitPromises.values())e.add(t);await Promise.allSettled(e)}async ensureTTSReady(e){if(this.assertNotDisposed(),await this.waitForPendingTTSReconfigure(),this.assertNotDisposed(),!this.ttsInitialized)return this.ttsInitPromise?this.ttsInitPromise:(this.ttsInitPromise=this._initializeTTS(e).then(()=>this.assertNotDisposed()).finally(()=>{this.ttsInitPromise=void 0}),this.ttsInitPromise)}async waitForPendingTTSReconfigure(){let e=this.ttsReconfigurePromise;for(;e;)await e,e=this.ttsReconfigurePromise}async _initializeTTS(e){if(this.ttsInitialized)return;let t=zU(this.resolveTTSToolConfig(e)),r=U_(t),n=qU(t);if(await this.hooks.onBeforeTTSInit?.({phase:"tts-init",details:{backend:r}}),this.assertNotDisposed(),await this.emitTelemetry("pie-toolkit-tts-init-start",{backend:r}),await this.emitTelemetry("pie-tool-init-start",{toolId:"textToSpeech",operation:"tts-init",backend:r}),this.toolProviderRegistry.has("tts"))try{let o=await(await this.ensureProviderReady("tts")).createInstance();await this.initializeTTSService(o,n),await this.emitTelemetry("pie-toolkit-tts-init-success",{provider:"registry"}),await this.emitTelemetry("pie-tool-init-success",{toolId:"textToSpeech",operation:"tts-init",backend:r,provider:"registry"}),console.log("[ToolkitCoordinator] TTS initialized via ToolProviderRegistry");return}catch(o){if(o instanceof ko)throw o;let s=o instanceof Error?o:Error(String(o));await this.emitTelemetry("pie-tool-init-error",{toolId:"textToSpeech",providerId:"tts",operation:"tts-init",backend:r,errorType:"TTSRegistryInitError",message:s.message,recovered:!0}),await this.emitTelemetry("pie-tool-init-fallback",{toolId:"textToSpeech",providerId:"tts",operation:"tts-init",backend:r,fromProvider:"registry",toProvider:"browser",reason:s.message}),console.warn("[ToolkitCoordinator] Failed to initialize TTS via registry, falling back to browser provider:",s)}else r!=="browser"&&this.reportMissingTTSProvider(r);let i=new h_;try{await this.initializeTTSService(i,n),await this.emitTelemetry("pie-toolkit-tts-init-success",{provider:"browser-fallback"}),await this.emitTelemetry("pie-tool-init-success",{toolId:"textToSpeech",operation:"tts-init",backend:r,provider:"browser-fallback"})}catch(o){if(o instanceof ko)throw o;let s=o instanceof Error?o:Error(String(o));throw this.handleError(s,{phase:"tts-init"}),await this.emitTelemetry("pie-toolkit-tts-init-error",{message:s.message}),await this.emitTelemetry("pie-tool-init-error",{toolId:"textToSpeech",operation:"tts-init",backend:r,errorType:"TTSInitError",message:s.message}),s}}resolveTTSToolConfig(e){return e||this.getTTSConfigFromProviders()||{}}async initializeTTSService(e,t){let r={...t.providerOptions||{},__pieTelemetry:async(i,o)=>{await this.emitTelemetry(i,{toolId:"textToSpeech",...o||{}})}},n={...t,providerOptions:r};await this.ttsService.initialize(e,n),await this.ensureBrowserVoicesReady(e),this.assertNotDisposed(),this.ttsService.setCatalogResolver(this.catalogResolver),this.ttsInitialized=!0,await this.hooks.onTTSReady?.(),this.assertNotDisposed()}async ensureBrowserVoicesReady(e,t=1200){if(e.providerId!=="browser"||typeof window>"u"||!("speechSynthesis"in window))return;let r=window.speechSynthesis;if(r.getVoices().length>0)return;await new Promise(i=>{let o=!1,s=typeof r.addEventListener=="function"&&typeof r.removeEventListener=="function",a=!s&&"onvoiceschanged"in r,l=a?r.onvoiceschanged:null,d=!1,c=()=>{o||(o=!0,window.clearTimeout(f),s?r.removeEventListener("voiceschanged",u):d&&r.onvoiceschanged===u&&(r.onvoiceschanged=l),i())},u=p=>{!s&&typeof l=="function"&&p&&l.call(r,p),c()},f=window.setTimeout(c,t);s?r.addEventListener("voiceschanged",u,{once:!0}):a&&(r.onvoiceschanged=u,d=!0)});let n=r.getVoices();await this.emitTelemetry("pie-toolkit-tts-browser-voices-ready",{voiceCount:n.length,timedOut:n.length===0})}getServiceBundle(){return{ttsService:this.ttsService,toolCoordinator:this.toolCoordinator,highlightCoordinator:this.highlightCoordinator,elementToolStateStore:this.elementToolStateStore,catalogResolver:this.catalogResolver,toolProviderRegistry:this.toolProviderRegistry}}async getToolProvider(e){return this.ensureProviderReady(e)}async waitUntilReady(){if(this.assertNotDisposed(),!this.isReady())return this.coordinatorReadyPromise?this.coordinatorReadyPromise:(this.coordinatorReadyPromise=(async()=>{await this.ensureStateLoaded(),this.assertNotDisposed();let e=this.getTTSConfigFromProviders();e?.enabled!==!1&&await this.ensureTTSReady(e),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.getInitStatus().coordinator}getInitStatus(){let e={};for(let r of this.toolProviderRegistry.getProviderIds())e[r]=this.toolProviderRegistry.isInitialized(r);let t=this.getTTSConfigFromProviders();return{tts:this.ttsInitialized,stateLoaded:this.stateLoaded||!this.hooks.loadToolState,coordinator:(this.stateLoaded||!this.hooks.loadToolState)&&(this.ttsInitialized||t?.enabled===!1),providers:e}}getTTSConfigFromProviders(){return this.config.tools?.providers?.textToSpeech}assertCanonicalToolId(e){if(typeof e!="string"||e.trim().length===0)throw Error("Tool id must be a non-empty string.");if(e==="tts")throw Error('Tool id "tts" is no longer supported. Use "textToSpeech".');if(this.toolRegistry.getAllToolIds().length!==0&&!this.toolRegistry.get(e))throw Error(`Unknown tool id "${e}".`)}installToolContextResolvers(e){if(e){for(let[t,r]of Object.entries(e))if(r!=null){if(this.assertCanonicalToolId(t),typeof r!="function")throw Error(`Invalid tool context resolver for "${t}": expected a function.`);this.toolContextResolvers.set(t,r)}}}setToolContextResolvers(e){this.toolContextResolvers.clear(),this.installToolContextResolvers(e??void 0),this.notifyToolContextResolverChange()}notifyToolContextResolverChange(){for(let e of this.toolContextResolverChangeListeners)try{e()}catch(t){console.warn("[ToolkitCoordinator] Tool context resolver listener threw:",t)}}isToolEnabled(e){return this.assertCanonicalToolId(e),this.config.tools?.providers?.[e]?.enabled!==!1}getToolConfig(e){return this.assertCanonicalToolId(e),this.config.tools?.providers?.[e]||null}updateToolConfig(e,t){this.assertCanonicalToolId(e);let r=this.getToolConfig(e)||{};this.config.tools||(this.config.tools=this.validateToolsConfig(void 0,{strictness:this.config.toolConfigStrictness??"error",source:"ToolkitCoordinator.updateToolConfig",toolRegistry:this.toolRegistry})),this.config.tools.providers||(this.config.tools.providers={});let n={...this.config.tools.providers||{},[e]:n9(e,r,t)};this.config.tools=this.validateToolsConfig({...this.config.tools,providers:n},{strictness:this.config.toolConfigStrictness??"error",source:"ToolkitCoordinator.updateToolConfig",toolRegistry:this.toolRegistry}),this.policyEngine.updateInputs({tools:this.config.tools}),this.emitTelemetry("pie-toolkit-tool-config-updated",{toolId:e}),this._applyToolConfigChange(e,r)}updateToolPlacement(e,t){this.updateToolsPlacement({[e]:[...t]})}updateToolsPlacement(e){this.config.tools||(this.config.tools=this.validateToolsConfig(void 0,{strictness:this.config.toolConfigStrictness??"error",source:"ToolkitCoordinator.updateToolsPlacement",toolRegistry:this.toolRegistry}));let t=this.config.tools?.placement??{section:[],item:[],passage:[]},r={section:[...e.section??t.section??[]],item:[...e.item??t.item??[]],passage:[...e.passage??t.passage??[]]},n=this.validateToolsConfig({...this.config.tools,placement:r},{strictness:this.config.toolConfigStrictness??"error",source:"ToolkitCoordinator.updateToolsPlacement",toolRegistry:this.toolRegistry});n.placement=r,this.config.tools=n,this.policyEngine.updateInputs({tools:this.config.tools})}decideToolPolicy(e){return this.policyEngine.decide(e)}decideFeaturePolicy(e){let t=this.policyEngine.decideFeature(e),r=this.config.assessmentOptional!==!0||this.pnpEnforcementOverride==="on";return!t.assessmentBound&&r&&!this.reportedUnboundFeaturePolicy&&(this.reportedUnboundFeaturePolicy=!0,console.warn(`[ToolkitCoordinator] Feature policy was asked about "${e}" with no assessment bound, so every capability will be declined for want of a profile to read. Call updateAssessment(...) with the assessment (its personalNeedsProfile, settings.districtPolicy and settings.testAdministration are what policy reads) before relying on any accommodation. Reported once per coordinator.`)),t}onPolicyChange(e){return this.policyEngine.onPolicyChange(e)}onCatalogsChange(e){return this.catalogResolver.onCatalogsChange(e)}updateAssessment(e){this.boundAssessment=e,this.policyEngine.updateInputs({assessment:e,pnpEnforcement:this.resolveEffectivePnpEnforcement()})}updateCurrentItemRef(e){this.boundCurrentItemRef=e,this.policyEngine.updateInputs({currentItemRef:e,pnpEnforcement:this.resolveEffectivePnpEnforcement()})}setPnpEnforcement(e){this.pnpEnforcementOverride=e,this.policyEngine.updateInputs({pnpEnforcement:this.resolveEffectivePnpEnforcement()})}getPolicyInputs(){return this.policyEngine.getInputs()}registerPolicySource(e){return this.policyEngine.registerPolicySource(e)}registerToolContextResolver(e,t){if(this.assertCanonicalToolId(e),typeof t!="function")throw Error(`Invalid tool context resolver for "${e}": expected a function.`);return this.toolContextResolvers.set(e,t),this.notifyToolContextResolverChange(),()=>{this.toolContextResolvers.get(e)===t&&(this.toolContextResolvers.delete(e),this.notifyToolContextResolverChange())}}hasToolContextResolver(e){return this.assertCanonicalToolId(e),this.toolContextResolvers.has(e)}resolveToolContext(e){this.assertCanonicalToolId(e.toolId);let t=this.toolContextResolvers.get(e.toolId);if(!t)return null;let r;try{r=t(e)}catch(i){return console.error(`[ToolkitCoordinator] Tool context resolver for "${e.toolId}" threw:`,i),{toolId:e.toolId,visible:!1,params:{},reason:"Tool context resolver threw."}}if(!r)return{toolId:e.toolId,visible:!0,params:{}};let n=r.params&&typeof r.params=="object"&&!Array.isArray(r.params)?r.params:{};return{toolId:e.toolId,visible:r.visible!==!1,params:n,reason:typeof r.reason=="string"?r.reason:void 0}}onToolContextResolverChange(e){return this.toolContextResolverChangeListeners.add(e),()=>{this.toolContextResolverChangeListeners.delete(e)}}registerToolRequestTarget(e){return this.toolRequests.registerTarget(e)}requestTool(e){return this.assertCanonicalToolId(e.toolId),this.toolRequests.request(e)}canRequestTool(e,t){try{this.assertCanonicalToolId(e)}catch{return!1}return this.toolRequests.canRequest(e,t)}onToolRequestTargetsChange(e){return this.toolRequests.onTargetsChange(e)}resolveEffectivePnpEnforcement(){return this.pnpEnforcementOverride!==null?this.pnpEnforcementOverride:q_({assessment:this.boundAssessment,currentItemRef:this.boundCurrentItemRef})}resolveConfiguredPnpEnforcement(){return this.config.tools?.pnpEnforcement??null}_applyToolConfigChange(e,t){if(this.disposePromise===null)switch(e){case"textToSpeech":this.scheduleTTSReconfigure();break;case"answerEliminator":break;default:this._registerChangedToolProvider(e,t)}}_registerChangedToolProvider(e,t){let r=this.getProviderDescriptorTools().find(s=>s.toolId===e);if(!r)return;this.registerProviderFromTool(r);let n=s=>{try{return iS(r,s)}catch{return null}},i=n(t),o=n(this.getToolConfig(e)||void 0);!i||i===o||!this.toolProviderRegistry.has(i)||this.toolProviderRegistry.unregister(i).catch(s=>{console.warn(`[ToolkitCoordinator] Failed to unregister provider "${i}":`,s)})}scheduleTTSReconfigure(){let e=this.ttsInitPromise,t=e?e.catch(()=>{}).then(()=>this._reconfigureTTSProvider()):this._reconfigureTTSProvider();this.ttsReconfigurePromise=t,t.finally(()=>{this.ttsReconfigurePromise===t&&(this.ttsReconfigurePromise=void 0)}),t.then(async()=>{if(this.disposePromise!==null)return;let r=this.getTTSConfigFromProviders();!this.lazyInit&&r?.enabled!==!1&&await this.ensureTTSReady(r)})}async _reconfigureTTSProvider(){this.ttsInitialized=!1,this.ttsInitPromise=void 0;try{this.ttsService.stop()}catch{}if(this.toolProviderRegistry.has("tts")&&await this.toolProviderRegistry.unregister("tts"),this.disposePromise!==null)return;let e=this.getProviderDescriptorTools().find(t=>t.toolId==="textToSpeech");e&&await this.registerProviderFromTool(e)}},a9=()=>{};function l9(e){let{ttsService:t,listenerId:r,silence:n}=e;if(typeof t?.onStateChange!="function")return a9;let i=o=>{o!==hr.PLAYING&&o!==hr.LOADING||n()};return t.onStateChange(r,i),()=>{try{t.offStateChange?.(r,i)}catch{}}}function c9(e){try{e?.isPlaying?.()&&e.pause?.()}catch{}}var d9="pie-register",u9="pie-unregister",f9="pie-item-session-changed",h9="pie-content-loaded",p9="pie-item-player-error",m9="pie-formative-action",g9="pie-media-time-source",v9={bubbles:!0,composed:!0,cancelable:!1};function y9(e,t,r={}){return new CustomEvent(e,{detail:t,...v9,...r})}function ek(e,t,r,n={}){return e.dispatchEvent(y9(t,r,n))}function Tw(){return{phase:"idle",cohort:null,controllerResolved:!1,readinessSignals:{sectionReady:!1,interactionReady:!1,allLoadingComplete:!1,runtimeError:!1},effectiveRuntime:null,effectiveToolsConfig:null,loadingCompleteEmitted:!1,lastFrameworkError:null,itemCount:0,loadedCount:0}}function tk(e,t){return e===t?!0:!e||!t?!1:e.sectionId===t.sectionId&&e.attemptId===t.attemptId}function b9(e){return e.runtimeError?"error":e.allLoadingComplete?"ready":e.interactionReady?"interaction-ready":e.sectionReady?"loading":"bootstrapping"}function w9(e){let t=e.signals.sectionReady&&e.signals.allLoadingComplete,r=e.mode==="strict"?t:e.signals.interactionReady;return{phase:b9({...e.signals,allLoadingComplete:t,interactionReady:r}),interactionReady:r,allLoadingComplete:t,reason:e.reason}}function S9(e){switch(e){case"idle":return null;case"booting-section":return"composed";case"engine-ready":return"engine-ready";case"interactive":return"interactive";case"disposed":return"disposed"}}function Dp(e,t,r,n="entered"){let i=S9(t);i&&e.push({kind:"stage-change",stage:i,status:n,cohort:r})}function rk(e){let t={...Tw(),phase:"booting-section",cohort:e.cohort,effectiveRuntime:e.effectiveRuntime,effectiveToolsConfig:e.effectiveToolsConfig,itemCount:e.itemCount},r=[];return Dp(r,"booting-section",e.cohort),{state:t,outputs:r}}function I9(e,t){if(e.phase==="idle"||e.phase==="disposed")return{state:e,outputs:[]};let r=w9({mode:t.mode,signals:t.signals}),n=[],i=e.phase,o=e.loadingCompleteEmitted;return i==="engine-ready"&&r.interactionReady&&(i="interactive",Dp(n,i,e.cohort)),r.allLoadingComplete&&e.cohort&&!o&&(o=!0,n.push({kind:"loading-complete",cohort:e.cohort,itemCount:t.itemCount,loadedCount:t.loadedCount})),{state:{...e,phase:i,readinessSignals:t.signals,loadedCount:t.loadedCount,itemCount:t.itemCount,loadingCompleteEmitted:o},outputs:n}}function Mh(e,t){switch(t.kind){case"initialize":return e.phase==="disposed"?{state:e,outputs:[]}:e.phase!=="idle"?tk(e.cohort,t.cohort)?Mh(e,{kind:"update-runtime",effectiveRuntime:t.effectiveRuntime,effectiveToolsConfig:t.effectiveToolsConfig}):Mh(e,{kind:"cohort-change",cohort:t.cohort,effectiveRuntime:t.effectiveRuntime,effectiveToolsConfig:t.effectiveToolsConfig,itemCount:t.itemCount}):rk({state:e,cohort:t.cohort,effectiveRuntime:t.effectiveRuntime,effectiveToolsConfig:t.effectiveToolsConfig,itemCount:t.itemCount});case"update-runtime":return e.phase==="idle"||e.phase==="disposed"?{state:e,outputs:[]}:{state:{...e,effectiveRuntime:t.effectiveRuntime,effectiveToolsConfig:t.effectiveToolsConfig},outputs:[]};case"cohort-change":{if(e.phase==="disposed")return{state:e,outputs:[]};if(tk(e.cohort,t.cohort))return Mh(e,{kind:"update-runtime",effectiveRuntime:t.effectiveRuntime,effectiveToolsConfig:t.effectiveToolsConfig});let r=[];e.phase!=="idle"&&r.push({kind:"stage-change",stage:"disposed",status:"entered",cohort:e.cohort});let n=rk({state:e,cohort:t.cohort,effectiveRuntime:t.effectiveRuntime,effectiveToolsConfig:t.effectiveToolsConfig,itemCount:t.itemCount});return{state:n.state,outputs:[...r,...n.outputs]}}case"section-controller-resolved":{if(e.phase!=="booting-section")return{state:{...e,controllerResolved:!0},outputs:[]};let r=[];return Dp(r,"engine-ready",e.cohort),{state:{...e,phase:"engine-ready",controllerResolved:!0},outputs:r}}case"update-readiness-signals":return I9(e,{signals:t.signals,mode:t.mode,loadedCount:t.loadedCount,itemCount:t.itemCount});case"framework-error":return{state:{...e,lastFrameworkError:t.error,readinessSignals:{...e.readinessSignals,runtimeError:t.error.recoverable===!0?e.readinessSignals.runtimeError:!0}},outputs:[{kind:"framework-error",error:t.error}]};case"dispose":{if(e.phase==="disposed")return{state:e,outputs:[]};let r=[];return e.phase!=="idle"&&Dp(r,"disposed",e.cohort),{state:{...e,phase:"disposed"},outputs:r}}default:return{state:e,outputs:[]}}}var k9=class{constructor(){T(this,"state",Tw()),T(this,"listeners",new Set)}getState(){return this.state}dispatch(e){let t=Mh(this.state,e);return this.state=t.state,t.outputs.length>0&&this.fanOut(t.outputs),t.outputs}subscribe(e){this.listeners.add(e);let t=!0;return()=>{t&&(t=!1,this.listeners.delete(e))}}disposeListeners(){this.listeners.clear()}fanOut(e){let t=Array.from(this.listeners),r=Object.freeze(e.slice());for(let n of t)try{n(r)}catch(i){console.warn("[SectionEngineCore] listener failed:",i)}}};function T9(e){let{coordinator:t,dispatchCoreInput:r}=e,n=0,i=null,o=null,s=!1,a=t.subscribeFrameworkErrors(u=>{try{r({kind:"framework-error",error:u})}catch(f){console.warn("[CoordinatorBridge] framework-error dispatch failed:",f)}});function l(){if(o){try{o()}catch(u){console.warn("[CoordinatorBridge] controller unsubscribe failed:",u)}o=null}}async function d(u){if(s)return;n+=1;let f=n;i=u.cohort;let p=await t.getOrCreateSectionController({sectionId:u.cohort.sectionId,attemptId:u.cohort.attemptId||void 0,input:{section:u.section,sectionId:u.cohort.sectionId,assessmentId:u.assessmentId,view:u.view},updateExisting:!0,createDefaultController:u.createDefaultController});if(f!==n||s)return;l(),u.onControllerResolved?.(p);let g=p.getCompositionModel;u.onCompositionChanged?.(g?.()),typeof p.subscribe=="function"&&(o=p.subscribe(v=>{f!==n||s||u.onCompositionChanged?.(g?.())})),r({kind:"section-controller-resolved"})}async function c(){if(s)return;s=!0,n+=1,l();try{a()}catch(f){console.warn("[CoordinatorBridge] framework-error unsubscribe failed:",f)}let u=i;if(i=null,u)try{await t.disposeSectionController({sectionId:u.sectionId,attemptId:u.attemptId||void 0})}catch(f){console.warn("[CoordinatorBridge] section-controller dispose failed:",f)}}return{resolveSectionController:d,dispose:c}}function E9(e){let{runtimeId:t,sourceCe:r}=e,n=e.host,i=e.now??(()=>new Date().toISOString());function o(c){let u={stage:c.stage,status:c.status,runtimeId:t,sectionId:c.cohort?.sectionId,attemptId:c.cohort?.attemptId?c.cohort.attemptId:void 0,timestamp:i(),sourceCe:r};n.dispatchEvent(new CustomEvent("pie-stage-change",{detail:u}))}function s(c){let u={runtimeId:t,sectionId:c.cohort.sectionId,attemptId:c.cohort.attemptId?c.cohort.attemptId:void 0,itemCount:c.itemCount,loadedCount:c.loadedCount,timestamp:i(),sourceCe:r};n.dispatchEvent(new CustomEvent("pie-loading-complete",{detail:u}))}function a(c){n.dispatchEvent(new CustomEvent("framework-error",{detail:c.error}))}function l(c){switch(c.kind){case"stage-change":o(c);return;case"loading-complete":s(c);return;case"framework-error":a(c);return;default:return}}function d(c){n=c}return{dispatch:l,setHost:d}}function C9(e){let{bus:t}=e;function r(n){switch(n.kind){case"framework-error":t.reportFrameworkError(n.error);return;case"stage-change":case"loading-complete":return;default:return}}return{dispatch:r}}function x9(e={}){let t=e.hook;function r(i){if(t)try{t(i)}catch(o){console.warn("[InstrumentationBridge] hook failed:",o)}}function n(i){t=i}return{dispatch:r,setHook:n}}function R9(){let e=new Set;function t(o){if(o.length===0)return;let s=Array.from(e),a=Object.freeze(o.slice());for(let l of s)try{l(a)}catch(d){console.warn("[SubscriberFanout] listener failed:",d)}}function r(o){e.add(o);let s=!0;return()=>{s&&(s=!1,e.delete(o))}}function n(){e.clear()}function i(){return e.size}return{emit:t,subscribe:r,dispose:n,getListenerCount:i}}var _9=class{constructor(e){T(this,"core",void 0),T(this,"domEventBridge",void 0),T(this,"frameworkErrorBridge",void 0),T(this,"instrumentationBridge",void 0),T(this,"subscriberFanout",void 0),T(this,"coordinatorBridge",void 0),T(this,"unsubscribeCore",void 0),T(this,"disposed",!1),this.core=e.core??new k9,this.domEventBridge=E9({host:e.host,runtimeId:e.runtimeId,sourceCe:e.sourceCe,now:e.now}),this.frameworkErrorBridge=C9({bus:e.frameworkErrorBus}),this.instrumentationBridge=x9({hook:e.instrumentationHook}),this.subscriberFanout=R9(),this.coordinatorBridge=e.coordinator?T9({coordinator:e.coordinator,dispatchCoreInput:t=>this.dispatchInput(t)}):null,this.unsubscribeCore=this.core.subscribe(t=>{this.routeOutputs(t)})}getState(){return this.core.getState()}dispatchInput(e){return this.disposed?[]:this.core.dispatch(e)}subscribe(e){return this.subscriberFanout.subscribe(e)}setHost(e){this.domEventBridge.setHost(e)}setInstrumentationHook(e){this.instrumentationBridge.setHook(e)}resolveSectionController(e){if(!this.coordinatorBridge)throw Error("[SectionEngineAdapter] resolveSectionController called without a coordinator.");return this.coordinatorBridge.resolveSectionController(e)}async dispose(){this.disposed||(this.disposed=!0,this.core.dispatch({kind:"dispose"}),this.unsubscribeCore(),this.subscriberFanout.dispose(),this.coordinatorBridge&&await this.coordinatorBridge.dispose())}routeOutputs(e){for(let t of e)this.routeOne(t);this.subscriberFanout.emit(e)}routeOne(e){switch(e.kind){case"stage-change":case"loading-complete":this.domEventBridge.dispatch(e);break;case"framework-error":this.domEventBridge.dispatch(e),this.frameworkErrorBridge.dispatch(e);break;default:return}this.instrumentationBridge.dispatch(e)}},P9={mode:"gather",role:"student"};function lh(e,t){return e!==void 0?e:t}function A9(e){let t=e.runtime??{};return t.onFrameworkError!==void 0?t.onFrameworkError:e.onFrameworkError}function M9(e){let t=e.runtime?.tools||{},r=t.placement||{};return{...t,placement:{...r}}}function $9(e){let t=e.runtime||{},r=t.player?{...t.player}:null;return{...t,assessmentId:lh(t.assessmentId,e.assessmentId),playerType:t.playerType??"iife",player:r,lazyInit:t.lazyInit??!0,accessibility:t.accessibility??null,coordinator:t.coordinator??null,createSectionController:t.createSectionController,isolation:t.isolation??"inherit",env:t.env??P9,toolConfigStrictness:lh(t.toolConfigStrictness,e.toolConfigStrictness)??"error",onFrameworkError:A9({runtime:e.runtime,onFrameworkError:e.onFrameworkError}),onStageChange:lh(t.onStageChange,e.onStageChange),onLoadingComplete:lh(t.onLoadingComplete,e.onLoadingComplete),tools:e.effectiveToolsConfig}}function L9(e,t){let r=e.assessmentId??"section-demo-direct",n=M9({runtime:e.runtime}),i=$9({assessmentId:r,runtime:e.runtime,effectiveToolsConfig:n,toolConfigStrictness:e.toolConfigStrictness,onFrameworkError:e.onFrameworkError,onStageChange:e.onStageChange,onLoadingComplete:e.onLoadingComplete});return{effectiveToolsConfig:n,effectiveRuntime:i,playerRuntime:t.resolvePlayerRuntime({effectiveRuntime:i,playerType:String(i.playerType??"iife"),env:i.env??null})}}function O9(e,t){if(e===t)return 0;let r=e.compareDocumentPosition(t);return r&Node.DOCUMENT_POSITION_PRECEDING?1:r&Node.DOCUMENT_POSITION_FOLLOWING?-1:0}var N9=class{constructor(){T(this,"shellsByElement",new Map)}register(e){let t=this.shellsByElement.get(e.element),r={...e,sortKey:Date.now()};return t&&t.kind===r.kind&&t.itemId===r.itemId&&t.canonicalItemId===r.canonicalItemId?!1:(this.shellsByElement.set(e.element,r),!0)}unregister(e){return this.shellsByElement.delete(e)}getOrderedShells(e){let t=Array.from(this.shellsByElement.values()).filter(r=>!e||r.kind===e);return t.sort((r,n)=>O9(r.element,n.element)),t}getCanonicalIdMap(){let e={};for(let t of this.getOrderedShells("item"))t.itemId&&(e[t.itemId]=t.canonicalItemId||t.itemId);return e}clear(){this.shellsByElement.clear()}};function V_(e="runtime"){return`${e}-${Math.random().toString(16).slice(2)}-${Date.now()}`}var D9=Ys("section-runtime-engine",()=>Yl()),j9=class{constructor(){T(this,"registry",new N9),T(this,"runtimeId",V_("section-engine")),T(this,"adapter",null),T(this,"controller",null),T(this,"coordinator",null),T(this,"sectionId",""),T(this,"attemptId",void 0),T(this,"unsubscribeController",null),T(this,"activeInitToken",0),T(this,"loadedRenderableKeys",new Set)}attachHost(e){if(this.adapter){this.adapter.setHost(e.host),e.instrumentationHook!==void 0&&this.adapter.setInstrumentationHook(e.instrumentationHook);return}this.adapter=new _9({host:e.host,runtimeId:this.runtimeId,sourceCe:e.sourceCe,frameworkErrorBus:e.frameworkErrorBus,coordinator:e.coordinator,instrumentationHook:e.instrumentationHook,now:e.now})}dispatchInput(e){return this.adapter?.dispatchInput(e)??[]}subscribe(e){return this.adapter?.subscribe(e)??B9}getState(){return this.adapter?.getState()??Tw()}getEffectiveRuntime(e,t){return L9(e,t).effectiveRuntime}setInstrumentationHook(e){this.adapter?.setInstrumentationHook(e)}getRuntimeId(){return this.runtimeId}async initialize(e){this.activeInitToken+=1;let t=this.activeInitToken;this.coordinator=e.coordinator,this.sectionId=e.sectionId,this.attemptId=e.attemptId;let r=await e.coordinator.getOrCreateSectionController({sectionId:e.sectionId,attemptId:e.attemptId,input:{section:e.section,sectionId:e.sectionId,assessmentId:e.assessmentId,view:e.view},updateExisting:!0,createDefaultController:e.createDefaultController});t===this.activeInitToken&&(this.unsubscribeController?.(),this.controller=r,this.replayRegisteredShellsIntoController(r),e.onCompositionChanged?.(r.getCompositionModel?.()),this.unsubscribeController=r.subscribe?.(n=>{try{e.onControllerEvent?.(n)}catch(i){D9.warn("onControllerEvent handler threw",i)}e.onCompositionChanged?.(r.getCompositionModel?.())})||null)}replayRegisteredShellsIntoController(e){if(!e.handleContentRegistered)return;let t=this.registry.getOrderedShells();if(t.length===0)return;for(let n of t){let i=n.canonicalItemId||n.itemId;e.handleContentRegistered({itemId:n.itemId,canonicalItemId:i,contentKind:n.contentKind||n.kind})}let r=Date.now();for(let n of t){let i=n.canonicalItemId||n.itemId,o=this.getLoadedKey(i,n.contentKind);this.loadedRenderableKeys.has(o)&&e.handleContentLoaded?.({itemId:n.itemId,canonicalItemId:i,contentKind:n.contentKind||n.kind,timestamp:r})}}getLoadedKey(e,t){return`${t??""}:${e}`}register(e){return this.registry.register(e)}unregister(e){return this.registry.unregister(e)}getCompositionModel(){return this.controller?.getCompositionModel?.()??null}getCanonicalItemId(e){return this.registry.getCanonicalIdMap()[e]||this.controller?.getCanonicalItemId?.(e)||e}handleContentRegistered(e){this.controller?.handleContentRegistered?.({itemId:e.itemId,canonicalItemId:e.canonicalItemId||e.itemId,contentKind:e.contentKind||e.kind})}handleContentUnregistered(e){let t=e.canonicalItemId||e.itemId;this.loadedRenderableKeys.delete(this.getLoadedKey(t,e.contentKind)),this.controller?.handleContentUnregistered?.({itemId:e.itemId,canonicalItemId:t,contentKind:e.contentKind||e.kind})}handleContentLoaded(e){let t=e.canonicalItemId||e.itemId;this.loadedRenderableKeys.add(this.getLoadedKey(t,e.contentKind)),this.controller?.handleContentLoaded?.(e)}handleItemPlayerError(e){this.controller?.handleItemPlayerError?.(e)}reportSectionError(e){this.controller?.reportSectionError?.(e)}updateItemSession(e,t){let r=this.getCanonicalItemId(e);return this.controller?.updateItemSession?.(r,t)??null}navigateToItem(e){return this.controller?.navigateToItem?.(e)??null}handleFormativeAction(e){if(!e?.itemId)return;let t=this.getCanonicalItemId(e.itemId);if(e.action==="retry"){this.controller?.retryFormativeItem?.({itemId:t});return}this.controller?.recordFormativeTry?.({itemId:t,outcomes:e.outcomes})}handleMediaTimeSource(e){if(e?.action==="detach"){this.controller?.detachMediaTimeSource?.({origin:e.origin??"host"});return}e?.source&&this.controller?.attachMediaTimeSource?.(e.source,{origin:e.origin??"host",renderableId:e.renderableId})}requestMediaPauseForCompetingAudio(){return this.controller?.pauseMediaForCompetingAudio?.()??!0}async persist(){await this.controller?.persist?.()}async hydrate(){await this.controller?.hydrate?.()}getRegistry(){return this.registry}async dispose(){if(this.activeInitToken+=1,this.unsubscribeController?.(),this.unsubscribeController=null,this.coordinator&&this.sectionId&&await this.coordinator.disposeSectionController({sectionId:this.sectionId,attemptId:this.attemptId}),this.registry.clear(),this.loadedRenderableKeys.clear(),this.controller=null,this.coordinator=null,this.adapter){let e=this.adapter;this.adapter=null,await e.dispose()}}},B9=()=>{},F9=Zl(Symbol.for("pie.sectionRuntimeEngineHostContext"));function H9(e,t){return $u(e,F9,t)}var z9=e=>{console.error("[pie-assessment-toolkit] onStageChange handler threw",e)};function W9(e,t){if(e.isSuppressed())return!1;e.dispatchDomEvent(t);let r=e.getOnStageChange();if(r)try{r(t)}catch(n){(e.logHandlerError??z9)(n)}return!0}function Od(e,t){return typeof e=="function"?e:e===null?null:typeof t=="function"?t:null}function U9(e={}){let t=e.frameDeadlineMs??100,r=!1,n=null,i=null,o=null,s=null,a=null;function l(){r=!1,i!==null&&(s?.(i),i=null),o!==null&&(a?.(o),o=null),s=null,a=null}function d(f){if(!r)return;f==="frame"&&(i=null),f==="timer"&&(o=null);let p=n;n=null,l(),p?.()}function c(f){if(n=f,r)return;r=!0;let p=globalThis,g=Od(e.requestFrame,p.requestAnimationFrame);s=Od(e.cancelFrame,p.cancelAnimationFrame);let v=Od(e.setTimer,p.setTimeout);if(a=Od(e.clearTimer,p.clearTimeout),g){let w=g(()=>d("frame"));if(!r)return;if(i=w,v){let I=v(()=>d("timer"),t);r&&(o=I)}return}let b=Od(e.queueMicrotaskFn,p.queueMicrotask);if(b){b(()=>d("microtask"));return}if(v){let w=v(()=>d("timer"),0);r&&(o=w);return}d("microtask")}function u(){r&&(n=null,l())}return{schedule:c,cancel:u,isPending:()=>r}}function q9(){return{lastSessionEventSignatureByItemId:new Map,lastMetadataSignatureByItemId:new Map}}function V9(e){e.lastSessionEventSignatureByItemId.clear(),e.lastMetadataSignatureByItemId.clear()}function G9(e){let{state:t,itemId:r,payload:n}=e;if(X9(n)){let o=Z9(n);if(t.lastMetadataSignatureByItemId.get(r)===o)return!1;t.lastMetadataSignatureByItemId.set(r,o)}let i=K9(n);return t.lastSessionEventSignatureByItemId.get(r)===i?!1:(t.lastSessionEventSignatureByItemId.set(r,i),!0)}function K9(e){let t={...e};delete t.timestamp,delete t.sourceRuntimeId;try{return JSON.stringify(t)}catch{return String(t.itemId||"")}}function X9(e){return e.intent==="metadata-only"}function Z9(e){try{return JSON.stringify({itemId:e.itemId,canonicalItemId:e.canonicalItemId,intent:e.intent,complete:e.complete??null,component:e.component??null})}catch{return String(e.itemId||"")}}var Y9=(e,t)=>{if(!customElements.get(e))try{customElements.define(e,t)}catch(r){if(!(r instanceof DOMException&&r.name==="NotSupportedError"||r&&typeof r=="object"&&r.name==="NotSupportedError")||!customElements.get(e))throw r}},J9=Zi('<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>'),Q9=Zi('<div class="pie-assessment-toolkit-anchor svelte-15pthty" aria-hidden="true"></div> <!>',1),eq={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
1538
+ 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 tq(e,t){dm(t,!0),dC(e,eq);let r=V_("toolkit"),n=new j9,i=Sr(null),o=new u_,s={mode:"gather",role:"student"},a={iife:"pie-item-player",esm:"pie-item-player",preloaded:"pie-item-player",custom:""},l=wt(t,"assessmentId",7,""),d=wt(t,"section",7,null),c=wt(t,"sectionId",7,""),u=wt(t,"attemptId",7,""),f=wt(t,"env",23,()=>({})),p=wt(t,"ndsIcons",7,!1),g=wt(t,"locale",7,""),v=wt(t,"lazyInit",7,!0),b=wt(t,"toolConfigStrictness",7,"error"),w=wt(t,"tools",23,()=>({})),I=wt(t,"toolContextResolvers",7,null),x=wt(t,"enabledTools",7,""),C=wt(t,"toolRegistry",7,null),L=wt(t,"accessibility",23,()=>({})),E=wt(t,"player",7,null),M=wt(t,"playerType",7,""),U=wt(t,"coordinator",7,null),te=wt(t,"createSectionController",7,null),re=wt(t,"onFrameworkError",7,null),Pe=wt(t,"errorRenderer",7,null),z=wt(t,"onStageChange",7,null),K=wt(t,"assessment",7,null),oe=wt(t,"currentItemRef",7,null),ue=wt(t,"pnpEnforcement",7,null),ae=wt(t,"isolation",7,"inherit"),X=Sr(null),j=Sr(null),D=Sr(null),Z=null,F=null,W=null,O=null,$=null,ie=null,N=Sr(0),ne=Sr(null),ge=Sr(null),Oe=Sr("Unable to initialize assessment toolkit."),We=Sr(Ls([])),Ne="",xe="",et=null,Ue=!1,Se=!1,Re=Sr(""),mt=null,$t=U9(),ve=[],me=new Map,Je=new WeakMap,Gt=q9(),le=UM({sourceCe:"pie-assessment-toolkit",sourceCeShape:"toolkit",runtimeId:r,sectionId:Hr(()=>c()||void 0),attemptId:Hr(()=>u()||void 0),emit:m=>{W9({isSuppressed:()=>y(i)!==null,dispatchDomEvent:k=>Bt("pie-stage-change",k),getOnStageChange:()=>z()},m)}}),Ae=Sr(Ls(Hr(()=>`${c()}|${u()}`))),Y=Sr(!1),we=Sr(!1),_e=Sr(!1),Be=Sr(!1);function it(){if(!y(X))return null;let m=y(X).getRootNode();return m&&"host"in m?m.host:y(X).parentElement}let tt=Ze(()=>it());function Bt(m,k){if(!y(tt)){ve=[...ve,{name:m,detail:k}];return}ek(y(tt),m,k)}jt(()=>{if(!y(tt)||ve.length===0)return;let m=ve;ve=[],queueMicrotask(()=>{let k=y(tt);if(!k){ve=[...m,...ve];return}for(let B of m)ek(k,B.name,B.detail)})});function ht(m){if(!Pe())return{title:"Unable to initialize assessment toolkit.",details:m.details.length>0?m.details:[m.message]};try{let k=Pe()(m)||{};return{title:typeof k.title=="string"&&k.title.trim().length>0?k.title:"Unable to initialize assessment toolkit.",details:Array.isArray(k.details)&&k.details.length>0?k.details.map(B=>String(B)):m.details.length>0?m.details:[m.message]}}catch(k){let B=k instanceof Error&&k.message.trim().length>0?k.message:String(k||"Unknown renderer error");return{title:"Unable to initialize assessment toolkit.",details:[...m.details,`Error renderer failed: ${B}`]}}}function ot(m){let k=r_({kind:m.kind,source:m.source,error:m.error,recoverable:m.recoverable});return o.reportFrameworkError(k),k}function $r(m){if(m?.type==="timed-media-policy-degraded"){let B=m.degradations||[];o.reportFrameworkError(yy({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:B.map(J=>J?.message).filter(J=>typeof J=="string"),recoverable:!0}));return}if(m?.type!=="timed-media-invalid")return;let k=m.errors||[];o.reportFrameworkError(yy({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:k.map(B=>B?.message).filter(B=>typeof B=="string"),recoverable:!1}))}function Ur(m){m?.type==="timed-media-audio-started"&&y(H)&&c9(y(H).getServiceBundle().ttsService)}function Lr(m){return m==="coordinator-init"||m==="runtime-init"||m==="tool-config"}function ln(m){if(re())try{re()(m),Ne=`${m.kind}|${m.source}|${m.message}`}catch(k){console.error(`[pie-framework:${m.kind}:${m.source}] framework error hook failed`,k)}}let qr=new WeakSet;jt(()=>{let m=o.subscribeFrameworkErrors(k=>{if(console.error(yW(k),k.cause),Lr(k.kind)&&!qr.has(k)){let B=ht(k);bt(ge,k,!0),bt(Oe,B.title,!0),bt(We,B.details,!0)}Bt("framework-error",k),ln(k)});return()=>{m()}}),jt(()=>{let m=U();if(!(!m||y(H)!==m)&&typeof m.subscribeFrameworkErrors=="function")return Hr(()=>m.subscribeFrameworkErrors(k=>{qr.add(k),o.reportFrameworkError(k)}))}),jt(()=>{let m=U(),k=C();!m||y(H)!==m||typeof m.adoptToolRegistry=="function"&&Hr(()=>m.adoptToolRegistry(k))}),jt(()=>{if(!y(ge))return;let m=`${y(ge).kind}|${y(ge).source}|${y(ge).message}`;Ne!==m&&ln(y(ge))});function xr(m){let k=5381;for(let B=0;B<m.length;B+=1)k=(k<<5)+k^m.charCodeAt(B);return(k>>>0).toString(36)}function Ar(m){return m&&typeof m=="object"?m:{}}function ye(m){let k=Ar(m.section),B=typeof k.identifier=="string"?k.identifier:"",J=typeof m.sectionId=="string"?m.sectionId:"";return B||J}function vt(m){return typeof m.currentItemIndex=="number"?m.currentItemIndex:-1}function kt(m){return(Array.isArray(m.renderables)?m.renderables:[]).map((k,B)=>{let J=Ar(Ar(k).entity),Me=typeof J.id=="string"&&J.id||`renderable-${B}`,st=Ar(J.config);return{id:Me,version:typeof J.version=="string"&&J.version||(typeof J.version=="number"?String(J.version):"")||(typeof st.version=="string"?st.version:"")}})}function Qe(m){let k=Ar(m.itemSessionsByItemId);return Object.keys(k).sort((B,J)=>B.localeCompare(J)).map(B=>{let J=Ar(k[B]),Me=typeof J.id=="string"?J.id:"",st=Array.isArray(J.data)?J.data:[],yt="";try{yt=xr(JSON.stringify(st))}catch{yt=String(st.length)}return{itemId:B,sessionId:Me,payloadSignature:yt}})}function cr(m){let k=Ar(Ar(m.formative).states);return Object.entries(k).map(([B,J])=>{let Me=Ar(J),st=Ar(Me.lastOutcome).correctness??"";return`${B}:${Me.tryCount??0}:${Me.revealed===!0?1:0}:${String(st)}:${String(Me.revealOverride??"")}`}).sort().join("|")}function V(m){let k=m.timedMedia;return XR(k)}function ke(m){let k=Ar(m),B=kt(k).map(Me=>`${Me.id}:${Me.version}`).join("|"),J=Qe(k).map(Me=>`${Me.itemId}:${Me.sessionId}:${Me.payloadSignature}`).join("|");return{sectionId:ye(k),currentItemIndex:vt(k),renderableSignature:B,itemSessionSignature:J,formativeSignature:cr(k),timedMediaSignature:V(k)}}function qe(m){let k=ke(m);return`${k.sectionId}|${k.currentItemIndex}|${k.renderableSignature}|${k.itemSessionSignature}|${k.formativeSignature}|${k.timedMediaSignature}`}function Ve(m){return m==="iife"||m==="esm"||m==="preloaded"||m==="custom"}function at(m,k){let B=m?.type,J=Ve(B)?B:Ve(k)?k:m?.tagName?"custom":"iife",Me=m?.tagName?.trim();return J==="custom"&&!Me?{type:"iife",tagName:a.iife,version:void 0,source:void 0,isDefault:!0}:{type:J,tagName:Me||a[J],version:m?.version,source:m?.source,loaderConfig:m?.loaderConfig,loaderOptions:m?.loaderOptions,isDefault:!m&&!k}}function Rt(m){let k=m||{};return{mode:typeof k.mode=="string"&&k.mode.trim()?k.mode.trim():s.mode,role:typeof k.role=="string"&&k.role.trim()?k.role.trim():s.role}}function Rr(m){let k=Rt(m);return k.mode==="author"?"author":k.role==="instructor"?"scorer":"candidate"}async function Vr(){if(te())return te()();throw Error("pie-assessment-toolkit requires createSectionController when no coordinator hook provides one")}function jr(){let m=w()||{},k=gC(x());if(k.length===0)return m;let B=m.placement||{},J=Array.isArray(B.section)?B.section:null;return J&&J.length>0?m:{...m,placement:{...B,section:k}}}function dr(){return CW(jr(),{strictness:b(),source:"pie-assessment-toolkit.bootstrap",toolRegistry:C()}).config}function fe(){let m="",k="";try{m=JSON.stringify(jr())}catch{m="[unserializable-tools]"}try{k=JSON.stringify(Object.entries(I()??{}).map(([B,J])=>[B,typeof J]))}catch{k="[unserializable-resolvers]"}return[l()||"",String(b()||"error"),m,k].join("|")}function _t(m){return m==="on"||m==="off"?m:null}function Gr(m,k){let B=_t(m);if(B)return B;if(k&&typeof k=="object"){let J=k.pnpEnforcement;return _t(typeof J=="string"?J:null)}return null}function tn(m){let k=l()||d()?.identifier||`assessment-${Math.random().toString(16).slice(2)}`;return new s9({assessmentId:k,lazyInit:v(),toolConfigStrictness:b(),deferToolConfigValidation:!0,assessmentOptional:!0,tools:m,toolRegistry:C(),toolContextResolvers:I(),accessibility:L(),frameworkErrorBus:o})}function Wn(m){try{return JSON.stringify(m??null)}catch{return"[unserializable]"}}function ei(){return{signatures:{assessmentId:l()||"",toolConfigStrictness:String(b()||"error"),lazyInit:String(v()),tools:Wn({...jr(),pnpEnforcement:void 0}),accessibility:Wn(L())},toolRegistry:C()}}function ta(){let m=et;if(!m)return[];let k=ei(),B=Object.keys(k.signatures).filter(J=>k.signatures[J]!==m.signatures[J]);return k.toolRegistry!==m.toolRegistry&&B.push("toolRegistry"),B}function Cr(m){Se||(Se=!0,console.warn(`[pie-assessment-toolkit] ${m.join(", ")} changed after a section initialized with the coordinator this toolkit built, and that coordinator keeps the values it was built with. Set these inputs no later than the section, pass a coordinator of your own, or update this one from toolkit-ready with updateToolConfig(...) or updateToolsPlacement(...). Reported once per toolkit.`))}function ti(){let m=y(j);return m?(bt(j,null),m.dispose()):Promise.resolve()}function Qo(m){ot({kind:"runtime-dispose",source:"pie-assessment-toolkit",error:m,recoverable:!0})}let H=Ze(()=>ae()!=="force"&&y(D)?.coordinator?y(D).coordinator:U()||y(j)),ce=Ze(()=>d()!=null);jt(()=>{y(tt),U(),ae(),y(D),I(),y(ce),w(),x(),l(),b(),v(),L(),C(),Hr(()=>{if(y(tt)){if(U()){y(j)&&ti().catch(Qo),F=null;return}if(ae()!=="force"&&y(D)?.coordinator){y(j)&&ti().catch(Qo),F=null;return}if(y(j)){let m=ta();m.length>0&&Ue?Cr(m):m.length>0&&d()&&ti().catch(Qo)}if(y(j)&&F!==I()){try{y(j).setToolContextResolvers(I()),F=I()}catch(m){ot({kind:"coordinator-init",source:"pie-assessment-toolkit",error:m})}return}if(!y(j)){let m=fe();if(xe===m)return;try{let k=dr();bt(j,tn(k),!0),et=ei(),Ue=!1,F=I(),xe="",bt(ge,null),bt(Oe,"Unable to initialize assessment toolkit."),bt(We,[],!0)}catch(k){bt(j,null),xe=m,ot({kind:"coordinator-init",source:"pie-assessment-toolkit",error:k})}}}})});let se=w$(),de=Sr(0);jt(()=>se.subscribe(()=>{bt(de,y(de)+1)})),jt(()=>{let m=typeof g()=="string"?g().trim():"";Hr(()=>{Promise.resolve(se.setLocale(m||"en-US")).catch(k=>{ot({kind:"i18n-locale-load",source:"pie-assessment-toolkit",error:k instanceof Error?k:Error(String(k))})})})});let lt=Ze(()=>l()||y(H)?.assessmentId||""),nr=Ze(()=>c()||d()?.identifier||`section-${y(lt)||"default"}`),Ee=Ze(()=>Rt(f())),rt=Ze(()=>Rr(y(Ee))),sr=Ze(()=>at(E(),M())),Pt=Ze(()=>ud({player:y(sr),component:"pie-assessment-toolkit"})),$e=Ze(()=>{if(!y(H))return null;let m=y(H).getServiceBundle();return{toolkitCoordinator:y(H),toolCoordinator:y(H).toolCoordinator,ttsService:m.ttsService,highlightCoordinator:m.highlightCoordinator,catalogResolver:m.catalogResolver,elementToolStateStore:m.elementToolStateStore,assessmentId:y(lt),sectionId:y(nr),itemPlayer:y(sr),ndsIcons:p()===!0,locale:(y(de),se.getLocale()),i18n:se,reportSessionChanged:(k,B)=>{gr({itemId:k,result:n.updateItemSession(k,B),fallbackSession:B})},reportSectionError:k=>{n.reportSectionError({source:"section-runtime",error:k,timestamp:Date.now()})}}}),wr=Ze(()=>y(H)?{runtimeId:r,coordinator:y(H)}:null);function hn(m){let k=qe(m);k!==y(Re)&&(bt(Re,k,!0),bt(N,y(N)+1),bt(ne,m,!0),Bt("composition-changed",{composition:y(ne),version:y(N)}))}function Ir(m){mt=m??n.getCompositionModel(),$t.schedule(()=>{hn(mt)})}function Br(m){if(!m)return;let k=Je.get(m);if(k){for(let B of k)B();Je.delete(m)}}function mr(){for(let m of me.values())Br(m.element)}function ur(m){if(Br(m.element),!y(H))return;let k=y(H).getServiceBundle().catalogResolver;Je.set(m.element,[k.registerOwner({owner:{kind:m.kind,itemId:m.itemId,canonicalItemId:m.canonicalItemId,assessmentId:y(lt),sectionId:y(nr)},entity:m.item})])}function Lt(){mr();for(let m of me.values())ur(m)}function gr(m){let k={...m.result?.eventDetail||m.fallbackSession,itemId:m.itemId,canonicalItemId:m.canonicalItemId||m.itemId,sourceRuntimeId:r};G9({state:Gt,itemId:m.itemId,payload:k})&&Bt("session-changed",k)}function Fr(m){return m instanceof HTMLElement?Z_(m,$v)?.runtimeId===r:!1}function Yt(m){return m.detail??null}function dt(m,k){for(let B of k)m.addEventListener(B.name,B.handler);return()=>{for(let B of k)m.removeEventListener(B.name,B.handler)}}jt(()=>{if(y(tt)){if(ae()==="force"){bt(D,null);return}return zN(y(tt),m=>{m.runtimeId!==r&&bt(D,m,!0)})}}),jt(()=>{let m=y(tt);return Hr(()=>{if(!m){bt(i,null);return}let k=H9(m,B=>{B.engine!==y(i)&&bt(i,B.engine,!0)});return()=>{k(),bt(i,null)}})}),jt(()=>{let m=y(H);if(m)return Hr(()=>l9({ttsService:m.getServiceBundle().ttsService,listenerId:`timed-media-audio-handoff:${r}`,silence:()=>n.requestMediaPauseForCompetingAudio()}))}),jt(()=>{let m=ae()!=="force"&&y(D)?y(D).runtimeId:null,k=m?"inherited":"owned";k!==Z&&(Z=k,Bt(k==="inherited"?"runtime-inherited":"runtime-owned",{runtimeId:r,parentRuntimeId:m}))}),jt(()=>{y(nr),u(),V9(Gt)});let zt=Ze(()=>y(wr)!==null),fr=Ze(()=>y($e)!==null);jt(()=>{if(!y(tt)||!y(zt))return;let m=Hr(()=>y(wr));if(m)return $=new Ws(y(tt),{context:$v,initialValue:m}),$.connect(),ie=new Bl(y(tt)),ie.attach(),()=>{ie?.detach(),ie=null,$?.disconnect(),$=null}}),jt(()=>{y(wr)&&$?.setValue(y(wr))}),jt(()=>{y(tt)&&(y(tt).setAttribute("data-item-player-type",y(sr).type),y(tt).setAttribute("data-item-player-tag",y(sr).tagName),y(tt).setAttribute("data-env-mode",String(y(Ee)?.mode||"")),y(tt).setAttribute("data-env-role",String(y(Ee)?.role||"")))}),jt(()=>{if(!y(tt)||!y(fr))return;let m=Hr(()=>y($e));if(m)return W=new Ws(y(tt),{context:$b,initialValue:m}),W.connect(),O=new Bl(y(tt)),O.attach(),()=>{O?.detach(),O=null,W?.disconnect(),W=null}}),jt(()=>{y($e)&&W?.setValue(y($e))}),jt(()=>(y(H),y(lt),y(nr),Lt(),()=>{mr()})),jt(()=>{if(y(tt))return Gu({host:y(tt),instrumentationProvider:y(Pt),component:"pie-assessment-toolkit",eventMap:qM,staticAttributes:{instrumentationLayer:"toolkit",assessmentId:y(lt),sectionId:y(nr),attemptId:u()||void 0}})}),jt(()=>{K(),oe(),ue(),w();let m=y(H);m&&m===y(j)&&Hr(()=>{m.setPnpEnforcement(Gr(ue(),w())),m.updateAssessment(K()),m.updateCurrentItemRef(oe())})}),jt(()=>{if(y(H))return y(H).subscribeTelemetry(({eventName:m,payload:k})=>{if(!Vu(y(Pt))||!y(Pt).isReady())return;let B=m,J=new Date().toISOString(),Me={...k||{},instrumentationLayer:"toolkit",assessmentId:y(lt),sectionId:y(nr),attemptId:u()||void 0,component:"pie-assessment-toolkit",sourceEventName:m,timestamp:J};y(Pt).trackEvent(B,Me);let st=k&&typeof k.errorType=="string"?k.errorType:void 0;if(!m.endsWith("-error")&&!st)return;let yt=k&&typeof k.message=="string"?k.message:`Toolkit telemetry error: ${m}`;y(Pt).trackError(Error(yt),{component:"pie-assessment-toolkit",errorType:st||"ToolkitTelemetryError",...Me})})}),jt(()=>{if(!d()||!y(H))return;let m=!1;return y(H)===Hr(()=>y(j))&&(Ue=!0),n.initialize({coordinator:y(H),section:d(),sectionId:y(nr),assessmentId:y(lt),attemptId:u()||void 0,view:y(rt),createDefaultController:Vr,onCompositionChanged:k=>{m||Ir(k)},onControllerEvent:k=>{m||(Ur(k),$r(k))}}).then(()=>{m||(Bt("toolkit-ready",{runtimeId:r,assessmentId:y(lt),sectionId:y(nr),itemPlayer:y(sr),coordinator:y(H)}),Bt("section-ready",{sectionId:y(nr)}),Hr(()=>{bt(Be,!0)}))}).catch(k=>{m||(Hr(()=>{y(we)||(bt(we,!0),le.enter("engine-ready","skipped")),le.enter("interactive","failed")}),n.reportSectionError({source:"section-runtime",error:k,timestamp:Date.now()}),ot({kind:"runtime-init",source:"pie-assessment-toolkit",error:k}))}),()=>{m=!0}}),jt(()=>{if(!y(tt))return;let m=y(tt),k=B=>Fr(B.target)?(B.stopPropagation(),!0):!1;return dt(m,[{name:d9,handler:B=>{if(!k(B))return;let J=Yt(B);if(!J?.element||!J?.itemId)return;let Me=n.register(J);me.set(J.element,J),ur(J),n.handleContentRegistered(J),Me&&Ir()}},{name:u9,handler:B=>{if(!k(B))return;let J=Yt(B);if(!J?.itemId)return;let Me=J?.element?n.unregister(J.element):!1;Br(J.element),J.element&&me.delete(J.element),n.handleContentUnregistered(J),Me&&Ir()}},{name:f9,handler:B=>{if(!k(B))return;let J=Yt(B);if(!J?.itemId)return;let Me=n.updateItemSession(J.itemId,J.session);gr({itemId:J.itemId,canonicalItemId:n.getCanonicalItemId(J.itemId),result:Me,fallbackSession:J.session})}},{name:h9,handler:B=>{if(!k(B))return;let J=Yt(B);J?.itemId&&n.handleContentLoaded({itemId:J.itemId,canonicalItemId:J.canonicalItemId,contentKind:J.contentKind,detail:J.detail,timestamp:Date.now()})}},{name:p9,handler:B=>{if(!k(B))return;let J=Yt(B);J?.itemId&&n.handleItemPlayerError({itemId:J.itemId,canonicalItemId:J.canonicalItemId,contentKind:J.contentKind,error:J.error,timestamp:Date.now()})}},{name:m9,handler:B=>{if(!k(B))return;let J=Yt(B);J?.itemId&&(J.action!=="check"&&J.action!=="retry"||n.handleFormativeAction({itemId:J.canonicalItemId||J.itemId,action:J.action,outcomes:J.outcomes}))}},{name:g9,handler:B=>{if(!k(B))return;let J=Yt(B);J?.renderableId&&(J.action!=="attach"&&J.action!=="detach"||n.handleMediaTimeSource({renderableId:J.renderableId,action:J.action,source:J.source,origin:J.origin}))}}])});async function Kn(){if(!y(H))throw Error("Coordinator not initialized");await y(H).waitUntilReady()}function _r(){if(!y(H))throw Error("Coordinator not initialized");return y(H).getServiceBundle()}function $n(m){if(!y(H))throw Error("Coordinator not initialized");y(H).setHooks(m)}function ri(m){return n.navigateToItem(m)}function pn(){return n.getCompositionModel()}function Zr(){return y(sr)}async function Pr(){await n.persist()}async function Or(){await n.hydrate()}jt(()=>()=>{Hr(()=>{le.getCurrent()!==null&&le.enter("disposed")})}),jt(()=>{let m=`${c()}|${u()}`;Hr(()=>{m!==y(Ae)&&(le.getCurrent()!==null&&le.enter("disposed"),le.reset({sectionId:c()||void 0,attemptId:u()||void 0}),bt(Ae,m),bt(Y,!1),bt(we,!1),bt(_e,!1),bt(Be,!1))})}),jt(()=>{let m=y(we)&&y(Be);Hr(()=>{m&&(y(_e)||(bt(_e,!0),le.enter("interactive")))})}),jt(()=>{let m=y(N)>0||y(ne)!==null;Hr(()=>{!y(Y)&&m&&(bt(Y,!0),le.enter("composed"))})}),jt(()=>{if(!y(H)||!y(Y)||y(we))return;let m=y(H),k=!1;return m.waitUntilReady().then(()=>{k||Hr(()=>{y(we)||(bt(we,!0),le.enter("engine-ready"))})}).catch(()=>{k||Hr(()=>{y(we)||(bt(we,!0),le.enter("engine-ready","failed"))})}),()=>{k=!0}}),jt(()=>()=>{$t.cancel(),n.dispose().catch(m=>{ot({kind:"runtime-dispose",source:"pie-assessment-toolkit",error:m,recoverable:!0})}).then(()=>ti()).catch(Qo).finally(()=>{o.dispose()})});var kr={waitUntilReady:Kn,getServiceBundle:_r,setHooks:$n,navigateToItem:ri,getCompositionModel:pn,getItemPlayerConfig:Zr,persist:Pr,hydrate:Or,get assessmentId(){return l()},set assessmentId(m){l(m),gt()},get section(){return d()},set section(m){d(m),gt()},get sectionId(){return c()},set sectionId(m){c(m),gt()},get attemptId(){return u()},set attemptId(m){u(m),gt()},get env(){return f()},set env(m){f(m),gt()},get ndsIcons(){return p()},set ndsIcons(m){p(m),gt()},get locale(){return g()},set locale(m){g(m),gt()},get lazyInit(){return v()},set lazyInit(m){v(m),gt()},get toolConfigStrictness(){return b()},set toolConfigStrictness(m){b(m),gt()},get tools(){return w()},set tools(m){w(m),gt()},get toolContextResolvers(){return I()},set toolContextResolvers(m){I(m),gt()},get enabledTools(){return x()},set enabledTools(m){x(m),gt()},get toolRegistry(){return C()},set toolRegistry(m){C(m),gt()},get accessibility(){return L()},set accessibility(m){L(m),gt()},get player(){return E()},set player(m){E(m),gt()},get playerType(){return M()},set playerType(m){M(m),gt()},get coordinator(){return U()},set coordinator(m){U(m),gt()},get createSectionController(){return te()},set createSectionController(m){te(m),gt()},get onFrameworkError(){return re()},set onFrameworkError(m){re(m),gt()},get errorRenderer(){return Pe()},set errorRenderer(m){Pe(m),gt()},get onStageChange(){return z()},set onStageChange(m){z(m),gt()},get assessment(){return K()},set assessment(m){K(m),gt()},get currentItemRef(){return oe()},set currentItemRef(m){oe(m),gt()},get pnpEnforcement(){return ue()},set pnpEnforcement(m){ue(m),gt()},get isolation(){return ae()},set isolation(m){ae(m),gt()}},xt=Q9(),Tr=vi(xt);hC(Tr,m=>bt(X,m),()=>y(X));var ni=jc(Tr,2),Ln=m=>{var k=J9(),B=rl(k),J=Zm(B,!0),Me=jc(B,2),st=Zm(Me,!0),yt=jc(Me,2),Jt=Zm(yt,!0);eo(k),en(ii=>{Qm(J,y(Oe)),Qm(st,y(ge).message),Qm(Jt,ii)},[()=>y(We).join(`
1539
+ `)]),Qt(m,k)},On=m=>{var k=$i(),B=vi(k);_N(B,t,"default",{},null),Qt(m,k)};return Li(ni,m=>{y(ge)&&!y(ge).recoverable?m(Ln):m(On,-1)}),Qt(e,xt),um(kr)}Y9("pie-assessment-toolkit",Mb(tq,{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"},lazyInit:{attribute:"lazy-init",type:"Boolean"},toolConfigStrictness:{attribute:"tool-config-strictness",type:"String"},tools:{attribute:"tools",type:"Object"},toolContextResolvers:{type:"Object"},enabledTools:{attribute:"enabled-tools",type:"String"},toolRegistry:{type:"Object"},accessibility:{type:"Object"},player:{attribute:"player",type:"Object"},playerType:{attribute:"player-type",type:"String"},coordinator:{type:"Object"},createSectionController:{type:"Object"},onFrameworkError:{type:"Object"},errorRenderer:{type:"Object"},onStageChange:{type:"Object"},assessment:{type:"Object"},currentItemRef:{type:"Object"},pnpEnforcement:{attribute:"pnp-enforcement",type:"String"},isolation:{type:"Object"}},["default"],["waitUntilReady","getServiceBundle","setHooks","navigateToItem","getCompositionModel","getItemPlayerConfig","persist","hydrate"],{mode:"open"},Zs));var rq=class{createUniqueId(e,t,r){const n=e.trim()||r;let i=n,o=2;for(;t.has(i);)i=`${n}-${o++}`;return t.add(i),i}resolvePassageBaseId(e,t){return(e?.id||e?.identifier||e?.name||"").trim()||t}normalizePassageEntity(e,t,r){const n=this.resolvePassageBaseId(e,r),i=this.createUniqueId(n,t,r);return{...e,id:i}}build(e,t){if(!e)return{passages:[],items:[],rubricBlocks:[],instructions:[],renderables:[],adapterItemRefs:[],stimulusRenderableIdsByRef:{}};const r=new Map,n=new Set,i=new Set,o={},s=(e.rubricBlocks||[]).filter(u=>u.view.includes(t)),a=s.filter(u=>u.class==="instructions");for(const[u,f]of(e.rubricBlocks||[]).entries())if(f.class==="stimulus"&&f.passage&&(f.view.includes("candidate")||f.view.includes(t))){const p=this.normalizePassageEntity(f.passage,n,`passage-${u+1}`);r.set(p.id,p),f.identifier&&(o[f.identifier]=p.id);const g=typeof f.passage.id=="string"?f.passage.id.trim():"";g&&(o[g]=p.id),o[p.id]=p.id}const l=[],d=[];for(const[u,f]of(e.assessmentItemRefs||[]).entries()){if(!f.item)continue;const p=f.item.id||f.identifier||f.item.name||`item-${u+1}`,g=this.createUniqueId(String(p),i,`item-${u+1}`),v=f.item.passage&&typeof f.item.passage=="object"?(()=>{const I=typeof f.item?.passage?.id=="string"?f.item.passage.id.trim():"";return I&&r.has(I)?r.get(I):this.normalizePassageEntity(f.item.passage,n,`passage-${u+1}`)})():void 0,b={...f.item,id:g,passage:v||f.item.passage};l.push(b);const w=f.identifier||g||f.item.name||"";d.push({identifier:w,item:{id:g,identifier:w},formative:f.formative}),v&&typeof v=="object"&&v.id&&!r.has(v.id)&&r.set(v.id,v)}const c=[...Array.from(r.values()).map(u=>({flavor:"passage",entity:u})),...l.map(u=>({flavor:"item",entity:u})),...s.filter(u=>u.class==="rubric").map((u,f)=>u?.passage?this.normalizePassageEntity(u.passage,n,`rubric-passage-${f+1}`):null).filter(u=>!!u?.config).map(u=>({flavor:"rubric",entity:u}))];return{passages:Array.from(r.values()),items:l,rubricBlocks:s,instructions:a,renderables:c,adapterItemRefs:d,stimulusRenderableIdsByRef:o}}},nq=class{navigate(e){if(e.index<0||e.index>=e.items.length)return null;const t=e.items[e.currentItemIndex]?.id||"",r=e.items[e.index],n=r?.id||"",i=typeof r?.title=="string"&&r.title.trim()||void 0,o=dL(uL(e.testAttemptSession,{currentItemIndex:e.index,currentSectionIdentifier:e.sectionIdentifier}),n);return{nextIndex:e.index,testAttemptSession:o,eventDetail:{previousItemId:t,currentItemId:n,itemIndex:e.index,totalItems:e.items.length,timestamp:Date.now(),itemLabel:i}}}},iq=class{createEmptyCanonicalAttempt(e){const t=e.adapterItemRefs.map(r=>r?.identifier||r?.item?.id).filter(r=>typeof r=="string"&&!!r);return cL({testAttemptSessionIdentifier:`tas_${e.assessmentId}_${e.sectionId}`,assessmentId:e.assessmentId,seed:`${e.assessmentId}:${e.sectionId}`,itemIdentifiers:t})}toSessionState(e){const t=e.navigationState?.currentItemIndex??0;return{currentItemIndex:t>=0?t:0,visitedItemIdentifiers:e.navigationState?.visitedItemIdentifiers||[],itemSessions:e.itemSessions||{}}}resolve(e){const t=this.createEmptyCanonicalAttempt(e);return{testAttemptSession:t,itemSessions:fv(t)}}applyItemSessionChanged(e){const t=LT({itemId:e.itemId,sessionDetail:e.sessionDetail,previousItemSession:e.itemSessions[e.itemId]}),r=t.itemId,n=t.session;let i=e.testAttemptSession;n&&r&&(i=fL(e.testAttemptSession,{itemIdentifier:r,pieSessionId:String(n.id||r),isCompleted:!!t.complete,session:n}));const o=fv(i),s=t.intent==="metadata-only"?null:o[r]||n||(e.sessionDetail&&typeof e.sessionDetail=="object"?e.sessionDetail.session??e.sessionDetail:{id:r,data:[]});return{testAttemptSession:i,itemSessions:o,sessionState:this.toSessionState(i),eventDetail:{itemId:r,session:s,intent:t.intent,complete:t.complete,component:t.component,...t.elementId?{elementId:t.elementId}:{},...t.sessionCommitReason?{sessionCommitReason:t.sessionCommitReason}:{},timestamp:Date.now()}}}},oq=5e3,vc=Ys("section-controller",()=>Yl()),sq=class{constructor(){this.contentService=new rq,this.sessionService=new iq,this.itemNavigationService=new nq,this.sessionPersistence=null,this.pendingSessionCommit=null,this.state={input:null,viewModel:{passages:[],items:[],rubricBlocks:[],instructions:[],renderables:[],adapterItemRefs:[],stimulusRenderableIdsByRef:{},currentItemIndex:0,isPageMode:!1},testAttemptSession:null},this.listeners=new Set,this.trackedRenderables=new Map,this.loadedRenderableKeys=new Set,this.itemCompletionByCanonicalId=new Map,this.elementCompletionByCanonicalId=new Map,this.reportedCompletionIds=new Set,this.sectionLoadingComplete=!1,this.totalRegistered=0,this.totalLoaded=0,this.sectionItemsComplete=!1,this.completedCount=0,this.totalItems=0,this.nextApplyRevision=0,this.lastReplayedApplyRevision=0,this.pendingApplyReplay=null,this.formativePolicies={},this.formativeStates={},this.formativeEnabled=!1,this.lastMasterySignature="",this.timedMediaData=null,this.timedMediaState=Ph(),this.mediaTimeSource=null,this.mediaTimeSourceOrigin="native-adapter",this.unsubscribeMediaTimeSource=null,this.lastTimedMediaSignature="",this.lastTimedMediaInvalidSignature="",this.reportedDegradationKeys=new Set,this.mediaAttachWatch=null}emitChange(e){for(const t of Array.from(this.listeners))try{t(e)}catch(r){vc.warn("listener failed",r)}}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}setPendingSessionCommit(e){this.pendingSessionCommit=e}commitPendingItemSessions(){if(this.pendingSessionCommit)try{this.pendingSessionCommit()}catch(e){vc.warn("pending session commit failed",e)}}async initialize(e){const t=e;if(!t)return;const r=this.state.input?.section?.identifier||this.state.input?.sectionId||void 0,n=this.contentService.build(t.section,t.view),i=this.sessionService.resolve({...t,adapterItemRefs:n.adapterItemRefs}),o=i.testAttemptSession?.navigationState?.currentItemIndex??0;this.state={input:t,viewModel:{...n,currentItemIndex:o,isPageMode:!!t.section&&"keepTogether"in t.section&&t.section.keepTogether===!0},testAttemptSession:i.testAttemptSession};const s=t.section?.identifier||t.sectionId||void 0,a=r!==s;if(a&&this.resetLifecycleTracking(),this.rebuildFormativePolicies(),this.rebuildTimedMedia(),this.bootstrapCompletionFromSessions(),a){const l={type:"section-navigation-change",previousSectionId:r,currentSectionId:s,reason:"input-change",timestamp:Date.now()};this.emitChange(l)}}async updateInput(e){this.commitPendingItemSessions();const t=this.getSession();await this.initialize(e),t&&this.applySessionState(t,"replace",!1)}configureSessionPersistence(e){this.sessionPersistence=e}async hydrate(){if(!this.sessionPersistence)return;const e=await this.sessionPersistence.strategy.loadSession(this.sessionPersistence.context);e&&await this.applySession(e,{mode:"replace"})}async persist(){this.sessionPersistence&&(this.commitPendingItemSessions(),await this.sessionPersistence.strategy.saveSession(this.sessionPersistence.context,this.getSession()))}dispose(){this.pendingSessionCommit=null,this.clearMediaAttachWatch(),this.detachMediaTimeSource(),this.listeners.clear(),this.resetLifecycleTracking(),this.pendingApplyReplay=null,this.nextApplyRevision=0,this.lastReplayedApplyRevision=0}getViewModel(){return this.cloneForRead(this.state.viewModel)}getCompositionModel(){const e=this.getItemViewModels();return{section:this.state.input?.section||null,assessmentItemRefs:this.state.input?.section?.assessmentItemRefs||[],passages:this.state.viewModel.passages,items:this.state.viewModel.items,rubricBlocks:this.state.viewModel.rubricBlocks,instructions:this.state.viewModel.instructions,renderables:this.state.viewModel.renderables,currentItemIndex:this.state.viewModel.currentItemIndex,currentItem:this.getCurrentItem(),isPageMode:this.state.viewModel.isPageMode,itemSessionsByItemId:this.getItemSessionsByItemId(),testAttemptSession:this.getResolvedTestAttemptSession(),itemViewModels:e,formative:this.getFormativeProjection(),timedMedia:this.getTimedMediaProjection()}}getInstructions(){return this.cloneForRead(this.state.viewModel.instructions)}getSectionLoadedEventDetail(){return{sectionId:this.state.input?.section?.identifier||this.state.input?.sectionId||"",itemCount:this.state.viewModel.items.length,passageCount:this.state.viewModel.passages.length,isPageMode:this.state.viewModel.isPageMode}}getResolvedItemSessions(){return this.state.testAttemptSession?fv(this.state.testAttemptSession):{}}getResolvedTestAttemptSession(){return this.cloneForRead(this.state.testAttemptSession)}getCanonicalItemId(e){return e&&(this.state.viewModel.adapterItemRefs.find(t=>t.item?.id===e)?.identifier||e)}getItemViewModels(){const e=this.getItemSessionsByItemId();return this.state.viewModel.items.map((t,r)=>{const n=t.id||"",i=this.getCanonicalItemId(n);return{item:t,itemId:n,canonicalItemId:i,index:r,isCurrent:r===this.state.viewModel.currentItemIndex,session:e[n]??e[i]}})}getItemSessionsByItemId(){const e=this.getResolvedItemSessions(),t=Object.fromEntries(this.state.viewModel.adapterItemRefs.map(r=>{const n=r.item?.id;if(!n)return null;const i=r.identifier||n;return[n,e[i]??e[n]]}).filter(r=>!!r&&typeof r[0]=="string"&&!!r[0]));for(const[r,n]of Object.entries(e))r in t||(t[r]=n);return t}getSession(){if(!this.state.testAttemptSession)return null;const e=this.sessionService.toSessionState(this.state.testAttemptSession),t=this.formativeEnabled?{...e,formative:PD(this.formativeStates)}:e;return this.timedMediaData?{...t,timedMedia:M4(this.timedMediaState)}:t}rebuildFormativePolicies(){const e=this.state.input?.section?.formative??null,t=this.state.viewModel.adapterItemRefs.map(r=>({identifier:r.identifier||r.item?.id||"",policy:r.formative??null})).filter(r=>!!r.identifier);this.formativePolicies=uD({sectionPolicy:e,items:t}),this.formativeEnabled=fD(this.formativePolicies)}computeMastery(){return TD({itemIdentifiers:this.getSectionItemIdentifiers(),states:this.formativeStates})}getFormativeProjection(){return this.formativeEnabled?this.cloneForRead({version:1,enabled:!0,policies:this.formativePolicies,states:this.formativeStates,mastery:this.computeMastery()}):null}recordFormativeTry(e){const t=this.getCanonicalItemId(e.itemId),r=this.formativePolicies[t];if(!r?.enabled)return;const n=gD(e.outcomes??[]),i=this.formativeStates[t],o=yD({state:i,itemIdentifier:t,policy:r,outcome:n});if(o===i)return;this.formativeStates={...this.formativeStates,[t]:o};const s=Date.now(),a={type:"formative-try-recorded",itemId:e.itemId,canonicalItemId:t,tryCount:o.tryCount,outcome:n,revealed:o.revealed,currentItemIndex:this.state.viewModel.currentItemIndex??0,timestamp:s};this.emitChange(a),this.emitMasteryIfChanged(s),this.notifyTimedMediaDeliveryChanged()}retryFormativeItem(e){const t=this.getCanonicalItemId(e.itemId),r=this.formativePolicies[t];if(!r?.enabled)return;const n=this.formativeStates[t],i=bD({state:n,policy:r});!i||i===n||this.commitFormativeReveal({itemId:e.itemId,canonicalItemId:t,next:i,source:"learner"})}revealFormativeItem(e){const t=this.getCanonicalItemId(e.itemId),r=this.formativePolicies[t];if(!r?.enabled||e.feedback!=="correctness"&&e.feedback!=="solution")return;const n=this.formativeStates[t],i=wD({state:n,itemIdentifier:t,policy:r,feedback:e.feedback});i!==n&&this.commitFormativeReveal({itemId:e.itemId,canonicalItemId:t,next:i,source:"host"})}hideFormativeItem(e){const t=this.getCanonicalItemId(e.itemId),r=this.formativePolicies[t];if(!r?.enabled)return;const n=this.formativeStates[t],i=SD({state:n,policy:r});!i||i===n||this.commitFormativeReveal({itemId:e.itemId,canonicalItemId:t,next:i,source:"host"})}commitFormativeReveal(e){this.formativeStates={...this.formativeStates,[e.canonicalItemId]:e.next};const t={type:"formative-reveal-changed",itemId:e.itemId,canonicalItemId:e.canonicalItemId,revealed:e.next.revealed,feedback:e.next.revealOverride,tryCount:e.next.tryCount,source:e.source,currentItemIndex:this.state.viewModel.currentItemIndex??0,timestamp:Date.now()};this.emitChange(t),this.notifyTimedMediaDeliveryChanged()}emitMasteryIfChanged(e){if(!this.formativeEnabled)return;const t=this.computeMastery(),r=JSON.stringify(t);if(r===this.lastMasterySignature)return;this.lastMasterySignature=r;const n={type:"section-mastery-changed",mastery:t,currentItemIndex:this.state.viewModel.currentItemIndex??0,timestamp:e};this.emitChange(n)}getSectionItemIdentifiers(){const e=this.state.viewModel.adapterItemRefs.map(t=>t.identifier||t.item?.id).filter(t=>typeof t=="string"&&!!t);return e.length>0?e:this.state.viewModel.items.map(t=>t.id).filter(t=>typeof t=="string"&&!!t)}rebuildTimedMedia(){const e=this.state.input?.section??null;if(this.clearMediaAttachWatch(),!e||e.sectionType!=="timed-media"){this.timedMediaData=null,this.lastTimedMediaInvalidSignature="";return}const t=S4({timedMedia:e.timedMedia,itemIdentifiers:this.getSectionItemIdentifiers(),resolveStimulusRenderableId:r=>this.state.viewModel.stimulusRenderableIdsByRef?.[r],resolveItemTryBudget:r=>{const n=this.formativePolicies[r];return n?.enabled?n.maxTries==="unlimited"?"unlimited":"finite":"not-formative"}});if(this.timedMediaData=t.data,t.data){this.lastTimedMediaInvalidSignature="";return}this.reportTimedMediaInvalid(t.errors)}reportTimedMediaInvalid(e){const t=JSON.stringify(e);if(t===this.lastTimedMediaInvalidSignature)return;this.lastTimedMediaInvalidSignature=t;const r={type:"timed-media-invalid",errors:e,currentItemIndex:this.state.viewModel.currentItemIndex??0,timestamp:Date.now()};this.emitChange(r)}resolveTimedMediaView(e){return this.timedMediaData?A4({data:this.timedMediaData,state:this.timedMediaState,delivery:e??this.getTimedMediaDeliveryState(),capabilities:this.mediaTimeSource?.capabilities??null}):null}getTimedMediaProjection(){return this.cloneForRead(this.resolveTimedMediaView())}getTimedMediaDeliveryState(){const e={};for(const[r,n]of this.itemCompletionByCanonicalId)e[r]=n===!0;const t={};for(const[r,n]of Object.entries(this.formativeStates)){const i=n.lastOutcome?.correctness;i&&(t[r]=i)}return{respondedByItemId:e,correctnessByItemId:t,itemsComplete:this.sectionItemsComplete}}attachMediaTimeSource(e,t){if(!e||typeof e.subscribe!="function"||this.mediaTimeSource===e)return;const r=t?.origin??"host";r==="native-adapter"&&t?.renderableId&&this.timedMediaData&&t.renderableId!==this.timedMediaData.stimulusRenderableId||r==="native-adapter"&&this.mediaTimeSource&&this.mediaTimeSourceOrigin==="host"||(this.detachMediaTimeSource(),this.mediaTimeSource=e,this.mediaTimeSourceOrigin=r,this.timedMediaData&&(this.clearMediaAttachWatch(),this.reportedDegradationKeys.clear(),this.unsubscribeMediaTimeSource=e.subscribe(n=>{switch(n.type){case"time":this.advanceTimedMedia({kind:"time",currentTimeSeconds:n.currentTime});return;case"seek":this.advanceTimedMedia({kind:"seek",currentTimeSeconds:n.currentTime});return;case"ended":this.advanceTimedMedia({kind:"ended",currentTimeSeconds:n.currentTime});return;case"play":this.advanceTimedMedia({kind:"time",currentTimeSeconds:n.currentTime}),this.announceMediaAudioStarted();return;default:return}}),this.reportTimedMediaDegradations(),this.syncMediaPositionFromState(),this.advanceTimedMedia({kind:"time",currentTimeSeconds:e.currentTime})))}detachMediaTimeSource(e){e?.origin==="native-adapter"&&this.mediaTimeSource&&this.mediaTimeSourceOrigin==="host"||(this.unsubscribeMediaTimeSource?.(),this.unsubscribeMediaTimeSource=null,this.mediaTimeSource=null)}armMediaAttachWatch(){this.timedMediaData&&(this.mediaTimeSource||this.mediaAttachWatch===null&&(this.mediaAttachWatch=setTimeout(()=>{this.mediaAttachWatch=null,this.reportStimulusExposesNoTimeSource()},oq),this.mediaAttachWatch.unref?.()))}clearMediaAttachWatch(){this.mediaAttachWatch!==null&&(clearTimeout(this.mediaAttachWatch),this.mediaAttachWatch=null)}reportStimulusExposesNoTimeSource(){const e=this.timedMediaData;!e||this.mediaTimeSource||(this.timedMediaData=null,this.lastTimedMediaSignature="",this.reportTimedMediaInvalid([{code:"stimulus-exposes-no-time-source",message:`timedMedia.stimulusRef "${e.stimulusRef}" resolved to renderable "${e.stimulusRenderableId}", which exposed no Media Time Source, so no cue could fire. The section delivers every item instead.`}]))}syncMediaPositionFromState(){const e=this.mediaTimeSource;if(!e)return;const t=this.timedMediaState.mediaCurrentTime;if(t>0&&!(e.currentTime>=t-.5))try{e.seekTo(t)}catch(r){vc.warn("media time source rejected a resume seek",r)}}advanceTimedMedia(e){const t=this.timedMediaData;if(!t)return;const r=this.getTimedMediaDeliveryState(),n=x4({state:this.timedMediaState,data:t,delivery:r,input:e});this.timedMediaState=n.state,this.applyTimedMediaEffects(n.effects),this.emitTimedMediaIfChanged(n.effects,r)}pauseMediaForCompetingAudio(){const e=this.mediaTimeSource;if(!e||e.paused)return!0;if(!e.capabilities.canPause)return!1;try{e.pause()}catch(t){return vc.warn("media time source rejected an audio-handoff pause",t),!1}return!0}announceMediaAudioStarted(){if(!this.timedMediaData||this.mediaTimeSource?.paused!==!1)return;const e={type:"timed-media-audio-started",currentItemIndex:this.state.viewModel.currentItemIndex??0,timestamp:Date.now()};this.emitChange(e)}applyTimedMediaEffects(e){const t=this.mediaTimeSource;if(t){if(e.seekToSeconds!==void 0&&t.capabilities.canRestrictSeeking)try{t.seekTo(e.seekToSeconds)}catch(r){vc.warn("media time source rejected a seek clamp",r)}if(e.pause&&t.capabilities.canPause&&!t.paused)try{t.pause()}catch(r){vc.warn("media time source rejected a pause",r)}}}reportTimedMediaDegradations(){const e=this.timedMediaData;if(!e)return;const{degradations:t}=GR({playbackPolicy:e.playbackPolicy,capabilities:this.mediaTimeSource?.capabilities??null,hasGate:e.cues.some(i=>i.activation==="gate")}),r=t.filter(i=>!this.reportedDegradationKeys.has(i.policy));if(r.length===0)return;for(const i of r)this.reportedDegradationKeys.add(i.policy);const n={type:"timed-media-policy-degraded",degradations:r,currentItemIndex:this.state.viewModel.currentItemIndex??0,timestamp:Date.now()};this.emitChange(n)}emitTimedMediaIfChanged(e,t){const r=this.resolveTimedMediaView(t);if(!r)return;const n=XR(r);if(n===this.lastTimedMediaSignature)return;this.lastTimedMediaSignature=n;const i={type:"timed-media-cue-changed",activatedCueIdentifier:e.activatedCueIdentifier,releasedCueIdentifier:e.releasedCueIdentifier,activeCueIdentifier:r.activeCueIdentifier,visitedCueIdentifiers:r.visitedCueIdentifiers,completedCueIdentifiers:r.completedCueIdentifiers,revealedItemIds:r.revealedItemIds,gateCueIdentifier:r.gate?.cueIdentifier??null,mediaCompleted:r.mediaCompleted,aggregateComplete:r.aggregateComplete,currentItemIndex:this.state.viewModel.currentItemIndex??0,timestamp:Date.now()};this.emitChange(i)}notifyTimedMediaDeliveryChanged(){this.timedMediaData&&this.advanceTimedMedia({kind:"delivery-changed"})}getRuntimeState(){if(!this.state.testAttemptSession)return null;const e=this.getSectionItemIdentifiers(),t=e[this.state.viewModel.currentItemIndex]||"",r=new Set(this.state.testAttemptSession.navigationState.visitedItemIdentifiers||[]),n=e.filter(s=>r.has(s)),i={};for(const s of this.state.viewModel.adapterItemRefs){const a=s.identifier||s.item?.id,l=s.item?.id;if(!a)continue;const d=this.state.testAttemptSession?.itemSessions?.[a]?.session??(l?this.state.testAttemptSession?.itemSessions?.[l]?.session:void 0);d&&(i[a]=d)}const o=this.collectLoadedRenderableSnapshot();return{sectionId:this.state.input?.sectionId||"",sectionIdentifier:this.state.input?.section?.identifier||this.state.input?.sectionId||void 0,currentItemIndex:this.state.viewModel.currentItemIndex,currentItemId:t,itemIdentifiers:e,visitedItemIdentifiers:n,itemSessions:i,loadingComplete:this.sectionLoadingComplete,totalRegistered:this.totalRegistered,totalLoaded:this.totalLoaded,itemsComplete:this.sectionItemsComplete,completedCount:this.completedCount,totalItems:this.totalItems,loadedRenderables:o}}collectLoadedRenderableSnapshot(){if(this.loadedRenderableKeys.size===0)return[];const e=[];for(const[t,r]of this.trackedRenderables)this.loadedRenderableKeys.has(t)&&e.push({itemId:r.itemId,canonicalItemId:r.canonicalItemId,contentKind:r.contentKind});return e}getCurrentItem(){return this.state.viewModel.items[this.state.viewModel.currentItemIndex]||null}getCurrentItemSession(){const e=this.getCurrentItem();if(e?.id)return this.getItemSessionsByItemId()[e.id]}getNavigationState(e=!1){const t=this.state.viewModel.currentItemIndex,r=this.state.viewModel.items.length;return{currentIndex:t,totalItems:r,canNext:t<r-1,canPrevious:t>0,isLoading:e}}updateItemSession(e,t){if(!this.state.testAttemptSession)return null;const r=this.getResolvedItemSessions(),n=this.sessionService.applyItemSessionChanged({itemId:e,sessionDetail:t,testAttemptSession:this.state.testAttemptSession,itemSessions:r});this.state.testAttemptSession=n.testAttemptSession;const i=this.getCanonicalItemId(n.eventDetail.itemId),o=n.eventDetail.timestamp,s=n.eventDetail.intent,a=typeof n.eventDetail.complete=="boolean"?n.eventDetail.complete:this.readCompleteFromSession(n.eventDetail.session),{elementId:l,sessionCommitReason:d}=n.eventDetail,c={...l?{elementId:l}:{},sectionId:this.state.input?.sectionId||"",...d?{sessionCommitReason:d}:{}};if(s==="metadata-only"){const u={type:"item-session-meta-changed",itemId:n.eventDetail.itemId,canonicalItemId:i,complete:n.eventDetail.complete,component:n.eventDetail.component,...c,currentItemIndex:this.state.viewModel.currentItemIndex??0,timestamp:o};this.emitChange(u)}else{const u={type:"item-session-data-changed",itemId:n.eventDetail.itemId,canonicalItemId:i,session:n.eventDetail.session,intent:n.eventDetail.intent,complete:n.eventDetail.complete,component:n.eventDetail.component,...c,currentItemIndex:this.state.viewModel.currentItemIndex??0,timestamp:o};this.emitChange(u)}return typeof a=="boolean"&&(this.reportedCompletionIds.add(i),this.updateItemCompleteState({itemId:n.eventDetail.itemId,canonicalItemId:i,complete:this.recordElementCompletion(i,l,a),timestamp:o})),n}async applySession(e,t){!this.state.testAttemptSession||!e||this.applySessionState(e,t?.mode||"replace",!0)}applySessionState(e,t,r){if(!this.state.testAttemptSession)return;const n=this.normalizeApplySession(e);this.applyNormalizedSessionToState(n,t),this.bootstrapCompletionFromSessions(r?new Set(Object.keys(n.itemSessions)):void 0),this.emitMasteryIfChanged(Date.now()),this.syncMediaPositionFromState(),this.notifyTimedMediaDeliveryChanged();const i=++this.nextApplyRevision;this.sectionLoadingComplete||(this.pendingApplyReplay={revision:i,mode:t,session:this.cloneForRead(e),restore:r});const o={type:"section-session-applied",mode:t,itemSessionCount:n.itemSessionCount,replay:!1,currentItemIndex:this.state.viewModel.currentItemIndex??0,timestamp:Date.now()};this.emitChange(o)}navigateToItem(e){if(!this.state.testAttemptSession)return null;this.commitPendingItemSessions();const t=this.itemNavigationService.navigate({index:e,items:this.state.viewModel.items,currentItemIndex:this.state.viewModel.currentItemIndex,sectionIdentifier:this.state.input?.section?.identifier||this.state.input?.sectionId,testAttemptSession:this.state.testAttemptSession});if(!t)return null;this.state.viewModel.currentItemIndex=t.nextIndex,this.state.testAttemptSession=t.testAttemptSession;const r={type:"item-selected",previousItemId:t.eventDetail.previousItemId,currentItemId:t.eventDetail.currentItemId,itemIndex:t.eventDetail.itemIndex,totalItems:t.eventDetail.totalItems,itemLabel:t.eventDetail.itemLabel,currentItemIndex:this.state.viewModel.currentItemIndex??0,timestamp:t.eventDetail.timestamp};return this.emitChange(r),t}handleContentRegistered(e){const t=this.getCanonicalItemId(e.canonicalItemId||e.itemId),r=this.getRenderableKey(t,e.contentKind),n=this.toSectionContentKind(e.contentKind),i=this.trackedRenderables.get(r);i&&i.itemId===e.itemId&&i.canonicalItemId===t&&i.contentKind===n||(this.trackedRenderables.set(r,{itemId:e.itemId,canonicalItemId:t,contentKind:n}),this.evaluateSectionLoadingState(Date.now()))}handleContentUnregistered(e){const t=this.getCanonicalItemId(e.canonicalItemId||e.itemId),r=this.getRenderableKey(t,e.contentKind);this.trackedRenderables.delete(r),this.loadedRenderableKeys.delete(r),this.evaluateSectionLoadingState(Date.now())}handleContentLoaded(e){const t=e.timestamp??Date.now(),r=this.getCanonicalItemId(e.canonicalItemId||e.itemId),n=this.toSectionContentKind(e.contentKind),i=this.getRenderableKey(r,n);if(this.loadedRenderableKeys.has(i))return;this.loadedRenderableKeys.add(i);const o={type:"content-loaded",contentKind:n,itemId:e.itemId,canonicalItemId:r,detail:e.detail,currentItemIndex:this.state.viewModel.currentItemIndex??0,timestamp:t};this.emitChange(o),this.evaluateSectionLoadingState(t)}handleItemPlayerError(e){const t=e.timestamp??Date.now(),r=this.getCanonicalItemId(e.canonicalItemId||e.itemId),n=this.toSectionContentKind(e.contentKind),i={type:"item-player-error",contentKind:n,itemId:e.itemId,canonicalItemId:r,error:e.error,currentItemIndex:this.state.viewModel.currentItemIndex??0,timestamp:t};this.emitChange(i),this.reportSectionError({source:"item-player",error:e.error,itemId:e.itemId,canonicalItemId:r,contentKind:n,timestamp:t})}reportSectionError(e){const t={type:"section-error",source:e.source,error:e.error,itemId:e.itemId,canonicalItemId:e.canonicalItemId,contentKind:e.contentKind?this.toSectionContentKind(e.contentKind):void 0,currentItemIndex:this.state.viewModel.currentItemIndex??0,timestamp:e.timestamp??Date.now()};this.emitChange(t)}resetLifecycleTracking(){this.trackedRenderables.clear(),this.loadedRenderableKeys.clear(),this.itemCompletionByCanonicalId.clear(),this.elementCompletionByCanonicalId.clear(),this.reportedCompletionIds.clear(),this.sectionLoadingComplete=!1,this.totalRegistered=0,this.totalLoaded=0,this.sectionItemsComplete=!1,this.completedCount=0,this.totalItems=0,this.formativeStates={},this.lastMasterySignature="",this.timedMediaState=Ph(),this.lastTimedMediaSignature="",this.reportedDegradationKeys.clear()}toSectionContentKind(e){const t=String(e||"").toLowerCase();return t==="item"||t.includes("assessment-item")?"item":t==="passage"?"passage":t==="rubric"||t.includes("rubric")?"rubric":"unknown"}getRenderableKey(e,t){return`${this.toSectionContentKind(t)}:${e}`}readCompleteFromSession(e){if(!e||typeof e!="object")return;const t=e.complete;return typeof t=="boolean"?t:void 0}sessionHoldsResponse(e){if(!e||typeof e!="object")return!1;const t=e.data;return nb(Array.isArray(t)?t:e)}bootstrapCompletionFromSessions(e=new Set){const t=this.getItemViewModels();for(const r of t){const n=r.canonicalItemId,i=this.readCompleteFromSession(r.session);typeof i=="boolean"?(this.elementCompletionByCanonicalId.delete(n),this.itemCompletionByCanonicalId.set(n,i)):(e.has(n)||!this.reportedCompletionIds.has(n))&&(this.elementCompletionByCanonicalId.delete(n),this.reportedCompletionIds.delete(n),this.itemCompletionByCanonicalId.set(n,this.sessionHoldsResponse(r.session)))}this.emitSectionItemsCompleteIfChanged(Date.now()),this.notifyTimedMediaDeliveryChanged()}recordElementCompletion(e,t,r){if(!t)return this.elementCompletionByCanonicalId.delete(e),r;let n=this.elementCompletionByCanonicalId.get(e);n||(n=new Map,this.elementCompletionByCanonicalId.set(e,n)),n.set(t,r);for(const i of n.values())if(!i)return!1;return!0}updateItemCompleteState(e){const t=this.itemCompletionByCanonicalId.get(e.canonicalItemId)??!1;if(t===e.complete){this.emitSectionItemsCompleteIfChanged(e.timestamp);return}this.itemCompletionByCanonicalId.set(e.canonicalItemId,e.complete);const r={type:"item-complete-changed",itemId:e.itemId,canonicalItemId:e.canonicalItemId,complete:e.complete,previousComplete:t,currentItemIndex:this.state.viewModel.currentItemIndex??0,timestamp:e.timestamp};this.emitChange(r),this.emitSectionItemsCompleteIfChanged(e.timestamp),this.notifyTimedMediaDeliveryChanged()}emitSectionItemsCompleteIfChanged(e){const t=this.getItemViewModels(),r=t.length;if(this.totalItems=r,r===0){this.completedCount=0,this.sectionItemsComplete=!1;return}let n=0;for(const s of t)this.itemCompletionByCanonicalId.get(s.canonicalItemId)===!0&&(n+=1);const i=n===r;if(this.completedCount=n,this.sectionItemsComplete===i)return;this.sectionItemsComplete=i;const o={type:"section-items-complete-changed",complete:i,completedCount:n,totalItems:r,currentItemIndex:this.state.viewModel.currentItemIndex??0,timestamp:e};this.emitChange(o)}evaluateSectionLoadingState(e){const t=this.trackedRenderables.size,r=this.loadedRenderableKeys.size;this.totalRegistered=t,this.totalLoaded=r;const n=t>0&&r>=t;if(n===this.sectionLoadingComplete||(this.sectionLoadingComplete=n,!n))return;const i={type:"section-loading-complete",totalRegistered:t,totalLoaded:r,currentItemIndex:this.state.viewModel.currentItemIndex??0,timestamp:e};this.emitChange(i),this.armMediaAttachWatch(),this.replayPendingAppliedSession()}async replayPendingAppliedSession(){const e=this.pendingApplyReplay;if(!e||e.revision<=this.lastReplayedApplyRevision||!this.sectionLoadingComplete)return;const t=this.normalizeApplySession(e.session);if(!this.state.testAttemptSession)return;this.applyNormalizedSessionToState(t,e.mode),this.bootstrapCompletionFromSessions(e.restore?new Set(Object.keys(t.itemSessions)):void 0),this.lastReplayedApplyRevision=e.revision;const r={type:"section-session-applied",mode:e.mode,itemSessionCount:t.itemSessionCount,replay:!0,currentItemIndex:this.state.viewModel.currentItemIndex??0,timestamp:Date.now()};this.emitChange(r)}normalizeApplySession(e){const t=e.itemSessions&&typeof e.itemSessions=="object"?e.itemSessions:{},r=new Set(this.state.viewModel.adapterItemRefs.map(s=>this.getCanonicalItemId(s.identifier||s.item?.id||"")).filter(s=>typeof s=="string"&&!!s)),n={};for(const[s,a]of Object.entries(t)){const l=this.getCanonicalItemId(s);if(!r.has(l))continue;const d=this.normalizeItemSessionEntry(l,a);d&&(n[l]=d)}const i=Array.isArray(e.visitedItemIdentifiers)?Array.from(new Set(e.visitedItemIdentifiers.map(s=>this.getCanonicalItemId(s)).filter(s=>r.has(s)))):void 0,o=Math.max(0,this.state.viewModel.items.length-1);return{currentItemIndex:typeof e.currentItemIndex=="number"&&Number.isFinite(e.currentItemIndex)?Math.min(Math.max(0,e.currentItemIndex),o):void 0,visitedItemIdentifiers:i,itemSessions:n,itemSessionCount:Object.keys(n).length,formativeStates:AD({slice:e.formative,allowedItemIdentifiers:Array.from(r)}),timedMediaState:$4({slice:e.timedMedia,data:this.timedMediaData})}}normalizeItemSessionEntry(e,t){if(!t||typeof t!="object")return null;const r=t,n=r;if(typeof n.itemIdentifier=="string"&&n.session&&typeof n.session=="object")return{itemIdentifier:e,attemptCount:typeof n.attemptCount=="number"&&Number.isFinite(n.attemptCount)?n.attemptCount:1,isCompleted:!!n.isCompleted,session:n.session};const i=n.session&&typeof n.session=="object"?n.session:r;return{itemIdentifier:e,attemptCount:1,isCompleted:typeof n.complete=="boolean"?n.complete:!!i.complete,session:i}}applyNormalizedSessionToState(e,t){this.state.testAttemptSession&&(t==="merge"?this.state.testAttemptSession.itemSessions={...this.state.testAttemptSession.itemSessions,...e.itemSessions}:this.state.testAttemptSession.itemSessions=e.itemSessions,Array.isArray(e.visitedItemIdentifiers)?this.state.testAttemptSession.navigationState.visitedItemIdentifiers=e.visitedItemIdentifiers:t==="replace"&&(this.state.testAttemptSession.navigationState.visitedItemIdentifiers=[]),typeof e.currentItemIndex=="number"?(this.state.testAttemptSession.navigationState.currentItemIndex=e.currentItemIndex,this.state.viewModel.currentItemIndex=e.currentItemIndex):t==="replace"&&(this.state.testAttemptSession.navigationState.currentItemIndex=0,this.state.viewModel.currentItemIndex=0),e.formativeStates?this.formativeStates=t==="merge"?{...this.formativeStates,...e.formativeStates}:e.formativeStates:t==="replace"&&(this.formativeStates={}),e.timedMediaState?this.timedMediaState=e.timedMediaState:t==="replace"&&this.timedMediaData&&(this.timedMediaState=Ph()),this.lastMasterySignature="",this.lastTimedMediaSignature="")}cloneForRead(e){if(e==null)return e;try{return structuredClone(e)}catch{try{return JSON.parse(JSON.stringify(e))}catch{return e}}}},nk=new WeakMap,aq=100,lq=300;function cq(e,t){let r;try{const i=e.getPolicyInputs().tools.placement;r=new Set(Object.values(i).flatMap(o=>Array.isArray(o)?o:[]))}catch{return}let n=nk.get(e);for(const i of r){if(n?.has(i))continue;const o=t.get(i);if(!o?.provider)continue;let s;try{const a=e.getToolConfig(i)??void 0;if(a?.enabled===!1)continue;s=I$(o,a)}catch{continue}!s||e.toolProviderRegistry.has(s)||(n||(n=new Set,nk.set(e,n)),n.add(i),console.warn(`[pie-section-player] Placed tool "${i}" uses provider "${s}", which the host-supplied coordinator (runtime.coordinator) has not registered. That coordinator registers tool providers only from the \`toolRegistry\` it was constructed with: include this tool's registration there — for the packaged capability set, \`createPackagedToolRegistry()\` from "@pie-players/pie-default-tool-loaders" — or construct it without one to use the section player's. Reported once per tool and coordinator.`))}}function dq(e,t){let r=!1,n;const i=()=>{clearInterval(n),n=void 0},o=()=>{let l=!1;try{l=e.isReady()}catch{return i(),!0}return l?(i(),cq(e,t),!0):!1},s=()=>{if(r||o()||n!==void 0)return;let l=0;n=setInterval(()=>{l+=1,!o()&&l>=lq&&i()},aq)},a=e.onPolicyChange(l=>{if(l.reason==="disposed"){i();return}queueMicrotask(s)});return s(),()=>{r=!0,i(),a()}}var uq=Ht('<pie-assessment-toolkit><div class="pie-section-player-surface-anchor svelte-k22ow9"></div> <!></pie-assessment-toolkit>',2),fq={hash:"svelte-k22ow9",code:`:host {display:block;width:100%;height:100%;min-height:0;}
1540
+
1541
+ /* Layout-transparent: the anchor is always present, and a permanent flex item
1542
+ would shift \`gap\` and child-index selectors in the column below it whether or
1543
+ not any capability is mounted. */.pie-section-player-surface-anchor.svelte-k22ow9 {display:contents;}pie-assessment-toolkit.svelte-k22ow9 {display:flex;flex-direction:column;flex:1;width:100%;height:100%;min-height:0;overflow:hidden;}`};function hq(e,t){un(t,!0),Mn(e,fq);const r=Ys("pie-section-player",()=>!1);let n=_(t,"assessmentId",7,rI),i=_(t,"runtime",7,null),o=_(t,"ndsIcons",7,!1),s=_(t,"locale",7,""),a=_(t,"section",7,null),l=_(t,"sectionId",7,""),d=_(t,"attemptId",7,""),c=_(t,"toolRegistry",7,null),u=_(t,"toolConfigStrictness",7,void 0),f=_(t,"onFrameworkError",7,void 0),p=_(t,"onStageChange",7,void 0),g=He(null),v=He(null);const b=ee(()=>i()?.assessmentId??n()),w=ee(()=>i()?.playerType),I=ee(()=>i()?.player??null),x=ee(()=>i()?.lazyInit),C=ee(()=>i()?.tools??null),L=ee(()=>i()?.toolContextResolvers??null),E=ee(()=>{const Se=i()?.toolConfigStrictness??u();return Se==="off"||Se==="warn"||Se==="error"?Se:"error"}),M=ee(()=>i()?.accessibility??null),U=ee(()=>i()?.coordinator??null),te=ee(()=>i()?.createSectionController),re=ee(()=>i()?.isolation??"inherit"),Pe=ee(()=>i()?.env??NR),z=ee(()=>(i()?.ndsIcons??o())===!0?!0:void 0),K=ee(()=>i()?.locale||s()||void 0);let oe=He(null);const ue=ee(()=>xa(h(oe)));ct(()=>{const Se=h(O);if(Se)return ck(Se,Re=>{be(oe,Re,!0)})});const ae=t_({toolModuleLoaders:e_}),X=ee(()=>c()??ae),j=ee(()=>DR({runtime:i(),onFrameworkError:f()})),D=ee(()=>i()?.onStageChange??p()),Z=ee(()=>l()||a()?.identifier||"");function F(Se){const Re=Se.detail?.coordinator;Re&&be(v,Re,!0)}ct(()=>{const Se=h(v),Re=h(X);if(!(!Se||Se!==h(U)))return on(()=>dq(Se,Re))});const W="section-overlay";let O=He(null);const $=dw(()=>{},{hostLabel:"pie-section-player"});ct(()=>{const Se=h(v);h(ue),$.update({anchor:h(O),surface:W,registry:h(X),services:{toolkitCoordinator:Se,ttsService:Se?.ttsService??null,catalogResolver:Se?.catalogResolver??null,i18n:h(ue)},scope:{kind:"section",assessmentId:h(b),sectionId:h(Z)}})}),Xp(()=>$.destroy()),ct(()=>{if(!h(g))return;const Se=h(g),Re=h(te),mt=typeof Re=="function"?Re:()=>new sq,$t=le=>{ib(Se,{reason:le,logger:r})},ve=le=>{le?.setPendingSessionCommit?.(()=>$t("navigate"))},me=()=>{$t("teardown");const le=mt();return ve(le),le},Je=Se.createSectionController;Se.createSectionController=me,ve(ge());let Gt=!1;return(async()=>{const le=Date.now()+1e4;for(;!Gt&&Date.now()<le;){const Ae=ge();if(Ae){Gt||ve(Ae);return}await new Promise(Y=>setTimeout(Y,25))}})(),()=>{Gt=!0,Se.createSectionController===me&&(Se.createSectionController=Je)}}),ct(()=>{if(typeof window>"u")return;const Se=h(g);if(Se)return d$({root:()=>Se,logger:r})}),ct(()=>{if(h(g))return h(g).onFrameworkError=h(j),()=>{h(g).onFrameworkError=void 0}}),ct(()=>{if(h(g))return h(g).onStageChange=h(D),()=>{h(g).onStageChange=void 0}});function ie(Se){return h(g)?.navigateToItem?h(g).navigateToItem(Se):null}function N(){return h(g)?.getCompositionModel?h(g).getCompositionModel():null}function ne(){const Se=N(),Re=Se?.items||[],mt=Math.max(0,Math.min(typeof Se?.currentItemIndex=="number"?Se.currentItemIndex:0,Math.max(0,Re.length-1)));return{currentIndex:mt,totalItems:Re.length,canNext:mt<Re.length-1,canPrevious:mt>0,currentItemId:Re[mt]?.id||void 0}}function ge(){const Se=h(Z);if(!Se)return null;const Re=d()||void 0,mt=h(v)||h(U);return mt?.getSectionController&&mt.getSectionController({sectionId:Se,attemptId:Re})||null}function Oe(){return ge()}async function We(Se=5e3){const Re=Date.now();for(;Date.now()-Re<Se;){const mt=ge();if(mt)return mt;await new Promise($t=>setTimeout($t,25))}return null}var Ne={navigateToItem:ie,getCompositionModelSnapshot:N,getNavigationStateSnapshot:ne,getSectionController:Oe,waitForSectionController:We,get assessmentId(){return n()},set assessmentId(Se=rI){n(Se),R()},get runtime(){return i()},set runtime(Se=null){i(Se),R()},get ndsIcons(){return o()},set ndsIcons(Se=!1){o(Se),R()},get locale(){return s()},set locale(Se=""){s(Se),R()},get section(){return a()},set section(Se=null){a(Se),R()},get sectionId(){return l()},set sectionId(Se=""){l(Se),R()},get attemptId(){return d()},set attemptId(Se=""){d(Se),R()},get toolRegistry(){return c()},set toolRegistry(Se=null){c(Se),R()},get toolConfigStrictness(){return u()},set toolConfigStrictness(Se=void 0){u(Se),R()},get onFrameworkError(){return f()},set onFrameworkError(Se=void 0){f(Se),R()},get onStageChange(){return p()},set onStageChange(Se=void 0){p(Se),R()}},xe=uq();q(()=>G(xe,"assessment-id",h(b))),q(()=>G(xe,"section",a())),q(()=>G(xe,"section-id",l())),q(()=>G(xe,"attempt-id",d())),q(()=>G(xe,"player-type",h(w))),q(()=>G(xe,"player",h(I))),q(()=>G(xe,"env",h(Pe))),q(()=>G(xe,"nds-icons",h(z))),q(()=>G(xe,"locale",h(K))),q(()=>G(xe,"lazy-init",h(x))),q(()=>G(xe,"tool-config-strictness",h(E))),q(()=>G(xe,"tools",h(C))),q(()=>G(xe,"toolContextResolvers",h(L))),q(()=>G(xe,"toolRegistry",h(X))),q(()=>G(xe,"accessibility",h(M))),q(()=>G(xe,"coordinator",h(U))),q(()=>G(xe,"isolation",h(re))),gn(xe,1,"svelte-k22ow9");var et=Xt(xe);nt(et,"data-pie-tool-surface",W),Er(et,Se=>be(O,Se),()=>h(O));var Ue=lr(et,2);return dd(Ue,t,"default",{},null),Kt(xe),Er(xe,Se=>be(g,Se),()=>h(g)),Gn("toolkit-ready",xe,F),ft(e,xe),fn(Ne)}pq("pie-section-player-base",In(hq,{assessmentId:{attribute:"assessment-id",type:"String"},runtime:{type:"Object"},ndsIcons:{attribute:"nds-icons",type:"Boolean"},locale:{attribute:"locale",type:"String"},section:{type:"Object"},sectionId:{attribute:"section-id",type:"String"},attemptId:{attribute:"attempt-id",type:"String"},toolRegistry:{type:"Object"},toolConfigStrictness:{attribute:"tool-config-strictness",type:"String"},onFrameworkError:{type:"Object"},onStageChange:{type:"Object"}},["default"],["navigateToItem","getCompositionModelSnapshot","getNavigationStateSnapshot","getSectionController","waitForSectionController"],{mode:"open"},Zs));function pq(e,t){customElements.get(e)||customElements.define(e,t)}var mq=(e,t)=>{if(!customElements.get(e))try{customElements.define(e,t)}catch(r){if(!(r instanceof DOMException&&r.name==="NotSupportedError"||r&&typeof r=="object"&&r.name==="NotSupportedError")||!customElements.get(e))throw r}},gq=Zi("<pie-item-toolbar></pie-item-toolbar>",2);function vq(e,t){dm(t,!0);let r=wt(t,"enabledTools",7,""),n=wt(t,"position",7,"bottom"),i=wt(t,"sectionId",7,""),o=wt(t,"size",7,"md"),s=wt(t,"language",7,"en-US"),a=wt(t,"toolRegistry",7,null),l=wt(t,"item",7,null),d=wt(t,"hostButtons",23,()=>[]);var c={get enabledTools(){return r()},set enabledTools(f){r(f),gt()},get position(){return n()},set position(f){n(f),gt()},get sectionId(){return i()},set sectionId(f){i(f),gt()},get size(){return o()},set size(f){o(f),gt()},get language(){return s()},set language(f){s(f),gt()},get toolRegistry(){return a()},set toolRegistry(f){a(f),gt()},get item(){return l()},set item(f){l(f),gt()},get hostButtons(){return d()},set hostButtons(f){d(f),gt()}},u=gq();return Dn(u,"level","section"),en(()=>Dn(u,"scope-id",i())),en(()=>Dn(u,"section-id",i())),en(()=>Dn(u,"tools",r())),Dn(u,"content-kind","section"),en(()=>Dn(u,"position",n())),en(()=>Dn(u,"size",o())),en(()=>Dn(u,"language",s())),en(()=>Dn(u,"toolRegistry",a())),en(()=>Dn(u,"item",l())),en(()=>Dn(u,"hostButtons",d())),Qt(e,u),um(c)}mq("pie-section-toolbar",Mb(vq,{enabledTools:{attribute:"enabled-tools",type:"String"},position:{attribute:"position",type:"String"},sectionId:{attribute:"section-id",type:"String"},size:{attribute:"size",type:"String"},language:{attribute:"language",type:"String"},toolRegistry:{type:"Object"},item:{type:"Object"},hostButtons:{type:"Object"}},[],[],{mode:"open"}));var ik=Ht("<pie-section-toolbar></pie-section-toolbar>",2),yq=Ht('<aside class="pie-section-player-toolbar-pane pie-section-player-toolbar-pane--left svelte-1f2vjx6"><pie-section-toolbar></pie-section-toolbar></aside>',2),bq=Ht('<aside class="pie-section-player-toolbar-pane pie-section-player-toolbar-pane--right svelte-1f2vjx6"><pie-section-toolbar></pie-section-toolbar></aside>',2),wq=Ht("<div><!> <div><!> <!> <!></div> <!></div>"),Sq={hash:"svelte-1f2vjx6",code:`:host {display:block;width:100%;height:100%;min-height:0;}.pie-section-player-shell.svelte-1f2vjx6 {display:flex;flex-direction:column;height:100%;min-height:0;overflow:hidden;background:var(--pie-background-dark, #ecedf1);}.pie-section-player-layout-body.svelte-1f2vjx6 {display:grid;grid-template-columns:minmax(0, 1fr);flex:1;min-height:0;overflow:hidden;background:var(--pie-background-dark, #ecedf1);}.pie-section-player-layout-body--inline.svelte-1f2vjx6 {gap:0;}.pie-section-player-layout-body--inline-left.svelte-1f2vjx6 {grid-template-columns:auto minmax(0, 1fr);}.pie-section-player-layout-body--inline-right.svelte-1f2vjx6 {grid-template-columns:minmax(0, 1fr) auto;}.pie-section-player-toolbar-pane.svelte-1f2vjx6 {min-height:0;overflow:auto;padding:0.25rem;box-sizing:border-box;background:var(--pie-background-dark, #ecedf1);}.pie-section-player-toolbar-pane--right.svelte-1f2vjx6 {border-left:1px solid var(--pie-border-light, #e5e7eb);}.pie-section-player-toolbar-pane--left.svelte-1f2vjx6 {border-right:1px solid var(--pie-border-light, #e5e7eb);}.pie-section-player-toolbar.svelte-1f2vjx6 {margin:0.25rem;}.pie-section-player-toolbar-pane.svelte-1f2vjx6 pie-section-toolbar:where(.svelte-1f2vjx6) {margin:0.25rem;}
1544
+
1545
+ @media (max-width: 1100px) {.pie-section-player-layout-body--inline.svelte-1f2vjx6 {grid-template-columns:1fr;}.pie-section-player-toolbar-pane--left.svelte-1f2vjx6,
1546
+ .pie-section-player-toolbar-pane--right.svelte-1f2vjx6 {border:none;padding:0;}
1547
+ }`};function Iq(e,t){un(t,!0),Mn(e,Sq);const r=1100;let n=_(t,"showToolbar",7,"false"),i=_(t,"toolbarPosition",7,"right"),o=_(t,"enabledTools",7,""),s=_(t,"toolRegistry",7,null),a=_(t,"sectionHostButtons",23,()=>[]),l=He(null);const d=uf(()=>h(l));let c=He(!1);ct(()=>{if(typeof window>"u")return;const z=window.matchMedia(`(max-width: ${r}px)`),K=()=>{be(c,z.matches,!0)};return K(),z.addEventListener("change",K),()=>z.removeEventListener("change",K)});const u=ee(()=>h(c)&&(i()==="left"||i()==="right")?"top":i()),f=ee(()=>Ly(n(),!1)&&h(u)!=="none"),p=ee(()=>h(u)==="top"),g=ee(()=>h(u)==="bottom"),v=ee(()=>h(u)==="left"||h(u)==="right");var b={get showToolbar(){return n()},set showToolbar(z="false"){n(z),R()},get toolbarPosition(){return i()},set toolbarPosition(z="right"){i(z),R()},get enabledTools(){return o()},set enabledTools(z=""){o(z),R()},get toolRegistry(){return s()},set toolRegistry(z=null){s(z),R()},get sectionHostButtons(){return a()},set sectionHostButtons(z=[]){a(z),R()}},w=wq(),I=Xt(w),x=z=>{var K=ik();q(()=>G(K,"position",h(u))),q(()=>G(K,"enabled-tools",o())),q(()=>G(K,"toolRegistry",s())),q(()=>G(K,"hostButtons",a())),q(()=>gn(K,1,`pie-section-player-toolbar pie-section-player-toolbar--${h(u)}`,"svelte-1f2vjx6")),ft(z,K)};vn(I,z=>{h(f)&&h(p)&&z(x)});var C=lr(I,2),L=Xt(C),E=z=>{var K=yq(),oe=Xt(K);G(oe,"position","left"),q(()=>G(oe,"enabled-tools",o())),q(()=>G(oe,"toolRegistry",s())),q(()=>G(oe,"hostButtons",a())),gn(oe,1,"svelte-1f2vjx6"),Kt(K),q(ue=>nt(K,"aria-label",ue),[()=>d.t("player.sectionToolsA11y")]),ft(z,K)};vn(L,z=>{h(f)&&h(v)&&h(u)==="left"&&z(E)});var M=lr(L,2);dd(M,t,"default",{},null);var U=lr(M,2),te=z=>{var K=bq(),oe=Xt(K);G(oe,"position","right"),q(()=>G(oe,"enabled-tools",o())),q(()=>G(oe,"toolRegistry",s())),q(()=>G(oe,"hostButtons",a())),gn(oe,1,"svelte-1f2vjx6"),Kt(K),q(ue=>nt(K,"aria-label",ue),[()=>d.t("player.sectionToolsA11y")]),ft(z,K)};vn(U,z=>{h(f)&&h(v)&&h(u)==="right"&&z(te)}),Kt(C),Er(C,z=>be(l,z),()=>h(l));var re=lr(C,2),Pe=z=>{var K=ik();q(()=>G(K,"position",h(u))),q(()=>G(K,"enabled-tools",o())),q(()=>G(K,"toolRegistry",s())),q(()=>G(K,"hostButtons",a())),q(()=>gn(K,1,`pie-section-player-toolbar pie-section-player-toolbar--${h(u)}`,"svelte-1f2vjx6")),ft(z,K)};return vn(re,z=>{h(f)&&h(g)&&z(Pe)}),Kt(w),q(()=>{gn(w,1,`pie-section-player-shell pie-section-player-shell--${h(u)}`,"svelte-1f2vjx6"),gn(C,1,`pie-section-player-layout-body ${h(f)&&h(v)?`pie-section-player-layout-body--inline pie-section-player-layout-body--inline-${h(u)}`:""}`,"svelte-1f2vjx6")}),ft(e,w),fn(b)}kq("pie-section-player-shell",In(Iq,{showToolbar:{attribute:"show-toolbar",type:"String"},toolbarPosition:{attribute:"toolbar-position",type:"String"},enabledTools:{attribute:"enabled-tools",type:"String"},toolRegistry:{type:"Object"},sectionHostButtons:{type:"Object"}},["default"],[],{mode:"open"}));function kq(e,t){customElements.get(e)||customElements.define(e,t)}var Tq=Ht('<div class="pie-section-player-layout-scaffold-anchor svelte-11yyrx2" aria-hidden="true"></div> <div class="pie-section-player-nav-status svelte-11yyrx2" role="alert" aria-live="assertive" aria-atomic="true"> </div> <pie-section-player-base><pie-section-player-shell><!></pie-section-player-shell></pie-section-player-base>',3),Eq={hash:"svelte-11yyrx2",code:`.pie-section-player-layout-scaffold-anchor.svelte-11yyrx2 {display:none;}
1548
+
1549
+ /* Visually hidden but available to screen readers (WCAG 4.1.3). */.pie-section-player-nav-status.svelte-11yyrx2 {position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0, 0, 0, 0);white-space:nowrap;border:0;}`};function G_(e,t){un(t,!0),Mn(e,Eq);let r=_(t,"runtime",7,null),n=_(t,"section",7,null),i=_(t,"sectionId",7,""),o=_(t,"attemptId",7,""),s=_(t,"showToolbar",7,"false"),a=_(t,"toolbarPosition",7,"right"),l=_(t,"enabledTools",7,""),d=_(t,"toolRegistry",7,null),c=_(t,"sectionHostButtons",23,()=>[]),u=_(t,"cardRenderContext",7,null),f=_(t,"onCompositionChanged",7),p=_(t,"onSectionReady",7),g=_(t,"onFrameworkErrorEvent",7),v=_(t,"onToolkitReady",7),b=He(null),w=He(""),I=null;function x(N){const ne=typeof N.itemIndex=="number"?N.itemIndex+1:null,ge=typeof N.totalItems=="number"?N.totalItems:null;return N.itemLabel&&ne!==null&&ge!==null?`${N.itemLabel}, question ${ne} of ${ge}`:ne!==null&&ge!==null?`Question ${ne} of ${ge}`:""}function C(N){I?.(),I=null,N?.subscribe&&(I=N.subscribe(ne=>{ne?.type==="item-selected"&&be(w,x(ne),!0)}))}Xp(()=>{I?.()});let L=He(null),E=He(null);const M=ee(()=>Pu(h(b))),U=ee(()=>Ly(s(),!1));function te(N){f()?.(N)}function re(N){p()?.(N)}function Pe(N){g()?.(N)}function z(N){v()?.(N),C(h(L)?.getSectionController?.()??null)}function K(N){if(typeof N!="number"||!Number.isFinite(N)||!h(L)?.navigateToItem)return!1;const ne=ue(),ge=h(L).navigateToItem(N);return ue().currentIndex!==ne.currentIndex?!0:ge!=null&&ge!==!1}function oe(){return h(L)?.getCompositionModelSnapshot?.()??null}function ue(){return h(L)?.getNavigationStateSnapshot?.()||{currentIndex:0,totalItems:0,canNext:!1,canPrevious:!1}}function ae(){return h(L)?.getSectionController?.()??null}async function X(N=5e3){return h(L)?.waitForSectionController?h(L).waitForSectionController(N):null}ct(()=>{if(!(!h(M)||!u()))return be(E,Fz(h(M),u()),!0),()=>{h(E)?.disconnect(),be(E,null)}}),ct(()=>{u()&&h(E)?.setValue(u())});var j={navigateToItem:K,getCompositionModelSnapshot:oe,getNavigationStateSnapshot:ue,getSectionController:ae,waitForSectionController:X,get runtime(){return r()},set runtime(N=null){r(N),R()},get section(){return n()},set section(N=null){n(N),R()},get sectionId(){return i()},set sectionId(N=""){i(N),R()},get attemptId(){return o()},set attemptId(N=""){o(N),R()},get showToolbar(){return s()},set showToolbar(N="false"){s(N),R()},get toolbarPosition(){return a()},set toolbarPosition(N="right"){a(N),R()},get enabledTools(){return l()},set enabledTools(N=""){l(N),R()},get toolRegistry(){return d()},set toolRegistry(N=null){d(N),R()},get sectionHostButtons(){return c()},set sectionHostButtons(N=[]){c(N),R()},get cardRenderContext(){return u()},set cardRenderContext(N=null){u(N),R()},get onCompositionChanged(){return f()},set onCompositionChanged(N){f(N),R()},get onSectionReady(){return p()},set onSectionReady(N){p(N),R()},get onFrameworkErrorEvent(){return g()},set onFrameworkErrorEvent(N){g(N),R()},get onToolkitReady(){return v()},set onToolkitReady(N){v(N),R()}},D=Tq(),Z=jn(D);Er(Z,N=>be(b,N),()=>h(b));var F=lr(Z,2),W=Ta(F,!0),O=lr(F,2);q(()=>G(O,"runtime",r())),q(()=>G(O,"section",n())),q(()=>G(O,"section-id",i())),q(()=>G(O,"attempt-id",o())),q(()=>G(O,"toolRegistry",d()));var $=Xt(O);q(()=>G($,"show-toolbar",h(U))),q(()=>G($,"toolbar-position",a())),q(()=>G($,"enabled-tools",l())),q(()=>G($,"toolRegistry",d())),q(()=>G($,"sectionHostButtons",c()));var ie=Xt($);return dd(ie,t,"default",{},null),Kt($),Kt(O),Er(O,N=>be(L,N),()=>h(L)),q(()=>vs(W,h(w))),Gn("composition-changed",O,te),Gn("section-ready",O,re),Gn("framework-error",O,Pe),Gn("toolkit-ready",O,z),ft(e,D),fn(j)}In(G_,{runtime:{},section:{},sectionId:{},attemptId:{},showToolbar:{},toolbarPosition:{},enabledTools:{},toolRegistry:{},sectionHostButtons:{},cardRenderContext:{},onCompositionChanged:{},onSectionReady:{},onFrameworkErrorEvent:{},onToolkitReady:{}},["default"],["navigateToItem","getCompositionModelSnapshot","getNavigationStateSnapshot","getSectionController","waitForSectionController"],{mode:"open"});function mf(e,t){un(t,!0);let r=_(t,"assessmentId",7),n=_(t,"runtime",7,null),i=_(t,"section",7,null),o=_(t,"sectionId",7,""),s=_(t,"attemptId",7,""),a=_(t,"iifeBundleHost",7),l=_(t,"showToolbar",7,"false"),d=_(t,"toolbarPosition",7,"right"),c=_(t,"toolConfigStrictness",7,"error"),u=_(t,"toolRegistry",7,null),f=_(t,"sectionHostButtons",23,()=>[]),p=_(t,"itemHostButtons",23,()=>[]),g=_(t,"passageHostButtons",23,()=>[]),v=_(t,"debug",7,void 0),b=_(t,"baseHeadingLevel",7,void 0),w=_(t,"playerActionConfig",23,()=>({stateKey:"__sectionPlayerAppliedParams",includeSessionRefInState:!1})),I=_(t,"policies",7,vy),x=_(t,"hooks",7,void 0),C=_(t,"onFrameworkError",7,void 0),L=_(t,"onStageChange",7,void 0),E=_(t,"onLoadingComplete",7,void 0),M=_(t,"sourceCe",7,"pie-section-player"),U=_(t,"host",7,null);const te=tc(),re=typeof window<"u"&&typeof document<"u",Pe=ee(()=>{if(v()!==void 0&&v()!==null){const fe=String(v()),_t=!(fe.toLowerCase()==="false"||fe==="0"||fe==="");if(re)try{window.PIE_DEBUG=_t}catch{}return _t}return Yl()}),z=Ys("section-player-layout-kernel",()=>h(Pe));let K=He(Ti(BR(bC))),oe=He(null),ue=He(!1),ae=He(null),X=He(!1),j=He(!1),D=He(!1);const Z=new X$,F=new iW;iA(sW,F);let W=null;const O={getRuntimeId:()=>F.getRuntimeId()};let $=!1,ie=null;const N=ee(()=>h(K).compositionModel),ne=ee(()=>h(K).passages),ge=ee(()=>h(K).items),Oe=ee(()=>h(K).renderables),We=ee(()=>h(K).renderablesSignature),Ne=ee(()=>h(ue)&&h(oe)?.elementsLoaded===!0&&h(oe).renderablesSignature===h(We)),xe=ee(()=>Sz({assessmentId:r(),runtime:n(),toolConfigStrictness:c(),onFrameworkError:C(),onStageChange:L(),onLoadingComplete:E()})),et=ee(()=>h(xe).effectiveRuntime),Ue=ee(()=>h(xe).effectiveToolsConfig),Se=t_({toolModuleLoaders:e_}),Re=ee(()=>u()??Se),mt=ee(()=>h(xe).playerRuntime),$t=ee(()=>{const fe=h(Ue)?.placement?.section;return Array.isArray(fe)?fe.join(","):""}),ve=ee(()=>{const fe=h(Ue)?.placement?.item;return Array.isArray(fe)?fe.join(","):""}),me=ee(()=>{const fe=h(Ue)?.placement?.passage;return Array.isArray(fe)?fe.join(","):""}),Je=ee(()=>h(mt).resolvedPlayerDefinition),Gt=ee(()=>h(mt).resolvedPlayerTag),le=ee(()=>h(mt).resolvedPlayerAttributes),Ae=ee(()=>h(mt).resolvedPlayerProps),Y=ee(()=>v()===void 0||v()===null?h(Ae):{...h(Ae)||{},debug:v()}),we=ee(()=>h(mt).resolvedPlayerEnv),_e=ee(()=>h(mt).strategy),Be=ee(()=>cw(b())),it=ee(()=>uW(w())),tt=ee(()=>x()?.cardTitleFormatter),Bt=ee(()=>({resolvedPlayerTag:h(Gt),playerAction:h(it),cardTitleFormatter:h(tt)})),ht=ee(()=>Ly(l(),!1)),ot=ee(()=>cW(I())),$r=ee(()=>h(ot).preload.enabled),Ur=ee(()=>OR({mode:h(ot).readiness.mode,signals:{sectionReady:h(X),interactionReady:h(X)&&h(Ne),allLoadingComplete:h(Ne),runtimeError:h(j)},reason:`policy:${h(ot).readiness.mode}`}));function Lr(fe){be(K,$z(fe),!0),be(ue,!0)}function ln(fe){const _t=fe.detail;be(oe,{elementsLoaded:_t?.elementsLoaded===!0,renderablesSignature:typeof _t?.renderablesSignature=="string"?_t.renderablesSignature:""},!0)}function qr(fe){const _t=fe.detail||{};te("element-preload-retry",{..._t,assessmentId:r(),sectionId:o(),attemptId:s()||void 0})}function xr(fe){const _t=fe.detail||{};te("element-preload-error",{..._t,assessmentId:r(),sectionId:o(),attemptId:s()||void 0})}function Ar(fe){be(X,!0)}function ye(fe){const _t=fe.detail;_t?.recoverable!==!0&&be(j,!0),_t&&(fe.stopPropagation(),F.dispatchInput({kind:"framework-error",error:_t}))}function vt(fe){F.dispatchInput({kind:"section-controller-resolved"})}async function kt(){if(h(D))return;const fe=await h(ae)?.waitForSectionController?.(2500);fe&&(be(D,!0),vt(fe))}function Qe(fe){kt()}function cr(){return h(ae)?.getNavigationStateSnapshot?.()||{currentIndex:0,totalItems:h(ge).length,canNext:h(ge).length>1,canPrevious:!1,currentItemId:h(ge)[0]?.id||void 0}}function V(){return{readiness:h(Ur),composition:{itemsCount:h(ge).length,passagesCount:h(ne).length},navigation:cr()}}function ke(){return{itemsCount:h(ge).length,passagesCount:h(ne).length}}function qe(){return cr()}function Ve(){return h(Ur)}function at(fe){return h(ae)?.navigateToItem?.(fe)===!0}function Rt(){const fe=cr();return fe.canNext?at(fe.currentIndex+1):!1}function Rr(){const fe=cr();return fe.canPrevious?at(fe.currentIndex-1):!1}function Vr(){const fe=h(ae)?.getSectionController?.()||null;return fe&&!h(D)&&(be(D,!0),vt(fe)),fe}async function jr(fe=5e3){const _t=await h(ae)?.waitForSectionController?.(fe);return _t&&!h(D)&&(be(D,!0),vt(_t)),_t||null}ct(()=>{h(Je)?.ensureDefined?.().catch(fe=>{z.error("Failed to load item player component:",fe)})}),ct(()=>{if(U())return W=new Ws(U(),{context:aW,initialValue:{engine:O}}),W.connect(),()=>{W?.disconnect(),W=null}}),ct(()=>{U(),o(),s(),h(et),h(Ue),h(ge).length,h(X),h(Ne),h(j),h(ot).readiness.mode,on(()=>{if(!U())return;F.attachHost({host:U(),sourceCe:M(),frameworkErrorBus:Z}),$=!0;const fe=iz({sectionId:o(),attemptId:s()}),_t=h(ge).length;if(hy(ie,fe)?fe!==null&&F.dispatchInput({kind:"update-runtime",effectiveRuntime:h(et),effectiveToolsConfig:h(Ue)}):(be(D,!1),fe&&(ie===null?F.dispatchInput({kind:"initialize",cohort:fe,effectiveRuntime:h(et),effectiveToolsConfig:h(Ue),itemCount:_t}):F.dispatchInput({kind:"cohort-change",cohort:fe,effectiveRuntime:h(et),effectiveToolsConfig:h(Ue),itemCount:_t})),ie=fe),ie!==null){const Gr={sectionReady:h(X),interactionReady:h(X)&&h(Ne),allLoadingComplete:h(Ne),runtimeError:h(j)};F.dispatchInput({kind:"update-readiness-signals",signals:Gr,loadedCount:_t,itemCount:_t,mode:h(ot).readiness.mode})}})}),ct(()=>{if(U())return mW({host:U(),getOnStageChange:()=>h(et)?.onStageChange,getOnLoadingComplete:()=>h(et)?.onLoadingComplete,onError:(fe,_t)=>{z.error(`${fe} handler threw`,_t)}})}),ct(()=>()=>{on(()=>{$&&F.dispatchInput({kind:"dispose"}),F.dispose().catch(fe=>{z.error("engine.dispose() failed",fe)}),Z.dispose()})});var dr={getSnapshot:V,selectComposition:ke,selectNavigation:qe,selectReadiness:Ve,navigateTo:at,navigateNext:Rt,navigatePrevious:Rr,getSectionController:Vr,waitForSectionController:jr,get assessmentId(){return r()},set assessmentId(fe){r(fe),R()},get runtime(){return n()},set runtime(fe=null){n(fe),R()},get section(){return i()},set section(fe=null){i(fe),R()},get sectionId(){return o()},set sectionId(fe=""){o(fe),R()},get attemptId(){return s()},set attemptId(fe=""){s(fe),R()},get iifeBundleHost(){return a()},set iifeBundleHost(fe){a(fe),R()},get showToolbar(){return l()},set showToolbar(fe="false"){l(fe),R()},get toolbarPosition(){return d()},set toolbarPosition(fe="right"){d(fe),R()},get toolConfigStrictness(){return c()},set toolConfigStrictness(fe="error"){c(fe),R()},get toolRegistry(){return u()},set toolRegistry(fe=null){u(fe),R()},get sectionHostButtons(){return f()},set sectionHostButtons(fe=[]){f(fe),R()},get itemHostButtons(){return p()},set itemHostButtons(fe=[]){p(fe),R()},get passageHostButtons(){return g()},set passageHostButtons(fe=[]){g(fe),R()},get debug(){return v()},set debug(fe=void 0){v(fe),R()},get baseHeadingLevel(){return b()},set baseHeadingLevel(fe=void 0){b(fe),R()},get playerActionConfig(){return w()},set playerActionConfig(fe={stateKey:"__sectionPlayerAppliedParams",includeSessionRefInState:!1}){w(fe),R()},get policies(){return I()},set policies(fe=vy){I(fe),R()},get hooks(){return x()},set hooks(fe=void 0){x(fe),R()},get onFrameworkError(){return C()},set onFrameworkError(fe=void 0){C(fe),R()},get onStageChange(){return L()},set onStageChange(fe=void 0){L(fe),R()},get onLoadingComplete(){return E()},set onLoadingComplete(fe=void 0){E(fe),R()},get sourceCe(){return M()},set sourceCe(fe="pie-section-player"){M(fe),R()},get host(){return U()},set host(fe=null){U(fe),R()}};return Er(G_(e,{get runtime(){return h(et)},get section(){return i()},get sectionId(){return o()},get attemptId(){return s()},onCompositionChanged:Lr,onSectionReady:Ar,onFrameworkErrorEvent:ye,onToolkitReady:Qe,get showToolbar(){return h(ht)},get toolbarPosition(){return d()},get enabledTools(){return h($t)},get toolRegistry(){return h(Re)},get sectionHostButtons(){return f()},get cardRenderContext(){return h(Bt)},children:(fe,_t)=>{var Gr=Nl(),tn=jn(Gr);dd(tn,t,"default",{get layoutModel(){return{compositionModel:h(N),passages:h(ne),items:h(ge),preloadedRenderables:h(Oe),preloadedRenderablesSignature:h(We),resolvedPlayerEnv:h(we),resolvedPlayerAttributes:h(le),resolvedPlayerProps:h(Y),playerStrategy:h(_e),baseHeadingLevel:h(Be),iifeBundleHost:a(),paneElementsLoaded:h(Ne),toolRegistry:h(Re),itemHostButtons:p(),passageHostButtons:g(),readinessDetail:h(Ur),preloadEnabled:h($r),itemToolbarTools:h(ve),passageToolbarTools:h(me),onItemsPaneElementsLoaded:ln,onItemsPanePreloadRetry:qr,onItemsPanePreloadError:xr}},get compositionModel(){return h(N)},get passages(){return h(ne)},get items(){return h(ge)},get preloadedRenderables(){return h(Oe)},get preloadedRenderablesSignature(){return h(We)},get resolvedPlayerEnv(){return h(we)},get resolvedPlayerAttributes(){return h(le)},get resolvedPlayerProps(){return h(Y)},get playerStrategy(){return h(_e)},get baseHeadingLevel(){return h(Be)},get iifeBundleHost(){return a()},get paneElementsLoaded(){return h(Ne)},get toolRegistry(){return h(Re)},get itemHostButtons(){return p()},get passageHostButtons(){return g()},get readinessDetail(){return h(Ur)},get preloadEnabled(){return h($r)},get itemToolbarTools(){return h(ve)},get passageToolbarTools(){return h(me)},onItemsPaneElementsLoaded:ln,onItemsPanePreloadRetry:qr,onItemsPanePreloadError:xr},null),ft(fe,Gr)},$$slots:{default:!0}}),fe=>be(ae,fe,!0),()=>h(ae)),fn(dr)}In(mf,{assessmentId:{},runtime:{},section:{},sectionId:{},attemptId:{},iifeBundleHost:{},showToolbar:{},toolbarPosition:{},toolConfigStrictness:{},toolRegistry:{},sectionHostButtons:{},itemHostButtons:{},passageHostButtons:{},debug:{},baseHeadingLevel:{},playerActionConfig:{},policies:{},hooks:{},onFrameworkError:{},onStageChange:{},onLoadingComplete:{},sourceCe:{},host:{}},["default"],["getSnapshot","selectComposition","selectNavigation","selectReadiness","navigateTo","navigateNext","navigatePrevious","getSectionController","waitForSectionController"],{mode:"open"});var Ew={phase:"bootstrapping",interactionReady:!1,allLoadingComplete:!1},cu={readiness:Ew,composition:{itemsCount:0,passagesCount:0},navigation:{currentIndex:0,totalItems:0,canNext:!1,canPrevious:!1}},Cw={snapshot:null,composition:null,navigation:null,readiness:null},Cq={snapshot:cu,composition:cu.composition,navigation:cu.navigation,readiness:Ew},xq=25;function xm(e){return t=>{const r=(n,i)=>{const o=Reflect.get(t.prototype,i,n);return typeof o=="function"?o:null};return class extends t{getSnapshot(){const n=r(this,"getSnapshot");return n?n():e.snapshot}selectComposition(){const n=r(this,"selectComposition");return n?n():e.composition}selectNavigation(){const n=r(this,"selectNavigation");return n?n():e.navigation}selectReadiness(){const n=r(this,"selectReadiness");return n?n():e.readiness}navigateTo(n){return r(this,"navigateTo")?.(n)===!0}navigateNext(){return r(this,"navigateNext")?.()===!0}navigatePrevious(){return r(this,"navigatePrevious")?.()===!0}getSectionController(){return r(this,"getSectionController")?.()??null}async waitForSectionController(n=5e3){const i=Date.now()+n;for(await Promise.resolve();;){const o=this.getSectionController();if(o)return o;if(Date.now()>=i)return null;await new Promise(s=>setTimeout(s,xq))}}}}}var Rq=Ht('<div class="pie-section-player-tabs svelte-311cih" role="tablist"><button type="button" role="tab" data-pie-purpose="passage-label"> </button> <button type="button" role="tab" data-pie-purpose="item-label"> </button></div>'),_q=Ht('<div class="pie-section-player-tab-panel pie-section-player-tab-panel--passages svelte-311cih" role="tabpanel"><pie-section-player-passages-pane></pie-section-player-passages-pane></div>',2),Pq=Ht('<div class="pie-section-player-tabbed-frame svelte-311cih"><div class="pie-section-player-tabbed-content svelte-311cih"><!> <!> <div class="pie-section-player-tab-panel pie-section-player-tab-panel--items svelte-311cih" role="tabpanel"><pie-section-player-items-pane></pie-section-player-items-pane></div></div></div>',2),Aq={hash:"svelte-311cih",code:`.pie-section-player-tabbed-frame.svelte-311cih {width:100%;max-width:var(--pie-section-player-layout-max-width, none);height:100%;min-height:0;max-height:100%;margin-inline:auto;overflow:hidden;}.pie-section-player-tabbed-content.svelte-311cih {height:100%;max-height:100%;min-height:0;min-width:0;display:flex;flex-direction:column;gap:var(--pie-section-player-tab-gap, 0.5rem);padding:0.5rem;box-sizing:border-box;background:var(--pie-background-dark, #ecedf1);overflow:hidden;}.pie-section-player-tabs.svelte-311cih {display:flex;gap:6px;background:var(--pie-background, #ffffff);border-radius:var(--pie-section-player-tab-track-radius, 9999px);
1550
+ /*
1551
+ * \`--pie-border-gray\` clears the 3:1 non-text minimum in every scheme and
1552
+ * is stepped to it under the DaisyUI provider. The literal only applies to
1553
+ * a host that mounts the player with no theme at all, where #D9DADA left
1554
+ * the track at 1.2:1 against the frame -- the same grey the button border
1555
+ * defaults to holds there instead.
1556
+ */border:1px solid var(--pie-border-gray, #767676);padding:var(--pie-section-player-tab-track-padding, 0.25rem);width:fit-content;align-self:center;}.pie-section-player-tab.svelte-311cih {position:relative;border:none;border-radius:24px;background:var(--pie-section-player-tab-background, transparent);
1557
+ /*
1558
+ * The unselected tab is transparent, so its ink has to hold against the
1559
+ * track's own \`--pie-background\`. Resolving the hook through \`--pie-text\`
1560
+ * is what keeps it on the certified ordinary-text pair; a literal here
1561
+ * stays near-black under every scheme and disappears on the dark ones.
1562
+ */color:var(--pie-section-player-tab-color, var(--pie-text, #111827));padding:var(--pie-section-player-tab-padding-block, 0.35rem) 12px;font:inherit;
1563
+ /* Was a hard \`12px\`, the only pixel type size in the content path: it
1564
+ ignored the font accommodation and the reader's own browser font size
1565
+ alike, leaving 12px tab labels beside body text at 175%. \`0.75rem\` is
1566
+ the same 12px at a default root, so this only diverges for a host that
1567
+ moves the root size — which is the point of using rem. */font-size:calc(0.75rem * var(--pie-font-scale, 1));font-weight:600;cursor:pointer;transition:background 0.15s ease, color 0.15s ease;white-space:nowrap;}.pie-section-player-tab.svelte-311cih::after {display:none;}.pie-section-player-tab--active.svelte-311cih {
1568
+ /*
1569
+ * The selected pill carries a fixed brand hue, so it behaves like any other
1570
+ * fixed encoding: pinned while no scheme is asking for a palette, folded
1571
+ * into that palette when one is. #1D7375 does not follow a scheme at all,
1572
+ * and as the selection indicator it measured 1.42:1 against the track under
1573
+ * Yellow on Navy, 2.26:1 under Light Gray on Dark Gray and 2.80:1 under
1574
+ * Black on Violet, where 1.4.11 asks for 3:1.
1575
+ *
1576
+ * At 100% collapse the fill becomes --pie-primary and the ink the page
1577
+ * colour, which is the one pairing that holds on every scheme: 5.44:1 or
1578
+ * better for the text, and the same ratio separating the pill from the
1579
+ * track it sits on, since the track paints --pie-background. Mixing rather
1580
+ * than substituting is what keeps the ink out of the light Base Theme's
1581
+ * transparent --pie-background, where it would render invisible: that end
1582
+ * of the mix is the pinned white, exact at 0%.
1583
+ */background:var(
1584
+ --pie-section-player-tab-active-background,
1585
+ color-mix(in srgb, var(--pie-primary, #1D7375) var(--pie-fixed-hue-collapse, 0%), #1D7375)
1586
+ );color:var(
1587
+ --pie-section-player-tab-active-color,
1588
+ color-mix(in srgb, var(--pie-background, #ffffff) var(--pie-fixed-hue-collapse, 0%), #ffffff)
1589
+ );}.pie-section-player-tab.svelte-311cih:focus-visible {outline:2px solid var(--pie-focus-outline, #1d4ed8);outline-offset:2px;}.pie-section-player-tab-panel.svelte-311cih {min-height:0;min-width:0;height:100%;max-height:100%;overflow-y:auto;overflow-x:hidden;overscroll-behavior:contain;scrollbar-width:thin;scrollbar-color:var(--pie-scrollbar-thumb, var(--pie-border-gray, #6b7280)) var(--pie-scrollbar-track, var(--pie-background-dark, #d1d5db));}.pie-section-player-tab-panel.svelte-311cih::-webkit-scrollbar {width:0.75rem;height:0.75rem;}.pie-section-player-tab-panel.svelte-311cih::-webkit-scrollbar-track {background:var(--pie-scrollbar-track, var(--pie-background-dark, #d1d5db));border-radius:999px;}.pie-section-player-tab-panel.svelte-311cih::-webkit-scrollbar-thumb {background:var(--pie-scrollbar-thumb, var(--pie-border-gray, #6b7280));border-radius:999px;border:2px solid var(--pie-scrollbar-track, var(--pie-background-dark, #d1d5db));}.pie-section-player-tab-panel.svelte-311cih::-webkit-scrollbar-thumb:hover {background:var(--pie-scrollbar-thumb-hover, var(--pie-border-dark, #4b5563));}.pie-section-player-tab-panel[hidden].svelte-311cih {display:none;}.pie-section-player-tab-panel.svelte-311cih .pie-section-player-passages-pane,
1590
+ .pie-section-player-tab-panel.svelte-311cih .pie-section-player-items-pane {height:100%;}`};function xw(e,t){un(t,!0),Mn(e,Aq);let r=_(t,"layoutModel",7),n=_(t,"itemToolbarTools",7,""),i=_(t,"passageToolbarTools",7,""),o=_(t,"toolRegistry",7,null),s=_(t,"itemHostButtons",23,()=>[]),a=_(t,"passageHostButtons",23,()=>[]),l=_(t,"iifeBundleHost",7),d=_(t,"preloadComponentTag",7,"pie-section-player-tabbed"),c=_(t,"contentMaxWidthNoPassagePx",7,void 0),u=_(t,"contentMaxWidthWithPassagePx",7,void 0),f=_(t,"idBase",7,"pie-section-player-tabbed"),p=He(null);const g=uf(()=>h(p));let v=He("passage"),b=He(null),w=He(null);ct(()=>{f(),on(()=>{be(v,"passage")})});const I=ee(()=>r().passages.length>0),x=ee(()=>h(I)?u():c()),C=ee(()=>`${f()}-tab-passage`),L=ee(()=>`${f()}-tab-items`),E=ee(()=>`${f()}-panel-passage`),M=ee(()=>`${f()}-panel-items`),U=ee(()=>h(I)?h(v):"items");function te(F){F==="passage"&&!h(I)||be(v,F,!0)}function re(F){if(F==="passage"){h(b)?.focus();return}h(w)?.focus()}function Pe(F,W){if(h(I))switch(F.key){case"ArrowRight":case"ArrowLeft":{F.preventDefault();const O=W==="passage"?"items":"passage";te(O),re(O);break}case"Home":F.preventDefault(),te("passage"),re("passage");break;case"End":F.preventDefault(),te("items"),re("items")}}var z={get layoutModel(){return r()},set layoutModel(F){r(F),R()},get itemToolbarTools(){return n()},set itemToolbarTools(F=""){n(F),R()},get passageToolbarTools(){return i()},set passageToolbarTools(F=""){i(F),R()},get toolRegistry(){return o()},set toolRegistry(F=null){o(F),R()},get itemHostButtons(){return s()},set itemHostButtons(F=[]){s(F),R()},get passageHostButtons(){return a()},set passageHostButtons(F=[]){a(F),R()},get iifeBundleHost(){return l()},set iifeBundleHost(F){l(F),R()},get preloadComponentTag(){return d()},set preloadComponentTag(F="pie-section-player-tabbed"){d(F),R()},get contentMaxWidthNoPassagePx(){return c()},set contentMaxWidthNoPassagePx(F=void 0){c(F),R()},get contentMaxWidthWithPassagePx(){return u()},set contentMaxWidthWithPassagePx(F=void 0){u(F),R()},get idBase(){return f()},set idBase(F="pie-section-player-tabbed"){f(F),R()}},K=Pq(),oe=Xt(K),ue=Xt(oe),ae=F=>{var W=Rq(),O=Xt(W),$=Ta(O,!0);Er(O,ne=>be(b,ne),()=>h(b));var ie=lr(O,2),N=Ta(ie,!0);Er(ie,ne=>be(w,ne),()=>h(w)),Kt(W),q((ne,ge,Oe)=>{nt(W,"aria-label",ne),nt(O,"id",h(C)),gn(O,1,`pie-section-player-tab ${h(U)==="passage"?"pie-section-player-tab--active":""} passage-label`,"svelte-311cih"),nt(O,"aria-controls",h(E)),nt(O,"aria-selected",h(U)==="passage"),nt(O,"tabindex",h(U)==="passage"?0:-1),vs($,ge),nt(ie,"id",h(L)),gn(ie,1,`pie-section-player-tab ${h(U)==="items"?"pie-section-player-tab--active":""} item-label`,"svelte-311cih"),nt(ie,"aria-controls",h(M)),nt(ie,"aria-selected",h(U)==="items"),nt(ie,"tabindex",h(U)==="items"?0:-1),vs(N,Oe)},[()=>g.t("player.sectionTabsA11y"),()=>g.t("player.passage"),()=>g.t("player.questions")]),lo("click",O,()=>te("passage")),lo("keydown",O,ne=>Pe(ne,"passage")),lo("click",ie,()=>te("items")),lo("keydown",ie,ne=>Pe(ne,"items")),ft(F,W)};vn(ue,F=>{h(I)&&F(ae)});var X=lr(ue,2),j=F=>{var W=_q(),O=Xt(W);q(()=>G(O,"compositionModel",r().compositionModel)),q(()=>G(O,"passages",r().passages)),q(()=>G(O,"elementsLoaded",r().paneElementsLoaded)),q(()=>G(O,"resolvedPlayerEnv",r().resolvedPlayerEnv)),q(()=>G(O,"resolvedPlayerAttributes",r().resolvedPlayerAttributes)),q(()=>G(O,"resolvedPlayerProps",r().resolvedPlayerProps)),q(()=>G(O,"baseHeadingLevel",r().baseHeadingLevel)),q(()=>G(O,"playerStrategy",r().playerStrategy)),q(()=>G(O,"passageToolbarTools",i())),q(()=>G(O,"toolRegistry",o()||r().toolRegistry)),q(()=>G(O,"hostButtons",a().length>0?a():r().passageHostButtons)),Kt(W),q(()=>{nt(W,"id",h(E)),nt(W,"aria-labelledby",h(C)),nt(W,"hidden",h(U)!=="passage")}),ft(F,W)};vn(X,F=>{h(I)&&F(j)});var D=lr(X,2),Z=Xt(D);return q(()=>G(Z,"items",r().items)),q(()=>G(Z,"compositionModel",r().compositionModel)),q(()=>G(Z,"resolvedPlayerEnv",r().resolvedPlayerEnv)),q(()=>G(Z,"resolvedPlayerAttributes",r().resolvedPlayerAttributes)),q(()=>G(Z,"resolvedPlayerProps",r().resolvedPlayerProps)),q(()=>G(Z,"baseHeadingLevel",r().baseHeadingLevel)),q(()=>G(Z,"playerStrategy",r().playerStrategy)),q(()=>G(Z,"itemToolbarTools",n())),q(()=>G(Z,"toolRegistry",o()||r().toolRegistry)),q(()=>G(Z,"hostButtons",s().length>0?s():r().itemHostButtons)),q(()=>G(Z,"iifeBundleHost",l())),q(()=>G(Z,"preloadedRenderables",r().preloadedRenderables)),q(()=>G(Z,"preloadedRenderablesSignature",r().preloadedRenderablesSignature)),q(()=>G(Z,"preloadComponentTag",d())),q(()=>G(Z,"preloadEnabled",r().preloadEnabled)),Kt(D),Kt(oe),Kt(K),Er(K,F=>be(p,F),()=>h(p)),q(()=>{Dl(K,`--pie-section-player-layout-max-width: ${h(x)!==void 0?`${h(x)}px`:"none"};`),nt(D,"id",h(M)),nt(D,"aria-labelledby",h(I)?h(L):void 0),nt(D,"hidden",h(I)&&h(U)!=="items")}),Gn("elements-loaded-change",Z,function(...F){r().onItemsPaneElementsLoaded?.apply(this,F)}),Gn("element-preload-retry",Z,function(...F){r().onItemsPanePreloadRetry?.apply(this,F)}),Gn("element-preload-error",Z,function(...F){r().onItemsPanePreloadError?.apply(this,F)}),ft(e,K),fn(z)}cd(["click","keydown"]);In(xw,{layoutModel:{},itemToolbarTools:{},passageToolbarTools:{},toolRegistry:{},itemHostButtons:{},passageHostButtons:{},iifeBundleHost:{},preloadComponentTag:{},contentMaxWidthNoPassagePx:{},contentMaxWidthWithPassagePx:{},idBase:{}},[],[],{mode:"open"});var Mq=Ht('<section class="pie-section-player-passages-section svelte-1q3epdx"><pie-section-player-passages-pane></pie-section-player-passages-pane></section>',2),$q=Ht('<div class="pie-section-player-vertical-frame svelte-1q3epdx"><div class="pie-section-player-vertical-content svelte-1q3epdx"><!> <section class="pie-section-player-items-section svelte-1q3epdx"><pie-section-player-items-pane></pie-section-player-items-pane></section></div></div>',2),Lq={hash:"svelte-1q3epdx",code:`.pie-section-player-vertical-frame.svelte-1q3epdx {width:100%;max-width:var(--pie-section-player-layout-max-width, none);height:100%;min-height:0;max-height:100%;margin-inline:auto;overflow:hidden;}.pie-section-player-vertical-content.svelte-1q3epdx {height:100%;max-height:100%;min-height:0;min-width:0;overflow-y:auto;overflow-x:hidden;overscroll-behavior:contain;display:flex;flex-direction:column;gap:1rem;padding:0.5rem;box-sizing:border-box;background:var(--pie-background-dark, #ecedf1);scrollbar-width:thin;scrollbar-color:var(--pie-scrollbar-thumb, var(--pie-border-gray, #6b7280)) var(--pie-scrollbar-track, var(--pie-background-dark, #d1d5db));}.pie-section-player-vertical-content.svelte-1q3epdx::-webkit-scrollbar {width:0.75rem;height:0.75rem;}.pie-section-player-vertical-content.svelte-1q3epdx::-webkit-scrollbar-track {background:var(--pie-scrollbar-track, var(--pie-background-dark, #d1d5db));border-radius:999px;}.pie-section-player-vertical-content.svelte-1q3epdx::-webkit-scrollbar-thumb {background:var(--pie-scrollbar-thumb, var(--pie-border-gray, #6b7280));border-radius:999px;border:2px solid var(--pie-scrollbar-track, var(--pie-background-dark, #d1d5db));}.pie-section-player-vertical-content.svelte-1q3epdx::-webkit-scrollbar-thumb:hover {background:var(--pie-scrollbar-thumb-hover, var(--pie-border-dark, #4b5563));}.pie-section-player-passages-section.svelte-1q3epdx,
1591
+ .pie-section-player-items-section.svelte-1q3epdx {min-height:0;
1592
+ /* Prevent flexbox from compressing content sections.
1593
+ Let the vertical container own scrolling instead. */flex:0 0 auto;}.pie-section-player-passages-section.svelte-1q3epdx {width:100%;}`};function Rw(e,t){un(t,!0),Mn(e,Lq);let r=_(t,"layoutModel",7),n=_(t,"itemToolbarTools",7,""),i=_(t,"passageToolbarTools",7,""),o=_(t,"toolRegistry",7,null),s=_(t,"itemHostButtons",23,()=>[]),a=_(t,"passageHostButtons",23,()=>[]),l=_(t,"iifeBundleHost",7),d=_(t,"preloadComponentTag",7,"pie-section-player-vertical"),c=_(t,"contentMaxWidthNoPassagePx",7,void 0),u=_(t,"contentMaxWidthWithPassagePx",7,void 0),f=He(null);const p=uf(()=>h(f)),g=ee(()=>r().passages.length>0?u():c());var v={get layoutModel(){return r()},set layoutModel(E){r(E),R()},get itemToolbarTools(){return n()},set itemToolbarTools(E=""){n(E),R()},get passageToolbarTools(){return i()},set passageToolbarTools(E=""){i(E),R()},get toolRegistry(){return o()},set toolRegistry(E=null){o(E),R()},get itemHostButtons(){return s()},set itemHostButtons(E=[]){s(E),R()},get passageHostButtons(){return a()},set passageHostButtons(E=[]){a(E),R()},get iifeBundleHost(){return l()},set iifeBundleHost(E){l(E),R()},get preloadComponentTag(){return d()},set preloadComponentTag(E="pie-section-player-vertical"){d(E),R()},get contentMaxWidthNoPassagePx(){return c()},set contentMaxWidthNoPassagePx(E=void 0){c(E),R()},get contentMaxWidthWithPassagePx(){return u()},set contentMaxWidthWithPassagePx(E=void 0){u(E),R()}},b=$q(),w=Xt(b),I=Xt(w),x=E=>{var M=Mq(),U=Xt(M);q(()=>G(U,"compositionModel",r().compositionModel)),q(()=>G(U,"passages",r().passages)),q(()=>G(U,"elementsLoaded",r().paneElementsLoaded)),q(()=>G(U,"resolvedPlayerEnv",r().resolvedPlayerEnv)),q(()=>G(U,"resolvedPlayerAttributes",r().resolvedPlayerAttributes)),q(()=>G(U,"resolvedPlayerProps",r().resolvedPlayerProps)),q(()=>G(U,"baseHeadingLevel",r().baseHeadingLevel)),q(()=>G(U,"playerStrategy",r().playerStrategy)),q(()=>G(U,"passageToolbarTools",i())),q(()=>G(U,"toolRegistry",o()||r().toolRegistry)),q(()=>G(U,"hostButtons",a().length>0?a():r().passageHostButtons)),Kt(M),q(te=>nt(M,"aria-label",te),[()=>p.t("player.passagesRegionA11y")]),ft(E,M)};vn(I,E=>{r().passages.length>0&&r().paneElementsLoaded&&E(x)});var C=lr(I,2),L=Xt(C);return q(()=>G(L,"items",r().items)),q(()=>G(L,"compositionModel",r().compositionModel)),q(()=>G(L,"resolvedPlayerEnv",r().resolvedPlayerEnv)),q(()=>G(L,"resolvedPlayerAttributes",r().resolvedPlayerAttributes)),q(()=>G(L,"resolvedPlayerProps",r().resolvedPlayerProps)),q(()=>G(L,"baseHeadingLevel",r().baseHeadingLevel)),q(()=>G(L,"playerStrategy",r().playerStrategy)),q(()=>G(L,"itemToolbarTools",n())),q(()=>G(L,"toolRegistry",o()||r().toolRegistry)),q(()=>G(L,"hostButtons",s().length>0?s():r().itemHostButtons)),q(()=>G(L,"iifeBundleHost",l())),q(()=>G(L,"preloadedRenderables",r().preloadedRenderables)),q(()=>G(L,"preloadedRenderablesSignature",r().preloadedRenderablesSignature)),q(()=>G(L,"preloadComponentTag",d())),q(()=>G(L,"preloadEnabled",r().preloadEnabled)),Kt(C),Kt(w),Kt(b),Er(b,E=>be(f,E),()=>h(f)),q(E=>{Dl(b,`--pie-section-player-layout-max-width: ${h(g)!==void 0?`${h(g)}px`:"none"};`),nt(C,"aria-label",E)},[()=>p.t("player.itemsRegionA11y")]),Gn("elements-loaded-change",L,function(...E){r().onItemsPaneElementsLoaded?.apply(this,E)}),Gn("element-preload-retry",L,function(...E){r().onItemsPanePreloadRetry?.apply(this,E)}),Gn("element-preload-error",L,function(...E){r().onItemsPanePreloadError?.apply(this,E)}),ft(e,b),fn(v)}In(Rw,{layoutModel:{},itemToolbarTools:{},passageToolbarTools:{},toolRegistry:{},itemHostButtons:{},passageHostButtons:{},iifeBundleHost:{},preloadComponentTag:{},contentMaxWidthNoPassagePx:{},contentMaxWidthWithPassagePx:{}},[],[],{mode:"open"});var Oq=Ht('<div role="separator" aria-orientation="vertical"><span class="pie-section-player-split-divider-handle svelte-mpm4s6"></span></div>'),Nq={hash:"svelte-mpm4s6",code:`.pie-section-player-split-divider.svelte-mpm4s6 {border:none;padding:0;margin:0;font:inherit;align-self:stretch;height:100%;min-height:0;position:relative;cursor:col-resize;background:var(--pie-secondary-background, #f3f4f6);display:flex;align-items:center;justify-content:center;user-select:none;touch-action:none;transition:background 0.2s ease;}.pie-section-player-split-divider.svelte-mpm4s6:hover {background:var(--pie-border-light, #e5e7eb);}.pie-section-player-split-divider.svelte-mpm4s6:focus {outline:none;}.pie-section-player-split-divider.svelte-mpm4s6:focus-visible {outline:3px solid var(--pie-section-player-focus-outline, var(--pie-focus-outline, #146eb3));outline-offset:-2px;border-radius:999px;}.pie-section-player-split-divider-handle.svelte-mpm4s6 {position:absolute;inset:0;margin:auto;width:6px;height:60px;background:var(--pie-blue-grey-600, #9ca3af);border-radius:3px;transition:all 0.2s ease;pointer-events:none;}.pie-section-player-split-divider-handle.svelte-mpm4s6::before {content:"";position:absolute;top:50%;left:50%;transform:translate(-50%, -50%);width:2px;height:20px;background:var(--pie-white, white);border-radius:1px;opacity:0.8;}.pie-section-player-split-divider.svelte-mpm4s6:hover .pie-section-player-split-divider-handle:where(.svelte-mpm4s6),
1594
+ .pie-section-player-split-divider.svelte-mpm4s6:focus-visible .pie-section-player-split-divider-handle:where(.svelte-mpm4s6),
1595
+ .pie-section-player-split-divider--dragging.svelte-mpm4s6 .pie-section-player-split-divider-handle:where(.svelte-mpm4s6) {background:var(--pie-section-player-focus-outline, var(--pie-focus-outline, #146eb3));height:80px;box-shadow:0 2px 8px color-mix(in srgb, var(--pie-section-player-focus-outline, var(--pie-focus-outline, #146eb3)) 30%, transparent);}.pie-section-player-split-divider--dragging.svelte-mpm4s6 {background:var(--pie-primary-light, #dbeafe);}`};function K_(e,t){un(t,!0),Mn(e,Nq);let r=_(t,"value",7,50),n=_(t,"min",7,20),i=_(t,"max",7,80),o=_(t,"step",7,5),s=_(t,"disabled",7,!1),a=_(t,"ariaLabel",7,"Resize panels"),l=_(t,"ariaControls",7,""),d=_(t,"ariaValueText",7,"");const c=tc();let u=He(!1),f=0,p=0;function g(L){return Math.max(n(),Math.min(i(),L))}function v(L){s()||(L.preventDefault(),be(u,!0),f=L.clientX,p=r(),c("resize-start",{value:r()}))}function b(L){if(!h(u))return;const E=L.clientX-f,M=g(p+E*.1);c("resize-preview",{value:M,input:"pointer"})}function w(){h(u)&&(be(u,!1),c("resize-commit",{value:r(),input:"pointer"}))}function I(L){if(s()||L.key!=="ArrowLeft"&&L.key!=="ArrowRight"&&L.key!=="Escape"&&L.key!=="Home"&&L.key!=="End")return;if(L.preventDefault(),L.key==="Escape"){c("resize-cancel",{value:r()});return}let E=r();if(L.key==="Home")E=n();else if(L.key==="End")E=i();else{const M=L.key==="ArrowLeft"?-o():o();E=g(r()+M)}c("resize-preview",{value:E,input:"keyboard"}),c("resize-commit",{value:E,input:"keyboard"})}ct(()=>{if(h(u))return window.addEventListener("mousemove",b),window.addEventListener("mouseup",w),()=>{window.removeEventListener("mousemove",b),window.removeEventListener("mouseup",w)}});var x={get value(){return r()},set value(L=50){r(L),R()},get min(){return n()},set min(L=20){n(L),R()},get max(){return i()},set max(L=80){i(L),R()},get step(){return o()},set step(L=5){o(L),R()},get disabled(){return s()},set disabled(L=!1){s(L),R()},get ariaLabel(){return a()},set ariaLabel(L="Resize panels"){a(L),R()},get ariaControls(){return l()},set ariaControls(L=""){l(L),R()},get ariaValueText(){return d()},set ariaValueText(L=""){d(L),R()}},C=Oq();return q(L=>{gn(C,1,`pie-section-player-split-divider ${h(u)?"pie-section-player-split-divider--dragging":""}`,"svelte-mpm4s6"),nt(C,"aria-label",a()),nt(C,"aria-controls",l()||void 0),nt(C,"aria-valuemin",n()),nt(C,"aria-valuemax",i()),nt(C,"aria-valuenow",L),nt(C,"aria-valuetext",d()||void 0),nt(C,"aria-disabled",s()?"true":void 0),nt(C,"tabindex",s()?void 0:0)},[()=>Math.round(r())]),lo("mousedown",C,v),lo("keydown",C,I),ft(e,C),fn(x)}cd(["mousedown","keydown"]);In(K_,{value:{},min:{},max:{},step:{},disabled:{},ariaLabel:{},ariaControls:{},ariaValueText:{}},[],[],{mode:"open"});var Dq=1100,jq=400,Bq=2e3,ok=320,sk=2200;function $y(e,t,r){if(e==null||e==="")return;const n=typeof e=="number"?e:Number(e);if(Number.isFinite(n))return Math.max(t,Math.min(r,n))}function _w(e){const t=typeof e=="number"?e:Number(e);return Math.max(jq,Math.min(Bq,Number.isFinite(t)?t:Dq))}function Pw(e,t){const r=$y(e,ok,sk),n=$y(t,ok,sk);return n===void 0?{noPassagePx:r,withPassagePx:void 0}:{noPassagePx:r,withPassagePx:r===void 0?n:Math.max(r,n)}}function Rm(e){if(!e)return null;const t=e.getRootNode();return t&&"host"in t?t.host:e.parentElement}function Aw(e){let t=He(!1);return ct(()=>{const r=e();if(typeof window>"u")return;const n=window.matchMedia(`(max-width: ${r}px)`),i=()=>{be(t,n.matches,!0)};return i(),n.addEventListener("change",i),()=>n.removeEventListener("change",i)}),{get isNarrow(){return h(t)}}}var Fq=Ht('<aside class="pie-section-player-passages-pane svelte-qeub3g"><pie-section-player-passages-pane></pie-section-player-passages-pane></aside> <!>',3),Hq=Ht('<div class="pie-section-player-split-frame svelte-qeub3g"><div><!> <main class="pie-section-player-items-pane svelte-qeub3g"><pie-section-player-items-pane></pie-section-player-items-pane></main></div></div>',2),zq=Ht('<div class="pie-section-player-observability-anchor svelte-qeub3g" aria-hidden="true"></div> <!>',1),Wq={hash:"svelte-qeub3g",code:`:host {display:block;width:100%;height:100%;min-height:0;max-height:100%;overflow:hidden;}.pie-section-player-split-frame.svelte-qeub3g {width:100%;max-width:var(--pie-section-player-layout-max-width, none);height:100%;min-height:0;max-height:100%;margin-inline:auto;overflow:hidden;}.pie-section-player-split-content.svelte-qeub3g {display:grid;gap:0;min-height:0;width:100%;height:100%;overflow:hidden;}.pie-section-player-passages-pane.svelte-qeub3g,
1596
+ .pie-section-player-items-pane.svelte-qeub3g {height:100%;max-height:100%;min-height:0;min-width:0;overflow-y:auto;overflow-x:hidden;overscroll-behavior:contain;
1597
+ /* Margin (not padding) so the gutter sits outside the scrollable
1598
+ region. Padding lives inside the scroll box, letting any child
1599
+ that uses position:sticky bleed into it as content scrolls past.
1600
+ Kept as margin so this pane composes cleanly with arbitrary
1601
+ descendant content (sticky headers, floating toolbars, etc.). */margin:0.5rem;box-sizing:border-box;
1602
+ /* Backdrop for the scroll surround behind the cards. Deliberately the
1603
+ canonical surface token and not --pie-passage-header-background: that
1604
+ is a passage header hook, and this rule also covers the items pane,
1605
+ which holds no passage header, so a host coloring its hosted
1606
+ passage-player's header used to repaint both pane backdrops. There is
1607
+ no pane-specific hook on purpose — the backdrop is meant to stay with
1608
+ the theme, which is what tracks dark themes and color schemes.
1609
+ --pie-background-dark resolves to #ecedf1 in the default light theme. */background:var(--pie-background-dark, #ecedf1);scrollbar-width:thin;scrollbar-color:var(--pie-scrollbar-thumb, var(--pie-border-gray, #6b7280)) var(--pie-scrollbar-track, var(--pie-background-dark, #d1d5db));}.pie-section-player-items-pane.svelte-qeub3g .pie-section-player-scroll-hint {bottom:-0.5rem;}.pie-section-player-passages-pane.svelte-qeub3g::-webkit-scrollbar,
1610
+ .pie-section-player-items-pane.svelte-qeub3g::-webkit-scrollbar {width:0.75rem;height:0.75rem;}.pie-section-player-passages-pane.svelte-qeub3g::-webkit-scrollbar-track,
1611
+ .pie-section-player-items-pane.svelte-qeub3g::-webkit-scrollbar-track {background:var(--pie-scrollbar-track, var(--pie-background-dark, #d1d5db));border-radius:999px;}.pie-section-player-passages-pane.svelte-qeub3g::-webkit-scrollbar-thumb,
1612
+ .pie-section-player-items-pane.svelte-qeub3g::-webkit-scrollbar-thumb {background:var(--pie-scrollbar-thumb, var(--pie-border-gray, #6b7280));border-radius:999px;border:2px solid var(--pie-scrollbar-track, var(--pie-background-dark, #d1d5db));}.pie-section-player-passages-pane.svelte-qeub3g::-webkit-scrollbar-thumb:hover,
1613
+ .pie-section-player-items-pane.svelte-qeub3g::-webkit-scrollbar-thumb:hover {background:var(--pie-scrollbar-thumb-hover, var(--pie-border-dark, #4b5563));}.pie-section-player-observability-anchor.svelte-qeub3g {display:none;}`};function Uq(e,t){un(t,!0),Mn(e,Wq);const r=160,n=1200,i=.5,o=20,s=80;function a(ye,vt){return Math.max(vt.min,Math.min(vt.max,ye))}function l(ye){if(ye==null||ye==="")return;const vt=typeof ye=="number"?ye:Number(ye);if(Number.isFinite(vt))return Math.max(o,Math.min(s,vt))}function d(ye){const vt=Number.parseFloat(getComputedStyle(ye).fontSize||"16");return(Number.isFinite(vt)&&vt>0?vt:16)*i}function c(ye){const vt=ye.querySelector(".pie-section-player-passages-pane, .pie-section-player-items-pane");if(!vt)return 0;const kt=getComputedStyle(vt),Qe=Number.parseFloat(kt.marginLeft||"0"),cr=Number.parseFloat(kt.marginRight||"0"),V=(Number.isFinite(Qe)?Qe:0)+(Number.isFinite(cr)?cr:0);return V>0?V:0}function u(ye,vt){const kt=ye.clientWidth;if(!Number.isFinite(kt)||kt<=0)return{min:o,max:s};const Qe=d(ye),cr=Math.max(0,kt-Qe);if(cr<=0)return{min:50,max:50};const V=(vt+c(ye))/cr*100;if(!Number.isFinite(V)||V>=50)return{min:50,max:50};const ke=Math.max(o,V);return{min:ke,max:Math.min(s,Math.max(ke,100-ke))}}let f=_(t,"assessmentId",7),p=_(t,"runtime",7,null),g=_(t,"ndsIcons",7,void 0),v=_(t,"locale",7,""),b=_(t,"section",7,null),w=_(t,"sectionId",7,""),I=_(t,"attemptId",7,""),x=_(t,"iifeBundleHost",7),C=_(t,"debug",7,void 0),L=_(t,"baseHeadingLevel",7,void 0),E=_(t,"showToolbar",7,"false"),M=_(t,"toolbarPosition",7,"right"),U=_(t,"toolRegistry",7,null),te=_(t,"sectionHostButtons",23,()=>[]),re=_(t,"itemHostButtons",23,()=>[]),Pe=_(t,"passageHostButtons",23,()=>[]),z=_(t,"policies",7,void 0),K=_(t,"hooks",7,void 0),oe=_(t,"toolConfigStrictness",7,void 0),ue=_(t,"onFrameworkError",7,void 0),ae=_(t,"onStageChange",7,void 0),X=_(t,"onLoadingComplete",7,void 0),j=_(t,"narrowLayoutBreakpoint",7,void 0),D=_(t,"contentMaxWidthNoPassage",7,void 0),Z=_(t,"contentMaxWidthWithPassage",7,void 0),F=_(t,"splitPaneMinRegionWidth",7,void 0),W=_(t,"splitPaneInitialPassageWidth",7,void 0),O=_(t,"splitPaneCollapseStrategy",7,"tabbed");const $=ee(()=>lw(p(),{ndsIcons:g(),locale:v()})),ie=on(()=>l(W())??50);let N=He(Ti(on(()=>l(W()))));const ne=ee(()=>_w(j())),ge=Aw(()=>h(ne));let Oe=He(Ti(ie)),We=He(Ti({min:20,max:80})),Ne=He(null);const xe=uf(()=>h(Ne));let et=He(null),Ue=He(null);const Se=tc(),Re=ee(()=>`pie-section-player-splitpane-${(w()||I()||"default").replace(/[^a-zA-Z0-9_-]/g,"-")}`),mt=ee(()=>`${h(Re)}-passages`),$t=ee(()=>`${h(Re)}-items`),ve=ee(()=>`${Math.round(h(Oe))}% passages width`),me=ee(()=>Pw(D(),Z())),Je=ee(()=>h(me).noPassagePx),Gt=ee(()=>h(me).withPassagePx),le=ee(()=>$y(F(),r,n)),Ae=ee(()=>O()==="tabbed"?"tabbed":"vertical"),Y=ee(()=>ud({runtimePlayer:p()?.player,component:"pie-section-player-splitpane"})),we=ee(()=>Rm(h(et)));ct(()=>{const ye=h(Ne),vt=h(le);if(typeof window>"u"||!ye||typeof ResizeObserver>"u")return;if(vt===void 0){const cr={min:o,max:s};be(We,cr,!0),be(Oe,a(h(Oe),cr),!0);return}const kt=()=>{const cr=u(ye,vt);be(We,cr,!0),be(Oe,a(h(Oe),cr),!0)};kt();const Qe=new ResizeObserver(()=>kt());return Qe.observe(ye),()=>Qe.disconnect()}),ct(()=>{const ye=l(W());on(()=>{ye!==h(N)&&(be(N,ye,!0),ye!==void 0&&be(Oe,a(ye,h(We)),!0))})});function _e(ye){const vt=ye;Se(vt.type,vt.detail)}function Be(ye){if(!h(Ne))return;const vt=ye.detail,kt=Number(vt?.value);Number.isNaN(kt)||be(Oe,a(kt,h(We)),!0)}function it(){return h(Ue)?.getSnapshot?.()??null}function tt(){return h(Ue)?.selectComposition?.()??null}function Bt(){return h(Ue)?.selectNavigation?.()??null}function ht(){return h(Ue)?.selectReadiness?.()??null}function ot(ye){return h(Ue)?.navigateTo?.(ye)===!0}function $r(){return h(Ue)?.navigateNext?.()===!0}function Ur(){return h(Ue)?.navigatePrevious?.()===!0}function Lr(){return h(Ue)?.getSectionController?.()||null}ct(()=>{if(!h(we)||!ff(z()))return;const ye=h(we);return Gu({host:ye,instrumentationProvider:h(Y),component:"pie-section-player-splitpane",eventMap:Yp,staticAttributes:{instrumentationLayer:"section",assessmentId:f(),sectionId:w(),attemptId:I()||void 0},shouldTrackEvent:vt=>vt.target===ye,dedupeWindowMs:100})});var ln={getSnapshot:it,selectComposition:tt,selectNavigation:Bt,selectReadiness:ht,navigateTo:ot,navigateNext:$r,navigatePrevious:Ur,getSectionController:Lr,get assessmentId(){return f()},set assessmentId(ye){f(ye),R()},get runtime(){return p()},set runtime(ye=null){p(ye),R()},get ndsIcons(){return g()},set ndsIcons(ye=void 0){g(ye),R()},get locale(){return v()},set locale(ye=""){v(ye),R()},get section(){return b()},set section(ye=null){b(ye),R()},get sectionId(){return w()},set sectionId(ye=""){w(ye),R()},get attemptId(){return I()},set attemptId(ye=""){I(ye),R()},get iifeBundleHost(){return x()},set iifeBundleHost(ye){x(ye),R()},get debug(){return C()},set debug(ye=void 0){C(ye),R()},get baseHeadingLevel(){return L()},set baseHeadingLevel(ye=void 0){L(ye),R()},get showToolbar(){return E()},set showToolbar(ye="false"){E(ye),R()},get toolbarPosition(){return M()},set toolbarPosition(ye="right"){M(ye),R()},get toolRegistry(){return U()},set toolRegistry(ye=null){U(ye),R()},get sectionHostButtons(){return te()},set sectionHostButtons(ye=[]){te(ye),R()},get itemHostButtons(){return re()},set itemHostButtons(ye=[]){re(ye),R()},get passageHostButtons(){return Pe()},set passageHostButtons(ye=[]){Pe(ye),R()},get policies(){return z()},set policies(ye=void 0){z(ye),R()},get hooks(){return K()},set hooks(ye=void 0){K(ye),R()},get toolConfigStrictness(){return oe()},set toolConfigStrictness(ye=void 0){oe(ye),R()},get onFrameworkError(){return ue()},set onFrameworkError(ye=void 0){ue(ye),R()},get onStageChange(){return ae()},set onStageChange(ye=void 0){ae(ye),R()},get onLoadingComplete(){return X()},set onLoadingComplete(ye=void 0){X(ye),R()},get narrowLayoutBreakpoint(){return j()},set narrowLayoutBreakpoint(ye=void 0){j(ye),R()},get contentMaxWidthNoPassage(){return D()},set contentMaxWidthNoPassage(ye=void 0){D(ye),R()},get contentMaxWidthWithPassage(){return Z()},set contentMaxWidthWithPassage(ye=void 0){Z(ye),R()},get splitPaneMinRegionWidth(){return F()},set splitPaneMinRegionWidth(ye=void 0){F(ye),R()},get splitPaneInitialPassageWidth(){return W()},set splitPaneInitialPassageWidth(ye=void 0){W(ye),R()},get splitPaneCollapseStrategy(){return O()},set splitPaneCollapseStrategy(ye="tabbed"){O(ye),R()}},qr=zq(),xr=jn(qr);Er(xr,ye=>be(et,ye),()=>h(et));var Ar=lr(xr,2);{let ye=ee(()=>ge.isNarrow?"top":M());Er(mf(Ar,{get assessmentId(){return f()},get runtime(){return h($)},get section(){return b()},get sectionId(){return w()},get attemptId(){return I()},get iifeBundleHost(){return x()},get debug(){return C()},get baseHeadingLevel(){return L()},get showToolbar(){return E()},get toolbarPosition(){return h(ye)},get toolRegistry(){return U()},get sectionHostButtons(){return te()},get itemHostButtons(){return re()},get passageHostButtons(){return Pe()},get policies(){return z()},get hooks(){return K()},get toolConfigStrictness(){return oe()},get onFrameworkError(){return ue()},get onStageChange(){return ae()},get onLoadingComplete(){return X()},sourceCe:"pie-section-player-splitpane",get host(){return h(we)},playerActionConfig:{stateKey:"__splitPaneAppliedParams",includeSessionRefInState:!0},$$events:{"element-preload-retry":_e,"element-preload-error":_e},children:Wp,$$slots:{default:(vt,kt)=>{const Qe=ee(()=>kt.layoutModel);var cr=Nl(),V=jn(cr),ke=Ve=>{var at=Nl(),Rt=jn(at),Rr=jr=>{{let dr=ee(()=>`${h(Re)}-tabbed`);xw(jr,{get layoutModel(){return h(Qe)},get itemToolbarTools(){return h(Qe).itemToolbarTools},get passageToolbarTools(){return h(Qe).passageToolbarTools},get contentMaxWidthNoPassagePx(){return h(Je)},get contentMaxWidthWithPassagePx(){return h(Gt)},get toolRegistry(){return h(Qe).toolRegistry},get itemHostButtons(){return h(Qe).itemHostButtons},get passageHostButtons(){return h(Qe).passageHostButtons},get iifeBundleHost(){return x()},preloadComponentTag:"pie-section-player-splitpane",get idBase(){return h(dr)}})}},Vr=jr=>{Rw(jr,{get layoutModel(){return h(Qe)},get itemToolbarTools(){return h(Qe).itemToolbarTools},get passageToolbarTools(){return h(Qe).passageToolbarTools},get contentMaxWidthNoPassagePx(){return h(Je)},get contentMaxWidthWithPassagePx(){return h(Gt)},get toolRegistry(){return h(Qe).toolRegistry},get itemHostButtons(){return h(Qe).itemHostButtons},get passageHostButtons(){return h(Qe).passageHostButtons},get iifeBundleHost(){return x()},preloadComponentTag:"pie-section-player-vertical"})};vn(Rt,jr=>{h(Ae)==="tabbed"?jr(Rr):jr(Vr,-1)}),ft(Ve,at)},qe=Ve=>{var at=Hq(),Rt=Xt(at),Rr=Xt(Rt),Vr=fe=>{var _t=Fq(),Gr=jn(_t),tn=Xt(Gr);q(()=>G(tn,"compositionModel",h(Qe).compositionModel)),q(()=>G(tn,"passages",h(Qe).passages)),q(()=>G(tn,"elementsLoaded",h(Qe).paneElementsLoaded)),q(()=>G(tn,"resolvedPlayerEnv",h(Qe).resolvedPlayerEnv)),q(()=>G(tn,"resolvedPlayerAttributes",h(Qe).resolvedPlayerAttributes)),q(()=>G(tn,"resolvedPlayerProps",h(Qe).resolvedPlayerProps)),q(()=>G(tn,"baseHeadingLevel",h(Qe).baseHeadingLevel)),q(()=>G(tn,"playerStrategy",h(Qe).playerStrategy)),q(()=>G(tn,"passageToolbarTools",h(Qe).passageToolbarTools)),q(()=>G(tn,"toolRegistry",h(Qe).toolRegistry)),q(()=>G(tn,"hostButtons",h(Qe).passageHostButtons)),Kt(Gr);var Wn=lr(Gr,2);{let ei=ee(()=>xe.t("player.resizePassagesAndItemsA11y"));K_(Wn,{get value(){return h(Oe)},get min(){return h(We).min},get max(){return h(We).max},get ariaLabel(){return h(ei)},get ariaControls(){return h(mt)},get ariaValueText(){return h(ve)},$$events:{"resize-preview":Be,"resize-commit":Be}})}q(ei=>{nt(Gr,"id",h(mt)),nt(Gr,"aria-label",ei)},[()=>xe.t("player.passagesRegionA11y")]),ft(fe,_t)};vn(Rr,fe=>{h(Qe).passages.length>0&&fe(Vr)});var jr=lr(Rr,2),dr=Xt(jr);q(()=>G(dr,"items",h(Qe).items)),q(()=>G(dr,"compositionModel",h(Qe).compositionModel)),q(()=>G(dr,"resolvedPlayerEnv",h(Qe).resolvedPlayerEnv)),q(()=>G(dr,"resolvedPlayerAttributes",h(Qe).resolvedPlayerAttributes)),q(()=>G(dr,"resolvedPlayerProps",h(Qe).resolvedPlayerProps)),q(()=>G(dr,"baseHeadingLevel",h(Qe).baseHeadingLevel)),q(()=>G(dr,"playerStrategy",h(Qe).playerStrategy)),q(()=>G(dr,"itemToolbarTools",h(Qe).itemToolbarTools)),q(()=>G(dr,"toolRegistry",h(Qe).toolRegistry)),q(()=>G(dr,"hostButtons",h(Qe).itemHostButtons)),q(()=>G(dr,"iifeBundleHost",x())),q(()=>G(dr,"preloadedRenderables",h(Qe).preloadedRenderables)),q(()=>G(dr,"preloadedRenderablesSignature",h(Qe).preloadedRenderablesSignature)),G(dr,"preloadComponentTag","pie-section-player-splitpane"),q(()=>G(dr,"preloadEnabled",h(Qe).preloadEnabled)),Kt(jr),Kt(Rt),Er(Rt,fe=>be(Ne,fe),()=>h(Ne)),Kt(at),q(fe=>{Dl(at,`--pie-section-player-layout-max-width: ${h(Qe).passages.length===0?h(Je)!==void 0?`${h(Je)}px`:"none":h(Gt)!==void 0?`${h(Gt)}px`:"none"};`),gn(Rt,1,`pie-section-player-split-content ${h(Qe).passages.length===0?"pie-section-player-split-content--no-passages":""}`,"svelte-qeub3g"),Dl(Rt,h(Qe).passages.length===0?"grid-template-columns: 1fr":`grid-template-columns: minmax(0, calc((100% - 0.5rem) * ${h(Oe)/100})) 0.5rem minmax(0, calc((100% - 0.5rem) * ${(100-h(Oe))/100}))`),nt(jr,"id",h($t)),nt(jr,"aria-label",fe)},[()=>xe.t("player.itemsRegionA11y")]),Gn("elements-loaded-change",dr,function(...fe){h(Qe).onItemsPaneElementsLoaded?.apply(this,fe)}),Gn("element-preload-retry",dr,function(...fe){h(Qe).onItemsPanePreloadRetry?.apply(this,fe)}),Gn("element-preload-error",dr,function(...fe){h(Qe).onItemsPanePreloadError?.apply(this,fe)}),ft(Ve,at)};vn(V,Ve=>{ge.isNarrow?Ve(ke):Ve(qe,-1)}),ft(vt,cr)}}}),vt=>be(Ue,vt,!0),()=>h(Ue))}return ft(e,qr),fn(ln)}qq("pie-section-player-splitpane",In(Uq,{assessmentId:{attribute:"assessment-id",type:"String"},runtime:{type:"Object"},ndsIcons:{attribute:"nds-icons",type:"Boolean"},locale:{attribute:"locale",type:"String"},section:{type:"Object"},sectionId:{attribute:"section-id",type:"String"},attemptId:{attribute:"attempt-id",type:"String"},iifeBundleHost:{attribute:"iife-bundle-host",type:"String"},debug:{attribute:"debug",type:"String"},baseHeadingLevel:{attribute:"base-heading-level",type:"Number"},showToolbar:{attribute:"show-toolbar",type:"String"},toolbarPosition:{attribute:"toolbar-position",type:"String"},toolRegistry:{type:"Object"},sectionHostButtons:{type:"Object"},itemHostButtons:{type:"Object"},passageHostButtons:{type:"Object"},policies:{type:"Object"},hooks:{type:"Object"},toolConfigStrictness:{attribute:"tool-config-strictness",type:"String"},onFrameworkError:{type:"Object"},onStageChange:{type:"Object"},onLoadingComplete:{type:"Object"},narrowLayoutBreakpoint:{attribute:"narrow-layout-breakpoint",type:"Number"},contentMaxWidthNoPassage:{attribute:"content-max-width-no-passage",type:"Number"},contentMaxWidthWithPassage:{attribute:"content-max-width-with-passage",type:"Number"},splitPaneMinRegionWidth:{attribute:"split-pane-min-region-width",type:"Number"},splitPaneInitialPassageWidth:{attribute:"split-pane-initial-passage-width",type:"Number"},splitPaneCollapseStrategy:{attribute:"split-pane-collapse-strategy",type:"String"}},[],["getSnapshot","selectComposition","selectNavigation","selectReadiness","navigateTo","navigateNext","navigatePrevious","getSectionController"],void 0,e=>Zs(xm(Cw)(e))));function qq(e,t){customElements.get(e)||customElements.define(e,t)}var Vq=Ht('<div class="pie-section-player-observability-anchor svelte-e5eey4" aria-hidden="true"></div> <!>',1),Gq={hash:"svelte-e5eey4",code:":host {display:block;width:100%;height:100%;min-height:0;max-height:100%;overflow:hidden;}.pie-section-player-observability-anchor.svelte-e5eey4 {display:none;}"};function Kq(e,t){un(t,!0),Mn(e,Gq);let r=_(t,"assessmentId",7),n=_(t,"runtime",7,null),i=_(t,"ndsIcons",7,void 0),o=_(t,"locale",7,""),s=_(t,"section",7,null),a=_(t,"sectionId",7,""),l=_(t,"attemptId",7,""),d=_(t,"iifeBundleHost",7),c=_(t,"debug",7,void 0),u=_(t,"baseHeadingLevel",7,void 0),f=_(t,"showToolbar",7,"false"),p=_(t,"toolbarPosition",7,"right"),g=_(t,"toolRegistry",7,null),v=_(t,"sectionHostButtons",23,()=>[]),b=_(t,"itemHostButtons",23,()=>[]),w=_(t,"passageHostButtons",23,()=>[]),I=_(t,"policies",7,void 0),x=_(t,"hooks",7,void 0),C=_(t,"toolConfigStrictness",7,void 0),L=_(t,"onFrameworkError",7,void 0),E=_(t,"onStageChange",7,void 0),M=_(t,"onLoadingComplete",7,void 0),U=_(t,"narrowLayoutBreakpoint",7,void 0),te=_(t,"contentMaxWidthNoPassage",7,void 0),re=_(t,"contentMaxWidthWithPassage",7,void 0),Pe=_(t,"splitPaneMinRegionWidth",7,void 0),z=_(t,"splitPaneInitialPassageWidth",7,void 0),K=_(t,"splitPaneCollapseStrategy",7,"vertical");const oe=ee(()=>lw(n(),{ndsIcons:i(),locale:o()})),ue=tc();let ae=He(null),X=He(null);const j=ee(()=>ud({runtimePlayer:n()?.player,component:"pie-section-player-vertical"})),D=ee(()=>Rm(h(ae))),Z=ee(()=>_w(U())),F=Aw(()=>h(Z)),W=ee(()=>F.isNarrow?"top":p()),O=ee(()=>Pw(te(),re())),$=ee(()=>h(O).noPassagePx),ie=ee(()=>h(O).withPassagePx);function N(ve){const me=ve;ue(me.type,me.detail)}function ne(){return h(X)?.getSnapshot?.()??null}function ge(){return h(X)?.selectComposition?.()??null}function Oe(){return h(X)?.selectNavigation?.()??null}function We(){return h(X)?.selectReadiness?.()??null}function Ne(ve){return h(X)?.navigateTo?.(ve)===!0}function xe(){return h(X)?.navigateNext?.()===!0}function et(){return h(X)?.navigatePrevious?.()===!0}function Ue(){return h(X)?.getSectionController?.()||null}ct(()=>{if(!h(D)||!ff(I()))return;const ve=h(D);return Gu({host:ve,instrumentationProvider:h(j),component:"pie-section-player-vertical",eventMap:Yp,staticAttributes:{instrumentationLayer:"section",assessmentId:r(),sectionId:a(),attemptId:l()||void 0},shouldTrackEvent:me=>me.target===ve,dedupeWindowMs:100})});var Se={getSnapshot:ne,selectComposition:ge,selectNavigation:Oe,selectReadiness:We,navigateTo:Ne,navigateNext:xe,navigatePrevious:et,getSectionController:Ue,get assessmentId(){return r()},set assessmentId(ve){r(ve),R()},get runtime(){return n()},set runtime(ve=null){n(ve),R()},get ndsIcons(){return i()},set ndsIcons(ve=void 0){i(ve),R()},get locale(){return o()},set locale(ve=""){o(ve),R()},get section(){return s()},set section(ve=null){s(ve),R()},get sectionId(){return a()},set sectionId(ve=""){a(ve),R()},get attemptId(){return l()},set attemptId(ve=""){l(ve),R()},get iifeBundleHost(){return d()},set iifeBundleHost(ve){d(ve),R()},get debug(){return c()},set debug(ve=void 0){c(ve),R()},get baseHeadingLevel(){return u()},set baseHeadingLevel(ve=void 0){u(ve),R()},get showToolbar(){return f()},set showToolbar(ve="false"){f(ve),R()},get toolbarPosition(){return p()},set toolbarPosition(ve="right"){p(ve),R()},get toolRegistry(){return g()},set toolRegistry(ve=null){g(ve),R()},get sectionHostButtons(){return v()},set sectionHostButtons(ve=[]){v(ve),R()},get itemHostButtons(){return b()},set itemHostButtons(ve=[]){b(ve),R()},get passageHostButtons(){return w()},set passageHostButtons(ve=[]){w(ve),R()},get policies(){return I()},set policies(ve=void 0){I(ve),R()},get hooks(){return x()},set hooks(ve=void 0){x(ve),R()},get toolConfigStrictness(){return C()},set toolConfigStrictness(ve=void 0){C(ve),R()},get onFrameworkError(){return L()},set onFrameworkError(ve=void 0){L(ve),R()},get onStageChange(){return E()},set onStageChange(ve=void 0){E(ve),R()},get onLoadingComplete(){return M()},set onLoadingComplete(ve=void 0){M(ve),R()},get narrowLayoutBreakpoint(){return U()},set narrowLayoutBreakpoint(ve=void 0){U(ve),R()},get contentMaxWidthNoPassage(){return te()},set contentMaxWidthNoPassage(ve=void 0){te(ve),R()},get contentMaxWidthWithPassage(){return re()},set contentMaxWidthWithPassage(ve=void 0){re(ve),R()},get splitPaneMinRegionWidth(){return Pe()},set splitPaneMinRegionWidth(ve=void 0){Pe(ve),R()},get splitPaneInitialPassageWidth(){return z()},set splitPaneInitialPassageWidth(ve=void 0){z(ve),R()},get splitPaneCollapseStrategy(){return K()},set splitPaneCollapseStrategy(ve="vertical"){K(ve),R()}},Re=Vq(),mt=jn(Re);Er(mt,ve=>be(ae,ve),()=>h(ae));var $t=lr(mt,2);return Er(mf($t,{get assessmentId(){return r()},get runtime(){return h(oe)},get section(){return s()},get sectionId(){return a()},get attemptId(){return l()},get iifeBundleHost(){return d()},get debug(){return c()},get baseHeadingLevel(){return u()},get showToolbar(){return f()},get toolbarPosition(){return h(W)},get toolRegistry(){return g()},get sectionHostButtons(){return v()},get itemHostButtons(){return b()},get passageHostButtons(){return w()},get policies(){return I()},get hooks(){return x()},get toolConfigStrictness(){return C()},get onFrameworkError(){return L()},get onStageChange(){return E()},get onLoadingComplete(){return M()},sourceCe:"pie-section-player-vertical",get host(){return h(D)},playerActionConfig:{stateKey:"__verticalAppliedParams",includeSessionRefInState:!1},$$events:{"element-preload-retry":N,"element-preload-error":N},children:Wp,$$slots:{default:(ve,me)=>{const Je=ee(()=>me.layoutModel);Rw(ve,{get layoutModel(){return h(Je)},get itemToolbarTools(){return h(Je).itemToolbarTools},get passageToolbarTools(){return h(Je).passageToolbarTools},get contentMaxWidthNoPassagePx(){return h($)},get contentMaxWidthWithPassagePx(){return h(ie)},get toolRegistry(){return h(Je).toolRegistry},get itemHostButtons(){return h(Je).itemHostButtons},get passageHostButtons(){return h(Je).passageHostButtons},get iifeBundleHost(){return d()},preloadComponentTag:"pie-section-player-vertical"})}}}),ve=>be(X,ve,!0),()=>h(X)),ft(e,Re),fn(Se)}Xq("pie-section-player-vertical",In(Kq,{assessmentId:{attribute:"assessment-id",type:"String"},runtime:{type:"Object"},ndsIcons:{attribute:"nds-icons",type:"Boolean"},locale:{attribute:"locale",type:"String"},section:{type:"Object"},sectionId:{attribute:"section-id",type:"String"},attemptId:{attribute:"attempt-id",type:"String"},iifeBundleHost:{attribute:"iife-bundle-host",type:"String"},debug:{attribute:"debug",type:"String"},baseHeadingLevel:{attribute:"base-heading-level",type:"Number"},showToolbar:{attribute:"show-toolbar",type:"String"},toolbarPosition:{attribute:"toolbar-position",type:"String"},toolRegistry:{type:"Object"},sectionHostButtons:{type:"Object"},itemHostButtons:{type:"Object"},passageHostButtons:{type:"Object"},policies:{type:"Object"},hooks:{type:"Object"},toolConfigStrictness:{attribute:"tool-config-strictness",type:"String"},onFrameworkError:{type:"Object"},onStageChange:{type:"Object"},onLoadingComplete:{type:"Object"},narrowLayoutBreakpoint:{attribute:"narrow-layout-breakpoint",type:"Number"},contentMaxWidthNoPassage:{attribute:"content-max-width-no-passage",type:"Number"},contentMaxWidthWithPassage:{attribute:"content-max-width-with-passage",type:"Number"},splitPaneMinRegionWidth:{attribute:"split-pane-min-region-width",type:"Number"},splitPaneInitialPassageWidth:{attribute:"split-pane-initial-passage-width",type:"Number"},splitPaneCollapseStrategy:{attribute:"split-pane-collapse-strategy",type:"String"}},[],["getSnapshot","selectComposition","selectNavigation","selectReadiness","navigateTo","navigateNext","navigatePrevious","getSectionController"],void 0,e=>Zs(xm(Cw)(e))));function Xq(e,t){customElements.get(e)||customElements.define(e,t)}var Zq=Ht('<div class="pie-section-player-observability-anchor svelte-w6yo40" aria-hidden="true"></div> <!>',1),Yq={hash:"svelte-w6yo40",code:":host {display:block;width:100%;height:100%;min-height:0;max-height:100%;overflow:hidden;}.pie-section-player-observability-anchor.svelte-w6yo40 {display:none;}"};function Jq(e,t){un(t,!0),Mn(e,Yq);let r=_(t,"assessmentId",7),n=_(t,"runtime",7,null),i=_(t,"ndsIcons",7,void 0),o=_(t,"locale",7,""),s=_(t,"section",7,null),a=_(t,"sectionId",7,""),l=_(t,"attemptId",7,""),d=_(t,"iifeBundleHost",7),c=_(t,"debug",7,void 0),u=_(t,"baseHeadingLevel",7,void 0),f=_(t,"showToolbar",7,"false"),p=_(t,"toolbarPosition",7,"right"),g=_(t,"toolRegistry",7,null),v=_(t,"sectionHostButtons",23,()=>[]),b=_(t,"itemHostButtons",23,()=>[]),w=_(t,"passageHostButtons",23,()=>[]),I=_(t,"policies",7,void 0),x=_(t,"hooks",7,void 0),C=_(t,"toolConfigStrictness",7,void 0),L=_(t,"onFrameworkError",7,void 0),E=_(t,"onStageChange",7,void 0),M=_(t,"onLoadingComplete",7,void 0),U=_(t,"narrowLayoutBreakpoint",7,void 0),te=_(t,"contentMaxWidthNoPassage",7,void 0),re=_(t,"contentMaxWidthWithPassage",7,void 0),Pe=_(t,"splitPaneMinRegionWidth",7,void 0),z=_(t,"splitPaneInitialPassageWidth",7,void 0),K=_(t,"splitPaneCollapseStrategy",7,"vertical");const oe=ee(()=>lw(n(),{ndsIcons:i(),locale:o()})),ue=tc();let ae=He(null),X=He(null);const j=ee(()=>`pie-section-player-tabbed-${(a()||l()||"default").replace(/[^a-zA-Z0-9_-]/g,"-")}`),D=ee(()=>ud({runtimePlayer:n()?.player,component:"pie-section-player-tabbed"})),Z=ee(()=>Rm(h(ae))),F=ee(()=>_w(U())),W=Aw(()=>h(F)),O=ee(()=>W.isNarrow?"top":p()),$=ee(()=>Pw(te(),re())),ie=ee(()=>h($).noPassagePx),N=ee(()=>h($).withPassagePx);function ne(me){const Je=me;ue(Je.type,Je.detail)}function ge(){return h(X)?.getSnapshot?.()??null}function Oe(){return h(X)?.selectComposition?.()??null}function We(){return h(X)?.selectNavigation?.()??null}function Ne(){return h(X)?.selectReadiness?.()??null}function xe(me){return h(X)?.navigateTo?.(me)===!0}function et(){return h(X)?.navigateNext?.()===!0}function Ue(){return h(X)?.navigatePrevious?.()===!0}function Se(){return h(X)?.getSectionController?.()||null}ct(()=>{if(!h(Z)||!ff(I()))return;const me=h(Z);return Gu({host:me,instrumentationProvider:h(D),component:"pie-section-player-tabbed",eventMap:Yp,staticAttributes:{instrumentationLayer:"section",assessmentId:r(),sectionId:a(),attemptId:l()||void 0},shouldTrackEvent:Je=>Je.target===me,dedupeWindowMs:100})});var Re={getSnapshot:ge,selectComposition:Oe,selectNavigation:We,selectReadiness:Ne,navigateTo:xe,navigateNext:et,navigatePrevious:Ue,getSectionController:Se,get assessmentId(){return r()},set assessmentId(me){r(me),R()},get runtime(){return n()},set runtime(me=null){n(me),R()},get ndsIcons(){return i()},set ndsIcons(me=void 0){i(me),R()},get locale(){return o()},set locale(me=""){o(me),R()},get section(){return s()},set section(me=null){s(me),R()},get sectionId(){return a()},set sectionId(me=""){a(me),R()},get attemptId(){return l()},set attemptId(me=""){l(me),R()},get iifeBundleHost(){return d()},set iifeBundleHost(me){d(me),R()},get debug(){return c()},set debug(me=void 0){c(me),R()},get baseHeadingLevel(){return u()},set baseHeadingLevel(me=void 0){u(me),R()},get showToolbar(){return f()},set showToolbar(me="false"){f(me),R()},get toolbarPosition(){return p()},set toolbarPosition(me="right"){p(me),R()},get toolRegistry(){return g()},set toolRegistry(me=null){g(me),R()},get sectionHostButtons(){return v()},set sectionHostButtons(me=[]){v(me),R()},get itemHostButtons(){return b()},set itemHostButtons(me=[]){b(me),R()},get passageHostButtons(){return w()},set passageHostButtons(me=[]){w(me),R()},get policies(){return I()},set policies(me=void 0){I(me),R()},get hooks(){return x()},set hooks(me=void 0){x(me),R()},get toolConfigStrictness(){return C()},set toolConfigStrictness(me=void 0){C(me),R()},get onFrameworkError(){return L()},set onFrameworkError(me=void 0){L(me),R()},get onStageChange(){return E()},set onStageChange(me=void 0){E(me),R()},get onLoadingComplete(){return M()},set onLoadingComplete(me=void 0){M(me),R()},get narrowLayoutBreakpoint(){return U()},set narrowLayoutBreakpoint(me=void 0){U(me),R()},get contentMaxWidthNoPassage(){return te()},set contentMaxWidthNoPassage(me=void 0){te(me),R()},get contentMaxWidthWithPassage(){return re()},set contentMaxWidthWithPassage(me=void 0){re(me),R()},get splitPaneMinRegionWidth(){return Pe()},set splitPaneMinRegionWidth(me=void 0){Pe(me),R()},get splitPaneInitialPassageWidth(){return z()},set splitPaneInitialPassageWidth(me=void 0){z(me),R()},get splitPaneCollapseStrategy(){return K()},set splitPaneCollapseStrategy(me="vertical"){K(me),R()}},mt=Zq(),$t=jn(mt);Er($t,me=>be(ae,me),()=>h(ae));var ve=lr($t,2);return Er(mf(ve,{get assessmentId(){return r()},get runtime(){return h(oe)},get section(){return s()},get sectionId(){return a()},get attemptId(){return l()},get iifeBundleHost(){return d()},get debug(){return c()},get baseHeadingLevel(){return u()},get showToolbar(){return f()},get toolbarPosition(){return h(O)},get toolRegistry(){return g()},get sectionHostButtons(){return v()},get itemHostButtons(){return b()},get passageHostButtons(){return w()},get policies(){return I()},get hooks(){return x()},get toolConfigStrictness(){return C()},get onFrameworkError(){return L()},get onStageChange(){return E()},get onLoadingComplete(){return M()},sourceCe:"pie-section-player-tabbed",get host(){return h(Z)},playerActionConfig:{stateKey:"__tabbedAppliedParams",includeSessionRefInState:!1},$$events:{"element-preload-retry":ne,"element-preload-error":ne},children:Wp,$$slots:{default:(me,Je)=>{const Gt=ee(()=>Je.layoutModel);xw(me,{get layoutModel(){return h(Gt)},get itemToolbarTools(){return h(Gt).itemToolbarTools},get passageToolbarTools(){return h(Gt).passageToolbarTools},get contentMaxWidthNoPassagePx(){return h(ie)},get contentMaxWidthWithPassagePx(){return h(N)},get toolRegistry(){return h(Gt).toolRegistry},get itemHostButtons(){return h(Gt).itemHostButtons},get passageHostButtons(){return h(Gt).passageHostButtons},get iifeBundleHost(){return d()},preloadComponentTag:"pie-section-player-tabbed",get idBase(){return h(j)}})}}}),me=>be(X,me,!0),()=>h(X)),ft(e,mt),fn(Re)}Qq("pie-section-player-tabbed",In(Jq,{assessmentId:{attribute:"assessment-id",type:"String"},runtime:{type:"Object"},ndsIcons:{attribute:"nds-icons",type:"Boolean"},locale:{attribute:"locale",type:"String"},section:{type:"Object"},sectionId:{attribute:"section-id",type:"String"},attemptId:{attribute:"attempt-id",type:"String"},iifeBundleHost:{attribute:"iife-bundle-host",type:"String"},debug:{attribute:"debug",type:"String"},baseHeadingLevel:{attribute:"base-heading-level",type:"Number"},showToolbar:{attribute:"show-toolbar",type:"String"},toolbarPosition:{attribute:"toolbar-position",type:"String"},toolRegistry:{type:"Object"},sectionHostButtons:{type:"Object"},itemHostButtons:{type:"Object"},passageHostButtons:{type:"Object"},policies:{type:"Object"},hooks:{type:"Object"},toolConfigStrictness:{attribute:"tool-config-strictness",type:"String"},onFrameworkError:{type:"Object"},onStageChange:{type:"Object"},onLoadingComplete:{type:"Object"},narrowLayoutBreakpoint:{attribute:"narrow-layout-breakpoint",type:"Number"},contentMaxWidthNoPassage:{attribute:"content-max-width-no-passage",type:"Number"},contentMaxWidthWithPassage:{attribute:"content-max-width-with-passage",type:"Number"},splitPaneMinRegionWidth:{attribute:"split-pane-min-region-width",type:"Number"},splitPaneInitialPassageWidth:{attribute:"split-pane-initial-passage-width",type:"Number"},splitPaneCollapseStrategy:{attribute:"split-pane-collapse-strategy",type:"String"}},[],["getSnapshot","selectComposition","selectNavigation","selectReadiness","navigateTo","navigateNext","navigatePrevious","getSectionController"],void 0,e=>Zs(xm(Cw)(e))));function Qq(e,t){customElements.get(e)||customElements.define(e,t)}var eV=Ht("<pie-section-player-passages-pane></pie-section-player-passages-pane>",2),tV=Ht('<div class="pie-section-player-kernel-host-content svelte-1y3fqx7"><!> <pie-section-player-items-pane></pie-section-player-items-pane></div>',2),rV=Ht('<div class="pie-section-player-observability-anchor svelte-1y3fqx7" aria-hidden="true"></div> <!>',1),nV={hash:"svelte-1y3fqx7",code:":host {display:block;width:100%;height:100%;min-height:0;overflow:hidden;}.pie-section-player-kernel-host-content.svelte-1y3fqx7 {display:flex;flex-direction:column;gap:1rem;min-height:0;height:100%;padding:0.5rem;box-sizing:border-box;}pie-section-player-items-pane.svelte-1y3fqx7 .pie-section-player-scroll-hint {bottom:-0.5rem;}.pie-section-player-observability-anchor.svelte-1y3fqx7 {display:none;}"};function iV(e,t){un(t,!0),Mn(e,nV);let r=_(t,"assessmentId",7),n=_(t,"runtime",7,null),i=_(t,"section",7,null),o=_(t,"sectionId",7,""),s=_(t,"attemptId",7,""),a=_(t,"iifeBundleHost",7),l=_(t,"debug",7,void 0),d=_(t,"baseHeadingLevel",7,void 0),c=_(t,"showToolbar",7,"false"),u=_(t,"toolbarPosition",7,"right"),f=_(t,"toolRegistry",7,null),p=_(t,"sectionHostButtons",23,()=>[]),g=_(t,"itemHostButtons",23,()=>[]),v=_(t,"passageHostButtons",23,()=>[]),b=_(t,"policies",7,void 0),w=_(t,"hooks",7,void 0),I=_(t,"toolConfigStrictness",7,void 0),x=_(t,"onFrameworkError",7,void 0),C=_(t,"onStageChange",7,void 0),L=_(t,"onLoadingComplete",7,void 0);const E=tc();let M=He(null),U=He(null);const te=ee(()=>ud({runtimePlayer:n()?.player,component:"pie-section-player-kernel-host"})),re=ee(()=>Rm(h(M)));function Pe(){return{readiness:oe(),composition:z(),navigation:K()}}function z(){return h(U)?.selectComposition?.()||cu.composition}function K(){return h(U)?.selectNavigation?.()||cu.navigation}function oe(){return h(U)?.selectReadiness?.()||Ew}function ue($){return h(U)?.navigateTo?.($)===!0}function ae(){return h(U)?.navigateNext?.()===!0}function X(){return h(U)?.navigatePrevious?.()===!0}function j(){return h(U)?.getSectionController?.()||null}function D($){const ie=$;E(ie.type,ie.detail)}ct(()=>{if(!h(re)||!ff(b()))return;const $=h(re);return Gu({host:$,instrumentationProvider:h(te),component:"pie-section-player-kernel-host",eventMap:Yp,staticAttributes:{instrumentationLayer:"section",assessmentId:r(),sectionId:o(),attemptId:s()||void 0},shouldTrackEvent:ie=>ie.target===$,dedupeWindowMs:100})});var Z={getSnapshot:Pe,selectComposition:z,selectNavigation:K,selectReadiness:oe,navigateTo:ue,navigateNext:ae,navigatePrevious:X,getSectionController:j,get assessmentId(){return r()},set assessmentId($){r($),R()},get runtime(){return n()},set runtime($=null){n($),R()},get section(){return i()},set section($=null){i($),R()},get sectionId(){return o()},set sectionId($=""){o($),R()},get attemptId(){return s()},set attemptId($=""){s($),R()},get iifeBundleHost(){return a()},set iifeBundleHost($){a($),R()},get debug(){return l()},set debug($=void 0){l($),R()},get baseHeadingLevel(){return d()},set baseHeadingLevel($=void 0){d($),R()},get showToolbar(){return c()},set showToolbar($="false"){c($),R()},get toolbarPosition(){return u()},set toolbarPosition($="right"){u($),R()},get toolRegistry(){return f()},set toolRegistry($=null){f($),R()},get sectionHostButtons(){return p()},set sectionHostButtons($=[]){p($),R()},get itemHostButtons(){return g()},set itemHostButtons($=[]){g($),R()},get passageHostButtons(){return v()},set passageHostButtons($=[]){v($),R()},get policies(){return b()},set policies($=void 0){b($),R()},get hooks(){return w()},set hooks($=void 0){w($),R()},get toolConfigStrictness(){return I()},set toolConfigStrictness($=void 0){I($),R()},get onFrameworkError(){return x()},set onFrameworkError($=void 0){x($),R()},get onStageChange(){return C()},set onStageChange($=void 0){C($),R()},get onLoadingComplete(){return L()},set onLoadingComplete($=void 0){L($),R()}},F=rV(),W=jn(F);Er(W,$=>be(M,$),()=>h(M));var O=lr(W,2);return Er(mf(O,{get assessmentId(){return r()},get runtime(){return n()},get section(){return i()},get sectionId(){return o()},get attemptId(){return s()},get iifeBundleHost(){return a()},get debug(){return l()},get baseHeadingLevel(){return d()},get showToolbar(){return c()},get toolbarPosition(){return u()},get toolRegistry(){return f()},get sectionHostButtons(){return p()},get itemHostButtons(){return g()},get passageHostButtons(){return v()},get policies(){return b()},get hooks(){return w()},get toolConfigStrictness(){return I()},get onFrameworkError(){return x()},get onStageChange(){return C()},get onLoadingComplete(){return L()},sourceCe:"pie-section-player",get host(){return h(re)},$$events:{"element-preload-retry":D,"element-preload-error":D},children:Wp,$$slots:{default:($,ie)=>{const N=ee(()=>ie.items),ne=ee(()=>ie.passages),ge=ee(()=>ie.compositionModel),Oe=ee(()=>ie.resolvedPlayerEnv),We=ee(()=>ie.resolvedPlayerAttributes),Ne=ee(()=>ie.resolvedPlayerProps),xe=ee(()=>ie.playerStrategy),et=ee(()=>ie.baseHeadingLevel),Ue=ee(()=>ie.preloadedRenderables),Se=ee(()=>ie.preloadedRenderablesSignature),Re=ee(()=>ie.preloadEnabled),mt=ee(()=>ie.itemToolbarTools),$t=ee(()=>ie.passageToolbarTools),ve=ee(()=>ie.toolRegistry),me=ee(()=>ie.readinessDetail),Je=ee(()=>ie.onItemsPaneElementsLoaded),Gt=ee(()=>ie.onItemsPanePreloadRetry),le=ee(()=>ie.onItemsPanePreloadError);var Ae=tV(),Y=Xt(Ae),we=Be=>{var it=eV();q(()=>G(it,"compositionModel",h(ge))),q(()=>G(it,"passages",h(ne))),q(()=>G(it,"elementsLoaded",h(me).allLoadingComplete)),q(()=>G(it,"resolvedPlayerEnv",h(Oe))),q(()=>G(it,"resolvedPlayerAttributes",h(We))),q(()=>G(it,"resolvedPlayerProps",h(Ne))),q(()=>G(it,"baseHeadingLevel",h(et))),q(()=>G(it,"playerStrategy",h(xe))),q(()=>G(it,"passageToolbarTools",h($t))),q(()=>G(it,"toolRegistry",h(ve))),q(()=>G(it,"hostButtons",v())),ft(Be,it)};vn(Y,Be=>{h(ne).length>0&&Be(we)});var _e=lr(Y,2);q(()=>G(_e,"items",h(N))),q(()=>G(_e,"compositionModel",h(ge))),q(()=>G(_e,"resolvedPlayerEnv",h(Oe))),q(()=>G(_e,"resolvedPlayerAttributes",h(We))),q(()=>G(_e,"resolvedPlayerProps",h(Ne))),q(()=>G(_e,"baseHeadingLevel",h(et))),q(()=>G(_e,"playerStrategy",h(xe))),q(()=>G(_e,"itemToolbarTools",h(mt))),q(()=>G(_e,"toolRegistry",h(ve))),q(()=>G(_e,"hostButtons",g())),q(()=>G(_e,"iifeBundleHost",a())),q(()=>G(_e,"preloadedRenderables",h(Ue))),q(()=>G(_e,"preloadedRenderablesSignature",h(Se))),G(_e,"preloadComponentTag","pie-section-player-kernel-host"),q(()=>G(_e,"preloadEnabled",h(Re))),gn(_e,1,"svelte-1y3fqx7"),Kt(Ae),Gn("elements-loaded-change",_e,function(...Be){h(Je)?.apply(this,Be)}),Gn("element-preload-retry",_e,function(...Be){h(Gt)?.apply(this,Be)}),Gn("element-preload-error",_e,function(...Be){h(le)?.apply(this,Be)}),ft($,Ae)}}}),$=>be(U,$,!0),()=>h(U)),ft(e,F),fn(Z)}oV("pie-section-player-kernel-host",In(iV,{assessmentId:{attribute:"assessment-id",type:"String"},runtime:{type:"Object"},section:{type:"Object"},sectionId:{attribute:"section-id",type:"String"},attemptId:{attribute:"attempt-id",type:"String"},iifeBundleHost:{attribute:"iife-bundle-host",type:"String"},debug:{attribute:"debug",type:"String"},baseHeadingLevel:{attribute:"base-heading-level",type:"Number"},showToolbar:{attribute:"show-toolbar",type:"String"},toolbarPosition:{attribute:"toolbar-position",type:"String"},toolRegistry:{type:"Object"},sectionHostButtons:{type:"Object"},itemHostButtons:{type:"Object"},passageHostButtons:{type:"Object"},policies:{type:"Object"},hooks:{type:"Object"},toolConfigStrictness:{attribute:"tool-config-strictness",type:"String"},onFrameworkError:{type:"Object"},onStageChange:{type:"Object"},onLoadingComplete:{type:"Object"}},[],["getSnapshot","selectComposition","selectNavigation","selectReadiness","navigateTo","navigateNext","navigatePrevious","getSectionController"],void 0,xm(Cq)));function oV(e,t){customElements.get(e)||customElements.define(e,t)}var Xa={runtimeOwned:"runtime-owned",runtimeInherited:"runtime-inherited",frameworkError:"framework-error",compositionChanged:"composition-changed",sessionChanged:"session-changed",stageChange:"pie-stage-change",loadingComplete:"pie-loading-complete"},_m=["assessmentId","section","sectionId","attemptId","debug","showToolbar","toolbarPosition","narrowLayoutBreakpoint","contentMaxWidthNoPassage","contentMaxWidthWithPassage","splitPaneMinRegionWidth","splitPaneInitialPassageWidth","splitPaneCollapseStrategy"],Pm=["runtime","iifeBundleHost","toolRegistry","sectionHostButtons","itemHostButtons","passageHostButtons","policies","toolConfigStrictness","hooks","onFrameworkError","onStageChange","onLoadingComplete"],Mw=[..._m,...Pm],$w=[Xa.runtimeOwned,Xa.runtimeInherited,Xa.frameworkError,Xa.compositionChanged,Xa.sessionChanged,Xa.stageChange,Xa.loadingComplete],Lw=["getSnapshot","selectComposition","selectNavigation","selectReadiness","navigateTo","navigateNext","navigatePrevious","getSectionController","waitForSectionController"],Ow=["items-pane","passages-pane","section-toolbar","item-toolbar","passage-toolbar","readiness-events","navigation-events"],jV={version:1,layout:"splitpane",props:Mw,recommendedBasicProps:_m,advancedEscapeHatchProps:Pm,events:$w,commands:Lw,capabilities:Ow},BV={version:1,layout:"vertical",props:Mw,recommendedBasicProps:_m,advancedEscapeHatchProps:Pm,events:$w,commands:Lw,capabilities:Ow},FV={version:1,layout:"tabbed",props:Mw,recommendedBasicProps:_m,advancedEscapeHatchProps:Pm,events:$w,commands:Lw,capabilities:Ow};export{vy as DEFAULT_SECTION_PLAYER_POLICIES,e_ as DEFAULT_TOOL_MODULE_LOADERS,Xa as SECTION_PLAYER_PUBLIC_EVENTS,jV as SPLITPANE_LAYOUT_CONTRACT,FV as TABBED_LAYOUT_CONTRACT,BV as VERTICAL_LAYOUT_CONTRACT,t_ as createPackagedToolRegistry,lW as isPreloadEnabled,ff as isTelemetryEnabled};