openlearn-next 0.2.9 → 0.3.2

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 (68) hide show
  1. package/cli.mjs +2 -0
  2. package/dist/assets/AdminDirectoryView-0XV86Ues.js +1 -0
  3. package/dist/assets/{BatchPickerModal-9BhmNM2R.js → BatchPickerModal-VYKUF5TC.js} +1 -1
  4. package/dist/assets/{ClassesView-DKScQDos.js → ClassesView-dDPegGIu.js} +2 -2
  5. package/dist/assets/CloudDriveModal-DiEEoAK5.js +1 -0
  6. package/dist/assets/ComputerLabView-BId0ZarM.js +1 -0
  7. package/dist/assets/CourseManagement-Dys0J3Xl.js +1 -0
  8. package/dist/assets/CourseWizardModal-DFZzYcbL.js +3 -0
  9. package/dist/assets/CoursewareHubPanel-LpUgjqbH.js +1 -0
  10. package/dist/assets/{Dashboard-BPxkmnvI.js → Dashboard-Bnxuy2BQ.js} +2 -2
  11. package/dist/assets/{ExportWeightModal-DSzySeqh.js → ExportWeightModal-DPriCEO9.js} +1 -1
  12. package/dist/assets/HelpTour-CHPIK2ae.js +1 -0
  13. package/dist/assets/{HelpView-CuNDka5n.js → HelpView-CTErIWbE.js} +3 -3
  14. package/dist/assets/ImportLessonsModal-BleM5Z-r.js +1 -0
  15. package/dist/assets/ImportModal-BTfia0Ah.js +1 -0
  16. package/dist/assets/InteractiveCoursewareViewer-DBCbyDmo.js +1 -0
  17. package/dist/assets/InteractiveWhiteboard-DnnYVSpP.js +78 -0
  18. package/dist/assets/{LazyCourseware-g7b8EXR_.js → LazyCourseware-BtliMSwD.js} +1 -1
  19. package/dist/assets/{LazyWhiteboard-BIepzrv9.js → LazyWhiteboard-D_U3t5Ft.js} +2 -2
  20. package/dist/assets/LessonEditorView-Lejw223i.js +1 -0
  21. package/dist/assets/LiveClassroomView-DW7gWs1X.js +1 -0
  22. package/dist/assets/{NotificationDetailModal-Bk1g_prI.js → NotificationDetailModal-me41YjnW.js} +1 -1
  23. package/dist/assets/{PluginView-C6s7Ltcy.js → PluginView-pof_3sut.js} +3 -3
  24. package/dist/assets/{ProcessLogsModal-B-PY780w.js → ProcessLogsModal-01S7zsw0.js} +1 -1
  25. package/dist/assets/{QuizGeneratorModal-DWH1zP0X.js → QuizGeneratorModal-UEVoYkB6.js} +1 -1
  26. package/dist/assets/StudentAssignmentView-BTfMYbmx.js +1 -0
  27. package/dist/assets/StudentLessonView-Bb5HQ6Kx.js +1 -0
  28. package/dist/assets/StudentPreviewModal-Bx86ogm7.js +1 -0
  29. package/dist/assets/StudentView-5bdEpjwh.js +2 -0
  30. package/dist/assets/SystemResourceLibraryModal-CRsieL1o.js +1 -0
  31. package/dist/assets/TeacherView-DCTHvypF.js +2 -0
  32. package/dist/assets/{TimetableView-BMsjwi-s.js → TimetableView-DJgOlGSf.js} +3 -3
  33. package/dist/assets/index-B-YxO39A.css +1 -0
  34. package/dist/assets/index-Bve0X_Y7.js +2 -0
  35. package/dist/assets/index-CerSuw-h.js +193 -0
  36. package/dist/assets/{index.es-DZ6UeYE-.js → index.es-CfxBkm_z.js} +1 -1
  37. package/dist/assets/{vendor-charts-B7ViBL9w.js → vendor-charts-CRXa4AlU.js} +1 -1
  38. package/dist/assets/vendor-content-CYR4BTuT.js +3 -0
  39. package/dist/assets/{vendor-icons-_c3xpwjZ.js → vendor-icons-Dq6MhgH9.js} +1 -1
  40. package/dist/assets/{vendor-pdf-CVyNPGVr.js → vendor-pdf-Cp-cYteE.js} +2 -2
  41. package/dist/assets/vendor-utils-BEhuP0Zq.js +1 -0
  42. package/dist/index.html +2 -2
  43. package/dist/server.cjs +994 -705
  44. package/package.json +10 -7
  45. package/dist/assets/AdminDirectoryView-CD7tW4mc.js +0 -1
  46. package/dist/assets/CloudDriveModal-cPtTMriS.js +0 -1
  47. package/dist/assets/ComputerLabView-B6-twB0u.js +0 -1
  48. package/dist/assets/CourseManagement-AoauIULq.js +0 -1
  49. package/dist/assets/CourseWizardModal-BOgLpLz7.js +0 -3
  50. package/dist/assets/CoursewareHubPanel-Cb1mAqHS.js +0 -1
  51. package/dist/assets/HelpTour-DwM9UBiA.js +0 -1
  52. package/dist/assets/ImportLessonsModal-Bwy2r-96.js +0 -1
  53. package/dist/assets/ImportModal-CmUt1YeX.js +0 -1
  54. package/dist/assets/InteractiveCoursewareViewer-DWnzq20c.js +0 -1
  55. package/dist/assets/InteractiveWhiteboard-C7JMplbp.js +0 -62
  56. package/dist/assets/LessonEditorView-C-mvYRUd.js +0 -1
  57. package/dist/assets/LiveClassroomView-CqRbWNis.js +0 -1
  58. package/dist/assets/StudentAssignmentView-CfTjeoAp.js +0 -1
  59. package/dist/assets/StudentLessonView-D2XvNGnW.js +0 -1
  60. package/dist/assets/StudentPreviewModal-BwXG6Cis.js +0 -1
  61. package/dist/assets/StudentView-DT-373QP.js +0 -2
  62. package/dist/assets/SystemResourceLibraryModal-BTL8rB0g.js +0 -1
  63. package/dist/assets/TeacherView-XdD-y67J.js +0 -2
  64. package/dist/assets/index-C5FKWIUq.js +0 -190
  65. package/dist/assets/index-CATki2cp.css +0 -1
  66. package/dist/assets/index-wdWIWwbg.js +0 -1
  67. package/dist/assets/vendor-content-V6uLfjnH.js +0 -3
  68. package/dist/assets/vendor-utils-4FcTwKPj.js +0 -1
@@ -0,0 +1,193 @@
1
+ import{R as et,r as p,j as l,g as Da,b as Ph,d as Fa,h as Ba,i as Th}from"./vendor-react-0Lg0vA-4.js";import{G as lo,S as Nh,U as $a,C as co,a as gn,L as uo,A as ho,b as Va,c as Ih,P as Dr,d as fo,D as po,X as At,e as Fr,f as ls,g as jh,h as Ah,T as zh,E as Ua,B as ai,R as Lh,i as _h,j as Rh,k as Oh,M as Mh,H as Dh,l as Fh,m as Bh,n as Wa,o as li,p as Br,q as $h,K as Vh,r as Uh,s as qn,t as Wh,u as ci,v as qh,w as ui,x as Hh,y as Gh,z as Qh,F as Jh,I as qa,J as Zh,N as Yh,V as Kh,O as Xh,Q as ef,W as ur,Y as tf,Z as nf,_ as sf,$ as rf,a0 as of}from"./vendor-icons-Dq6MhgH9.js";import{_ as Ie,E as af}from"./vendor-pdf-Cp-cYteE.js";import{d as Ha,e as qt,f as lf}from"./vendor-utils-BEhuP0Zq.js";import{i as dr,g as cf,s as Ga,a as di,b as Qa,c as mo,d as uf,e as df,f as hf,h as ff,r as pf,j as mf,k as Ja,l as gf,m as yf,n as xf,o as bf,S as wf,H as Sf,F as vt,p as vf,q as Cf,t as Za,u as ns,v as go,w as Xe,x as Ya,y as kf,z as yo,A as Ef,B as ss,C as $r,D as xo,E as Pf,G as Tf,I as bt,J as Nf,K as If,L as jf,M as bo,N as Af,O as zf,P as wo,Q as Lf,R as _f,T as Hn,U as Rf,V as Of,W as Ka,X as Mf,Y as Df}from"./vendor-motion-DjY2czvL.js";import{v as Ff}from"./vendor-pptx-B_NheIKl.js";import{R as Bf}from"./vendor-charts-CRXa4AlU.js";const $f=e=>{const t=e.split(/\r?\n/);if(t.length<2)return[];const n=t[0],s=[",",";"," "];let r=",",i=0;s.forEach(h=>{const g=n.split(h).length;g>i&&(i=g,r=h)});const o=h=>{const g=[];let x=!1,v="";for(let w=0;w<h.length;w++){const I=h[w];I==='"'?x=!x:I===r&&!x?(g.push(v.trim()),v=""):v+=I}return g.push(v.trim()),g},a=o(n).map(h=>h.toLowerCase().replace(/["'\r]/g,"").trim()),c=a.findIndex(h=>h.includes("name")||h.includes("student")||h.includes("姓名")||h.includes("学生")),u=a.findIndex(h=>h.includes("email")||h.includes("mail")||h.includes("邮箱")),d=c>=0?c:0,f=u>=0?u:1,m=[];for(let h=1;h<t.length;h++){if(!t[h].trim())continue;const g=o(t[h]),x=g[d]?g[d].replace(/["'\r]/g,"").trim():"",v=g[f]?g[f].replace(/["'\r]/g,"").trim():"";x&&m.push({name:x,email:v})}return m},So={zh:{migratableBadge:"可迁移",migrateToFormat:"迁移到新格式",migrationPromptHeading:"发现可迁移的旧格式插件",migrationPromptBody:"该插件使用旧格式运行。上传新格式 ZIP 包以完成迁移,迁移后旧版本可安全卸载。",zipParseError:"ZIP 文件解析失败,请确认文件包含有效的 manifest.json",workerActivationError:"插件在 Worker 环境中激活失败,请检查插件代码与浏览器兼容性",extensionLoadError:"扩展组件加载失败",retry:"重新加载",noExtensionPoints:"暂无已注册的扩展组件",dropZipHere:"拖拽 ZIP 文件到此处",zipFileHint:"仅支持 .zip 格式的插件包",analyzing:"分析中...",dragActive:"释放以上传",legacyTooltip:"该插件使用旧执行格式运行。新格式版本可能可用。",ready:"就绪",uploadZipPlugin:"上传并安装 ZIP 插件",agentTitle:"内核助手",agentSubtitle:"自主 Shell 控制器",agentIntro:"你好!我是你的教育系统 OS 内核助手。你可以让我“创建一节物理课并在白板上画一个圆”,我将通过底层总线为你构建。",placeholder:"例如:创建一节历史课并画一张地图...",dashboard:"系统总览",kernelRunning:"系统正常运行",lessons:"课程",noLessons:"暂无课程。请让助手创建一节课!",noContent:"无内容...",whiteboardCanvas:"白板画布",emptyWhiteboard:"白板为空",simulationError:"系统错误:执行 OS 命令失败。",executedCommands:"执行的命令:",switchLang:"Switch to English",plugins:"插件中心",uploadPlugin:"上传并安装插件",pluginSource:"扩展插件源码 (JS)",installPlugin:"验证并安装",installing:"安装中...",installedPlugins:"已运行插件",noPlugins:"未发现第三方插件",lessonContent:"课程教案与笔记",eventStream:"内核审计事件流",selectLesson:"请先在左侧选择一节课程",systemLogs:"系统日志",hideLogs:"隐藏日志",showLogs:"显示日志",approvals:"待审批高危操作",approve:"批准",reject:"拒绝",noApprovals:"暂无待审批命令",fileSystem:"虚拟文件系统",noFiles:"当前目录为空",processes:"进程管理",noProcesses:"没有正在运行的进程",processLogs:"查看日志",classes:"班级管理",students:"学生管理",noClasses:"暂无班级",noStudents:"暂无学生"},en:{migratableBadge:"Migratable",migrateToFormat:"Migrate to New Format",migrationPromptHeading:"Legacy Plugin Detected",migrationPromptBody:"This plugin runs in legacy mode. Upload a new-format ZIP package to migrate. The old version can be safely uninstalled afterwards.",zipParseError:"Failed to parse ZIP file. Ensure the package contains a valid manifest.json.",workerActivationError:"Plugin activation in Worker environment failed. Check plugin code and browser compatibility.",extensionLoadError:"Extension failed to load",retry:"Retry Load",noExtensionPoints:"No extension points registered",dropZipHere:"Drop ZIP file here",zipFileHint:".zip plugin packages only",analyzing:"Analyzing...",dragActive:"Release to upload",legacyTooltip:"This plugin uses the old execution format. A new-format version may be available.",ready:"Ready",uploadZipPlugin:"Upload & Install ZIP Plugin",agentTitle:"Kernel Agent",agentSubtitle:"Autonomous Shell Controller",agentIntro:'Hello! I am your Educational OS Kernel Agent. You can ask me to "create a physics lesson and draw a circle on its whiteboard" and I will use the Command Bus to build it.',placeholder:"e.g. Create a history lesson and draw a map...",dashboard:"OS Dashboard",kernelRunning:"Kernel Running",lessons:"Lessons",noLessons:"No lessons yet. Ask the Agent to create one!",noContent:"No content...",whiteboardCanvas:"Whiteboard Canvas",emptyWhiteboard:"Empty Whiteboard",simulationError:"Simulation Error: Failed to execute OS command.",executedCommands:"Executed Commands: ",switchLang:"切换到中文",plugins:"Plugin Center",uploadPlugin:"Upload & Install Plugin",pluginSource:"Extension Source Code (JS)",installPlugin:"Validate & Install",installing:"Installing...",installedPlugins:"Running Plugins",noPlugins:"No 3rd-party plugins found",lessonContent:"Lesson Content & Notes",eventStream:"Kernel Audit Event Stream",selectLesson:"Please select a lesson from the left",systemLogs:"System Logs",hideLogs:"Hide Logs",showLogs:"Show Logs",approvals:"Pending Approvals",approve:"Approve",reject:"Reject",noApprovals:"No pending commands",fileSystem:"Virtual File System",noFiles:"Directory is empty",processes:"Process Manager",noProcesses:"No active processes",processLogs:"View Logs",classes:"Classes",students:"Students",noClasses:"No classes found",noStudents:"No students found"}},Vf=et.memo(function({onLoginSuccess:t,lang:n}){const[s,r]=p.useState("teacher"),[i,o]=p.useState(null),[a,c]=p.useState(""),[u,d]=p.useState(""),[f,m]=p.useState(""),[h,g]=p.useState(!1),[x,v]=p.useState([]),[w,I]=p.useState(""),[S,P]=p.useState(""),[z,E]=p.useState(""),[L,_]=p.useState(""),[M,N]=p.useState(!1);p.useEffect(()=>{(async()=>{try{const F=await fetch("/api/students");if(F.ok){const j=await F.json();v(j),j.length>0&&I(j[0].id)}}catch(F){console.warn("Failed to fetch student roster for login selection:",F)}})()},[]),p.useEffect(()=>{(async()=>{try{const F=await fetch("/api/site-settings");if(F.ok){const j=await F.json();o(j)}}catch(F){console.warn("Failed to fetch site settings for login branding:",F)}})()},[]);const A=async D=>{if(D.preventDefault(),!a.trim()||!u){m(n==="zh"?"请输入完整的用户名和密码。":"Please fill in both key fields.");return}try{m(""),g(!0);const F=await fetch("/api/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({entrance:"teacher",username:a.trim(),password:u})});if(F.ok){const j=await F.json();t(j.session)}else{const j=await F.json();m(j.error||(n==="zh"?"用户名或密码不正确":"Invalid username or password"))}}catch{m(n==="zh"?"网络连接异常,请重试":"Network communication failure. Please try again.")}finally{g(!1)}},R=async D=>{D.preventDefault();const F=w||S.trim();if(!F){_(n==="zh"?"请选择或输入学号/学生标识。":"Please select or enter your Student ID.");return}if(!z.trim()){_(n==="zh"?"请输入个人密码或临时班级密码。":"Please enter your personal password or temporary class passcode.");return}try{_(""),N(!0);const j=await fetch("/api/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({entrance:"student",studentId:F,password:z.trim()})});if(j.ok){const T=await j.json();t(T.session)}else{const T=await j.json();_(T.error||(n==="zh"?"找不到该学生记录":"Student record not found"))}}catch{_(n==="zh"?"网络连接异常,请重试":"Network connection failure. Please try again.")}finally{N(!1)}};return l.jsxs("div",{className:"min-h-screen bg-slate-900 flex flex-col items-center justify-center p-4 relative overflow-hidden font-sans",id:"login_page_container",children:[l.jsx("div",{className:"absolute top-[-10%] left-[-10%] w-[40rem] h-[40rem] rounded-full bg-indigo-500/10 blur-3xl -z-10"}),l.jsx("div",{className:"absolute bottom-[-10%] right-[-10%] w-[35rem] h-[35rem] rounded-full bg-violet-500/10 blur-3xl -z-10"}),l.jsxs("div",{className:"w-full max-w-md bg-slate-950/85 backdrop-blur-md rounded-2xl border border-slate-800 shadow-2xl p-6 sm:p-8",id:"login_card",children:[l.jsxs("div",{className:"text-center mb-8",children:[i?.logoUrl?l.jsx("img",{src:i.logoUrl,alt:i.siteName||"logo",className:"inline-block h-16 w-16 object-contain mb-4 rounded-xl"}):l.jsx("div",{className:"inline-flex items-center justify-center p-3 bg-gradient-to-tr from-indigo-500 to-indigo-600 rounded-2xl shadow-lg border border-indigo-400/20 mb-4 text-white",children:l.jsx(lo,{size:32})}),l.jsxs("h1",{className:"text-2xl sm:text-3xl font-black text-white tracking-tight flex items-center justify-center gap-2",children:[i?.siteName||"OpenLearn Next"," ",l.jsx("span",{className:"text-indigo-400 font-medium text-xs bg-indigo-500/20 px-2 py-0.5 rounded-full border border-indigo-400/20",children:"V2.0"})]}),l.jsx("p",{className:"text-slate-400 text-xs sm:text-sm mt-2",children:i?.slogan||(n==="zh"?"下一代智能数字化学习系统":"Next-Generation Intelligent Digital Learning Platform")})]}),l.jsxs("div",{className:"flex bg-slate-900 p-1 rounded-xl border border-slate-800 gap-1 mb-6",children:[l.jsxs("button",{onClick:()=>r("teacher"),className:`flex-1 py-2.5 rounded-lg text-xs font-bold transition-all duration-200 flex items-center justify-center gap-2 focus:outline-none ${s==="teacher"?"bg-indigo-600 text-white shadow-md":"text-slate-400 hover:text-slate-200 hover:bg-slate-800/40"}`,children:[l.jsx(Nh,{size:14}),n==="zh"?"教师与管理端":"Teacher / Staff Portal"]}),l.jsxs("button",{onClick:()=>r("student"),className:`flex-1 py-2.5 rounded-lg text-xs font-bold transition-all duration-200 flex items-center justify-center gap-2 focus:outline-none ${s==="student"?"bg-indigo-600 text-white shadow-md":"text-slate-400 hover:text-slate-200 hover:bg-slate-800/40"}`,children:[l.jsx($a,{size:14}),n==="zh"?"学生自助端":"Student Self-Service"]})]}),s==="teacher"?l.jsxs("form",{onSubmit:A,className:"space-y-4",children:[f&&l.jsxs("div",{className:"p-3 bg-red-950/50 border border-red-800 text-red-300 text-xs rounded-xl flex items-center gap-2",children:[l.jsx(co,{size:15,className:"shrink-0"}),l.jsx("span",{children:f})]}),l.jsxs("div",{className:"space-y-1.5",children:[l.jsxs("label",{className:"text-xs font-medium text-slate-400 flex items-center gap-1.5",children:[l.jsx(gn,{size:13}),n==="zh"?"教工账户名 / username":"Staff Username"]}),l.jsx("input",{type:"text",value:a,onChange:D=>c(D.target.value),placeholder:n==="zh"?"输入教工账户名":"Enter staff username",className:"w-full bg-slate-900 border border-slate-800 focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500 rounded-xl text-xs sm:text-sm p-3 text-white outline-none placeholder-slate-500 transition-colors",required:!0})]}),l.jsxs("div",{className:"space-y-1.5",children:[l.jsxs("label",{className:"text-xs font-medium text-slate-400 flex items-center gap-1.5",children:[l.jsx(uo,{size:13}),n==="zh"?"输入登录密码 / password":"Access Password"]}),l.jsx("input",{type:"password",value:u,onChange:D=>d(D.target.value),placeholder:n==="zh"?"输入登录密码":"Enter access password",className:"w-full bg-slate-900 border border-slate-800 focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500 rounded-xl text-xs sm:text-sm p-3 text-white outline-none placeholder-slate-500 transition-colors",required:!0})]}),l.jsxs("button",{type:"submit",disabled:h,className:"w-full mt-6 bg-gradient-to-r from-indigo-600 to-violet-600 hover:from-indigo-500 hover:to-violet-500 disabled:opacity-50 text-white font-bold py-3 px-4 rounded-xl text-xs sm:text-sm flex items-center justify-center gap-2 transition-all duration-200 cursor-pointer shadow-lg shadow-indigo-600/20 active:scale-[0.98]",children:[l.jsx("span",{children:h?n==="zh"?"鉴权登录中...":"Authorizing...":n==="zh"?"安全验证登录":"Authorized Sign In"}),l.jsx(ho,{size:15})]})]}):l.jsxs("form",{onSubmit:R,className:"space-y-4",children:[L&&l.jsxs("div",{className:"p-3 bg-red-950/50 border border-red-800 text-red-300 text-xs rounded-xl flex items-center gap-2",children:[l.jsx(co,{size:15,className:"shrink-0"}),l.jsx("span",{children:L})]}),x.length>0?l.jsxs("div",{className:"space-y-1.5",children:[l.jsxs("label",{className:"text-xs font-medium text-slate-400 flex items-center gap-1.5",children:[l.jsx(lo,{size:14}),n==="zh"?"从学生花名册中快速选择":"Quick Access Student Select"]}),l.jsx("select",{value:w,onChange:D=>{I(D.target.value),P("")},className:"w-full bg-slate-900 border border-slate-800 focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500 rounded-xl text-xs sm:text-sm p-3 text-white outline-none transition-colors cursor-pointer",children:x.map(D=>l.jsxs("option",{value:D.id,children:[D.name," (",D.student_number||D.id,")"]},D.id))}),l.jsx("p",{className:"text-[10px] text-slate-500 font-medium",children:n==="zh"?"✨ 在沙盒调试中,你可以直接下拉选择已有的学生账户一键登录为该生。":"✨ Sandbox help: Quick select existing students on file to simulate as student."})]}):null,l.jsxs("div",{className:"relative flex py-2 items-center",children:[l.jsx("div",{className:"flex-grow border-t border-slate-850"}),l.jsx("span",{className:"flex-shrink mx-3 text-[10px] font-bold text-slate-500 uppercase tracking-wider",children:n==="zh"?"或手动输入学号":"Or input key manually"}),l.jsx("div",{className:"flex-grow border-t border-slate-850"})]}),l.jsxs("div",{className:"space-y-1.5",children:[l.jsxs("label",{className:"text-xs font-medium text-slate-400 flex items-center gap-1.5",children:[l.jsx(gn,{size:13}),n==="zh"?"学号 / Student ID":"Student Access Key"]}),l.jsx("input",{type:"text",value:S,onChange:D=>{P(D.target.value),I("")},placeholder:n==="zh"?"手工输入您的特有学号":"Enter specific numeric ID code",className:"w-full bg-slate-900 border border-slate-800 focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500 rounded-xl text-xs sm:text-sm p-3 text-white outline-none placeholder-slate-500 transition-colors"})]}),l.jsxs("div",{className:"space-y-1.5",children:[l.jsxs("label",{className:"text-xs font-medium text-slate-400 flex items-center gap-1.5",children:[l.jsx(uo,{size:13}),n==="zh"?"个人密码 / 临时班级密码":"Personal Password / Class Passcode"]}),l.jsx("input",{type:"password",required:!0,value:z,onChange:D=>E(D.target.value),placeholder:n==="zh"?"输入个人密码或临时班级密码":"Enter personal password or class passcode",className:"w-full bg-slate-900 border border-slate-800 focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500 rounded-xl text-xs sm:text-sm p-3 text-white outline-none placeholder-slate-500 transition-colors"})]}),l.jsxs("button",{type:"submit",disabled:M,className:"w-full mt-6 bg-gradient-to-r from-indigo-600 to-violet-600 hover:from-indigo-500 hover:to-violet-500 disabled:opacity-50 text-white font-bold py-3 px-4 rounded-xl text-xs sm:text-sm flex items-center justify-center gap-2 transition-all duration-200 cursor-pointer shadow-lg shadow-indigo-600/20 active:scale-[0.98]",children:[l.jsx("span",{children:M?n==="zh"?"正在连接学生终端...":"Entering Desk...":n==="zh"?"登录学生智慧桌面":"Login Interactive Desk"}),l.jsx(ho,{size:15})]})]})]})]})});function Uf({session:e,lang:t,onLogout:n,onProfile:s}){const[r,i]=p.useState(!1),o=p.useRef(null);p.useEffect(()=>{if(!r)return;const c=u=>{o.current&&!o.current.contains(u.target)&&i(!1)};return document.addEventListener("mousedown",c),()=>document.removeEventListener("mousedown",c)},[r]);const a=(c,u)=>t==="zh"?c:u;return l.jsxs("div",{className:"relative",ref:o,children:[l.jsxs("button",{type:"button",onClick:()=>i(c=>!c),"aria-haspopup":"menu","aria-expanded":r,title:e.name,className:"flex items-center gap-1 rounded-full p-1 hover:bg-gray-100 transition-colors cursor-pointer",children:[l.jsx("span",{className:"w-9 h-9 rounded-full bg-indigo-100 text-indigo-600 flex items-center justify-center shrink-0 overflow-hidden",children:e.avatar?l.jsx("img",{src:e.avatar,alt:e.name,className:"w-full h-full object-cover"}):l.jsx(gn,{size:20})}),l.jsx(Va,{size:14,className:`text-gray-400 transition-transform duration-200 ${r?"rotate-180":""}`})]}),r&&l.jsxs("div",{role:"menu",className:"absolute right-0 mt-2 w-52 bg-white border border-gray-200 shadow-lg rounded-xl z-50 overflow-hidden py-1",children:[l.jsxs("div",{className:"px-4 py-2 border-b border-gray-100",children:[l.jsx("p",{className:"text-sm font-semibold text-gray-800 truncate",title:e.name,children:e.name}),l.jsx("p",{className:"text-xs text-gray-400 truncate",children:e.username})]}),l.jsxs("button",{type:"button",role:"menuitem",onClick:()=>{i(!1),s()},className:"w-full flex items-center gap-2 px-4 py-2 text-sm text-gray-700 hover:bg-gray-50 transition-colors cursor-pointer",children:[l.jsx(gn,{size:16,className:"text-gray-400"}),a("个人资料","Profile")]}),l.jsxs("button",{type:"button",role:"menuitem",onClick:()=>{i(!1),n()},className:"w-full flex items-center gap-2 px-4 py-2 text-sm text-rose-600 hover:bg-rose-50 transition-colors cursor-pointer",children:[l.jsx(Ih,{size:16}),a("注销登录","Sign Out")]})]})]})}const Wf=[{id:"light",label:"浅色日间",description:"明亮通透,适合自然采光良好的日间课堂",previewBg:"#f8fafc",previewPrimary:"#4f46e5",category:"builtin"},{id:"dark",label:"暗夜极客",description:"深邃内敛,适合计算机房与夜间专注备课",previewBg:"#0b0f19",previewPrimary:"#6366f1",category:"builtin"},{id:"eyecare",label:"教学护眼",description:"柔和舒缓,防教室大屏眩光,减轻视觉疲劳",previewBg:"#f2f7f4",previewPrimary:"#2d6a4f",category:"builtin"},{id:"chalkboard",label:"经典黑板",description:"经典墨绿板书质感,沉浸式板书演练",previewBg:"#0e1713",previewPrimary:"#4caf50",category:"builtin"}],Gn={light:{"--bg-app":"#f8fafc","--bg-surface":"#ffffff","--bg-surface-secondary":"#f1f5f9","--bg-surface-elevated":"#ffffff","--border-theme":"#e2e8f0","--border-theme-subtle":"#f1f5f9","--text-main":"#0f172a","--text-muted":"#64748b","--color-primary":"#4f46e5","--color-primary-hover":"#4338ca"},dark:{"--bg-app":"#0b0f19","--bg-surface":"#111827","--bg-surface-secondary":"#1f2937","--bg-surface-elevated":"#1f2937","--border-theme":"#374151","--border-theme-subtle":"#1f2937","--text-main":"#f9fafb","--text-muted":"#9ca3af","--color-primary":"#6366f1","--color-primary-hover":"#4f46e5"},eyecare:{"--bg-app":"#f2f7f4","--bg-surface":"#ffffff","--bg-surface-secondary":"#e4eee8","--bg-surface-elevated":"#ffffff","--border-theme":"#cbe0d5","--border-theme-subtle":"#dbeef2","--text-main":"#143526","--text-muted":"#3d6350","--color-primary":"#2d6a4f","--color-primary-hover":"#1b4332"},chalkboard:{"--bg-app":"#0e1713","--bg-surface":"#15241e","--bg-surface-secondary":"#1b2f27","--bg-surface-elevated":"#1f382e","--border-theme":"#28473a","--border-theme-subtle":"#1b2f27","--text-main":"#e8f5e9","--text-muted":"#81c784","--color-primary":"#4caf50","--color-primary-hover":"#388e3c"}},hr="openlearn_theme",rn="openlearn_custom_themes",rs={};function hi(e){return rs[e]?rs[e]:e in Gn?Gn[e]:Gn.light}function fr(e){typeof document>"u"||document.documentElement.setAttribute("data-theme",e)}function qf(e,t){if(typeof document>"u")return;rs[e]=t;const n=`openlearn-custom-theme-${e}`;let s=document.getElementById(n);s||(s=document.createElement("style"),s.id=n,document.head.appendChild(s));const r=Object.entries(t).map(([i,o])=>` ${i}: ${o};`).join(`
2
+ `);s.textContent=`[data-theme="${e}"] {
3
+ ${r}
4
+ }`}function Hf(e){if(typeof document>"u")return;delete rs[e];const t=document.getElementById(`openlearn-custom-theme-${e}`);t&&t.parentNode&&t.parentNode.removeChild(t)}function pr(e){if(!(typeof window>"u"))try{setTimeout(async()=>{try{const{broadcastThemeToIframes:t}=await Ie(async()=>{const{broadcastThemeToIframes:n}=await Promise.resolve().then(()=>Nw);return{broadcastThemeToIframes:n}},void 0);t(e,hi(e))}catch{}},0)}catch{}}const cs=Ha((e,t)=>({theme:"light",availableThemes:[...Wf],initTheme:()=>{if(typeof window>"u")return;try{const r=localStorage.getItem(rn);if(r){const i=JSON.parse(r);Array.isArray(i)&&i.forEach(o=>{o&&o.spec&&o.spec.id&&t().registerTheme(o.spec,o.cssVariables)})}}catch{}const s=localStorage.getItem(hr)||"light";fr(s),e({theme:s}),pr(s)},setTheme:n=>{fr(n),typeof window<"u"&&localStorage.setItem(hr,n),e({theme:n}),pr(n)},registerTheme:(n,s)=>{s&&qf(n.id,s),e(r=>({availableThemes:[...r.availableThemes.filter(o=>o.id!==n.id),n]}))},unregisterTheme:n=>{Hf(n),e(s=>{const r=s.availableThemes.filter(o=>o.id!==n),i=s.theme===n?"light":s.theme;return s.theme===n&&(fr("light"),typeof window<"u"&&localStorage.setItem(hr,"light"),pr("light")),{availableThemes:r,theme:i}})},saveCustomTheme:(n,s)=>{if(t().registerTheme(n,s),typeof window<"u")try{const r=localStorage.getItem(rn);let i=r?JSON.parse(r):[];Array.isArray(i)||(i=[]),i=i.filter(o=>o.spec.id!==n.id),i.push({spec:n,cssVariables:s}),localStorage.setItem(rn,JSON.stringify(i))}catch{}t().setTheme(n.id)},deleteCustomTheme:n=>{if(typeof window<"u")try{const s=localStorage.getItem(rn);if(s){let r=JSON.parse(s);Array.isArray(r)&&(r=r.filter(i=>i.spec.id!==n),localStorage.setItem(rn,JSON.stringify(r)))}}catch{}t().unregisterTheme(n)}})),Gf=[{id:"sapphire-classic",label:"高雅墨蓝",description:"深海午夜蓝灰与经典宝石蓝,适合沉浸式研究与高对比度投影",tokens:{"--bg-app":"#0d131f","--bg-surface":"#161f30","--bg-surface-secondary":"#1f2c42","--bg-surface-elevated":"#24334d","--border-theme":"#2e3f5b","--border-theme-subtle":"#1f2c42","--text-main":"#f1f5f9","--text-muted":"#94a3b8","--color-primary":"#3b82f6","--color-primary-hover":"#2563eb"}},{id:"sakura-dusk",label:"暮樱柔粉",description:"柔和日系樱花与温暖象牙白,适合美育、艺术与温馨研讨课堂",tokens:{"--bg-app":"#fff9fa","--bg-surface":"#ffffff","--bg-surface-secondary":"#fceef1","--bg-surface-elevated":"#ffffff","--border-theme":"#f5d5db","--border-theme-subtle":"#fae8eb","--text-main":"#3f2d33","--text-muted":"#8a6d76","--color-primary":"#f43f5e","--color-primary-hover":"#e11d48"}},{id:"autumn-amber",label:"复古秋叶",description:"温暖金秋落叶色调与复古羊皮纸质感,适合文科通识与阅读研讨",tokens:{"--bg-app":"#fdfaf6","--bg-surface":"#ffffff","--bg-surface-secondary":"#f5eee6","--bg-surface-elevated":"#ffffff","--border-theme":"#e6d7c3","--border-theme-subtle":"#ede3d5","--text-main":"#2d241e","--text-muted":"#7c6a59","--color-primary":"#d97706","--color-primary-hover":"#b45309"}},{id:"deep-sea-cyber",label:"深海极客",description:"赛博暗黑青绿冷光,极高现代感与未来科技探索质感",tokens:{"--bg-app":"#091014","--bg-surface":"#0f1a20","--bg-surface-secondary":"#16262e","--bg-surface-elevated":"#1d333e","--border-theme":"#25414e","--border-theme-subtle":"#16262e","--text-main":"#e0f2fe","--text-muted":"#7dd3fc","--color-primary":"#06b6d4","--color-primary-hover":"#0891b2"}}],vo={...Gn.light};function Qf({isOpen:e,onClose:t,lang:n="zh"}){const{availableThemes:s,saveCustomTheme:r,deleteCustomTheme:i}=cs(),o=p.useId(),[a,c]=p.useState("custom-mytheme"),[u,d]=p.useState("我的专属主题"),[f,m]=p.useState("自定义教学调色板配置"),[h,g]=p.useState({...vo}),[x,v]=p.useState("none"),[w,I]=p.useState(""),[S,P]=p.useState(!1),[z,E]=p.useState(null);if(!e)return null;const L=s.filter(k=>k.category==="custom"),_=k=>{E(k),setTimeout(()=>E(null),3e3)},M=k=>{c(k.id),d(k.label),m(k.description),g({...k.tokens}),_(`已载入预设: ${k.label}`)},N=k=>{c(k.id),d(k.label),m(k.description);const B=hi(k.id);B&&Object.keys(B).length>0&&g({...B}),_(`已载入自定义主题: ${k.label}`)},A=(k,B)=>{g(y=>({...y,[k]:B}))},R=()=>{const k=a.trim().toLowerCase().replace(/[^a-z0-9_-]/g,"-");if(!k){alert("请输入有效的主题标识 (ID)");return}const B={id:k,label:u.trim()||"未命名主题",description:f.trim()||"自定义主题",previewBg:h["--bg-app"]||"#ffffff",previewPrimary:h["--color-primary"]||"#4f46e5",category:"custom"};r(B,h),_(`主题「${B.label}」已保存并成功激活!`)},D=()=>{I(JSON.stringify({version:"1.0",id:a,label:u,description:f,tokens:h},null,2)),v("export")},F=()=>{I(""),v("import")},j=()=>{try{const k=JSON.parse(w);if(!k.tokens||typeof k.tokens!="object")throw new Error("缺少合法的 tokens 字段");k.id&&c(k.id),k.label&&d(k.label),k.description&&m(k.description),g(B=>({...B,...k.tokens})),v("none"),_("主题配置导入成功!")}catch(k){alert(`导入失败: ${k.message||"JSON 格式解析错误"}`)}},T=()=>{navigator.clipboard.writeText(w),P(!0),setTimeout(()=>P(!1),2e3)},$=[{key:"--color-primary",labelZh:"核心主色",labelEn:"Primary Brand Color",desc:"按钮高亮、焦点描边与重点图标"},{key:"--color-primary-hover",labelZh:"主色悬浮",labelEn:"Primary Hover",desc:"按钮悬停交互色"},{key:"--bg-app",labelZh:"全局底色",labelEn:"App Background",desc:"页面整体底衬颜色"},{key:"--bg-surface",labelZh:"卡片底色",labelEn:"Surface Background",desc:"白板卡片、浮层与侧边栏底色"},{key:"--bg-surface-secondary",labelZh:"次级底色",labelEn:"Secondary Surface",desc:"表格斑马纹、标签与次级面板"},{key:"--bg-surface-elevated",labelZh:"浮层底色",labelEn:"Elevated Surface",desc:"弹窗与下拉菜单浮动卡片"},{key:"--border-theme",labelZh:"主边框色",labelEn:"Border Color",desc:"卡片外边框、网格分割线"},{key:"--border-theme-subtle",labelZh:"弱化边框",labelEn:"Subtle Border",desc:"细微内部分割线"},{key:"--text-main",labelZh:"主文本色",labelEn:"Main Text",desc:"正文文字、标题"},{key:"--text-muted",labelZh:"弱化文本",labelEn:"Muted Text",desc:"副标题、辅助信息与提示说明"}];return l.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center p-4 sm:p-6 bg-black/60 backdrop-blur-xs animate-in fade-in duration-150",children:l.jsxs("div",{className:"bg-surface text-main border border-theme rounded-2xl shadow-2xl w-full max-w-6xl h-[92vh] max-h-[900px] flex flex-col overflow-hidden relative",children:[l.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-theme shrink-0 bg-surface",children:[l.jsxs("div",{className:"flex items-center gap-3",children:[l.jsx("div",{className:"p-2 bg-primary-theme/10 rounded-xl text-primary-theme",children:l.jsx(Dr,{size:22})}),l.jsxs("div",{children:[l.jsxs("h2",{className:"text-lg font-bold flex items-center gap-2 text-main",children:[n==="zh"?"主题可视化设计器":"Theme Visual Designer",l.jsx("span",{className:"text-xs px-2 py-0.5 rounded-full bg-primary-theme/10 text-primary-theme font-medium",children:"v0.3.0"})]}),l.jsx("p",{className:"text-xs text-muted mt-0.5",children:n==="zh"?"自定义课堂交互色盘,支持一键载入创意预设、实时拟真沙箱预览与微前端自动同步":"Customize learning palettes with live previews, creative presets, and micro-frontend sync"})]})]}),l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsxs("button",{onClick:F,className:"px-3 py-1.5 rounded-lg border border-theme text-xs font-medium hover:bg-surface-secondary text-main transition-colors flex items-center gap-1.5 cursor-pointer",title:"导入 JSON",children:[l.jsx(fo,{size:14}),n==="zh"?"导入配置":"Import"]}),l.jsxs("button",{onClick:D,className:"px-3 py-1.5 rounded-lg border border-theme text-xs font-medium hover:bg-surface-secondary text-main transition-colors flex items-center gap-1.5 cursor-pointer",title:"导出 JSON",children:[l.jsx(po,{size:14}),n==="zh"?"导出配置":"Export"]}),l.jsx("button",{onClick:t,className:"p-2 rounded-lg text-muted hover:text-main hover:bg-surface-secondary transition-colors cursor-pointer ml-1","aria-label":"Close",children:l.jsx(At,{size:18})})]})]}),z&&l.jsxs("div",{className:"absolute top-18 left-1/2 -translate-x-1/2 z-50 bg-primary-theme text-white px-4 py-2 rounded-xl shadow-lg text-xs font-medium flex items-center gap-2 animate-in fade-in slide-in-from-top-2",children:[l.jsx(Fr,{size:14}),z]}),l.jsxs("div",{className:"flex-1 flex flex-col md:flex-row overflow-hidden",children:[l.jsxs("div",{className:"w-full md:w-1/2 border-r border-theme overflow-y-auto p-6 space-y-6",children:[l.jsxs("section",{className:"space-y-3",children:[l.jsxs("div",{className:"flex items-center justify-between",children:[l.jsxs("label",{className:"text-xs font-bold uppercase tracking-wider text-muted flex items-center gap-1.5",children:[l.jsx(ls,{size:14,className:"text-amber-500"}),n==="zh"?"创意预设配色":"Creative Presets"]}),l.jsx("span",{className:"text-2xs text-muted",children:"一键填入调色板"})]}),l.jsx("div",{className:"grid grid-cols-2 gap-2.5",children:Gf.map(k=>l.jsxs("button",{onClick:()=>M(k),className:"flex flex-col p-3 rounded-xl border border-theme hover:border-primary-theme/50 hover:bg-surface-secondary text-left transition-all cursor-pointer group relative overflow-hidden",children:[l.jsxs("div",{className:"flex items-center justify-between w-full",children:[l.jsxs("div",{className:"font-semibold text-xs text-main flex items-center gap-2",children:[l.jsx("span",{className:"w-3 h-3 rounded-full border border-black/10 shrink-0",style:{backgroundColor:k.tokens["--color-primary"]}}),k.label]}),l.jsxs("div",{className:"flex items-center gap-1",children:[l.jsx("span",{className:"w-2.5 h-2.5 rounded-xs",style:{backgroundColor:k.tokens["--bg-app"]}}),l.jsx("span",{className:"w-2.5 h-2.5 rounded-xs",style:{backgroundColor:k.tokens["--bg-surface"]}})]})]}),l.jsx("p",{className:"text-3xs text-muted mt-1.5 line-clamp-2 leading-relaxed opacity-85",children:k.description})]},k.id))})]}),l.jsxs("section",{className:"space-y-3 pt-2 border-t border-theme-subtle",children:[l.jsxs("label",{className:"text-xs font-bold uppercase tracking-wider text-muted flex items-center gap-1.5",children:[l.jsx(jh,{size:14,className:"text-primary-theme"}),n==="zh"?"主题基础信息":"Theme Metadata"]}),l.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[l.jsxs("div",{children:[l.jsx("label",{htmlFor:`${o}-themeId`,className:"block text-2xs font-medium text-muted mb-1",children:"主题标识 (ID)"}),l.jsx("input",{id:`${o}-themeId`,type:"text",value:a,onChange:k=>c(k.target.value),placeholder:"custom-mytheme",className:"w-full px-3 py-1.5 text-xs rounded-lg border border-theme bg-surface-secondary text-main focus:outline-none focus:ring-1 focus:ring-primary-theme"})]}),l.jsxs("div",{children:[l.jsx("label",{htmlFor:`${o}-label`,className:"block text-2xs font-medium text-muted mb-1",children:"主题名称"}),l.jsx("input",{id:`${o}-label`,type:"text",value:u,onChange:k=>d(k.target.value),placeholder:"我的专属主题",className:"w-full px-3 py-1.5 text-xs rounded-lg border border-theme bg-surface-secondary text-main focus:outline-none focus:ring-1 focus:ring-primary-theme"})]})]}),l.jsxs("div",{children:[l.jsx("label",{htmlFor:`${o}-description`,className:"block text-2xs font-medium text-muted mb-1",children:"主题描述"}),l.jsx("input",{id:`${o}-description`,type:"text",value:f,onChange:k=>m(k.target.value),placeholder:"针对特定课堂采光与演示场景优化",className:"w-full px-3 py-1.5 text-xs rounded-lg border border-theme bg-surface-secondary text-main focus:outline-none focus:ring-1 focus:ring-primary-theme"})]})]}),l.jsxs("section",{className:"space-y-3 pt-2 border-t border-theme-subtle",children:[l.jsxs("label",{className:"text-xs font-bold uppercase tracking-wider text-muted flex items-center gap-1.5",children:[l.jsx(Dr,{size:14,className:"text-primary-theme"}),n==="zh"?"色彩变量调节 (Design Tokens)":"CSS Variables Token Tuning"]}),l.jsx("div",{className:"space-y-2.5",children:$.map(k=>{const B=h[k.key]||"#000000";return l.jsxs("div",{className:"flex items-center justify-between p-2.5 rounded-xl border border-theme hover:bg-surface-secondary/40 transition-colors",children:[l.jsxs("div",{className:"flex-1 min-w-0 pr-3",children:[l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("span",{className:"text-xs font-medium text-main",children:k.labelZh}),l.jsx("span",{className:"text-3xs font-mono text-muted bg-surface-secondary px-1.5 py-0.5 rounded",children:k.key})]}),l.jsx("p",{className:"text-3xs text-muted mt-0.5",children:k.desc})]}),l.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[l.jsx("div",{className:"relative flex items-center",children:l.jsx("input",{type:"color",value:B.startsWith("#")&&B.length===7?B:"#4f46e5",onChange:y=>A(k.key,y.target.value),className:"w-8 h-8 rounded-lg cursor-pointer border border-theme p-0.5 bg-surface",title:"打开系统拾色器"})}),l.jsx("input",{type:"text",value:B,onChange:y=>A(k.key,y.target.value),className:"w-20 px-2 py-1 text-xs font-mono rounded-lg border border-theme bg-surface text-main text-center focus:outline-none focus:ring-1 focus:ring-primary-theme"})]})]},k.key)})})]}),L.length>0&&l.jsxs("section",{className:"space-y-3 pt-2 border-t border-theme-subtle",children:[l.jsxs("label",{className:"text-xs font-bold uppercase tracking-wider text-muted flex items-center gap-1.5",children:[l.jsx(Ah,{size:14,className:"text-primary-theme"}),n==="zh"?"已创建的自定义主题":"Saved Custom Themes"]}),l.jsx("div",{className:"space-y-2",children:L.map(k=>l.jsxs("div",{className:"flex items-center justify-between p-2.5 rounded-xl border border-theme bg-surface-secondary/30",children:[l.jsxs("div",{className:"flex items-center gap-2.5 min-w-0",children:[l.jsx("span",{className:"w-3.5 h-3.5 rounded-full border border-black/10 shrink-0",style:{backgroundColor:k.previewPrimary}}),l.jsxs("div",{className:"truncate",children:[l.jsx("div",{className:"text-xs font-semibold text-main truncate",children:k.label}),l.jsx("div",{className:"text-3xs text-muted truncate",children:k.description})]})]}),l.jsxs("div",{className:"flex items-center gap-1.5 shrink-0 ml-2",children:[l.jsx("button",{onClick:()=>N(k),className:"px-2 py-1 text-2xs rounded-md bg-surface border border-theme hover:bg-surface-secondary text-main transition-colors cursor-pointer",children:"编辑"}),l.jsx("button",{onClick:()=>{confirm(`确定删除自定义主题「${k.label}」吗?`)&&(i(k.id),_(`已删除主题「${k.label}」`))},className:"p-1 text-muted hover:text-red-500 rounded-md transition-colors cursor-pointer",title:"删除",children:l.jsx(zh,{size:13})})]})]},k.id))})]})]}),l.jsxs("div",{className:"w-full md:w-1/2 flex flex-col p-6 bg-surface-secondary/30 overflow-y-auto",children:[l.jsxs("div",{className:"flex items-center justify-between mb-3 shrink-0",children:[l.jsxs("div",{className:"flex items-center gap-1.5 text-xs font-bold uppercase tracking-wider text-muted",children:[l.jsx(Ua,{size:14,className:"text-primary-theme"}),n==="zh"?"拟真沙盒视口 (Live Sandbox)":"Live Sandbox Preview"]}),l.jsxs("span",{className:"text-2xs text-muted font-mono",children:["当前预览: ",u," (",a,")"]})]}),l.jsxs("div",{className:"flex-1 rounded-2xl border shadow-inner overflow-hidden flex flex-col transition-colors duration-200",style:{backgroundColor:h["--bg-app"]||"#f8fafc",borderColor:h["--border-theme"]||"#e2e8f0",color:h["--text-main"]||"#0f172a"},children:[l.jsxs("div",{className:"h-12 border-b px-4 flex items-center justify-between shrink-0",style:{backgroundColor:h["--bg-surface"]||"#ffffff",borderColor:h["--border-theme"]||"#e2e8f0"},children:[l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("div",{className:"w-6 h-6 rounded-lg flex items-center justify-center font-bold text-white text-xs",style:{backgroundColor:h["--color-primary"]||"#4f46e5"},children:"OL"}),l.jsx("span",{className:"font-bold text-xs",style:{color:h["--text-main"]},children:"OpenLearn V2"})]}),l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("div",{className:"text-3xs px-2 py-0.5 rounded-md font-mono",style:{backgroundColor:h["--bg-surface-secondary"]||"#f1f5f9",color:h["--text-muted"]||"#64748b"},children:"10:30:00"}),l.jsx("div",{className:"w-6 h-6 rounded-full flex items-center justify-center text-3xs font-bold text-white",style:{backgroundColor:h["--color-primary"]||"#4f46e5"},children:"T"})]})]}),l.jsxs("div",{className:"p-4 space-y-4 flex-1 overflow-y-auto",children:[l.jsxs("div",{className:"p-4 rounded-xl border shadow-xs space-y-3",style:{backgroundColor:h["--bg-surface"]||"#ffffff",borderColor:h["--border-theme"]||"#e2e8f0"},children:[l.jsxs("div",{className:"flex items-start justify-between",children:[l.jsxs("div",{children:[l.jsx("h4",{className:"font-bold text-sm",style:{color:h["--text-main"]},children:"高中物理实验探究:机械能守恒定律"}),l.jsx("p",{className:"text-xs mt-1",style:{color:h["--text-muted"]},children:"DIS 光电门传感器毫秒级数据回传与曲线拟合分析"})]}),l.jsx("span",{className:"text-3xs px-2 py-0.5 rounded-full font-medium",style:{backgroundColor:h["--bg-surface-secondary"],color:h["--color-primary"],border:`1px solid ${h["--border-theme"]}`},children:"进行中"})]}),l.jsxs("div",{className:"grid grid-cols-3 gap-2 pt-1",children:[l.jsxs("div",{className:"p-2 rounded-lg",style:{backgroundColor:h["--bg-surface-secondary"]},children:[l.jsx("div",{className:"text-3xs",style:{color:h["--text-muted"]},children:"光电门测速 (v)"}),l.jsx("div",{className:"text-sm font-bold font-mono mt-0.5",style:{color:h["--text-main"]},children:"2.43 m/s"})]}),l.jsxs("div",{className:"p-2 rounded-lg",style:{backgroundColor:h["--bg-surface-secondary"]},children:[l.jsx("div",{className:"text-3xs",style:{color:h["--text-muted"]},children:"动能增量 (ΔEk)"}),l.jsx("div",{className:"text-sm font-bold font-mono mt-0.5",style:{color:h["--color-primary"]},children:"0.589 J"})]}),l.jsxs("div",{className:"p-2 rounded-lg",style:{backgroundColor:h["--bg-surface-secondary"]},children:[l.jsx("div",{className:"text-3xs",style:{color:h["--text-muted"]},children:"误差率 (Err)"}),l.jsx("div",{className:"text-sm font-bold font-mono mt-0.5",style:{color:h["--text-main"]},children:"0.84 %"})]})]}),l.jsxs("div",{className:"flex items-center gap-2 pt-2",children:[l.jsx("button",{className:"px-3 py-1.5 rounded-lg text-xs font-medium text-white shadow-xs transition-opacity hover:opacity-90 cursor-pointer",style:{backgroundColor:h["--color-primary"]||"#4f46e5"},children:"开始数据采集"}),l.jsx("button",{className:"px-3 py-1.5 rounded-lg text-xs font-medium border transition-colors cursor-pointer",style:{backgroundColor:h["--bg-surface-elevated"]||"#ffffff",borderColor:h["--border-theme"]||"#e2e8f0",color:h["--text-main"]||"#0f172a"},children:"重置实验"}),l.jsx("button",{className:"px-2 py-1.5 rounded-lg text-xs transition-colors cursor-pointer",style:{color:h["--text-muted"]},children:"查看教案"})]})]}),l.jsxs("div",{className:"p-3 rounded-xl border space-y-2",style:{backgroundColor:h["--bg-surface-elevated"]||"#ffffff",borderColor:h["--border-theme-subtle"]||"#f1f5f9"},children:[l.jsxs("div",{className:"flex items-center justify-between",children:[l.jsx("span",{className:"text-2xs font-semibold",style:{color:h["--text-main"]},children:"互动白板区域 (Whiteboard Canvas)"}),l.jsx("span",{className:"text-3xs font-mono",style:{color:h["--text-muted"]},children:"60 FPS"})]}),l.jsxs("div",{className:"h-28 rounded-lg border border-dashed flex items-center justify-center p-3 relative overflow-hidden",style:{backgroundColor:h["--bg-app"],borderColor:h["--border-theme"]},children:[l.jsx("div",{className:"w-12 h-12 rounded-xl flex items-center justify-center text-white font-bold shadow-md transform -rotate-6",style:{backgroundColor:h["--color-primary"]},children:l.jsx(ai,{size:20})}),l.jsx("div",{className:"absolute bottom-2 right-2 text-3xs font-mono px-1.5 py-0.5 rounded border",style:{backgroundColor:h["--bg-surface"],borderColor:h["--border-theme"],color:h["--text-muted"]},children:"iframe Bridge Sync Ready"})]})]})]})]})]})]}),l.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-t border-theme shrink-0 bg-surface",children:[l.jsx("div",{className:"flex items-center gap-2",children:l.jsxs("button",{onClick:()=>{g({...vo}),_("已重置为系统默认调色板")},className:"px-3 py-1.5 rounded-lg border border-theme text-xs font-medium hover:bg-surface-secondary text-main transition-colors flex items-center gap-1.5 cursor-pointer",children:[l.jsx(Lh,{size:14}),n==="zh"?"重置默认":"Reset Defaults"]})}),l.jsxs("div",{className:"flex items-center gap-3",children:[l.jsx("button",{onClick:t,className:"px-4 py-2 rounded-xl border border-theme text-xs font-medium hover:bg-surface-secondary text-main transition-colors cursor-pointer",children:n==="zh"?"关闭":"Close"}),l.jsxs("button",{onClick:R,className:"px-5 py-2 rounded-xl bg-primary-theme text-white text-xs font-semibold shadow-sm hover:opacity-95 transition-opacity flex items-center gap-1.5 cursor-pointer",children:[l.jsx(_h,{size:15}),n==="zh"?"保存并激活主题":"Save & Activate Theme"]})]})]}),x!=="none"&&l.jsx("div",{className:"absolute inset-0 bg-black/60 backdrop-blur-xs flex items-center justify-center p-6 z-50 animate-in fade-in duration-100",children:l.jsxs("div",{className:"bg-surface border border-theme rounded-2xl p-5 w-full max-w-lg shadow-2xl space-y-4",children:[l.jsxs("div",{className:"flex items-center justify-between",children:[l.jsx("h3",{className:"font-bold text-sm text-main flex items-center gap-2",children:x==="export"?l.jsxs(l.Fragment,{children:[l.jsx(po,{size:16,className:"text-primary-theme"}),n==="zh"?"导出主题配置 JSON":"Export Theme JSON"]}):l.jsxs(l.Fragment,{children:[l.jsx(fo,{size:16,className:"text-primary-theme"}),n==="zh"?"导入主题配置 JSON":"Import Theme JSON"]})}),l.jsx("button",{onClick:()=>v("none"),className:"p-1 rounded-md text-muted hover:text-main cursor-pointer",children:l.jsx(At,{size:16})})]}),l.jsx("div",{children:l.jsx("textarea",{value:w,readOnly:x==="export",onChange:k=>I(k.target.value),placeholder:x==="import"?"请在此粘贴主题导出的 JSON 字符串...":"",rows:10,className:"w-full p-3 font-mono text-2xs rounded-xl border border-theme bg-surface-secondary text-main focus:outline-none focus:ring-1 focus:ring-primary-theme resize-none"})}),l.jsx("div",{className:"flex items-center justify-end gap-2",children:x==="export"?l.jsx(l.Fragment,{children:l.jsxs("button",{onClick:T,className:"px-4 py-1.5 rounded-lg bg-primary-theme text-white text-xs font-medium flex items-center gap-1.5 cursor-pointer",children:[S?l.jsx(Fr,{size:14}):l.jsx(Rh,{size:14}),S?n==="zh"?"已复制":"Copied":n==="zh"?"复制到剪贴板":"Copy"]})}):l.jsxs(l.Fragment,{children:[l.jsx("button",{onClick:()=>v("none"),className:"px-3 py-1.5 rounded-lg border border-theme text-xs font-medium hover:bg-surface-secondary text-main cursor-pointer",children:n==="zh"?"取消":"Cancel"}),l.jsx("button",{onClick:j,className:"px-4 py-1.5 rounded-lg bg-primary-theme text-white text-xs font-medium cursor-pointer",children:n==="zh"?"解析并导入":"Parse & Import"})]})})]})})]})})}function Jf({lang:e="zh"}){const[t,n]=p.useState(!1),[s,r]=p.useState(!1),i=p.useRef(null),{theme:o,availableThemes:a,setTheme:c}=cs();p.useEffect(()=>{function d(f){i.current&&!i.current.contains(f.target)&&n(!1)}return t&&document.addEventListener("mousedown",d),()=>{document.removeEventListener("mousedown",d)}},[t]);const u=d=>{switch(d){case"dark":return l.jsx(Mh,{size:16,className:"text-indigo-400"});case"eyecare":return l.jsx(Ua,{size:16,className:"text-emerald-500"});case"chalkboard":return l.jsx(Dr,{size:16,className:"text-green-400"});case"light":default:return l.jsx(Oh,{size:16,className:"text-amber-500"})}};return l.jsxs(l.Fragment,{children:[l.jsxs("div",{className:"relative",ref:i,children:[l.jsx("button",{onClick:()=>n(!t),title:e==="zh"?"切换教学界面主题":"Switch Theme",className:"p-2 hover:bg-surface-secondary text-main transition-colors bg-surface rounded-lg border border-theme shadow-3xs flex items-center justify-center shrink-0 cursor-pointer","aria-label":"Theme selector",children:u(o)}),t&&l.jsxs("div",{className:"absolute right-0 mt-2 w-64 rounded-xl border border-theme bg-surface shadow-xl z-50 p-2 overflow-hidden animate-in fade-in zoom-in-95 duration-100",children:[l.jsxs("div",{className:"px-3 py-2 border-b border-theme-subtle mb-1",children:[l.jsx("div",{className:"text-xs font-semibold text-main uppercase tracking-wider",children:e==="zh"?"界面主题模式":"Interface Theme"}),l.jsx("div",{className:"text-2xs text-muted mt-0.5",children:e==="zh"?"针对不同教学采光与场景优化":"Optimized for diverse lighting"})]}),l.jsx("div",{className:"space-y-1",children:a.map(d=>{const f=o===d.id;return l.jsxs("button",{onClick:()=>{c(d.id),n(!1)},className:`w-full flex items-center justify-between px-3 py-2 rounded-lg text-left text-xs transition-all cursor-pointer ${f?"bg-surface-secondary text-main font-semibold shadow-xs":"text-muted hover:bg-surface-secondary hover:text-main"}`,children:[l.jsxs("div",{className:"flex items-center gap-2.5",children:[l.jsx("span",{className:"w-3.5 h-3.5 rounded-full border border-black/10 dark:border-white/20 shrink-0 shadow-inner",style:{backgroundColor:d.previewPrimary}}),l.jsxs("div",{children:[l.jsx("div",{className:"font-medium text-main leading-none",children:d.label}),l.jsx("div",{className:"text-3xs text-muted mt-1 leading-tight opacity-80",children:d.description})]})]}),f&&l.jsx(Fr,{size:14,className:"text-primary-theme shrink-0"})]},d.id)})}),l.jsx("div",{className:"pt-2 mt-1 border-t border-theme-subtle",children:l.jsxs("button",{onClick:()=>{n(!1),r(!0)},className:"w-full flex items-center gap-2 px-3 py-2 rounded-lg text-xs font-medium text-primary-theme hover:bg-primary-theme/10 transition-colors cursor-pointer",children:[l.jsx(ls,{size:14}),l.jsx("span",{children:e==="zh"?"🎨 自定义主题设计器...":"🎨 Theme Designer..."})]})})]})]}),l.jsx(Qf,{isOpen:s,onClose:()=>r(!1),lang:e})]})}function Zf(e){const{activeRole:t,lang:n,teacherTab:s,studentViewStatus:r,session:i,activeStudentId:o,students:a,studentDashboardData:c,isNotificationsOpen:u,studentNotifications:d,unreadNotifications:f,readNotifications:m,dbConnected:h,dbStatus:g,siteInfo:x,setActiveStudentId:v,setReadNotifications:w,setIsSystemResourceLibraryOpen:I,setProfileOpen:S,setTeacherTab:P,setStudentViewStatus:z,setIsNotificationsOpen:E,setSelectedNotificationForModal:L,handleLogout:_,toggleLanguage:M}=e;return l.jsxs("header",{className:"h-16 border-b border-theme bg-surface text-main flex items-center px-6 justify-between shrink-0 shadow-sm relative z-20 transition-colors duration-200",children:[l.jsxs("div",{className:"flex items-center gap-4 sm:gap-6",children:[l.jsxs("button",{onClick:()=>{t==="teacher"?P("dashboard"):t==="student"&&z("dashboard")},className:"flex items-center gap-2.5 shrink-0 hover:opacity-80 transition-opacity cursor-pointer",title:n==="zh"?"返回系统总览":"Back to Dashboard",children:[x.logoUrl?l.jsx("img",{src:x.logoUrl,alt:"site logo",className:"h-8 w-8 object-contain rounded-lg shrink-0"}):l.jsx("div",{className:"h-8 w-8 rounded-lg bg-gradient-to-tr from-indigo-600 to-indigo-700 flex items-center justify-center text-white font-black text-sm shadow-xs shrink-0",children:"OL"}),l.jsxs("div",{className:"flex items-baseline gap-2",children:[l.jsx("span",{className:"text-base font-black text-slate-900 tracking-tight",children:x.siteName||"OpenLearn Next"}),l.jsxs("span",{className:"text-[10px] font-medium text-slate-400 tracking-tight",children:["v","0.3.2"]}),x.slogan&&l.jsx("span",{className:"hidden md:inline text-xs text-slate-400 font-normal truncate max-w-[200px]",children:x.slogan})]})]}),l.jsxs("button",{onClick:()=>{t==="teacher"?P("dashboard"):t==="student"&&z("dashboard")},className:`flex items-center gap-1.5 px-3 py-1.5 rounded-md text-sm font-medium transition-colors cursor-pointer ${t==="teacher"&&s==="dashboard"||t==="student"&&r==="dashboard"?"bg-indigo-50 text-indigo-700":"text-slate-600 hover:text-indigo-600 hover:bg-slate-100"}`,children:[l.jsx(Dh,{size:16}),n==="zh"?"系统总览":"Dashboard"]}),t==="student"&&l.jsxs(l.Fragment,{children:[l.jsx("span",{className:"text-slate-300 font-light text-lg select-none",children:"/"}),l.jsxs("h2",{className:"font-semibold text-gray-800 tracking-tight flex items-center gap-2",children:[l.jsx(Fh,{size:20,className:"text-gray-400"}),"Student Dashboard"]})]}),t==="student"&&i.role==="teacher"&&l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("span",{className:"text-sm text-gray-500",children:"View as:"}),l.jsxs("select",{className:"border border-gray-200 rounded p-1 text-sm bg-white",value:o||"",onChange:N=>v(N.target.value),children:[l.jsx("option",{value:"",children:"-- Select Student --"}),a.map(N=>l.jsx("option",{value:N.id,children:N.name},N.id))]})]})]}),l.jsxs("div",{className:"flex items-center gap-4 text-sm text-gray-500",children:[t==="student"&&o&&c&&l.jsxs("div",{className:"relative",children:[l.jsxs("button",{onClick:()=>E(!u),className:"relative p-2 text-gray-500 hover:text-gray-700 hover:bg-gray-100 rounded-full transition-colors",children:[l.jsx(Bh,{size:20}),f.length>0&&l.jsx("span",{className:"absolute top-1 right-1 bg-red-500 text-white text-[10px] font-bold px-1.5 py-0.5 rounded-full flex items-center justify-center min-w-[18px]",children:f.length})]}),u&&l.jsxs("div",{className:"absolute right-0 mt-2 w-80 bg-white border border-gray-200 shadow-lg rounded-xl z-50 overflow-hidden",children:[l.jsxs("div",{className:"p-3 border-b border-gray-100 flex justify-between items-center bg-gray-50",children:[l.jsx("h3",{className:"font-semibold text-gray-800",children:"Notifications"}),f.length>0&&l.jsx("button",{onClick:async()=>{if(!o)return;try{const A=d.filter(R=>!m.has(R.id)).map(R=>fetch(`/api/students/${o}/read_notifications`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({notificationId:R.id})}));await Promise.all(A)}catch(A){console.error(A)}const N=new Set(m);d.forEach(A=>N.add(A.id)),w(N)},className:"text-xs text-indigo-600 hover:text-indigo-800 font-medium",children:"Mark all as read"})]}),l.jsx("div",{className:"max-h-96 overflow-y-auto",children:d.length===0?l.jsx("div",{className:"p-4 text-center text-sm text-gray-500 italic",children:"No notifications."}):l.jsx("div",{className:"divide-y divide-gray-100",children:d.map(N=>{const A=!m.has(N.id);return l.jsx("div",{className:`p-3 hover:bg-gray-50 cursor-pointer ${A?"bg-indigo-50/30":""}`,onClick:()=>{if(A){o&&fetch(`/api/students/${o}/read_notifications`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({notificationId:N.id})}).catch(console.error);const D=new Set(m);D.add(N.id),w(D)}const R=c?.assignments?.find(D=>D.id===N.relatedId);L({...N,assignment:R}),E(!1)},children:l.jsxs("div",{className:"flex gap-3",children:[l.jsx("div",{className:"mt-0.5",children:N.type==="new_assignment"?l.jsx(Wa,{size:16,className:"text-indigo-500"}):N.type==="rollcall_picked"?l.jsx(ls,{size:16,className:"text-amber-500 animate-pulse"}):l.jsx(li,{size:16,className:"text-green-500"})}),l.jsxs("div",{className:"flex-1",children:[l.jsx("div",{className:`text-sm ${A?"font-semibold text-gray-900":"font-medium text-gray-700"}`,children:N.title}),l.jsx("div",{className:`text-xs mt-0.5 ${A?"text-gray-600":"text-gray-500"}`,children:N.message})]}),A&&l.jsx("div",{className:"w-2 h-2 rounded-full bg-indigo-500 mt-1"})]})},N.id)})})})]})]}),l.jsxs("button",{onClick:()=>I(!0),className:"flex items-center gap-1.5 hover:text-primary-theme transition-colors bg-surface text-main px-3 py-1.5 rounded-md border border-theme shadow-sm font-medium cursor-pointer",children:[l.jsx(Br,{size:14,className:"text-emerald-500 animate-pulse"}),n==="zh"?"系统资源库":"System Resource Library"]}),l.jsx("button",{onClick:M,title:n==="zh"?"Switch to English":"切换为中文",className:"p-2 hover:bg-surface-secondary text-main transition-colors bg-surface rounded-lg border border-theme shadow-3xs flex items-center justify-center shrink-0 cursor-pointer",children:l.jsx(Br,{size:16})}),l.jsx(Jf,{lang:n}),(()=>{const N=g==="error"||!h?{bg:"bg-rose-50 border-rose-200 text-rose-600 hover:bg-rose-100 animate-pulse",dot:"bg-rose-500",ping:"bg-rose-400",label:n==="zh"?"SQLite 数据库连接出错或已断开":"SQLite DB Error / Disconnected"}:g==="warning"?{bg:"bg-amber-50 border-amber-200 text-amber-600 hover:bg-amber-100",dot:"bg-amber-500",ping:"bg-amber-400",label:n==="zh"?"SQLite 数据库存在状态警告":"SQLite DB Warning"}:{bg:"bg-emerald-50 border-emerald-200 text-emerald-600 hover:bg-emerald-100",dot:"bg-emerald-500",ping:"bg-emerald-400",label:n==="zh"?"SQLite 数据库连接正常":"SQLite DB Connected & Normal"};return l.jsxs("div",{id:"db-connection-status-badge",className:`w-8 h-8 rounded-lg border flex items-center justify-center relative select-none shrink-0 cursor-pointer transition-colors shadow-3xs ${N.bg}`,title:N.label,children:[l.jsx($h,{size:15}),l.jsxs("span",{className:"absolute -top-0.5 -right-0.5 flex h-2.5 w-2.5",children:[l.jsx("span",{className:`animate-ping absolute inline-flex h-full w-full rounded-full opacity-75 ${N.ping}`}),l.jsx("span",{className:`relative inline-flex rounded-full h-2.5 w-2.5 ${N.dot}`})]})]})})(),l.jsx(Uf,{session:i,lang:n,onLogout:_,onProfile:()=>S(!0)})]})]})}function Yf({open:e,session:t,lang:n,onClose:s,onSaved:r,onAvatar:i}){const[o,a]=p.useState(t.name),[c,u]=p.useState(!1),[d,f]=p.useState(null),m=p.useRef(null),[h,g]=p.useState(!1),[x,v]=p.useState(null),[w,I]=p.useState(!1),[S,P]=p.useState(""),[z,E]=p.useState(""),[L,_]=p.useState(""),[M,N]=p.useState(!1),[A,R]=p.useState(null),[D,F]=p.useState(!1);if(!e)return null;const j=(q,ee)=>n==="zh"?q:ee,T=t.role==="teacher"?t.subRole==="administrator"?j("管理员","Administrator"):j("教师","Teacher"):j("学生","Student"),$=o.trim(),k=$.length>0&&$!==t.name,B=async()=>{if(!(!k||c)){u(!0),f(null);try{const q=await fetch("/api/auth/profile",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:$})}),ee=await q.json();if(!q.ok){f(ee.error||(n==="zh"?"保存失败":"Save failed"));return}r(ee.name??$)}catch{f(n==="zh"?"网络错误,请重试":"Network error, please retry")}finally{u(!1)}}},y=S.length>0&&z.length>=8&&/[a-zA-Z]/.test(z)&&/[0-9]/.test(z)&&z===L,te=async()=>{if(!(!y||M)){N(!0),R(null);try{const q=await fetch("/api/auth/change-password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({oldPassword:S,newPassword:z})}),ee=await q.json();if(!q.ok){R(ee.error||(n==="zh"?"修改失败":"Change failed"));return}F(!0),P(""),E(""),_(""),I(!1)}catch{R(n==="zh"?"网络错误,请重试":"Network error, please retry")}finally{N(!1)}}},ae=async q=>{const ee=q.target.files?.[0];if(q.target.value="",!!ee){g(!0),v(null);try{const se=await new Promise((ze,je)=>{const he=new FileReader;he.onload=()=>ze(he.result),he.onerror=()=>je(he.error),he.readAsDataURL(ee)}),fe=await fetch("/api/auth/avatar",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({filename:ee.name,base64Data:se})}),ge=await fe.json();if(!fe.ok){v(ge.error||(n==="zh"?"上传失败":"Upload failed"));return}i?.(ge.avatar)}catch{v(n==="zh"?"网络错误,请重试":"Network error, please retry")}finally{g(!1)}}},b=async()=>{g(!0),v(null);try{const q=await fetch("/api/auth/avatar",{method:"DELETE"}),ee=await q.json().catch(()=>({}));if(!q.ok){v(ee.error||(n==="zh"?"移除失败":"Remove failed"));return}i?.(null)}catch{v(n==="zh"?"网络错误,请重试":"Network error, please retry")}finally{g(!1)}};return l.jsx("div",{className:"fixed inset-0 bg-black/40 backdrop-blur-xs flex items-center justify-center z-50 p-4",onClick:s,children:l.jsxs("div",{className:"bg-white rounded-2xl shadow-xl w-full max-w-md overflow-hidden",onClick:q=>q.stopPropagation(),children:[l.jsxs("div",{className:"flex items-center justify-between px-5 py-4 border-b border-gray-100",children:[l.jsx("h3",{className:"font-semibold text-gray-800",children:j("个人资料","Profile")}),l.jsx("button",{onClick:s,className:"text-gray-400 hover:text-gray-600 cursor-pointer",children:l.jsx(At,{size:18})})]}),l.jsxs("div",{className:"p-5 space-y-5",children:[l.jsxs("div",{className:"flex items-center gap-3",children:[l.jsx("span",{className:"w-14 h-14 rounded-full bg-indigo-100 text-indigo-600 flex items-center justify-center shrink-0 overflow-hidden",children:t.avatar?l.jsx("img",{src:t.avatar,alt:t.name,className:"w-full h-full object-cover"}):l.jsx(gn,{size:28})}),l.jsxs("div",{className:"min-w-0",children:[l.jsx("p",{className:"text-base font-semibold text-gray-800 truncate",children:t.name}),l.jsx("p",{className:"text-xs text-gray-400",children:T}),l.jsxs("div",{className:"mt-1.5 flex items-center gap-3",children:[l.jsx("button",{type:"button",onClick:()=>m.current?.click(),disabled:h,className:"text-xs text-indigo-600 hover:text-indigo-800 disabled:opacity-50 cursor-pointer",children:h?j("上传中…","Uploading…"):t.avatar?j("更换头像","Change avatar"):j("上传头像","Upload avatar")}),t.avatar&&l.jsx("button",{type:"button",onClick:b,disabled:h,className:"text-xs text-rose-500 hover:text-rose-700 disabled:opacity-50 cursor-pointer",children:j("移除","Remove")})]}),l.jsx("input",{ref:m,type:"file",accept:"image/png,image/jpeg,image/gif,image/webp",className:"hidden",onChange:ae})]})]}),x&&l.jsx("p",{className:"text-xs text-rose-500",children:x}),l.jsxs("div",{children:[l.jsx("label",{className:"block text-sm text-gray-500 mb-1",children:j("显示名称","Display Name")}),l.jsxs("div",{className:"flex gap-2",children:[l.jsx("input",{value:o,onChange:q=>a(q.target.value),maxLength:50,className:"flex-1 border border-gray-300 rounded-lg px-3 py-2 text-sm text-gray-800 focus:outline-none focus:ring-2 focus:ring-indigo-200"}),l.jsx("button",{onClick:B,disabled:!k||c,className:"px-4 py-2 rounded-lg bg-indigo-600 text-white text-sm font-medium disabled:opacity-40 enabled:hover:bg-indigo-700 transition-colors cursor-pointer shrink-0",children:c?j("保存中…","Saving…"):j("保存","Save")})]}),d&&l.jsx("p",{className:"text-xs text-rose-500 mt-1",children:d})]}),l.jsxs("div",{className:"border-t border-gray-100 pt-4",children:[l.jsxs("div",{className:"flex items-center justify-between",children:[l.jsxs("span",{className:"text-sm font-medium text-gray-700 flex items-center gap-2",children:[l.jsx(Vh,{size:16,className:"text-gray-400"}),j("修改密码","Change Password")]}),!w&&!D&&l.jsx("button",{onClick:()=>{I(!0),R(null)},className:"text-sm text-indigo-600 hover:text-indigo-800 cursor-pointer",children:j("修改","Edit")})]}),D&&l.jsxs("p",{className:"mt-2 flex items-center gap-1.5 text-sm text-emerald-600",children:[l.jsx(li,{size:16}),j("密码已修改,其他设备的登录已失效","Password changed. Other devices were logged out.")]}),w&&l.jsxs("div",{className:"mt-3 space-y-3",children:[l.jsx("input",{type:"password",value:S,onChange:q=>P(q.target.value),placeholder:j("当前密码","Current password"),className:"w-full border border-gray-300 rounded-lg px-3 py-2 text-sm text-gray-800 focus:outline-none focus:ring-2 focus:ring-indigo-200"}),l.jsx("input",{type:"password",value:z,onChange:q=>E(q.target.value),placeholder:j("新密码(≥8 位,含字母和数字)","New password (≥8 chars, letters + numbers)"),className:"w-full border border-gray-300 rounded-lg px-3 py-2 text-sm text-gray-800 focus:outline-none focus:ring-2 focus:ring-indigo-200"}),l.jsx("input",{type:"password",value:L,onChange:q=>_(q.target.value),placeholder:j("确认新密码","Confirm new password"),className:"w-full border border-gray-300 rounded-lg px-3 py-2 text-sm text-gray-800 focus:outline-none focus:ring-2 focus:ring-indigo-200"}),A&&l.jsx("p",{className:"text-xs text-rose-500",children:A}),l.jsxs("div",{className:"flex gap-2 justify-end",children:[l.jsx("button",{onClick:()=>{I(!1),P(""),E(""),_(""),R(null)},className:"px-4 py-2 rounded-lg border border-gray-300 text-sm text-gray-600 hover:bg-gray-50 cursor-pointer",children:j("取消","Cancel")}),l.jsx("button",{onClick:te,disabled:!y||M,className:"px-4 py-2 rounded-lg bg-indigo-600 text-white text-sm font-medium disabled:opacity-40 enabled:hover:bg-indigo-700 transition-colors cursor-pointer",children:M?j("提交中…","Submitting…"):j("提交","Submit")})]})]})]}),l.jsxs("div",{className:"border-t border-gray-100 pt-4 space-y-2",children:[l.jsxs("div",{className:"flex items-center justify-between",children:[l.jsx("span",{className:"text-sm text-gray-400",children:j("用户名(登录账号)","Username (login)")}),l.jsx("span",{className:"text-sm font-medium text-gray-700 truncate max-w-[60%]",title:t.username,children:t.username||"-"})]}),l.jsxs("div",{className:"flex items-center justify-between",children:[l.jsx("span",{className:"text-sm text-gray-400",children:j("角色","Role")}),l.jsx("span",{className:"text-sm font-medium text-gray-700",children:T})]})]})]})]})})}const u0={slate:{iconBg:"bg-slate-100",iconText:"text-slate-600",cardHoverBorder:"hover:border-slate-400",cardHoverRing:"group-hover:ring-slate-300",cardHoverShadow:"group-hover:shadow-slate-200/70",groupAccent:"bg-slate-400",groupText:"text-slate-500"},blue:{iconBg:"bg-blue-100",iconText:"text-blue-600",cardHoverBorder:"hover:border-blue-400",cardHoverRing:"group-hover:ring-blue-300",cardHoverShadow:"group-hover:shadow-blue-200/70",groupAccent:"bg-blue-400",groupText:"text-blue-500"},violet:{iconBg:"bg-violet-100",iconText:"text-violet-600",cardHoverBorder:"hover:border-violet-400",cardHoverRing:"group-hover:ring-violet-300",cardHoverShadow:"group-hover:shadow-violet-200/70",groupAccent:"bg-violet-400",groupText:"text-violet-500"},amber:{iconBg:"bg-amber-100",iconText:"text-amber-600",cardHoverBorder:"hover:border-amber-400",cardHoverRing:"group-hover:ring-amber-300",cardHoverShadow:"group-hover:shadow-amber-200/70",groupAccent:"bg-amber-400",groupText:"text-amber-500"},rose:{iconBg:"bg-rose-100",iconText:"text-rose-600",cardHoverBorder:"hover:border-rose-400",cardHoverRing:"group-hover:ring-rose-300",cardHoverShadow:"group-hover:shadow-rose-200/70",groupAccent:"bg-rose-400",groupText:"text-rose-500"},emerald:{iconBg:"bg-emerald-100",iconText:"text-emerald-600",cardHoverBorder:"hover:border-emerald-400",cardHoverRing:"group-hover:ring-emerald-300",cardHoverShadow:"group-hover:shadow-emerald-200/70",groupAccent:"bg-emerald-400",groupText:"text-emerald-500"},cyan:{iconBg:"bg-cyan-100",iconText:"text-cyan-600",cardHoverBorder:"hover:border-cyan-400",cardHoverRing:"group-hover:ring-cyan-300",cardHoverShadow:"group-hover:shadow-cyan-200/70",groupAccent:"bg-cyan-400",groupText:"text-cyan-500"},pink:{iconBg:"bg-pink-100",iconText:"text-pink-600",cardHoverBorder:"hover:border-pink-400",cardHoverRing:"group-hover:ring-pink-300",cardHoverShadow:"group-hover:shadow-pink-200/70",groupAccent:"bg-pink-400",groupText:"text-pink-500"},indigo:{iconBg:"bg-indigo-100",iconText:"text-indigo-600",cardHoverBorder:"hover:border-indigo-400",cardHoverRing:"group-hover:ring-indigo-300",cardHoverShadow:"group-hover:shadow-indigo-200/70",groupAccent:"bg-indigo-400",groupText:"text-indigo-500"}},d0=[{id:"present",labelZh:"内容呈现",labelEn:"Content"},{id:"assess",labelZh:"评估互动",labelEn:"Assessment"},{id:"manage",labelZh:"课堂管理",labelEn:"Classroom"}],Kf=[{type:"presentation",labelZh:"课件演示",labelEn:"Slides Deck",descriptionZh:"Markdown 幻灯片",descriptionEn:"Markdown slides",icon:Uh,color:"violet",group:"present",defaultData:{markdown:`# Title Slide
5
+ ---
6
+ ## Slide 2`},editFields:[{key:"markdown",labelZh:"幻灯片内容 (Markdown)",labelEn:"Slides Content (Markdown)",kind:"textarea",placeholderZh:`# 标题
7
+ ---
8
+ ## 第二页`}]},{type:"code-sandbox",labelZh:"代码沙箱",labelEn:"Code Editor",descriptionZh:"可运行代码",descriptionEn:"Runnable code",icon:qn,color:"slate",group:"present",defaultData:{code:"console.log('Hello Sandbox!');"},editFields:[{key:"code",labelZh:"代码",labelEn:"Code",kind:"textarea",placeholderZh:"console.log('Hello');"}]},{type:"math-graph",labelZh:"数学函数",labelEn:"Math Grapher",descriptionZh:"函数图像",descriptionEn:"Function graph",icon:Wh,color:"blue",group:"present",defaultData:{equation:"Math.sin(x)"},editFields:[{key:"equation",labelZh:"函数表达式",labelEn:"Equation",kind:"input",placeholderZh:"如 Math.sin(x)"}]},{type:"html-applet",labelZh:"交互网页课件",labelEn:"Interactive Courseware",descriptionZh:"可交互 HTML/ZIP 网页",descriptionEn:"Interactive web/ZIP applet",icon:Br,color:"emerald",group:"present",defaultData:{title:"Interactive Web Courseware",code:`<!-- Interactive Web Courseware -->
9
+ <div style='padding:20px; text-align:center;'>
10
+ <h2>Interactive Web Courseware</h2>
11
+ <p>在属性栏中配置本地 ZIP/HTML 部署包。</p>
12
+ </div>`},editFields:[{key:"title",labelZh:"标题",labelEn:"Title",kind:"input",placeholderZh:"课件标题",placeholderEn:"Courseware title"},{key:"coursewareUuid",labelZh:"互动课件",labelEn:"Courseware",kind:"select",loadOptions:async()=>{try{return(await(await fetch("/api/courseware")).json()).map(n=>({value:n.uuid,label:n.name}))}catch{return[]}}},{key:"resourceId",labelZh:"系统资源",labelEn:"System Resource",kind:"select",loadOptions:async()=>{try{return(await(await fetch("/api/resources")).json()).map(n=>({value:n.id,label:`[${n.type}] ${n.name}`}))}catch{return[]}}},{key:"code",labelZh:"HTML 代码",labelEn:"HTML Code",kind:"textarea",placeholderZh:"<div>…</div>"}]},{type:"quiz",labelZh:"随堂测试",labelEn:"Interactive Quiz",descriptionZh:"选择题互动",descriptionEn:"Multiple choice",icon:ci,color:"amber",group:"assess",defaultData:{question:"New Quiz",options:["A","B","C","D"]},editFields:[{key:"question",labelZh:"题目",labelEn:"Question",kind:"input",placeholderZh:"请输入题目"},{key:"options",labelZh:"选项 (A/B/C/D)",labelEn:"Options (A/B/C/D)",kind:"options"}]},{type:"assignment",labelZh:"作业提交",labelEn:"Assignment",descriptionZh:"布置与提交",descriptionEn:"Submit work",icon:Wa,color:"rose",group:"assess",defaultData:{title:"New Assignment",description:"Upload your work here"},editFields:[{key:"title",labelZh:"作业标题",labelEn:"Title",kind:"input",placeholderZh:"如:第一章练习"},{key:"description",labelZh:"说明",labelEn:"Description",kind:"textarea",placeholderZh:"作业要求说明…"}]},{type:"rollcall",labelZh:"随机点名",labelEn:"Random Picker",descriptionZh:"课堂点名",descriptionEn:"Pick a student",icon:qh,color:"cyan",group:"manage",defaultData:{allStudents:[]},editFields:[]},{type:"hello-world",labelZh:"问候插件",labelEn:"Hello World",descriptionZh:"欢迎问候",descriptionEn:"Welcome greeting",icon:ls,color:"pink",group:"manage",defaultData:{},editFields:[]}],Xf=Kf.reduce((e,t)=>(e[t.type]=t,e),{}),nt=qt(e=>({lang:"zh",activeRole:"teacher",teacherTab:"courses",profileOpen:!1,isCourseWizardOpen:!1,isImportLessonsOpen:!1,isQuizGeneratorOpen:!1,isLessonPreviewVisible:!1,isSystemResourceLibraryOpen:!1,batchPicker:null,isExportWeightModalOpen:!1,toasts:[],siteInfo:{siteName:"",slogan:"",logoUrl:null},setLang:t=>e({lang:t}),setActiveRole:t=>e({activeRole:t}),setTeacherTab:t=>e({teacherTab:t}),setProfileOpen:t=>e({profileOpen:t}),setIsCourseWizardOpen:t=>e({isCourseWizardOpen:t}),setIsImportLessonsOpen:t=>e({isImportLessonsOpen:t}),setIsQuizGeneratorOpen:t=>e({isQuizGeneratorOpen:t}),setIsLessonPreviewVisible:t=>e({isLessonPreviewVisible:t}),setIsSystemResourceLibraryOpen:t=>e({isSystemResourceLibraryOpen:t}),setBatchPicker:t=>e({batchPicker:t}),setIsExportWeightModalOpen:t=>e({isExportWeightModalOpen:t}),addToast:t=>e(n=>({toasts:[...n.toasts,t]})),removeToast:t=>e(n=>({toasts:n.toasts.filter(s=>s.id!==t)})),setSiteInfo:t=>e({siteInfo:t})})),ep=qt(e=>({classes:[],students:[],classStudentsMap:{},classDashboardMap:{},studentProgressMap:{},classSchedulesMap:{},scheduleAttendanceMap:{},assignmentSubmissionsMap:{},classAssignmentsMap:{},classProgressMap:{},classSeats:{lab_id:null,seats:[]},setClasses:t=>e({classes:t}),setStudents:t=>e({students:t}),setClassStudents:(t,n)=>e(s=>({classStudentsMap:{...s.classStudentsMap,[t]:n}})),setClassDashboard:(t,n)=>e(s=>({classDashboardMap:{...s.classDashboardMap,[t]:n}})),setStudentProgress:(t,n)=>e(s=>({studentProgressMap:{...s.studentProgressMap,[t]:n}})),setClassSchedules:(t,n)=>e(s=>({classSchedulesMap:{...s.classSchedulesMap,[t]:n}})),setScheduleAttendance:(t,n)=>e(s=>({scheduleAttendanceMap:{...s.scheduleAttendanceMap,[t]:n}})),setAssignmentSubmissions:(t,n)=>e(s=>({assignmentSubmissionsMap:{...s.assignmentSubmissionsMap,[t]:n}})),setClassAssignments:(t,n)=>e(s=>({classAssignmentsMap:{...s.classAssignmentsMap,[t]:n}})),setClassProgress:(t,n)=>e(s=>({classProgressMap:{...s.classProgressMap,[t]:n}})),setClassSeats:t=>e({classSeats:t})})),tp=qt(e=>({lessons:[],selectedLesson:null,elements:[],vfsNodes:[],setLessons:t=>e(n=>({lessons:typeof t=="function"?t(n.lessons):t})),setSelectedLesson:t=>e({selectedLesson:t}),setElements:t=>e({elements:t}),setVfsNodes:t=>e({vfsNodes:t})})),np=qt(e=>({liveClassSelectedClassId:null,liveClassIsActive:!1,liveClassFeed:[],liveClassTimeRemaining:0,liveClassAcknowledgedMap:new Map,liveClassStudentProgress:[],onlineStudentIds:[],activeStudentLessons:{},setLiveClassSelectedClassId:t=>e({liveClassSelectedClassId:t}),setLiveClassIsActive:t=>e({liveClassIsActive:t}),setLiveClassFeed:t=>e({liveClassFeed:t}),appendLiveClassFeed:t=>e(n=>({liveClassFeed:[...n.liveClassFeed.slice(-49),t]})),setLiveClassTimeRemaining:t=>e({liveClassTimeRemaining:t}),setLiveClassAcknowledgedMap:t=>e({liveClassAcknowledgedMap:t}),setLiveClassStudentProgress:t=>e({liveClassStudentProgress:t}),setOnlineStudentIds:t=>e({onlineStudentIds:t}),setActiveStudentLessons:t=>e({activeStudentLessons:t})})),sp=qt(e=>({studentDashboardData:null,notifications:[],setStudentDashboardData:t=>e({studentDashboardData:t}),setNotifications:t=>e({notifications:t})})),Ce=qt(e=>({lang:nt.getState().lang,session:null,lessons:[],selectedLesson:null,elements:[],classes:[],students:[],liveClassSelectedClassId:null,liveClassIsActive:!1,teacherTab:nt.getState().teacherTab,aiProviders:[],plugins:[],registeredCommands:[],events:[],approvals:[],processes:[],vfsNodes:[],todaySchedules:[],computerLabs:[],dbConnected:!1,sessionLoading:!0,classStudentsMap:{},classDashboardMap:{},studentProgressMap:{},classSchedulesMap:{},scheduleAttendanceMap:{},assignmentSubmissionsMap:{},classAssignmentsMap:{},classProgressMap:{},classSeats:{lab_id:null,seats:[]},onlineStudentIds:[],activeStudentLessons:{},liveClassFeed:[],liveClassTimeRemaining:0,liveClassAcknowledgedMap:new Map,liveClassStudentProgress:[],studentDashboardData:null,notifications:[],toasts:nt.getState().toasts,siteInfo:nt.getState().siteInfo,setLang:t=>{nt.getState().setLang(t)},setSession:t=>e({session:t}),setLessons:t=>e(n=>({lessons:typeof t=="function"?t(n.lessons):t})),setSelectedLesson:t=>e({selectedLesson:t}),setElements:t=>e({elements:t}),setClasses:t=>e({classes:t}),setStudents:t=>e({students:t}),setLiveClassSelectedClassId:t=>e({liveClassSelectedClassId:t}),setLiveClassIsActive:t=>e({liveClassIsActive:t}),setTeacherTab:t=>{nt.getState().setTeacherTab(t)},setAiProviders:t=>e({aiProviders:t}),setPlugins:t=>e({plugins:t}),setRegisteredCommands:t=>e({registeredCommands:t}),setEvents:t=>e({events:t}),setApprovals:t=>e({approvals:t}),setProcesses:t=>e({processes:t}),setVfsNodes:t=>e({vfsNodes:t}),setTodaySchedules:t=>e({todaySchedules:t}),setComputerLabs:t=>e({computerLabs:t}),setDbConnected:t=>e({dbConnected:t}),setSessionLoading:t=>e({sessionLoading:t}),setClassStudents:(t,n)=>e(s=>({classStudentsMap:{...s.classStudentsMap,[t]:n}})),setClassDashboard:(t,n)=>e(s=>({classDashboardMap:{...s.classDashboardMap,[t]:n}})),setStudentProgress:(t,n)=>e(s=>({studentProgressMap:{...s.studentProgressMap,[t]:n}})),setClassSchedules:(t,n)=>e(s=>({classSchedulesMap:{...s.classSchedulesMap,[t]:n}})),setScheduleAttendance:(t,n)=>e(s=>({scheduleAttendanceMap:{...s.scheduleAttendanceMap,[t]:n}})),setAssignmentSubmissions:(t,n)=>e(s=>({assignmentSubmissionsMap:{...s.assignmentSubmissionsMap,[t]:n}})),setClassAssignments:(t,n)=>e(s=>({classAssignmentsMap:{...s.classAssignmentsMap,[t]:n}})),setClassProgress:(t,n)=>e(s=>({classProgressMap:{...s.classProgressMap,[t]:n}})),setClassSeats:t=>e({classSeats:t}),setOnlineStudentIds:t=>e({onlineStudentIds:t}),setActiveStudentLessons:t=>e({activeStudentLessons:t}),setLiveClassFeed:t=>e({liveClassFeed:t}),appendLiveClassFeed:t=>e(n=>({liveClassFeed:[...n.liveClassFeed.slice(-49),t]})),setLiveClassTimeRemaining:t=>e({liveClassTimeRemaining:t}),setLiveClassAcknowledgedMap:t=>e({liveClassAcknowledgedMap:t}),setLiveClassStudentProgress:t=>e({liveClassStudentProgress:t}),setStudentDashboardData:t=>e({studentDashboardData:t}),setNotifications:t=>e({notifications:t}),addToast:t=>{nt.getState().addToast(t)},removeToast:t=>{nt.getState().removeToast(t)},setSiteInfo:t=>{nt.getState().setSiteInfo(t)}}));nt.subscribe(e=>{Ce.setState({lang:e.lang,teacherTab:e.teacherTab,toasts:e.toasts,siteInfo:e.siteInfo})});ep.subscribe(e=>{Ce.setState({classes:e.classes,students:e.students,classStudentsMap:e.classStudentsMap,classDashboardMap:e.classDashboardMap,studentProgressMap:e.studentProgressMap,classSchedulesMap:e.classSchedulesMap,scheduleAttendanceMap:e.scheduleAttendanceMap,assignmentSubmissionsMap:e.assignmentSubmissionsMap,classAssignmentsMap:e.classAssignmentsMap,classProgressMap:e.classProgressMap,classSeats:e.classSeats})});tp.subscribe(e=>{Ce.setState({lessons:e.lessons,selectedLesson:e.selectedLesson,elements:e.elements,vfsNodes:e.vfsNodes})});np.subscribe(e=>{Ce.setState({liveClassSelectedClassId:e.liveClassSelectedClassId,liveClassIsActive:e.liveClassIsActive,liveClassFeed:e.liveClassFeed,liveClassTimeRemaining:e.liveClassTimeRemaining,liveClassAcknowledgedMap:e.liveClassAcknowledgedMap,liveClassStudentProgress:e.liveClassStudentProgress,onlineStudentIds:e.onlineStudentIds,activeStudentLessons:e.activeStudentLessons})});sp.subscribe(e=>{Ce.setState({studentDashboardData:e.studentDashboardData,notifications:e.notifications})});const ce=e=>lf(Ce,e);function rp(e,t){const n={};return(e[e.length-1]===""?[...e,""]:e).join((n.padRight?" ":"")+","+(n.padLeft===!1?"":" ")).trim()}const ip=/^[$_\p{ID_Start}][$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,op=/^[$_\p{ID_Start}][-$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,ap={};function Co(e,t){return(ap.jsx?op:ip).test(e)}const lp=/[ \t\n\f\r]/g;function cp(e){return typeof e=="object"?e.type==="text"?ko(e.value):!1:ko(e)}function ko(e){return e.replace(lp,"")===""}class xn{constructor(t,n,s){this.normal=n,this.property=t,s&&(this.space=s)}}xn.prototype.normal={};xn.prototype.property={};xn.prototype.space=void 0;function Xa(e,t){const n={},s={};for(const r of e)Object.assign(n,r.property),Object.assign(s,r.normal);return new xn(n,s,t)}function Vr(e){return e.toLowerCase()}class De{constructor(t,n){this.attribute=n,this.property=t}}De.prototype.attribute="";De.prototype.booleanish=!1;De.prototype.boolean=!1;De.prototype.commaOrSpaceSeparated=!1;De.prototype.commaSeparated=!1;De.prototype.defined=!1;De.prototype.mustUseProperty=!1;De.prototype.number=!1;De.prototype.overloadedBoolean=!1;De.prototype.property="";De.prototype.spaceSeparated=!1;De.prototype.space=void 0;let up=0;const X=zt(),xe=zt(),Ur=zt(),U=zt(),le=zt(),jt=zt(),Ue=zt();function zt(){return 2**++up}const Wr=Object.freeze(Object.defineProperty({__proto__:null,boolean:X,booleanish:xe,commaOrSpaceSeparated:Ue,commaSeparated:jt,number:U,overloadedBoolean:Ur,spaceSeparated:le},Symbol.toStringTag,{value:"Module"})),mr=Object.keys(Wr);class fi extends De{constructor(t,n,s,r){let i=-1;if(super(t,n),Eo(this,"space",r),typeof s=="number")for(;++i<mr.length;){const o=mr[i];Eo(this,mr[i],(s&Wr[o])===Wr[o])}}}fi.prototype.defined=!0;function Eo(e,t,n){n&&(e[t]=n)}function Ht(e){const t={},n={};for(const[s,r]of Object.entries(e.properties)){const i=new fi(s,e.transform(e.attributes||{},s),r,e.space);e.mustUseProperty&&e.mustUseProperty.includes(s)&&(i.mustUseProperty=!0),t[s]=i,n[Vr(s)]=s,n[Vr(i.attribute)]=s}return new xn(t,n,e.space)}const el=Ht({properties:{ariaActiveDescendant:null,ariaAtomic:xe,ariaAutoComplete:null,ariaBusy:xe,ariaChecked:xe,ariaColCount:U,ariaColIndex:U,ariaColSpan:U,ariaControls:le,ariaCurrent:null,ariaDescribedBy:le,ariaDetails:null,ariaDisabled:xe,ariaDropEffect:le,ariaErrorMessage:null,ariaExpanded:xe,ariaFlowTo:le,ariaGrabbed:xe,ariaHasPopup:null,ariaHidden:xe,ariaInvalid:null,ariaKeyShortcuts:null,ariaLabel:null,ariaLabelledBy:le,ariaLevel:U,ariaLive:null,ariaModal:xe,ariaMultiLine:xe,ariaMultiSelectable:xe,ariaOrientation:null,ariaOwns:le,ariaPlaceholder:null,ariaPosInSet:U,ariaPressed:xe,ariaReadOnly:xe,ariaRelevant:null,ariaRequired:xe,ariaRoleDescription:le,ariaRowCount:U,ariaRowIndex:U,ariaRowSpan:U,ariaSelected:xe,ariaSetSize:U,ariaSort:null,ariaValueMax:U,ariaValueMin:U,ariaValueNow:U,ariaValueText:null,role:null},transform(e,t){return t==="role"?t:"aria-"+t.slice(4).toLowerCase()}});function tl(e,t){return t in e?e[t]:t}function nl(e,t){return tl(e,t.toLowerCase())}const dp=Ht({attributes:{acceptcharset:"accept-charset",classname:"class",htmlfor:"for",httpequiv:"http-equiv"},mustUseProperty:["checked","multiple","muted","selected"],properties:{abbr:null,accept:jt,acceptCharset:le,accessKey:le,action:null,allow:null,allowFullScreen:X,allowPaymentRequest:X,allowUserMedia:X,alpha:X,alt:null,as:null,async:X,autoCapitalize:null,autoComplete:le,autoFocus:X,autoPlay:X,blocking:le,capture:null,charSet:null,checked:X,cite:null,className:le,closedBy:null,colorSpace:null,cols:U,colSpan:U,command:null,commandFor:null,content:null,contentEditable:xe,controls:X,controlsList:le,coords:U|jt,crossOrigin:null,data:null,dateTime:null,decoding:null,default:X,defer:X,dir:null,dirName:null,disabled:X,download:Ur,draggable:xe,encType:null,enterKeyHint:null,fetchPriority:null,form:null,formAction:null,formEncType:null,formMethod:null,formNoValidate:X,formTarget:null,headers:le,height:U,hidden:Ur,high:U,href:null,hrefLang:null,htmlFor:le,httpEquiv:le,id:null,imageSizes:null,imageSrcSet:null,inert:X,inputMode:null,integrity:null,is:null,isMap:X,itemId:null,itemProp:le,itemRef:le,itemScope:X,itemType:le,kind:null,label:null,lang:null,language:null,list:null,loading:null,loop:X,low:U,manifest:null,max:null,maxLength:U,media:null,method:null,min:null,minLength:U,multiple:X,muted:X,name:null,nonce:null,noModule:X,noValidate:X,onAbort:null,onAfterPrint:null,onAuxClick:null,onBeforeMatch:null,onBeforePrint:null,onBeforeToggle:null,onBeforeUnload:null,onBlur:null,onCancel:null,onCanPlay:null,onCanPlayThrough:null,onChange:null,onClick:null,onClose:null,onContextLost:null,onContextMenu:null,onContextRestored:null,onCopy:null,onCueChange:null,onCut:null,onDblClick:null,onDrag:null,onDragEnd:null,onDragEnter:null,onDragExit:null,onDragLeave:null,onDragOver:null,onDragStart:null,onDrop:null,onDurationChange:null,onEmptied:null,onEnded:null,onError:null,onFocus:null,onFormData:null,onHashChange:null,onInput:null,onInvalid:null,onKeyDown:null,onKeyPress:null,onKeyUp:null,onLanguageChange:null,onLoad:null,onLoadedData:null,onLoadedMetadata:null,onLoadEnd:null,onLoadStart:null,onMessage:null,onMessageError:null,onMouseDown:null,onMouseEnter:null,onMouseLeave:null,onMouseMove:null,onMouseOut:null,onMouseOver:null,onMouseUp:null,onOffline:null,onOnline:null,onPageHide:null,onPageShow:null,onPaste:null,onPause:null,onPlay:null,onPlaying:null,onPopState:null,onProgress:null,onRateChange:null,onRejectionHandled:null,onReset:null,onResize:null,onScroll:null,onScrollEnd:null,onSecurityPolicyViolation:null,onSeeked:null,onSeeking:null,onSelect:null,onSlotChange:null,onStalled:null,onStorage:null,onSubmit:null,onSuspend:null,onTimeUpdate:null,onToggle:null,onUnhandledRejection:null,onUnload:null,onVolumeChange:null,onWaiting:null,onWheel:null,open:X,optimum:U,pattern:null,ping:le,placeholder:null,playsInline:X,popover:null,popoverTarget:null,popoverTargetAction:null,poster:null,preload:null,readOnly:X,referrerPolicy:null,rel:le,required:X,reversed:X,rows:U,rowSpan:U,sandbox:le,scope:null,scoped:X,seamless:X,selected:X,shadowRootClonable:X,shadowRootCustomElementRegistry:X,shadowRootDelegatesFocus:X,shadowRootMode:null,shadowRootSerializable:X,shape:null,size:U,sizes:null,slot:null,span:U,spellCheck:xe,src:null,srcDoc:null,srcLang:null,srcSet:null,start:U,step:null,style:null,tabIndex:U,target:null,title:null,translate:null,type:null,typeMustMatch:X,useMap:null,value:xe,width:U,wrap:null,writingSuggestions:null,align:null,aLink:null,archive:le,axis:null,background:null,bgColor:null,border:U,borderColor:null,bottomMargin:U,cellPadding:null,cellSpacing:null,char:null,charOff:null,classId:null,clear:null,code:null,codeBase:null,codeType:null,color:null,compact:X,declare:X,event:null,face:null,frame:null,frameBorder:null,hSpace:U,leftMargin:U,link:null,longDesc:null,lowSrc:null,marginHeight:U,marginWidth:U,noResize:X,noHref:X,noShade:X,noWrap:X,object:null,profile:null,prompt:null,rev:null,rightMargin:U,rules:null,scheme:null,scrolling:xe,standby:null,summary:null,text:null,topMargin:U,valueType:null,version:null,vAlign:null,vLink:null,vSpace:U,allowTransparency:null,autoCorrect:null,autoSave:null,credentialless:X,disablePictureInPicture:X,disableRemotePlayback:X,exportParts:jt,part:le,prefix:null,property:null,results:U,security:null,unselectable:null},space:"html",transform:nl}),hp=Ht({attributes:{accentHeight:"accent-height",alignmentBaseline:"alignment-baseline",arabicForm:"arabic-form",baselineShift:"baseline-shift",capHeight:"cap-height",className:"class",clipPath:"clip-path",clipRule:"clip-rule",colorInterpolation:"color-interpolation",colorInterpolationFilters:"color-interpolation-filters",colorProfile:"color-profile",colorRendering:"color-rendering",crossOrigin:"crossorigin",dataType:"datatype",dominantBaseline:"dominant-baseline",enableBackground:"enable-background",fillOpacity:"fill-opacity",fillRule:"fill-rule",floodColor:"flood-color",floodOpacity:"flood-opacity",fontFamily:"font-family",fontSize:"font-size",fontSizeAdjust:"font-size-adjust",fontStretch:"font-stretch",fontStyle:"font-style",fontVariant:"font-variant",fontWeight:"font-weight",glyphName:"glyph-name",glyphOrientationHorizontal:"glyph-orientation-horizontal",glyphOrientationVertical:"glyph-orientation-vertical",hrefLang:"hreflang",horizAdvX:"horiz-adv-x",horizOriginX:"horiz-origin-x",horizOriginY:"horiz-origin-y",imageRendering:"image-rendering",letterSpacing:"letter-spacing",lightingColor:"lighting-color",markerEnd:"marker-end",markerMid:"marker-mid",markerStart:"marker-start",maskType:"mask-type",navDown:"nav-down",navDownLeft:"nav-down-left",navDownRight:"nav-down-right",navLeft:"nav-left",navNext:"nav-next",navPrev:"nav-prev",navRight:"nav-right",navUp:"nav-up",navUpLeft:"nav-up-left",navUpRight:"nav-up-right",onAbort:"onabort",onActivate:"onactivate",onAfterPrint:"onafterprint",onBeforePrint:"onbeforeprint",onBegin:"onbegin",onCancel:"oncancel",onCanPlay:"oncanplay",onCanPlayThrough:"oncanplaythrough",onChange:"onchange",onClick:"onclick",onClose:"onclose",onCopy:"oncopy",onCueChange:"oncuechange",onCut:"oncut",onDblClick:"ondblclick",onDrag:"ondrag",onDragEnd:"ondragend",onDragEnter:"ondragenter",onDragExit:"ondragexit",onDragLeave:"ondragleave",onDragOver:"ondragover",onDragStart:"ondragstart",onDrop:"ondrop",onDurationChange:"ondurationchange",onEmptied:"onemptied",onEnd:"onend",onEnded:"onended",onError:"onerror",onFocus:"onfocus",onFocusIn:"onfocusin",onFocusOut:"onfocusout",onHashChange:"onhashchange",onInput:"oninput",onInvalid:"oninvalid",onKeyDown:"onkeydown",onKeyPress:"onkeypress",onKeyUp:"onkeyup",onLoad:"onload",onLoadedData:"onloadeddata",onLoadedMetadata:"onloadedmetadata",onLoadStart:"onloadstart",onMessage:"onmessage",onMouseDown:"onmousedown",onMouseEnter:"onmouseenter",onMouseLeave:"onmouseleave",onMouseMove:"onmousemove",onMouseOut:"onmouseout",onMouseOver:"onmouseover",onMouseUp:"onmouseup",onMouseWheel:"onmousewheel",onOffline:"onoffline",onOnline:"ononline",onPageHide:"onpagehide",onPageShow:"onpageshow",onPaste:"onpaste",onPause:"onpause",onPlay:"onplay",onPlaying:"onplaying",onPopState:"onpopstate",onProgress:"onprogress",onRateChange:"onratechange",onRepeat:"onrepeat",onReset:"onreset",onResize:"onresize",onScroll:"onscroll",onSeeked:"onseeked",onSeeking:"onseeking",onSelect:"onselect",onShow:"onshow",onStalled:"onstalled",onStorage:"onstorage",onSubmit:"onsubmit",onSuspend:"onsuspend",onTimeUpdate:"ontimeupdate",onToggle:"ontoggle",onUnload:"onunload",onVolumeChange:"onvolumechange",onWaiting:"onwaiting",onZoom:"onzoom",overlinePosition:"overline-position",overlineThickness:"overline-thickness",paintOrder:"paint-order",panose1:"panose-1",pointerEvents:"pointer-events",referrerPolicy:"referrerpolicy",renderingIntent:"rendering-intent",shapeRendering:"shape-rendering",stopColor:"stop-color",stopOpacity:"stop-opacity",strikethroughPosition:"strikethrough-position",strikethroughThickness:"strikethrough-thickness",strokeDashArray:"stroke-dasharray",strokeDashOffset:"stroke-dashoffset",strokeLineCap:"stroke-linecap",strokeLineJoin:"stroke-linejoin",strokeMiterLimit:"stroke-miterlimit",strokeOpacity:"stroke-opacity",strokeWidth:"stroke-width",tabIndex:"tabindex",textAnchor:"text-anchor",textDecoration:"text-decoration",textRendering:"text-rendering",transformOrigin:"transform-origin",typeOf:"typeof",underlinePosition:"underline-position",underlineThickness:"underline-thickness",unicodeBidi:"unicode-bidi",unicodeRange:"unicode-range",unitsPerEm:"units-per-em",vAlphabetic:"v-alphabetic",vHanging:"v-hanging",vIdeographic:"v-ideographic",vMathematical:"v-mathematical",vectorEffect:"vector-effect",vertAdvY:"vert-adv-y",vertOriginX:"vert-origin-x",vertOriginY:"vert-origin-y",wordSpacing:"word-spacing",writingMode:"writing-mode",xHeight:"x-height",playbackOrder:"playbackorder",timelineBegin:"timelinebegin"},properties:{about:Ue,accentHeight:U,accumulate:null,additive:null,alignmentBaseline:null,alphabetic:U,amplitude:U,arabicForm:null,ascent:U,attributeName:null,attributeType:null,azimuth:U,bandwidth:null,baselineShift:null,baseFrequency:null,baseProfile:null,bbox:null,begin:null,bias:U,by:null,calcMode:null,capHeight:U,className:le,clip:null,clipPath:null,clipPathUnits:null,clipRule:null,color:null,colorInterpolation:null,colorInterpolationFilters:null,colorProfile:null,colorRendering:null,content:null,contentScriptType:null,contentStyleType:null,crossOrigin:null,cursor:null,cx:null,cy:null,d:null,dataType:null,defaultAction:null,descent:U,diffuseConstant:U,direction:null,display:null,dur:null,divisor:U,dominantBaseline:null,download:X,dx:null,dy:null,edgeMode:null,editable:null,elevation:U,enableBackground:null,end:null,event:null,exponent:U,externalResourcesRequired:null,fill:null,fillOpacity:U,fillRule:null,filter:null,filterRes:null,filterUnits:null,floodColor:null,floodOpacity:null,focusable:null,focusHighlight:null,fontFamily:null,fontSize:null,fontSizeAdjust:null,fontStretch:null,fontStyle:null,fontVariant:null,fontWeight:null,format:null,fr:null,from:null,fx:null,fy:null,g1:jt,g2:jt,glyphName:jt,glyphOrientationHorizontal:null,glyphOrientationVertical:null,glyphRef:null,gradientTransform:null,gradientUnits:null,handler:null,hanging:U,hatchContentUnits:null,hatchUnits:null,height:null,href:null,hrefLang:null,horizAdvX:U,horizOriginX:U,horizOriginY:U,id:null,ideographic:U,imageRendering:null,initialVisibility:null,in:null,in2:null,intercept:U,k:U,k1:U,k2:U,k3:U,k4:U,kernelMatrix:Ue,kernelUnitLength:null,keyPoints:null,keySplines:null,keyTimes:null,kerning:null,lang:null,lengthAdjust:null,letterSpacing:null,lightingColor:null,limitingConeAngle:U,local:null,markerEnd:null,markerMid:null,markerStart:null,markerHeight:null,markerUnits:null,markerWidth:null,mask:null,maskContentUnits:null,maskType:null,maskUnits:null,mathematical:null,max:null,media:null,mediaCharacterEncoding:null,mediaContentEncodings:null,mediaSize:U,mediaTime:null,method:null,min:null,mode:null,name:null,navDown:null,navDownLeft:null,navDownRight:null,navLeft:null,navNext:null,navPrev:null,navRight:null,navUp:null,navUpLeft:null,navUpRight:null,numOctaves:null,observer:null,offset:null,onAbort:null,onActivate:null,onAfterPrint:null,onBeforePrint:null,onBegin:null,onCancel:null,onCanPlay:null,onCanPlayThrough:null,onChange:null,onClick:null,onClose:null,onCopy:null,onCueChange:null,onCut:null,onDblClick:null,onDrag:null,onDragEnd:null,onDragEnter:null,onDragExit:null,onDragLeave:null,onDragOver:null,onDragStart:null,onDrop:null,onDurationChange:null,onEmptied:null,onEnd:null,onEnded:null,onError:null,onFocus:null,onFocusIn:null,onFocusOut:null,onHashChange:null,onInput:null,onInvalid:null,onKeyDown:null,onKeyPress:null,onKeyUp:null,onLoad:null,onLoadedData:null,onLoadedMetadata:null,onLoadStart:null,onMessage:null,onMouseDown:null,onMouseEnter:null,onMouseLeave:null,onMouseMove:null,onMouseOut:null,onMouseOver:null,onMouseUp:null,onMouseWheel:null,onOffline:null,onOnline:null,onPageHide:null,onPageShow:null,onPaste:null,onPause:null,onPlay:null,onPlaying:null,onPopState:null,onProgress:null,onRateChange:null,onRepeat:null,onReset:null,onResize:null,onScroll:null,onSeeked:null,onSeeking:null,onSelect:null,onShow:null,onStalled:null,onStorage:null,onSubmit:null,onSuspend:null,onTimeUpdate:null,onToggle:null,onUnload:null,onVolumeChange:null,onWaiting:null,onZoom:null,opacity:null,operator:null,order:null,orient:null,orientation:null,origin:null,overflow:null,overlay:null,overlinePosition:U,overlineThickness:U,paintOrder:null,panose1:null,path:null,pathLength:U,patternContentUnits:null,patternTransform:null,patternUnits:null,phase:null,ping:le,pitch:null,playbackOrder:null,pointerEvents:null,points:null,pointsAtX:U,pointsAtY:U,pointsAtZ:U,preserveAlpha:null,preserveAspectRatio:null,primitiveUnits:null,propagate:null,property:Ue,r:null,radius:null,referrerPolicy:null,refX:null,refY:null,rel:Ue,rev:Ue,renderingIntent:null,repeatCount:null,repeatDur:null,requiredExtensions:Ue,requiredFeatures:Ue,requiredFonts:Ue,requiredFormats:Ue,resource:null,restart:null,result:null,rotate:null,rx:null,ry:null,scale:null,seed:null,shapeRendering:null,side:null,slope:null,snapshotTime:null,specularConstant:U,specularExponent:U,spreadMethod:null,spacing:null,startOffset:null,stdDeviation:null,stemh:null,stemv:null,stitchTiles:null,stopColor:null,stopOpacity:null,strikethroughPosition:U,strikethroughThickness:U,string:null,stroke:null,strokeDashArray:Ue,strokeDashOffset:null,strokeLineCap:null,strokeLineJoin:null,strokeMiterLimit:U,strokeOpacity:U,strokeWidth:null,style:null,surfaceScale:U,syncBehavior:null,syncBehaviorDefault:null,syncMaster:null,syncTolerance:null,syncToleranceDefault:null,systemLanguage:Ue,tabIndex:U,tableValues:null,target:null,targetX:U,targetY:U,textAnchor:null,textDecoration:null,textRendering:null,textLength:null,timelineBegin:null,title:null,transformBehavior:null,type:null,typeOf:Ue,to:null,transform:null,transformOrigin:null,u1:null,u2:null,underlinePosition:U,underlineThickness:U,unicode:null,unicodeBidi:null,unicodeRange:null,unitsPerEm:U,values:null,vAlphabetic:U,vMathematical:U,vectorEffect:null,vHanging:U,vIdeographic:U,version:null,vertAdvY:U,vertOriginX:U,vertOriginY:U,viewBox:null,viewTarget:null,visibility:null,width:null,widths:null,wordSpacing:null,writingMode:null,x:null,x1:null,x2:null,xChannelSelector:null,xHeight:U,y:null,y1:null,y2:null,yChannelSelector:null,z:null,zoomAndPan:null},space:"svg",transform:tl}),sl=Ht({properties:{xLinkActuate:null,xLinkArcRole:null,xLinkHref:null,xLinkRole:null,xLinkShow:null,xLinkTitle:null,xLinkType:null},space:"xlink",transform(e,t){return"xlink:"+t.slice(5).toLowerCase()}}),rl=Ht({attributes:{xmlnsxlink:"xmlns:xlink"},properties:{xmlnsXLink:null,xmlns:null},space:"xmlns",transform:nl}),il=Ht({properties:{xmlBase:null,xmlLang:null,xmlSpace:null},space:"xml",transform(e,t){return"xml:"+t.slice(3).toLowerCase()}}),fp={classId:"classID",dataType:"datatype",itemId:"itemID",strokeDashArray:"strokeDasharray",strokeDashOffset:"strokeDashoffset",strokeLineCap:"strokeLinecap",strokeLineJoin:"strokeLinejoin",strokeMiterLimit:"strokeMiterlimit",typeOf:"typeof",xLinkActuate:"xlinkActuate",xLinkArcRole:"xlinkArcrole",xLinkHref:"xlinkHref",xLinkRole:"xlinkRole",xLinkShow:"xlinkShow",xLinkTitle:"xlinkTitle",xLinkType:"xlinkType",xmlnsXLink:"xmlnsXlink"},pp=/[A-Z]/g,Po=/-[a-z]/g,mp=/^data[-\w.:]+$/i;function gp(e,t){const n=Vr(t);let s=t,r=De;if(n in e.normal)return e.property[e.normal[n]];if(n.length>4&&n.slice(0,4)==="data"&&mp.test(t)){if(t.charAt(4)==="-"){const i=t.slice(5).replace(Po,xp);s="data"+i.charAt(0).toUpperCase()+i.slice(1)}else{const i=t.slice(4);if(!Po.test(i)){let o=i.replace(pp,yp);o.charAt(0)!=="-"&&(o="-"+o),t="data"+o}}r=fi}return new r(s,t)}function yp(e){return"-"+e.toLowerCase()}function xp(e){return e.charAt(1).toUpperCase()}const bp=Xa([el,dp,sl,rl,il],"html"),pi=Xa([el,hp,sl,rl,il],"svg");function wp(e){return e.join(" ").trim()}var $t={},gr,To;function Sp(){if(To)return gr;To=1;var e=/\/\*[^*]*\*+([^/*][^*]*\*+)*\//g,t=/\n/g,n=/^\s*/,s=/^(\*?[-#/*\\\w]+(\[[0-9a-z_-]+\])?)\s*/,r=/^:\s*/,i=/^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^)]*?\)|[^};])+)/,o=/^[;\s]*/,a=/^\s+|\s+$/g,c=`
13
+ `,u="/",d="*",f="",m="comment",h="declaration";function g(v,w){if(typeof v!="string")throw new TypeError("First argument must be a string");if(!v)return[];w=w||{};var I=1,S=1;function P(F){var j=F.match(t);j&&(I+=j.length);var T=F.lastIndexOf(c);S=~T?F.length-T:S+F.length}function z(){var F={line:I,column:S};return function(j){return j.position=new E(F),M(),j}}function E(F){this.start=F,this.end={line:I,column:S},this.source=w.source}E.prototype.content=v;function L(F){var j=new Error(w.source+":"+I+":"+S+": "+F);if(j.reason=F,j.filename=w.source,j.line=I,j.column=S,j.source=v,!w.silent)throw j}function _(F){var j=F.exec(v);if(j){var T=j[0];return P(T),v=v.slice(T.length),j}}function M(){_(n)}function N(F){var j;for(F=F||[];j=A();)j!==!1&&F.push(j);return F}function A(){var F=z();if(!(u!=v.charAt(0)||d!=v.charAt(1))){for(var j=2;f!=v.charAt(j)&&(d!=v.charAt(j)||u!=v.charAt(j+1));)++j;if(j+=2,f===v.charAt(j-1))return L("End of comment missing");var T=v.slice(2,j-2);return S+=2,P(T),v=v.slice(j),S+=2,F({type:m,comment:T})}}function R(){var F=z(),j=_(s);if(j){if(A(),!_(r))return L("property missing ':'");var T=_(i),$=F({type:h,property:x(j[0].replace(e,f)),value:T?x(T[0].replace(e,f)):f});return _(o),$}}function D(){var F=[];N(F);for(var j;j=R();)j!==!1&&(F.push(j),N(F));return F}return M(),D()}function x(v){return v?v.replace(a,f):f}return gr=g,gr}var No;function vp(){if(No)return $t;No=1;var e=$t&&$t.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty($t,"__esModule",{value:!0}),$t.default=n;const t=e(Sp());function n(s,r){let i=null;if(!s||typeof s!="string")return i;const o=(0,t.default)(s),a=typeof r=="function";return o.forEach(c=>{if(c.type!=="declaration")return;const{property:u,value:d}=c;a?r(u,d,c):d&&(i=i||{},i[u]=d)}),i}return $t}var on={},Io;function Cp(){if(Io)return on;Io=1,Object.defineProperty(on,"__esModule",{value:!0}),on.camelCase=void 0;var e=/^--[a-zA-Z0-9_-]+$/,t=/-([a-z])/g,n=/^[^-]+$/,s=/^-(webkit|moz|ms|o|khtml)-/,r=/^-(ms)-/,i=function(u){return!u||n.test(u)||e.test(u)},o=function(u,d){return d.toUpperCase()},a=function(u,d){return"".concat(d,"-")},c=function(u,d){return d===void 0&&(d={}),i(u)?u:(u=u.toLowerCase(),d.reactCompat?u=u.replace(r,a):u=u.replace(s,a),u.replace(t,o))};return on.camelCase=c,on}var an,jo;function kp(){if(jo)return an;jo=1;var e=an&&an.__importDefault||function(r){return r&&r.__esModule?r:{default:r}},t=e(vp()),n=Cp();function s(r,i){var o={};return!r||typeof r!="string"||(0,t.default)(r,function(a,c){a&&c&&(o[(0,n.camelCase)(a,i)]=c)}),o}return s.default=s,an=s,an}var Ep=kp();const Pp=Da(Ep),ol=al("end"),mi=al("start");function al(e){return t;function t(n){const s=n&&n.position&&n.position[e]||{};if(typeof s.line=="number"&&s.line>0&&typeof s.column=="number"&&s.column>0)return{line:s.line,column:s.column,offset:typeof s.offset=="number"&&s.offset>-1?s.offset:void 0}}}function Tp(e){const t=mi(e),n=ol(e);if(t&&n)return{start:t,end:n}}function hn(e){return!e||typeof e!="object"?"":"position"in e||"type"in e?Ao(e.position):"start"in e||"end"in e?Ao(e):"line"in e||"column"in e?qr(e):""}function qr(e){return zo(e&&e.line)+":"+zo(e&&e.column)}function Ao(e){return qr(e&&e.start)+"-"+qr(e&&e.end)}function zo(e){return e&&typeof e=="number"?e:1}class Ae extends Error{constructor(t,n,s){super(),typeof n=="string"&&(s=n,n=void 0);let r="",i={},o=!1;if(n&&("line"in n&&"column"in n?i={place:n}:"start"in n&&"end"in n?i={place:n}:"type"in n?i={ancestors:[n],place:n.position}:i={...n}),typeof t=="string"?r=t:!i.cause&&t&&(o=!0,r=t.message,i.cause=t),!i.ruleId&&!i.source&&typeof s=="string"){const c=s.indexOf(":");c===-1?i.ruleId=s:(i.source=s.slice(0,c),i.ruleId=s.slice(c+1))}if(!i.place&&i.ancestors&&i.ancestors){const c=i.ancestors[i.ancestors.length-1];c&&(i.place=c.position)}const a=i.place&&"start"in i.place?i.place.start:i.place;this.ancestors=i.ancestors||void 0,this.cause=i.cause||void 0,this.column=a?a.column:void 0,this.fatal=void 0,this.file="",this.message=r,this.line=a?a.line:void 0,this.name=hn(i.place)||"1:1",this.place=i.place||void 0,this.reason=this.message,this.ruleId=i.ruleId||void 0,this.source=i.source||void 0,this.stack=o&&i.cause&&typeof i.cause.stack=="string"?i.cause.stack:"",this.actual=void 0,this.expected=void 0,this.note=void 0,this.url=void 0}}Ae.prototype.file="";Ae.prototype.name="";Ae.prototype.reason="";Ae.prototype.message="";Ae.prototype.stack="";Ae.prototype.column=void 0;Ae.prototype.line=void 0;Ae.prototype.ancestors=void 0;Ae.prototype.cause=void 0;Ae.prototype.fatal=void 0;Ae.prototype.place=void 0;Ae.prototype.ruleId=void 0;Ae.prototype.source=void 0;const gi={}.hasOwnProperty,Np=new Map,Ip=/[A-Z]/g,jp=new Set(["table","tbody","thead","tfoot","tr"]),Ap=new Set(["td","th"]),ll="https://github.com/syntax-tree/hast-util-to-jsx-runtime";function zp(e,t){if(!t||t.Fragment===void 0)throw new TypeError("Expected `Fragment` in options");const n=t.filePath||void 0;let s;if(t.development){if(typeof t.jsxDEV!="function")throw new TypeError("Expected `jsxDEV` in options when `development: true`");s=Bp(n,t.jsxDEV)}else{if(typeof t.jsx!="function")throw new TypeError("Expected `jsx` in production options");if(typeof t.jsxs!="function")throw new TypeError("Expected `jsxs` in production options");s=Fp(n,t.jsx,t.jsxs)}const r={Fragment:t.Fragment,ancestors:[],components:t.components||{},create:s,elementAttributeNameCase:t.elementAttributeNameCase||"react",evaluater:t.createEvaluater?t.createEvaluater():void 0,filePath:n,ignoreInvalidStyle:t.ignoreInvalidStyle||!1,passKeys:t.passKeys!==!1,passNode:t.passNode||!1,schema:t.space==="svg"?pi:bp,stylePropertyNameCase:t.stylePropertyNameCase||"dom",tableCellAlignToStyle:t.tableCellAlignToStyle!==!1},i=cl(r,e,void 0);return i&&typeof i!="string"?i:r.create(e,r.Fragment,{children:i||void 0},void 0)}function cl(e,t,n){if(t.type==="element")return Lp(e,t,n);if(t.type==="mdxFlowExpression"||t.type==="mdxTextExpression")return _p(e,t);if(t.type==="mdxJsxFlowElement"||t.type==="mdxJsxTextElement")return Op(e,t,n);if(t.type==="mdxjsEsm")return Rp(e,t);if(t.type==="root")return Mp(e,t,n);if(t.type==="text")return Dp(e,t)}function Lp(e,t,n){const s=e.schema;let r=s;t.tagName.toLowerCase()==="svg"&&s.space==="html"&&(r=pi,e.schema=r),e.ancestors.push(t);const i=dl(e,t.tagName,!1),o=$p(e,t);let a=xi(e,t);return jp.has(t.tagName)&&(a=a.filter(function(c){return typeof c=="string"?!cp(c):!0})),ul(e,o,i,t),yi(o,a),e.ancestors.pop(),e.schema=s,e.create(t,i,o,n)}function _p(e,t){if(t.data&&t.data.estree&&e.evaluater){const s=t.data.estree.body[0];return s.type,e.evaluater.evaluateExpression(s.expression)}yn(e,t.position)}function Rp(e,t){if(t.data&&t.data.estree&&e.evaluater)return e.evaluater.evaluateProgram(t.data.estree);yn(e,t.position)}function Op(e,t,n){const s=e.schema;let r=s;t.name==="svg"&&s.space==="html"&&(r=pi,e.schema=r),e.ancestors.push(t);const i=t.name===null?e.Fragment:dl(e,t.name,!0),o=Vp(e,t),a=xi(e,t);return ul(e,o,i,t),yi(o,a),e.ancestors.pop(),e.schema=s,e.create(t,i,o,n)}function Mp(e,t,n){const s={};return yi(s,xi(e,t)),e.create(t,e.Fragment,s,n)}function Dp(e,t){return t.value}function ul(e,t,n,s){typeof n!="string"&&n!==e.Fragment&&e.passNode&&(t.node=s)}function yi(e,t){if(t.length>0){const n=t.length>1?t:t[0];n&&(e.children=n)}}function Fp(e,t,n){return s;function s(r,i,o,a){const u=Array.isArray(o.children)?n:t;return a?u(i,o,a):u(i,o)}}function Bp(e,t){return n;function n(s,r,i,o){const a=Array.isArray(i.children),c=mi(s);return t(r,i,o,a,{columnNumber:c?c.column-1:void 0,fileName:e,lineNumber:c?c.line:void 0},void 0)}}function $p(e,t){const n={};let s,r;for(r in t.properties)if(r!=="children"&&gi.call(t.properties,r)){const i=Up(e,r,t.properties[r]);if(i){const[o,a]=i;e.tableCellAlignToStyle&&o==="align"&&typeof a=="string"&&Ap.has(t.tagName)?s=a:n[o]=a}}if(s){const i=n.style||(n.style={});i[e.stylePropertyNameCase==="css"?"text-align":"textAlign"]=s}return n}function Vp(e,t){const n={};for(const s of t.attributes)if(s.type==="mdxJsxExpressionAttribute")if(s.data&&s.data.estree&&e.evaluater){const i=s.data.estree.body[0];i.type;const o=i.expression;o.type;const a=o.properties[0];a.type,Object.assign(n,e.evaluater.evaluateExpression(a.argument))}else yn(e,t.position);else{const r=s.name;let i;if(s.value&&typeof s.value=="object")if(s.value.data&&s.value.data.estree&&e.evaluater){const a=s.value.data.estree.body[0];a.type,i=e.evaluater.evaluateExpression(a.expression)}else yn(e,t.position);else i=s.value===null?!0:s.value;n[r]=i}return n}function xi(e,t){const n=[];let s=-1;const r=e.passKeys?new Map:Np;for(;++s<t.children.length;){const i=t.children[s];let o;if(e.passKeys){const c=i.type==="element"?i.tagName:i.type==="mdxJsxFlowElement"||i.type==="mdxJsxTextElement"?i.name:void 0;if(c){const u=r.get(c)||0;o=c+"-"+u,r.set(c,u+1)}}const a=cl(e,i,o);a!==void 0&&n.push(a)}return n}function Up(e,t,n){const s=gp(e.schema,t);if(!(n==null||typeof n=="number"&&Number.isNaN(n))){if(Array.isArray(n)&&(n=s.commaSeparated?rp(n):wp(n)),s.property==="style"){let r=typeof n=="object"?n:Wp(e,String(n));return e.stylePropertyNameCase==="css"&&(r=qp(r)),["style",r]}return[e.elementAttributeNameCase==="react"&&s.space?fp[s.property]||s.property:s.attribute,n]}}function Wp(e,t){try{return Pp(t,{reactCompat:!0})}catch(n){if(e.ignoreInvalidStyle)return{};const s=n,r=new Ae("Cannot parse `style` attribute",{ancestors:e.ancestors,cause:s,ruleId:"style",source:"hast-util-to-jsx-runtime"});throw r.file=e.filePath||void 0,r.url=ll+"#cannot-parse-style-attribute",r}}function dl(e,t,n){let s;if(!n)s={type:"Literal",value:t};else if(t.includes(".")){const r=t.split(".");let i=-1,o;for(;++i<r.length;){const a=Co(r[i])?{type:"Identifier",name:r[i]}:{type:"Literal",value:r[i]};o=o?{type:"MemberExpression",object:o,property:a,computed:!!(i&&a.type==="Literal"),optional:!1}:a}s=o}else s=Co(t)&&!/^[a-z]/.test(t)?{type:"Identifier",name:t}:{type:"Literal",value:t};if(s.type==="Literal"){const r=s.value;return gi.call(e.components,r)?e.components[r]:r}if(e.evaluater)return e.evaluater.evaluateExpression(s);yn(e)}function yn(e,t){const n=new Ae("Cannot handle MDX estrees without `createEvaluater`",{ancestors:e.ancestors,place:t,ruleId:"mdx-estree",source:"hast-util-to-jsx-runtime"});throw n.file=e.filePath||void 0,n.url=ll+"#cannot-handle-mdx-estrees-without-createevaluater",n}function qp(e){const t={};let n;for(n in e)gi.call(e,n)&&(t[Hp(n)]=e[n]);return t}function Hp(e){let t=e.replace(Ip,Gp);return t.slice(0,3)==="ms-"&&(t="-"+t),t}function Gp(e){return"-"+e.toLowerCase()}const yr={action:["form"],cite:["blockquote","del","ins","q"],data:["object"],formAction:["button","input"],href:["a","area","base","link"],icon:["menuitem"],itemId:null,manifest:["html"],ping:["a","area"],poster:["video"],src:["audio","embed","iframe","img","input","script","source","track","video"]},Qp={};function Jp(e,t){const n=Qp,s=typeof n.includeImageAlt=="boolean"?n.includeImageAlt:!0,r=typeof n.includeHtml=="boolean"?n.includeHtml:!0;return hl(e,s,r)}function hl(e,t,n){if(Zp(e)){if("value"in e)return e.type==="html"&&!n?"":e.value;if(t&&"alt"in e&&e.alt)return e.alt;if("children"in e)return Lo(e.children,t,n)}return Array.isArray(e)?Lo(e,t,n):""}function Lo(e,t,n){const s=[];let r=-1;for(;++r<e.length;)s[r]=hl(e[r],t,n);return s.join("")}function Zp(e){return!!(e&&typeof e=="object")}const _o=document.createElement("i");function bi(e){const t="&"+e+";";_o.innerHTML=t;const n=_o.textContent;return n.charCodeAt(n.length-1)===59&&e!=="semi"||n===t?!1:n}function ot(e,t,n,s){const r=e.length;let i=0,o;if(t<0?t=-t>r?0:r+t:t=t>r?r:t,n=n>0?n:0,s.length<1e4)o=Array.from(s),o.unshift(t,n),e.splice(...o);else for(n&&e.splice(t,n);i<s.length;)o=s.slice(i,i+1e4),o.unshift(t,0),e.splice(...o),i+=1e4,t+=1e4}function Qe(e,t){return e.length>0?(ot(e,e.length,0,t),e):t}const Ro={}.hasOwnProperty;function Yp(e){const t={};let n=-1;for(;++n<e.length;)Kp(t,e[n]);return t}function Kp(e,t){let n;for(n in t){const r=(Ro.call(e,n)?e[n]:void 0)||(e[n]={}),i=t[n];let o;if(i)for(o in i){Ro.call(r,o)||(r[o]=[]);const a=i[o];Xp(r[o],Array.isArray(a)?a:a?[a]:[])}}}function Xp(e,t){let n=-1;const s=[];for(;++n<t.length;)(t[n].add==="after"?e:s).push(t[n]);ot(e,0,0,s)}function fl(e,t){const n=Number.parseInt(e,t);return n<9||n===11||n>13&&n<32||n>126&&n<160||n>55295&&n<57344||n>64975&&n<65008||(n&65535)===65535||(n&65535)===65534||n>1114111?"�":String.fromCodePoint(n)}function Wt(e){return e.replace(/[\t\n\r ]+/g," ").replace(/^ | $/g,"").toLowerCase().toUpperCase()}const rt=Ct(/[A-Za-z]/),We=Ct(/[\dA-Za-z]/),em=Ct(/[#-'*+\--9=?A-Z^-~]/);function Hr(e){return e!==null&&(e<32||e===127)}const Gr=Ct(/\d/),tm=Ct(/[\dA-Fa-f]/),nm=Ct(/[!-/:-@[-`{-~]/);function Y(e){return e!==null&&e<-2}function Me(e){return e!==null&&(e<0||e===32)}function oe(e){return e===-2||e===-1||e===32}const sm=Ct(/\p{P}|\p{S}/u),rm=Ct(/\s/);function Ct(e){return t;function t(n){return n!==null&&n>-1&&e.test(String.fromCharCode(n))}}function Gt(e){const t=[];let n=-1,s=0,r=0;for(;++n<e.length;){const i=e.charCodeAt(n);let o="";if(i===37&&We(e.charCodeAt(n+1))&&We(e.charCodeAt(n+2)))r=2;else if(i<128)/[!#$&-;=?-Z_a-z~]/.test(String.fromCharCode(i))||(o=String.fromCharCode(i));else if(i>55295&&i<57344){const a=e.charCodeAt(n+1);i<56320&&a>56319&&a<57344?(o=String.fromCharCode(i,a),r=1):o="�"}else o=String.fromCharCode(i);o&&(t.push(e.slice(s,n),encodeURIComponent(o)),s=n+r+1,o=""),r&&(n+=r,r=0)}return t.join("")+e.slice(s)}function ue(e,t,n,s){const r=s?s-1:Number.POSITIVE_INFINITY;let i=0;return o;function o(c){return oe(c)?(e.enter(n),a(c)):t(c)}function a(c){return oe(c)&&i++<r?(e.consume(c),a):(e.exit(n),t(c))}}const im={tokenize:om};function om(e){const t=e.attempt(this.parser.constructs.contentInitial,s,r);let n;return t;function s(a){if(a===null){e.consume(a);return}return e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),ue(e,t,"linePrefix")}function r(a){return e.enter("paragraph"),i(a)}function i(a){const c=e.enter("chunkText",{contentType:"text",previous:n});return n&&(n.next=c),n=c,o(a)}function o(a){if(a===null){e.exit("chunkText"),e.exit("paragraph"),e.consume(a);return}return Y(a)?(e.consume(a),e.exit("chunkText"),i):(e.consume(a),o)}}const am={tokenize:lm},Oo={tokenize:cm};function lm(e){const t=this,n=[];let s=0,r,i,o;return a;function a(S){if(s<n.length){const P=n[s];return t.containerState=P[1],e.attempt(P[0].continuation,c,u)(S)}return u(S)}function c(S){if(s++,t.containerState._closeFlow){t.containerState._closeFlow=void 0,r&&I();const P=t.events.length;let z=P,E;for(;z--;)if(t.events[z][0]==="exit"&&t.events[z][1].type==="chunkFlow"){E=t.events[z][1].end;break}w(s);let L=P;for(;L<t.events.length;)t.events[L][1].end={...E},L++;return ot(t.events,z+1,0,t.events.slice(P)),t.events.length=L,u(S)}return a(S)}function u(S){if(s===n.length){if(!r)return m(S);if(r.currentConstruct&&r.currentConstruct.concrete)return g(S);t.interrupt=!!(r.currentConstruct&&!r._gfmTableDynamicInterruptHack)}return t.containerState={},e.check(Oo,d,f)(S)}function d(S){return r&&I(),w(s),m(S)}function f(S){return t.parser.lazy[t.now().line]=s!==n.length,o=t.now().offset,g(S)}function m(S){return t.containerState={},e.attempt(Oo,h,g)(S)}function h(S){return s++,n.push([t.currentConstruct,t.containerState]),m(S)}function g(S){if(S===null){r&&I(),w(0),e.consume(S);return}return r=r||t.parser.flow(t.now()),e.enter("chunkFlow",{_tokenizer:r,contentType:"flow",previous:i}),x(S)}function x(S){if(S===null){v(e.exit("chunkFlow"),!0),w(0),e.consume(S);return}return Y(S)?(e.consume(S),v(e.exit("chunkFlow")),s=0,t.interrupt=void 0,a):(e.consume(S),x)}function v(S,P){const z=t.sliceStream(S);if(P&&z.push(null),S.previous=i,i&&(i.next=S),i=S,r.defineSkip(S.start),r.write(z),t.parser.lazy[S.start.line]){let E=r.events.length;for(;E--;)if(r.events[E][1].start.offset<o&&(!r.events[E][1].end||r.events[E][1].end.offset>o))return;const L=t.events.length;let _=L,M,N;for(;_--;)if(t.events[_][0]==="exit"&&t.events[_][1].type==="chunkFlow"){if(M){N=t.events[_][1].end;break}M=!0}for(w(s),E=L;E<t.events.length;)t.events[E][1].end={...N},E++;ot(t.events,_+1,0,t.events.slice(L)),t.events.length=E}}function w(S){let P=n.length;for(;P-- >S;){const z=n[P];t.containerState=z[1],z[0].exit.call(t,e)}n.length=S}function I(){r.write([null]),i=void 0,r=void 0,t.containerState._closeFlow=void 0}}function cm(e,t,n){return ue(e,e.attempt(this.parser.constructs.document,t,n),"linePrefix",this.parser.constructs.disable.null.includes("codeIndented")?void 0:4)}function Mo(e){if(e===null||Me(e)||rm(e))return 1;if(sm(e))return 2}function wi(e,t,n){const s=[];let r=-1;for(;++r<e.length;){const i=e[r].resolveAll;i&&!s.includes(i)&&(t=i(t,n),s.push(i))}return t}const Qr={name:"attention",resolveAll:um,tokenize:dm};function um(e,t){let n=-1,s,r,i,o,a,c,u,d;for(;++n<e.length;)if(e[n][0]==="enter"&&e[n][1].type==="attentionSequence"&&e[n][1]._close){for(s=n;s--;)if(e[s][0]==="exit"&&e[s][1].type==="attentionSequence"&&e[s][1]._open&&t.sliceSerialize(e[s][1]).charCodeAt(0)===t.sliceSerialize(e[n][1]).charCodeAt(0)){if((e[s][1]._close||e[n][1]._open)&&(e[n][1].end.offset-e[n][1].start.offset)%3&&!((e[s][1].end.offset-e[s][1].start.offset+e[n][1].end.offset-e[n][1].start.offset)%3))continue;c=e[s][1].end.offset-e[s][1].start.offset>1&&e[n][1].end.offset-e[n][1].start.offset>1?2:1;const f={...e[s][1].end},m={...e[n][1].start};Do(f,-c),Do(m,c),o={type:c>1?"strongSequence":"emphasisSequence",start:f,end:{...e[s][1].end}},a={type:c>1?"strongSequence":"emphasisSequence",start:{...e[n][1].start},end:m},i={type:c>1?"strongText":"emphasisText",start:{...e[s][1].end},end:{...e[n][1].start}},r={type:c>1?"strong":"emphasis",start:{...o.start},end:{...a.end}},e[s][1].end={...o.start},e[n][1].start={...a.end},u=[],e[s][1].end.offset-e[s][1].start.offset&&(u=Qe(u,[["enter",e[s][1],t],["exit",e[s][1],t]])),u=Qe(u,[["enter",r,t],["enter",o,t],["exit",o,t],["enter",i,t]]),u=Qe(u,wi(t.parser.constructs.insideSpan.null,e.slice(s+1,n),t)),u=Qe(u,[["exit",i,t],["enter",a,t],["exit",a,t],["exit",r,t]]),e[n][1].end.offset-e[n][1].start.offset?(d=2,u=Qe(u,[["enter",e[n][1],t],["exit",e[n][1],t]])):d=0,ot(e,s-1,n-s+3,u),n=s+u.length-d-2;break}}for(n=-1;++n<e.length;)e[n][1].type==="attentionSequence"&&(e[n][1].type="data");return e}function dm(e,t){const n=this.parser.constructs.attentionMarkers.null,s=this.previous,r=Mo(s);let i;return o;function o(c){return i=c,e.enter("attentionSequence"),a(c)}function a(c){if(c===i)return e.consume(c),a;const u=e.exit("attentionSequence"),d=Mo(c),f=!d||d===2&&r||n.includes(c),m=!r||r===2&&d||n.includes(s);return u._open=!!(i===42?f:f&&(r||!m)),u._close=!!(i===42?m:m&&(d||!f)),t(c)}}function Do(e,t){e.column+=t,e.offset+=t,e._bufferIndex+=t}const hm={name:"autolink",tokenize:fm};function fm(e,t,n){let s=0;return r;function r(h){return e.enter("autolink"),e.enter("autolinkMarker"),e.consume(h),e.exit("autolinkMarker"),e.enter("autolinkProtocol"),i}function i(h){return rt(h)?(e.consume(h),o):h===64?n(h):u(h)}function o(h){return h===43||h===45||h===46||We(h)?(s=1,a(h)):u(h)}function a(h){return h===58?(e.consume(h),s=0,c):(h===43||h===45||h===46||We(h))&&s++<32?(e.consume(h),a):(s=0,u(h))}function c(h){return h===62?(e.exit("autolinkProtocol"),e.enter("autolinkMarker"),e.consume(h),e.exit("autolinkMarker"),e.exit("autolink"),t):h===null||h===32||h===60||Hr(h)?n(h):(e.consume(h),c)}function u(h){return h===64?(e.consume(h),d):em(h)?(e.consume(h),u):n(h)}function d(h){return We(h)?f(h):n(h)}function f(h){return h===46?(e.consume(h),s=0,d):h===62?(e.exit("autolinkProtocol").type="autolinkEmail",e.enter("autolinkMarker"),e.consume(h),e.exit("autolinkMarker"),e.exit("autolink"),t):m(h)}function m(h){if((h===45||We(h))&&s++<63){const g=h===45?m:f;return e.consume(h),g}return n(h)}}const us={partial:!0,tokenize:pm};function pm(e,t,n){return s;function s(i){return oe(i)?ue(e,r,"linePrefix")(i):r(i)}function r(i){return i===null||Y(i)?t(i):n(i)}}const pl={continuation:{tokenize:gm},exit:ym,name:"blockQuote",tokenize:mm};function mm(e,t,n){const s=this;return r;function r(o){if(o===62){const a=s.containerState;return a.open||(e.enter("blockQuote",{_container:!0}),a.open=!0),e.enter("blockQuotePrefix"),e.enter("blockQuoteMarker"),e.consume(o),e.exit("blockQuoteMarker"),i}return n(o)}function i(o){return oe(o)?(e.enter("blockQuotePrefixWhitespace"),e.consume(o),e.exit("blockQuotePrefixWhitespace"),e.exit("blockQuotePrefix"),t):(e.exit("blockQuotePrefix"),t(o))}}function gm(e,t,n){const s=this;return r;function r(o){return oe(o)?ue(e,i,"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(o):i(o)}function i(o){return e.attempt(pl,t,n)(o)}}function ym(e){e.exit("blockQuote")}const ml={name:"characterEscape",tokenize:xm};function xm(e,t,n){return s;function s(i){return e.enter("characterEscape"),e.enter("escapeMarker"),e.consume(i),e.exit("escapeMarker"),r}function r(i){return nm(i)?(e.enter("characterEscapeValue"),e.consume(i),e.exit("characterEscapeValue"),e.exit("characterEscape"),t):n(i)}}const gl={name:"characterReference",tokenize:bm};function bm(e,t,n){const s=this;let r=0,i,o;return a;function a(f){return e.enter("characterReference"),e.enter("characterReferenceMarker"),e.consume(f),e.exit("characterReferenceMarker"),c}function c(f){return f===35?(e.enter("characterReferenceMarkerNumeric"),e.consume(f),e.exit("characterReferenceMarkerNumeric"),u):(e.enter("characterReferenceValue"),i=31,o=We,d(f))}function u(f){return f===88||f===120?(e.enter("characterReferenceMarkerHexadecimal"),e.consume(f),e.exit("characterReferenceMarkerHexadecimal"),e.enter("characterReferenceValue"),i=6,o=tm,d):(e.enter("characterReferenceValue"),i=7,o=Gr,d(f))}function d(f){if(f===59&&r){const m=e.exit("characterReferenceValue");return o===We&&!bi(s.sliceSerialize(m))?n(f):(e.enter("characterReferenceMarker"),e.consume(f),e.exit("characterReferenceMarker"),e.exit("characterReference"),t)}return o(f)&&r++<i?(e.consume(f),d):n(f)}}const Fo={partial:!0,tokenize:Sm},Bo={concrete:!0,name:"codeFenced",tokenize:wm};function wm(e,t,n){const s=this,r={partial:!0,tokenize:z};let i=0,o=0,a;return c;function c(E){return u(E)}function u(E){const L=s.events[s.events.length-1];return i=L&&L[1].type==="linePrefix"?L[2].sliceSerialize(L[1],!0).length:0,a=E,e.enter("codeFenced"),e.enter("codeFencedFence"),e.enter("codeFencedFenceSequence"),d(E)}function d(E){return E===a?(o++,e.consume(E),d):o<3?n(E):(e.exit("codeFencedFenceSequence"),oe(E)?ue(e,f,"whitespace")(E):f(E))}function f(E){return E===null||Y(E)?(e.exit("codeFencedFence"),s.interrupt?t(E):e.check(Fo,x,P)(E)):(e.enter("codeFencedFenceInfo"),e.enter("chunkString",{contentType:"string"}),m(E))}function m(E){return E===null||Y(E)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),f(E)):oe(E)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),ue(e,h,"whitespace")(E)):E===96&&E===a?n(E):(e.consume(E),m)}function h(E){return E===null||Y(E)?f(E):(e.enter("codeFencedFenceMeta"),e.enter("chunkString",{contentType:"string"}),g(E))}function g(E){return E===null||Y(E)?(e.exit("chunkString"),e.exit("codeFencedFenceMeta"),f(E)):E===96&&E===a?n(E):(e.consume(E),g)}function x(E){return e.attempt(r,P,v)(E)}function v(E){return e.enter("lineEnding"),e.consume(E),e.exit("lineEnding"),w}function w(E){return i>0&&oe(E)?ue(e,I,"linePrefix",i+1)(E):I(E)}function I(E){return E===null||Y(E)?e.check(Fo,x,P)(E):(e.enter("codeFlowValue"),S(E))}function S(E){return E===null||Y(E)?(e.exit("codeFlowValue"),I(E)):(e.consume(E),S)}function P(E){return e.exit("codeFenced"),t(E)}function z(E,L,_){let M=0;return N;function N(j){return E.enter("lineEnding"),E.consume(j),E.exit("lineEnding"),A}function A(j){return E.enter("codeFencedFence"),oe(j)?ue(E,R,"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(j):R(j)}function R(j){return j===a?(E.enter("codeFencedFenceSequence"),D(j)):_(j)}function D(j){return j===a?(M++,E.consume(j),D):M>=o?(E.exit("codeFencedFenceSequence"),oe(j)?ue(E,F,"whitespace")(j):F(j)):_(j)}function F(j){return j===null||Y(j)?(E.exit("codeFencedFence"),L(j)):_(j)}}}function Sm(e,t,n){const s=this;return r;function r(o){return o===null?n(o):(e.enter("lineEnding"),e.consume(o),e.exit("lineEnding"),i)}function i(o){return s.parser.lazy[s.now().line]?n(o):t(o)}}const xr={name:"codeIndented",tokenize:Cm},vm={partial:!0,tokenize:km};function Cm(e,t,n){const s=this;return r;function r(u){return e.enter("codeIndented"),ue(e,i,"linePrefix",5)(u)}function i(u){const d=s.events[s.events.length-1];return d&&d[1].type==="linePrefix"&&d[2].sliceSerialize(d[1],!0).length>=4?o(u):n(u)}function o(u){return u===null?c(u):Y(u)?e.attempt(vm,o,c)(u):(e.enter("codeFlowValue"),a(u))}function a(u){return u===null||Y(u)?(e.exit("codeFlowValue"),o(u)):(e.consume(u),a)}function c(u){return e.exit("codeIndented"),t(u)}}function km(e,t,n){const s=this;return r;function r(o){return s.parser.lazy[s.now().line]?n(o):Y(o)?(e.enter("lineEnding"),e.consume(o),e.exit("lineEnding"),r):ue(e,i,"linePrefix",5)(o)}function i(o){const a=s.events[s.events.length-1];return a&&a[1].type==="linePrefix"&&a[2].sliceSerialize(a[1],!0).length>=4?t(o):Y(o)?r(o):n(o)}}const Em={name:"codeText",previous:Tm,resolve:Pm,tokenize:Nm};function Pm(e){let t=e.length-4,n=3,s,r;if((e[n][1].type==="lineEnding"||e[n][1].type==="space")&&(e[t][1].type==="lineEnding"||e[t][1].type==="space")){for(s=n;++s<t;)if(e[s][1].type==="codeTextData"){e[n][1].type="codeTextPadding",e[t][1].type="codeTextPadding",n+=2,t-=2;break}}for(s=n-1,t++;++s<=t;)r===void 0?s!==t&&e[s][1].type!=="lineEnding"&&(r=s):(s===t||e[s][1].type==="lineEnding")&&(e[r][1].type="codeTextData",s!==r+2&&(e[r][1].end=e[s-1][1].end,e.splice(r+2,s-r-2),t-=s-r-2,s=r+2),r=void 0);return e}function Tm(e){return e!==96||this.events[this.events.length-1][1].type==="characterEscape"}function Nm(e,t,n){let s=0,r,i;return o;function o(f){return e.enter("codeText"),e.enter("codeTextSequence"),a(f)}function a(f){return f===96?(e.consume(f),s++,a):(e.exit("codeTextSequence"),c(f))}function c(f){return f===null?n(f):f===32?(e.enter("space"),e.consume(f),e.exit("space"),c):f===96?(i=e.enter("codeTextSequence"),r=0,d(f)):Y(f)?(e.enter("lineEnding"),e.consume(f),e.exit("lineEnding"),c):(e.enter("codeTextData"),u(f))}function u(f){return f===null||f===32||f===96||Y(f)?(e.exit("codeTextData"),c(f)):(e.consume(f),u)}function d(f){return f===96?(e.consume(f),r++,d):r===s?(e.exit("codeTextSequence"),e.exit("codeText"),t(f)):(i.type="codeTextData",u(f))}}class Im{constructor(t){this.left=t?[...t]:[],this.right=[]}get(t){if(t<0||t>=this.left.length+this.right.length)throw new RangeError("Cannot access index `"+t+"` in a splice buffer of size `"+(this.left.length+this.right.length)+"`");return t<this.left.length?this.left[t]:this.right[this.right.length-t+this.left.length-1]}get length(){return this.left.length+this.right.length}shift(){return this.setCursor(0),this.right.pop()}slice(t,n){const s=n??Number.POSITIVE_INFINITY;return s<this.left.length?this.left.slice(t,s):t>this.left.length?this.right.slice(this.right.length-s+this.left.length,this.right.length-t+this.left.length).reverse():this.left.slice(t).concat(this.right.slice(this.right.length-s+this.left.length).reverse())}splice(t,n,s){const r=n||0;this.setCursor(Math.trunc(t));const i=this.right.splice(this.right.length-r,Number.POSITIVE_INFINITY);return s&&ln(this.left,s),i.reverse()}pop(){return this.setCursor(Number.POSITIVE_INFINITY),this.left.pop()}push(t){this.setCursor(Number.POSITIVE_INFINITY),this.left.push(t)}pushMany(t){this.setCursor(Number.POSITIVE_INFINITY),ln(this.left,t)}unshift(t){this.setCursor(0),this.right.push(t)}unshiftMany(t){this.setCursor(0),ln(this.right,t.reverse())}setCursor(t){if(!(t===this.left.length||t>this.left.length&&this.right.length===0||t<0&&this.left.length===0))if(t<this.left.length){const n=this.left.splice(t,Number.POSITIVE_INFINITY);ln(this.right,n.reverse())}else{const n=this.right.splice(this.left.length+this.right.length-t,Number.POSITIVE_INFINITY);ln(this.left,n.reverse())}}}function ln(e,t){let n=0;if(t.length<1e4)e.push(...t);else for(;n<t.length;)e.push(...t.slice(n,n+1e4)),n+=1e4}function yl(e){const t={};let n=-1,s,r,i,o,a,c,u;const d=new Im(e);for(;++n<d.length;){for(;n in t;)n=t[n];if(s=d.get(n),n&&s[1].type==="chunkFlow"&&d.get(n-1)[1].type==="listItemPrefix"&&(c=s[1]._tokenizer.events,i=0,i<c.length&&c[i][1].type==="lineEndingBlank"&&(i+=2),i<c.length&&c[i][1].type==="content"))for(;++i<c.length&&c[i][1].type!=="content";)c[i][1].type==="chunkText"&&(c[i][1]._isInFirstContentOfListItem=!0,i++);if(s[0]==="enter")s[1].contentType&&(Object.assign(t,jm(d,n)),n=t[n],u=!0);else if(s[1]._container){for(i=n,r=void 0;i--;)if(o=d.get(i),o[1].type==="lineEnding"||o[1].type==="lineEndingBlank")o[0]==="enter"&&(r&&(d.get(r)[1].type="lineEndingBlank"),o[1].type="lineEnding",r=i);else if(!(o[1].type==="linePrefix"||o[1].type==="listItemIndent"))break;r&&(s[1].end={...d.get(r)[1].start},a=d.slice(r,n),a.unshift(s),d.splice(r,n-r+1,a))}}return ot(e,0,Number.POSITIVE_INFINITY,d.slice(0)),!u}function jm(e,t){const n=e.get(t)[1],s=e.get(t)[2];let r=t-1;const i=[];let o=n._tokenizer;o||(o=s.parser[n.contentType](n.start),n._contentTypeTextTrailing&&(o._contentTypeTextTrailing=!0));const a=o.events,c=[],u={};let d,f,m=-1,h=n,g=0,x=0;const v=[x];for(;h;){for(;e.get(++r)[1]!==h;);i.push(r),h._tokenizer||(d=s.sliceStream(h),h.next||d.push(null),f&&o.defineSkip(h.start),h._isInFirstContentOfListItem&&(o._gfmTasklistFirstContentOfListItem=!0),o.write(d),h._isInFirstContentOfListItem&&(o._gfmTasklistFirstContentOfListItem=void 0)),f=h,h=h.next}for(h=n;++m<a.length;)a[m][0]==="exit"&&a[m-1][0]==="enter"&&a[m][1].type===a[m-1][1].type&&a[m][1].start.line!==a[m][1].end.line&&(x=m+1,v.push(x),h._tokenizer=void 0,h.previous=void 0,h=h.next);for(o.events=[],h?(h._tokenizer=void 0,h.previous=void 0):v.pop(),m=v.length;m--;){const w=a.slice(v[m],v[m+1]),I=i.pop();c.push([I,I+w.length-1]),e.splice(I,2,w)}for(c.reverse(),m=-1;++m<c.length;)u[g+c[m][0]]=g+c[m][1],g+=c[m][1]-c[m][0]-1;return u}const Am={resolve:Lm,tokenize:_m},zm={partial:!0,tokenize:Rm};function Lm(e){return yl(e),e}function _m(e,t){let n;return s;function s(a){return e.enter("content"),n=e.enter("chunkContent",{contentType:"content"}),r(a)}function r(a){return a===null?i(a):Y(a)?e.check(zm,o,i)(a):(e.consume(a),r)}function i(a){return e.exit("chunkContent"),e.exit("content"),t(a)}function o(a){return e.consume(a),e.exit("chunkContent"),n.next=e.enter("chunkContent",{contentType:"content",previous:n}),n=n.next,r}}function Rm(e,t,n){const s=this;return r;function r(o){return e.exit("chunkContent"),e.enter("lineEnding"),e.consume(o),e.exit("lineEnding"),ue(e,i,"linePrefix")}function i(o){if(o===null||Y(o))return n(o);const a=s.events[s.events.length-1];return!s.parser.constructs.disable.null.includes("codeIndented")&&a&&a[1].type==="linePrefix"&&a[2].sliceSerialize(a[1],!0).length>=4?t(o):e.interrupt(s.parser.constructs.flow,n,t)(o)}}function xl(e,t,n,s,r,i,o,a,c){const u=c||Number.POSITIVE_INFINITY;let d=0;return f;function f(w){return w===60?(e.enter(s),e.enter(r),e.enter(i),e.consume(w),e.exit(i),m):w===null||w===32||w===41||Hr(w)?n(w):(e.enter(s),e.enter(o),e.enter(a),e.enter("chunkString",{contentType:"string"}),x(w))}function m(w){return w===62?(e.enter(i),e.consume(w),e.exit(i),e.exit(r),e.exit(s),t):(e.enter(a),e.enter("chunkString",{contentType:"string"}),h(w))}function h(w){return w===62?(e.exit("chunkString"),e.exit(a),m(w)):w===null||w===60||Y(w)?n(w):(e.consume(w),w===92?g:h)}function g(w){return w===60||w===62||w===92?(e.consume(w),h):h(w)}function x(w){return!d&&(w===null||w===41||Me(w))?(e.exit("chunkString"),e.exit(a),e.exit(o),e.exit(s),t(w)):d<u&&w===40?(e.consume(w),d++,x):w===41?(e.consume(w),d--,x):w===null||w===32||w===40||Hr(w)?n(w):(e.consume(w),w===92?v:x)}function v(w){return w===40||w===41||w===92?(e.consume(w),x):x(w)}}function bl(e,t,n,s,r,i){const o=this;let a=0,c;return u;function u(h){return e.enter(s),e.enter(r),e.consume(h),e.exit(r),e.enter(i),d}function d(h){return a>999||h===null||h===91||h===93&&!c||h===94&&!a&&"_hiddenFootnoteSupport"in o.parser.constructs?n(h):h===93?(e.exit(i),e.enter(r),e.consume(h),e.exit(r),e.exit(s),t):Y(h)?(e.enter("lineEnding"),e.consume(h),e.exit("lineEnding"),d):(e.enter("chunkString",{contentType:"string"}),f(h))}function f(h){return h===null||h===91||h===93||Y(h)||a++>999?(e.exit("chunkString"),d(h)):(e.consume(h),c||(c=!oe(h)),h===92?m:f)}function m(h){return h===91||h===92||h===93?(e.consume(h),a++,f):f(h)}}function wl(e,t,n,s,r,i){let o;return a;function a(m){return m===34||m===39||m===40?(e.enter(s),e.enter(r),e.consume(m),e.exit(r),o=m===40?41:m,c):n(m)}function c(m){return m===o?(e.enter(r),e.consume(m),e.exit(r),e.exit(s),t):(e.enter(i),u(m))}function u(m){return m===o?(e.exit(i),c(o)):m===null?n(m):Y(m)?(e.enter("lineEnding"),e.consume(m),e.exit("lineEnding"),ue(e,u,"linePrefix")):(e.enter("chunkString",{contentType:"string"}),d(m))}function d(m){return m===o||m===null||Y(m)?(e.exit("chunkString"),u(m)):(e.consume(m),m===92?f:d)}function f(m){return m===o||m===92?(e.consume(m),d):d(m)}}function fn(e,t){let n;return s;function s(r){return Y(r)?(e.enter("lineEnding"),e.consume(r),e.exit("lineEnding"),n=!0,s):oe(r)?ue(e,s,n?"linePrefix":"lineSuffix")(r):t(r)}}const Om={name:"definition",tokenize:Dm},Mm={partial:!0,tokenize:Fm};function Dm(e,t,n){const s=this;let r;return i;function i(h){return e.enter("definition"),o(h)}function o(h){return bl.call(s,e,a,n,"definitionLabel","definitionLabelMarker","definitionLabelString")(h)}function a(h){return r=Wt(s.sliceSerialize(s.events[s.events.length-1][1]).slice(1,-1)),h===58?(e.enter("definitionMarker"),e.consume(h),e.exit("definitionMarker"),c):n(h)}function c(h){return Me(h)?fn(e,u)(h):u(h)}function u(h){return xl(e,d,n,"definitionDestination","definitionDestinationLiteral","definitionDestinationLiteralMarker","definitionDestinationRaw","definitionDestinationString")(h)}function d(h){return e.attempt(Mm,f,f)(h)}function f(h){return oe(h)?ue(e,m,"whitespace")(h):m(h)}function m(h){return h===null||Y(h)?(e.exit("definition"),s.parser.defined.push(r),t(h)):n(h)}}function Fm(e,t,n){return s;function s(a){return Me(a)?fn(e,r)(a):n(a)}function r(a){return wl(e,i,n,"definitionTitle","definitionTitleMarker","definitionTitleString")(a)}function i(a){return oe(a)?ue(e,o,"whitespace")(a):o(a)}function o(a){return a===null||Y(a)?t(a):n(a)}}const Bm={name:"hardBreakEscape",tokenize:$m};function $m(e,t,n){return s;function s(i){return e.enter("hardBreakEscape"),e.consume(i),r}function r(i){return Y(i)?(e.exit("hardBreakEscape"),t(i)):n(i)}}const Vm={name:"headingAtx",resolve:Um,tokenize:Wm};function Um(e,t){let n=e.length-2,s=3,r,i;return e[s][1].type==="whitespace"&&(s+=2),n-2>s&&e[n][1].type==="whitespace"&&(n-=2),e[n][1].type==="atxHeadingSequence"&&(s===n-1||n-4>s&&e[n-2][1].type==="whitespace")&&(n-=s+1===n?2:4),n>s&&(r={type:"atxHeadingText",start:e[s][1].start,end:e[n][1].end},i={type:"chunkText",start:e[s][1].start,end:e[n][1].end,contentType:"text"},ot(e,s,n-s+1,[["enter",r,t],["enter",i,t],["exit",i,t],["exit",r,t]])),e}function Wm(e,t,n){let s=0;return r;function r(d){return e.enter("atxHeading"),i(d)}function i(d){return e.enter("atxHeadingSequence"),o(d)}function o(d){return d===35&&s++<6?(e.consume(d),o):d===null||Me(d)?(e.exit("atxHeadingSequence"),a(d)):n(d)}function a(d){return d===35?(e.enter("atxHeadingSequence"),c(d)):d===null||Y(d)?(e.exit("atxHeading"),t(d)):oe(d)?ue(e,a,"whitespace")(d):(e.enter("atxHeadingText"),u(d))}function c(d){return d===35?(e.consume(d),c):(e.exit("atxHeadingSequence"),a(d))}function u(d){return d===null||d===35||Me(d)?(e.exit("atxHeadingText"),a(d)):(e.consume(d),u)}}const qm=["address","article","aside","base","basefont","blockquote","body","caption","center","col","colgroup","dd","details","dialog","dir","div","dl","dt","fieldset","figcaption","figure","footer","form","frame","frameset","h1","h2","h3","h4","h5","h6","head","header","hr","html","iframe","legend","li","link","main","menu","menuitem","nav","noframes","ol","optgroup","option","p","param","search","section","summary","table","tbody","td","tfoot","th","thead","title","tr","track","ul"],$o=["pre","script","style","textarea"],Hm={concrete:!0,name:"htmlFlow",resolveTo:Jm,tokenize:Zm},Gm={partial:!0,tokenize:Km},Qm={partial:!0,tokenize:Ym};function Jm(e){let t=e.length;for(;t--&&!(e[t][0]==="enter"&&e[t][1].type==="htmlFlow"););return t>1&&e[t-2][1].type==="linePrefix"&&(e[t][1].start=e[t-2][1].start,e[t+1][1].start=e[t-2][1].start,e.splice(t-2,2)),e}function Zm(e,t,n){const s=this;let r,i,o,a,c;return u;function u(b){return d(b)}function d(b){return e.enter("htmlFlow"),e.enter("htmlFlowData"),e.consume(b),f}function f(b){return b===33?(e.consume(b),m):b===47?(e.consume(b),i=!0,x):b===63?(e.consume(b),r=3,s.interrupt?t:y):rt(b)?(e.consume(b),o=String.fromCharCode(b),v):n(b)}function m(b){return b===45?(e.consume(b),r=2,h):b===91?(e.consume(b),r=5,a=0,g):rt(b)?(e.consume(b),r=4,s.interrupt?t:y):n(b)}function h(b){return b===45?(e.consume(b),s.interrupt?t:y):n(b)}function g(b){const q="CDATA[";return b===q.charCodeAt(a++)?(e.consume(b),a===q.length?s.interrupt?t:R:g):n(b)}function x(b){return rt(b)?(e.consume(b),o=String.fromCharCode(b),v):n(b)}function v(b){if(b===null||b===47||b===62||Me(b)){const q=b===47,ee=o.toLowerCase();return!q&&!i&&$o.includes(ee)?(r=1,s.interrupt?t(b):R(b)):qm.includes(o.toLowerCase())?(r=6,q?(e.consume(b),w):s.interrupt?t(b):R(b)):(r=7,s.interrupt&&!s.parser.lazy[s.now().line]?n(b):i?I(b):S(b))}return b===45||We(b)?(e.consume(b),o+=String.fromCharCode(b),v):n(b)}function w(b){return b===62?(e.consume(b),s.interrupt?t:R):n(b)}function I(b){return oe(b)?(e.consume(b),I):N(b)}function S(b){return b===47?(e.consume(b),N):b===58||b===95||rt(b)?(e.consume(b),P):oe(b)?(e.consume(b),S):N(b)}function P(b){return b===45||b===46||b===58||b===95||We(b)?(e.consume(b),P):z(b)}function z(b){return b===61?(e.consume(b),E):oe(b)?(e.consume(b),z):S(b)}function E(b){return b===null||b===60||b===61||b===62||b===96?n(b):b===34||b===39?(e.consume(b),c=b,L):oe(b)?(e.consume(b),E):_(b)}function L(b){return b===c?(e.consume(b),c=null,M):b===null||Y(b)?n(b):(e.consume(b),L)}function _(b){return b===null||b===34||b===39||b===47||b===60||b===61||b===62||b===96||Me(b)?z(b):(e.consume(b),_)}function M(b){return b===47||b===62||oe(b)?S(b):n(b)}function N(b){return b===62?(e.consume(b),A):n(b)}function A(b){return b===null||Y(b)?R(b):oe(b)?(e.consume(b),A):n(b)}function R(b){return b===45&&r===2?(e.consume(b),T):b===60&&r===1?(e.consume(b),$):b===62&&r===4?(e.consume(b),te):b===63&&r===3?(e.consume(b),y):b===93&&r===5?(e.consume(b),B):Y(b)&&(r===6||r===7)?(e.exit("htmlFlowData"),e.check(Gm,ae,D)(b)):b===null||Y(b)?(e.exit("htmlFlowData"),D(b)):(e.consume(b),R)}function D(b){return e.check(Qm,F,ae)(b)}function F(b){return e.enter("lineEnding"),e.consume(b),e.exit("lineEnding"),j}function j(b){return b===null||Y(b)?D(b):(e.enter("htmlFlowData"),R(b))}function T(b){return b===45?(e.consume(b),y):R(b)}function $(b){return b===47?(e.consume(b),o="",k):R(b)}function k(b){if(b===62){const q=o.toLowerCase();return $o.includes(q)?(e.consume(b),te):R(b)}return rt(b)&&o.length<8?(e.consume(b),o+=String.fromCharCode(b),k):R(b)}function B(b){return b===93?(e.consume(b),y):R(b)}function y(b){return b===62?(e.consume(b),te):b===45&&r===2?(e.consume(b),y):R(b)}function te(b){return b===null||Y(b)?(e.exit("htmlFlowData"),ae(b)):(e.consume(b),te)}function ae(b){return e.exit("htmlFlow"),t(b)}}function Ym(e,t,n){const s=this;return r;function r(o){return Y(o)?(e.enter("lineEnding"),e.consume(o),e.exit("lineEnding"),i):n(o)}function i(o){return s.parser.lazy[s.now().line]?n(o):t(o)}}function Km(e,t,n){return s;function s(r){return e.enter("lineEnding"),e.consume(r),e.exit("lineEnding"),e.attempt(us,t,n)}}const Xm={name:"htmlText",tokenize:eg};function eg(e,t,n){const s=this;let r,i,o;return a;function a(y){return e.enter("htmlText"),e.enter("htmlTextData"),e.consume(y),c}function c(y){return y===33?(e.consume(y),u):y===47?(e.consume(y),z):y===63?(e.consume(y),S):rt(y)?(e.consume(y),_):n(y)}function u(y){return y===45?(e.consume(y),d):y===91?(e.consume(y),i=0,g):rt(y)?(e.consume(y),I):n(y)}function d(y){return y===45?(e.consume(y),h):n(y)}function f(y){return y===null?n(y):y===45?(e.consume(y),m):Y(y)?(o=f,$(y)):(e.consume(y),f)}function m(y){return y===45?(e.consume(y),h):f(y)}function h(y){return y===62?T(y):y===45?m(y):f(y)}function g(y){const te="CDATA[";return y===te.charCodeAt(i++)?(e.consume(y),i===te.length?x:g):n(y)}function x(y){return y===null?n(y):y===93?(e.consume(y),v):Y(y)?(o=x,$(y)):(e.consume(y),x)}function v(y){return y===93?(e.consume(y),w):x(y)}function w(y){return y===62?T(y):y===93?(e.consume(y),w):x(y)}function I(y){return y===null||y===62?T(y):Y(y)?(o=I,$(y)):(e.consume(y),I)}function S(y){return y===null?n(y):y===63?(e.consume(y),P):Y(y)?(o=S,$(y)):(e.consume(y),S)}function P(y){return y===62?T(y):S(y)}function z(y){return rt(y)?(e.consume(y),E):n(y)}function E(y){return y===45||We(y)?(e.consume(y),E):L(y)}function L(y){return Y(y)?(o=L,$(y)):oe(y)?(e.consume(y),L):T(y)}function _(y){return y===45||We(y)?(e.consume(y),_):y===47||y===62||Me(y)?M(y):n(y)}function M(y){return y===47?(e.consume(y),T):y===58||y===95||rt(y)?(e.consume(y),N):Y(y)?(o=M,$(y)):oe(y)?(e.consume(y),M):T(y)}function N(y){return y===45||y===46||y===58||y===95||We(y)?(e.consume(y),N):A(y)}function A(y){return y===61?(e.consume(y),R):Y(y)?(o=A,$(y)):oe(y)?(e.consume(y),A):M(y)}function R(y){return y===null||y===60||y===61||y===62||y===96?n(y):y===34||y===39?(e.consume(y),r=y,D):Y(y)?(o=R,$(y)):oe(y)?(e.consume(y),R):(e.consume(y),F)}function D(y){return y===r?(e.consume(y),r=void 0,j):y===null?n(y):Y(y)?(o=D,$(y)):(e.consume(y),D)}function F(y){return y===null||y===34||y===39||y===60||y===61||y===96?n(y):y===47||y===62||Me(y)?M(y):(e.consume(y),F)}function j(y){return y===47||y===62||Me(y)?M(y):n(y)}function T(y){return y===62?(e.consume(y),e.exit("htmlTextData"),e.exit("htmlText"),t):n(y)}function $(y){return e.exit("htmlTextData"),e.enter("lineEnding"),e.consume(y),e.exit("lineEnding"),k}function k(y){return oe(y)?ue(e,B,"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(y):B(y)}function B(y){return e.enter("htmlTextData"),o(y)}}const Si={name:"labelEnd",resolveAll:rg,resolveTo:ig,tokenize:og},tg={tokenize:ag},ng={tokenize:lg},sg={tokenize:cg};function rg(e){let t=-1;const n=[];for(;++t<e.length;){const s=e[t][1];if(n.push(e[t]),s.type==="labelImage"||s.type==="labelLink"||s.type==="labelEnd"){const r=s.type==="labelImage"?4:2;s.type="data",t+=r}}return e.length!==n.length&&ot(e,0,e.length,n),e}function ig(e,t){let n=e.length,s=0,r,i,o,a;for(;n--;)if(r=e[n][1],i){if(r.type==="link"||r.type==="labelLink"&&r._inactive)break;e[n][0]==="enter"&&r.type==="labelLink"&&(r._inactive=!0)}else if(o){if(e[n][0]==="enter"&&(r.type==="labelImage"||r.type==="labelLink")&&!r._balanced&&(i=n,r.type!=="labelLink")){s=2;break}}else r.type==="labelEnd"&&(o=n);const c={type:e[i][1].type==="labelLink"?"link":"image",start:{...e[i][1].start},end:{...e[e.length-1][1].end}},u={type:"label",start:{...e[i][1].start},end:{...e[o][1].end}},d={type:"labelText",start:{...e[i+s+2][1].end},end:{...e[o-2][1].start}};return a=[["enter",c,t],["enter",u,t]],a=Qe(a,e.slice(i+1,i+s+3)),a=Qe(a,[["enter",d,t]]),a=Qe(a,wi(t.parser.constructs.insideSpan.null,e.slice(i+s+4,o-3),t)),a=Qe(a,[["exit",d,t],e[o-2],e[o-1],["exit",u,t]]),a=Qe(a,e.slice(o+1)),a=Qe(a,[["exit",c,t]]),ot(e,i,e.length,a),e}function og(e,t,n){const s=this;let r=s.events.length,i,o;for(;r--;)if((s.events[r][1].type==="labelImage"||s.events[r][1].type==="labelLink")&&!s.events[r][1]._balanced){i=s.events[r][1];break}return a;function a(m){return i?i._inactive?f(m):(o=s.parser.defined.includes(Wt(s.sliceSerialize({start:i.end,end:s.now()}))),e.enter("labelEnd"),e.enter("labelMarker"),e.consume(m),e.exit("labelMarker"),e.exit("labelEnd"),c):n(m)}function c(m){return m===40?e.attempt(tg,d,o?d:f)(m):m===91?e.attempt(ng,d,o?u:f)(m):o?d(m):f(m)}function u(m){return e.attempt(sg,d,f)(m)}function d(m){return t(m)}function f(m){return i._balanced=!0,n(m)}}function ag(e,t,n){return s;function s(f){return e.enter("resource"),e.enter("resourceMarker"),e.consume(f),e.exit("resourceMarker"),r}function r(f){return Me(f)?fn(e,i)(f):i(f)}function i(f){return f===41?d(f):xl(e,o,a,"resourceDestination","resourceDestinationLiteral","resourceDestinationLiteralMarker","resourceDestinationRaw","resourceDestinationString",32)(f)}function o(f){return Me(f)?fn(e,c)(f):d(f)}function a(f){return n(f)}function c(f){return f===34||f===39||f===40?wl(e,u,n,"resourceTitle","resourceTitleMarker","resourceTitleString")(f):d(f)}function u(f){return Me(f)?fn(e,d)(f):d(f)}function d(f){return f===41?(e.enter("resourceMarker"),e.consume(f),e.exit("resourceMarker"),e.exit("resource"),t):n(f)}}function lg(e,t,n){const s=this;return r;function r(a){return bl.call(s,e,i,o,"reference","referenceMarker","referenceString")(a)}function i(a){return s.parser.defined.includes(Wt(s.sliceSerialize(s.events[s.events.length-1][1]).slice(1,-1)))?t(a):n(a)}function o(a){return n(a)}}function cg(e,t,n){return s;function s(i){return e.enter("reference"),e.enter("referenceMarker"),e.consume(i),e.exit("referenceMarker"),r}function r(i){return i===93?(e.enter("referenceMarker"),e.consume(i),e.exit("referenceMarker"),e.exit("reference"),t):n(i)}}const ug={name:"labelStartImage",resolveAll:Si.resolveAll,tokenize:dg};function dg(e,t,n){const s=this;return r;function r(a){return e.enter("labelImage"),e.enter("labelImageMarker"),e.consume(a),e.exit("labelImageMarker"),i}function i(a){return a===91?(e.enter("labelMarker"),e.consume(a),e.exit("labelMarker"),e.exit("labelImage"),o):n(a)}function o(a){return a===94&&"_hiddenFootnoteSupport"in s.parser.constructs?n(a):t(a)}}const hg={name:"labelStartLink",resolveAll:Si.resolveAll,tokenize:fg};function fg(e,t,n){const s=this;return r;function r(o){return e.enter("labelLink"),e.enter("labelMarker"),e.consume(o),e.exit("labelMarker"),e.exit("labelLink"),i}function i(o){return o===94&&"_hiddenFootnoteSupport"in s.parser.constructs?n(o):t(o)}}const br={name:"lineEnding",tokenize:pg};function pg(e,t){return n;function n(s){return e.enter("lineEnding"),e.consume(s),e.exit("lineEnding"),ue(e,t,"linePrefix")}}const Qn={name:"thematicBreak",tokenize:mg};function mg(e,t,n){let s=0,r;return i;function i(u){return e.enter("thematicBreak"),o(u)}function o(u){return r=u,a(u)}function a(u){return u===r?(e.enter("thematicBreakSequence"),c(u)):s>=3&&(u===null||Y(u))?(e.exit("thematicBreak"),t(u)):n(u)}function c(u){return u===r?(e.consume(u),s++,c):(e.exit("thematicBreakSequence"),oe(u)?ue(e,a,"whitespace")(u):a(u))}}const Oe={continuation:{tokenize:bg},exit:Sg,name:"list",tokenize:xg},gg={partial:!0,tokenize:vg},yg={partial:!0,tokenize:wg};function xg(e,t,n){const s=this,r=s.events[s.events.length-1];let i=r&&r[1].type==="linePrefix"?r[2].sliceSerialize(r[1],!0).length:0,o=0;return a;function a(h){const g=s.containerState.type||(h===42||h===43||h===45?"listUnordered":"listOrdered");if(g==="listUnordered"?!s.containerState.marker||h===s.containerState.marker:Gr(h)){if(s.containerState.type||(s.containerState.type=g,e.enter(g,{_container:!0})),g==="listUnordered")return e.enter("listItemPrefix"),h===42||h===45?e.check(Qn,n,u)(h):u(h);if(!s.interrupt||h===49)return e.enter("listItemPrefix"),e.enter("listItemValue"),c(h)}return n(h)}function c(h){return Gr(h)&&++o<10?(e.consume(h),c):(!s.interrupt||o<2)&&(s.containerState.marker?h===s.containerState.marker:h===41||h===46)?(e.exit("listItemValue"),u(h)):n(h)}function u(h){return e.enter("listItemMarker"),e.consume(h),e.exit("listItemMarker"),s.containerState.marker=s.containerState.marker||h,e.check(us,s.interrupt?n:d,e.attempt(gg,m,f))}function d(h){return s.containerState.initialBlankLine=!0,i++,m(h)}function f(h){return oe(h)?(e.enter("listItemPrefixWhitespace"),e.consume(h),e.exit("listItemPrefixWhitespace"),m):n(h)}function m(h){return s.containerState.size=i+s.sliceSerialize(e.exit("listItemPrefix"),!0).length,t(h)}}function bg(e,t,n){const s=this;return s.containerState._closeFlow=void 0,e.check(us,r,i);function r(a){return s.containerState.furtherBlankLines=s.containerState.furtherBlankLines||s.containerState.initialBlankLine,ue(e,t,"listItemIndent",s.containerState.size+1)(a)}function i(a){return s.containerState.furtherBlankLines||!oe(a)?(s.containerState.furtherBlankLines=void 0,s.containerState.initialBlankLine=void 0,o(a)):(s.containerState.furtherBlankLines=void 0,s.containerState.initialBlankLine=void 0,e.attempt(yg,t,o)(a))}function o(a){return s.containerState._closeFlow=!0,s.interrupt=void 0,ue(e,e.attempt(Oe,t,n),"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(a)}}function wg(e,t,n){const s=this;return ue(e,r,"listItemIndent",s.containerState.size+1);function r(i){const o=s.events[s.events.length-1];return o&&o[1].type==="listItemIndent"&&o[2].sliceSerialize(o[1],!0).length===s.containerState.size?t(i):n(i)}}function Sg(e){e.exit(this.containerState.type)}function vg(e,t,n){const s=this;return ue(e,r,"listItemPrefixWhitespace",s.parser.constructs.disable.null.includes("codeIndented")?void 0:5);function r(i){const o=s.events[s.events.length-1];return!oe(i)&&o&&o[1].type==="listItemPrefixWhitespace"?t(i):n(i)}}const Vo={name:"setextUnderline",resolveTo:Cg,tokenize:kg};function Cg(e,t){let n=e.length,s,r,i;for(;n--;)if(e[n][0]==="enter"){if(e[n][1].type==="content"){s=n;break}e[n][1].type==="paragraph"&&(r=n)}else e[n][1].type==="content"&&e.splice(n,1),!i&&e[n][1].type==="definition"&&(i=n);const o={type:"setextHeading",start:{...e[s][1].start},end:{...e[e.length-1][1].end}};return e[r][1].type="setextHeadingText",i?(e.splice(r,0,["enter",o,t]),e.splice(i+1,0,["exit",e[s][1],t]),e[s][1].end={...e[i][1].end}):e[s][1]=o,e.push(["exit",o,t]),e}function kg(e,t,n){const s=this;let r;return i;function i(u){let d=s.events.length,f;for(;d--;)if(s.events[d][1].type!=="lineEnding"&&s.events[d][1].type!=="linePrefix"&&s.events[d][1].type!=="content"){f=s.events[d][1].type==="paragraph";break}return!s.parser.lazy[s.now().line]&&(s.interrupt||f)?(e.enter("setextHeadingLine"),r=u,o(u)):n(u)}function o(u){return e.enter("setextHeadingLineSequence"),a(u)}function a(u){return u===r?(e.consume(u),a):(e.exit("setextHeadingLineSequence"),oe(u)?ue(e,c,"lineSuffix")(u):c(u))}function c(u){return u===null||Y(u)?(e.exit("setextHeadingLine"),t(u)):n(u)}}const Eg={tokenize:Pg};function Pg(e){const t=this,n=e.attempt(us,s,e.attempt(this.parser.constructs.flowInitial,r,ue(e,e.attempt(this.parser.constructs.flow,r,e.attempt(Am,r)),"linePrefix")));return n;function s(i){if(i===null){e.consume(i);return}return e.enter("lineEndingBlank"),e.consume(i),e.exit("lineEndingBlank"),t.currentConstruct=void 0,n}function r(i){if(i===null){e.consume(i);return}return e.enter("lineEnding"),e.consume(i),e.exit("lineEnding"),t.currentConstruct=void 0,n}}const Tg={resolveAll:vl()},Ng=Sl("string"),Ig=Sl("text");function Sl(e){return{resolveAll:vl(e==="text"?jg:void 0),tokenize:t};function t(n){const s=this,r=this.parser.constructs[e],i=n.attempt(r,o,a);return o;function o(d){return u(d)?i(d):a(d)}function a(d){if(d===null){n.consume(d);return}return n.enter("data"),n.consume(d),c}function c(d){return u(d)?(n.exit("data"),i(d)):(n.consume(d),c)}function u(d){if(d===null)return!0;const f=r[d];let m=-1;if(f)for(;++m<f.length;){const h=f[m];if(!h.previous||h.previous.call(s,s.previous))return!0}return!1}}}function vl(e){return t;function t(n,s){let r=-1,i;for(;++r<=n.length;)i===void 0?n[r]&&n[r][1].type==="data"&&(i=r,r++):(!n[r]||n[r][1].type!=="data")&&(r!==i+2&&(n[i][1].end=n[r-1][1].end,n.splice(i+2,r-i-2),r=i+2),i=void 0);return e?e(n,s):n}}function jg(e,t){let n=0;for(;++n<=e.length;)if((n===e.length||e[n][1].type==="lineEnding")&&e[n-1][1].type==="data"){const s=e[n-1][1],r=t.sliceStream(s);let i=r.length,o=-1,a=0,c;for(;i--;){const u=r[i];if(typeof u=="string"){for(o=u.length;u.charCodeAt(o-1)===32;)a++,o--;if(o)break;o=-1}else if(u===-2)c=!0,a++;else if(u!==-1){i++;break}}if(t._contentTypeTextTrailing&&n===e.length&&(a=0),a){const u={type:n===e.length||c||a<2?"lineSuffix":"hardBreakTrailing",start:{_bufferIndex:i?o:s.start._bufferIndex+o,_index:s.start._index+i,line:s.end.line,column:s.end.column-a,offset:s.end.offset-a},end:{...s.end}};s.end={...u.start},s.start.offset===s.end.offset?Object.assign(s,u):(e.splice(n,0,["enter",u,t],["exit",u,t]),n+=2)}n++}return e}const Ag={42:Oe,43:Oe,45:Oe,48:Oe,49:Oe,50:Oe,51:Oe,52:Oe,53:Oe,54:Oe,55:Oe,56:Oe,57:Oe,62:pl},zg={91:Om},Lg={[-2]:xr,[-1]:xr,32:xr},_g={35:Vm,42:Qn,45:[Vo,Qn],60:Hm,61:Vo,95:Qn,96:Bo,126:Bo},Rg={38:gl,92:ml},Og={[-5]:br,[-4]:br,[-3]:br,33:ug,38:gl,42:Qr,60:[hm,Xm],91:hg,92:[Bm,ml],93:Si,95:Qr,96:Em},Mg={null:[Qr,Tg]},Dg={null:[42,95]},Fg={null:[]},Bg=Object.freeze(Object.defineProperty({__proto__:null,attentionMarkers:Dg,contentInitial:zg,disable:Fg,document:Ag,flow:_g,flowInitial:Lg,insideSpan:Mg,string:Rg,text:Og},Symbol.toStringTag,{value:"Module"}));function $g(e,t,n){let s={_bufferIndex:-1,_index:0,line:n&&n.line||1,column:n&&n.column||1,offset:n&&n.offset||0};const r={},i=[];let o=[],a=[];const c={attempt:L(z),check:L(E),consume:I,enter:S,exit:P,interrupt:L(E,{interrupt:!0})},u={code:null,containerState:{},defineSkip:x,events:[],now:g,parser:e,previous:null,sliceSerialize:m,sliceStream:h,write:f};let d=t.tokenize.call(u,c);return t.resolveAll&&i.push(t),u;function f(A){return o=Qe(o,A),v(),o[o.length-1]!==null?[]:(_(t,0),u.events=wi(i,u.events,u),u.events)}function m(A,R){return Ug(h(A),R)}function h(A){return Vg(o,A)}function g(){const{_bufferIndex:A,_index:R,line:D,column:F,offset:j}=s;return{_bufferIndex:A,_index:R,line:D,column:F,offset:j}}function x(A){r[A.line]=A.column,N()}function v(){let A;for(;s._index<o.length;){const R=o[s._index];if(typeof R=="string")for(A=s._index,s._bufferIndex<0&&(s._bufferIndex=0);s._index===A&&s._bufferIndex<R.length;)w(R.charCodeAt(s._bufferIndex));else w(R)}}function w(A){d=d(A)}function I(A){Y(A)?(s.line++,s.column=1,s.offset+=A===-3?2:1,N()):A!==-1&&(s.column++,s.offset++),s._bufferIndex<0?s._index++:(s._bufferIndex++,s._bufferIndex===o[s._index].length&&(s._bufferIndex=-1,s._index++)),u.previous=A}function S(A,R){const D=R||{};return D.type=A,D.start=g(),u.events.push(["enter",D,u]),a.push(D),D}function P(A){const R=a.pop();return R.end=g(),u.events.push(["exit",R,u]),R}function z(A,R){_(A,R.from)}function E(A,R){R.restore()}function L(A,R){return D;function D(F,j,T){let $,k,B,y;return Array.isArray(F)?ae(F):"tokenize"in F?ae([F]):te(F);function te(se){return fe;function fe(ge){const ze=ge!==null&&se[ge],je=ge!==null&&se.null,he=[...Array.isArray(ze)?ze:ze?[ze]:[],...Array.isArray(je)?je:je?[je]:[]];return ae(he)(ge)}}function ae(se){return $=se,k=0,se.length===0?T:b(se[k])}function b(se){return fe;function fe(ge){return y=M(),B=se,se.partial||(u.currentConstruct=se),se.name&&u.parser.constructs.disable.null.includes(se.name)?ee():se.tokenize.call(R?Object.assign(Object.create(u),R):u,c,q,ee)(ge)}}function q(se){return A(B,y),j}function ee(se){return y.restore(),++k<$.length?b($[k]):T}}}function _(A,R){A.resolveAll&&!i.includes(A)&&i.push(A),A.resolve&&ot(u.events,R,u.events.length-R,A.resolve(u.events.slice(R),u)),A.resolveTo&&(u.events=A.resolveTo(u.events,u))}function M(){const A=g(),R=u.previous,D=u.currentConstruct,F=u.events.length,j=Array.from(a);return{from:F,restore:T};function T(){s=A,u.previous=R,u.currentConstruct=D,u.events.length=F,a=j,N()}}function N(){s.line in r&&s.column<2&&(s.column=r[s.line],s.offset+=r[s.line]-1)}}function Vg(e,t){const n=t.start._index,s=t.start._bufferIndex,r=t.end._index,i=t.end._bufferIndex;let o;if(n===r)o=[e[n].slice(s,i)];else{if(o=e.slice(n,r),s>-1){const a=o[0];typeof a=="string"?o[0]=a.slice(s):o.shift()}i>0&&o.push(e[r].slice(0,i))}return o}function Ug(e,t){let n=-1;const s=[];let r;for(;++n<e.length;){const i=e[n];let o;if(typeof i=="string")o=i;else switch(i){case-5:{o="\r";break}case-4:{o=`
14
+ `;break}case-3:{o=`\r
15
+ `;break}case-2:{o=t?" ":" ";break}case-1:{if(!t&&r)continue;o=" ";break}default:o=String.fromCharCode(i)}r=i===-2,s.push(o)}return s.join("")}function Wg(e){const s={constructs:Yp([Bg,...(e||{}).extensions||[]]),content:r(im),defined:[],document:r(am),flow:r(Eg),lazy:{},string:r(Ng),text:r(Ig)};return s;function r(i){return o;function o(a){return $g(s,i,a)}}}function qg(e){for(;!yl(e););return e}const Uo=/[\0\t\n\r]/g;function Hg(){let e=1,t="",n=!0,s;return r;function r(i,o,a){const c=[];let u,d,f,m,h;for(i=t+(typeof i=="string"?i.toString():new TextDecoder(o||void 0).decode(i)),f=0,t="",n&&(i.charCodeAt(0)===65279&&f++,n=void 0);f<i.length;){if(Uo.lastIndex=f,u=Uo.exec(i),m=u&&u.index!==void 0?u.index:i.length,h=i.charCodeAt(m),!u){t=i.slice(f);break}if(h===10&&f===m&&s)c.push(-3),s=void 0;else switch(s&&(c.push(-5),s=void 0),f<m&&(c.push(i.slice(f,m)),e+=m-f),h){case 0:{c.push(65533),e++;break}case 9:{for(d=Math.ceil(e/4)*4,c.push(-2);e++<d;)c.push(-1);break}case 10:{c.push(-4),e=1;break}default:s=!0,e=1}f=m+1}return a&&(s&&c.push(-5),t&&c.push(t),c.push(null)),c}}const Gg=/\\([!-/:-@[-`{-~])|&(#(?:\d{1,7}|x[\da-f]{1,6})|[\da-z]{1,31});/gi;function Qg(e){return e.replace(Gg,Jg)}function Jg(e,t,n){if(t)return t;if(n.charCodeAt(0)===35){const r=n.charCodeAt(1),i=r===120||r===88;return fl(n.slice(i?2:1),i?16:10)}return bi(n)||e}const Cl={}.hasOwnProperty;function Zg(e,t,n){return t&&typeof t=="object"&&(n=t,t=void 0),Yg(n)(qg(Wg(n).document().write(Hg()(e,t,!0))))}function Yg(e){const t={transforms:[],canContainEols:["emphasis","fragment","heading","paragraph","strong"],enter:{autolink:i(re),autolinkProtocol:M,autolinkEmail:M,atxHeading:i(pt),blockQuote:i(je),characterEscape:M,characterReference:M,codeFenced:i(he),codeFencedFenceInfo:o,codeFencedFenceMeta:o,codeIndented:i(he,o),codeText:i(ft,o),codeTextData:M,data:M,codeFlowValue:M,definition:i(Lt),definitionDestinationString:o,definitionLabelString:o,definitionTitleString:o,emphasis:i(_t),hardBreakEscape:i(mt),hardBreakTrailing:i(mt),htmlFlow:i(G,o),htmlFlowData:M,htmlText:i(G,o),htmlTextData:M,image:i(K),label:o,link:i(re),listItem:i(qe),listItemValue:m,listOrdered:i(we,f),listUnordered:i(we),paragraph:i(de),reference:b,referenceString:o,resourceDestinationString:o,resourceTitleString:o,setextHeading:i(pt),strong:i(Te),thematicBreak:i(Ze)},exit:{atxHeading:c(),atxHeadingSequence:z,autolink:c(),autolinkEmail:ze,autolinkProtocol:ge,blockQuote:c(),characterEscapeValue:N,characterReferenceMarkerHexadecimal:ee,characterReferenceMarkerNumeric:ee,characterReferenceValue:se,characterReference:fe,codeFenced:c(v),codeFencedFence:x,codeFencedFenceInfo:h,codeFencedFenceMeta:g,codeFlowValue:N,codeIndented:c(w),codeText:c(j),codeTextData:N,data:N,definition:c(),definitionDestinationString:P,definitionLabelString:I,definitionTitleString:S,emphasis:c(),hardBreakEscape:c(R),hardBreakTrailing:c(R),htmlFlow:c(D),htmlFlowData:N,htmlText:c(F),htmlTextData:N,image:c($),label:B,labelText:k,lineEnding:A,link:c(T),listItem:c(),listOrdered:c(),listUnordered:c(),paragraph:c(),referenceString:q,resourceDestinationString:y,resourceTitleString:te,resource:ae,setextHeading:c(_),setextHeadingLineSequence:L,setextHeadingText:E,strong:c(),thematicBreak:c()}};kl(t,(e||{}).mdastExtensions||[]);const n={};return s;function s(O){let W={type:"root",children:[]};const Q={stack:[W],tokenStack:[],config:t,enter:a,exit:u,buffer:o,resume:d,data:n},Z=[];let ie=-1;for(;++ie<O.length;)if(O[ie][1].type==="listOrdered"||O[ie][1].type==="listUnordered")if(O[ie][0]==="enter")Z.push(ie);else{const Ne=Z.pop();ie=r(O,Ne,ie)}for(ie=-1;++ie<O.length;){const Ne=t[O[ie][0]];Cl.call(Ne,O[ie][1].type)&&Ne[O[ie][1].type].call(Object.assign({sliceSerialize:O[ie][2].sliceSerialize},Q),O[ie][1])}if(Q.tokenStack.length>0){const Ne=Q.tokenStack[Q.tokenStack.length-1];(Ne[1]||Wo).call(Q,void 0,Ne[0])}for(W.position={start:wt(O.length>0?O[0][1].start:{line:1,column:1,offset:0}),end:wt(O.length>0?O[O.length-2][1].end:{line:1,column:1,offset:0})},ie=-1;++ie<t.transforms.length;)W=t.transforms[ie](W)||W;return W}function r(O,W,Q){let Z=W-1,ie=-1,Ne=!1,Ye,Le,lt,_e;for(;++Z<=Q;){const ye=O[Z];switch(ye[1].type){case"listUnordered":case"listOrdered":case"blockQuote":{ye[0]==="enter"?ie++:ie--,_e=void 0;break}case"lineEndingBlank":{ye[0]==="enter"&&(Ye&&!_e&&!ie&&!lt&&(lt=Z),_e=void 0);break}case"linePrefix":case"listItemValue":case"listItemMarker":case"listItemPrefix":case"listItemPrefixWhitespace":break;default:_e=void 0}if(!ie&&ye[0]==="enter"&&ye[1].type==="listItemPrefix"||ie===-1&&ye[0]==="exit"&&(ye[1].type==="listUnordered"||ye[1].type==="listOrdered")){if(Ye){let He=Z;for(Le=void 0;He--;){const Fe=O[He];if(Fe[1].type==="lineEnding"||Fe[1].type==="lineEndingBlank"){if(Fe[0]==="exit")continue;Le&&(O[Le][1].type="lineEndingBlank",Ne=!0),Fe[1].type="lineEnding",Le=He}else if(!(Fe[1].type==="linePrefix"||Fe[1].type==="blockQuotePrefix"||Fe[1].type==="blockQuotePrefixWhitespace"||Fe[1].type==="blockQuoteMarker"||Fe[1].type==="listItemIndent"))break}lt&&(!Le||lt<Le)&&(Ye._spread=!0),Ye.end=Object.assign({},Le?O[Le][1].start:ye[1].end),O.splice(Le||Z,0,["exit",Ye,ye[2]]),Z++,Q++}if(ye[1].type==="listItemPrefix"){const He={type:"listItem",_spread:!1,start:Object.assign({},ye[1].start),end:void 0};Ye=He,O.splice(Z,0,["enter",He,ye[2]]),Z++,Q++,lt=void 0,_e=!0}}}return O[W][1]._spread=Ne,Q}function i(O,W){return Q;function Q(Z){a.call(this,O(Z),Z),W&&W.call(this,Z)}}function o(){this.stack.push({type:"fragment",children:[]})}function a(O,W,Q){this.stack[this.stack.length-1].children.push(O),this.stack.push(O),this.tokenStack.push([W,Q||void 0]),O.position={start:wt(W.start),end:void 0}}function c(O){return W;function W(Q){O&&O.call(this,Q),u.call(this,Q)}}function u(O,W){const Q=this.stack.pop(),Z=this.tokenStack.pop();if(Z)Z[0].type!==O.type&&(W?W.call(this,O,Z[0]):(Z[1]||Wo).call(this,O,Z[0]));else throw new Error("Cannot close `"+O.type+"` ("+hn({start:O.start,end:O.end})+"): it’s not open");Q.position.end=wt(O.end)}function d(){return Jp(this.stack.pop())}function f(){this.data.expectingFirstListItemValue=!0}function m(O){if(this.data.expectingFirstListItemValue){const W=this.stack[this.stack.length-2];W.start=Number.parseInt(this.sliceSerialize(O),10),this.data.expectingFirstListItemValue=void 0}}function h(){const O=this.resume(),W=this.stack[this.stack.length-1];W.lang=O}function g(){const O=this.resume(),W=this.stack[this.stack.length-1];W.meta=O}function x(){this.data.flowCodeInside||(this.buffer(),this.data.flowCodeInside=!0)}function v(){const O=this.resume(),W=this.stack[this.stack.length-1];W.value=O.replace(/^(\r?\n|\r)|(\r?\n|\r)$/g,""),this.data.flowCodeInside=void 0}function w(){const O=this.resume(),W=this.stack[this.stack.length-1];W.value=O.replace(/(\r?\n|\r)$/g,"")}function I(O){const W=this.resume(),Q=this.stack[this.stack.length-1];Q.label=W,Q.identifier=Wt(this.sliceSerialize(O)).toLowerCase()}function S(){const O=this.resume(),W=this.stack[this.stack.length-1];W.title=O}function P(){const O=this.resume(),W=this.stack[this.stack.length-1];W.url=O}function z(O){const W=this.stack[this.stack.length-1];if(!W.depth){const Q=this.sliceSerialize(O).length;W.depth=Q}}function E(){this.data.setextHeadingSlurpLineEnding=!0}function L(O){const W=this.stack[this.stack.length-1];W.depth=this.sliceSerialize(O).codePointAt(0)===61?1:2}function _(){this.data.setextHeadingSlurpLineEnding=void 0}function M(O){const Q=this.stack[this.stack.length-1].children;let Z=Q[Q.length-1];(!Z||Z.type!=="text")&&(Z=ke(),Z.position={start:wt(O.start),end:void 0},Q.push(Z)),this.stack.push(Z)}function N(O){const W=this.stack.pop();W.value+=this.sliceSerialize(O),W.position.end=wt(O.end)}function A(O){const W=this.stack[this.stack.length-1];if(this.data.atHardBreak){const Q=W.children[W.children.length-1];Q.position.end=wt(O.end),this.data.atHardBreak=void 0;return}!this.data.setextHeadingSlurpLineEnding&&t.canContainEols.includes(W.type)&&(M.call(this,O),N.call(this,O))}function R(){this.data.atHardBreak=!0}function D(){const O=this.resume(),W=this.stack[this.stack.length-1];W.value=O}function F(){const O=this.resume(),W=this.stack[this.stack.length-1];W.value=O}function j(){const O=this.resume(),W=this.stack[this.stack.length-1];W.value=O}function T(){const O=this.stack[this.stack.length-1];if(this.data.inReference){const W=this.data.referenceType||"shortcut";O.type+="Reference",O.referenceType=W,delete O.url,delete O.title}else delete O.identifier,delete O.label;this.data.referenceType=void 0}function $(){const O=this.stack[this.stack.length-1];if(this.data.inReference){const W=this.data.referenceType||"shortcut";O.type+="Reference",O.referenceType=W,delete O.url,delete O.title}else delete O.identifier,delete O.label;this.data.referenceType=void 0}function k(O){const W=this.sliceSerialize(O),Q=this.stack[this.stack.length-2];Q.label=Qg(W),Q.identifier=Wt(W).toLowerCase()}function B(){const O=this.stack[this.stack.length-1],W=this.resume(),Q=this.stack[this.stack.length-1];if(this.data.inReference=!0,Q.type==="link"){const Z=O.children;Q.children=Z}else Q.alt=W}function y(){const O=this.resume(),W=this.stack[this.stack.length-1];W.url=O}function te(){const O=this.resume(),W=this.stack[this.stack.length-1];W.title=O}function ae(){this.data.inReference=void 0}function b(){this.data.referenceType="collapsed"}function q(O){const W=this.resume(),Q=this.stack[this.stack.length-1];Q.label=W,Q.identifier=Wt(this.sliceSerialize(O)).toLowerCase(),this.data.referenceType="full"}function ee(O){this.data.characterReferenceType=O.type}function se(O){const W=this.sliceSerialize(O),Q=this.data.characterReferenceType;let Z;Q?(Z=fl(W,Q==="characterReferenceMarkerNumeric"?10:16),this.data.characterReferenceType=void 0):Z=bi(W);const ie=this.stack[this.stack.length-1];ie.value+=Z}function fe(O){const W=this.stack.pop();W.position.end=wt(O.end)}function ge(O){N.call(this,O);const W=this.stack[this.stack.length-1];W.url=this.sliceSerialize(O)}function ze(O){N.call(this,O);const W=this.stack[this.stack.length-1];W.url="mailto:"+this.sliceSerialize(O)}function je(){return{type:"blockquote",children:[]}}function he(){return{type:"code",lang:null,meta:null,value:""}}function ft(){return{type:"inlineCode",value:""}}function Lt(){return{type:"definition",identifier:"",label:null,title:null,url:""}}function _t(){return{type:"emphasis",children:[]}}function pt(){return{type:"heading",depth:0,children:[]}}function mt(){return{type:"break"}}function G(){return{type:"html",value:""}}function K(){return{type:"image",title:null,url:"",alt:null}}function re(){return{type:"link",title:null,url:"",children:[]}}function we(O){return{type:"list",ordered:O.type==="listOrdered",start:null,spread:O._spread,children:[]}}function qe(O){return{type:"listItem",spread:O._spread,checked:null,children:[]}}function de(){return{type:"paragraph",children:[]}}function Te(){return{type:"strong",children:[]}}function ke(){return{type:"text",value:""}}function Ze(){return{type:"thematicBreak"}}}function wt(e){return{line:e.line,column:e.column,offset:e.offset}}function kl(e,t){let n=-1;for(;++n<t.length;){const s=t[n];Array.isArray(s)?kl(e,s):Kg(e,s)}}function Kg(e,t){let n;for(n in t)if(Cl.call(t,n))switch(n){case"canContainEols":{const s=t[n];s&&e[n].push(...s);break}case"transforms":{const s=t[n];s&&e[n].push(...s);break}case"enter":case"exit":{const s=t[n];s&&Object.assign(e[n],s);break}}}function Wo(e,t){throw e?new Error("Cannot close `"+e.type+"` ("+hn({start:e.start,end:e.end})+"): a different token (`"+t.type+"`, "+hn({start:t.start,end:t.end})+") is open"):new Error("Cannot close document, a token (`"+t.type+"`, "+hn({start:t.start,end:t.end})+") is still open")}function Xg(e){const t=this;t.parser=n;function n(s){return Zg(s,{...t.data("settings"),...e,extensions:t.data("micromarkExtensions")||[],mdastExtensions:t.data("fromMarkdownExtensions")||[]})}}function ey(e,t){const n={type:"element",tagName:"blockquote",properties:{},children:e.wrap(e.all(t),!0)};return e.patch(t,n),e.applyData(t,n)}function ty(e,t){const n={type:"element",tagName:"br",properties:{},children:[]};return e.patch(t,n),[e.applyData(t,n),{type:"text",value:`
16
+ `}]}function ny(e,t){const n=t.value?t.value+`
17
+ `:"",s={},r=t.lang?t.lang.split(/\s+/):[];r.length>0&&(s.className=["language-"+r[0]]);let i={type:"element",tagName:"code",properties:s,children:[{type:"text",value:n}]};return t.meta&&(i.data={meta:t.meta}),e.patch(t,i),i=e.applyData(t,i),i={type:"element",tagName:"pre",properties:{},children:[i]},e.patch(t,i),i}function sy(e,t){const n={type:"element",tagName:"del",properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function ry(e,t){const n={type:"element",tagName:"em",properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function iy(e,t){const n=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",s=String(t.identifier).toUpperCase(),r=Gt(s.toLowerCase()),i=e.footnoteOrder.indexOf(s);let o,a=e.footnoteCounts.get(s);a===void 0?(a=0,e.footnoteOrder.push(s),o=e.footnoteOrder.length):o=i+1,a+=1,e.footnoteCounts.set(s,a);const c={type:"element",tagName:"a",properties:{href:"#"+n+"fn-"+r,id:n+"fnref-"+r+(a>1?"-"+a:""),dataFootnoteRef:!0,ariaDescribedBy:["footnote-label"]},children:[{type:"text",value:String(o)}]};e.patch(t,c);const u={type:"element",tagName:"sup",properties:{},children:[c]};return e.patch(t,u),e.applyData(t,u)}function oy(e,t){const n={type:"element",tagName:"h"+t.depth,properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function ay(e,t){if(e.options.allowDangerousHtml){const n={type:"raw",value:t.value};return e.patch(t,n),e.applyData(t,n)}}function El(e,t){const n=t.referenceType;let s="]";if(n==="collapsed"?s+="[]":n==="full"&&(s+="["+(t.label||t.identifier)+"]"),t.type==="imageReference")return[{type:"text",value:"!["+t.alt+s}];const r=e.all(t),i=r[0];i&&i.type==="text"?i.value="["+i.value:r.unshift({type:"text",value:"["});const o=r[r.length-1];return o&&o.type==="text"?o.value+=s:r.push({type:"text",value:s}),r}function ly(e,t){const n=String(t.identifier).toUpperCase(),s=e.definitionById.get(n);if(!s)return El(e,t);const r={src:Gt(s.url||""),alt:t.alt};s.title!==null&&s.title!==void 0&&(r.title=s.title);const i={type:"element",tagName:"img",properties:r,children:[]};return e.patch(t,i),e.applyData(t,i)}function cy(e,t){const n={src:Gt(t.url)};t.alt!==null&&t.alt!==void 0&&(n.alt=t.alt),t.title!==null&&t.title!==void 0&&(n.title=t.title);const s={type:"element",tagName:"img",properties:n,children:[]};return e.patch(t,s),e.applyData(t,s)}function uy(e,t){const n={type:"text",value:t.value.replace(/\r?\n|\r/g," ")};e.patch(t,n);const s={type:"element",tagName:"code",properties:{},children:[n]};return e.patch(t,s),e.applyData(t,s)}function dy(e,t){const n=String(t.identifier).toUpperCase(),s=e.definitionById.get(n);if(!s)return El(e,t);const r={href:Gt(s.url||"")};s.title!==null&&s.title!==void 0&&(r.title=s.title);const i={type:"element",tagName:"a",properties:r,children:e.all(t)};return e.patch(t,i),e.applyData(t,i)}function hy(e,t){const n={href:Gt(t.url)};t.title!==null&&t.title!==void 0&&(n.title=t.title);const s={type:"element",tagName:"a",properties:n,children:e.all(t)};return e.patch(t,s),e.applyData(t,s)}function fy(e,t,n){const s=e.all(t),r=n?py(n):Pl(t),i={},o=[];if(typeof t.checked=="boolean"){const d=s[0];let f;d&&d.type==="element"&&d.tagName==="p"?f=d:(f={type:"element",tagName:"p",properties:{},children:[]},s.unshift(f)),f.children.length>0&&f.children.unshift({type:"text",value:" "}),f.children.unshift({type:"element",tagName:"input",properties:{type:"checkbox",checked:t.checked,disabled:!0},children:[]}),i.className=["task-list-item"]}let a=-1;for(;++a<s.length;){const d=s[a];(r||a!==0||d.type!=="element"||d.tagName!=="p")&&o.push({type:"text",value:`
18
+ `}),d.type==="element"&&d.tagName==="p"&&!r?o.push(...d.children):o.push(d)}const c=s[s.length-1];c&&(r||c.type!=="element"||c.tagName!=="p")&&o.push({type:"text",value:`
19
+ `});const u={type:"element",tagName:"li",properties:i,children:o};return e.patch(t,u),e.applyData(t,u)}function py(e){let t=!1;if(e.type==="list"){t=e.spread||!1;const n=e.children;let s=-1;for(;!t&&++s<n.length;)t=Pl(n[s])}return t}function Pl(e){const t=e.spread;return t??e.children.length>1}function my(e,t){const n={},s=e.all(t);let r=-1;for(typeof t.start=="number"&&t.start!==1&&(n.start=t.start);++r<s.length;){const o=s[r];if(o.type==="element"&&o.tagName==="li"&&o.properties&&Array.isArray(o.properties.className)&&o.properties.className.includes("task-list-item")){n.className=["contains-task-list"];break}}const i={type:"element",tagName:t.ordered?"ol":"ul",properties:n,children:e.wrap(s,!0)};return e.patch(t,i),e.applyData(t,i)}function gy(e,t){const n={type:"element",tagName:"p",properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function yy(e,t){const n={type:"root",children:e.wrap(e.all(t))};return e.patch(t,n),e.applyData(t,n)}function xy(e,t){const n={type:"element",tagName:"strong",properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function by(e,t){const n=e.all(t),s=n.shift(),r=[];if(s){const o={type:"element",tagName:"thead",properties:{},children:e.wrap([s],!0)};e.patch(t.children[0],o),r.push(o)}if(n.length>0){const o={type:"element",tagName:"tbody",properties:{},children:e.wrap(n,!0)},a=mi(t.children[1]),c=ol(t.children[t.children.length-1]);a&&c&&(o.position={start:a,end:c}),r.push(o)}const i={type:"element",tagName:"table",properties:{},children:e.wrap(r,!0)};return e.patch(t,i),e.applyData(t,i)}function wy(e,t,n){const s=n?n.children:void 0,i=(s?s.indexOf(t):1)===0?"th":"td",o=n&&n.type==="table"?n.align:void 0,a=o?o.length:t.children.length;let c=-1;const u=[];for(;++c<a;){const f=t.children[c],m={},h=o?o[c]:void 0;h&&(m.align=h);let g={type:"element",tagName:i,properties:m,children:[]};f&&(g.children=e.all(f),e.patch(f,g),g=e.applyData(f,g)),u.push(g)}const d={type:"element",tagName:"tr",properties:{},children:e.wrap(u,!0)};return e.patch(t,d),e.applyData(t,d)}function Sy(e,t){const n={type:"element",tagName:"td",properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}const qo=9,Ho=32;function vy(e){const t=String(e),n=/\r?\n|\r/g;let s=n.exec(t),r=0;const i=[];for(;s;)i.push(Go(t.slice(r,s.index),r>0,!0),s[0]),r=s.index+s[0].length,s=n.exec(t);return i.push(Go(t.slice(r),r>0,!1)),i.join("")}function Go(e,t,n){let s=0,r=e.length;if(t){let i=e.codePointAt(s);for(;i===qo||i===Ho;)s++,i=e.codePointAt(s)}if(n){let i=e.codePointAt(r-1);for(;i===qo||i===Ho;)r--,i=e.codePointAt(r-1)}return r>s?e.slice(s,r):""}function Cy(e,t){const n={type:"text",value:vy(String(t.value))};return e.patch(t,n),e.applyData(t,n)}function ky(e,t){const n={type:"element",tagName:"hr",properties:{},children:[]};return e.patch(t,n),e.applyData(t,n)}const Ey={blockquote:ey,break:ty,code:ny,delete:sy,emphasis:ry,footnoteReference:iy,heading:oy,html:ay,imageReference:ly,image:cy,inlineCode:uy,linkReference:dy,link:hy,listItem:fy,list:my,paragraph:gy,root:yy,strong:xy,table:by,tableCell:Sy,tableRow:wy,text:Cy,thematicBreak:ky,toml:_n,yaml:_n,definition:_n,footnoteDefinition:_n};function _n(){}const Tl=-1,ds=0,pn=1,is=2,vi=3,Ci=4,ki=5,Ei=6,Nl=7,Il=8,Py=typeof self=="object"?self:globalThis,Qo=(e,t)=>{switch(e){case"Function":case"SharedWorker":case"Worker":case"eval":case"setInterval":case"setTimeout":throw new TypeError("unable to deserialize "+e)}return new Py[e](t)},Ty=(e,t)=>{const n=(r,i)=>(e.set(i,r),r),s=r=>{if(e.has(r))return e.get(r);const[i,o]=t[r];switch(i){case ds:case Tl:return n(o,r);case pn:{const a=n([],r);for(const c of o)a.push(s(c));return a}case is:{const a=n({},r);for(const[c,u]of o)a[s(c)]=s(u);return a}case vi:return n(new Date(o),r);case Ci:{const{source:a,flags:c}=o;return n(new RegExp(a,c),r)}case ki:{const a=n(new Map,r);for(const[c,u]of o)a.set(s(c),s(u));return a}case Ei:{const a=n(new Set,r);for(const c of o)a.add(s(c));return a}case Nl:{const{name:a,message:c}=o;return n(Qo(a,c),r)}case Il:return n(BigInt(o),r);case"BigInt":return n(Object(BigInt(o)),r);case"ArrayBuffer":return n(new Uint8Array(o).buffer,o);case"DataView":{const{buffer:a}=new Uint8Array(o);return n(new DataView(a),o)}}return n(Qo(i,o),r)};return s},Jo=e=>Ty(new Map,e)(0),Vt="",{toString:Ny}={},{keys:Iy}=Object,cn=e=>{const t=typeof e;if(t!=="object"||!e)return[ds,t];const n=Ny.call(e).slice(8,-1);switch(n){case"Array":return[pn,Vt];case"Object":return[is,Vt];case"Date":return[vi,Vt];case"RegExp":return[Ci,Vt];case"Map":return[ki,Vt];case"Set":return[Ei,Vt];case"DataView":return[pn,n]}return n.includes("Array")?[pn,n]:n.includes("Error")?[Nl,n]:[is,n]},Rn=([e,t])=>e===ds&&(t==="function"||t==="symbol"),jy=(e,t,n,s)=>{const r=(o,a)=>{const c=s.push(o)-1;return n.set(a,c),c},i=o=>{if(n.has(o))return n.get(o);let[a,c]=cn(o);switch(a){case ds:{let d=o;switch(c){case"bigint":a=Il,d=o.toString();break;case"function":case"symbol":if(e)throw new TypeError("unable to serialize "+c);d=null;break;case"undefined":return r([Tl],o)}return r([a,d],o)}case pn:{if(c){let m=o;return c==="DataView"?m=new Uint8Array(o.buffer):c==="ArrayBuffer"&&(m=new Uint8Array(o)),r([c,[...m]],o)}const d=[],f=r([a,d],o);for(const m of o)d.push(i(m));return f}case is:{if(c)switch(c){case"BigInt":return r([c,o.toString()],o);case"Boolean":case"Number":case"String":return r([c,o.valueOf()],o)}if(t&&"toJSON"in o)return i(o.toJSON());const d=[],f=r([a,d],o);for(const m of Iy(o))(e||!Rn(cn(o[m])))&&d.push([i(m),i(o[m])]);return f}case vi:return r([a,o.toISOString()],o);case Ci:{const{source:d,flags:f}=o;return r([a,{source:d,flags:f}],o)}case ki:{const d=[],f=r([a,d],o);for(const[m,h]of o)(e||!(Rn(cn(m))||Rn(cn(h))))&&d.push([i(m),i(h)]);return f}case Ei:{const d=[],f=r([a,d],o);for(const m of o)(e||!Rn(cn(m)))&&d.push(i(m));return f}}const{message:u}=o;return r([a,{name:c,message:u}],o)};return i},Zo=(e,{json:t,lossy:n}={})=>{const s=[];return jy(!(t||n),!!t,new Map,s)(e),s},os=typeof structuredClone=="function"?(e,t)=>t&&("json"in t||"lossy"in t)?Jo(Zo(e,t)):structuredClone(e):(e,t)=>Jo(Zo(e,t));function Ay(e,t){const n=[{type:"text",value:"↩"}];return t>1&&n.push({type:"element",tagName:"sup",properties:{},children:[{type:"text",value:String(t)}]}),n}function zy(e,t){return"Back to reference "+(e+1)+(t>1?"-"+t:"")}function Ly(e){const t=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",n=e.options.footnoteBackContent||Ay,s=e.options.footnoteBackLabel||zy,r=e.options.footnoteLabel||"Footnotes",i=e.options.footnoteLabelTagName||"h2",o=e.options.footnoteLabelProperties||{className:["sr-only"]},a=[];let c=-1;for(;++c<e.footnoteOrder.length;){const u=e.footnoteById.get(e.footnoteOrder[c]);if(!u)continue;const d=e.all(u),f=String(u.identifier).toUpperCase(),m=Gt(f.toLowerCase());let h=0;const g=[],x=e.footnoteCounts.get(f);for(;x!==void 0&&++h<=x;){g.length>0&&g.push({type:"text",value:" "});let I=typeof n=="string"?n:n(c,h);typeof I=="string"&&(I={type:"text",value:I}),g.push({type:"element",tagName:"a",properties:{href:"#"+t+"fnref-"+m+(h>1?"-"+h:""),dataFootnoteBackref:"",ariaLabel:typeof s=="string"?s:s(c,h),className:["data-footnote-backref"]},children:Array.isArray(I)?I:[I]})}const v=d[d.length-1];if(v&&v.type==="element"&&v.tagName==="p"){const I=v.children[v.children.length-1];I&&I.type==="text"?I.value+=" ":v.children.push({type:"text",value:" "}),v.children.push(...g)}else d.push(...g);const w={type:"element",tagName:"li",properties:{id:t+"fn-"+m},children:e.wrap(d,!0)};e.patch(u,w),a.push(w)}if(a.length!==0)return{type:"element",tagName:"section",properties:{dataFootnotes:!0,className:["footnotes"]},children:[{type:"element",tagName:i,properties:{...os(o),id:"footnote-label"},children:[{type:"text",value:r}]},{type:"text",value:`
20
+ `},{type:"element",tagName:"ol",properties:{},children:e.wrap(a,!0)},{type:"text",value:`
21
+ `}]}}const jl=(function(e){if(e==null)return My;if(typeof e=="function")return hs(e);if(typeof e=="object")return Array.isArray(e)?_y(e):Ry(e);if(typeof e=="string")return Oy(e);throw new Error("Expected function, string, or object as test")});function _y(e){const t=[];let n=-1;for(;++n<e.length;)t[n]=jl(e[n]);return hs(s);function s(...r){let i=-1;for(;++i<t.length;)if(t[i].apply(this,r))return!0;return!1}}function Ry(e){const t=e;return hs(n);function n(s){const r=s;let i;for(i in e)if(r[i]!==t[i])return!1;return!0}}function Oy(e){return hs(t);function t(n){return n&&n.type===e}}function hs(e){return t;function t(n,s,r){return!!(Dy(n)&&e.call(this,n,typeof s=="number"?s:void 0,r||void 0))}}function My(){return!0}function Dy(e){return e!==null&&typeof e=="object"&&"type"in e}const Al=[],Fy=!0,Yo=!1,By="skip";function $y(e,t,n,s){let r;typeof t=="function"&&typeof n!="function"?(s=n,n=t):r=t;const i=jl(r),o=s?-1:1;a(e,void 0,[])();function a(c,u,d){const f=c&&typeof c=="object"?c:{};if(typeof f.type=="string"){const h=typeof f.tagName=="string"?f.tagName:typeof f.name=="string"?f.name:void 0;Object.defineProperty(m,"name",{value:"node ("+(c.type+(h?"<"+h+">":""))+")"})}return m;function m(){let h=Al,g,x,v;if((!t||i(c,u,d[d.length-1]||void 0))&&(h=Vy(n(c,d)),h[0]===Yo))return h;if("children"in c&&c.children){const w=c;if(w.children&&h[0]!==By)for(x=(s?w.children.length:-1)+o,v=d.concat(w);x>-1&&x<w.children.length;){const I=w.children[x];if(g=a(I,x,v)(),g[0]===Yo)return g;x=typeof g[1]=="number"?g[1]:x+o}}return h}}}function Vy(e){return Array.isArray(e)?e:typeof e=="number"?[Fy,e]:e==null?Al:[e]}function zl(e,t,n,s){let r,i,o;typeof t=="function"&&typeof n!="function"?(i=void 0,o=t,r=n):(i=t,o=n,r=s),$y(e,i,a,r);function a(c,u){const d=u[u.length-1],f=d?d.children.indexOf(c):void 0;return o(c,f,d)}}const Jr={}.hasOwnProperty,Uy={};function Wy(e,t){const n=t||Uy,s=new Map,r=new Map,i=new Map,o={...Ey,...n.handlers},a={all:u,applyData:Hy,definitionById:s,footnoteById:r,footnoteCounts:i,footnoteOrder:[],handlers:o,one:c,options:n,patch:qy,wrap:Qy};return zl(e,function(d){if(d.type==="definition"||d.type==="footnoteDefinition"){const f=d.type==="definition"?s:r,m=String(d.identifier).toUpperCase();f.has(m)||f.set(m,d)}}),a;function c(d,f){const m=d.type,h=a.handlers[m];if(Jr.call(a.handlers,m)&&h)return h(a,d,f);if(a.options.passThrough&&a.options.passThrough.includes(m)){if("children"in d){const{children:x,...v}=d,w=os(v);return w.children=a.all(d),w}return os(d)}return(a.options.unknownHandler||Gy)(a,d,f)}function u(d){const f=[];if("children"in d){const m=d.children;let h=-1;for(;++h<m.length;){const g=a.one(m[h],d);if(g){if(h&&m[h-1].type==="break"&&(!Array.isArray(g)&&g.type==="text"&&(g.value=Ko(g.value)),!Array.isArray(g)&&g.type==="element")){const x=g.children[0];x&&x.type==="text"&&(x.value=Ko(x.value))}Array.isArray(g)?f.push(...g):f.push(g)}}}return f}}function qy(e,t){e.position&&(t.position=Tp(e))}function Hy(e,t){let n=t;if(e&&e.data){const s=e.data.hName,r=e.data.hChildren,i=e.data.hProperties;if(typeof s=="string")if(n.type==="element")n.tagName=s;else{const o="children"in n?n.children:[n];n={type:"element",tagName:s,properties:{},children:o}}n.type==="element"&&i&&Object.assign(n.properties,os(i)),"children"in n&&n.children&&r!==null&&r!==void 0&&(n.children=r)}return n}function Gy(e,t){const n=t.data||{},s="value"in t&&!(Jr.call(n,"hProperties")||Jr.call(n,"hChildren"))?{type:"text",value:t.value}:{type:"element",tagName:"div",properties:{},children:e.all(t)};return e.patch(t,s),e.applyData(t,s)}function Qy(e,t){const n=[];let s=-1;for(t&&n.push({type:"text",value:`
22
+ `});++s<e.length;)s&&n.push({type:"text",value:`
23
+ `}),n.push(e[s]);return t&&e.length>0&&n.push({type:"text",value:`
24
+ `}),n}function Ko(e){let t=0,n=e.charCodeAt(t);for(;n===9||n===32;)t++,n=e.charCodeAt(t);return e.slice(t)}function Xo(e,t){const n=Wy(e,t),s=n.one(e,void 0),r=Ly(n),i=Array.isArray(s)?{type:"root",children:s}:s||{type:"root",children:[]};return r&&i.children.push({type:"text",value:`
25
+ `},r),i}function Jy(e,t){return e&&"run"in e?async function(n,s){const r=Xo(n,{file:s,...t});await e.run(r,s)}:function(n,s){return Xo(n,{file:s,...e||t})}}function ea(e){if(e)throw e}var wr,ta;function Zy(){if(ta)return wr;ta=1;var e=Object.prototype.hasOwnProperty,t=Object.prototype.toString,n=Object.defineProperty,s=Object.getOwnPropertyDescriptor,r=function(u){return typeof Array.isArray=="function"?Array.isArray(u):t.call(u)==="[object Array]"},i=function(u){if(!u||t.call(u)!=="[object Object]")return!1;var d=e.call(u,"constructor"),f=u.constructor&&u.constructor.prototype&&e.call(u.constructor.prototype,"isPrototypeOf");if(u.constructor&&!d&&!f)return!1;var m;for(m in u);return typeof m>"u"||e.call(u,m)},o=function(u,d){n&&d.name==="__proto__"?n(u,d.name,{enumerable:!0,configurable:!0,value:d.newValue,writable:!0}):u[d.name]=d.newValue},a=function(u,d){if(d==="__proto__")if(e.call(u,d)){if(s)return s(u,d).value}else return;return u[d]};return wr=function c(){var u,d,f,m,h,g,x=arguments[0],v=1,w=arguments.length,I=!1;for(typeof x=="boolean"&&(I=x,x=arguments[1]||{},v=2),(x==null||typeof x!="object"&&typeof x!="function")&&(x={});v<w;++v)if(u=arguments[v],u!=null)for(d in u)f=a(x,d),m=a(u,d),x!==m&&(I&&m&&(i(m)||(h=r(m)))?(h?(h=!1,g=f&&r(f)?f:[]):g=f&&i(f)?f:{},o(x,{name:d,newValue:c(I,g,m)})):typeof m<"u"&&o(x,{name:d,newValue:m}));return x},wr}var Yy=Zy();const Sr=Da(Yy);function Zr(e){if(typeof e!="object"||e===null)return!1;const t=Object.getPrototypeOf(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Symbol.toStringTag in e)&&!(Symbol.iterator in e)}function Ky(){const e=[],t={run:n,use:s};return t;function n(...r){let i=-1;const o=r.pop();if(typeof o!="function")throw new TypeError("Expected function as last argument, not "+o);a(null,...r);function a(c,...u){const d=e[++i];let f=-1;if(c){o(c);return}for(;++f<r.length;)(u[f]===null||u[f]===void 0)&&(u[f]=r[f]);r=u,d?Xy(d,a)(...u):o(null,...u)}}function s(r){if(typeof r!="function")throw new TypeError("Expected `middelware` to be a function, not "+r);return e.push(r),t}}function Xy(e,t){let n;return s;function s(...o){const a=e.length>o.length;let c;a&&o.push(r);try{c=e.apply(this,o)}catch(u){const d=u;if(a&&n)throw d;return r(d)}a||(c&&c.then&&typeof c.then=="function"?c.then(i,r):c instanceof Error?r(c):i(c))}function r(o,...a){n||(n=!0,t(o,...a))}function i(o){r(null,o)}}const st={basename:ex,dirname:tx,extname:nx,join:sx,sep:"/"};function ex(e,t){if(t!==void 0&&typeof t!="string")throw new TypeError('"ext" argument must be a string');bn(e);let n=0,s=-1,r=e.length,i;if(t===void 0||t.length===0||t.length>e.length){for(;r--;)if(e.codePointAt(r)===47){if(i){n=r+1;break}}else s<0&&(i=!0,s=r+1);return s<0?"":e.slice(n,s)}if(t===e)return"";let o=-1,a=t.length-1;for(;r--;)if(e.codePointAt(r)===47){if(i){n=r+1;break}}else o<0&&(i=!0,o=r+1),a>-1&&(e.codePointAt(r)===t.codePointAt(a--)?a<0&&(s=r):(a=-1,s=o));return n===s?s=o:s<0&&(s=e.length),e.slice(n,s)}function tx(e){if(bn(e),e.length===0)return".";let t=-1,n=e.length,s;for(;--n;)if(e.codePointAt(n)===47){if(s){t=n;break}}else s||(s=!0);return t<0?e.codePointAt(0)===47?"/":".":t===1&&e.codePointAt(0)===47?"//":e.slice(0,t)}function nx(e){bn(e);let t=e.length,n=-1,s=0,r=-1,i=0,o;for(;t--;){const a=e.codePointAt(t);if(a===47){if(o){s=t+1;break}continue}n<0&&(o=!0,n=t+1),a===46?r<0?r=t:i!==1&&(i=1):r>-1&&(i=-1)}return r<0||n<0||i===0||i===1&&r===n-1&&r===s+1?"":e.slice(r,n)}function sx(...e){let t=-1,n;for(;++t<e.length;)bn(e[t]),e[t]&&(n=n===void 0?e[t]:n+"/"+e[t]);return n===void 0?".":rx(n)}function rx(e){bn(e);const t=e.codePointAt(0)===47;let n=ix(e,!t);return n.length===0&&!t&&(n="."),n.length>0&&e.codePointAt(e.length-1)===47&&(n+="/"),t?"/"+n:n}function ix(e,t){let n="",s=0,r=-1,i=0,o=-1,a,c;for(;++o<=e.length;){if(o<e.length)a=e.codePointAt(o);else{if(a===47)break;a=47}if(a===47){if(!(r===o-1||i===1))if(r!==o-1&&i===2){if(n.length<2||s!==2||n.codePointAt(n.length-1)!==46||n.codePointAt(n.length-2)!==46){if(n.length>2){if(c=n.lastIndexOf("/"),c!==n.length-1){c<0?(n="",s=0):(n=n.slice(0,c),s=n.length-1-n.lastIndexOf("/")),r=o,i=0;continue}}else if(n.length>0){n="",s=0,r=o,i=0;continue}}t&&(n=n.length>0?n+"/..":"..",s=2)}else n.length>0?n+="/"+e.slice(r+1,o):n=e.slice(r+1,o),s=o-r-1;r=o,i=0}else a===46&&i>-1?i++:i=-1}return n}function bn(e){if(typeof e!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(e))}const ox={cwd:ax};function ax(){return"/"}function Yr(e){return!!(e!==null&&typeof e=="object"&&"href"in e&&e.href&&"protocol"in e&&e.protocol&&e.auth===void 0)}function lx(e){if(typeof e=="string")e=new URL(e);else if(!Yr(e)){const t=new TypeError('The "path" argument must be of type string or an instance of URL. Received `'+e+"`");throw t.code="ERR_INVALID_ARG_TYPE",t}if(e.protocol!=="file:"){const t=new TypeError("The URL must be of scheme file");throw t.code="ERR_INVALID_URL_SCHEME",t}return cx(e)}function cx(e){if(e.hostname!==""){const s=new TypeError('File URL host must be "localhost" or empty on darwin');throw s.code="ERR_INVALID_FILE_URL_HOST",s}const t=e.pathname;let n=-1;for(;++n<t.length;)if(t.codePointAt(n)===37&&t.codePointAt(n+1)===50){const s=t.codePointAt(n+2);if(s===70||s===102){const r=new TypeError("File URL path must not include encoded / characters");throw r.code="ERR_INVALID_FILE_URL_PATH",r}}return decodeURIComponent(t)}const vr=["history","path","basename","stem","extname","dirname"];class Ll{constructor(t){let n;t?Yr(t)?n={path:t}:typeof t=="string"||ux(t)?n={value:t}:n=t:n={},this.cwd="cwd"in n?"":ox.cwd(),this.data={},this.history=[],this.messages=[],this.value,this.map,this.result,this.stored;let s=-1;for(;++s<vr.length;){const i=vr[s];i in n&&n[i]!==void 0&&n[i]!==null&&(this[i]=i==="history"?[...n[i]]:n[i])}let r;for(r in n)vr.includes(r)||(this[r]=n[r])}get basename(){return typeof this.path=="string"?st.basename(this.path):void 0}set basename(t){kr(t,"basename"),Cr(t,"basename"),this.path=st.join(this.dirname||"",t)}get dirname(){return typeof this.path=="string"?st.dirname(this.path):void 0}set dirname(t){na(this.basename,"dirname"),this.path=st.join(t||"",this.basename)}get extname(){return typeof this.path=="string"?st.extname(this.path):void 0}set extname(t){if(Cr(t,"extname"),na(this.dirname,"extname"),t){if(t.codePointAt(0)!==46)throw new Error("`extname` must start with `.`");if(t.includes(".",1))throw new Error("`extname` cannot contain multiple dots")}this.path=st.join(this.dirname,this.stem+(t||""))}get path(){return this.history[this.history.length-1]}set path(t){Yr(t)&&(t=lx(t)),kr(t,"path"),this.path!==t&&this.history.push(t)}get stem(){return typeof this.path=="string"?st.basename(this.path,this.extname):void 0}set stem(t){kr(t,"stem"),Cr(t,"stem"),this.path=st.join(this.dirname||"",t+(this.extname||""))}fail(t,n,s){const r=this.message(t,n,s);throw r.fatal=!0,r}info(t,n,s){const r=this.message(t,n,s);return r.fatal=void 0,r}message(t,n,s){const r=new Ae(t,n,s);return this.path&&(r.name=this.path+":"+r.name,r.file=this.path),r.fatal=!1,this.messages.push(r),r}toString(t){return this.value===void 0?"":typeof this.value=="string"?this.value:new TextDecoder(t||void 0).decode(this.value)}}function Cr(e,t){if(e&&e.includes(st.sep))throw new Error("`"+t+"` cannot be a path: did not expect `"+st.sep+"`")}function kr(e,t){if(!e)throw new Error("`"+t+"` cannot be empty")}function na(e,t){if(!e)throw new Error("Setting `"+t+"` requires `path` to be set too")}function ux(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const dx=(function(e){const s=this.constructor.prototype,r=s[e],i=function(){return r.apply(i,arguments)};return Object.setPrototypeOf(i,s),i}),hx={}.hasOwnProperty;class Pi extends dx{constructor(){super("copy"),this.Compiler=void 0,this.Parser=void 0,this.attachers=[],this.compiler=void 0,this.freezeIndex=-1,this.frozen=void 0,this.namespace={},this.parser=void 0,this.transformers=Ky()}copy(){const t=new Pi;let n=-1;for(;++n<this.attachers.length;){const s=this.attachers[n];t.use(...s)}return t.data(Sr(!0,{},this.namespace)),t}data(t,n){return typeof t=="string"?arguments.length===2?(Tr("data",this.frozen),this.namespace[t]=n,this):hx.call(this.namespace,t)&&this.namespace[t]||void 0:t?(Tr("data",this.frozen),this.namespace=t,this):this.namespace}freeze(){if(this.frozen)return this;const t=this;for(;++this.freezeIndex<this.attachers.length;){const[n,...s]=this.attachers[this.freezeIndex];if(s[0]===!1)continue;s[0]===!0&&(s[0]=void 0);const r=n.call(t,...s);typeof r=="function"&&this.transformers.use(r)}return this.frozen=!0,this.freezeIndex=Number.POSITIVE_INFINITY,this}parse(t){this.freeze();const n=On(t),s=this.parser||this.Parser;return Er("parse",s),s(String(n),n)}process(t,n){const s=this;return this.freeze(),Er("process",this.parser||this.Parser),Pr("process",this.compiler||this.Compiler),n?r(void 0,n):new Promise(r);function r(i,o){const a=On(t),c=s.parse(a);s.run(c,a,function(d,f,m){if(d||!f||!m)return u(d);const h=f,g=s.stringify(h,m);mx(g)?m.value=g:m.result=g,u(d,m)});function u(d,f){d||!f?o(d):i?i(f):n(void 0,f)}}}processSync(t){let n=!1,s;return this.freeze(),Er("processSync",this.parser||this.Parser),Pr("processSync",this.compiler||this.Compiler),this.process(t,r),ra("processSync","process",n),s;function r(i,o){n=!0,ea(i),s=o}}run(t,n,s){sa(t),this.freeze();const r=this.transformers;return!s&&typeof n=="function"&&(s=n,n=void 0),s?i(void 0,s):new Promise(i);function i(o,a){const c=On(n);r.run(t,c,u);function u(d,f,m){const h=f||t;d?a(d):o?o(h):s(void 0,h,m)}}}runSync(t,n){let s=!1,r;return this.run(t,n,i),ra("runSync","run",s),r;function i(o,a){ea(o),r=a,s=!0}}stringify(t,n){this.freeze();const s=On(n),r=this.compiler||this.Compiler;return Pr("stringify",r),sa(t),r(t,s)}use(t,...n){const s=this.attachers,r=this.namespace;if(Tr("use",this.frozen),t!=null)if(typeof t=="function")c(t,n);else if(typeof t=="object")Array.isArray(t)?a(t):o(t);else throw new TypeError("Expected usable value, not `"+t+"`");return this;function i(u){if(typeof u=="function")c(u,[]);else if(typeof u=="object")if(Array.isArray(u)){const[d,...f]=u;c(d,f)}else o(u);else throw new TypeError("Expected usable value, not `"+u+"`")}function o(u){if(!("plugins"in u)&&!("settings"in u))throw new Error("Expected usable value but received an empty preset, which is probably a mistake: presets typically come with `plugins` and sometimes with `settings`, but this has neither");a(u.plugins),u.settings&&(r.settings=Sr(!0,r.settings,u.settings))}function a(u){let d=-1;if(u!=null)if(Array.isArray(u))for(;++d<u.length;){const f=u[d];i(f)}else throw new TypeError("Expected a list of plugins, not `"+u+"`")}function c(u,d){let f=-1,m=-1;for(;++f<s.length;)if(s[f][0]===u){m=f;break}if(m===-1)s.push([u,...d]);else if(d.length>0){let[h,...g]=d;const x=s[m][1];Zr(x)&&Zr(h)&&(h=Sr(!0,x,h)),s[m]=[u,h,...g]}}}}const fx=new Pi().freeze();function Er(e,t){if(typeof t!="function")throw new TypeError("Cannot `"+e+"` without `parser`")}function Pr(e,t){if(typeof t!="function")throw new TypeError("Cannot `"+e+"` without `compiler`")}function Tr(e,t){if(t)throw new Error("Cannot call `"+e+"` on a frozen processor.\nCreate a new processor first, by calling it: use `processor()` instead of `processor`.")}function sa(e){if(!Zr(e)||typeof e.type!="string")throw new TypeError("Expected node, got `"+e+"`")}function ra(e,t,n){if(!n)throw new Error("`"+e+"` finished async. Use `"+t+"` instead")}function On(e){return px(e)?e:new Ll(e)}function px(e){return!!(e&&typeof e=="object"&&"message"in e&&"messages"in e)}function mx(e){return typeof e=="string"||gx(e)}function gx(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const yx="https://github.com/remarkjs/react-markdown/blob/main/changelog.md",ia=[],oa={allowDangerousHtml:!0},xx=/^(https?|ircs?|mailto|xmpp)$/i,bx=[{from:"astPlugins",id:"remove-buggy-html-in-markdown-parser"},{from:"allowDangerousHtml",id:"remove-buggy-html-in-markdown-parser"},{from:"allowNode",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"allowElement"},{from:"allowedTypes",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"allowedElements"},{from:"className",id:"remove-classname"},{from:"disallowedTypes",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"disallowedElements"},{from:"escapeHtml",id:"remove-buggy-html-in-markdown-parser"},{from:"includeElementIndex",id:"#remove-includeelementindex"},{from:"includeNodeIndex",id:"change-includenodeindex-to-includeelementindex"},{from:"linkTarget",id:"remove-linktarget"},{from:"plugins",id:"change-plugins-to-remarkplugins",to:"remarkPlugins"},{from:"rawSourcePos",id:"#remove-rawsourcepos"},{from:"renderers",id:"change-renderers-to-components",to:"components"},{from:"source",id:"change-source-to-children",to:"children"},{from:"sourcePos",id:"#remove-sourcepos"},{from:"transformImageUri",id:"#add-urltransform",to:"urlTransform"},{from:"transformLinkUri",id:"#add-urltransform",to:"urlTransform"}];function wx(e){const t=Sx(e),n=vx(e);return Cx(t.runSync(t.parse(n),n),e)}function Sx(e){const t=e.rehypePlugins||ia,n=e.remarkPlugins||ia,s=e.remarkRehypeOptions?{...e.remarkRehypeOptions,...oa}:oa;return fx().use(Xg).use(n).use(Jy,s).use(t)}function vx(e){const t=e.children||"",n=new Ll;return typeof t=="string"&&(n.value=t),n}function Cx(e,t){const n=t.allowedElements,s=t.allowElement,r=t.components,i=t.disallowedElements,o=t.skipHtml,a=t.unwrapDisallowed,c=t.urlTransform||kx;for(const d of bx)Object.hasOwn(t,d.from)&&(""+d.from+(d.to?"use `"+d.to+"` instead":"remove it")+yx+d.id,void 0);return zl(e,u),zp(e,{Fragment:l.Fragment,components:r,ignoreInvalidStyle:!0,jsx:l.jsx,jsxs:l.jsxs,passKeys:!0,passNode:!0});function u(d,f,m){if(d.type==="raw"&&m&&typeof f=="number")return o?m.children.splice(f,1):m.children[f]={type:"text",value:d.value},f;if(d.type==="element"){let h;for(h in yr)if(Object.hasOwn(yr,h)&&Object.hasOwn(d.properties,h)){const g=d.properties[h],x=yr[h];(x===null||x.includes(d.tagName))&&(d.properties[h]=c(String(g||""),h,d))}}if(d.type==="element"){let h=n?!n.includes(d.tagName):i?i.includes(d.tagName):!1;if(!h&&s&&typeof f=="number"&&(h=!s(d,f,m)),h&&m&&typeof f=="number")return a&&d.children?m.children.splice(f,1,...d.children):m.children.splice(f,1),f}}}function kx(e){const t=e.indexOf(":"),n=e.indexOf("?"),s=e.indexOf("#"),r=e.indexOf("/");return t===-1||r!==-1&&t>r||n!==-1&&t>n||s!==-1&&t>s||xx.test(e.slice(0,t))?e:""}const _l=p.createContext(null);function Ex({children:e,host:t}){return l.jsx(_l.Provider,{value:t,children:e})}function Rl(){const e=p.useContext(_l);if(!e)throw new Error("usePluginHost must be used within PluginHostProvider");return e}const Ol="openlearn:dashboardVisibility";function Px(){try{const e=localStorage.getItem(Ol);if(e)return new Map(JSON.parse(e))}catch{}return new Map}function aa(e){try{localStorage.setItem(Ol,JSON.stringify([...e.entries()]))}catch{}}const ve=Ha()((e,t)=>({activePlugins:[],extensionPoints:new Map,services:null,dashboardVisibility:Px(),initialized:!1,initialize:n=>e({services:n,initialized:!0}),addPlugin:n=>e(s=>({activePlugins:[...s.activePlugins,n]})),removePlugin:n=>e(s=>({activePlugins:s.activePlugins.filter(r=>r.id!==n)})),updatePluginState:(n,s)=>e(r=>({activePlugins:r.activePlugins.map(i=>i.id===n?{...i,state:s}:i)})),registerExtensionPoint:(n,s)=>e(r=>{const i=r.extensionPoints.get(n)??[];if(i.find(c=>c.id===s.id)){const c=new Map(r.extensionPoints);return c.set(n,i.map(u=>u.id===s.id?s:u)),{extensionPoints:c}}const a=new Map(r.extensionPoints);return a.set(n,[...i,s]),{extensionPoints:a}}),unregisterExtensionPoint:(n,s)=>e(r=>{const i=r.extensionPoints.get(n);if(!i)return r;const o=i.filter(c=>c.id!==s),a=new Map(r.extensionPoints);return o.length===0?a.delete(n):a.set(n,o),{extensionPoints:a}}),unregisterPluginExtensionPoints:n=>e(s=>{const r=new Map(s.extensionPoints);for(const[i,o]of r){const a=o.filter(c=>c.pluginId!==n);a.length===0?r.delete(i):r.set(i,a)}return{extensionPoints:r}}),getExtensions:n=>[...t().extensionPoints.get(n)??[]].sort((r,i)=>(r.position??100)-(i.position??100)),setDashboardVisibility:(n,s)=>e(r=>{const i=new Map(r.dashboardVisibility);return i.set(n,s),aa(i),{dashboardVisibility:i}}),setDashboardVisibilityBatch:n=>e(s=>{const r=new Map(s.dashboardVisibility);for(const[i,o]of n)r.set(i,o);return aa(r),{dashboardVisibility:r}})}));function Tx(){return l.jsx("div",{className:"w-full h-32 bg-gray-100 rounded-xl animate-pulse flex items-center justify-center",children:l.jsxs("div",{className:"flex flex-col items-center gap-2",children:[l.jsx(ui,{size:24,className:"text-gray-400 animate-spin"}),l.jsx("span",{className:"text-xs text-gray-400",children:"Loading..."})]})})}class Nx extends et.Component{constructor(t){super(t),this.state={hasError:!1},this.props=t}static getDerivedStateFromError(){return{hasError:!0}}render(){return this.state.hasError?this.props.fallback??null:this.props.children}}function Ix({ext:e,route:t,slotProps:n,slot:s}){const r=et.useRef(null),i=JSON.stringify(n||{});et.useEffect(()=>{r.current&&typeof e.render=="function"&&(r.current.innerHTML="",Promise.resolve(e.render(r.current,{route:t,...n})).catch(console.error))},[e,t,i]);const a=s==="teacher.dashboard.widget"?"h-auto":"h-full min-h-0";return l.jsx("div",{ref:r,className:`w-full ${a}`})}const Nr=new WeakMap;function jx(e){const t=e.component,n=Nr.get(t);if(n)return n;if(t.__isLazyFactory===!0){const s=et.lazy(t);return Nr.set(t,s),s}return Nr.set(t,t),t}function h0({slot:e,fallback:t,lang:n,route:s,slotProps:r,placement:i}){let a=Rl().getExtensions(e);const c=ve(f=>f.dashboardVisibility),u=ce(f=>f.selectedLesson),d=ce(f=>f.liveClassSelectedClassId);return i&&(a=a.filter(f=>(f.placement??"after")===i)),a.length===0?null:e==="teacher.tab"&&r?.renderType==="button"?l.jsx(l.Fragment,{children:a.map(f=>{const m=`${f.pluginId}/${f.id}`,h=r?.teacherTab===m,g=f.title||f.label||f.id;return l.jsxs("button",{onClick:()=>r?.setTeacherTab?.(m),className:`flex items-center gap-3 p-3 transition-colors text-sm font-medium rounded-xl ${h?"bg-indigo-50 text-indigo-700 font-bold":"text-gray-600 hover:bg-gray-50"} ${r?.mainNavCollapsed?"justify-center px-2":""}`,title:g,children:[l.jsx(ci,{size:20,className:"shrink-0"}),l.jsx("span",{className:r?.mainNavCollapsed?"hidden":"hidden md:block",children:g})]},`${f.pluginId}/${f.id}`)})}):l.jsx(l.Fragment,{children:a.map(f=>{const m=typeof f.component=="function",h=typeof f.render=="function";return e==="teacher.dashboard.widget"&&c.get(f.pluginId)===!1||!m&&!h?null:l.jsx(Nx,{fallback:l.jsx("div",{className:"bg-red-50 border border-red-200 rounded-lg p-4 text-sm text-red-700",children:l.jsx("p",{children:n==="zh"?"扩展组件加载失败":"Extension failed to load"})}),children:l.jsx(p.Suspense,{fallback:t??l.jsx(Tx,{}),children:m?et.createElement(jx(f),{route:f.route||s,lessonId:u,classId:d,...f.slotProps,...r}):l.jsx(Ix,{ext:f,route:f.route||s,slotProps:{lessonId:u,classId:d,...f.slotProps,...r},slot:e})})},`${f.pluginId}/${f.id}`)})})}const Ax=(e,t)=>{const n=e?e.trim():"New Course";switch(t){case"Mathematics":return`# ${n}
26
+
27
+ ## 101 Course Core Foundations
28
+ Welcome to our mathematics laboratory. This course is designed to break down abstract calculations into visual whiteboard proofs and real-world application models.
29
+
30
+ ### 📐 Key Theorems & Proof Matrix
31
+ - **Formula A**: $E = mc^2$ or equivalent derivative parameters
32
+ - **Core Axiom**: For every linear projection, a finite dimension defines its trace.
33
+
34
+ ### 实践演练随堂真题 Practice Problems
35
+ 1. Calculate the local optima for the function on the interactive workspace.
36
+ 2. Prove the uniqueness of the residual limit under Gaussian conditions.
37
+
38
+ ### 📥 Homework Assignment Task
39
+ Identify three real-world physical structures implementing these spatial principles and coordinate maps.`;case"ComputerScience":return`# ${n}
40
+
41
+ ## 💻 Technical Exploration & Engineering Lab
42
+ This session acts as an immersive sandbox exploring core algorithmic structures, optimization mechanics, and data abstractions.
43
+
44
+ ### ⚙️ Core Lecture Blueprint & Pseudocode
45
+ \`\`\`python
46
+ def optimize_weights(data, factor=0.01):
47
+ # Initialize local metrics
48
+ scores = [x * factor for x in data]
49
+ return sum(scores) / len(scores)
50
+ \`\`\`
51
+
52
+ ### ⚡ Laboratory Workspace Drill
53
+ - **Objective**: Develop a linear hash-map with zero-collision distribution.
54
+ - **Action**: Use the interactive canvas to sketch data pipelines.
55
+
56
+ ### 📝 Post-Class Evaluation
57
+ Write a 200-word critique analyzing memory-locality vs execution-speed trade-offs in low-level registers.`;case"Literature":return`# ${n}
58
+
59
+ ## ✍️ Literary Critical Analysis Seminar
60
+ This curriculum evaluates textual aesthetics, semantic patterns, subtextual symbols, and historical contexts across classic paradigms.
61
+
62
+ ### 🏛️ Classic Textual Excerpts
63
+ > "Reality represents a state of constant translation between what is experienced and what is chronicled."
64
+
65
+ ### 💭 Critique Evaluation Metrics
66
+ - **Theme Assessment**: Analyze structural ironies within contemporary essays.
67
+ - **Author Intention**: Focus on pacing triggers and character foils.
68
+
69
+ ### 💬 Classroom Collaborative Debate Topics
70
+ Does digital notation diminish the biological connection to textual journaling? Discuss under 15 minutes framework.`;case"Physics":return`# ${n}
71
+
72
+ ## ⚡ Experimental Physics & Natural Science Sandbox
73
+ In this session, theoretical models undergo practical validation through interactive virtual whiteboard modeling and numerical measurements.
74
+
75
+ ### 🔬 Key Mechanical Principles & Constraints
76
+ - **Axiom 1**: Momentum is conserved in closed coordinate vectors.
77
+ - **Axiom 2**: Resistance is directly proportional to temperature factors.
78
+
79
+ ### 🛠️ Lab Step-by-Step Procedure
80
+ 1. Plot the force vectors acting on the balance coordinate vertices.
81
+ 2. Measure the velocity coefficients across three alternate trial loops.
82
+
83
+ ### 📝 Homework Assignment Evaluation
84
+ Calculate energy loss ratios using standard mathematical integrals in your journal.`;case"History":return`# ${n}
85
+
86
+ ## 🏛️ Geopolitical Context Mapping & Historical Context
87
+ This course explores historical trends, decision frameworks, resource patterns, and socio-economic influences that shaped modern civilization.
88
+
89
+ ### 🗺️ Context Timeline Focus
90
+ - **Phase A**: Resource migration patterns along major trade waterways.
91
+ - **Phase B**: Strategic institutional reforms and cultural integration cycles.
92
+
93
+ ### 🔍 Primary Source Critique Work
94
+ Analyze the 18th-century legislative documents for bias, context gaps, and underlying socio-economic drivers.
95
+
96
+ ### 💬 Group Discussion Prompts
97
+ How did geography influence the longevity of ancient administrative models?`;case"Art":return`# ${n}
98
+
99
+ ## 🎨 Visual Composition & Creative Sketching Studio
100
+ A workshop focusing on aesthetic principles, negative space ratios, visual balance, and dynamic typography models.
101
+
102
+ ### 🖌️ Design Principles
103
+ - **Golden Spiral**: Align critical focal points with recursive visual arcs.
104
+ - **Chiaroscuro**: Leverage deep high-contrast shading to establish three-dimensional form.
105
+
106
+ ### 🛠️ Whiteboard Practical Sandbox Project
107
+ Collaborate on the dynamic canvas to draft a raw responsive layout using minimal monochromatic blocks.
108
+
109
+ ### 🎨 Portfolio Task
110
+ Submit three divergent conceptual drafts representing active space constraints.`;default:return`# ${n}
111
+
112
+ ## 🔮 Multidisciplinary Advanced Exploration & Research
113
+ This course integrates cross-subject paradigms, cognitive practices, and critical reasoning methods.
114
+
115
+ ### 📚 Course Syllabus Modules
116
+ - **Module 1**: Core theoretical grounding and conceptual models.
117
+ - **Module 2**: Practical exercises combining research and action.
118
+
119
+ ### 📝 Interactive Classroom Tasks
120
+ 1. Formulate 2 key research queries aligning with this lecture.
121
+ 2. Sketch the systemic flow diagram depicting interaction factors.
122
+
123
+ ### 📥 Assignment Brief
124
+ Draft a 300-word integration proposal based on today's whiteboard exercises.`}};async function zx(e="all"){const t=await fetch(`/api/activities?role=${encodeURIComponent(e)}`,{headers:{Accept:"application/json"}});if(!t.ok)throw new Error(`Failed to load activities (${t.status})`);return(await t.json()).activities??[]}async function la(){const e=await fetch("/api/activities/running",{headers:{Accept:"application/json"}});if(!e.ok)throw new Error(`Failed to load running activities (${e.status})`);return(await e.json()).activities??[]}async function Lx(e){const t=await fetch(`/api/activities/${encodeURIComponent(e)}/finish`,{method:"POST",headers:{"Content-Type":"application/json"}});if(!t.ok){const n=await t.json().catch(()=>({}));throw new Error(n.error||`Failed to finish activity (${t.status})`)}}async function _x(e){const t=await fetch(`/api/activities/${encodeURIComponent(e)}/pause`,{method:"POST",headers:{"Content-Type":"application/json"}});if(!t.ok){const n=await t.json().catch(()=>({}));throw new Error(n.error||`Failed to pause activity (${t.status})`)}}async function Rx(e){const t=await fetch(`/api/activities/${encodeURIComponent(e)}/resume`,{method:"POST",headers:{"Content-Type":"application/json"}});if(!t.ok){const n=await t.json().catch(()=>({}));throw new Error(n.error||`Failed to resume activity (${t.status})`)}}async function Ox(e,t,n){const s=await fetch(`/api/activities/${encodeURIComponent(e)}/start`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({payload:t??{},actorId:n})}),r=await s.json();if(!s.ok||r.ok===!1)throw new Error(r.error||`Failed to start activity (${s.status})`);return r}const Mn={padding:"12px",color:"#e2e8f0",fontSize:"13px"},Mx={HelpCircle:Xh,Vote:Kh,BarChart3:Yh,MessagesSquare:Zh,Users:$a,FileText:qa,Trophy:Jh,CheckCircle2:li,BookOpen:ai};function Dx({name:e,className:t}){const n=e&&Mx[e]||ci;return l.jsx(n,{size:18,className:t})}function Fx(e,t){if(!e)return t==="zh"?"进行中":"In progress";const n=Math.max(0,Math.floor((Date.now()-e)/1e3)),s=Math.floor(n/60),r=n%60;return t==="zh"?`${s} 分 ${r} 秒`:`${s}m ${r}s`}const Ml=({role:e,actorId:t,lang:n="en",classroomId:s,mode:r="launcher"})=>{const[i,o]=p.useState([]),[a,c]=p.useState(!0),[u,d]=p.useState(null),[f,m]=p.useState({}),[h,g]=p.useState([]),[x,v]=p.useState(!0),[w,I]=p.useState(null),[S,P]=p.useState(null),[z,E]=p.useState(!1),[L,_]=p.useState(null),M=ce(k=>k.setTeacherTab),N=p.useMemo(()=>{const k=new Map;for(const B of i){const y=B.category;k.has(y)||k.set(y,[]),k.get(y).push(B)}return Array.from(k.entries())},[i]);p.useEffect(()=>{if(r!=="launcher")return;let k=!1;return c(!0),zx(e).then(B=>{k||o(B)}).catch(B=>{k||d(B instanceof Error?B.message:String(B))}).finally(()=>{k||c(!1)}),()=>{k=!0}},[e,r]),p.useEffect(()=>{if(r!=="status")return;let k=!1;const B=async()=>{try{const te=await la();k||g(te)}catch(te){k||I(te instanceof Error?te.message:String(te))}finally{k||v(!1)}};B();const y=setInterval(B,5e3);return()=>{k=!0,clearInterval(y)}},[r]);const A=async k=>{if(S){E(!0),_(null);try{await k(S),g(await la())}catch(B){_(B instanceof Error?B.message:String(B))}finally{E(!1)}}},R=()=>A(Lx),D=()=>A(_x),F=()=>A(Rx),j=()=>{P(null),M("live_class")};if(r==="status"){if(x)return l.jsx("div",{className:"bg-white border border-slate-200/80 rounded-2xl p-5 shadow-sm h-24 animate-pulse"});if(w||h.length===0)return null;const k=h.find(B=>B.id===S)||null;return l.jsxs("div",{className:"bg-white border border-slate-200/80 rounded-2xl p-5 shadow-sm",children:[l.jsxs("div",{className:"flex items-center justify-between mb-3",children:[l.jsxs("div",{className:"flex items-center gap-2 text-slate-800 font-extrabold",children:[l.jsx("span",{children:"🧩"}),l.jsx("span",{children:n==="zh"?"进行中的活动":"Activities in Progress"})]}),l.jsx("span",{className:"text-[10px] font-bold bg-indigo-50 text-indigo-700 px-2 py-0.5 rounded-full",children:h.length})]}),l.jsx("div",{className:"flex flex-col gap-2",children:h.map(B=>{const y=B.state==="running";return l.jsxs("button",{onClick:()=>P(B.id),className:"w-full flex items-center gap-3 text-left bg-slate-50 hover:bg-slate-100 border border-slate-200/70 rounded-xl p-3 transition-colors",children:[l.jsx(Dx,{name:B.icon,className:"text-indigo-600 shrink-0"}),l.jsxs("div",{className:"min-w-0 flex-1",children:[l.jsx("div",{className:"font-bold text-slate-800 truncate",children:B.name}),B.category&&l.jsx("div",{className:"text-[11px] text-slate-500 truncate",children:B.category})]}),l.jsxs("div",{className:"flex flex-col items-end gap-1 shrink-0",children:[l.jsx("span",{className:`text-[10px] font-bold px-2 py-0.5 rounded-full ${y?"bg-emerald-100 text-emerald-700":"bg-amber-100 text-amber-700"}`,children:y?n==="zh"?"进行中":"Running":n==="zh"?"已暂停":"Paused"}),l.jsxs("span",{className:"text-[10px] text-slate-400 flex items-center gap-1",children:[l.jsx(Hh,{size:10})," ",Fx(B.startedAt,n)]})]})]},B.id)})}),k&&l.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/30 p-4",onClick:()=>P(null),children:l.jsxs("div",{className:"bg-white rounded-2xl shadow-xl w-full max-w-sm p-5",onClick:B=>B.stopPropagation(),children:[l.jsxs("div",{className:"flex items-center justify-between mb-3",children:[l.jsx("h3",{className:"font-bold text-slate-800",children:k.name}),l.jsx("button",{onClick:()=>P(null),className:"text-slate-400 hover:text-slate-600","aria-label":"close",children:l.jsx(At,{size:18})})]}),l.jsxs("div",{className:"text-sm text-slate-500 mb-1",children:[n==="zh"?"状态":"Status",":"," ",k.state==="running"?n==="zh"?"进行中":"Running":n==="zh"?"已暂停":"Paused"]}),l.jsxs("div",{className:"text-sm text-slate-500 mb-4",children:[n==="zh"?"开始时间":"Started",":"," ",k.startedAt?new Date(k.startedAt).toLocaleString():"-"]}),L&&l.jsx("div",{className:"text-xs text-rose-600 mb-2",children:L}),l.jsxs("div",{className:"flex gap-2",children:[k.state==="running"?l.jsxs("button",{disabled:z,onClick:D,className:"flex-1 flex items-center justify-center gap-1 bg-amber-500 hover:bg-amber-600 disabled:opacity-60 text-white rounded-lg py-2 text-sm font-bold",children:[l.jsx(Gh,{size:14})," ",n==="zh"?"暂停":"Pause"]}):l.jsxs("button",{disabled:z,onClick:F,className:"flex-1 flex items-center justify-center gap-1 bg-indigo-500 hover:bg-indigo-600 disabled:opacity-60 text-white rounded-lg py-2 text-sm font-bold",children:[l.jsx(Qh,{size:14})," ",n==="zh"?"恢复":"Resume"]}),l.jsx("button",{disabled:z,onClick:R,className:"flex-1 flex items-center justify-center gap-1 bg-rose-600 hover:bg-rose-700 disabled:opacity-60 text-white rounded-lg py-2 text-sm font-bold",children:z?n==="zh"?"处理中…":"Working…":n==="zh"?"结束":"End"})]}),l.jsx("button",{onClick:j,className:"w-full mt-2 bg-slate-100 hover:bg-slate-200 text-slate-700 rounded-lg py-2 text-sm font-bold",children:n==="zh"?"进入课堂":"Enter Classroom"})]})})]})}const T=async k=>{m(B=>({...B,[k.id]:n==="zh"?"启动中…":"Starting…"}));try{const B=await Ox(k.id,{classroomId:s,role:e},t);m(y=>({...y,[k.id]:B.dispatched?n==="zh"?"已启动 ✓":"Started ✓":n==="zh"?"已通知 ✓":"Notified ✓"}))}catch(B){m(y=>({...y,[k.id]:B instanceof Error?B.message:String(B)}))}};if(a)return l.jsx("div",{style:Mn,children:n==="zh"?"加载活动中…":"Loading activities…"});if(u)return l.jsxs("div",{style:Mn,children:[l.jsxs("div",{style:{fontWeight:600,marginBottom:6},children:["🧩 ",n==="zh"?"活动中心":"Activity Center"]}),l.jsx("div",{style:{opacity:.7},children:u})]});const $=e==="teacher"?n==="zh"?"活动中心(教师)":"Activity Center":n==="zh"?"活动(学生)":"Activities";return i.length===0?l.jsxs("div",{style:Mn,children:[l.jsxs("div",{style:{fontWeight:600,marginBottom:6},children:["🧩 ",$]}),l.jsx("div",{style:{opacity:.7},children:n==="zh"?"暂无可用活动。":"No activities available."})]}):l.jsxs("div",{style:Mn,children:[l.jsxs("div",{style:{fontWeight:600,marginBottom:8},children:["🧩 ",$]}),N.map(([k,B])=>l.jsxs("div",{style:{marginBottom:10},children:[l.jsx("div",{style:{opacity:.6,fontSize:11,textTransform:"uppercase",marginBottom:4},children:k}),l.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:8},children:B.map(y=>l.jsxs("div",{style:{border:"1px solid #334155",borderRadius:8,padding:"8px 10px",minWidth:150,background:"#0f172a"},children:[l.jsxs("div",{style:{fontWeight:600},children:[y.icon?`${y.icon} `:"▫️ ",y.name]}),y.description&&l.jsx("div",{style:{opacity:.7,fontSize:11,margin:"2px 0 6px"},children:y.description}),l.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[l.jsx("button",{onClick:()=>T(y),style:{cursor:"pointer",background:e==="teacher"?"#2563eb":"#0ea5e9",color:"#fff",border:"none",borderRadius:6,padding:"4px 10px",fontSize:12},children:e==="teacher"?n==="zh"?"启动":"Start":n==="zh"?"参与":"Open"}),f[y.id]&&l.jsx("span",{style:{fontSize:11,opacity:.85},children:f[y.id]})]}),l.jsx("div",{style:{opacity:.5,fontSize:10,marginTop:4},children:y.provider==="official"?"official":y.provider})]},y.id))})]},k))]})},Bx=Object.freeze(Object.defineProperty({__proto__:null,ActivityWorkspaceWidget:Ml},Symbol.toStringTag,{value:"Module"}));let ca=!1;function $x(){if(ca)return;ca=!0;const e=()=>Ie(()=>Promise.resolve().then(()=>Bx),void 0).then(t=>({default:()=>l.jsx(Ml,{role:"teacher",mode:"status"})}));e.__isLazyFactory=!0,ve.getState().registerExtensionPoint("teacher.dashboard.widget",{id:"official_activity_center",label:"Activity Center",icon:"Puzzle",pluginId:"openlearn-official",component:e})}const ua="@openlearn/frontend:IFrontendAPI",da="@openlearn/frontend:ISocketService",ha="@openlearn/frontend:IUIService",fa="@openlearn/frontend:IStorageService",Vx="@openlearn/frontend:ISemesterGradeService";var pe=(e=>(e.INSTALLED="installed",e.ACTIVATING="activating",e.ACTIVE="active",e.DEACTIVATING="deactivating",e.INACTIVE="inactive",e.ERROR="error",e.UNINSTALLED="uninstalled",e))(pe||{});const Ux=p.lazy(()=>Ie(()=>import("./StudentView-5bdEpjwh.js"),[]).then(e=>({default:e.StudentView}))),Wx=p.lazy(()=>Ie(()=>import("./TeacherView-DCTHvypF.js"),[]).then(e=>({default:e.TeacherView})));function qx(e){const{activeRole:t}=e;return l.jsx(p.Suspense,{fallback:l.jsxs("div",{className:"flex-1 flex flex-col items-center justify-center min-h-[50vh] text-slate-400 gap-3",children:[l.jsx(ui,{className:"w-8 h-8 animate-spin text-indigo-500"}),l.jsx("span",{className:"text-sm font-medium tracking-wide",children:"正在加载工作台..."})]}),children:t==="student"?l.jsx(Ux,{...e}):l.jsx(Wx,{...e})})}const Ti=p.createContext({});function Ni(e){const t=p.useRef(null);return t.current===null&&(t.current=e()),t.current}const Hx=typeof window<"u",Dl=Hx?p.useLayoutEffect:p.useEffect,fs=p.createContext(null),Ii=p.createContext({transformPagePoint:e=>e,isStatic:!1,reducedMotion:"never"});function pa(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function Gx(...e){return t=>{let n=!1;const s=e.map(r=>{const i=pa(r,t);return!n&&typeof i=="function"&&(n=!0),i});if(n)return()=>{for(let r=0;r<s.length;r++){const i=s[r];typeof i=="function"?i():pa(e[r],null)}}}}function Qx(...e){return p.useCallback(Gx(...e),e)}class Jx extends p.Component{getSnapshotBeforeUpdate(t){const n=this.props.childRef.current;if(dr(n)&&t.isPresent&&!this.props.isPresent&&this.props.pop!==!1){const s=n.offsetParent,r=dr(s)&&s.offsetWidth||0,i=dr(s)&&s.offsetHeight||0,o=getComputedStyle(n),a=this.props.sizeRef.current;a.height=parseFloat(o.height),a.width=parseFloat(o.width),a.top=n.offsetTop,a.left=n.offsetLeft,a.right=r-a.width-a.left,a.bottom=i-a.height-a.top,a.direction=o.direction}return null}componentDidUpdate(){}render(){return this.props.children}}function Zx({children:e,isPresent:t,anchorX:n,anchorY:s,root:r,pop:i}){const o=p.useId(),a=p.useRef(null),c=p.useRef({width:0,height:0,top:0,left:0,right:0,bottom:0,direction:"ltr"}),{nonce:u}=p.useContext(Ii),d=e.props?.ref??e?.ref,f=Qx(a,d);return p.useInsertionEffect(()=>{const{width:m,height:h,top:g,left:x,right:v,bottom:w,direction:I}=c.current;if(t||i===!1||!a.current||!m||!h)return;const S=I==="rtl",P=n==="left"?S?`right: ${v}`:`left: ${x}`:S?`left: ${x}`:`right: ${v}`,z=s==="bottom"?`bottom: ${w}`:`top: ${g}`;a.current.dataset.motionPopId=o;const E=document.createElement("style");u&&(E.nonce=u);const L=r??document.head;return L.appendChild(E),E.sheet&&E.sheet.insertRule(`
125
+ [data-motion-pop-id="${o}"] {
126
+ position: absolute !important;
127
+ width: ${m}px !important;
128
+ height: ${h}px !important;
129
+ ${P}px !important;
130
+ ${z}px !important;
131
+ }
132
+ `),()=>{a.current?.removeAttribute("data-motion-pop-id"),L.contains(E)&&L.removeChild(E)}},[t]),l.jsx(Jx,{isPresent:t,childRef:a,sizeRef:c,pop:i,children:i===!1?e:p.cloneElement(e,{ref:f})})}const Yx=({children:e,initial:t,isPresent:n,onExitComplete:s,custom:r,presenceAffectsLayout:i,mode:o,anchorX:a,anchorY:c,root:u})=>{const d=Ni(Kx),f=p.useId();let m=!0,h=p.useMemo(()=>(m=!1,{id:f,initial:t,isPresent:n,custom:r,onExitComplete:g=>{d.set(g,!0);for(const x of d.values())if(!x)return;s&&s()},register:g=>(d.set(g,!1),()=>d.delete(g))}),[n,d,s]);return i&&m&&(h={...h}),p.useMemo(()=>{d.forEach((g,x)=>d.set(x,!1))},[n]),p.useEffect(()=>{!n&&!d.size&&s&&s()},[n]),e=l.jsx(Zx,{pop:o==="popLayout",isPresent:n,anchorX:a,anchorY:c,root:u,children:e}),l.jsx(fs.Provider,{value:h,children:e})};function Kx(){return new Map}function Fl(e=!0){const t=p.useContext(fs);if(t===null)return[!0,null];const{isPresent:n,onExitComplete:s,register:r}=t,i=p.useId();p.useEffect(()=>{if(e)return r(i)},[e]);const o=p.useCallback(()=>e&&s&&s(i),[i,s,e]);return!n&&s?[!1,o]:[!0]}const Dn=e=>e.key||"";function ma(e){const t=[];return p.Children.forEach(e,n=>{p.isValidElement(n)&&t.push(n)}),t}const Xx=({children:e,custom:t,initial:n=!0,onExitComplete:s,presenceAffectsLayout:r=!0,mode:i="sync",propagate:o=!1,anchorX:a="left",anchorY:c="top",root:u})=>{const[d,f]=Fl(o),m=p.useMemo(()=>ma(e),[e]),h=o&&!d?[]:m.map(Dn),g=p.useRef(!0),x=p.useRef(m),v=Ni(()=>new Map),w=p.useRef(new Set),[I,S]=p.useState(m),[P,z]=p.useState(m);Dl(()=>{g.current=!1,x.current=m;for(let _=0;_<P.length;_++){const M=Dn(P[_]);h.includes(M)?(v.delete(M),w.current.delete(M)):v.get(M)!==!0&&v.set(M,!1)}},[P,h.length,h.join("-")]);const E=[];if(m!==I){let _=[...m];for(let M=0;M<P.length;M++){const N=P[M],A=Dn(N);h.includes(A)||(_.splice(M,0,N),E.push(N))}return i==="wait"&&E.length&&(_=E),z(ma(_)),S(m),null}const{forceRender:L}=p.useContext(Ti);return l.jsx(l.Fragment,{children:P.map(_=>{const M=Dn(_),N=o&&!d?!1:m===P||h.includes(M),A=()=>{if(w.current.has(M))return;if(v.has(M))w.current.add(M),v.set(M,!0);else return;let R=!0;v.forEach(D=>{D||(R=!1)}),R&&(L?.(),z(x.current),o&&f?.(),s&&s())};return l.jsx(Yx,{isPresent:N,initial:!g.current||n?void 0:!1,custom:t,presenceAffectsLayout:r,mode:i,root:u,onExitComplete:N?void 0:A,anchorX:a,anchorY:c,children:_},M)})})},Bl=p.createContext({strict:!1}),ga={animation:["animate","variants","whileHover","whileTap","exit","whileInView","whileFocus","whileDrag"],exit:["exit"],drag:["drag","dragControls"],focus:["whileFocus"],hover:["whileHover","onHoverStart","onHoverEnd"],tap:["whileTap","onTap","onTapStart","onTapCancel"],pan:["onPan","onPanStart","onPanSessionStart","onPanEnd"],inView:["whileInView","onViewportEnter","onViewportLeave"],layout:["layout","layoutId"]};let ya=!1;function eb(){if(ya)return;const e={};for(const t in ga)e[t]={isEnabled:n=>ga[t].some(s=>!!n[s])};Ga(e),ya=!0}function $l(){return eb(),cf()}function tb(e){const t=$l();for(const n in e)t[n]={...t[n],...e[n]};Ga(t)}const nb=new Set(["animate","exit","variants","initial","style","values","variants","transition","transformTemplate","custom","inherit","onBeforeLayoutMeasure","onAnimationStart","onAnimationComplete","onUpdate","onDragStart","onDrag","onDragEnd","onMeasureDragConstraints","onDirectionLock","onDragTransitionEnd","_dragX","_dragY","onHoverStart","onHoverEnd","onViewportEnter","onViewportLeave","globalTapTarget","propagate","ignoreStrict","viewport"]);function as(e){return e.startsWith("while")||e.startsWith("drag")&&e!=="draggable"||e.startsWith("layout")||e.startsWith("onTap")||e.startsWith("onPan")||e.startsWith("onLayout")||nb.has(e)}let Vl=e=>!as(e);function sb(e){typeof e=="function"&&(Vl=t=>t.startsWith("on")?!as(t):e(t))}try{sb(require("@emotion/is-prop-valid").default)}catch{}function rb(e,t,n){const s={};for(const r in e)r==="values"&&typeof e.values=="object"||di(e[r])||(Vl(r)||n===!0&&as(r)||!t&&!as(r)||e.draggable&&r.startsWith("onDrag"))&&(s[r]=e[r]);return s}const ps=p.createContext({});function ib(e,t){if(Qa(e)){const{initial:n,animate:s}=e;return{initial:n===!1||mo(n)?n:void 0,animate:mo(s)?s:void 0}}return e.inherit!==!1?t:{}}function ob(e){const{initial:t,animate:n}=ib(e,p.useContext(ps));return p.useMemo(()=>({initial:t,animate:n}),[xa(t),xa(n)])}function xa(e){return Array.isArray(e)?e.join(" "):e}const ji=()=>({style:{},transform:{},transformOrigin:{},vars:{}});function Ul(e,t,n){for(const s in t)!di(t[s])&&!uf(s,n)&&(e[s]=t[s])}function ab({transformTemplate:e},t){return p.useMemo(()=>{const n=ji();return df(n,t,e),Object.assign({},n.vars,n.style)},[t])}function lb(e,t){const n=e.style||{},s={};return Ul(s,n,e),Object.assign(s,ab(e,t)),s}function cb(e,t){const n={},s=lb(e,t);return e.drag&&e.dragListener!==!1&&(n.draggable=!1,s.userSelect=s.WebkitUserSelect=s.WebkitTouchCallout="none",s.touchAction=e.drag===!0?"none":`pan-${e.drag==="x"?"y":"x"}`),e.tabIndex===void 0&&(e.onTap||e.onTapStart||e.whileTap)&&(n.tabIndex=0),n.style=s,n}const Wl=()=>({...ji(),attrs:{}});function ub(e,t,n,s){const r=p.useMemo(()=>{const i=Wl();return hf(i,t,ff(s),e.transformTemplate,e.style),{...i.attrs,style:{...i.style}}},[t]);if(e.style){const i={};Ul(i,e.style,e),r.style={...i,...r.style}}return r}const db=["animate","circle","defs","desc","ellipse","g","image","line","filter","marker","mask","metadata","path","pattern","polygon","polyline","rect","stop","switch","symbol","svg","text","tspan","use","view"];function Ai(e){return typeof e!="string"||e.includes("-")?!1:!!(db.indexOf(e)>-1||/[A-Z]/u.test(e))}function hb(e,t,n,{latestValues:s},r,i=!1,o){const c=(o??Ai(e)?ub:cb)(t,s,r,e),u=rb(t,typeof e=="string",i),d=e!==p.Fragment?{...u,...c,ref:n}:{},{children:f}=t,m=p.useMemo(()=>di(f)?f.get():f,[f]);return p.createElement(e,{...d,children:m})}function fb({scrapeMotionValuesFromProps:e,createRenderState:t},n,s,r){return{latestValues:pb(n,s,r,e),renderState:t()}}function pb(e,t,n,s){const r={},i=s(e,{});for(const m in i)r[m]=pf(i[m]);let{initial:o,animate:a}=e;const c=Qa(e),u=mf(e);t&&u&&!c&&e.inherit!==!1&&(o===void 0&&(o=t.initial),a===void 0&&(a=t.animate));let d=n?n.initial===!1:!1;d=d||o===!1;const f=d?a:o;if(f&&typeof f!="boolean"&&!Ja(f)){const m=Array.isArray(f)?f:[f];for(let h=0;h<m.length;h++){const g=gf(e,m[h]);if(g){const{transitionEnd:x,transition:v,...w}=g;for(const I in w){let S=w[I];if(Array.isArray(S)){const P=d?S.length-1:0;S=S[P]}S!==null&&(r[I]=S)}for(const I in x)r[I]=x[I]}}}return r}const ql=e=>(t,n)=>{const s=p.useContext(ps),r=p.useContext(fs),i=()=>fb(e,t,s,r);return n?i():Ni(i)},mb=ql({scrapeMotionValuesFromProps:yf,createRenderState:ji}),gb=ql({scrapeMotionValuesFromProps:xf,createRenderState:Wl}),yb=Symbol.for("motionComponentSymbol");function xb(e,t,n){const s=p.useRef(n);p.useInsertionEffect(()=>{s.current=n});const r=p.useRef(null);return p.useCallback(i=>{i&&e.onMount?.(i),t&&(i?t.mount(i):t.unmount());const o=s.current;if(typeof o=="function")if(i){const a=o(i);typeof a=="function"&&(r.current=a)}else r.current?(r.current(),r.current=null):o(i);else o&&(o.current=i)},[t])}const Hl=p.createContext({});function Ut(e){return e&&typeof e=="object"&&Object.prototype.hasOwnProperty.call(e,"current")}function bb(e,t,n,s,r,i){const{visualElement:o}=p.useContext(ps),a=p.useContext(Bl),c=p.useContext(fs),u=p.useContext(Ii),d=u.reducedMotion,f=u.skipAnimations,m=p.useRef(null),h=p.useRef(!1);s=s||a.renderer,!m.current&&s&&(m.current=s(e,{visualState:t,parent:o,props:n,presenceContext:c,blockInitialAnimation:c?c.initial===!1:!1,reducedMotionConfig:d,skipAnimations:f,isSVG:i}),h.current&&m.current&&(m.current.manuallyAnimateOnMount=!0));const g=m.current,x=p.useContext(Hl);g&&!g.projection&&r&&(g.type==="html"||g.type==="svg")&&wb(m.current,n,r,x);const v=p.useRef(!1);p.useInsertionEffect(()=>{g&&v.current&&g.update(n,c)});const w=n[bf],I=p.useRef(!!w&&typeof window<"u"&&!window.MotionHandoffIsComplete?.(w)&&window.MotionHasOptimisedAnimation?.(w));return Dl(()=>{h.current=!0,g&&(v.current=!0,window.MotionIsMounted=!0,g.updateFeatures(),g.scheduleRenderMicrotask(),I.current&&g.animationState&&g.animationState.animateChanges())}),p.useEffect(()=>{g&&(!I.current&&g.animationState&&g.animationState.animateChanges(),I.current&&(queueMicrotask(()=>{window.MotionHandoffMarkAsComplete?.(w)}),I.current=!1),g.enteringChildren=void 0)}),g}function wb(e,t,n,s){const{layoutId:r,layout:i,drag:o,dragConstraints:a,layoutScroll:c,layoutRoot:u,layoutAnchor:d,layoutCrossfade:f}=t;e.projection=new n(e.latestValues,t["data-framer-portal-id"]?void 0:Gl(e.parent)),e.projection.setOptions({layoutId:r,layout:i,alwaysMeasureLayout:!!o||a&&Ut(a),visualElement:e,animationType:typeof i=="string"?i:"both",initialPromotionConfig:s,crossfade:f,layoutScroll:c,layoutRoot:u,layoutAnchor:d})}function Gl(e){if(e)return e.options.allowProjection!==!1?e.projection:Gl(e.parent)}function Ir(e,{forwardMotionProps:t=!1,type:n}={},s,r){s&&tb(s);const i=n?n==="svg":Ai(e),o=i?gb:mb;function a(u,d){let f;const m={...p.useContext(Ii),...u,layoutId:Sb(u)},{isStatic:h}=m,g=ob(u),x=o(u,h);if(!h&&typeof window<"u"){vb();const v=Cb(m);f=v.MeasureLayout,g.visualElement=bb(e,x,m,r,v.ProjectionNode,i)}return l.jsxs(ps.Provider,{value:g,children:[f&&g.visualElement?l.jsx(f,{visualElement:g.visualElement,...m}):null,hb(e,u,xb(x,g.visualElement,d),x,h,t,i)]})}a.displayName=`motion.${typeof e=="string"?e:`create(${e.displayName??e.name??""})`}`;const c=p.forwardRef(a);return c[yb]=e,c}function Sb({layoutId:e}){const t=p.useContext(Ti).id;return t&&e!==void 0?t+"-"+e:e}function vb(e,t){p.useContext(Bl).strict}function Cb(e){const t=$l(),{drag:n,layout:s}=t;if(!n&&!s)return{};const r={...n,...s};return{MeasureLayout:n?.isEnabled(e)||s?.isEnabled(e)?r.MeasureLayout:void 0,ProjectionNode:r.ProjectionNode}}function kb(e,t){if(typeof Proxy>"u")return Ir;const n=new Map,s=(i,o)=>Ir(i,o,e,t),r=(i,o)=>s(i,o);return new Proxy(r,{get:(i,o)=>o==="create"?s:(n.has(o)||n.set(o,Ir(o,void 0,e,t)),n.get(o))})}const Eb=(e,t)=>t.isSVG??Ai(e)?new wf(t):new Sf(t,{allowProjection:e!==p.Fragment});class Pb extends vt{constructor(t){super(t),t.animationState||(t.animationState=vf(t))}updateAnimationControlsSubscription(){const{animate:t}=this.node.getProps();Ja(t)&&(this.unmountControls=t.subscribe(this.node))}mount(){this.updateAnimationControlsSubscription()}update(){const{animate:t}=this.node.getProps(),{animate:n}=this.node.prevProps||{};t!==n&&this.updateAnimationControlsSubscription()}unmount(){this.node.animationState.reset(),this.unmountControls?.()}}let Tb=0;class Nb extends vt{constructor(){super(...arguments),this.id=Tb++,this.isExitComplete=!1}update(){if(!this.node.presenceContext)return;const{isPresent:t,onExitComplete:n}=this.node.presenceContext,{isPresent:s}=this.node.prevPresenceContext||{};if(!this.node.animationState||t===s)return;if(t&&s===!1){if(this.isExitComplete){const{initial:i,custom:o}=this.node.getProps();if(typeof i=="string"||typeof i=="object"&&i!==null&&!Array.isArray(i)){const a=Cf(this.node,i,o);if(a){const{transition:c,transitionEnd:u,...d}=a;for(const f in d)this.node.getValue(f)?.jump(d[f])}}this.node.animationState.reset(),this.node.animationState.animateChanges()}else this.node.animationState.setActive("exit",!1);this.isExitComplete=!1;return}const r=this.node.animationState.setActive("exit",!t);n&&!t&&r.then(()=>{this.isExitComplete=!0,n(this.id)})}mount(){const{register:t,onExitComplete:n}=this.node.presenceContext||{};n&&n(this.id),t&&(this.unmount=t(this.id))}unmount(){}}const Ib={animation:{Feature:Pb},exit:{Feature:Nb}};function wn(e){return{point:{x:e.pageX,y:e.pageY}}}const jb=e=>t=>Za(t)&&e(t,wn(t));function mn(e,t,n,s){return ns(e,t,jb(n),s)}const Ql=({current:e})=>e?e.ownerDocument.defaultView:null,ba=(e,t)=>Math.abs(e-t);function Ab(e,t){const n=ba(e.x,t.x),s=ba(e.y,t.y);return Math.sqrt(n**2+s**2)}const wa=new Set(["auto","scroll"]);class Jl{constructor(t,n,{transformPagePoint:s,contextWindow:r=window,dragSnapToOrigin:i=!1,distanceThreshold:o=3,element:a}={}){if(this.startEvent=null,this.lastMoveEvent=null,this.lastMoveEventInfo=null,this.lastRawMoveEventInfo=null,this.handlers={},this.contextWindow=window,this.scrollPositions=new Map,this.removeScrollListeners=null,this.onElementScroll=h=>{this.handleScroll(h.target)},this.onWindowScroll=()=>{this.handleScroll(window)},this.updatePoint=()=>{if(!(this.lastMoveEvent&&this.lastMoveEventInfo))return;this.lastRawMoveEventInfo&&(this.lastMoveEventInfo=Fn(this.lastRawMoveEventInfo,this.transformPagePoint));const h=jr(this.lastMoveEventInfo,this.history),g=this.startEvent!==null,x=Ab(h.offset,{x:0,y:0})>=this.distanceThreshold;if(!g&&!x)return;const{point:v}=h,{timestamp:w}=go;this.history.push({...v,timestamp:w});const{onStart:I,onMove:S}=this.handlers;g||(I&&I(this.lastMoveEvent,h),this.startEvent=this.lastMoveEvent),S&&S(this.lastMoveEvent,h)},this.handlePointerMove=(h,g)=>{this.lastMoveEvent=h,this.lastRawMoveEventInfo=g,this.lastMoveEventInfo=Fn(g,this.transformPagePoint),Xe.update(this.updatePoint,!0)},this.handlePointerUp=(h,g)=>{this.end();const{onEnd:x,onSessionEnd:v,resumeAnimation:w}=this.handlers;if((this.dragSnapToOrigin||!this.startEvent)&&w&&w(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const I=jr(h.type==="pointercancel"?this.lastMoveEventInfo:Fn(g,this.transformPagePoint),this.history);this.startEvent&&x&&x(h,I),v&&v(h,I)},!Za(t))return;this.dragSnapToOrigin=i,this.handlers=n,this.transformPagePoint=s,this.distanceThreshold=o,this.contextWindow=r||window;const c=wn(t),u=Fn(c,this.transformPagePoint),{point:d}=u,{timestamp:f}=go;this.history=[{...d,timestamp:f}];const{onSessionStart:m}=n;m&&m(t,jr(u,this.history)),this.removeListeners=Ya(mn(this.contextWindow,"pointermove",this.handlePointerMove),mn(this.contextWindow,"pointerup",this.handlePointerUp),mn(this.contextWindow,"pointercancel",this.handlePointerUp)),a&&this.startScrollTracking(a)}startScrollTracking(t){let n=t.parentElement;for(;n;){const s=getComputedStyle(n);(wa.has(s.overflowX)||wa.has(s.overflowY))&&this.scrollPositions.set(n,{x:n.scrollLeft,y:n.scrollTop}),n=n.parentElement}this.scrollPositions.set(window,{x:window.scrollX,y:window.scrollY}),window.addEventListener("scroll",this.onElementScroll,{capture:!0}),window.addEventListener("scroll",this.onWindowScroll),this.removeScrollListeners=()=>{window.removeEventListener("scroll",this.onElementScroll,{capture:!0}),window.removeEventListener("scroll",this.onWindowScroll)}}handleScroll(t){const n=this.scrollPositions.get(t);if(!n)return;const s=t===window,r=s?{x:window.scrollX,y:window.scrollY}:{x:t.scrollLeft,y:t.scrollTop},i={x:r.x-n.x,y:r.y-n.y};i.x===0&&i.y===0||(s?this.lastMoveEventInfo&&(this.lastMoveEventInfo.point.x+=i.x,this.lastMoveEventInfo.point.y+=i.y):this.history.length>0&&(this.history[0].x-=i.x,this.history[0].y-=i.y),this.scrollPositions.set(t,r),Xe.update(this.updatePoint,!0))}updateHandlers(t){this.handlers=t}end(){this.removeListeners&&this.removeListeners(),this.removeScrollListeners&&this.removeScrollListeners(),this.scrollPositions.clear(),kf(this.updatePoint)}}function Fn(e,t){return t?{point:t(e.point)}:e}function Sa(e,t){return{x:e.x-t.x,y:e.y-t.y}}function jr({point:e},t){return{point:e,delta:Sa(e,Zl(t)),offset:Sa(e,zb(t)),velocity:Lb(t,.1)}}function zb(e){return e[0]}function Zl(e){return e[e.length-1]}function Lb(e,t){if(e.length<2)return{x:0,y:0};let n=e.length-1,s=null;const r=Zl(e);for(;n>=0&&(s=e[n],!(r.timestamp-s.timestamp>yo(t)));)n--;if(!s)return{x:0,y:0};s===e[0]&&e.length>2&&r.timestamp-s.timestamp>yo(t)*2&&(s=e[1]);const i=Ef(r.timestamp-s.timestamp);if(i===0)return{x:0,y:0};const o={x:(r.x-s.x)/i,y:(r.y-s.y)/i};return o.x===1/0&&(o.x=0),o.y===1/0&&(o.y=0),o}function _b(e,{min:t,max:n},s){return t!==void 0&&e<t?e=s?ss(t,e,s.min):Math.max(e,t):n!==void 0&&e>n&&(e=s?ss(n,e,s.max):Math.min(e,n)),e}function va(e,t,n){return{min:t!==void 0?e.min+t:void 0,max:n!==void 0?e.max+n-(e.max-e.min):void 0}}function Rb(e,{top:t,left:n,bottom:s,right:r}){return{x:va(e.x,n,r),y:va(e.y,t,s)}}function Ca(e,t){let n=t.min-e.min,s=t.max-e.max;return t.max-t.min<e.max-e.min&&([n,s]=[s,n]),{min:n,max:s}}function Ob(e,t){return{x:Ca(e.x,t.x),y:Ca(e.y,t.y)}}function Mb(e,t){let n=.5;const s=$r(e),r=$r(t);return r>s?n=xo(t.min,t.max-s,e.min):s>r&&(n=xo(e.min,e.max-r,t.min)),Pf(0,1,n)}function Db(e,t){const n={};return t.min!==void 0&&(n.min=t.min-e.min),t.max!==void 0&&(n.max=t.max-e.min),n}const Kr=.35;function Fb(e=Kr){return e===!1?e=0:e===!0&&(e=Kr),{x:ka(e,"left","right"),y:ka(e,"top","bottom")}}function ka(e,t,n){return{min:Ea(e,t),max:Ea(e,n)}}function Ea(e,t){return typeof e=="number"?e:e[t]||0}const Bb=new WeakMap;class $b{constructor(t){this.openDragLock=null,this.isDragging=!1,this.currentDirection=null,this.originPoint={x:0,y:0},this.constraints=!1,this.hasMutatedConstraints=!1,this.elastic=Tf(),this.latestPointerEvent=null,this.latestPanInfo=null,this.visualElement=t}start(t,{snapToCursor:n=!1,distanceThreshold:s}={}){const{presenceContext:r}=this.visualElement;if(r&&r.isPresent===!1)return;const i=f=>{n&&this.snapToCursor(wn(f).point),this.stopAnimation()},o=(f,m)=>{const{drag:h,dragPropagation:g,onDragStart:x}=this.getProps();if(h&&!g&&(this.openDragLock&&this.openDragLock(),this.openDragLock=zf(h),!this.openDragLock))return;this.latestPointerEvent=f,this.latestPanInfo=m,this.isDragging=!0,this.currentDirection=null,this.resolveConstraints(),this.visualElement.projection&&(this.visualElement.projection.isAnimationBlocked=!0,this.visualElement.projection.target=void 0),bt(w=>{let I=this.getAxisMotionValue(w).get()||0;if(Lf.test(I)){const{projection:S}=this.visualElement;if(S&&S.layout){const P=S.layout.layoutBox[w];P&&(I=$r(P)*(parseFloat(I)/100))}}this.originPoint[w]=I}),x&&Xe.update(()=>x(f,m),!1,!0),bo(this.visualElement,"transform");const{animationState:v}=this.visualElement;v&&v.setActive("whileDrag",!0)},a=(f,m)=>{this.latestPointerEvent=f,this.latestPanInfo=m;const{dragPropagation:h,dragDirectionLock:g,onDirectionLock:x,onDrag:v}=this.getProps();if(!h&&!this.openDragLock)return;const{offset:w}=m;if(g&&this.currentDirection===null){this.currentDirection=Ub(w),this.currentDirection!==null&&x&&x(this.currentDirection);return}this.updateAxis("x",m.point,w),this.updateAxis("y",m.point,w),this.visualElement.render(),v&&Xe.update(()=>v(f,m),!1,!0)},c=(f,m)=>{this.latestPointerEvent=f,this.latestPanInfo=m,this.stop(f,m),this.latestPointerEvent=null,this.latestPanInfo=null},u=()=>{const{dragSnapToOrigin:f}=this.getProps();(f||this.constraints)&&this.startAnimation({x:0,y:0})},{dragSnapToOrigin:d}=this.getProps();this.panSession=new Jl(t,{onSessionStart:i,onStart:o,onMove:a,onSessionEnd:c,resumeAnimation:u},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:d,distanceThreshold:s,contextWindow:Ql(this.visualElement),element:this.visualElement.current})}stop(t,n){const s=t||this.latestPointerEvent,r=n||this.latestPanInfo,i=this.isDragging;if(this.cancel(),!i||!r||!s)return;const{velocity:o}=r;this.startAnimation(o);const{onDragEnd:a}=this.getProps();a&&Xe.postRender(()=>a(s,r))}cancel(){this.isDragging=!1;const{projection:t,animationState:n}=this.visualElement;t&&(t.isAnimationBlocked=!1),this.endPanSession();const{dragPropagation:s}=this.getProps();!s&&this.openDragLock&&(this.openDragLock(),this.openDragLock=null),n&&n.setActive("whileDrag",!1)}endPanSession(){this.panSession&&this.panSession.end(),this.panSession=void 0}updateAxis(t,n,s){const{drag:r}=this.getProps();if(!s||!Bn(t,r,this.currentDirection))return;const i=this.getAxisMotionValue(t);let o=this.originPoint[t]+s[t];this.constraints&&this.constraints[t]&&(o=_b(o,this.constraints[t],this.elastic[t])),i.set(o)}resolveConstraints(){const{dragConstraints:t,dragElastic:n}=this.getProps(),s=this.visualElement.projection&&!this.visualElement.projection.layout?this.visualElement.projection.measure(!1):this.visualElement.projection?.layout,r=this.constraints;t&&Ut(t)?this.constraints||(this.constraints=this.resolveRefConstraints()):t&&s?this.constraints=Rb(s.layoutBox,t):this.constraints=!1,this.elastic=Fb(n),r!==this.constraints&&!Ut(t)&&s&&this.constraints&&!this.hasMutatedConstraints&&bt(i=>{this.constraints!==!1&&this.getAxisMotionValue(i)&&(this.constraints[i]=Db(s.layoutBox[i],this.constraints[i]))})}resolveRefConstraints(){const{dragConstraints:t,onMeasureDragConstraints:n}=this.getProps();if(!t||!Ut(t))return!1;const s=t.current,{projection:r}=this.visualElement;if(!r||!r.layout)return!1;r.root&&(r.root.scroll=void 0,r.root.updateScroll());const i=Nf(s,r.root,this.visualElement.getTransformPagePoint());let o=Ob(r.layout.layoutBox,i);if(n){const a=n(If(o));this.hasMutatedConstraints=!!a,a&&(o=jf(a))}return o}startAnimation(t){const{drag:n,dragMomentum:s,dragElastic:r,dragTransition:i,dragSnapToOrigin:o,onDragTransitionEnd:a}=this.getProps(),c=this.constraints||{},u=bt(d=>{if(!Bn(d,n,this.currentDirection))return;let f=c&&c[d]||{};(o===!0||o===d)&&(f={min:0,max:0});const m=r?200:1e6,h=r?40:1e7,g={type:"inertia",velocity:s?t[d]:0,bounceStiffness:m,bounceDamping:h,timeConstant:750,restDelta:1,restSpeed:10,...i,...f};return this.startAxisValueAnimation(d,g)});return Promise.all(u).then(a)}startAxisValueAnimation(t,n){const s=this.getAxisMotionValue(t);return bo(this.visualElement,t),s.start(Af(t,s,0,n,this.visualElement,!1))}stopAnimation(){bt(t=>this.getAxisMotionValue(t).stop())}getAxisMotionValue(t){const n=`_drag${t.toUpperCase()}`,r=this.visualElement.getProps()[n];return r||this.visualElement.getValue(t,this.visualElement.latestValues[t]??0)}snapToCursor(t){bt(n=>{const{drag:s}=this.getProps();if(!Bn(n,s,this.currentDirection))return;const{projection:r}=this.visualElement,i=this.getAxisMotionValue(n);if(r&&r.layout){const{min:o,max:a}=r.layout.layoutBox[n],c=i.get()||0;i.set(t[n]-ss(o,a,.5)+c)}})}scalePositionWithinConstraints(){if(!this.visualElement.current)return;const{drag:t,dragConstraints:n}=this.getProps(),{projection:s}=this.visualElement;if(!Ut(n)||!s||!this.constraints)return;this.stopAnimation();const r={x:0,y:0};bt(o=>{const a=this.getAxisMotionValue(o);if(a&&this.constraints!==!1){const c=a.get();r[o]=Mb({min:c,max:c},this.constraints[o])}});const{transformTemplate:i}=this.visualElement.getProps();this.visualElement.current.style.transform=i?i({},""):"none",s.root&&s.root.updateScroll(),s.updateLayout(),this.constraints=!1,this.resolveConstraints(),bt(o=>{if(!Bn(o,t,null))return;const a=this.getAxisMotionValue(o),{min:c,max:u}=this.constraints[o];a.set(ss(c,u,r[o]))}),this.visualElement.render()}addListeners(){if(!this.visualElement.current)return;Bb.set(this.visualElement,this);const t=this.visualElement.current,n=mn(t,"pointerdown",u=>{const{drag:d,dragListener:f=!0}=this.getProps(),m=u.target,h=m!==t&&_f(m);d&&f&&!h&&this.start(u)});let s;const r=()=>{const{dragConstraints:u}=this.getProps();Ut(u)&&u.current&&(this.constraints=this.resolveRefConstraints(),s||(s=Vb(t,u.current,()=>this.scalePositionWithinConstraints())))},{projection:i}=this.visualElement,o=i.addEventListener("measure",r);i&&!i.layout&&(i.root&&i.root.updateScroll(),i.updateLayout()),Xe.read(r);const a=ns(window,"resize",()=>this.scalePositionWithinConstraints()),c=i.addEventListener("didUpdate",(({delta:u,hasLayoutChanged:d})=>{this.isDragging&&d&&(bt(f=>{const m=this.getAxisMotionValue(f);m&&(this.originPoint[f]+=u[f].translate,m.set(m.get()+u[f].translate))}),this.visualElement.render())}));return()=>{a(),n(),o(),c&&c(),s&&s()}}getProps(){const t=this.visualElement.getProps(),{drag:n=!1,dragDirectionLock:s=!1,dragPropagation:r=!1,dragConstraints:i=!1,dragElastic:o=Kr,dragMomentum:a=!0}=t;return{...t,drag:n,dragDirectionLock:s,dragPropagation:r,dragConstraints:i,dragElastic:o,dragMomentum:a}}}function Pa(e){let t=!0;return()=>{if(t){t=!1;return}e()}}function Vb(e,t,n){const s=wo(e,Pa(n)),r=wo(t,Pa(n));return()=>{s(),r()}}function Bn(e,t,n){return(t===!0||t===e)&&(n===null||n===e)}function Ub(e,t=10){let n=null;return Math.abs(e.y)>t?n="y":Math.abs(e.x)>t&&(n="x"),n}class Wb extends vt{constructor(t){super(t),this.removeGroupControls=Hn,this.removeListeners=Hn,this.controls=new $b(t)}mount(){const{dragControls:t}=this.node.getProps();t&&(this.removeGroupControls=t.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||Hn}update(){const{dragControls:t}=this.node.getProps(),{dragControls:n}=this.node.prevProps||{};t!==n&&(this.removeGroupControls(),t&&(this.removeGroupControls=t.subscribe(this.controls)))}unmount(){this.removeGroupControls(),this.removeListeners(),this.controls.isDragging||this.controls.endPanSession()}}const Ar=e=>(t,n)=>{e&&Xe.update(()=>e(t,n),!1,!0)};class qb extends vt{constructor(){super(...arguments),this.removePointerDownListener=Hn}onPointerDown(t){this.session=new Jl(t,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:Ql(this.node)})}createPanHandlers(){const{onPanSessionStart:t,onPanStart:n,onPan:s,onPanEnd:r}=this.node.getProps();return{onSessionStart:Ar(t),onStart:Ar(n),onMove:Ar(s),onEnd:(i,o)=>{delete this.session,r&&Xe.postRender(()=>r(i,o))}}}mount(){this.removePointerDownListener=mn(this.node.current,"pointerdown",t=>this.onPointerDown(t))}update(){this.session&&this.session.updateHandlers(this.createPanHandlers())}unmount(){this.removePointerDownListener(),this.session&&this.session.end()}}let zr=!1;class Hb extends p.Component{componentDidMount(){const{visualElement:t,layoutGroup:n,switchLayoutGroup:s,layoutId:r}=this.props,{projection:i}=t;i&&(n.group&&n.group.add(i),s&&s.register&&r&&s.register(i),zr&&i.root.didUpdate(),i.addEventListener("animationComplete",()=>{this.safeToRemove()}),i.setOptions({...i.options,layoutDependency:this.props.layoutDependency,onExitComplete:()=>this.safeToRemove()})),Of.hasEverUpdated=!0}getSnapshotBeforeUpdate(t){const{layoutDependency:n,visualElement:s,drag:r,isPresent:i}=this.props,{projection:o}=s;return o&&(o.isPresent=i,t.layoutDependency!==n&&o.setOptions({...o.options,layoutDependency:n}),zr=!0,r||t.layoutDependency!==n||n===void 0||t.isPresent!==i?o.willUpdate():this.safeToRemove(),t.isPresent!==i&&(i?o.promote():o.relegate()||Xe.postRender(()=>{const a=o.getStack();(!a||!a.members.length)&&this.safeToRemove()}))),null}componentDidUpdate(){const{visualElement:t,layoutAnchor:n}=this.props,{projection:s}=t;s&&(s.options.layoutAnchor=n,s.root.didUpdate(),Rf.postRender(()=>{!s.currentAnimation&&s.isLead()&&this.safeToRemove()}))}componentWillUnmount(){const{visualElement:t,layoutGroup:n,switchLayoutGroup:s}=this.props,{projection:r}=t;zr=!0,r&&(r.scheduleCheckAfterUnmount(),n&&n.group&&n.group.remove(r),s&&s.deregister&&s.deregister(r))}safeToRemove(){const{safeToRemove:t}=this.props;t&&t()}render(){return null}}function Yl(e){const[t,n]=Fl(),s=p.useContext(Ti);return l.jsx(Hb,{...e,layoutGroup:s,switchLayoutGroup:p.useContext(Hl),isPresent:t,safeToRemove:n})}const Gb={pan:{Feature:qb},drag:{Feature:Wb,ProjectionNode:Ka,MeasureLayout:Yl}};function Ta(e,t,n){const{props:s}=e;e.animationState&&s.whileHover&&e.animationState.setActive("whileHover",n==="Start");const r="onHover"+n,i=s[r];i&&Xe.postRender(()=>i(t,wn(t)))}class Qb extends vt{mount(){const{current:t}=this.node;t&&(this.unmount=Mf(t,(n,s)=>(Ta(this.node,s,"Start"),r=>Ta(this.node,r,"End"))))}unmount(){}}class Jb extends vt{constructor(){super(...arguments),this.isActive=!1}onFocus(){let t=!1;try{t=this.node.current.matches(":focus-visible")}catch{t=!0}!t||!this.node.animationState||(this.node.animationState.setActive("whileFocus",!0),this.isActive=!0)}onBlur(){!this.isActive||!this.node.animationState||(this.node.animationState.setActive("whileFocus",!1),this.isActive=!1)}mount(){this.unmount=Ya(ns(this.node.current,"focus",()=>this.onFocus()),ns(this.node.current,"blur",()=>this.onBlur()))}unmount(){}}function Na(e,t,n){const{props:s}=e;if(e.current instanceof HTMLButtonElement&&e.current.disabled)return;e.animationState&&s.whileTap&&e.animationState.setActive("whileTap",n==="Start");const r="onTap"+(n==="End"?"":n),i=s[r];i&&Xe.postRender(()=>i(t,wn(t)))}class Zb extends vt{mount(){const{current:t}=this.node;if(!t)return;const{globalTapTarget:n,propagate:s}=this.node.props;this.unmount=Df(t,(r,i)=>(Na(this.node,i,"Start"),(o,{success:a})=>Na(this.node,o,a?"End":"Cancel")),{useGlobalTarget:n,stopPropagation:s?.tap===!1})}unmount(){}}const Xr=new WeakMap,Lr=new WeakMap,Yb=e=>{const t=Xr.get(e.target);t&&t(e)},Kb=e=>{e.forEach(Yb)};function Xb({root:e,...t}){const n=e||document;Lr.has(n)||Lr.set(n,{});const s=Lr.get(n),r=JSON.stringify(t);return s[r]||(s[r]=new IntersectionObserver(Kb,{root:e,...t})),s[r]}function ew(e,t,n){const s=Xb(t);return Xr.set(e,n),s.observe(e),()=>{Xr.delete(e),s.unobserve(e)}}const tw={some:0,all:1};class nw extends vt{constructor(){super(...arguments),this.hasEnteredView=!1,this.isInView=!1}startObserver(){this.stopObserver?.();const{viewport:t={}}=this.node.getProps(),{root:n,margin:s,amount:r="some",once:i}=t,o={root:n?n.current:void 0,rootMargin:s,threshold:typeof r=="number"?r:tw[r]},a=c=>{const{isIntersecting:u}=c;if(this.isInView===u||(this.isInView=u,i&&!u&&this.hasEnteredView))return;u&&(this.hasEnteredView=!0),this.node.animationState&&this.node.animationState.setActive("whileInView",u);const{onViewportEnter:d,onViewportLeave:f}=this.node.getProps(),m=u?d:f;m&&m(c)};this.stopObserver=ew(this.node.current,o,a)}mount(){this.startObserver()}update(){if(typeof IntersectionObserver>"u")return;const{props:t,prevProps:n}=this.node;["amount","margin","root"].some(sw(t,n))&&this.startObserver()}unmount(){this.stopObserver?.(),this.hasEnteredView=!1,this.isInView=!1}}function sw({viewport:e={}},{viewport:t={}}={}){return n=>e[n]!==t[n]}const rw={inView:{Feature:nw},tap:{Feature:Zb},focus:{Feature:Jb},hover:{Feature:Qb}},iw={layout:{ProjectionNode:Ka,MeasureLayout:Yl}},ow={...Ib,...rw,...Gb,...iw},aw=kb(ow,Eb);function lw(){const e=ce(t=>t.toasts);return l.jsx("div",{className:"fixed bottom-6 right-6 z-50 flex flex-col gap-3 min-w-[320px] max-w-sm pointer-events-none",children:l.jsx(Xx,{children:e.map(t=>l.jsxs(aw.div,{initial:{opacity:0,y:50,x:50,scale:.9},animate:{opacity:1,y:0,x:0,scale:1},exit:{opacity:0,scale:.85,transition:{duration:.2}},transition:{type:"spring",stiffness:300,damping:24},className:"pointer-events-auto w-full bg-white ring-1 ring-black/5 shadow-2xl rounded-xl p-4 flex gap-3 border-l-4 border-emerald-500 overflow-hidden",id:`toast-${t.id}`,children:[l.jsxs("div",{className:"flex-1",children:[l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("span",{className:"p-1 rounded-full bg-emerald-50 text-emerald-600",children:l.jsx(ef,{size:16})}),l.jsx("p",{className:"font-semibold text-gray-900 text-sm font-sans",children:t.title})]}),l.jsx("p",{className:"text-xs text-gray-500 mt-2 leading-relaxed font-sans",children:t.message})]}),l.jsx("button",{type:"button",onClick:()=>Ce.getState().removeToast(t.id),className:"text-gray-400 hover:text-gray-600 hover:bg-gray-50 rounded p-1 h-fit transition-colors shrink-0 cursor-pointer",children:l.jsx(At,{size:14})})]},t.id))})})}function cw({showRightSidebar:e,setShowRightSidebar:t,rightSidebarTab:n,setRightSidebarTab:s,effectiveAgentProviderId:r,agentProviderId:i,setAgentProviderId:o,aiProviders:a,selectedAgentProvider:c,chatLog:u,loading:d,input:f,setInput:m,handleSend:h,chatAttachments:g,setChatAttachments:x,handleChatFileChange:v,handleChatDrop:w,onClearAgentMemory:I,events:S,lang:P,t:z}){const E=p.useRef(null);return p.useEffect(()=>{E.current?.scrollIntoView({behavior:"smooth"})},[u]),l.jsx("div",{className:`transition-all duration-300 bg-white border-l border-gray-200 flex flex-col shadow-xl relative z-30 shrink-0 ${e?"w-96":"w-12 items-center cursor-pointer hover:bg-gray-50"}`,children:e?l.jsxs(l.Fragment,{children:[l.jsxs("div",{className:"flex bg-gray-100 p-1 m-4 rounded-lg shrink-0",children:[l.jsxs("button",{onClick:()=>s("agent"),className:`flex-1 py-1.5 text-xs font-medium rounded-md transition-colors flex items-center justify-center gap-1 ${n==="agent"?"bg-white shadow text-indigo-600":"text-gray-500 hover:text-gray-700"}`,children:[l.jsx(ur,{size:14})," Agent"]}),l.jsxs("button",{onClick:()=>s("shell"),className:`flex-1 py-1.5 text-xs font-medium rounded-md transition-colors flex items-center justify-center gap-1 ${n==="shell"?"bg-white shadow text-indigo-600":"text-gray-500 hover:text-gray-700"}`,children:[l.jsx(qn,{size:14})," Shell"]}),l.jsx("button",{onClick:()=>t(!1),className:"ml-1 p-1.5 text-gray-400 hover:text-gray-600 rounded-md",children:l.jsx(tf,{size:14})})]}),n==="agent"?l.jsxs("div",{className:"flex-1 flex flex-col min-h-0",children:[l.jsx("div",{className:"p-4 border-b border-gray-100 shrink-0",children:l.jsxs("div",{className:"flex items-start justify-between gap-3",children:[l.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[l.jsx("div",{className:"p-1.5 bg-indigo-50 text-indigo-600 rounded-lg",children:l.jsx(ur,{size:16})}),l.jsxs("div",{className:"min-w-0",children:[l.jsx("h2",{className:"font-semibold text-gray-900 text-sm",children:z.agentTitle}),l.jsx("p",{className:"text-[10px] text-gray-500",children:z.agentSubtitle}),l.jsxs("button",{onClick:I,title:P==="zh"?"清除内核助手的对话记忆":"Clear the kernel assistant's conversation memory",className:"mt-1 inline-flex items-center gap-1 text-[10px] text-gray-400 hover:text-red-500 transition-colors",children:["🧹 ",P==="zh"?"清除记忆":"Clear memory"]})]})]}),l.jsxs("div",{className:"flex flex-col items-end gap-1.5 min-w-[150px] max-w-[50%]",children:[l.jsx("span",{className:"text-[10px] font-semibold uppercase tracking-[0.18em] text-gray-400",children:P==="zh"?"AI 提供商":"AI Provider"}),l.jsxs("div",{className:"relative w-full",children:[l.jsxs("select",{value:r,onChange:L=>o(L.target.value),className:"w-full appearance-none rounded-xl border border-gray-200 bg-gradient-to-b from-white to-gray-50 px-3 py-2 pr-9 text-[11px] font-medium text-gray-700 shadow-sm outline-none transition-colors focus:border-indigo-400 focus:ring-2 focus:ring-indigo-100",children:[l.jsx("option",{value:"system",children:P==="zh"?"系统默认(Gemini)":"System Default (Gemini)"}),a.map(L=>l.jsx("option",{value:L.id,children:L.name},L.id))]}),l.jsx(Va,{size:12,className:"pointer-events-none absolute right-3 top-1/2 -translate-y-1/2 text-gray-400"})]}),l.jsx("div",{className:"text-[10px] text-gray-400 truncate w-full text-right",title:r==="system"?P==="zh"?"使用内置 Gemini 系统模型":"Using the built-in Gemini system model":c?.model_name||"",children:r==="system"?P==="zh"?"内置系统模型":"Built-in system model":`${c?.name||(P==="zh"?"已选提供商":"Selected provider")}`})]})]})}),l.jsxs("div",{className:"flex-1 overflow-y-auto p-4 space-y-4",children:[u.map((L,_)=>l.jsx("div",{className:`flex flex-col ${L.role==="user"?"items-end":"items-start"}`,children:l.jsx("div",{className:`px-4 py-2.5 rounded-2xl max-w-[85%] text-xs whitespace-pre-wrap ${L.role==="user"?"bg-indigo-600 text-white rounded-br-none":"bg-gray-100 text-gray-800 rounded-bl-none"}`,children:L.content})},_)),d&&l.jsx("div",{className:"flex items-start",children:l.jsxs("div",{className:"px-4 py-2.5 rounded-2xl max-w-[85%] text-xs bg-gray-100 text-gray-500 rounded-bl-none flex items-center gap-1",children:[l.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-gray-400 animate-bounce"}),l.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-gray-400 animate-bounce",style:{animationDelay:"0.1s"}}),l.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-gray-400 animate-bounce",style:{animationDelay:"0.2s"}})]})}),l.jsx("div",{ref:E})]}),l.jsxs("form",{onSubmit:h,className:"p-3 border-t border-gray-100 bg-white shrink-0 font-sans",onDragOver:L=>L.preventDefault(),onDrop:w,children:[g.length>0&&l.jsx("div",{className:"flex flex-wrap gap-1 mb-2 px-1",children:g.map((L,_)=>l.jsxs("div",{className:"flex items-center gap-1 bg-indigo-50 border border-indigo-100 text-indigo-700 px-2 py-0.5 rounded-full text-[10px]",children:[l.jsx(qa,{size:10,className:"shrink-0"}),l.jsx("span",{className:"truncate max-w-[100px]",title:L.name,children:L.name}),l.jsx("button",{type:"button",onClick:()=>x(M=>M.filter((N,A)=>A!==_)),className:"hover:bg-indigo-200 rounded-full p-0.5 cursor-pointer ml-0.5 transition-colors text-indigo-400 hover:text-indigo-600",children:l.jsx(At,{size:10})})]},_))}),l.jsxs("div",{className:"flex items-center gap-1.5",children:[l.jsxs("label",{className:"p-1 px-1.5 text-gray-500 hover:text-indigo-600 rounded-full hover:bg-gray-100 cursor-pointer transition-colors shrink-0",children:[l.jsx(nf,{size:14}),l.jsx("input",{type:"file",multiple:!0,className:"hidden",onChange:v,accept:".csv,.txt,.json,.md"})]}),l.jsxs("div",{className:"relative flex-1",children:[l.jsx("input",{type:"text",value:f,onChange:L=>m(L.target.value),placeholder:z.placeholder,className:"w-full bg-gray-50 border border-gray-200 rounded-full pl-4 pr-10 py-1.5 text-xs focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:border-transparent transition-all"}),l.jsx("button",{type:"submit",disabled:d||!f.trim(),className:"absolute right-1 top-1/2 -translate-y-1/2 p-1 bg-indigo-600 text-white rounded-full hover:bg-indigo-700 disabled:opacity-50 transition-colors",children:l.jsx(sf,{size:10})})]})]})]})]}):l.jsxs("div",{className:"flex-1 flex flex-col bg-black text-green-400 font-mono text-[10px] min-h-0 mx-4 mb-4 rounded-xl shadow-inner border border-gray-800 overflow-hidden",children:[l.jsx("div",{className:"p-3 border-b border-gray-800 flex items-center justify-between shrink-0 bg-gray-900",children:l.jsxs("div",{className:"flex items-center gap-2 text-gray-300 font-sans tracking-wide",children:[l.jsx(qn,{size:14}),l.jsx("span",{className:"text-xs",children:z.eventStream})]})}),l.jsx("div",{className:"p-3 overflow-y-auto flex-1 flex flex-col gap-1 select-text",children:S.length===0?l.jsx("div",{className:"text-gray-600 italic",children:"Waiting for events..."}):S.map((L,_)=>l.jsxs("div",{className:"flex flex-col gap-1 hover:bg-gray-800/50 p-2 rounded mb-1",children:[l.jsxs("div",{className:"flex items-center gap-2 justify-between",children:[l.jsxs("span",{className:"text-gray-500 shrink-0 text-[9px]",children:["[",new Date(L.timestamp).toLocaleTimeString(),"]"]}),l.jsx("span",{className:"text-blue-400 shrink-0 truncate text-[9px]",title:L.source,children:L.source})]}),l.jsx("div",{className:"text-green-300 font-bold",children:L.type}),l.jsx("div",{className:"text-gray-400 break-words mt-1 leading-tight",children:L.payload})]},_))})]})]}):l.jsxs("div",{className:"flex flex-col items-center py-6 h-full text-gray-400 w-full",onClick:()=>t(!0),children:[l.jsx(ur,{size:18,className:"mb-6 hover:text-indigo-500"}),l.jsx(qn,{size:18,className:"hover:text-indigo-500"}),l.jsx("div",{className:"mt-8 flex-1 flex flex-col justify-end pb-8",children:l.jsx("div",{className:"uppercase tracking-widest text-[9px] rotate-180",style:{writingMode:"vertical-rl"},children:"OS Core Options"})})]})})}const uw=p.lazy(()=>Ie(()=>import("./ImportModal-BTfia0Ah.js"),[]).then(e=>({default:e.ImportModal}))),dw=p.lazy(()=>Ie(()=>import("./CourseWizardModal-DFZzYcbL.js"),[]).then(e=>({default:e.CourseWizardModal}))),hw=p.lazy(()=>Ie(()=>import("./ImportLessonsModal-BleM5Z-r.js"),[]).then(e=>({default:e.ImportLessonsModal}))),fw=p.lazy(()=>Ie(()=>import("./QuizGeneratorModal-UEVoYkB6.js"),[]).then(e=>({default:e.QuizGeneratorModal}))),pw=p.lazy(()=>Ie(()=>import("./StudentPreviewModal-Bx86ogm7.js"),[]).then(e=>({default:e.StudentPreviewModal}))),mw=p.lazy(()=>Ie(()=>import("./ProcessLogsModal-01S7zsw0.js"),[]).then(e=>({default:e.ProcessLogsModal}))),gw=p.lazy(()=>Ie(()=>import("./CloudDriveModal-DiEEoAK5.js"),[]).then(e=>({default:e.CloudDriveModal}))),yw=p.lazy(()=>Ie(()=>import("./SystemResourceLibraryModal-CRsieL1o.js"),[]).then(e=>({default:e.SystemResourceLibraryModal}))),xw=p.lazy(()=>Ie(()=>import("./BatchPickerModal-VYKUF5TC.js"),[]).then(e=>({default:e.BatchPickerModal}))),bw=p.lazy(()=>Ie(()=>import("./ExportWeightModal-DPriCEO9.js"),[]).then(e=>({default:e.ExportWeightModal}))),ww=p.lazy(()=>Ie(()=>import("./NotificationDetailModal-me41YjnW.js"),[]).then(e=>({default:e.NotificationDetailModal}))),Sw=p.lazy(()=>Ie(()=>import("./HelpTour-CHPIK2ae.js"),[]).then(e=>({default:e.HelpTour}))),vw=p.lazy(()=>Ie(()=>import("./CoursewareHubPanel-LpUgjqbH.js"),[]).then(e=>({default:e.CoursewareHubPanel})));function Cw(e){const{lang:t,t:n,showImportModal:s=!1,setShowImportModal:r=()=>{},handleImportFile:i=()=>{},importError:o=null,importSuccess:a=null,isImporting:c=!1,downloadCSVTemplate:u=()=>{},addToast:d=()=>{},generateTemplateContent:f=()=>"",isImportLessonsOpen:m=!1,setIsImportLessonsOpen:h=()=>{},importStatus:g="idle",setIsDraggingImport:x=()=>{},handleCSVFileChange:v=()=>{},downloadCsvTemplate:w=()=>{},isDraggingImport:I=!1,previewImportData:S=[],setPreviewImportData:P=()=>{},setImportStatus:z=()=>{},importProgress:E=0,importProgressTotal:L=0,importErrorMsg:_="",setImportErrorMsg:M=()=>{},handleCSVImportSubmit:N=()=>{},lessons:A=[],fetchClassDashboard:R=()=>{},isLessonPreviewVisible:D=!1,setIsLessonPreviewVisible:F=()=>{},selectedLesson:j=null,previewFullscreenPanel:T="none",setPreviewFullscreenPanel:$=()=>{},previewLessonTab:k="whiteboard",setPreviewLessonTab:B=()=>{},activeRole:y="teacher",elements:te=[],activeSegmentId:ae=null,setActiveSegmentId:b=()=>{},fetchElements:q=()=>{},currentVfsParent:ee=null,setCurrentVfsParent:se=()=>{},vfsNodes:fe=[],previewSelectedCourseware:ge=null,setPreviewSelectedCourseware:ze=()=>{},showProcessLogs:je=null,setShowProcessLogs:he=()=>{},processLogsContent:ft="",isCloudDriveOpen:Lt=!1,setIsCloudDriveOpen:_t=()=>{},cloudDrivePreviewNode:pt=null,setCloudDrivePreviewNode:mt=()=>{},isSystemResourceLibraryOpen:G=!1,setIsSystemResourceLibraryOpen:K=()=>{},systemResourceTab:re="system",setSystemResourceTab:we=()=>{},selectedLibraryResourceId:qe=null,setSelectedLibraryResourceId:de=()=>{},loadingLibraryResources:Te=!1,libraryResources:ke=[],fetchLibraryResources:Ze=()=>{},classes:O=[],expandedClassId:W=null,isExportWeightModalOpen:Q=!1,setIsExportWeightModalOpen:Z=()=>{},quizzesWeight:ie=40,setQuizzesWeight:Ne=()=>{},assignmentsWeight:Ye=60,setAssignmentsWeight:Le=()=>{},handleQuizzesWeightChange:lt=()=>{},handleAssignmentsWeightChange:_e=()=>{},customCategoryOverrides:ye={},setCustomCategoryOverrides:He=()=>{},classDashboardMap:Fe={},exportClassId:ys="",exportClassName:xs="",csvPreviewData:bs=null,handleExportGrades:ws=()=>{},setSelectedAssignment:Ss=()=>{},setStudentViewStatus:vs=()=>{},setQuizStudentAnswers:Cs=()=>{},setSubAssignmentTab:Sn=()=>{},isTourOpen:ks=!1,setIsTourOpen:Es=()=>{},handleSeedSuccess:Ps=()=>{},setTeacherTab:Jt=()=>{},showCoursewareHub:Zt=!1,setShowCoursewareHub:vn=()=>{}}=e,Ee=e.courseWizard,Rt=Ee?.isCourseWizardOpen??e.isCourseWizardOpen??!1,Ts=Ee?.setIsCourseWizardOpen??e.setIsCourseWizardOpen??(()=>{}),tt=Ee?.wizardStep??e.wizardStep??1,Cn=Ee?.setWizardStep??e.setWizardStep??(()=>{}),Ns=Ee?.wizardIsSubmitting??e.wizardIsSubmitting??!1,kn=Ee?.wizardCourseTitle??e.wizardCourseTitle??"",Is=Ee?.setWizardCourseTitle??e.setWizardCourseTitle??(()=>{}),Ot=Ee?.wizardCourseDescription??e.wizardCourseDescription??"",js=Ee?.setWizardCourseDescription??e.setWizardCourseDescription??(()=>{}),En=Ee?.wizardCourseCategory??e.wizardCourseCategory??"",As=Ee?.setWizardCourseCategory??e.setWizardCourseCategory??(()=>{}),zs=Ee?.wizardCourseTimeline??e.wizardCourseTimeline??[],Ls=Ee?.setWizardCourseTimeline??e.setWizardCourseTimeline??(()=>{}),_s=Ee?.wizardCourseContent??e.wizardCourseContent??"",Rs=Ee?.setWizardCourseContent??e.setWizardCourseContent??(()=>{}),Os=Ee?.handleDeployWizardCourse??e.handleDeployWizardCourse??(()=>{}),me=e.quizGenerator,Ms=me?.isQuizGeneratorOpen??e.isQuizGeneratorOpen??!1,kt=me?.setIsQuizGeneratorOpen??e.setIsQuizGeneratorOpen??(()=>{}),Ds=me?.quizGenMode??e.quizGenMode??"scan_lesson",Fs=me?.setQuizGenMode??e.setQuizGenMode??(()=>{}),Bs=me?.quizGenSelectedLessonId??e.quizGenSelectedLessonId??"",Pn=me?.setQuizGenSelectedLessonId??e.setQuizGenSelectedLessonId??(()=>{}),Tn=me?.quizGenTopic??e.quizGenTopic??"",$s=me?.setQuizGenTopic??e.setQuizGenTopic??(()=>{}),Vs=me?.isGeneratingSuggestions??e.isGeneratingSuggestions??!1,Nn=me?.setIsGeneratingSuggestions??e.setIsGeneratingSuggestions??(()=>{}),Yt=me?.suggestedObjectives??e.suggestedObjectives??[],Kt=me?.setSuggestedObjectives??e.setSuggestedObjectives??(()=>{}),Us=me?.suggestedQuestions??e.suggestedQuestions??[],Ws=me?.setSuggestedQuestions??e.setSuggestedQuestions??(()=>{}),Se=me?.quizGenTimeLimit??e.quizGenTimeLimit??0,Et=me?.setQuizGenTimeLimit??e.setQuizGenTimeLimit??(()=>{}),In=me?.savingQuiz??e.savingQuiz??!1,jn=me?.setSavingQuiz??e.setSavingQuiz??(()=>{}),Be=me?.quizGeneratorClassId??e.quizGeneratorClassId??null,Re=e.classBatch,qs=Re?.batchPicker??e.batchPicker??null,Hs=Re?.setBatchPicker??e.setBatchPicker??(()=>{}),Gs=Re?.batchPickerLesson??e.batchPickerLesson??"",Mt=Re?.setBatchPickerLesson??e.setBatchPickerLesson??(()=>{}),Qs=Re?.batchPickerDate??e.batchPickerDate??"",Pt=Re?.setBatchPickerDate??e.setBatchPickerDate??(()=>{}),gt=Re?.batchPickerTargetClass??e.batchPickerTargetClass??"",$e=Re?.setBatchPickerTargetClass??e.setBatchPickerTargetClass??(()=>{}),Js=Re?.confirmBatchPicker??e.confirmBatchPicker??(()=>{}),Dt=e.studentNotificationsHook,Zs=Dt?.selectedNotificationForModal??e.selectedNotificationForModal??null,Ys=Dt?.setSelectedNotificationForModal??e.setSelectedNotificationForModal??(()=>{});return l.jsxs(p.Suspense,{fallback:null,children:[l.jsx(uw,{show:s,onClose:()=>r(!1),lang:t,handleImportFile:i,importError:o,importSuccess:a,isImporting:c,downloadCSVTemplate:u}),l.jsx(dw,{isCourseWizardOpen:Rt,setIsCourseWizardOpen:Ts,lang:t,wizardStep:tt,setWizardStep:Cn,wizardIsSubmitting:Ns,wizardCourseTitle:kn,setWizardCourseTitle:Is,wizardCourseDescription:Ot,setWizardCourseDescription:js,wizardCourseCategory:En,setWizardCourseCategory:As,wizardCourseTimeline:zs,setWizardCourseTimeline:Ls,wizardCourseContent:_s,setWizardCourseContent:Rs,addToast:d,generateTemplateContent:f,handleDeployWizardCourse:Os}),l.jsx(hw,{isImportLessonsOpen:m,setIsImportLessonsOpen:h,lang:t,importStatus:g,setIsDraggingImport:x,handleCSVFileChange:v,downloadCsvTemplate:w,isDraggingImport:I,previewImportData:S,setPreviewImportData:P,setImportStatus:z,importProgress:E,importProgressTotal:L,importErrorMsg:_,setImportErrorMsg:M,handleCSVImportSubmit:N}),l.jsx(fw,{isQuizGeneratorOpen:Ms,setIsQuizGeneratorOpen:kt,lessons:A,quizGenMode:Ds,setQuizGenMode:Fs,quizGenSelectedLessonId:Bs,setQuizGenSelectedLessonId:Pn,quizGenTopic:Tn,setQuizGenTopic:$s,isGeneratingSuggestions:Vs,setIsGeneratingSuggestions:Nn,suggestedObjectives:Yt,setSuggestedObjectives:Kt,suggestedQuestions:Us,setSuggestedQuestions:Ws,quizGenTimeLimit:Se,setQuizGenTimeLimit:Et,savingQuiz:In,setSavingQuiz:jn,quizGeneratorClassId:Be,fetchClassDashboard:R}),l.jsx(pw,{isLessonPreviewVisible:D,setIsLessonPreviewVisible:F,lessons:A,selectedLesson:j,previewFullscreenPanel:T,setPreviewFullscreenPanel:$,previewLessonTab:k,setPreviewLessonTab:B,activeRole:y,elements:te,activeSegmentId:ae,setActiveSegmentId:b,fetchElements:q,currentVfsParent:ee,setCurrentVfsParent:se,vfsNodes:fe,previewSelectedCourseware:ge,setPreviewSelectedCourseware:ze}),l.jsx(mw,{showProcessLogs:je,setShowProcessLogs:he,processLogsContent:ft,t:n}),l.jsx(gw,{isOpen:Lt,onClose:()=>_t(!1),vfsNodes:fe,currentVfsParent:ee,setCurrentVfsParent:se,cloudDrivePreviewNode:pt,setCloudDrivePreviewNode:mt}),l.jsx(yw,{isSystemResourceLibraryOpen:G,setIsSystemResourceLibraryOpen:K,lang:t,systemResourceTab:re,setSystemResourceTab:we,selectedLibraryResourceId:qe,setSelectedLibraryResourceId:de,vfsNodes:fe,currentVfsParent:ee,setCurrentVfsParent:se,cloudDrivePreviewNode:pt,setCloudDrivePreviewNode:mt,loadingLibraryResources:Te,libraryResources:ke,fetchLibraryResources:Ze}),l.jsx(xw,{batchPicker:qs,setBatchPicker:Hs,batchPickerLesson:Gs,setBatchPickerLesson:Mt,batchPickerDate:Qs,setBatchPickerDate:Pt,batchPickerTargetClass:gt,setBatchPickerTargetClass:$e,lessons:A,classes:O,expandedClassId:W,confirmBatchPicker:Js,lang:t}),l.jsx(bw,{isExportWeightModalOpen:Q,setIsExportWeightModalOpen:Z,lang:t,quizzesWeight:ie,setQuizzesWeight:Ne,assignmentsWeight:Ye,setAssignmentsWeight:Le,handleQuizzesWeightChange:lt,handleAssignmentsWeightChange:_e,customCategoryOverrides:ye,setCustomCategoryOverrides:He,classDashboardMap:Fe,exportClassId:ys,exportClassName:xs,csvPreviewData:bs,handleExportGrades:ws}),l.jsx(ww,{notification:Zs,onClose:()=>Ys(null),lang:t,onOpenWorkspace:Xt=>{Ss(Xt),vs("assignment"),Cs({}),Sn("quiz")}}),l.jsx(Sw,{isOpen:ks,onClose:()=>Es(!1),lang:t,onSeedSuccess:Ps,onJumpTab:Xt=>Jt(Xt)}),Zt&&l.jsx(vw,{onClose:()=>vn(!1),lang:t})]})}const kw=["whiteboard.","courseware.","quiz.","rollcall."];class Ew{constructor(){this.handlers=new Map}setSocketBridge(t){this.socketBridge=t}hasSocketBridge(){return!!this.socketBridge}subscribe(t,n){return this.handlers.has(t)||this.handlers.set(t,new Set),this.handlers.get(t).add(n),()=>{this.handlers.get(t)?.delete(n)}}async publish(t){const n=this.handlers.get(t.type);if(n)for(const s of n)try{s(t)}catch(r){console.error("[FrontendEventBus] handler error:",r)}this.socketBridge&&kw.some(s=>t.type.startsWith(s))&&this.socketBridge(t)}}const Pw=new Ew;async function Kl(e){const t=e.data;if(!t||typeof t!="object")return;if(typeof window<"u"&&typeof document<"u"&&e.source)try{if(!Array.from(document.querySelectorAll("iframe")).some(u=>u.contentWindow===e.source)&&e.source!==window)return}catch{}let n=t.attempt_id;const s=t.type||"",r=t.payload||t;if(!n&&e.source)try{const a=Array.from(document.querySelectorAll("iframe")).find(c=>c.contentWindow===e.source);if(a&&a.contentWindow){const c=a.contentWindow;c.__LMS_STUDENT__?.attempt_id&&(n=c.__LMS_STUDENT__.attempt_id)}}catch{}if(!n||typeof n!="string")return;if(s==="LMS_CONFIG"){$n("courseware.config_reported",n,t.config??r);return}if(s==="LMS_GET_PROGRESS"){const a=t.requestId,c=e.source;if(a&&c&&typeof c.postMessage=="function"){if(typeof document<"u"&&!Array.from(document.querySelectorAll("iframe")).some(h=>h.contentWindow===c)&&c!==window){console.warn("[LMS Bridge Security] Dropping response to untrusted window");return}let u;try{u=(await(await fetch(`/api/courseware/attempts/${encodeURIComponent(n)}/progress`)).json()).progress??null}catch{u=null}const d=e.origin&&e.origin!=="null"?e.origin:"*";c.postMessage({type:"LMS_PROGRESS_RESPONSE",requestId:a,progress:u},d)}return}const i=s==="LMS_SUBMIT"||s==="LMS_FINISH"||s==="submit"||s==="finish"||s==="completed"||r&&typeof r=="object"&&(r.score!==void 0||r.grade!==void 0||r.result!==void 0||r.points!==void 0),o=s==="LMS_SAVE_PROGRESS"||s==="saveProgress";if(i){$n("courseware.submitted",n,r);try{await fetch(`/api/courseware/attempts/${encodeURIComponent(n)}/submit`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({score:r?.score??r?.grade??r?.result??r?.points??void 0,comment:r?.comment??r?.feedback??r?.note??void 0,completion:r?.completion??1,status:"submitted",extra:r})})}catch(a){console.error("[LMS Bridge] Failed to submit attempt data to backend:",a)}}else if(o){$n("courseware.progress_saved",n,r);try{await fetch(`/api/courseware/attempts/${encodeURIComponent(n)}/submit`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({score:r?.score??r?.grade??r?.result??r?.points??void 0,comment:r?.comment??r?.feedback??void 0,completion:r?.completion??void 0,status:"inprogress",extra:r})})}catch(a){console.error("[LMS Bridge] Failed to save progress to backend:",a)}}else{$n("courseware.event_logged",n,r);try{await fetch(`/api/courseware/attempts/${encodeURIComponent(n)}/log`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({eventType:s||"log",payload:r})})}catch(a){console.error("[LMS Bridge] Failed to log event to backend:",a)}}}function $n(e,t,n){Pw.publish({id:Ff(),type:e,source:"courseware-bridge",payload:{attemptId:t,data:n},timestamp:Date.now(),correlationId:t})}function Tw(e,t,n,s){try{let r=s;if(!r&&e.src&&typeof window<"u")try{const i=new URL(e.src,window.location.href);i.origin&&i.origin!=="null"&&!e.src.startsWith("blob:")&&!e.src.startsWith("data:")&&(r=i.origin)}catch{}e.contentWindow?.postMessage({type:"LMS_HOST_COMMAND",event:t,payload:n},r||"*")}catch{}}function Xl(e){p.useEffect(()=>{if(!e)return;const t=n=>{Kl(n)};return window.addEventListener("message",t),()=>{window.removeEventListener("message",t)}},[e])}function ec(e,t={}){if(!(typeof document>"u"))try{document.querySelectorAll("iframe").forEach(s=>{try{s.contentWindow?.postMessage({type:"LMS_HOST_COMMAND",event:"theme:changed",payload:{theme:e,tokens:t}},"*"),s.contentWindow?.postMessage({type:"LMS_THEME_CHANGED",theme:e,tokens:t},"*")}catch{}})}catch{}}const Nw=Object.freeze(Object.defineProperty({__proto__:null,broadcastThemeToIframes:ec,processLmsMessage:Kl,sendCommandToCourseware:Tw,useLmsBridge:Xl},Symbol.toStringTag,{value:"Module"}));function Iw(e){const{session:t,showProcessLogs:n,activeStudentId:s,currentVfsParent:r,selectedLesson:i,selectedAssignment:o,expandedClassId:a,fetchLessons:c,fetchPlugins:u,fetchRegisteredCommands:d,fetchEvents:f,fetchApprovals:m,fetchProcesses:h,fetchClasses:g,fetchTodaySchedules:x,fetchStudents:v,fetchLabs:w,fetchVfs:I,fetchProcessLogs:S,fetchClassStudents:P,fetchElements:z}=e,E=p.useRef(r),L=p.useRef(i),_=p.useRef(o),M=p.useRef(a);p.useEffect(()=>{E.current=r},[r]),p.useEffect(()=>{L.current=i},[i]),p.useEffect(()=>{_.current=o},[o]),p.useEffect(()=>{M.current=a},[a]),p.useEffect(()=>{if(!t)return;c(),u(),d(),f(),m(),h(),g(),x(),v(),w(),I(E.current);let N=!1;const A=setInterval(async()=>{if(!N){N=!0;try{if(await f(),await c(),await m(),await h(),await g(),await x().catch(()=>{}),await v(),await w(),await I(E.current),await d(),n&&await S(n),M.current&&await P(M.current),L.current&&await z(L.current),_.current){const R=s||_.current.student_id;await z(`assignment-${_.current.id}-student-${R}`)}}finally{N=!1}}},2e3);return()=>clearInterval(A)},[t,n,s]),p.useEffect(()=>{I(r)},[r]),p.useEffect(()=>{i&&z(i)},[i])}function jw(e){const{lang:t,t:n,selectedLesson:s,effectiveAgentProviderId:r,expandedClassId:i,fetchLessons:o,fetchClasses:a,fetchStudents:c,fetchClassStudents:u,fetchClassProgress:d,fetchClassDashboard:f,fetchElements:m}=e,[h,g]=p.useState([{role:"agent",content:n.agentIntro||""}]),[x,v]=p.useState(""),[w,I]=p.useState(!1),[S,P]=p.useState([]);p.useEffect(()=>{h.length===1&&h[0].role==="agent"&&g([{role:"agent",content:n.agentIntro}])},[t,n.agentIntro]);const z=p.useCallback(async N=>{try{const A=await fetch(`/api/agent/conversations?lessonId=${encodeURIComponent(N||"")}`);if(!A.ok)return;const R=await A.json(),D=Array.isArray(R.messages)?R.messages:[];D.length>0?g(D.map(F=>({role:F.role==="assistant"?"agent":"user",content:F.content}))):g([{role:"agent",content:n.agentIntro}])}catch{}},[n.agentIntro]),E=p.useCallback(async()=>{try{await fetch(`/api/agent/conversations?lessonId=${encodeURIComponent(s||"")}`,{method:"DELETE"})}catch{}g([{role:"agent",content:n.agentIntro}])},[s,n.agentIntro]);return p.useEffect(()=>{z(s)},[s,z]),{chatLog:h,setChatLog:g,input:x,setInput:v,loading:w,setLoading:I,chatAttachments:S,setChatAttachments:P,handleChatFileChange:N=>{N.target.files&&Array.from(N.target.files).forEach(A=>{const R=new FileReader;R.onload=D=>{D.target?.result&&P(F=>[...F,{name:A.name,content:D.target.result}])},A.name.endsWith(".zip")?R.readAsDataURL(A):R.readAsText(A)})},handleChatDrop:N=>{N.preventDefault(),N.dataTransfer.files&&Array.from(N.dataTransfer.files).forEach(A=>{const R=new FileReader;R.onload=D=>{D.target?.result&&P(F=>[...F,{name:A.name,content:D.target.result}])},A.name.endsWith(".zip")?R.readAsDataURL(A):R.readAsText(A)})},handleSend:async N=>{if(N.preventDefault(),!x.trim()||w)return;const A=[...S];let R=x;A.length>0&&(R+=`
133
+ (📁 ${t==="zh"?"附件":"Attachments"}: ${A.map(D=>D.name).join(", ")})`),g(D=>[...D,{role:"user",content:R}]),v(""),P([]),I(!0);try{const D=await fetch("/api/agent/chat",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({message:x,lang:t,currentLessonId:s,attachments:A,providerId:r==="system"?null:r})}),F=await D.json();let j="";!D.ok||F.success===!1?j=`⚠️ [System Error] ${F.error||(t==="zh"?"未知系统错误":"Unknown System Error")}`:(j=F.agentText||"",F.toolResults&&F.toolResults.length>0&&(j+=`
134
+
135
+ ${n.executedCommands}`+F.toolResults.map(T=>T.callName).join(", "))),g(T=>[...T,{role:"agent",content:j}]),await o(),await a(),await c(),i&&(await u(i),await d(i),await f(i)),s&&await m(s)}catch{g(D=>[...D,{role:"agent",content:n.simulationError}])}finally{I(!1)}},handleClearAgentMemory:E,restoreAgentMemory:z}}const at=Object.create(null);at.open="0";at.close="1";at.ping="2";at.pong="3";at.message="4";at.upgrade="5";at.noop="6";const Jn=Object.create(null);Object.keys(at).forEach(e=>{Jn[at[e]]=e});const ei={type:"error",data:"parser error"},tc=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",nc=typeof ArrayBuffer=="function",sc=e=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,zi=({type:e,data:t},n,s)=>tc&&t instanceof Blob?n?s(t):Ia(t,s):nc&&(t instanceof ArrayBuffer||sc(t))?n?s(t):Ia(new Blob([t]),s):s(at[e]+(t||"")),Ia=(e,t)=>{const n=new FileReader;return n.onload=function(){const s=n.result.split(",")[1];t("b"+(s||""))},n.readAsDataURL(e)};function ja(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}let _r;function Aw(e,t){if(tc&&e.data instanceof Blob)return e.data.arrayBuffer().then(ja).then(t);if(nc&&(e.data instanceof ArrayBuffer||sc(e.data)))return t(ja(e.data));zi(e,!1,n=>{_r||(_r=new TextEncoder),t(_r.encode(n))})}const Aa="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",dn=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let e=0;e<Aa.length;e++)dn[Aa.charCodeAt(e)]=e;const zw=e=>{let t=e.length*.75,n=e.length,s,r=0,i,o,a,c;e[e.length-1]==="="&&(t--,e[e.length-2]==="="&&t--);const u=new ArrayBuffer(t),d=new Uint8Array(u);for(s=0;s<n;s+=4)i=dn[e.charCodeAt(s)],o=dn[e.charCodeAt(s+1)],a=dn[e.charCodeAt(s+2)],c=dn[e.charCodeAt(s+3)],d[r++]=i<<2|o>>4,d[r++]=(o&15)<<4|a>>2,d[r++]=(a&3)<<6|c&63;return u},Lw=typeof ArrayBuffer=="function",Li=(e,t)=>{if(typeof e!="string")return{type:"message",data:rc(e,t)};const n=e.charAt(0);return n==="b"?{type:"message",data:_w(e.substring(1),t)}:Jn[n]?e.length>1?{type:Jn[n],data:e.substring(1)}:{type:Jn[n]}:ei},_w=(e,t)=>{if(Lw){const n=zw(e);return rc(n,t)}else return{base64:!0,data:e}},rc=(e,t)=>{switch(t){case"blob":return e instanceof Blob?e:new Blob([e]);case"arraybuffer":default:return e instanceof ArrayBuffer?e:e.buffer}},ic="",Rw=(e,t)=>{const n=e.length,s=new Array(n);let r=0;e.forEach((i,o)=>{zi(i,!1,a=>{s[o]=a,++r===n&&t(s.join(ic))})})},Ow=(e,t)=>{const n=e.split(ic),s=[];for(let r=0;r<n.length;r++){const i=Li(n[r],t);if(s.push(i),i.type==="error")break}return s};function Mw(){return new TransformStream({transform(e,t){Aw(e,n=>{const s=n.length;let r;if(s<126)r=new Uint8Array(1),new DataView(r.buffer).setUint8(0,s);else if(s<65536){r=new Uint8Array(3);const i=new DataView(r.buffer);i.setUint8(0,126),i.setUint16(1,s)}else{r=new Uint8Array(9);const i=new DataView(r.buffer);i.setUint8(0,127),i.setBigUint64(1,BigInt(s))}e.data&&typeof e.data!="string"&&(r[0]|=128),t.enqueue(r),t.enqueue(n)})}})}let Rr;function Vn(e){return e.reduce((t,n)=>t+n.length,0)}function Un(e,t){if(e[0].length===t)return e.shift();const n=new Uint8Array(t);let s=0;for(let r=0;r<t;r++)n[r]=e[0][s++],s===e[0].length&&(e.shift(),s=0);return e.length&&s<e[0].length&&(e[0]=e[0].slice(s)),n}function Dw(e,t){Rr||(Rr=new TextDecoder);const n=[];let s=0,r=-1,i=!1;return new TransformStream({transform(o,a){for(n.push(o);;){if(s===0){if(Vn(n)<1)break;const c=Un(n,1);i=(c[0]&128)===128,r=c[0]&127,r<126?s=3:r===126?s=1:s=2}else if(s===1){if(Vn(n)<2)break;const c=Un(n,2);r=new DataView(c.buffer,c.byteOffset,c.length).getUint16(0),s=3}else if(s===2){if(Vn(n)<8)break;const c=Un(n,8),u=new DataView(c.buffer,c.byteOffset,c.length),d=u.getUint32(0);if(d>Math.pow(2,21)-1){a.enqueue(ei);break}r=d*Math.pow(2,32)+u.getUint32(4),s=3}else{if(Vn(n)<r)break;const c=Un(n,r);a.enqueue(Li(i?c:Rr.decode(c),t)),s=0}if(r===0||r>e){a.enqueue(ei);break}}}})}const oc=4;function be(e){if(e)return Fw(e)}function Fw(e){for(var t in be.prototype)e[t]=be.prototype[t];return e}be.prototype.on=be.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(t),this};be.prototype.once=function(e,t){function n(){this.off(e,n),t.apply(this,arguments)}return n.fn=t,this.on(e,n),this};be.prototype.off=be.prototype.removeListener=be.prototype.removeAllListeners=be.prototype.removeEventListener=function(e,t){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var n=this._callbacks["$"+e];if(!n)return this;if(arguments.length==1)return delete this._callbacks["$"+e],this;for(var s,r=0;r<n.length;r++)if(s=n[r],s===t||s.fn===t){n.splice(r,1);break}return n.length===0&&delete this._callbacks["$"+e],this};be.prototype.emit=function(e){this._callbacks=this._callbacks||{};for(var t=new Array(arguments.length-1),n=this._callbacks["$"+e],s=1;s<arguments.length;s++)t[s-1]=arguments[s];if(n){n=n.slice(0);for(var s=0,r=n.length;s<r;++s)n[s].apply(this,t)}return this};be.prototype.emitReserved=be.prototype.emit;be.prototype.listeners=function(e){return this._callbacks=this._callbacks||{},this._callbacks["$"+e]||[]};be.prototype.hasListeners=function(e){return!!this.listeners(e).length};const ms=typeof Promise=="function"&&typeof Promise.resolve=="function"?t=>Promise.resolve().then(t):(t,n)=>n(t,0),Je=typeof self<"u"?self:typeof window<"u"?window:Function("return this")(),Bw="arraybuffer";function ac(e,...t){return t.reduce((n,s)=>(e.hasOwnProperty(s)&&(n[s]=e[s]),n),{})}const $w=Je.setTimeout,Vw=Je.clearTimeout;function gs(e,t){t.useNativeTimers?(e.setTimeoutFn=$w.bind(Je),e.clearTimeoutFn=Vw.bind(Je)):(e.setTimeoutFn=Je.setTimeout.bind(Je),e.clearTimeoutFn=Je.clearTimeout.bind(Je))}const Uw=1.33;function Ww(e){return typeof e=="string"?qw(e):Math.ceil((e.byteLength||e.size)*Uw)}function qw(e){let t=0,n=0;for(let s=0,r=e.length;s<r;s++)t=e.charCodeAt(s),t<128?n+=1:t<2048?n+=2:t<55296||t>=57344?n+=3:(s++,n+=4);return n}function lc(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}function Hw(e){let t="";for(let n in e)e.hasOwnProperty(n)&&(t.length&&(t+="&"),t+=encodeURIComponent(n)+"="+encodeURIComponent(e[n]));return t}function Gw(e){let t={},n=e.split("&");for(let s=0,r=n.length;s<r;s++){let i=n[s].split("=");t[decodeURIComponent(i[0])]=decodeURIComponent(i[1])}return t}class Qw extends Error{constructor(t,n,s){super(t),this.description=n,this.context=s,this.type="TransportError"}}class _i extends be{constructor(t){super(),this.writable=!1,gs(this,t),this.opts=t,this.query=t.query,this.socket=t.socket,this.supportsBinary=!t.forceBase64}onError(t,n,s){return super.emitReserved("error",new Qw(t,n,s)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return(this.readyState==="opening"||this.readyState==="open")&&(this.doClose(),this.onClose()),this}send(t){this.readyState==="open"&&this.write(t)}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(t){const n=Li(t,this.socket.binaryType);this.onPacket(n)}onPacket(t){super.emitReserved("packet",t)}onClose(t){this.readyState="closed",super.emitReserved("close",t)}pause(t){}createUri(t,n={}){return t+"://"+this._hostname()+this._port()+this.opts.path+this._query(n)}_hostname(){const t=this.opts.hostname;return t.indexOf(":")===-1?t:"["+t+"]"}_port(){return this.opts.port&&(this.opts.secure&&Number(this.opts.port)!==443||!this.opts.secure&&Number(this.opts.port)!==80)?":"+this.opts.port:""}_query(t){const n=Hw(t);return n.length?"?"+n:""}}class Jw extends _i{constructor(){super(...arguments),this._polling=!1}get name(){return"polling"}doOpen(){this._poll()}pause(t){this.readyState="pausing";const n=()=>{this.readyState="paused",t()};if(this._polling||!this.writable){let s=0;this._polling&&(s++,this.once("pollComplete",function(){--s||n()})),this.writable||(s++,this.once("drain",function(){--s||n()}))}else n()}_poll(){this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(t){const n=s=>{if(this.readyState==="opening"&&s.type==="open"&&this.onOpen(),s.type==="close")return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(s)};Ow(t,this.socket.binaryType).forEach(n),this.readyState!=="closed"&&(this._polling=!1,this.emitReserved("pollComplete"),this.readyState==="open"&&this._poll())}doClose(){const t=()=>{this.write([{type:"close"}])};this.readyState==="open"?t():this.once("open",t)}write(t){this.writable=!1,Rw(t,n=>{this.doWrite(n,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){const t=this.opts.secure?"https":"http",n=this.query||{};return this.opts.timestampRequests!==!1&&(n[this.opts.timestampParam]=lc()),!this.supportsBinary&&!n.sid&&(n.b64=1),this.createUri(t,n)}}let cc=!1;try{cc=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}const Zw=cc;function Yw(){}class Kw extends Jw{constructor(t){if(super(t),typeof location<"u"){const n=location.protocol==="https:";let s=location.port;s||(s=n?"443":"80"),this.xd=typeof location<"u"&&t.hostname!==location.hostname||s!==t.port}}doWrite(t,n){const s=this.request({method:"POST",data:t});s.on("success",n),s.on("error",(r,i)=>{this.onError("xhr post error",r,i)})}doPoll(){const t=this.request();t.on("data",this.onData.bind(this)),t.on("error",(n,s)=>{this.onError("xhr poll error",n,s)}),this.pollXhr=t}}class it extends be{constructor(t,n,s){super(),this.createRequest=t,gs(this,s),this._opts=s,this._method=s.method||"GET",this._uri=n,this._data=s.data!==void 0?s.data:null,this._create()}_create(){var t;const n=ac(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");n.xdomain=!!this._opts.xd;const s=this._xhr=this.createRequest(n);try{s.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){s.setDisableHeaderCheck&&s.setDisableHeaderCheck(!0);for(let r in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(r)&&s.setRequestHeader(r,this._opts.extraHeaders[r])}}catch{}if(this._method==="POST")try{s.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch{}try{s.setRequestHeader("Accept","*/*")}catch{}(t=this._opts.cookieJar)===null||t===void 0||t.addCookies(s),"withCredentials"in s&&(s.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(s.timeout=this._opts.requestTimeout),s.onreadystatechange=()=>{var r;s.readyState===3&&((r=this._opts.cookieJar)===null||r===void 0||r.parseCookies(s.getResponseHeader("set-cookie"))),s.readyState===4&&(s.status===200||s.status===1223?this._onLoad():this.setTimeoutFn(()=>{this._onError(typeof s.status=="number"?s.status:0)},0))},s.send(this._data)}catch(r){this.setTimeoutFn(()=>{this._onError(r)},0);return}typeof document<"u"&&(this._index=it.requestsCount++,it.requests[this._index]=this)}_onError(t){this.emitReserved("error",t,this._xhr),this._cleanup(!0)}_cleanup(t){if(!(typeof this._xhr>"u"||this._xhr===null)){if(this._xhr.onreadystatechange=Yw,t)try{this._xhr.abort()}catch{}typeof document<"u"&&delete it.requests[this._index],this._xhr=null}}_onLoad(){const t=this._xhr.responseText;t!==null&&(this.emitReserved("data",t),this.emitReserved("success"),this._cleanup())}abort(){this._cleanup()}}it.requestsCount=0;it.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",za);else if(typeof addEventListener=="function"){const e="onpagehide"in Je?"pagehide":"unload";addEventListener(e,za,!1)}}function za(){for(let e in it.requests)it.requests.hasOwnProperty(e)&&it.requests[e].abort()}const Xw=(function(){const e=uc({xdomain:!1});return e&&e.responseType!==null})();class eS extends Kw{constructor(t){super(t);const n=t&&t.forceBase64;this.supportsBinary=Xw&&!n}request(t={}){return Object.assign(t,{xd:this.xd},this.opts),new it(uc,this.uri(),t)}}function uc(e){const t=e.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!t||Zw))return new XMLHttpRequest}catch{}if(!t)try{return new Je[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}const dc=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative";class tS extends _i{get name(){return"websocket"}doOpen(){const t=this.uri(),n=this.opts.protocols,s=dc?{}:ac(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(s.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(t,n,s)}catch(r){return this.emitReserved("error",r)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=t=>this.onClose({description:"websocket connection closed",context:t}),this.ws.onmessage=t=>this.onData(t.data),this.ws.onerror=t=>this.onError("websocket error",t)}write(t){this.writable=!1;for(let n=0;n<t.length;n++){const s=t[n],r=n===t.length-1;zi(s,this.supportsBinary,i=>{try{this.doWrite(s,i)}catch{}r&&ms(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){typeof this.ws<"u"&&(this.ws.onerror=()=>{},this.ws.close(),this.ws=null)}uri(){const t=this.opts.secure?"wss":"ws",n=this.query||{};return this.opts.timestampRequests&&(n[this.opts.timestampParam]=lc()),this.supportsBinary||(n.b64=1),this.createUri(t,n)}}const Or=Je.WebSocket||Je.MozWebSocket;class nS extends tS{createSocket(t,n,s){return dc?new Or(t,n,s):n?new Or(t,n):new Or(t)}doWrite(t,n){this.ws.send(n)}}class sS extends _i{get name(){return"webtransport"}doOpen(){try{this._transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(t){return this.emitReserved("error",t)}this._transport.closed.then(()=>{this.onClose()}).catch(t=>{this.onError("webtransport error",t)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(t=>{const n=Dw(Number.MAX_SAFE_INTEGER,this.socket.binaryType),s=t.readable.pipeThrough(n).getReader(),r=Mw();r.readable.pipeTo(t.writable),this._writer=r.writable.getWriter();const i=()=>{s.read().then(({done:a,value:c})=>{a||(this.onPacket(c),i())}).catch(a=>{})};i();const o={type:"open"};this.query.sid&&(o.data=`{"sid":"${this.query.sid}"}`),this._writer.write(o).then(()=>this.onOpen())})})}write(t){this.writable=!1;for(let n=0;n<t.length;n++){const s=t[n],r=n===t.length-1;this._writer.write(s).then(()=>{r&&ms(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var t;(t=this._transport)===null||t===void 0||t.close()}}const rS={websocket:nS,webtransport:sS,polling:eS},iS=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,oS=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function ti(e){if(e.length>8e3)throw"URI too long";const t=e,n=e.indexOf("["),s=e.indexOf("]");n!=-1&&s!=-1&&(e=e.substring(0,n)+e.substring(n,s).replace(/:/g,";")+e.substring(s,e.length));let r=iS.exec(e||""),i={},o=14;for(;o--;)i[oS[o]]=r[o]||"";return n!=-1&&s!=-1&&(i.source=t,i.host=i.host.substring(1,i.host.length-1).replace(/;/g,":"),i.authority=i.authority.replace("[","").replace("]","").replace(/;/g,":"),i.ipv6uri=!0),i.pathNames=aS(i,i.path),i.queryKey=lS(i,i.query),i}function aS(e,t){const n=/\/{2,9}/g,s=t.replace(n,"/").split("/");return(t.slice(0,1)=="/"||t.length===0)&&s.splice(0,1),t.slice(-1)=="/"&&s.splice(s.length-1,1),s}function lS(e,t){const n={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(s,r,i){r&&(n[r]=i)}),n}const ni=typeof addEventListener=="function"&&typeof removeEventListener=="function",Zn=[];ni&&addEventListener("offline",()=>{Zn.forEach(e=>e())},!1);class St extends be{constructor(t,n){if(super(),this.binaryType=Bw,this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,t&&typeof t=="object"&&(n=t,t=null),t){const s=ti(t);n.hostname=s.host,n.secure=s.protocol==="https"||s.protocol==="wss",n.port=s.port,s.query&&(n.query=s.query)}else n.host&&(n.hostname=ti(n.host).host);gs(this,n),this.secure=n.secure!=null?n.secure:typeof location<"u"&&location.protocol==="https:",n.hostname&&!n.port&&(n.port=this.secure?"443":"80"),this.hostname=n.hostname||(typeof location<"u"?location.hostname:"localhost"),this.port=n.port||(typeof location<"u"&&location.port?location.port:this.secure?"443":"80"),this.transports=[],this._transportsByName={},n.transports.forEach(s=>{const r=s.prototype.name;this.transports.push(r),this._transportsByName[r]=s}),this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},n),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),typeof this.opts.query=="string"&&(this.opts.query=Gw(this.opts.query)),ni&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this._beforeunloadEventListener,!1)),this.hostname!=="localhost"&&(this._offlineEventListener=()=>{this._onClose("transport close",{description:"network connection lost"})},Zn.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(t){const n=Object.assign({},this.opts.query);n.EIO=oc,n.transport=t,this.id&&(n.sid=this.id);const s=Object.assign({},this.opts,{query:n,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[t]);return new this._transportsByName[t](s)}_open(){if(this.transports.length===0){this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);return}const t=this.opts.rememberUpgrade&&St.priorWebsocketSuccess&&this.transports.indexOf("websocket")!==-1?"websocket":this.transports[0];this.readyState="opening";const n=this.createTransport(t);n.open(),this.setTransport(n)}setTransport(t){this.transport&&this.transport.removeAllListeners(),this.transport=t,t.on("drain",this._onDrain.bind(this)).on("packet",this._onPacket.bind(this)).on("error",this._onError.bind(this)).on("close",n=>this._onClose("transport close",n))}onOpen(){this.readyState="open",St.priorWebsocketSuccess=this.transport.name==="websocket",this.emitReserved("open"),this.flush()}_onPacket(t){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing")switch(this.emitReserved("packet",t),this.emitReserved("heartbeat"),t.type){case"open":this.onHandshake(JSON.parse(t.data));break;case"ping":this._sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong"),this._resetPingTimeout();break;case"error":const n=new Error("server error");n.code=t.data,this._onError(n);break;case"message":this.emitReserved("data",t.data),this.emitReserved("message",t.data);break}}onHandshake(t){this.emitReserved("handshake",t),this.id=t.sid,this.transport.query.sid=t.sid,this._pingInterval=t.pingInterval,this._pingTimeout=t.pingTimeout,this._maxPayload=t.maxPayload,this.onOpen(),this.readyState!=="closed"&&this._resetPingTimeout()}_resetPingTimeout(){this.clearTimeoutFn(this._pingTimeoutTimer);const t=this._pingInterval+this._pingTimeout;this._pingTimeoutTime=Date.now()+t,this._pingTimeoutTimer=this.setTimeoutFn(()=>{this._onClose("ping timeout")},t),this.opts.autoUnref&&this._pingTimeoutTimer.unref()}_onDrain(){this.writeBuffer.splice(0,this._prevBufferLen),this._prevBufferLen=0,this.writeBuffer.length===0?this.emitReserved("drain"):this.flush()}flush(){if(this.readyState!=="closed"&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){const t=this._getWritablePackets();this.transport.send(t),this._prevBufferLen=t.length,this.emitReserved("flush")}}_getWritablePackets(){if(!(this._maxPayload&&this.transport.name==="polling"&&this.writeBuffer.length>1))return this.writeBuffer;let n=1;for(let s=0;s<this.writeBuffer.length;s++){const r=this.writeBuffer[s].data;if(r&&(n+=Ww(r)),s>0&&n>this._maxPayload)return this.writeBuffer.slice(0,s);n+=2}return this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;const t=Date.now()>this._pingTimeoutTime;return t&&(this._pingTimeoutTime=0,ms(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),t}write(t,n,s){return this._sendPacket("message",t,n,s),this}send(t,n,s){return this._sendPacket("message",t,n,s),this}_sendPacket(t,n,s,r){if(typeof n=="function"&&(r=n,n=void 0),typeof s=="function"&&(r=s,s=null),this.readyState==="closing"||this.readyState==="closed")return;s=s||{},s.compress=s.compress!==!1;const i={type:t,data:n,options:s};this.emitReserved("packetCreate",i),this.writeBuffer.push(i),r&&this.once("flush",r),this.flush()}close(){const t=()=>{this._onClose("forced close"),this.transport.close()},n=()=>{this.off("upgrade",n),this.off("upgradeError",n),t()},s=()=>{this.once("upgrade",n),this.once("upgradeError",n)};return(this.readyState==="opening"||this.readyState==="open")&&(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?s():t()}):this.upgrading?s():t()),this}_onError(t){if(St.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&this.readyState==="opening")return this.transports.shift(),this._open();this.emitReserved("error",t),this._onClose("transport error",t)}_onClose(t,n){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing"){if(this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),ni&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const s=Zn.indexOf(this._offlineEventListener);s!==-1&&Zn.splice(s,1)}this.readyState="closed",this.id=null,this.emitReserved("close",t,n),this.writeBuffer=[],this._prevBufferLen=0}}}St.protocol=oc;class cS extends St{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),this.readyState==="open"&&this.opts.upgrade)for(let t=0;t<this._upgrades.length;t++)this._probe(this._upgrades[t])}_probe(t){let n=this.createTransport(t),s=!1;St.priorWebsocketSuccess=!1;const r=()=>{s||(n.send([{type:"ping",data:"probe"}]),n.once("packet",f=>{if(!s)if(f.type==="pong"&&f.data==="probe"){if(this.upgrading=!0,this.emitReserved("upgrading",n),!n)return;St.priorWebsocketSuccess=n.name==="websocket",this.transport.pause(()=>{s||this.readyState!=="closed"&&(d(),this.setTransport(n),n.send([{type:"upgrade"}]),this.emitReserved("upgrade",n),n=null,this.upgrading=!1,this.flush())})}else{const m=new Error("probe error");m.transport=n.name,this.emitReserved("upgradeError",m)}}))};function i(){s||(s=!0,d(),n.close(),n=null)}const o=f=>{const m=new Error("probe error: "+f);m.transport=n.name,i(),this.emitReserved("upgradeError",m)};function a(){o("transport closed")}function c(){o("socket closed")}function u(f){n&&f.name!==n.name&&i()}const d=()=>{n.removeListener("open",r),n.removeListener("error",o),n.removeListener("close",a),this.off("close",c),this.off("upgrading",u)};n.once("open",r),n.once("error",o),n.once("close",a),this.once("close",c),this.once("upgrading",u),this._upgrades.indexOf("webtransport")!==-1&&t!=="webtransport"?this.setTimeoutFn(()=>{s||n.open()},200):n.open()}onHandshake(t){this._upgrades=this._filterUpgrades(t.upgrades),super.onHandshake(t)}_filterUpgrades(t){const n=[];for(let s=0;s<t.length;s++)~this.transports.indexOf(t[s])&&n.push(t[s]);return n}}let uS=class extends cS{constructor(t,n={}){const s=typeof t=="object"?t:n;(!s.transports||s.transports&&typeof s.transports[0]=="string")&&(s.transports=(s.transports||["polling","websocket","webtransport"]).map(r=>rS[r]).filter(r=>!!r)),super(t,s)}};function dS(e,t="",n){let s=e;n=n||typeof location<"u"&&location,e==null&&(e=n.protocol+"//"+n.host),typeof e=="string"&&(e.charAt(0)==="/"&&(e.charAt(1)==="/"?e=n.protocol+e:e=n.host+e),/^(https?|wss?):\/\//.test(e)||(typeof n<"u"?e=n.protocol+"//"+e:e="https://"+e),s=ti(e)),s.port||(/^(http|ws)$/.test(s.protocol)?s.port="80":/^(http|ws)s$/.test(s.protocol)&&(s.port="443")),s.path=s.path||"/";const i=s.host.indexOf(":")!==-1?"["+s.host+"]":s.host;return s.id=s.protocol+"://"+i+":"+s.port+t,s.href=s.protocol+"://"+i+(n&&n.port===s.port?"":":"+s.port),s}const hS=typeof ArrayBuffer=="function",fS=e=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer,hc=Object.prototype.toString,pS=typeof Blob=="function"||typeof Blob<"u"&&hc.call(Blob)==="[object BlobConstructor]",mS=typeof File=="function"||typeof File<"u"&&hc.call(File)==="[object FileConstructor]";function Ri(e){return hS&&(e instanceof ArrayBuffer||fS(e))||pS&&e instanceof Blob||mS&&e instanceof File}function Yn(e,t){if(!e||typeof e!="object")return!1;if(Array.isArray(e)){for(let n=0,s=e.length;n<s;n++)if(Yn(e[n]))return!0;return!1}if(Ri(e))return!0;if(e.toJSON&&typeof e.toJSON=="function"&&arguments.length===1)return Yn(e.toJSON(),!0);for(const n in e)if(Object.prototype.hasOwnProperty.call(e,n)&&Yn(e[n]))return!0;return!1}function gS(e){const t=[],n=e.data,s=e;return s.data=Kn(n,t),s.attachments=t.length,{packet:s,buffers:t}}function Kn(e,t,n){if(!e)return e;if(Ri(e)){const s={_placeholder:!0,num:t.length};return t.push(e),s}else if(Array.isArray(e)){const s=new Array(e.length);for(let r=0;r<e.length;r++)s[r]=Kn(e[r],t);return s}else if(typeof e=="object"&&!(e instanceof Date)){if(e.toJSON&&typeof e.toJSON=="function"&&!n)return Kn(e.toJSON(),t,!0);const s={};for(const r in e)Object.prototype.hasOwnProperty.call(e,r)&&(s[r]=Kn(e[r],t));return s}return e}function yS(e,t){return e.data=si(e.data,t),delete e.attachments,e}function si(e,t){if(!e)return e;if(e&&e._placeholder===!0){if(typeof e.num=="number"&&e.num>=0&&e.num<t.length)return t[e.num];throw new Error("illegal attachments")}else if(Array.isArray(e))for(let n=0;n<e.length;n++)e[n]=si(e[n],t);else if(typeof e=="object")for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&(e[n]=si(e[n],t));return e}const xS=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];var ne;(function(e){e[e.CONNECT=0]="CONNECT",e[e.DISCONNECT=1]="DISCONNECT",e[e.EVENT=2]="EVENT",e[e.ACK=3]="ACK",e[e.CONNECT_ERROR=4]="CONNECT_ERROR",e[e.BINARY_EVENT=5]="BINARY_EVENT",e[e.BINARY_ACK=6]="BINARY_ACK"})(ne||(ne={}));class bS{constructor(t){this.replacer=t}encode(t){return(t.type===ne.EVENT||t.type===ne.ACK)&&Yn(t)?this.encodeAsBinary({type:t.type===ne.EVENT?ne.BINARY_EVENT:ne.BINARY_ACK,nsp:t.nsp,data:t.data,id:t.id}):[this.encodeAsString(t)]}encodeAsString(t){let n=""+t.type;return(t.type===ne.BINARY_EVENT||t.type===ne.BINARY_ACK)&&(n+=t.attachments+"-"),t.nsp&&t.nsp!=="/"&&(n+=t.nsp+","),t.id!=null&&(n+=t.id),t.data!=null&&(n+=JSON.stringify(t.data,this.replacer)),n}encodeAsBinary(t){const n=gS(t),s=this.encodeAsString(n.packet),r=n.buffers;return r.unshift(s),r}}class Oi extends be{constructor(t){super(),this.opts=Object.assign({reviver:void 0,maxAttachments:10},typeof t=="function"?{reviver:t}:t)}add(t){let n;if(typeof t=="string"){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");n=this.decodeString(t);const s=n.type===ne.BINARY_EVENT;s||n.type===ne.BINARY_ACK?(n.type=s?ne.EVENT:ne.ACK,this.reconstructor=new wS(n)):super.emitReserved("decoded",n)}else if(Ri(t)||t.base64)if(this.reconstructor)n=this.reconstructor.takeBinaryData(t),n&&(this.reconstructor=null,super.emitReserved("decoded",n));else throw new Error("got binary data when not reconstructing a packet");else throw new Error("Unknown type: "+t)}decodeString(t){let n=0;const s={type:Number(t.charAt(0))};if(ne[s.type]===void 0)throw new Error("unknown packet type "+s.type);if(s.type===ne.BINARY_EVENT||s.type===ne.BINARY_ACK){const i=n+1;for(;t.charAt(++n)!=="-"&&n!=t.length;);const o=t.substring(i,n);if(o!=Number(o)||t.charAt(n)!=="-")throw new Error("Illegal attachments");const a=Number(o);if(!SS(a)||a<1)throw new Error("Illegal attachments");if(a>this.opts.maxAttachments)throw new Error("too many attachments");s.attachments=a}if(t.charAt(n+1)==="/"){const i=n+1;for(;++n&&!(t.charAt(n)===","||n===t.length););s.nsp=t.substring(i,n)}else s.nsp="/";const r=t.charAt(n+1);if(r!==""&&Number(r)==r){const i=n+1;for(;++n;){const o=t.charAt(n);if(o==null||Number(o)!=o){--n;break}if(n===t.length)break}s.id=Number(t.substring(i,n+1))}if(t.charAt(++n)){const i=this.tryParse(t.substr(n));if(Oi.isPayloadValid(s.type,i))s.data=i;else throw new Error("invalid payload")}return s}tryParse(t){try{return JSON.parse(t,this.opts.reviver)}catch{return!1}}static isPayloadValid(t,n){switch(t){case ne.CONNECT:return La(n);case ne.DISCONNECT:return n===void 0;case ne.CONNECT_ERROR:return typeof n=="string"||La(n);case ne.EVENT:case ne.BINARY_EVENT:return Array.isArray(n)&&(typeof n[0]=="number"||typeof n[0]=="string"&&xS.indexOf(n[0])===-1);case ne.ACK:case ne.BINARY_ACK:return Array.isArray(n)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class wS{constructor(t){this.packet=t,this.buffers=[],this.reconPack=t}takeBinaryData(t){if(this.buffers.push(t),this.buffers.length===this.reconPack.attachments){const n=yS(this.reconPack,this.buffers);return this.finishedReconstruction(),n}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}const SS=Number.isInteger||function(e){return typeof e=="number"&&isFinite(e)&&Math.floor(e)===e};function La(e){return Object.prototype.toString.call(e)==="[object Object]"}const vS=Object.freeze(Object.defineProperty({__proto__:null,Decoder:Oi,Encoder:bS,get PacketType(){return ne}},Symbol.toStringTag,{value:"Module"}));function Ke(e,t,n){return e.on(t,n),function(){e.off(t,n)}}const CS=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class fc extends be{constructor(t,n,s){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=t,this.nsp=n,s&&s.auth&&(this.auth=s.auth),this._opts=Object.assign({},s),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const t=this.io;this.subs=[Ke(t,"open",this.onopen.bind(this)),Ke(t,"packet",this.onpacket.bind(this)),Ke(t,"error",this.onerror.bind(this)),Ke(t,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected?this:(this.subEvents(),this.io._reconnecting||this.io.open(),this.io._readyState==="open"&&this.onopen(),this)}open(){return this.connect()}send(...t){return t.unshift("message"),this.emit.apply(this,t),this}emit(t,...n){var s,r,i;if(CS.hasOwnProperty(t))throw new Error('"'+t.toString()+'" is a reserved event name');if(n.unshift(t),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(n),this;const o={type:ne.EVENT,data:n};if(o.options={},o.options.compress=this.flags.compress!==!1,typeof n[n.length-1]=="function"){const d=this.ids++,f=n.pop();this._registerAckCallback(d,f),o.id=d}const a=(r=(s=this.io.engine)===null||s===void 0?void 0:s.transport)===null||r===void 0?void 0:r.writable,c=this.connected&&!(!((i=this.io.engine)===null||i===void 0)&&i._hasPingExpired());return this.flags.volatile&&!a||(c?(this.notifyOutgoingListeners(o),this.packet(o)):this.sendBuffer.push(o)),this.flags={},this}_registerAckCallback(t,n){var s;const r=(s=this.flags.timeout)!==null&&s!==void 0?s:this._opts.ackTimeout;if(r===void 0){this.acks[t]=n;return}const i=this.io.setTimeoutFn(()=>{delete this.acks[t];for(let a=0;a<this.sendBuffer.length;a++)this.sendBuffer[a].id===t&&this.sendBuffer.splice(a,1);n.call(this,new Error("operation has timed out"))},r),o=(...a)=>{this.io.clearTimeoutFn(i),n.apply(this,a)};o.withError=!0,this.acks[t]=o}emitWithAck(t,...n){return new Promise((s,r)=>{const i=(o,a)=>o?r(o):s(a);i.withError=!0,n.push(i),this.emit(t,...n)})}_addToQueue(t){let n;typeof t[t.length-1]=="function"&&(n=t.pop());const s={id:this._queueSeq++,tryCount:0,pending:!1,args:t,flags:Object.assign({fromQueue:!0},this.flags)};t.push((r,...i)=>(this._queue[0],r!==null?s.tryCount>this._opts.retries&&(this._queue.shift(),n&&n(r)):(this._queue.shift(),n&&n(null,...i)),s.pending=!1,this._drainQueue())),this._queue.push(s),this._drainQueue()}_drainQueue(t=!1){if(!this.connected||this._queue.length===0)return;const n=this._queue[0];n.pending&&!t||(n.pending=!0,n.tryCount++,this.flags=n.flags,this.emit.apply(this,n.args))}packet(t){t.nsp=this.nsp,this.io._packet(t)}onopen(){typeof this.auth=="function"?this.auth(t=>{this._sendConnectPacket(t)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(t){this.packet({type:ne.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},t):t})}onerror(t){this.connected||this.emitReserved("connect_error",t)}onclose(t,n){this.connected=!1,delete this.id,this.emitReserved("disconnect",t,n),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach(t=>{if(!this.sendBuffer.some(s=>String(s.id)===t)){const s=this.acks[t];delete this.acks[t],s.withError&&s.call(this,new Error("socket has been disconnected"))}})}onpacket(t){if(t.nsp===this.nsp)switch(t.type){case ne.CONNECT:t.data&&t.data.sid?this.onconnect(t.data.sid,t.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case ne.EVENT:case ne.BINARY_EVENT:this.onevent(t);break;case ne.ACK:case ne.BINARY_ACK:this.onack(t);break;case ne.DISCONNECT:this.ondisconnect();break;case ne.CONNECT_ERROR:this.destroy();const s=new Error(t.data.message);s.data=t.data.data,this.emitReserved("connect_error",s);break}}onevent(t){const n=t.data||[];t.id!=null&&n.push(this.ack(t.id)),this.connected?this.emitEvent(n):this.receiveBuffer.push(Object.freeze(n))}emitEvent(t){if(this._anyListeners&&this._anyListeners.length){const n=this._anyListeners.slice();for(const s of n)s.apply(this,t)}super.emit.apply(this,t),this._pid&&t.length&&typeof t[t.length-1]=="string"&&(this._lastOffset=t[t.length-1])}ack(t){const n=this;let s=!1;return function(...r){s||(s=!0,n.packet({type:ne.ACK,id:t,data:r}))}}onack(t){const n=this.acks[t.id];typeof n=="function"&&(delete this.acks[t.id],n.withError&&t.data.unshift(null),n.apply(this,t.data))}onconnect(t,n){this.id=t,this.recovered=n&&this._pid===n,this._pid=n,this.connected=!0,this.emitBuffered(),this._drainQueue(!0),this.emitReserved("connect")}emitBuffered(){this.receiveBuffer.forEach(t=>this.emitEvent(t)),this.receiveBuffer=[],this.sendBuffer.forEach(t=>{this.notifyOutgoingListeners(t),this.packet(t)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(t=>t()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:ne.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(t){return this.flags.compress=t,this}get volatile(){return this.flags.volatile=!0,this}timeout(t){return this.flags.timeout=t,this}onAny(t){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(t),this}prependAny(t){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(t),this}offAny(t){if(!this._anyListeners)return this;if(t){const n=this._anyListeners;for(let s=0;s<n.length;s++)if(t===n[s])return n.splice(s,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(t){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(t),this}prependAnyOutgoing(t){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(t),this}offAnyOutgoing(t){if(!this._anyOutgoingListeners)return this;if(t){const n=this._anyOutgoingListeners;for(let s=0;s<n.length;s++)if(t===n[s])return n.splice(s,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(t){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){const n=this._anyOutgoingListeners.slice();for(const s of n)s.apply(this,t.data)}}}function Qt(e){e=e||{},this.ms=e.min||100,this.max=e.max||1e4,this.factor=e.factor||2,this.jitter=e.jitter>0&&e.jitter<=1?e.jitter:0,this.attempts=0}Qt.prototype.duration=function(){var e=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var t=Math.random(),n=Math.floor(t*this.jitter*e);e=(Math.floor(t*10)&1)==0?e-n:e+n}return Math.min(e,this.max)|0};Qt.prototype.reset=function(){this.attempts=0};Qt.prototype.setMin=function(e){this.ms=e};Qt.prototype.setMax=function(e){this.max=e};Qt.prototype.setJitter=function(e){this.jitter=e};class ri extends be{constructor(t,n){var s;super(),this.nsps={},this.subs=[],t&&typeof t=="object"&&(n=t,t=void 0),n=n||{},n.path=n.path||"/socket.io",this.opts=n,gs(this,n),this.reconnection(n.reconnection!==!1),this.reconnectionAttempts(n.reconnectionAttempts||1/0),this.reconnectionDelay(n.reconnectionDelay||1e3),this.reconnectionDelayMax(n.reconnectionDelayMax||5e3),this.randomizationFactor((s=n.randomizationFactor)!==null&&s!==void 0?s:.5),this.backoff=new Qt({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(n.timeout==null?2e4:n.timeout),this._readyState="closed",this.uri=t;const r=n.parser||vS;this.encoder=new r.Encoder,this.decoder=new r.Decoder,this._autoConnect=n.autoConnect!==!1,this._autoConnect&&this.open()}reconnection(t){return arguments.length?(this._reconnection=!!t,t||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(t){return t===void 0?this._reconnectionAttempts:(this._reconnectionAttempts=t,this)}reconnectionDelay(t){var n;return t===void 0?this._reconnectionDelay:(this._reconnectionDelay=t,(n=this.backoff)===null||n===void 0||n.setMin(t),this)}randomizationFactor(t){var n;return t===void 0?this._randomizationFactor:(this._randomizationFactor=t,(n=this.backoff)===null||n===void 0||n.setJitter(t),this)}reconnectionDelayMax(t){var n;return t===void 0?this._reconnectionDelayMax:(this._reconnectionDelayMax=t,(n=this.backoff)===null||n===void 0||n.setMax(t),this)}timeout(t){return arguments.length?(this._timeout=t,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&this.backoff.attempts===0&&this.reconnect()}open(t){if(~this._readyState.indexOf("open"))return this;this.engine=new uS(this.uri,this.opts);const n=this.engine,s=this;this._readyState="opening",this.skipReconnect=!1;const r=Ke(n,"open",function(){s.onopen(),t&&t()}),i=a=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",a),t?t(a):this.maybeReconnectOnOpen()},o=Ke(n,"error",i);if(this._timeout!==!1){const a=this._timeout,c=this.setTimeoutFn(()=>{r(),i(new Error("timeout")),n.close()},a);this.opts.autoUnref&&c.unref(),this.subs.push(()=>{this.clearTimeoutFn(c)})}return this.subs.push(r),this.subs.push(o),this}connect(t){return this.open(t)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const t=this.engine;this.subs.push(Ke(t,"ping",this.onping.bind(this)),Ke(t,"data",this.ondata.bind(this)),Ke(t,"error",this.onerror.bind(this)),Ke(t,"close",this.onclose.bind(this)),Ke(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(t){try{this.decoder.add(t)}catch(n){this.onclose("parse error",n)}}ondecoded(t){ms(()=>{this.emitReserved("packet",t)},this.setTimeoutFn)}onerror(t){this.emitReserved("error",t)}socket(t,n){let s=this.nsps[t];return s?this._autoConnect&&!s.active&&s.connect():(s=new fc(this,t,n),this.nsps[t]=s),s}_destroy(t){const n=Object.keys(this.nsps);for(const s of n)if(this.nsps[s].active)return;this._close()}_packet(t){const n=this.encoder.encode(t);for(let s=0;s<n.length;s++)this.engine.write(n[s],t.options)}cleanup(){this.subs.forEach(t=>t()),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(t,n){var s;this.cleanup(),(s=this.engine)===null||s===void 0||s.close(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",t,n),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const t=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const n=this.backoff.duration();this._reconnecting=!0;const s=this.setTimeoutFn(()=>{t.skipReconnect||(this.emitReserved("reconnect_attempt",t.backoff.attempts),!t.skipReconnect&&t.open(r=>{r?(t._reconnecting=!1,t.reconnect(),this.emitReserved("reconnect_error",r)):t.onreconnect()}))},n);this.opts.autoUnref&&s.unref(),this.subs.push(()=>{this.clearTimeoutFn(s)})}}onreconnect(){const t=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",t)}}const un={};function Xn(e,t){typeof e=="object"&&(t=e,e=void 0),t=t||{};const n=dS(e,t.path||"/socket.io"),s=n.source,r=n.id,i=n.path,o=un[r]&&i in un[r].nsps,a=t.forceNew||t["force new connection"]||t.multiplex===!1||o;let c;return a?c=new ri(s,t):(un[r]||(un[r]=new ri(s,t)),c=un[r]),n.query&&!t.query&&(t.query=n.queryKey),c.socket(n.path,t)}Object.assign(Xn,{Manager:ri,Socket:fc,io:Xn,connect:Xn});class kS{constructor(t=""){this.baseUrl=t}async get(t){return this.request("GET",t)}async post(t,n){return this.request("POST",t,n)}async del(t){return this.request("DELETE",t)}async request(t,n,s){try{const r=`${this.baseUrl}${n}`,i={method:t,credentials:"same-origin",headers:{"Content-Type":"application/json"}};return s!==void 0&&t!=="GET"&&t!=="DELETE"&&(i.body=JSON.stringify(s)),await(await fetch(r,i)).json()}catch(r){return{success:!1,error:r.message??"Network error"}}}}let ii=null;function ES(e){ii=e}function p0(){if(!ii)throw new Error("Socket instance not initialized. Call setSocketInstance() first.");return ii}class PS{constructor(t){this.socket=t,ES(t)}emit(t,...n){this.socket.emit(t,...n)}on(t,n){this.socket.on(t,n)}off(t,n){this.socket.off(t,n)}disconnect(){this.socket.disconnect()}}class TS{constructor(t){this.modalState=null,this.addToastFn=t??null}showToast(t,n,s="info"){this.addToastFn?this.addToastFn(t,n,s):console.warn("[UIService] No addToast callback registered — toast not shown:",t,n)}showModal(t,n){this.modalState={visible:!0,title:t,content:n}}closeModal(){this.modalState=null}getModalState(){return this.modalState}downloadFile(t,n,s="application/octet-stream"){const r=typeof t=="string"?new Blob([t],{type:s}):t,i=URL.createObjectURL(r),o=document.createElement("a");o.href=i,o.download=n,document.body.appendChild(o),o.click(),document.body.removeChild(o),URL.revokeObjectURL(i)}}class NS{constructor(t){this.prefix=`edu_os_plugin:${t}:`}get(t){return localStorage.getItem(this.prefix+t)}set(t,n){localStorage.setItem(this.prefix+t,n)}delete(t){localStorage.removeItem(this.prefix+t)}clear(){this.prefix.length;const t=[];for(let n=0;n<localStorage.length;n++){const s=localStorage.key(n);s&&s.startsWith(this.prefix)&&t.push(s)}for(const n of t)localStorage.removeItem(n)}}function IS(e){const{session:t,host:n,activeRole:s,activeStudentId:r,selectedLesson:i,activeSegmentId:o,studentViewStatus:a,lang:c,students:u,addToast:d,setOnlineStudentIds:f,setActiveStudentLessons:m,setLessons:h,setActiveSegmentId:g,setLiveClassStudentProgress:x,setLiveClassAcknowledgedMap:v,setLiveClassFeed:w,setSelectedLesson:I,setStudentViewStatus:S,setLocalProgressPercent:P,fetchStudentDashboard:z,fetchStudents:E,fetchElements:L}=e,_=p.useRef(null),M=p.useRef(s),N=p.useRef(r),A=p.useRef(c),R=p.useRef(u),D=p.useRef(d),F=p.useRef(i);return p.useEffect(()=>{M.current=s},[s]),p.useEffect(()=>{N.current=r},[r]),p.useEffect(()=>{A.current=c},[c]),p.useEffect(()=>{R.current=u},[u]),p.useEffect(()=>{D.current=d},[d]),p.useEffect(()=>{F.current=i},[i]),p.useEffect(()=>{if(!t)return;const j=Xn();return _.current=j,n.isInitialized()||n.initialize(new kS,new PS(j),new TS(D.current),new NS("__app__")),M.current==="student"&&N.current&&j.emit("register-student",{studentId:N.current,name:R.current.find(T=>T.id===N.current)?.name||N.current}),j.emit("join-room","whiteboard-broadcast"),j.on("presence-update",T=>{f(T.onlineStudentIds),m(T.activeStudentLessons)}),j.on("lesson-progress-mode-changed",T=>{const{lessonId:$,progressMode:k,progressConditions:B}=T;h(y=>y.map(te=>te.id===$?{...te,progress_mode:k,progress_conditions:B}:te))}),j.on("student-active-segment-changed",T=>{const{activeSegmentId:$}=T;g($)}),j.on("student-pinged",T=>{const $=T.message||(A.current==="zh"?"⚠️ 学习进度预警:老师注意到您的进度有些落后,请抓紧时间跟上!":"⚠️ Progress Alert: The teacher noticed you are falling behind. Please keep up!");d(A.current==="zh"?"⚠️ 学习进度预警":"⚠️ Progress Warning",$,"warning")}),j.on("student-progress-updated",T=>{const{studentId:$,progressPercent:k,completed:B}=T;x(y=>{const te=y.findIndex(ae=>ae.student_id===$);if(te!==-1){const ae=[...y];return ae[te]={...ae[te],progress_percent:k,completed:B?1:0},ae}else return[...y,{student_id:$,progress_percent:k,completed:B?1:0}]})}),j.on("assignment-graded-toast",T=>{if(M.current==="student"&&N.current&&T.studentId===N.current){const $=T.assignmentTitle||T.assignmentId,k=A.current==="zh"?`您的作业"${$}"已完成评分!得分:${T.score}%。建议反馈已收到,快去查看。`:`Your assignment "${$}" was graded. Score: ${T.score}%. Tutoring feedback has been posted.`;d(A.current==="zh"?"🎓 作业已评分":"🎓 Assignment Graded",k,"success"),z(N.current)}}),j.on("student-picked",T=>{if(M.current==="student"&&N.current&&T.studentId===N.current){const $=A.current==="zh"?"闪电警报!您已被老师在课程随机提问点名中抽中!请立即集中注意力参与课堂。":"Attention alert! You have been randomly picked by the teacher! Please pay immediate attention.";d(A.current==="zh"?"⚡️ 随机点名提问":"⚡️ Classroom Pick Alert",$,"warning"),z(N.current)}w($=>[{id:`feed-pick-${T.studentId}-${T.pickedTime||Date.now()}`,time:new Date(T.pickedTime||Date.now()).toLocaleTimeString(),type:"picked",message:A.current==="zh"?`点名互动:随机抽中学生【${T.studentName}】。`:`Classroom Pick: Randomly selected student "${T.studentName}".`},...$])}),j.on("student-acknowledged",T=>{const{studentId:$}=T;v(k=>{const B=new Map(k);return B.set($,!0),B}),w(k=>[{id:`feed-ack-${$}-${Date.now()}`,time:new Date().toLocaleTimeString(),type:"checkin",message:A.current==="zh"?`学生已确认收到提问点名(学生 ID: ${$})。`:`Student acknowledged the classroom call (Student ID: ${$}).`},...k]),E()}),j.on("class-lock-status-changed",T=>{const{lessonId:$,locked:k}=T;M.current==="student"&&N.current?(Promise.resolve(E()).then(()=>{k&&$&&(I($),S("lesson"),d(A.current==="zh"?"🔒 课程已被锁定":"🔒 Lesson Locked",A.current==="zh"?"老师已锁定当前授课,您将无法切换到其他页面。":"The teacher has locked the active lesson. You cannot leave this page.","info"))}),z(N.current)):E()}),j.on("whiteboard-sync",T=>{const{roomId:$,type:k}=T||{};k==="refresh"&&$&&(L($),!F.current&&M.current==="student"&&(I($),S("lesson")),j.emit("join-room",$))}),()=>{j.disconnect(),_.current=null}},[t,s,r]),p.useEffect(()=>{_.current&&s==="student"&&r&&(a==="lesson"&&i?(_.current.emit("enter-lesson",{studentId:r,lessonId:i}),fetch(`/api/students/${r}/progress`).then(j=>j.json()).then(j=>{if(Array.isArray(j)){const T=j.find($=>$.lesson_id===i);P(T?T.progress_percent:0)}}).catch(console.error)):_.current.emit("leave-lesson",{studentId:r}))},[a,i,s,r]),p.useEffect(()=>{s==="teacher"&&i&&o&&_.current&&_.current.emit("teacher-broadcast-segment",{lessonId:i,activeSegmentId:o})},[o,i,s]),{socketRef:_}}const jS=`exports.default = {
136
+ manifest: {
137
+ id: "@my-scope/hello-world",
138
+ name: "Hello World Plugin",
139
+ version: "1.0.0",
140
+ capabilitiesProposed: ["lesson:read"]
141
+ },
142
+ activate: async (ctx) => {
143
+ ctx.log.info('Hello World plugin activated');
144
+ }
145
+ };`;function AS(e){const{host:t,lang:n,addToast:s,setChatLog:r,setTeacherTab:i,fetchLessons:o}=e,[a,c]=p.useState([]),[u,d]=p.useState([]),[f,m]=p.useState(!1),[h,g]=p.useState(null),[x,v]=p.useState(""),[w,I]=p.useState(""),[S,P]=p.useState(""),[z,E]=p.useState(""),[L,_]=p.useState(null),[M,N]=p.useState(!1),[A,R]=p.useState("store"),[D,F]=p.useState(jS),[j,T]=p.useState(!1),[$,k]=p.useState([]),[B,y]=p.useState([]),[te,ae]=p.useState({}),b=p.useRef(new Set),q=p.useCallback(async()=>{try{const G=await fetch("/api/plugins");if(G.ok){const K=await G.json();c(K)}}catch(G){console.warn("Failed to fetch plugins",G)}},[]),ee=p.useCallback(async()=>{try{const G=await fetch("/api/ai-providers");if(G.ok){const K=await G.json();d(K)}}catch(G){console.warn("Failed to fetch AI Providers",G)}},[]);p.useEffect(()=>{q(),ee()},[q,ee]);const se=p.useCallback(async()=>{try{const G=await fetch("/api/events");G.ok&&k(await G.json())}catch{}},[]),fe=p.useCallback(async()=>{try{const G=await fetch("/api/approvals");G.ok&&y(await G.json())}catch{}},[]);return{plugins:a,setPlugins:c,fetchPlugins:q,aiProviders:u,setAiProviders:d,fetchAIProviders:ee,isAIProviderModalOpen:f,setIsAIProviderModalOpen:m,editingAIProvider:h,setEditingAIProvider:g,providerName:x,setProviderName:v,providerApiUrl:w,setProviderApiUrl:I,providerApiKey:S,setProviderApiKey:P,providerModelName:z,setProviderModelName:E,testingProviderId:L,setTestingProviderId:_,showPluginModal:M,setShowPluginModal:N,storeTab:A,setStoreTab:R,pluginCode:D,setPluginCode:F,installingPlugin:j,setInstallingPlugin:T,events:$,setEvents:k,fetchEvents:se,approvals:B,setApprovals:y,fetchApprovals:fe,scoreOverrides:te,setScoreOverrides:ae,handleSaveAIProvider:async()=>{if(!x.trim()||!w.trim()||!z.trim()){s(n==="zh"?"表单不完整":"Incomplete Form",n==="zh"?"请填写提供商名称、API 基础地址与模型标识。":"Please fill in Name, API URL, and Model Name.","warning");return}try{let G;if(h?G=await fetch(`/api/ai-providers/${h.id}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:x,api_url:w,api_key:S,model_name:z})}):G=await fetch("/api/ai-providers",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:x,api_url:w,api_key:S,model_name:z})}),G.ok)s(n==="zh"?"保存成功":"Saved Successfully",n==="zh"?`AI 提供商 [${x}] 已保存。`:`AI Provider [${x}] has been updated.`,"success"),m(!1),g(null),v(""),I(""),P(""),E(""),ee();else{const K=await G.json().catch(()=>({}));s(n==="zh"?"保存失败":"Failed to Save",K.error||(n==="zh"?"无法写入数据库":"Failed to write to database"),"warning")}}catch(G){console.error(G),s(n==="zh"?"保存异常":"Execution Error",G.message||"Error occurred","warning")}},handleDeleteAIProvider:async(G,K)=>{if(confirm(n==="zh"?`确定要删除 AI 提供商 [${K}] 吗?此操作无法撤销。`:`Are you sure you want to delete AI Provider [${K}]?`))try{(await fetch(`/api/ai-providers/${G}`,{method:"DELETE"})).ok?(s(n==="zh"?"删除成功":"Deleted Successfully",n==="zh"?`AI 提供商 [${K}] 已经被清除。`:`AI Provider [${K}] has been removed.`,"success"),ee()):s(n==="zh"?"删除失败":"Failed to Delete","Database error","warning")}catch(re){console.error(re),s(n==="zh"?"操作异常":"Execution Error",re.message||"Error occurred","warning")}},handleTestAIProvider:async G=>{_(G.id);try{const K=await fetch("/api/ai-providers/test",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({api_url:G.api_url,api_key:G.api_key,model_name:G.model_name})}),re=await K.json();K.ok&&re.success?s(n==="zh"?"测试通过":"Test Succeeded",n==="zh"?`成功连接至 [${G.name}]。${re.message}`:`Successfully connected to [${G.name}]. ${re.message}`,"success"):s(n==="zh"?"测试失败":"Test Failed",re.error||"Connection error","warning")}catch(K){console.error(K),s(n==="zh"?"连接异常":"Connection Exception",K.message||"Error occurred","warning")}finally{_(null)}},handleInstallPlugin:async()=>{if(D.trim()){T(!0);try{const K=await(await fetch("/api/plugins",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sourceCode:D})})).json();K.success?(await q(),N(!1),r(re=>[...re,{role:"agent",content:`[System] Plugin "${K.manifest.name}" installed successfully. You can now prompt me to use it.`}])):alert("Plugin installation failed: "+K.error)}catch(G){alert("Error: "+G.message)}finally{T(!1)}}},handleZipPluginUpload:async(G,K,re)=>{T(!0);const we=re?.mode==="update";try{const qe={"Content-Type":"application/octet-stream","X-Filename":encodeURIComponent(G.name),"X-Execution-Mode":K,"X-Install-Mode":we?"update":"install","X-Allow-Downgrade":re?.allowDowngrade?"true":"false"};re?.targetPluginId&&(qe["X-Target-Plugin-Id"]=encodeURIComponent(re.targetPluginId));const de=we&&re?.targetPluginId?`/api/plugins/${encodeURIComponent(re.targetPluginId)}/update-zip-raw`:"/api/plugins/upload-zip-raw",Te=await fetch(de,{method:"POST",headers:qe,body:G}),ke=await Te.json().catch(()=>({}));if(!Te.ok||!ke.success){const Q=ke.error||"Unknown error";throw s(n==="zh"?we?"更新失败":"安装失败":we?"Update Failed":"Installation Failed",Q,"error"),new Error(Q)}const Ze=ke.pluginId||ke.manifest?.pluginId||ke.manifest?.id,O=!!(ke.updated||we);if(!O&&Ze)await fetch(`/api/plugins/${encodeURIComponent(Ze)}/toggle`,{method:"POST"}).catch(()=>{});else if(O&&ke.wasActive&&Ze)try{await t.deactivatePlugin(Ze)}catch{}i("plugins"),R("store"),await q(),setTimeout(()=>{q()},1e3);const W=ke.manifest?.name||Ze||G.name;if(O){const Q=ke.oldVersion||"?",Z=ke.newVersion||ke.manifest?.version||"?";s(n==="zh"?"插件更新成功":"Plugin Updated",n==="zh"?`"${W}" 已从 v${Q} 更新到 v${Z}(配置与数据已保留)`:`"${W}" updated v${Q} → v${Z} (config & data preserved)`,"success"),r(ie=>[...ie,{role:"agent",content:`[System] Plugin "${W}" updated ${Q} → ${Z}.`}])}else s(n==="zh"?"插件安装成功":"Plugin Installed",n==="zh"?`三方插件 "${W}" 已成功上传并以 [${K==="worker"?"Worker 隔离":"VM 嵌入"}] 模式激活运行!`:`Plugin "${W}" installed and activated in [${K}] mode!`,"success"),r(Q=>[...Q,{role:"agent",content:`[System] Plugin "${W}" installed successfully from ZIP file.`}])}catch(qe){const de=qe?.message?String(qe.message):"";throw de&&de!=="Failed to fetch"&&de!=="Network error"||s(n==="zh"?"网络错误":"Network Error",de||"Network error","error"),qe}finally{T(!1)}},handleTogglePlugin:async G=>{if(!b.current.has(G)){b.current.add(G);try{const K=await fetch(`/api/plugins/${encodeURIComponent(G)}/toggle`,{method:"POST"}),re=await K.json().catch(()=>({}));if(K.ok)await q();else{const we=re.error||"Unknown error";we.includes("requires human approval")||we.includes("queued")?(alert(n==="zh"?'该操作已加入"待审批高危操作"列表,请在右侧侧边栏中通过审批以生效。':"This action has been queued. Please approve it in the Pending Approvals list on the right side."),await fe()):alert((n==="zh"?"切换插件状态失败: ":"Failed to toggle plugin: ")+we)}}catch(K){console.error("Failed to toggle plugin:",K),alert(n==="zh"?"网络错误,切换插件失败":"Network error, failed to toggle plugin")}finally{b.current.delete(G)}}},handleDeletePlugin:async G=>{if(window.confirm(n==="zh"?"确定要彻底删除该插件吗?删除后此插件相关的功能将无法使用。":"Are you sure you want to completely delete this plugin? This cannot be undone."))try{const K=await fetch(`/api/plugins/${encodeURIComponent(G)}`,{method:"DELETE"});if(K.ok)i("plugins"),R("store"),await q(),r(re=>[...re,{role:"agent",content:"[System] Plugin uninstalled and deleted."}]);else{const re=await K.json().catch(()=>({}));alert(re.error||(n==="zh"?"删除插件失败":"Failed to delete plugin"))}}catch(K){console.error("Failed to delete plugin:",K),alert(n==="zh"?"删除插件失败":"Failed to delete plugin")}},handleApprove:async(G,K)=>{try{const we=await(await fetch(`/api/approvals/${G}/approve`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({payloadOverride:K})})).json();we.success?(await fe(),await o(),await q()):alert("Action failed: "+we.error)}catch(re){console.error(re)}},handleReject:async G=>{try{await fetch(`/api/approvals/${G}/reject`,{method:"POST"}),await fe(),await q()}catch(K){console.error(K)}}}}function zS(e){const{lang:t,addToast:n,fetchLessons:s,setSelectedLesson:r,setTeacherTab:i}=e,[o,a]=p.useState(!1),[c,u]=p.useState(1),[d,f]=p.useState(""),[m,h]=p.useState("Mathematics"),[g,x]=p.useState(""),[v,w]=p.useState(""),[I,S]=p.useState([{id:"seg-w1",title:"Course Orientation / 课堂导入",type:"intro",duration:"5m",color:"bg-blue-50 text-blue-700 border-blue-200 hover:bg-blue-100",notes:"Introduce basic goals"},{id:"seg-w2",title:"Subject Core Lecture / 核心精讲",type:"lecture",duration:"20m",color:"bg-indigo-50 text-indigo-700 border-indigo-200 hover:bg-indigo-100",notes:"Present major content frameworks"},{id:"seg-w3",title:"Interactive Lab Work / 实践演练",type:"practice",duration:"15m",color:"bg-green-50 text-green-700 border-green-200 hover:bg-green-100",notes:"Provide collaborative assignments on terminal or board"},{id:"seg-w4",title:"Wrap up / 随堂总结与答疑",type:"summary",duration:"5m",color:"bg-purple-50 text-purple-700 border-purple-200 hover:bg-purple-100",notes:"Reflect and assign task"}]),[P,z]=p.useState(!1);return{isCourseWizardOpen:o,setIsCourseWizardOpen:a,wizardStep:c,setWizardStep:u,wizardCourseTitle:d,setWizardCourseTitle:f,wizardCourseCategory:m,setWizardCourseCategory:h,wizardCourseDescription:g,setWizardCourseDescription:x,wizardCourseContent:v,setWizardCourseContent:w,wizardCourseTimeline:I,setWizardCourseTimeline:S,wizardIsSubmitting:P,setWizardIsSubmitting:z,handleDeployWizardCourse:async()=>{if(!d.trim()){alert(t==="zh"?"请输入课程标题!":"Please provide a course title!");return}z(!0);try{const L=v.trim()||`Course outline for ${d} (${m})`,_=await fetch("/api/lessons",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({title:d,content:L})});if(_.ok){const N=(await _.json()).result?.lessonId;N&&await fetch(`/api/lessons/${N}/timeline`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({timeline:I})}),await s(),N&&(r(N),i("lesson_editor")),n(t==="zh"?"⭐ 课程发布成功":"⭐ Course Deployed Successfully",t==="zh"?`课程《${d}》已成功保存到核心SQLite并已自动激活!`:`Course "${d}" is now live in SQLite and auto-activated.`,"success"),a(!1),f(""),h("Mathematics"),x(""),w(""),u(1)}else n("Error","SQLite save failed","warning")}catch(L){console.error(L),n("Error","Launch Exception","warning")}finally{z(!1)}}}}function LS(){const[e,t]=p.useState(!1),[n,s]=p.useState(null),[r,i]=p.useState("scan_lesson"),[o,a]=p.useState(""),[c,u]=p.useState(""),[d,f]=p.useState(!1),[m,h]=p.useState([]),[g,x]=p.useState([]),[v,w]=p.useState(!1),[I,S]=p.useState({}),[P,z]=p.useState(10),[E,L]=p.useState("quiz"),_=p.useRef(I);return p.useEffect(()=>{_.current=I},[I]),{isQuizGeneratorOpen:e,setIsQuizGeneratorOpen:t,quizGeneratorClassId:n,setQuizGeneratorClassId:s,quizGenMode:r,setQuizGenMode:i,quizGenSelectedLessonId:o,setQuizGenSelectedLessonId:a,quizGenTopic:c,setQuizGenTopic:u,isGeneratingSuggestions:d,setIsGeneratingSuggestions:f,suggestedObjectives:m,setSuggestedObjectives:h,suggestedQuestions:g,setSuggestedQuestions:x,savingQuiz:v,setSavingQuiz:w,quizStudentAnswers:I,setQuizStudentAnswers:S,quizGenTimeLimit:P,setQuizGenTimeLimit:z,quizStudentAnswersRef:_,subAssignmentTab:E,setSubAssignmentTab:L}}function _S(e){const{lang:t,classes:n,expandedClassId:s,fetchClasses:r,fetchClassStudents:i,handleExportAllClassesCombined:o}=e,[a,c]=p.useState(!1),[u,d]=p.useState(new Set),[f,m]=p.useState(new Set),[h,g]=p.useState(null),[x,v]=p.useState(""),[w,I]=p.useState(""),[S,P]=p.useState("");return{batchMode:a,setBatchMode:c,selectedClassIds:u,setSelectedClassIds:d,selectedStudentIds:f,setSelectedStudentIds:m,batchPicker:h,setBatchPicker:g,batchPickerLesson:x,setBatchPickerLesson:v,batchPickerDate:w,setBatchPickerDate:I,batchPickerTargetClass:S,setBatchPickerTargetClass:P,toggleClassSelection:k=>{d(B=>{const y=new Set(B);return y.has(k)?y.delete(k):y.add(k),y})},toggleSelectAllClasses:()=>{d(k=>k.size===n.length&&n.length>0?new Set:new Set(n.map(B=>B.id)))},toggleStudentSelection:k=>{m(B=>{const y=new Set(B);return y.has(k)?y.delete(k):y.add(k),y})},toggleSelectAllStudents:k=>{m(B=>B.size===k.length&&k.length>0?new Set:new Set(k.map(y=>y.id)))},handleBatchDeleteClasses:async()=>{if(u.size!==0&&confirm(t==="zh"?`确认彻底删除选中的 ${u.size} 个班级吗?该操作不可恢复。`:`Delete ${u.size} selected classes permanently?`)){for(const k of u)await fetch(`/api/classes/${k}`,{method:"DELETE"});d(new Set),await r()}},handleBatchExportClasses:async()=>{u.size!==0&&await o(n.filter(k=>u.has(k.id)))},handleBatchSetPasscode:async()=>{if(u.size===0)return;const k=window.prompt(t==="zh"?"请输入临时班级密码(留空则清除):":"Enter temporary passcode (leave empty to clear):");if(k!==null){for(const B of u)await fetch(`/api/classes/${B}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({class_passcode:k===""?null:k})});d(new Set),await r()}},handleBatchScheduleClasses:()=>{u.size!==0&&(v(""),I(new Date().toISOString().split("T")[0]),g("schedule"))},handleBatchDeleteStudents:async()=>{if(!(f.size===0||!s)&&confirm(t==="zh"?`确认彻底删除选中的 ${f.size} 名学生账号吗?将删除其全部关联数据,不可恢复。`:`Permanently delete ${f.size} selected student accounts?`)){for(const k of f)await fetch(`/api/students/${k}`,{method:"DELETE"});m(new Set),await i(s)}},handleBatchResetPassword:async()=>{if(f.size===0||!s)return;const k=window.prompt(t==="zh"?"请输入要为选中学生设置的新密码:":"Enter new password for selected students:");if(!(k===null||k.trim()==="")){for(const B of f)await fetch(`/api/students/${B}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:k})});m(new Set),await i(s)}},handleBatchTransferStudents:()=>{f.size===0||!s||(P(""),g("transfer"))},handleBatchSetLockedLesson:()=>{f.size===0||!s||(v(""),g("lockedLesson"))},confirmBatchPicker:async()=>{if(s){if(h==="schedule"){if(!x){alert(t==="zh"?"请选择课程":"Please select a lesson");return}for(const k of u)await fetch(`/api/classes/${k}/schedules`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({lessonId:x,scheduledDate:w+" 09:00:00",status:"scheduled"})});d(new Set)}else if(h==="lockedLesson"){if(!x){alert(t==="zh"?"请选择课程":"Please select a lesson");return}for(const k of f)await fetch(`/api/students/${k}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({locked_lesson_id:x})});m(new Set)}else if(h==="transfer"){if(!S||S===s){alert(t==="zh"?"请选择不同的目标班级":"Please select a different target class");return}for(const k of f)await fetch(`/api/classes/${s}/students/${k}`,{method:"DELETE"}),await fetch(`/api/classes/${S}/students`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({studentId:k})});m(new Set)}g(null),s&&await i(s)}}}}function RS(){const[e,t]=p.useState([]),[n,s]=p.useState(!1),[r,i]=p.useState({lab_id:null,seats:[]}),[o,a]=p.useState(!1),[c,u]=p.useState([]),[d,f]=p.useState({}),[m,h]=p.useState({}),[g,x]=p.useState(null),[v,w]=p.useState(""),[I,S]=p.useState(""),P=p.useCallback(async()=>{try{s(!0);const M=await fetch("/api/labs");M.ok&&t(await M.json())}catch(M){console.error(M)}finally{s(!1)}},[]),z=p.useCallback(async M=>{try{const N=await fetch(`/api/classes/${M}/seats`);if(N.ok){const A=await N.json();i(A)}}catch(N){console.error(N)}},[]),E=p.useCallback(async()=>{try{const M=new Date().toISOString().split("T")[0],N=await fetch(`/api/schedules/today?date=${M}`);if(N.ok){const A=await N.json();A.success&&A.schedules&&u(A.schedules)}}catch(M){console.warn("Failed to fetch today schedules",M)}},[]),L=p.useCallback(async M=>{try{const N=await fetch(`/api/classes/${M}/schedules`);if(N.ok){const A=await N.json();f(R=>({...R,[M]:A}))}}catch{}},[]),_=p.useCallback(async M=>{try{const N=await fetch(`/api/schedules/${M}/attendance`);if(N.ok){const A=await N.json();h(R=>({...R,[M]:A}))}}catch{}},[]);return{computerLabs:e,setComputerLabs:t,loadingLabs:n,setLoadingLabs:s,fetchLabs:P,classSeats:r,setClassSeats:i,savingSeats:o,setSavingSeats:a,fetchClassSeats:z,todaySchedules:c,setTodaySchedules:u,fetchTodaySchedules:E,classSchedulesMap:d,setClassSchedulesMap:f,fetchClassSchedules:L,scheduleAttendanceMap:m,setScheduleAttendanceMap:h,fetchScheduleAttendance:_,expandedScheduleId:g,setExpandedScheduleId:x,newScheduleDate:v,setNewScheduleDate:w,newScheduleLessonId:I,setNewScheduleLessonId:S}}function OS(e){const{selectedLesson:t,lessons:n,setLessons:s}=e,[r,i]=p.useState([]),[o,a]=p.useState("seg-1"),[c,u]=p.useState(null),[d,f]=p.useState(null),[m,h]=p.useState("none"),[g,x]=p.useState(null),[v,w]=p.useState(!0),I=p.useRef(null),S=async(P,z)=>{h("saving");try{(await fetch(`/api/lessons/${P}/timeline`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({timeline:z})})).ok?(s(L=>L.map(_=>_.id===P?{..._,timeline:JSON.stringify(z)}:_)),i(z),h("saved"),x(new Date)):h("error")}catch(E){console.error("Failed to save timeline:",E),h("error")}};return p.useEffect(()=>{if(t){const P=n.find(z=>z.id===t);if(P){let z=[];if(P.timeline)try{z=typeof P.timeline=="string"?JSON.parse(P.timeline):P.timeline}catch{z=[{id:"seg-1",title:"开场准备",type:"intro",duration:"5m",color:"bg-blue-50 text-blue-700 border-blue-200 hover:bg-blue-100"},{id:"seg-2",title:"讲授新课",type:"lecture",duration:"20m",color:"bg-indigo-50 text-indigo-700 border-indigo-200 hover:bg-indigo-100"},{id:"seg-3",title:"互动练习",type:"practice",duration:"15m",color:"bg-green-50 text-green-700 border-green-200 hover:bg-green-100"},{id:"seg-4",title:"课堂总结",type:"summary",duration:"5m",color:"bg-purple-50 text-purple-700 border-purple-200 hover:bg-purple-100"}]}else z=[{id:"seg-1",title:"开场准备",type:"intro",duration:"5m",color:"bg-blue-50 text-blue-700 border-blue-200 hover:bg-blue-100"},{id:"seg-2",title:"讲授新课",type:"lecture",duration:"20m",color:"bg-indigo-50 text-indigo-700 border-indigo-200 hover:bg-indigo-100"},{id:"seg-3",title:"互动练习",type:"practice",duration:"15m",color:"bg-green-50 text-green-700 border-green-200 hover:bg-green-100"},{id:"seg-4",title:"课堂总结",type:"summary",duration:"5m",color:"bg-purple-50 text-purple-700 border-purple-200 hover:bg-purple-100"}];i(z);const E=I.current!==t;I.current=t,z.length>0?(E||!z.some(L=>L.id===o))&&a(z[0].id):a(null)}}},[t,n]),{timelineSegments:r,setTimelineSegments:i,activeSegmentId:o,setActiveSegmentId:a,segmentToEdit:c,setSegmentToEdit:u,draggedSegmentIdx:d,setDraggedSegmentIdx:f,editorSaveStatus:m,setEditorSaveStatus:h,editorLastSavedTime:g,setEditorLastSavedTime:x,editorPanelsExpanded:v,setEditorPanelsExpanded:w,saveTimeline:S}}function MS(e,t,n){const[s,r]=p.useState(new Set),[i,o]=p.useState(null),[a,c]=p.useState(!1),u=p.useMemo(()=>{if(e!=="student"||!t)return[];const f=[],m=t.assignments||[];for(const g of m)if(!g.submission_status)f.push({id:`new-${g.id}`,type:"new_assignment",title:n==="zh"?"新发布作业":"New Assignment",message:n==="zh"?`您有一项新作业:"${g.title}"`:`You have a new assignment: ${g.title}`,date:g.created_at,relatedId:g.id});else if(g.submission_status==="graded"){const x=!!g.feedback;f.push({id:`graded-${g.id}`,type:"graded",title:x?n==="zh"?"收到新成绩与反馈":"Grade & Feedback Posted":n==="zh"?"新成绩发布":"Assignment Graded",message:x?n==="zh"?`您的作业"${g.title}"已评分,得分:${g.score}%。反馈:"${g.feedback}"`:`Your assignment "${g.title}" was graded. Score: ${g.score}%. Teacher feedback: "${g.feedback}"`:n==="zh"?`您的作业"${g.title}"已评分,得分:${g.score}%`:`Your assignment "${g.title}" was graded. Score: ${g.score}%`,date:g.submitted_at||g.created_at,relatedId:g.id})}const h=t.rollcalls||[];for(const g of h)f.push({id:g.id,type:"rollcall_picked",title:n==="zh"?"⚡️ 随机提问选中通知":"⚡️ Random Pick Notification",message:n==="zh"?`您已被老师在课程"${g.lesson_title||"课堂"}"中随机选中提问!请立即确认您的出勤与注意。`:`You have been randomly picked by the teacher in lesson "${g.lesson_title||"Class"}"! Please pay immediate attention.`,date:g.picked_time,relatedId:g.lesson_id});return f.sort((g,x)=>x.date-g.date)},[e,t,n]),d=p.useMemo(()=>u.filter(f=>!s.has(f.id)),[u,s]);return{studentNotifications:u,unreadNotifications:d,readNotifications:s,setReadNotifications:r,selectedNotificationForModal:i,setSelectedNotificationForModal:o,isNotificationsOpen:a,setIsNotificationsOpen:c}}function pc(e){if(e==null)return"";const t=String(e);return t.includes(",")||t.includes('"')||t.includes(`
146
+ `)?`"${t.replace(/"/g,'""')}"`:t}async function DS(e){const{classId:t,className:n,students:s,dashData:r,lang:i,addToast:o,setIsGeneratingPDFReport:a}=e;a(c=>({...c,[t]:!0}));try{if(!r){o(i==="zh"?"暂无班级评分数据":"No Class Performance Data",i==="zh"?"请确保在此班级加载了作业与测验。":"Please check if assignments or quizzes are present for this class.","warning");return}const c=r.performance||[],u=r.assignments||[],d={};s.forEach(T=>{d[T.id]={id:T.id,name:T.name,totalGradesSum:0,gradedCount:0,submittedCount:0,totalCount:0}}),c.forEach(T=>{const $=T.student_id;d[$]&&(d[$].totalCount++,(T.submission_status==="submitted"||T.submission_status==="graded")&&d[$].submittedCount++,T.score!==null&&T.score!==void 0&&(d[$].totalGradesSum+=T.score,d[$].gradedCount++))});const f=Object.values(d).map(T=>{const $=T.gradedCount>0?T.totalGradesSum/T.gradedCount:0,k=T.totalCount>0?T.submittedCount/T.totalCount*100:0;return{...T,avgScore:$,submissionRate:k}});f.sort((T,$)=>$.avgScore-T.avgScore);let m=0,h=0,g=0,x=0;c.forEach(T=>{x++,(T.submission_status==="submitted"||T.submission_status==="graded")&&g++,T.score!==null&&T.score!==void 0&&(m+=T.score,h++)});const v=h>0?m/h:0,w=x>0?g/x*100:0,I={};u.forEach(T=>{I[T.id]={id:T.id,title:T.title,scores:[],submittedCount:0,totalCount:0}}),c.forEach(T=>{const $=T.assignment_id;I[$]&&(I[$].totalCount++,(T.submission_status==="submitted"||T.submission_status==="graded")&&I[$].submittedCount++,T.score!==null&&T.score!==void 0&&I[$].scores.push(T.score))});const S=Object.values(I).map(T=>{const $=T.scores.length,k=T.scores.reduce((b,q)=>b+q,0),B=$>0?k/$:0,y=$>0?Math.max(...T.scores):0,te=$>0?Math.min(...T.scores):0,ae=T.totalCount>0?T.submittedCount/T.totalCount*100:0;return{...T,avg:B,max:y,min:te,subRate:ae}}),P=new af({orientation:"p",unit:"mm",format:"a4"}),z=[15,23,42],E=[79,70,229],L=[51,65,85],_=[226,232,240],M=T=>{P.setDrawColor(_[0],_[1],_[2]),P.setLineWidth(.3),P.line(14,T,196,T)};P.setFillColor(z[0],z[1],z[2]),P.rect(0,0,210,42,"F"),P.setTextColor(255,255,255),P.setFont("helvetica","bold"),P.setFontSize(20),P.text("CLASS PERFORMANCE REPORT",14,18),P.setFont("helvetica","normal"),P.setFontSize(10),P.setTextColor(194,205,225),P.text("Academic Insights • Generative Report Summary",14,25),P.text(`Classroom: ${n} | Date: ${new Date().toLocaleDateString()} ${new Date().toLocaleTimeString()}`,14,32),P.setFillColor(E[0],E[1],E[2]),P.rect(172,10,24,24,"F"),P.setFont("helvetica","bold"),P.setFontSize(14),P.setTextColor(255,255,255),P.text("OS",180,26);let N=52;P.setTextColor(z[0],z[1],z[2]),P.setFont("helvetica","bold"),P.setFontSize(12),P.text("I. EXECUTIVE OVERVIEW",14,N),N+=6;const A=[["Classroom/Subject Name",n],["Total Enrolled Students",`${s.length} student(s)`],["Curriculum Items (Assignments/Quizzes)",`${u.length} items`],["Global Assignment Submission Rate",`${w.toFixed(1)}%`],["Class Average Performance Score",`${v.toFixed(1)}%`]];P.autoTable({startY:N,head:[["Metric Indicator","Class-wide Metric Value"]],body:A,theme:"striped",headStyles:{fillColor:z,textColor:[255,255,255],fontStyle:"bold",fontSize:9},bodyStyles:{textColor:L,fontSize:8.5},margin:{left:14,right:14}}),N=P.lastAutoTable.finalY+12,P.setTextColor(z[0],z[1],z[2]),P.setFont("helvetica","bold"),P.setFontSize(12),P.text("II. STUDENT RANKING DISTRIBUTION",14,N),N+=6;const R=f.map((T,$)=>{let k="Excellent";return T.avgScore>=90?k="Excellent (A)":T.avgScore>=75?k="Good (B)":T.avgScore>=60?k="Satisfactory (C)":k="Needs Improvement (D)",[`${$+1}`,T.name,`${T.submittedCount}/${T.totalCount} (${T.submissionRate.toFixed(0)}%)`,`${T.avgScore.toFixed(1)}%`,k]});P.autoTable({startY:N,head:[["Rank","Student Name","Completion Rate","Average Score","Academic Standing Tier"]],body:R,theme:"grid",headStyles:{fillColor:E,textColor:[255,255,255],fontStyle:"bold",fontSize:8.5},bodyStyles:{textColor:L,fontSize:8},alternateRowStyles:{fillColor:[248,250,252]},columnStyles:{0:{cellWidth:15,halign:"center",fontStyle:"bold"},1:{fontStyle:"bold"},2:{halign:"center"},3:{halign:"center",fontStyle:"bold"}},margin:{left:14,right:14}}),N=P.lastAutoTable.finalY+12,N>210&&(P.addPage(),N=20),P.setTextColor(z[0],z[1],z[2]),P.setFont("helvetica","bold"),P.setFontSize(12),P.text("III. ASSIGNMENT PERFORMANCE METRICS",14,N),N+=6;const D=S.map(T=>[T.title,`${T.subRate.toFixed(0)}%`,`${T.avg.toFixed(1)}%`,`${T.min.toFixed(0)}% - ${T.max.toFixed(0)}%`]);P.autoTable({startY:N,head:[["Assignment/Quiz Title","Submission Rate","Average Grade","Range (Min - Max)"]],body:D.length>0?D:[["No assignment performance records found.","-","-","-"]],theme:"striped",headStyles:{fillColor:[100,116,139],textColor:[255,255,255],fontStyle:"bold",fontSize:8.5},bodyStyles:{textColor:L,fontSize:8},columnStyles:{1:{halign:"center"},2:{halign:"center",fontStyle:"bold"},3:{halign:"center"}},margin:{left:14,right:14}}),N=P.lastAutoTable.finalY+15,M(275),P.setFontSize(8),P.setTextColor(148,163,184),P.text("Generated by OpenLearn Next • Educational Operating System",14,282),P.text("Page 1 of 1 • Internal Educational Audit",196,282,{align:"right"});const F=n.replace(/[^a-z0-9]/gi,"_").toLowerCase(),j=new Date().toISOString().split("T")[0];P.save(`Class_Report_${F}_${j}.pdf`),o(i==="zh"?"📄 PDF 报告导出完成":"📄 PDF Report Generated",i==="zh"?`班级【${n}】的综合学情 PDF 报告已生成并下载。`:`Class performance report for ${n} saved to your device.`,"success")}catch(c){console.error("PDF Generation Failed:",c),o(i==="zh"?"❌ PDF 报告生成失败":"❌ PDF Report Failed",c.message||"Error occurred during PDF generation","warning")}finally{a(c=>({...c,[t]:!1}))}}function FS(e){const{className:t,students:n,dashData:s,qWeight:r=40,aWeight:i=60,overrides:o={}}=e;if(!s||!s.assignments){alert("No performance data available to export. Please open the dashboard to load class data first.");return}if(n.length===0){alert("No students in this class to export grades for.");return}const a=s.assignments||[],c=s.performance||[],u=a.map(S=>{let P="assignment";if(o[S.id])P=o[S.id];else{const z=S.content&&S.content.startsWith('{"quizType":"mcq_learning_objectives"'),E=S.title&&(S.title.toLowerCase().includes("quiz")||S.title.toLowerCase().includes("test")||S.title.includes("测验")||S.title.includes("测试"));P=z||E?"quiz":"assignment"}return{...S,category:P}}),d=["Student Name","Student Email"];u.forEach(S=>{const P=S.category==="quiz"?"Quiz":"Assignment";d.push(`${P}: ${S.title}`)}),d.push("Quizzes Average","Assignments Average",`Weighted Average (${r}% Quizzes, ${i}% Assignments)`,"Simple Average Score","Submitted Count","Total Items");const f=[d];n.forEach(S=>{const P=[S.name,S.email];let z=0,E=0,L=0,_=0,M=0,N=0,A=0;u.forEach(k=>{const B=c.find(y=>y.assignment_id===k.id&&y.student_id===S.id);if(B&&B.score!==null&&B.score!==void 0){P.push(`${B.score}%`);const y=Number(B.score);k.category==="quiz"?(z+=y,E++):(L+=y,_++),M+=y,N++,A++}else B&&B.submission_status==="submitted"?(P.push("Pending Grade"),A++):P.push("Not Submitted")});const R=E>0?Math.round(z/E):null,D=_>0?Math.round(L/_):null;let F="N/A";if(R!==null&&D!==null){const k=R*(r/100)+D*(i/100);F=`${Math.round(k)}%`}else R!==null?F=`${R}%`:D!==null&&(F=`${D}%`);const j=R!==null?`${R}%`:"N/A",T=D!==null?`${D}%`:"N/A",$=N>0?`${Math.round(M/N)}%`:"N/A";P.push(j,T,F,$,`${A}`,`${a.length}`),f.push(P.map(pc))});const m=f.map(S=>S.join(",")).join(`
147
+ `),h=new Blob(["\uFEFF"+m],{type:"text/csv;charset=utf-8;"}),g=URL.createObjectURL(h),x=document.createElement("a"),v=t.replace(/[^a-z0-9]/gi,"_").toLowerCase(),w=new Date().toISOString().split("T")[0],I=`${v}_grades_report_${w}.csv`;x.setAttribute("href",g),x.setAttribute("download",I),x.style.visibility="hidden",document.body.appendChild(x),x.click(),document.body.removeChild(x),URL.revokeObjectURL(g)}function BS(e){const{exportClassId:t,classStudentsMap:n,classDashboardMap:s,quizzesWeight:r,assignmentsWeight:i,customCategoryOverrides:o,lang:a}=e;if(!t)return null;const c=n[t]||[],u=s[t];if(!u||!u.assignments||c.length===0)return null;const d=u.assignments||[],f=u.performance||[],m=d.map(v=>{let w="assignment";if(o[v.id])w=o[v.id];else{const I=v.content&&v.content.startsWith('{"quizType":"mcq_learning_objectives"'),S=v.title&&(v.title.toLowerCase().includes("quiz")||v.title.toLowerCase().includes("test")||v.title.includes("测验")||v.title.includes("测试"));w=I||S?"quiz":"assignment"}return{...v,category:w}}),h=["Student Name","Student Email"];m.forEach(v=>{const w=v.category==="quiz"?"Quiz":"Assignment";h.push(`${w}: ${v.title}`)}),h.push("Quizzes Average","Assignments Average",`Weighted Average (${r}% Quizzes, ${i}% Assignments)`,"Simple Average Score","Submitted Count","Total Items");const g=[];return c.slice(0,5).forEach(v=>{const w=[v.name,v.email];let I=0,S=0,P=0,z=0,E=0,L=0,_=0;m.forEach(j=>{const T=f.find($=>$.assignment_id===j.id&&$.student_id===v.id);if(T&&T.score!==null&&T.score!==void 0){w.push(`${T.score}%`);const $=Number(T.score);j.category==="quiz"?(I+=$,S++):(P+=$,z++),E+=$,L++,_++}else T&&T.submission_status==="submitted"?(w.push(a==="zh"?"待评分":"Pending Grade"),_++):w.push(a==="zh"?"未提交":"Not Submitted")});const M=S>0?Math.round(I/S):null,N=z>0?Math.round(P/z):null;let A="N/A";if(M!==null&&N!==null){const j=M*(r/100)+N*(i/100);A=`${Math.round(j)}%`}else M!==null?A=`${M}%`:N!==null&&(A=`${N}%`);const R=M!==null?`${M}%`:"N/A",D=N!==null?`${N}%`:"N/A",F=L>0?`${Math.round(E/L)}%`:"N/A";w.push(R,D,A,F,`${_}`,`${d.length}`),g.push(w)}),{headers:h,rows:g,totalStudents:c.length}}function $S(e){const{classes:t,classStudentsMap:n,classDashboardMap:s,lang:r}=e,o=[["Class Name","Student Name","Student Email","Quizzes Average","Assignments Average","Calculated Weighted Score (40% Quiz / 60% Assignment)","Simple Average Score","Submitted Count","Total Items"]];if(t.forEach(d=>{const f=n[d.id]||[],m=s[d.id];if(!m||!m.assignments||f.length===0)return;const h=m.assignments||[],g=h.map(x=>{const v=x.content&&x.content.startsWith('{"quizType":"mcq_learning_objectives"'),w=x.title&&(x.title.toLowerCase().includes("quiz")||x.title.toLowerCase().includes("test")||x.title.includes("测验")||x.title.includes("测试"));return{...x,category:v||w?"quiz":"assignment"}});f.forEach(x=>{let v=0,w=0,I=0,S=0,P=0,z=0;g.forEach(A=>{const R=m.performance?.find(D=>D.student_id===x.id&&D.assignment_id===A.id&&D.submission_status==="graded"&&D.score!==null);if(R){const D=Number(R.score);P+=D,z++,A.category==="quiz"?(v+=D,w++):(I+=D,S++)}});const E=w>0?Math.round(v/w):null,L=S>0?Math.round(I/S):null;let _=0;E!==null&&L!==null?_=Math.round(E*.4+L*.6):E!==null?_=Math.round(E):L!==null&&(_=Math.round(L));const M=z>0?Math.round(P/z):0,N=[d.name,x.name,x.email,E!==null?`${E}%`:"N/A",L!==null?`${L}%`:"N/A",`${_}%`,`${M}%`,`${z}`,`${h.length}`];o.push(N)})}),o.length<=1){alert(r==="zh"?"暂无可导出的成绩数据。请确保班级中有已评分的作业。":"No graded performance data available to export.");return}const a="data:text/csv;charset=utf-8,\uFEFF"+o.map(d=>d.map(pc).join(",")).join(`
148
+ `),c=encodeURI(a),u=document.createElement("a");u.setAttribute("href",c),u.setAttribute("download",`All_Classes_Combined_Grades_${new Date().toISOString().slice(0,10)}.csv`),document.body.appendChild(u),u.click(),document.body.removeChild(u)}function VS(e){const{lang:t,classes:n,classStudentsMap:s,classDashboardMap:r,fetchClassStudents:i,fetchClassDashboard:o,fetchClassProgress:a,addToast:c=()=>{}}=e,[u,d]=p.useState(!1),[f,m]=p.useState(""),[h,g]=p.useState(""),[x,v]=p.useState(40),[w,I]=p.useState(60),[S,P]=p.useState({}),[z,E]=p.useState(!1),[L,_]=p.useState(!1),[M,N]=p.useState(null),[A,R]=p.useState(!1),[D,F]=p.useState({}),j=p.useCallback(b=>{const q=Math.min(100,Math.max(0,b));v(q),I(100-q)},[]),T=p.useCallback(b=>{const q=Math.min(100,Math.max(0,b));I(q),v(100-q)},[]),$=p.useMemo(()=>BS({exportClassId:f,classStudentsMap:s,classDashboardMap:r,quizzesWeight:x,assignmentsWeight:w,customCategoryOverrides:S,lang:t}),[f,x,w,S,s,r,t]),k=p.useCallback(async(b,q)=>{N(b);try{await i(b),await o(b),await a(b),m(b),g(q),v(40),I(60),P({}),d(!0)}catch(ee){console.error(ee)}finally{N(null),E(!1)}},[i,o,a]),B=p.useCallback((b,q,ee=40,se=60,fe={})=>{FS({className:q,students:s[b]||[],dashData:r[b],qWeight:ee,aWeight:se,overrides:fe})},[s,r]),y=p.useCallback(async(b,q)=>{await i(b),await o(b),await a(b),await DS({classId:b,className:q,students:s[b]||[],dashData:r[b],lang:t,addToast:c,setIsGeneratingPDFReport:F})},[s,r,t,c,i,o,a]),te=p.useCallback(async()=>{R(!0);try{await $S({classes:n,classStudentsMap:s,classDashboardMap:r,lang:t})}catch(b){console.error("Export all classes error:",b)}finally{R(!1),E(!1)}},[n,s,r,t]),ae=p.useCallback((b,q)=>{const ee=r[q];if(!ee||!ee.performance)return null;const se=Date.now()-2592e6,ge=ee.performance.filter(he=>he.student_id===b).filter(he=>he.submitted_at&&he.submitted_at>=se&&he.score!==null&&he.score!==void 0);if(ge.length===0)return null;const je=ge.reduce((he,ft)=>he+Number(ft.score),0)/ge.length;return je<60?Math.round(je):null},[r]);return{isExportWeightModalOpen:u,setIsExportWeightModalOpen:d,exportClassId:f,setExportClassId:m,exportClassName:h,setExportClassName:g,quizzesWeight:x,setQuizzesWeight:v,assignmentsWeight:w,setAssignmentsWeight:I,customCategoryOverrides:S,setCustomCategoryOverrides:P,exportDropdownOpen:z,setExportDropdownOpen:E,exportTooltipOpen:L,setExportTooltipOpen:_,loadingExportClassId:M,setLoadingExportClassId:N,isExportingAllCombined:A,setIsExportingAllCombined:R,isGeneratingPDFReport:D,setIsGeneratingPDFReport:F,handleQuizzesWeightChange:j,handleAssignmentsWeightChange:T,csvPreviewData:$,triggerExportForClass:k,handleExportGrades:B,handleGeneratePDFReport:y,handleExportAllClassesCombined:te,get30DayAverageWarning:ae}}function US(e){const[t,n]=p.useState(""),[s,r]=p.useState("recent"),[i,o]=p.useState(!1),[a,c]=p.useState(!1),[u,d]=p.useState(!1),[f,m]=p.useState(null),h=p.useMemo(()=>{let g=[...e];if(t.trim()){const x=t.toLowerCase();g=g.filter(v=>v.title.toLowerCase().includes(x)||v.content.toLowerCase().includes(x))}if(i&&(g=g.filter(x=>(x.enrollment_count||0)>0)),a&&(g=g.filter(x=>x.content&&x.content.trim().length>0)),u){const x=new Date(new Date().getFullYear(),new Date().getMonth(),1).getTime();g=g.filter(v=>(v.created_at||0)>=x)}return s==="recent"?g.sort((x,v)=>(v.created_at||0)-(x.created_at||0)):s==="alphabetical"?g.sort((x,v)=>x.title.localeCompare(v.title)):s==="enrollment"&&g.sort((x,v)=>(v.enrollment_count||0)-(x.enrollment_count||0)),g},[e,t,s,i,a,u]);return{lessonsSearchQuery:t,setLessonsSearchQuery:n,lessonsSortOrder:s,setLessonsSortOrder:r,filterEnrollment:i,setFilterEnrollment:o,filterHasContent:a,setFilterHasContent:c,filterThisMonth:u,setFilterThisMonth:d,copyingLessonId:f,setCopyingLessonId:m,filteredAndSortedLessons:h}}function _a(e,t){let n="",s="",r="";e==="class"?(n=t==="zh"?"班级及学生批量导入模板.csv":"class_import_template.csv",s="Class Name,Class Desc,Student Name,Student Email",r=t==="zh"?`高一A班,基础英语课程,李明,liming@example.com
149
+ 高一A班,基础英语课程,王华,wanghua@example.com`:`Class 101,Introduction to English,John Doe,john@example.com
150
+ Class 101,Introduction to English,Jane Smith,jane@example.com`):(n=t==="zh"?"学生批量导入模板.csv":"student_import_template.csv",s="Student Name,Student Email",r=t==="zh"?`张三,zhangsan@example.com
151
+ 李四,lisi@example.com`:`Alice Cooper,alice@example.com
152
+ Bob Dylan,bob@example.com`);const i=new Blob(["\uFEFF"+s+`
153
+ `+r],{type:"text/csv;charset=utf-8;"}),o=URL.createObjectURL(i),a=document.createElement("a");a.href=o,a.setAttribute("download",n),document.body.appendChild(a),a.click(),document.body.removeChild(a)}async function WS(e,t){const{lang:n,fetchClasses:s,fetchStudents:r}=t;return new Promise((i,o)=>{const a=new FileReader;a.onload=async c=>{try{const u=c.target?.result;if(!u)throw new Error("File content is empty");let d=[],f=[],m=!0;if(e.name.endsWith(".json")){const h=JSON.parse(u);if(!Array.isArray(h))throw new Error("JSON structure must be an array");h.some(x=>x.className||x.name&&(x.students||x.classDescription))?(m=!0,d=h.map(x=>{const v=x.name||x.className||x.class_name,w=x.description||x.classDescription||"",I=x.students||x.studentList||[],S=(Array.isArray(I)?I:[]).map(P=>({name:P.name||P.studentName||"",email:P.email||P.studentEmail||""})).filter(P=>P.name);return{name:v,description:w,students:S}}).filter(x=>x.name)):(m=!1,f=h.map(x=>({name:x.name||x.studentName||x.student_name||"",email:x.email||x.studentEmail||x.student_email||""})).filter(x=>x.name))}else{const h=u.split(/\r?\n/);if(h.length<2)throw new Error("CSV has empty or insufficient data");const g=h[0].split(",").map(S=>S.trim().toLowerCase()),x=g.findIndex(S=>S.includes("class name")||S.includes("班级名称")||S.includes("班级")||S.includes("classname")||S.includes("class_name")),v=g.findIndex(S=>S.includes("class desc")||S.includes("班级描述")||S.includes("描述")||S.includes("class_desc")),w=g.findIndex(S=>S.includes("student name")||S.includes("学生姓名")||S.includes("姓名")||S.includes("学生")||S.includes("studentname")||S.includes("student_name")),I=g.findIndex(S=>S.includes("student email")||S.includes("学生邮箱")||S.includes("邮箱")||S.includes("email")||S.includes("studentemail")||S.includes("student_email"));if(w===-1)throw new Error('CSV is missing column: "Student Name" (学生姓名/姓名/学生)');if(x!==-1){m=!0;const S={};for(let P=1;P<h.length;P++){const z=h[P].trim();if(!z)continue;const L=(z.match(/(".*?"|[^",]+)(?=\s*,|\s*$)/g)||z.split(",")).map(R=>R.replace(/^"|"$/g,"").trim()),_=L[x];if(!_)continue;const M=v!==-1&&L[v]||"",N=w!==-1&&L[w]||"",A=I!==-1&&L[I]||"";S[_]||(S[_]={name:_,description:M,students:[]}),N&&S[_].students.push({name:N,email:A})}d=Object.values(S)}else{m=!1;for(let S=1;S<h.length;S++){const P=h[S].trim();if(!P)continue;const E=(P.match(/(".*?"|[^",]+)(?=\s*,|\s*$)/g)||P.split(",")).map(M=>M.replace(/^"|"$/g,"").trim()),L=w!==-1&&E[w]||"",_=I!==-1&&E[I]||"";L&&f.push({name:L,email:_})}}}if(m){if(d.length===0)throw new Error("No valid class elements found inside file.");const h=await fetch("/api/classes/import",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({classes:d})});if(!h.ok){const x=await h.json();throw new Error(x.error||"Server importation failed")}const g=await h.json();await s(),await r(),i({success:!0,message:n==="zh"?`成功导入 ${g.imported.length} 个班级数据!`:`Successfully imported ${g.imported.length} classes data!`})}else{if(f.length===0)throw new Error("No valid student elements found inside file.");const h=await fetch("/api/students/import",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({students:f})});if(!h.ok){const x=await h.json();throw new Error(x.error||"Server student importation failed")}const g=await h.json();await r(),i({success:!0,message:n==="zh"?`成功导入 ${g.imported.filter(x=>x.new).length} 名新学者,匹配并更新了其中的 ${g.imported.filter(x=>!x.new).length} 名同学!`:`Successfully imported ${g.imported.filter(x=>x.new).length} new students and updated ${g.imported.filter(x=>!x.new).length} existing ones!`})}}catch(u){o(u)}},a.onerror=()=>{o(new Error("Failed to read file from disk."))},a.readAsText(e)})}function qS(e,t){return new Promise((n,s)=>{const r=new FileReader;r.onload=i=>{try{const o=i.target?.result;if(!o)throw new Error("Empty CSV file");const a=o.split(/\r?\n/);if(a.length<2)throw new Error(t==="zh"?"CSV 文件行数不足,请包含标题和至少一行数据。":"CSV is missing content or headers.");const c=a[0].split(",").map(m=>m.trim().toLowerCase()),u=c.findIndex(m=>m.includes("title")||m.includes("标题")||m.includes("课程")),d=c.findIndex(m=>m.includes("content")||m.includes("内容")||m.includes("正文"));if(u===-1||d===-1)throw new Error(t==="zh"?'CSV 缺少必要表头列:必须包含 "Title"(课程标题)和 "Content"(课程内容)。':'CSV must contain "Title" and "Content" headers.');const f=[];for(let m=1;m<a.length;m++){const h=a[m].trim();if(!h)continue;const x=(h.match(/(".*?"|[^",]+)(?=\s*,|\s*$)/g)||h.split(",")).map(I=>I.replace(/^"|"$/g,"").trim()),v=x[u],w=x[d];v&&w&&f.push({title:v,content:w})}if(f.length===0)throw new Error(t==="zh"?"未能从 CSV 解析出有效课程数据。":"No valid courses found in CSV.");n(f)}catch(o){s(o)}},r.onerror=()=>{s(new Error(t==="zh"?"无法读取选取的 CSV 文件!":"Failure to read the CSV!"))},r.readAsText(e)})}async function HS(e,t){const{lang:n,setImportProgress:s,fetchLessons:r}=t;let i=0;for(let o=0;o<e.length;o++){const a=e[o];try{const c=await fetch("/api/lessons",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({title:a.title,content:a.content})});if(c.ok)i++;else{const u=await c.json();console.warn(`Failed to import item ${o+1}:`,u)}}catch(c){console.warn(`Error importing item ${o+1}:`,c)}s(o+1)}return i>0?(await r(),{success:!0}):{success:!1,errorMsg:n==="zh"?"所有课程项导入均失败。请检查控制台或格式。":"Failed to import any of the courses. Please check your console or schema."}}function GS(e){return"#/"+e}function Ra(e){const t=e.replace(/^#/,"");return!t||t==="/"?null:t.replace(/^\//,"")}$x();const Oa="openlearnv2.agentProviderId";function QS(){const e=ce(C=>C.lang),t=ce(C=>C.setLang),n=So[e]??So.zh,[s,r]=p.useState(!1),i=ce(C=>C.liveClassSelectedClassId),o=ce(C=>C.setLiveClassSelectedClassId),a=ce(C=>C.liveClassIsActive),c=ce(C=>C.setLiveClassIsActive),[u,d]=p.useState(0),[f,m]=p.useState([]),[h,g]=p.useState(new Map),x=Rl(),[v,w]=p.useState([]),[I,S]=p.useState({}),[P,z]=p.useState([]),[E,L]=p.useState(0),[_,M]=p.useState(!1),[N,A]=p.useState(null),[R,D]=p.useState(!1),[F,j]=p.useState("system"),[T,$]=p.useState(null),[k,B]=p.useState([]),[y,te]=p.useState(!1),[ae,b]=p.useState(!1),q=async()=>{try{te(!0);const C=await fetch("/api/resources");if(C.ok){const V=await C.json();B(V)}}catch(C){console.warn("Error fetching library resources:",C)}finally{te(!1)}};et.useEffect(()=>{cs.getState().initTheme()},[]),et.useEffect(()=>{R&&q()},[R]);const ee=ce(C=>C.lessons),se=ce(C=>C.setLessons),{lessonsSearchQuery:fe,setLessonsSearchQuery:ge,lessonsSortOrder:ze,setLessonsSortOrder:je,filterEnrollment:he,setFilterEnrollment:ft,filterHasContent:Lt,setFilterHasContent:_t,filterThisMonth:pt,setFilterThisMonth:mt,copyingLessonId:G,setCopyingLessonId:K,filteredAndSortedLessons:re}=US(ee),[we,qe]=p.useState([]),de=ce(C=>C.selectedLesson),Te=ce(C=>C.setSelectedLesson),ke=ce(C=>C.elements),Ze=ce(C=>C.setElements),[O,W]=p.useState(!1),[Q,Z]=p.useState("idle"),[ie,Ne]=p.useState(0),[Ye,Le]=p.useState(0),[lt,_e]=p.useState(""),[ye,He]=p.useState([]),[Fe,ys]=p.useState(!1),[xs,bs]=p.useState(!1),[ws,Ss]=p.useState("agent"),[vs,Cs]=p.useState(!1),[Sn,ks]=p.useState([]),[Es,Ps]=p.useState([]),[Jt,Zt]=p.useState(null),[vn,Ee]=p.useState(""),Rt=ce(C=>C.classes),Ts=ce(C=>C.setClasses),tt=ce(C=>C.students),Cn=ce(C=>C.setStudents),{computerLabs:Ns,fetchLabs:kn,todaySchedules:Is,fetchTodaySchedules:Ot,classSchedulesMap:js,fetchClassSchedules:En,scheduleAttendanceMap:As,fetchScheduleAttendance:zs,expandedScheduleId:Ls,setExpandedScheduleId:_s,newScheduleDate:Rs,setNewScheduleDate:Os,newScheduleLessonId:me,setNewScheduleLessonId:Ms}=RS(),[kt,Ds]=p.useState(null),Fs=p.useRef(null),Bs=C=>{Ds(C),Fs.current=C},[Pn,Tn]=p.useState({}),[$s,Vs]=p.useState(null),Nn=p.useRef(null),[Yt,Kt]=p.useState(null),Us=C=>{const V=Xf[C];V&&Kt({type:C,data:{...V.defaultData}})},Ws=async C=>{Yt&&await Nn.current?.addElementAtCenter(Yt.type,C),Kt(null)},Se=ce(C=>C.session),Et=ce(C=>C.setSession),In=ce(C=>C.siteInfo),jn=ce(C=>C.setSiteInfo),[Be,Re]=p.useState("teacher"),[qs,Hs]=p.useState(!0),[Gs,Mt]=p.useState(!0),[Qs,Pt]=p.useState("normal");p.useEffect(()=>{if(!Se)return;const C=async()=>{try{const H=await fetch("/api/db-status");if(H.ok){const J=await H.json().catch(()=>({}));J.status==="warning"||J.warning?Pt("warning"):Pt("normal"),Mt(!0)}else H.status===429||H.status===503?(Pt("warning"),Mt(!0)):(Pt("error"),Mt(!1))}catch{Pt("error"),Mt(!1)}};C();const V=setInterval(C,5e3);return()=>clearInterval(V)},[Se]),p.useEffect(()=>{(async()=>{try{const V=await fetch("/api/auth/session");if(V.ok){const H=await V.json();H.session&&(Et(H.session),Re(H.session.role),H.session.role==="student"&&H.session.studentId&&(An(H.session.studentId),It()))}}catch(V){console.warn("Session check failed",V)}finally{Hs(!1)}})()},[]),p.useEffect(()=>{(async()=>{try{const V=await fetch("/api/site-settings");if(V.ok){const H=await V.json();jn({siteName:H.siteName||"",slogan:H.slogan||"",logoUrl:H.logoUrl||null})}}catch(V){console.warn("Failed to fetch site settings:",V)}})()},[]);const gt=ce(C=>C.teacherTab),$e=ce(C=>C.setTeacherTab);p.useEffect(()=>{const C=()=>{const H=Ra(window.location.hash);H&&H!==Ce.getState().teacherTab&&$e(H)};window.addEventListener("hashchange",C);const V=Ra(window.location.hash);return V&&$e(V),()=>window.removeEventListener("hashchange",C)},[$e]),p.useEffect(()=>{const C=GS(gt);window.location.hash!==C&&(window.location.hash=C)},[gt,$e]);const[Js,Dt]=p.useState(!1),[Zs,Ys]=p.useState(!1),[Xt,mc]=p.useState(!1);p.useEffect(()=>{Se?.subRole==="administrator"&&localStorage.getItem("edu_os_tour_completed")!=="true"&&Dt(!0)},[Se]);const gc=async C=>{await Ft(),await ct(),await Ot().catch(()=>{}),o(C.classId),Te(C.lessonId),c(!0),Ge(e==="zh"?"示范课堂准备就绪":"Demo Classroom Ready",e==="zh"?"示范班级与课件已加载,已自动开启授课状态!":"Demo class & courseware loaded. Live class session is now active!","success")};p.useEffect(()=>{gt==="live_class"&&r(!0)},[gt]);const{timelineSegments:yc,activeSegmentId:Ks,setActiveSegmentId:Xs,draggedSegmentIdx:xc,setDraggedSegmentIdx:bc,editorSaveStatus:wc,setEditorSaveStatus:Sc,editorLastSavedTime:vc,setEditorLastSavedTime:Cc,editorPanelsExpanded:kc,setEditorPanelsExpanded:Ec,saveTimeline:Pc}=OS({selectedLesson:de,lessons:ee,setLessons:se}),[Pe,An]=p.useState(null),[er,Tc]=p.useState(null),Ge=(C,V,H="info")=>{const J=Math.random().toString(36).substring(2,9);Ce.getState().addToast({id:J,title:C,message:V,type:H}),setTimeout(()=>{Ce.getState().removeToast(J)},6e3)},ct=async()=>{try{const C=await fetch("/api/lessons");if(C.ok){const V=await C.json();se(V),!Ce.getState().selectedLesson&&V.length>0&&Te(V[0].id)}}catch(C){console.warn("Failed to fetch lessons",C)}},Mi=p.useRef(()=>{}),Di=zS({lang:e,addToast:Ge,fetchLessons:ct,setSelectedLesson:Te,setTeacherTab:$e}),{isCourseWizardOpen:fv,setIsCourseWizardOpen:Nc,wizardStep:pv,setWizardStep:Ic,wizardCourseTitle:mv,setWizardCourseTitle:gv,wizardCourseCategory:yv,setWizardCourseCategory:xv,wizardCourseDescription:bv,setWizardCourseDescription:wv,wizardCourseContent:Sv,setWizardCourseContent:vv,wizardCourseTimeline:Cv,setWizardCourseTimeline:kv,wizardIsSubmitting:Ev,handleDeployWizardCourse:Pv}=Di,{plugins:yt,fetchPlugins:jc,aiProviders:Tt,fetchAIProviders:Ac,testingProviderId:zc,storeTab:Lc,setStoreTab:_c,pluginCode:Rc,setPluginCode:Oc,installingPlugin:Mc,events:Dc,fetchEvents:Fc,approvals:Bc,fetchApprovals:$c,scoreOverrides:Vc,setScoreOverrides:Uc,handleInstallPlugin:Wc,handleZipPluginUpload:qc,handleTogglePlugin:Hc,handleDeletePlugin:Gc,handleApprove:Qc,handleReject:Jc}=AS({host:x,lang:e,addToast:Ge,setChatLog:C=>Mi.current(C),setTeacherTab:$e,fetchLessons:ct}),[ut,Fi]=p.useState(()=>typeof window>"u"?"system":window.localStorage.getItem(Oa)||"system"),tr=ut==="system"||Tt.some(C=>C.id===ut)?ut:"system",Zc=Tt.find(C=>C.id===tr)||null,[en,Nt]=p.useState("dashboard"),[Yc,Kc]=p.useState("whiteboard"),[Xc,eu]=p.useState(null),[xt,nr]=p.useState(null),[tu,Bi]=p.useState(!1),[nu,$i]=p.useState(null),[su,Vi]=p.useState("whiteboard"),[ru,iu]=p.useState("none"),[ou,au]=p.useState("none"),[lu,Ui]=p.useState(!0);p.useEffect(()=>{en!=="lesson"&&Ui(!0)},[en]);const Wi=LS(),{isQuizGeneratorOpen:Tv,setIsQuizGeneratorOpen:cu,quizGeneratorClassId:Nv,setQuizGeneratorClassId:uu,quizGenMode:Iv,setQuizGenMode:du,quizGenSelectedLessonId:jv,setQuizGenSelectedLessonId:hu,quizGenTopic:Av,setQuizGenTopic:fu,isGeneratingSuggestions:zv,setIsGeneratingSuggestions:Lv,suggestedObjectives:_v,setSuggestedObjectives:pu,suggestedQuestions:Rv,setSuggestedQuestions:mu,savingQuiz:Ov,setSavingQuiz:Mv,quizStudentAnswers:gu,setQuizStudentAnswers:qi,quizGenTimeLimit:Dv,setQuizGenTimeLimit:Fv,quizStudentAnswersRef:yu,subAssignmentTab:xu,setSubAssignmentTab:Hi}=Wi,[bu,wu]=p.useState(""),[Su,vu]=p.useState("all"),[Cu,ku]=p.useState("grid"),[Eu,Pu]=p.useState({}),[Tu,Nu]=p.useState({}),[Iu,ju]=p.useState({}),Gi=MS(Be,er,e),{studentNotifications:Au,unreadNotifications:zu,readNotifications:Qi,setReadNotifications:zn,selectedNotificationForModal:Lu,setSelectedNotificationForModal:_u,isNotificationsOpen:Ru,setIsNotificationsOpen:Ou}=Gi;p.useEffect(()=>{Pe&&fetch(`/api/students/${Pe}/read_notifications`).then(C=>C.ok?C.json():[]).then(C=>{zn(new Set(C))}).catch(C=>{console.warn("Failed to load read notifications from DB",C),zn(new Set)})},[Pe]);const Mu=p.useRef(null),Du=C=>{Vs(C),Mu.current=C},[Fu,Bu]=p.useState({}),[$u,Vu]=p.useState({}),[Bv,$v]=p.useState({}),[Vv,Uv]=p.useState({}),[Uu,Wv]=p.useState(null),[Wu,qu]=p.useState("dueDate"),[qv,Hv]=p.useState(null),[Hu,Gu]=p.useState({}),[Qu,Ji]=p.useState(!1),[Ju,Zi]=p.useState(!1),[Zu,sr]=p.useState(null),[Yu,rr]=p.useState(null),[ir,Ku]=p.useState(null),Xu=p.useRef(null),Yi=C=>{Ku(C),Xu.current=C};p.useEffect(()=>{typeof window<"u"&&window.localStorage.setItem(Oa,ut)},[ut]),p.useEffect(()=>{ut!=="system"&&Tt.length>0&&!Tt.some(C=>C.id===ut)&&Fi("system")},[Tt,ut]);const ed=async(C,V,H)=>{try{if((await fetch(`/api/classes/${C}/schedules`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({lessonId:V,scheduledDate:H})})).ok)return await En(C),!0}catch(J){console.error("Quick schedule class failed",J)}return!1},td=async(C,V,H)=>{try{const J=V||H||"Assignment",Ve=await fetch(`/api/classes/${C}/assignments/generate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({topic:J})});if(Ve.ok){const dt=await Ve.json().catch(()=>({}));return await tn(C),dt.id||"assignment-created"}}catch(J){console.error("Quick generate assignment failed",J)}return null},nd=async(C,V)=>{try{const H=await fetch("/api/lessons",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({title:C,content:V})});if(H.ok){const J=await H.json().catch(()=>({}));return await ct(),J.id||"lesson-created"}}catch(H){console.error("Quick create lesson failed",H)}return""},sd=()=>{_a("class",e)},rd=async C=>{if(C){if(!C.name.toLowerCase().endsWith(".csv")){Z("error"),_e(e==="zh"?"只支持包含 .csv 后缀名的文件!":"Only files ending in .csv are supported!");return}Z("parsing"),_e("");try{const V=await qS(C,e);He(V),Z("idle")}catch(V){Z("error"),_e(V.message||String(V))}}},id=async()=>{if(ye.length===0)return;Z("importing"),Ne(0),Le(ye.length);const C=await HS(ye,{lang:e,setImportProgress:Ne,fetchLessons:ct});C.success?Z("success"):(Z("error"),_e(C.errorMsg||""))},od=async C=>{const V=await fetch(`/api/lessons/${C}`,{method:"DELETE"});if(!V.ok){const H=await V.json().catch(()=>({}));throw new Error(H.error||"Failed to delete course")}await ct(),de===C&&Te(null),Ge(e==="zh"?"课程已删除":"Course Deleted",e==="zh"?"课程及其所有关联数据已被删除。":"The course and all associated data have been deleted.","success")},ad=async C=>{K(C);try{const V=await fetch(`/api/lessons/${C}/clone`,{method:"POST"});if(!V.ok){const H=await V.json().catch(()=>({}));throw new Error(H.error||"Failed to copy course")}await ct(),Ge(e==="zh"?"复制成功":"Course Copied",e==="zh"?"课程已成功复制。":"Course has been copied successfully.","success")}catch(V){Ge(e==="zh"?"复制失败":"Copy Failed",V.message||(e==="zh"?"复制课程时发生错误。":"An error occurred while copying the course."),"error")}finally{K(null)}},Ki=async()=>{try{const C=await fetch("/api/commands/registered");if(!C.ok)return;const V=C.headers.get("content-type");if(V&&V.includes("application/json")){const H=await C.json();Array.isArray(H)&&qe(H)}}catch(C){console.warn("Failed to fetch registered commands",C)}},ld=async C=>{try{const V=await fetch(`/api/vfs${C?`?parentId=${C}`:""}`);if(V.ok){const H=await V.json();ks(H)}}catch(V){console.warn("Failed to fetch VFS nodes",V)}},cd=async()=>{try{const C=await fetch("/api/processes");C.ok&&Ps(await C.json())}catch{}},Ft=async()=>{try{const C=await fetch("/api/classes");C.ok&&Ts(await C.json())}catch{}},It=async()=>{try{const C=await fetch("/api/students");C.ok&&Cn(await C.json())}catch{}},Bt=async C=>{try{const V=await fetch(`/api/classes/${C}/students`);if(V.ok){const H=await V.json();Tn(J=>({...J,[C]:H}))}}catch{}},or=async C=>{try{const V=await fetch(`/api/classes/${C}/progress`);if(V.ok){const H=await V.json();Vu(J=>({...J,[C]:H}))}}catch{}},[ar,ud]=p.useState({}),tn=async C=>{try{const V=await fetch(`/api/classes/${C}/dashboard`);if(V.ok){const H=await V.json();ud(J=>({...J,[C]:H}))}}catch{}},dd=VS({lang:e,classes:Rt,classStudentsMap:Pn,classDashboardMap:ar,fetchClassStudents:Bt,fetchClassDashboard:tn,fetchClassProgress:or}),{isExportWeightModalOpen:hd,setIsExportWeightModalOpen:Xi,exportClassId:fd,setExportClassId:pd,exportClassName:md,setExportClassName:gd,quizzesWeight:yd,setQuizzesWeight:eo,assignmentsWeight:xd,setAssignmentsWeight:to,customCategoryOverrides:bd,setCustomCategoryOverrides:no,exportDropdownOpen:wd,setExportDropdownOpen:Sd,exportTooltipOpen:vd,setExportTooltipOpen:Cd,loadingExportClassId:kd,isExportingAllCombined:Ed,isGeneratingPDFReport:Pd,handleQuizzesWeightChange:Td,handleAssignmentsWeightChange:Nd,csvPreviewData:Id,triggerExportForClass:jd,handleExportGrades:Ad,handleGeneratePDFReport:zd,handleExportAllClassesCombined:so,get30DayAverageWarning:Ld}=dd,ro=_S({lang:e,classes:Rt,expandedClassId:kt,fetchClasses:Ft,fetchClassStudents:Bt,handleExportAllClassesCombined:so}),{batchMode:_d,setBatchMode:Rd,selectedClassIds:Od,setSelectedClassIds:Md,selectedStudentIds:Dd,setSelectedStudentIds:Fd,batchPicker:Gv,setBatchPicker:Qv,batchPickerLesson:Jv,setBatchPickerLesson:Zv,batchPickerDate:Yv,setBatchPickerDate:Kv,batchPickerTargetClass:Xv,setBatchPickerTargetClass:e0,toggleClassSelection:Bd,toggleSelectAllClasses:$d,toggleStudentSelection:Vd,toggleSelectAllStudents:Ud,handleBatchDeleteClasses:Wd,handleBatchExportClasses:qd,handleBatchSetPasscode:Hd,handleBatchScheduleClasses:Gd,handleBatchDeleteStudents:Qd,handleBatchResetPassword:Jd,handleBatchTransferStudents:Zd,handleBatchSetLockedLesson:Yd,confirmBatchPicker:t0}=ro,lr=async C=>{try{const V=await fetch(`/api/students/${C}/dashboard`);if(V.ok){const H=await V.json();Tc(H),H.profile&&H.profile.locked_lesson_id&&(Te(H.profile.locked_lesson_id),Nt("lesson"))}}catch{}},Kd=async(C=!1)=>{if(!xt)return;const H=xt?.content&&xt.content.startsWith('{"quizType":"mcq_learning_objectives"')?JSON.stringify(yu.current):"Submitted via Whiteboard";try{(await fetch(`/api/assignments/${xt.id}/submissions`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({studentId:Pe,content:H})})).ok&&(C&&alert("Time is up! Your assessment was successfully submitted automatically."),await lr(Pe),Nt("dashboard"),nr(null))}catch(J){console.error(J)}};p.useEffect(()=>{if(Se&&Be==="student"&&Pe){lr(Pe);const C=tt.find(V=>V.id===Pe);C&&C.locked_lesson_id&&(Te(C.locked_lesson_id),Nt("lesson"))}},[Se,Be,Pe,tt]);const Xd=p.useRef(Be),eh=p.useRef(Pe),th=p.useRef(e),nh=p.useRef(tt),sh=p.useRef(Ge),Ln=p.useRef(new Set);p.useRef(new Set),p.useEffect(()=>{Xd.current=Be},[Be]),p.useEffect(()=>{eh.current=Pe},[Pe]),p.useEffect(()=>{th.current=e},[e]),p.useEffect(()=>{nh.current=tt},[tt]),p.useEffect(()=>{sh.current=Ge},[Ge]),p.useEffect(()=>{if(!x.isInitialized()||yt.length===0)return;const C=ve.getState(),V=yt.filter(J=>J.status==="active");for(const J of V){if(!J.has_frontend||Ln.current.has(J.id))continue;const Ve=C.activePlugins.find(ht=>ht.id===J.id),dt=!!(Ve&&J.version&&Ve.version!==J.version);if(!(!Ve||dt||Ve.state!==pe.ACTIVE&&Ve.state!==pe.ACTIVATING))continue;Ln.current.add(J.id);const ao=()=>{if(!C.activePlugins.find(ht=>ht.id===J.id))C.addPlugin({id:J.id,name:J.name,version:J.version,state:pe.INSTALLED,executionMode:"inline"});else if(dt)try{ve.setState(ht=>({activePlugins:ht.activePlugins.map(sn=>sn.id===J.id?{...sn,version:J.version,name:J.name}:sn)}))}catch{}try{const ht=JSON.parse(J.manifest);x.activateRemotePlugin(J.id,ht).catch(sn=>{console.error(`[App] Failed to activate remote plugin "${J.name}":`,sn)}).finally(()=>{Ln.current.delete(J.id)})}catch(ht){Ln.current.delete(J.id),console.error(`[App] Failed to parse manifest for plugin "${J.name}":`,ht)}};Ve&&Ve.state===pe.ACTIVE&&dt?x.deactivatePlugin(J.id).catch(()=>{}).finally(ao):ao()}const H=yt.filter(J=>J.status!=="active");for(const J of H){if(!J.has_frontend)continue;const Ve=C.activePlugins.find(dt=>dt.id===J.id);Ve&&Ve.state===pe.ACTIVE&&x.deactivatePlugin(J.id).catch(dt=>{console.error(`[App] Failed to deactivate remote plugin "${J.name}":`,dt)})}},[yt,x]),et.useEffect(()=>{if(!x.isInitialized()||yt.length===0)return;const C=ve.getState();for(const V of yt)V.status==="active"&&(C.dashboardVisibility.has(V.id)||C.setDashboardVisibility(V.id,!0))},[yt,x]);const rh=async C=>{if(Be==="student"&&Pe&&de)try{await fetch(`/api/students/${Pe}/progress`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({lessonId:de,completed:C===100,progressPercent:C})})}catch(V){console.error("Failed to update student progress:",V)}},ih=async(C,V)=>{try{const H=await fetch(`/api/classes/${C}/lessons/${V}/progress`);H.ok&&z(await H.json())}catch{}};p.useEffect(()=>{i&&de?ih(i,de):z([])},[i,de]),p.useEffect(()=>{i&&Bt(i)},[i]);const oh=async C=>{try{const V=await fetch(`/api/students/${C}/progress`);if(V.ok){const H=await V.json();Bu(J=>({...J,[C]:H}))}}catch{}},io=async C=>{try{const V=await fetch(`/api/processes/${C}/logs`);if(V.ok){const H=await V.json();Ee(H.logs||""),Zt(C)}}catch{}},nn=async C=>{const H=await(await fetch(`/api/lessons/${C}/whiteboard`)).json();Ze(H)},ah=p.useRef(null);p.useRef(null);const lh=p.useRef(null);p.useEffect(()=>{ah.current=de},[de]),p.useEffect(()=>{lh.current=xt},[xt]),Xl(Se);const{chatLog:ch,setChatLog:uh,input:dh,setInput:hh,loading:fh,chatAttachments:ph,setChatAttachments:mh,handleChatFileChange:gh,handleChatDrop:yh,handleSend:xh,handleClearAgentMemory:bh}=jw({lang:e,t:n,selectedLesson:de,effectiveAgentProviderId:tr,expandedClassId:kt,fetchLessons:ct,fetchClasses:Ft,fetchStudents:It,fetchClassStudents:Bt,fetchClassProgress:or,fetchClassDashboard:tn,fetchElements:nn});Mi.current=uh,Iw({session:Se,showProcessLogs:Jt,activeStudentId:Pe,currentVfsParent:ir,selectedLesson:de,selectedAssignment:xt,expandedClassId:kt,fetchLessons:ct,fetchPlugins:jc,fetchRegisteredCommands:Ki,fetchEvents:Fc,fetchApprovals:$c,fetchProcesses:cd,fetchClasses:Ft,fetchTodaySchedules:Ot,fetchStudents:It,fetchLabs:kn,fetchVfs:ld,fetchProcessLogs:io,fetchClassStudents:Bt,fetchElements:nn});const{socketRef:wh}=IS({session:Se,host:x,activeRole:Be,activeStudentId:Pe,selectedLesson:de,activeSegmentId:Ks,studentViewStatus:en,lang:e,students:tt,addToast:Ge,setOnlineStudentIds:w,setActiveStudentLessons:S,setLessons:se,setActiveSegmentId:Xs,setLiveClassStudentProgress:z,setLiveClassAcknowledgedMap:g,setLiveClassFeed:m,setSelectedLesson:Te,setStudentViewStatus:Nt,setLocalProgressPercent:L,fetchStudentDashboard:lr,fetchStudents:It,fetchElements:nn}),Sh=C=>{_a(C,e)},vh=async C=>{Zi(!0),sr(null),rr(null);try{const V=await WS(C,{lang:e,fetchClasses:Ft,fetchStudents:It});rr(V.message)}catch(V){sr(V.message||String(V))}finally{Zi(!1)}},Ch=()=>{t(e==="zh"?"en":"zh")},kh=p.useCallback(C=>{Et(C),C.role==="teacher"?(Re("teacher"),$e("dashboard")):(Re("student"),An(C.studentId),It())},[]),oo=async()=>{try{await fetch("/api/auth/logout",{method:"POST"})}catch(C){console.error("Logout failed",C)}Et(null)},[Eh,cr]=p.useState(!1);return qs?l.jsxs("div",{className:"min-h-screen bg-slate-900 flex flex-col items-center justify-center p-4 relative overflow-hidden font-sans",children:[l.jsx(ui,{size:48,className:"text-indigo-500 animate-spin"}),l.jsx("span",{className:"text-white text-sm mt-4 font-semibold tracking-wide",children:e==="zh"?"正在连接安全核心数据库...":"Connecting Secure OS Core Database..."})]}):Se?l.jsx(l.Fragment,{children:l.jsxs("div",{className:"flex h-screen bg-app text-main font-sans transition-colors duration-150",children:[l.jsxs("div",{className:"flex-1 flex flex-col bg-app h-full overflow-hidden",children:[l.jsx(Zf,{activeRole:Be,lang:e,teacherTab:gt,studentViewStatus:en,session:Se,activeStudentId:Pe,students:tt,studentDashboardData:er,isNotificationsOpen:Ru,studentNotifications:Au,unreadNotifications:zu,readNotifications:Qi,selectedNotificationForModal:Lu,dbConnected:Gs,dbStatus:Qs,siteInfo:In,setActiveStudentId:An,setReadNotifications:zn,setIsSystemResourceLibraryOpen:D,setProfileOpen:cr,setTeacherTab:$e,setStudentViewStatus:Nt,setIsNotificationsOpen:Ou,setSelectedNotificationForModal:_u,handleLogout:oo,toggleLanguage:Ch}),l.jsx(Yf,{open:Eh,session:Se,lang:e,onClose:()=>cr(!1),onSaved:C=>{Se&&Et({...Se,name:C}),cr(!1)},onAvatar:C=>{Se&&Et({...Se,avatar:C??void 0})}}),l.jsx(qx,{students:tt,activeStudentId:Pe,studentViewStatus:en,studentDashboardData:er,readNotifications:Qi,setReadNotifications:zn,addToast:Ge,lang:e,setSelectedLesson:Te,setStudentViewStatus:Nt,setSelectedAssignment:nr,setQuizStudentAnswers:qi,setSubAssignmentTab:Hi,lessons:ee,selectedLesson:de,studentFullscreenPanel:ou,setStudentFullscreenPanel:au,timelineSegments:yc,activeSegmentId:Ks,setActiveSegmentId:Xs,localProgressPercent:E,setLocalProgressPercent:L,updateStudentProgress:rh,isStudentLessonContentCollapsed:lu,setIsStudentLessonContentCollapsed:Ui,studentLessonTab:Yc,setStudentLessonTab:Kc,elements:ke,activeRole:Be,fetchElements:nn,currentVfsParent:ir,setCurrentVfsParent:Yi,vfsNodes:Sn,studentSelectedCourseware:Xc,setStudentSelectedCourseware:eu,selectedAssignment:xt,quizStudentAnswers:gu,submitQuizAssignment:Kd,subAssignmentTab:xu,mainNavCollapsed:s,setMainNavCollapsed:r,teacherTab:gt,setTeacherTab:$e,session:Se,todaySchedules:Is,t:n,classes:Rt,approvals:Bc,processes:Es,isApprovalsCollapsed:Zs,setIsApprovalsCollapsed:Ys,isProcessesCollapsed:Xt,setIsProcessesCollapsed:mc,scoreOverrides:Vc,setScoreOverrides:Uc,handleApprove:Qc,handleReject:Jc,showLogs:vs,setShowLogs:Cs,processLogsContent:vn,showProcessLogs:Jt,fetchProcessLogs:io,setShowProcessLogs:Zt,handleQuickScheduleClass:ed,handleQuickGenerateAssignment:td,handleQuickCreateLesson:nd,setActiveRole:Re,editorSaveStatus:wc,setEditorSaveStatus:Sc,editorLastSavedTime:vc,setEditorLastSavedTime:Cc,setIsLessonPreviewVisible:Bi,setPreviewLessonTab:Vi,setPreviewSelectedCourseware:$i,handlePaletteActivate:Us,draggedSegmentIdx:xc,setDraggedSegmentIdx:bc,saveTimeline:Pc,editorPanelsExpanded:kc,setEditorPanelsExpanded:Ec,whiteboardRef:Nn,paletteEdit:Yt,handlePaletteConfirm:Ws,setPaletteEdit:Kt,plugins:yt,liveClassSelectedClassId:i,setLiveClassSelectedClassId:o,liveClassIsActive:a,setLiveClassIsActive:c,liveClassTimeRemaining:u,setLiveClassTimeRemaining:d,liveClassFeed:f,setLiveClassFeed:m,liveClassAcknowledgedMap:h,setLiveClassAcknowledgedMap:g,onlineStudentIds:v,activeStudentLessons:I,liveClassStudentProgress:P,storeTab:Lc,setStoreTab:_c,pluginCode:Rc,setPluginCode:Oc,installingPlugin:Mc,onInstall:Wc,onZipUpload:qc,onToggle:Hc,onDelete:Gc,lessonsSearchQuery:fe,setLessonsSearchQuery:ge,lessonsSortOrder:ze,setLessonsSortOrder:je,filteredLessons:re,onOpenImportLessons:()=>{Z("idle"),Ne(0),Le(0),_e(""),He([]),W(!0)},onOpenCourseWizard:()=>{Ic(1),Nc(!0)},onViewCourse:C=>{$e("lesson_editor"),Te(C)},onDeleteCourse:od,onCopyCourse:ad,filterEnrollment:he,setFilterEnrollment:ft,filterHasContent:Lt,setFilterHasContent:_t,filterThisMonth:pt,setFilterThisMonth:mt,copyingLessonId:G,onSchedulesUpdated:Ot,onLogout:oo,aiProviders:Tt,testingProviderId:zc,onAIProvidersChanged:Ac,onTriggerTour:()=>Dt(!0),siteInfo:In,onSiteInfoChanged:jn,computerLabs:Ns,onRefresh:kn,registeredCommands:we,fetchRegisteredCommands:Ki,batchMode:_d,selectedClassIds:Od,setSelectedClassIds:Md,setSelectedStudentIds:Fd,setBatchMode:Rd,expandedClassId:kt,setExpandedClassId:Bs,exportTooltipOpen:vd,setExportTooltipOpen:Cd,exportDropdownOpen:wd,setExportDropdownOpen:Sd,isExportingAllCombined:Ed,loadingExportClassId:kd,classStudentsMap:Pn,setClassStudentsMap:Tn,expandedStudentId:$s,setExpandedStudentId:Du,selectedStudentIds:Dd,rosterViewMode:Cu,setRosterViewMode:ku,rosterSearchQuery:bu,setRosterSearchQuery:wu,rosterTagFilter:Su,setRosterTagFilter:vu,toggleSelectAllStudents:Ud,handleBatchDeleteStudents:Qd,handleBatchResetPassword:Jd,handleBatchTransferStudents:Zd,handleBatchSetLockedLesson:Yd,toggleStudentSelection:Vd,get30DayAverageWarning:Ld,studentProgressMap:Fu,studentActiveTabs:Iu,setStudentActiveTabs:ju,setStudents:Cn,fetchClassStudents:Bt,fetchStudents:It,parseCSV:$f,setImportError:sr,setImportSuccess:rr,setShowImportModal:Ji,fetchClasses:Ft,classSubmissionFilters:Eu,setClassSubmissionFilters:Pu,classActiveTabs:Tu,setClassActiveTabs:Nu,classProgressMap:$u,classSchedulesMap:js,classDashboardMap:ar,assignmentSortOrder:Wu,setAssignmentSortOrder:qu,isGeneratingPDFReport:Pd,handleGeneratePDFReport:zd,setExportClassId:pd,setExportClassName:gd,setQuizzesWeight:eo,setAssignmentsWeight:to,setCustomCategoryOverrides:no,setIsExportWeightModalOpen:Xi,isGeneratingAssignment:Uu,setQuizGeneratorClassId:uu,setQuizGenMode:du,setQuizGenSelectedLessonId:hu,setQuizGenTopic:fu,setSuggestedObjectives:pu,setSuggestedQuestions:mu,setIsQuizGeneratorOpen:cu,setActiveStudentId:An,isGrading:Hu,setIsGrading:Gu,fetchClassDashboard:tn,newScheduleDate:Rs,setNewScheduleDate:Os,newScheduleLessonId:me,setNewScheduleLessonId:Ms,expandedScheduleId:Ls,setExpandedScheduleId:_s,fetchScheduleAttendance:zs,scheduleAttendanceMap:As,toggleSelectAllClasses:$d,handleBatchDeleteClasses:Wd,handleBatchExportClasses:qd,handleBatchSetPasscode:Hd,handleBatchScheduleClasses:Gd,handleExportAllClassesCombined:so,triggerExportForClass:jd,fetchClassProgress:or,fetchClassSchedules:En,fetchStudentProgress:oh,toggleClassSelection:Bd,socketRef:wh,setShowCoursewareHub:b,fetchTodaySchedules:Ot})]}),l.jsx(cw,{showRightSidebar:xs,setShowRightSidebar:bs,rightSidebarTab:ws,setRightSidebarTab:Ss,effectiveAgentProviderId:tr,agentProviderId:ut,setAgentProviderId:Fi,aiProviders:Tt,selectedAgentProvider:Zc,chatLog:ch,loading:fh,input:dh,setInput:hh,handleSend:xh,chatAttachments:ph,setChatAttachments:mh,handleChatFileChange:gh,handleChatDrop:yh,onClearAgentMemory:bh,events:Dc,lang:e,t:n}),l.jsx(Cw,{lang:e,t:n,courseWizard:Di,quizGenerator:Wi,classBatch:ro,studentNotificationsHook:Gi,showImportModal:Qu,setShowImportModal:Ji,handleImportFile:vh,importError:Zu,importSuccess:Yu,isImporting:Ju,downloadCSVTemplate:Sh,addToast:Ge,generateTemplateContent:Ax,isImportLessonsOpen:O,setIsImportLessonsOpen:W,importStatus:Q,setIsDraggingImport:ys,handleCSVFileChange:rd,downloadCsvTemplate:sd,isDraggingImport:Fe,previewImportData:ye,setPreviewImportData:He,setImportStatus:Z,importProgress:ie,importProgressTotal:Ye,importErrorMsg:lt,setImportErrorMsg:_e,handleCSVImportSubmit:id,lessons:ee,fetchClassDashboard:tn,isLessonPreviewVisible:tu,setIsLessonPreviewVisible:Bi,selectedLesson:de,previewFullscreenPanel:ru,setPreviewFullscreenPanel:iu,previewLessonTab:su,setPreviewLessonTab:Vi,activeRole:Be,elements:ke,activeSegmentId:Ks,setActiveSegmentId:Xs,fetchElements:nn,currentVfsParent:ir,setCurrentVfsParent:Yi,vfsNodes:Sn,previewSelectedCourseware:nu,setPreviewSelectedCourseware:$i,showProcessLogs:Jt,setShowProcessLogs:Zt,processLogsContent:vn,isCloudDriveOpen:_,setIsCloudDriveOpen:M,cloudDrivePreviewNode:N,setCloudDrivePreviewNode:A,isSystemResourceLibraryOpen:R,setIsSystemResourceLibraryOpen:D,systemResourceTab:F,setSystemResourceTab:j,selectedLibraryResourceId:T,setSelectedLibraryResourceId:$,loadingLibraryResources:y,libraryResources:k,fetchLibraryResources:q,classes:Rt,expandedClassId:kt,isExportWeightModalOpen:hd,setIsExportWeightModalOpen:Xi,quizzesWeight:yd,setQuizzesWeight:eo,assignmentsWeight:xd,setAssignmentsWeight:to,handleQuizzesWeightChange:Td,handleAssignmentsWeightChange:Nd,customCategoryOverrides:bd,setCustomCategoryOverrides:no,classDashboardMap:ar,exportClassId:fd,exportClassName:md,csvPreviewData:Id,handleExportGrades:Ad,setSelectedAssignment:nr,setStudentViewStatus:Nt,setQuizStudentAnswers:qi,setSubAssignmentTab:Hi,isTourOpen:Js,setIsTourOpen:Dt,handleSeedSuccess:gc,setTeacherTab:$e,showCoursewareHub:ae,setShowCoursewareHub:b}),l.jsx(lw,{})]})}):l.jsx(Vf,{onLoginSuccess:kh,lang:e})}class JS{constructor(){this.services=new Map}async register(t,n){if(this.services.has(t))throw new Error(`Service already registered: ${t}`);this.services.set(t,n)}async resolve(t){const n=this.services.get(t);if(!n)throw new Error(`No provider registered for token: ${t}`);return n}async unregister(t){this.services.delete(t)}has(t){return this.services.has(t)}list(){return Array.from(this.services.entries()).map(([t,n])=>({name:t,instance:n}))}}const ZS=/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[0-9a-f]{4}-[0-9a-f]{12}\./i;function YS(e,t){const n=t+".";return e.startsWith(n)||ZS.test(e)?e:n+e}let KS=0;function XS(e,t){const s={student_id:"teacher_preview",student_name:"Teacher (Preview)",class_id:"",attempt_id:`att_srcdoc_${t}_${Date.now()}_${++KS}`},r={uuid:t,name:"Whiteboard HTML Applet"};return`<!DOCTYPE html>
154
+ <html><head>
155
+ <script>
156
+ window.__LMS_STUDENT__ = ${JSON.stringify(s)};
157
+ window.__LMS_COURSEWARE__ = ${JSON.stringify(r)};
158
+ (function() {
159
+ try {
160
+ // Override window.postMessage (self-targeting, always works)
161
+ var origPM = window.postMessage;
162
+ window.postMessage = function(msg, targetOrigin, transfer) {
163
+ var origin = (targetOrigin === 'null' || targetOrigin === null) ? '*' : targetOrigin;
164
+ try { return origPM.call(this, msg, origin, transfer); }
165
+ catch(err) { if (err.name === 'SyntaxError') return origPM.call(this, msg, '*', transfer); throw err; }
166
+ };
167
+ // Shadow window.parent / window.top with Proxy to intercept .postMessage()
168
+ // Direct assignment (window.parent.postMessage = ...) silently fails on cross-origin WindowProxy
169
+ function proxyWin(realRef, propName) {
170
+ try {
171
+ var safePost = function(msg, targetOrigin, transfer) {
172
+ var origin = (targetOrigin === 'null' || targetOrigin === null) ? '*' : targetOrigin;
173
+ try { return realRef.postMessage.call(realRef, msg, origin, transfer); }
174
+ catch(err) { if (err.name === 'SyntaxError') return realRef.postMessage.call(realRef, msg, '*', transfer); throw err; }
175
+ };
176
+ var px = new Proxy(realRef, {
177
+ get: function(t, p) {
178
+ if (p === 'postMessage') return safePost;
179
+ try { var v = t[p]; return typeof v === 'function' ? v.bind(t) : v; } catch(e) { return undefined; }
180
+ }
181
+ });
182
+ Object.defineProperty(window, propName, { get: function() { return px; }, configurable: true });
183
+ } catch(e) {}
184
+ }
185
+ if (window.parent && window.parent !== window) proxyWin(window.parent, 'parent');
186
+ try { if (window.top && window.top !== window) proxyWin(window.top, 'top'); } catch(e) {}
187
+ } catch(e) {}
188
+ })();
189
+ <\/script>
190
+ <script src="/bridge.js"><\/script>
191
+ </head><body>
192
+ ${e||""}
193
+ </body></html>`}class ev{constructor(){this.loaders=new Map}register(t,n){this.loaders.set(t.id,{impl:t,pluginId:n})}unregister(t,n){const s=this.loaders.get(t);s&&(n&&s.pluginId!==n||this.loaders.delete(t))}unregisterPlugin(t){for(const[n,s]of this.loaders)s.pluginId===t&&this.loaders.delete(n)}resolve(t,n){for(const{impl:s}of this.loaders.values())try{const r=s.resolve(t,n);if(r)return r}catch{}return null}}const es=new ev,tv=4;let Wn=0;const oi=new Set;function Ma(){return Wn>=tv?null:(Wn+=1,()=>{Wn=Math.max(0,Wn-1);for(const e of oi)e()})}function nv(e){return oi.add(e),()=>{oi.delete(e)}}function sv(e,t){const[n,s]=p.useState(!e),[r,i]=p.useState(!1),o=p.useRef(null);return p.useEffect(()=>{if(!e||n)return;const a=t.current;if(!a)return;if(typeof IntersectionObserver>"u"){s(!0);return}const c=new IntersectionObserver(u=>{u.some(d=>d.isIntersecting)&&(s(!0),c.disconnect())},{rootMargin:"200px"});return c.observe(a),()=>c.disconnect()},[e,n,t]),p.useEffect(()=>{if(!n){o.current?.(),o.current=null,i(!1);return}const a=Ma();if(a)o.current=a,i(!0);else{const c=nv(()=>{const u=Ma();u&&(c(),o.current=u,i(!0))});return()=>c()}},[n]),p.useEffect(()=>()=>{o.current?.()},[]),r}function rv({data:e,lessonId:t,className:n,title:s,lazy:r=!0}){const i=et.useRef(null),o=sv(r,i),{theme:a}=cs(),c=()=>{ec(a,hi(a))},u=es.resolve(e,{lessonId:t}),d=e.coursewareUuid?`/runtime/${e.coursewareUuid}/`:e.resourceId?`/api/resources/${e.resourceId}/`:u??void 0;return l.jsx("div",{ref:i,className:n??"w-full h-full",children:o?l.jsx("iframe",{className:"w-full h-full border-none",src:d,srcDoc:d?void 0:XS(e.code||"",t),sandbox:"allow-scripts allow-forms allow-downloads",referrerPolicy:"no-referrer",title:s??e.title??"Interactive Courseware",credentialless:!0,onLoad:c}):l.jsx("div",{className:"w-full h-full flex items-center justify-center text-xs text-gray-400 bg-slate-50 rounded-xl",children:"课件未加载"})})}class iv{constructor(){this.renderers=new Map}register(t,n,s){this.renderers.set(t,{impl:n,pluginId:s})}get(t){return this.renderers.get(t)?.impl}has(t){return this.renderers.has(t)}unregister(t,n){const s=this.renderers.get(t);s&&(n&&s.pluginId!==n||this.renderers.delete(t))}unregisterPlugin(t){for(const[n,s]of this.renderers)s.pluginId===t&&this.renderers.delete(n)}}const ts=new iv,m0=({type:e,title:t,data:n,containerSize:s,onClose:r,lessonId:i})=>{et.useEffect(()=>{const d=f=>{f.key==="Escape"&&r()};return window.addEventListener("keydown",d),()=>window.removeEventListener("keydown",d)},[r]);const o=ts.get(e),[a,c]=p.useState({width:window.innerWidth,height:window.innerHeight});p.useEffect(()=>{const d=()=>c({width:window.innerWidth,height:window.innerHeight});return window.addEventListener("resize",d),()=>window.removeEventListener("resize",d)},[]);const u=l.jsx("div",{className:"fixed inset-0 z-[99999] bg-black/60 flex items-center justify-center",style:{pointerEvents:"auto"},children:l.jsxs("div",{className:"relative bg-white rounded-xl shadow-2xl overflow-hidden flex flex-col",style:{width:Math.max(400,a.width-32),height:Math.max(300,a.height-32)},children:[l.jsxs("div",{className:"bg-indigo-50 text-indigo-700 px-4 py-2 flex justify-between items-center text-sm font-semibold border-b border-indigo-100 shrink-0",children:[l.jsx("span",{className:"truncate",children:t}),l.jsxs("button",{onClick:r,className:"p-1.5 hover:bg-indigo-200/50 rounded-lg text-indigo-600 hover:text-indigo-900 transition-colors cursor-pointer flex items-center gap-1 text-xs",children:[l.jsx(rf,{size:14})," 退出全屏"]})]}),l.jsx("div",{className:"absolute top-3 right-3 z-10",children:l.jsx("button",{onClick:r,className:"w-8 h-8 flex items-center justify-center rounded-full bg-black/20 hover:bg-black/40 text-white transition-colors cursor-pointer",title:"关闭 (ESC)",children:l.jsx(At,{size:16})})}),l.jsx("div",{className:"flex-1 overflow-auto p-6",children:o?l.jsx(o,{elementType:e,data:n,onClose:r,containerSize:a,lessonId:i}):l.jsx(av,{elementType:e,data:n,onClose:r,containerSize:a,lessonId:i})})]})});return Ph.createPortal(u,document.body)},ov=[{field:"text",icon:"📝",label:"文本"},{field:"markdown",icon:"📄",label:"Markdown"},{field:"code",icon:"💻",label:"代码"},{field:"question",icon:"❓",label:"测验",extra:["options"]},{field:"equation",icon:"📐",label:"公式"},{field:"url",icon:"🔗",label:"链接"},{field:"src",icon:"🖼",label:"图片"},{field:"coursewareUuid",icon:"📚",label:"课件"}];function av({data:e,lessonId:t}){const n=ov.find(a=>e[a.field]!==void 0&&e[a.field]!==null&&e[a.field]!=="");if(!n)return l.jsxs("div",{className:"flex flex-col items-center justify-center h-full gap-4 text-gray-500",children:[l.jsx(ai,{size:48,className:"opacity-30"}),l.jsx("div",{className:"text-sm font-medium",children:"自动识别渲染"}),l.jsx("pre",{className:"text-xs text-left bg-gray-50 border rounded-lg p-4 max-w-full max-h-80 overflow-auto font-mono",children:JSON.stringify(e,null,2)})]});const{field:s,icon:r,label:i,extra:o}=n;if(s==="markdown")return l.jsx("div",{className:"prose prose-sm max-w-none",children:l.jsx(wx,{children:String(e.markdown)})});if(s==="code")return l.jsx("textarea",{value:String(e.code),readOnly:!0,className:"w-full h-full p-4 bg-gray-900 text-green-400 font-mono text-sm rounded-xl resize-none"});if(s==="text")return l.jsx("div",{className:"flex items-start h-full",children:l.jsx("div",{className:"text-lg whitespace-pre-wrap leading-relaxed",children:String(e.text)})});if(s==="question"){const a=Array.isArray(e.options)?e.options:[];return l.jsxs("div",{className:"max-w-2xl mx-auto space-y-6",children:[l.jsx("h3",{className:"text-xl font-bold text-gray-800",children:e.question}),l.jsx("div",{className:"flex flex-col gap-3",children:a.map((c,u)=>l.jsxs("div",{className:"px-5 py-4 text-left bg-gray-50 border-2 border-gray-200 rounded-xl text-base",children:[l.jsxs("span",{className:"font-bold text-indigo-600 mr-3",children:["ABCDEFGHIJKLMNOPQRSTUVWXYZ"[u],"."]}),c]},u))})]})}return s==="url"?l.jsx("div",{className:"flex items-center justify-center h-full",children:l.jsx("a",{href:String(e.url),target:"_blank",rel:"noopener noreferrer",className:"text-indigo-600 underline text-lg",children:String(e.url)})}):s==="src"?l.jsx("div",{className:"flex items-center justify-center h-full",children:l.jsx("img",{src:String(e.src),alt:"",className:"max-w-full max-h-full object-contain rounded-lg"})}):s==="coursewareUuid"?l.jsx(rv,{data:{coursewareUuid:String(e.coursewareUuid)},lessonId:t,className:"w-full h-full rounded-xl border"}):s==="equation"?l.jsx("div",{className:"flex items-center justify-center h-full",children:l.jsx("div",{className:"text-2xl font-mono text-gray-800 bg-gray-50 px-8 py-4 rounded-xl border",children:String(e.equation)})}):l.jsx("div",{className:"flex items-center justify-center h-full",children:l.jsxs("div",{className:"text-center",children:[l.jsx("div",{className:"text-4xl mb-2",children:r}),l.jsx("div",{className:"text-lg font-semibold text-gray-800",children:i}),l.jsx("pre",{className:"mt-4 text-xs text-gray-500 max-w-md overflow-auto",children:JSON.stringify(e,null,2)})]})})}class lv{constructor(){this.editors=new Map}register(t,n,s){this.editors.set(t,{impl:n,pluginId:s})}get(t){return this.editors.get(t)?.impl}has(t){return this.editors.has(t)}unregister(t,n){const s=this.editors.get(t);s&&(n&&s.pluginId!==n||this.editors.delete(t))}unregisterPlugin(t){for(const[n,s]of this.editors)s.pluginId===t&&this.editors.delete(n)}}const Mr=new lv,cv=["@openlearn/frontend:IFrontendAPI","@openlearn/frontend:ISocketService","@openlearn/frontend:IUIService","@openlearn/frontend:IStorageService","@openlearn/frontend:ISemesterGradeService"];class uv{constructor(t){this.registry=null,this.initialized=!1,this.sourceCodes=new Map,this.pluginModules=new Map,this.workerManager=null,this.moduleLoader=t?.moduleLoader??this.defaultModuleLoader}setWorkerManager(t){this.workerManager=t}async initialize(t,n,s,r){const i=new JS;await i.register(ua,t),await i.register(da,n),await i.register(ha,s),await i.register(fa,r),await i.register(Vx,new dv(t)),this.registry=i,this.initialized=!0,ve.getState().initialize(i)}getRegistry(){return this.registry}isInitialized(){return this.initialized}async installPlugin(t,n){this.sourceCodes.set(t.id,n),ve.getState().addPlugin({id:t.id,name:t.name,version:t.version,state:pe.INSTALLED,executionMode:"inline"})}async activateRemotePlugin(t,n){const s=ve.getState(),r=s.activePlugins.find(i=>i.id===t);if(!(r&&(r.state===pe.ACTIVE||r.state===pe.ACTIVATING))){s.updatePluginState(t,pe.ACTIVATING);try{const i=`/plugins/${t}/frontend.js`,o=await fetch(i);if(!o.ok)throw new Error(`Failed to fetch frontend.js for plugin "${t}": HTTP ${o.status}`);let a=await o.text();window.HostSharedDeps&&(a=a.replace(/import\s+(\w+)\s+from\s+['"]react['"];?/g,"const $1 = window.HostSharedDeps.React;").replace(/import\s+\*\s+as\s+(\w+)\s+from\s+['"]react['"];?/g,"const $1 = window.HostSharedDeps.React;").replace(/import\s+\{\s*([^}]+)\s*\}\s+from\s+['"]react['"];?/g,(h,g)=>`const { ${g} } = window.HostSharedDeps.React;`).replace(/import\s+\{\s*([^}]+)\s*\}\s+from\s+['"]lucide-react['"];?/g,(h,g)=>`const { ${g} } = window.HostSharedDeps.LucideReact;`).replace(/import\s+\{\s*([^}]+)\s*\}\s+from\s+['"]recharts['"];?/g,(h,g)=>`const { ${g} } = window.HostSharedDeps.Recharts;`));const c=new Blob([a],{type:"text/javascript"}),u=URL.createObjectURL(c);let d;try{d=await import(u)}finally{URL.revokeObjectURL(u)}const f=d.default??d;if(typeof f.activate!="function")throw new Error("Invalid remote frontend plugin: missing activate function");const m=await this.buildContext(t,n);await Promise.race([f.activate(m),new Promise((h,g)=>setTimeout(()=>g(new Error("Activation timeout (5000ms)")),5e3))]),this.pluginModules.set(t,{manifest:n,activate:f.activate,deactivate:typeof f.deactivate=="function"?f.deactivate:void 0}),s.updatePluginState(t,pe.ACTIVE)}catch(i){throw console.error(`[FrontendPluginHost] Failed to activate remote plugin "${t}":`,i),s.updatePluginState(t,pe.ERROR),this.unregisterPluginResources(t),i}}}async activatePlugin(t){const n=ve.getState(),s=n.activePlugins.find(r=>r.id===t);if(!s)throw new Error(`Plugin not found: ${t}`);if(s.executionMode==="worker")return this.activateWorkerPlugin(t,s);if(s.executionMode!=="inline")throw new Error(`Unsupported execution mode for activation: ${s.executionMode}`);n.updatePluginState(t,pe.ACTIVATING);try{const r=this.sourceCodes.get(t);if(!r)throw new Error(`No source code found for plugin: ${t}`);const i=await this.moduleLoader(r),o=i.default??i,a=o.manifest??i.manifest,c=o.activate??i.activate,u=o.deactivate??i.deactivate;if(!a||typeof c!="function")throw new Error("Invalid plugin: missing manifest or activate function");if(a.id!==t)throw new Error(`Manifest id mismatch: expected "${t}", got "${a.id}"`);if(a.classroomTools)for(const f of a.classroomTools)n.registerExtensionPoint("classroom.tool",{id:f.id,label:f.name,icon:f.icon,component:()=>Promise.resolve({default:(()=>null)}),pluginId:t});const d=await this.buildContext(t,a);await Promise.race([c(d),new Promise((f,m)=>setTimeout(()=>m(new Error("Activation timeout (5000ms)")),5e3))]),this.pluginModules.set(t,{manifest:a,activate:c,deactivate:typeof u=="function"?u:void 0}),n.updatePluginState(t,pe.ACTIVE)}catch(r){throw n.updatePluginState(t,pe.ERROR),this.unregisterPluginResources(t),r}}async activateWorkerPlugin(t,n){if(!this.workerManager)throw new Error(`Cannot activate plugin "${t}" in worker mode: BrowserWorkerManager not set. Call setWorkerManager() first.`);const s=ve.getState(),r=this.sourceCodes.get(t);if(!r)throw new Error(`No source code found for plugin: ${t}`);const i={id:t,name:n.name,version:n.version};s.updatePluginState(t,pe.ACTIVATING);try{let o;if(this.registry)try{o=await this.registry.resolve("@openlearn/frontend:ISocketService")}catch{}const{serviceHost:a}=await this.workerManager.createWorker(t,i,r,cv,o);this.pluginModules.set(t,{manifest:i,activate:async()=>{},deactivate:async()=>{await this.workerManager.terminateWorker(t)}}),s.updatePluginState(t,pe.ACTIVE)}catch(o){throw s.updatePluginState(t,pe.ERROR),this.unregisterPluginResources(t),o}}async deactivatePlugin(t){const n=ve.getState(),s=n.activePlugins.find(r=>r.id===t);if(!(!s||s.state!==pe.ACTIVE)){n.updatePluginState(t,pe.DEACTIVATING);try{const r=this.pluginModules.get(t);r?.deactivate&&await Promise.race([r.deactivate(),new Promise((i,o)=>setTimeout(()=>o(new Error("Deactivation timeout (5000ms)")),5e3))])}catch(r){console.error(`[FrontendPluginHost] Deactivation error for "${t}":`,r)}finally{this.unregisterPluginResources(t),this.pluginModules.delete(t),n.updatePluginState(t,pe.INACTIVE)}}}async uninstallPlugin(t){const n=ve.getState();n.activePlugins.find(r=>r.id===t)?.state===pe.ACTIVE&&await this.deactivatePlugin(t);try{await fetch(`/api/plugins/${t}`,{method:"DELETE"})}catch(r){console.error(`[FrontendPluginHost] Failed to DELETE plugin "${t}" on server:`,r)}this.sourceCodes.delete(t),this.pluginModules.delete(t),this.unregisterPluginResources(t),n.removePlugin(t)}getExtensions(t){return ve.getState().getExtensions(t)}unregisterPluginResources(t){ve.getState().unregisterPluginExtensionPoints(t),ts.unregisterPlugin(t),Mr.unregisterPlugin(t),es.unregisterPlugin(t)}async defaultModuleLoader(t){const n=new Blob([t],{type:"text/javascript"}),s=URL.createObjectURL(n);try{return await import(s)}finally{URL.revokeObjectURL(s)}}async buildContext(t,n){if(!this.registry)throw new Error("FrontendPluginHost not initialized");const s=await this.registry.resolve(ua),r=await this.registry.resolve(da),i=await this.registry.resolve(ha),o=await this.registry.resolve(fa);return{services:{frontendApi:s,socketService:r,uiService:i,storageService:o},pluginId:t,manifest:n,ui:{registerExtensionPoint:(a,c)=>{ve.getState().registerExtensionPoint(a,{...c,pluginId:t})},unregisterExtensionPoint:(a,c)=>{ve.getState().unregisterExtensionPoint(a,c)},registerFullscreenRenderer:(a,c)=>{ts.register(a,c,t)},unregisterFullscreenRenderer:a=>{ts.unregister(a,t)},registerPropertyEditor:(a,c)=>{Mr.register(a,c,t)},unregisterPropertyEditor:a=>{Mr.unregister(a,t)},registerCoursewareSource:a=>{es.register(a,t)},unregisterCoursewareSource:a=>{es.unregister(a,t)}},navigation:{getTeacherTab:()=>Ce.getState().teacherTab,setTeacherTab:a=>Ce.getState().setTeacherTab(a),setSelectedLesson:a=>Ce.getState().setSelectedLesson(a),subscribeTeacherTab:a=>{let c=Ce.getState().teacherTab;return Ce.subscribe(u=>{const d=u.teacherTab;d!==c&&(c=d,a(d))})}},context:{get:()=>{const a=Ce.getState();return{lessonId:a.selectedLesson,classId:a.liveClassSelectedClassId}},subscribe:a=>{const c=Ce.getState();let u={lessonId:c.selectedLesson,classId:c.liveClassSelectedClassId};return Ce.subscribe(d=>{const f={lessonId:d.selectedLesson,classId:d.liveClassSelectedClassId};(f.lessonId!==u.lessonId||f.classId!==u.classId)&&(u=f,a(f))})}},invokeCommand:async(a,c)=>{if(!s)throw new Error(`Plugin "${t}" cannot invoke command: frontendApi is not available. Has FrontendPluginHost initialized?`);const u=YS(a,n.id),d=await s.post("/api/plugins/execute-command",{type:u,payload:c});if(d.success&&d.result!==void 0)return d.result;throw new Error(d.error||"Command execution failed")},registerPanel:a=>{const c=a.slot||"teacher.dashboard.widget";ve.getState().registerExtensionPoint(c,{...a,pluginId:t})},registerMenu:a=>{const c=a.slot||"teacher.panel";ve.getState().registerExtensionPoint(c,{...a,pluginId:t})},registerToolbarButton:a=>{ve.getState().registerExtensionPoint("classroom.tool",{...a,pluginId:t})}}}}class dv{constructor(t){this.frontendApi=t}async saveSemesterGrade(t,n,s){const r=await this.frontendApi.post("/api/grade-sync",{lessonId:t,studentId:n,grade:s});if(!r.success)throw new Error(r.error||"Failed to sync semester grade")}}window.React=Fa;window.ReactDOM=Ba;window.HostSharedDeps={React:Fa,ReactDOM:Ba,Recharts:Bf,LucideReact:of};const hv=new uv;Th.createRoot(document.getElementById("root")).render(l.jsx(p.StrictMode,{children:l.jsx(Ex,{host:hv,children:l.jsx(QS,{})})}));export{Xx as A,u0 as C,Ix as D,h0 as E,m0 as F,rv as H,wx as M,Kf as P,ce as a,d0 as b,Xf as c,cs as d,p0 as e,Pw as f,Ax as g,ts as h,ec as i,hi as j,Xn as l,aw as m,Mr as p,YS as r,ve as u};