openlearn-next 0.3.22 → 0.4.0

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/README.md +1 -0
  2. package/dist/assets/AdminDirectoryView-DY--WM5Z.js +1 -0
  3. package/dist/assets/{BatchPickerModal-C9FH3J57.js → BatchPickerModal-BobcoTtn.js} +1 -1
  4. package/dist/assets/ClassesView-DtO0PJXQ.js +22 -0
  5. package/dist/assets/ClassroomCountdownWidget-AWnCu4JJ.js +2 -0
  6. package/dist/assets/CloudDriveModal-Dr4kDySU.js +1 -0
  7. package/dist/assets/ComputerLabView-1qWDNRQ2.js +1 -0
  8. package/dist/assets/CourseManagement-DtInD0J-.js +1 -0
  9. package/dist/assets/CourseWizardModal-B16QBckO.js +3 -0
  10. package/dist/assets/CoursewareHubPanel-CaEizhxl.js +1 -0
  11. package/dist/assets/Dashboard-D1gZ_4NI.js +8 -0
  12. package/dist/assets/{ExportWeightModal-C4d-0uTM.js → ExportWeightModal-UPsVax6L.js} +1 -1
  13. package/dist/assets/HelpTour-CMJbbGne.js +1 -0
  14. package/dist/assets/{HelpView-B9Pny6u9.js → HelpView-BryOHwLE.js} +4 -4
  15. package/dist/assets/{ImportLessonsModal-hKRuw9p4.js → ImportLessonsModal-Dnx_QR0Z.js} +1 -1
  16. package/dist/assets/{ImportModal-CVXHZ1Ei.js → ImportModal-D7L-KNhZ.js} +1 -1
  17. package/dist/assets/{InteractiveCoursewareViewer-DMMAs2k_.js → InteractiveCoursewareViewer-BYMKvIHi.js} +1 -1
  18. package/dist/assets/InteractiveWhiteboard-550JMFBu.js +77 -0
  19. package/dist/assets/LazyCourseware-CLHWQJ8g.js +2 -0
  20. package/dist/assets/LazyWhiteboard-DJWh6sdV.js +2 -0
  21. package/dist/assets/LessonEditorView-DRwi0sjA.js +1 -0
  22. package/dist/assets/LiveClassroomView-DgN2Zqe6.js +59 -0
  23. package/dist/assets/{NotificationDetailModal-1MOkBDr_.js → NotificationDetailModal-CMKHpWX1.js} +1 -1
  24. package/dist/assets/PluginView-BQVWPofY.js +66 -0
  25. package/dist/assets/{ProcessLogsModal-gZ9LILYM.js → ProcessLogsModal-DmFXg9mG.js} +1 -1
  26. package/dist/assets/QuizGeneratorModal-BeaBRn1w.js +1 -0
  27. package/dist/assets/StudentAssignmentView-Dn4Bgqr2.js +1 -0
  28. package/dist/assets/StudentLessonView-CMPqL1ia.js +1 -0
  29. package/dist/assets/StudentPreviewModal-0QSLnD9u.js +1 -0
  30. package/dist/assets/StudentView-9pjzjJgG.js +2 -0
  31. package/dist/assets/{SystemResourceLibraryModal-Ce-Dis6M.js → SystemResourceLibraryModal-COrhUd53.js} +1 -1
  32. package/dist/assets/TeacherView-mP2YucVr.js +2 -0
  33. package/dist/assets/{TimetableView-0VaTfpz3.js → TimetableView-BQG-rEb5.js} +4 -4
  34. package/dist/assets/index-C70OJPV_.js +217 -0
  35. package/dist/assets/index-CvGu7LSj.css +1 -0
  36. package/dist/assets/{index.es-CkgATcHw.js → index.es-C5eWEO4o.js} +1 -1
  37. package/dist/assets/{vendor-charts-U9fLlNC_.js → vendor-charts-qLbgF1eL.js} +1 -1
  38. package/dist/assets/{vendor-icons-30iiuCQb.js → vendor-icons-BRmhY6fg.js} +1 -1
  39. package/dist/assets/vendor-motion-BFAPOs-b.js +1 -0
  40. package/dist/assets/{vendor-pdf-Bw0ZQZtM.js → vendor-pdf-D7rGevI1.js} +3 -2
  41. package/dist/index.html +12 -13
  42. package/dist/server.cjs +4955 -623
  43. package/package.json +9 -4
  44. package/dist/assets/AdminDirectoryView-D-AOtp1o.js +0 -1
  45. package/dist/assets/ClassesView-DTuyCvYd.js +0 -19
  46. package/dist/assets/CloudDriveModal-Bi-aMuax.js +0 -1
  47. package/dist/assets/ComputerLabView-DWMtMSHV.js +0 -1
  48. package/dist/assets/CourseManagement-CeelAyst.js +0 -1
  49. package/dist/assets/CourseWizardModal-m7TDgcB2.js +0 -3
  50. package/dist/assets/CoursewareHubPanel-C4LQjt4v.js +0 -1
  51. package/dist/assets/Dashboard-CiBtG7Ge.js +0 -8
  52. package/dist/assets/HelpTour-00eT17Vg.js +0 -1
  53. package/dist/assets/InteractiveWhiteboard-jpweQ094.js +0 -77
  54. package/dist/assets/LazyCourseware-DVgyrg3r.js +0 -2
  55. package/dist/assets/LazyWhiteboard-BSzsAPXC.js +0 -2
  56. package/dist/assets/LessonEditorView-D4g48fr5.js +0 -1
  57. package/dist/assets/LiveClassroomView-HQGhVwd_.js +0 -1
  58. package/dist/assets/PluginView-D8cQ8mLM.js +0 -65
  59. package/dist/assets/QuizGeneratorModal-BFCJe1cm.js +0 -1
  60. package/dist/assets/StudentAssignmentView-C34nleZT.js +0 -1
  61. package/dist/assets/StudentLessonView-DNbu2o04.js +0 -1
  62. package/dist/assets/StudentPreviewModal-BXbKzQgo.js +0 -1
  63. package/dist/assets/StudentView-BF2WjF4_.js +0 -2
  64. package/dist/assets/TeacherView-BySyCiZG.js +0 -2
  65. package/dist/assets/index-C7jMgry5.js +0 -216
  66. package/dist/assets/index-huP36ZNf.css +0 -1
  67. package/dist/assets/vendor-motion-DjY2czvL.js +0 -1
  68. /package/dist/assets/{vendor-content-CYR4BTuT.js → purify.es-CYR4BTuT.js} +0 -0
@@ -1,216 +0,0 @@
1
- import{R as Je,r as p,j as o,u as $f,g as Dl,b as Bf,d as xi,h as yi,J as Xo,i as ea,k as Vf}from"./vendor-react-B0t7H3hh.js";import{G as js,S as Uf,U as Fl,C as bi,a as _n,L as wi,A as ta,b as Ln,c as Hi,P as Si,d as na,D as sa,X as tt,e as et,f as Mn,g as Hf,h as qf,T as $l,E as Ms,B as qi,R as Bl,i as Wf,j as rn,k as Gf,M as Qf,l as Jf,m as Zf,n as Yf,H as Vl,o as Kf,p as Xf,q as Ul,r as On,s as vi,t as ep,K as tp,u as np,v as hs,w as sp,x as Wi,y as rp,z as Gi,F as ip,I as op,J as ap,N as lp,O as Hl,Q as cp,V as up,W as dp,Y as hp,Z as fp,_ as Ns,$ as Fr,a0 as pp,a1 as mp,a2 as gp,a3 as xp,a4 as yp,a5 as Ci,a6 as ql,a7 as bp,a8 as ra,a9 as wp,aa as ia}from"./vendor-icons-30iiuCQb.js";import{_ as je,E as Sp}from"./vendor-pdf-Bw0ZQZtM.js";import{e as Qi,f as wt,h as Os}from"./vendor-utils-m0Urvtws.js";import{i as $r,g as vp,s as Wl,a as Ji,b as Gl,c as oa,d as Cp,e as kp,f as Ep,h as jp,r as Np,j as Tp,k as Ql,l as Pp,m as Ip,n as Ap,o as zp,S as _p,H as Lp,F as _t,p as Rp,q as Mp,t as Jl,u as Ts,v as aa,w as nt,x as Zl,y as Op,z as la,A as Dp,B as Ps,C as ki,D as ca,E as Fp,G as $p,I as Pt,J as Bp,K as Vp,L as Up,M as ua,N as Hp,O as qp,P as da,Q as Wp,R as Gp,T as fs,U as Qp,V as Jp,W as Yl,X as Zp,Y as Yp}from"./vendor-motion-DjY2czvL.js";import{v as Kl}from"./vendor-pptx-C5-U7ieS.js";import{R as ha}from"./vendor-charts-U9fLlNC_.js";const Kp=e=>{const t=e.split(/\r?\n/);if(t.length<2)return[];const n=t[0],s=[",",";"," "];let r=",",i=0;s.forEach(g=>{const y=n.split(g).length;y>i&&(i=y,r=g)});const a=g=>{const y=[];let k=!1,S="";for(let I=0;I<g.length;I++){const C=g[I];C==='"'?k=!k:C===r&&!k?(y.push(S.trim()),S=""):S+=C}return y.push(S.trim()),y},l=a(n).map(g=>g.toLowerCase().replace(/["'\r]/g,"").trim()),c=l.findIndex(g=>g.includes("student_number")||g.includes("studentnumber")||g.includes("student_id")||g.includes("studentid")||g.includes("学号")||g.includes("编号")||g.includes("id")&&!g.includes("class")&&!g.includes("lesson")),u=l.findIndex(g=>g.includes("name")||g.includes("姓名")||g.includes("student")&&!g.includes("num")&&!g.includes("id")||g.includes("学生")&&!g.includes("号")),d=l.findIndex(g=>g.includes("email")||g.includes("mail")||g.includes("邮箱")),h=u>=0?u:0,m=d>=0?d:1,f=[];for(let g=1;g<t.length;g++){if(!t[g].trim())continue;const y=a(t[g]),k=y[h]?y[h].replace(/["'\r]/g,"").trim():"",S=y[m]?y[m].replace(/["'\r]/g,"").trim():"",I=c>=0&&y[c]?y[c].replace(/["'\r]/g,"").trim():void 0;k&&f.push({name:k,email:S,...I?{student_number:I}:{}})}return f},fa={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"}},Xp=Je.memo(function({onLoginSuccess:t,lang:n}){const[s,r]=p.useState("teacher"),[i,a]=p.useState(null),[l,c]=p.useState(""),[u,d]=p.useState(""),[h,m]=p.useState(""),[f,g]=p.useState(!1),[y,k]=p.useState([]),[S,I]=p.useState(""),[C,T]=p.useState(""),[_,E]=p.useState(""),[R,B]=p.useState(""),[F,M]=p.useState(!1);p.useEffect(()=>{(async()=>{try{const P=await fetch("/api/students");if(P.ok){const j=await P.json();k(j),j.length>0&&I(j[0].id)}}catch(P){console.warn("Failed to fetch student roster for login selection:",P)}})()},[]),p.useEffect(()=>{(async()=>{try{const P=await fetch("/api/site-settings");if(P.ok){const j=await P.json();a(j)}}catch(P){console.warn("Failed to fetch site settings for login branding:",P)}})()},[]);const v=async L=>{if(L.preventDefault(),!l.trim()||!u){m(n==="zh"?"请输入完整的用户名和密码。":"Please fill in both key fields.");return}try{m(""),g(!0);const P=await fetch("/api/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({entrance:"teacher",username:l.trim(),password:u})});if(P.ok){const j=await P.json();t(j.session)}else{const j=await P.json();m(j.error||(n==="zh"?"用户名或密码不正确":"Invalid username or password"))}}catch{m(n==="zh"?"网络连接异常,请重试":"Network communication failure. Please try again.")}finally{g(!1)}},z=async L=>{L.preventDefault();const P=S||C.trim();if(!P){B(n==="zh"?"请选择或输入学号/学生标识。":"Please select or enter your Student ID.");return}if(!_.trim()){B(n==="zh"?"请输入个人密码或临时班级密码。":"Please enter your personal password or temporary class passcode.");return}try{B(""),M(!0);const j=await fetch("/api/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({entrance:"student",studentId:P,password:_.trim()})});if(j.ok){const A=await j.json();t(A.session)}else{const A=await j.json();B(A.error||(n==="zh"?"找不到该学生记录":"Student record not found"))}}catch{B(n==="zh"?"网络连接异常,请重试":"Network connection failure. Please try again.")}finally{M(!1)}};return o.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:[o.jsx("div",{className:"absolute top-[-10%] left-[-10%] w-[40rem] h-[40rem] rounded-full bg-indigo-500/10 blur-3xl -z-10"}),o.jsx("div",{className:"absolute bottom-[-10%] right-[-10%] w-[35rem] h-[35rem] rounded-full bg-violet-500/10 blur-3xl -z-10"}),o.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:[o.jsxs("div",{className:"text-center mb-8",children:[i?.logoUrl?o.jsx("img",{src:i.logoUrl,alt:i.siteName||"logo",className:"inline-block h-16 w-16 object-contain mb-4 rounded-xl"}):o.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:o.jsx(js,{size:32})}),o.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"," ",o.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"})]}),o.jsx("p",{className:"text-slate-400 text-xs sm:text-sm mt-2",children:i?.slogan||(n==="zh"?"下一代智能数字化学习系统":"Next-Generation Intelligent Digital Learning Platform")})]}),o.jsxs("div",{className:"flex bg-slate-900 p-1 rounded-xl border border-slate-800 gap-1 mb-6",children:[o.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:[o.jsx(Uf,{size:14}),n==="zh"?"教师与管理端":"Teacher / Staff Portal"]}),o.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:[o.jsx(Fl,{size:14}),n==="zh"?"学生自助端":"Student Self-Service"]})]}),s==="teacher"?o.jsxs("form",{onSubmit:v,className:"space-y-4",children:[h&&o.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:[o.jsx(bi,{size:15,className:"shrink-0"}),o.jsx("span",{children:h})]}),o.jsxs("div",{className:"space-y-1.5",children:[o.jsxs("label",{className:"text-xs font-medium text-slate-400 flex items-center gap-1.5",children:[o.jsx(_n,{size:13}),n==="zh"?"教工账户名 / username":"Staff Username"]}),o.jsx("input",{type:"text",value:l,onChange:L=>c(L.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})]}),o.jsxs("div",{className:"space-y-1.5",children:[o.jsxs("label",{className:"text-xs font-medium text-slate-400 flex items-center gap-1.5",children:[o.jsx(wi,{size:13}),n==="zh"?"输入登录密码 / password":"Access Password"]}),o.jsx("input",{type:"password",value:u,onChange:L=>d(L.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})]}),o.jsxs("button",{type:"submit",disabled:f,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:[o.jsx("span",{children:f?n==="zh"?"鉴权登录中...":"Authorizing...":n==="zh"?"安全验证登录":"Authorized Sign In"}),o.jsx(ta,{size:15})]})]}):o.jsxs("form",{onSubmit:z,className:"space-y-4",children:[R&&o.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:[o.jsx(bi,{size:15,className:"shrink-0"}),o.jsx("span",{children:R})]}),y.length>0?o.jsxs("div",{className:"space-y-1.5",children:[o.jsxs("label",{className:"text-xs font-medium text-slate-400 flex items-center gap-1.5",children:[o.jsx(js,{size:14}),n==="zh"?"从学生花名册中快速选择":"Quick Access Student Select"]}),o.jsx("select",{value:S,onChange:L=>{I(L.target.value),T("")},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:y.map(L=>o.jsxs("option",{value:L.id,children:[L.name," (",L.student_number||L.id,")"]},L.id))}),o.jsx("p",{className:"text-xs text-slate-500 font-medium",children:n==="zh"?"✨ 在沙盒调试中,你可以直接下拉选择已有的学生账户一键登录为该生。":"✨ Sandbox help: Quick select existing students on file to simulate as student."})]}):null,o.jsxs("div",{className:"relative flex py-2 items-center",children:[o.jsx("div",{className:"flex-grow border-t border-slate-850"}),o.jsx("span",{className:"flex-shrink mx-3 text-xs font-bold text-slate-500 uppercase tracking-wider",children:n==="zh"?"或手动输入学号":"Or input key manually"}),o.jsx("div",{className:"flex-grow border-t border-slate-850"})]}),o.jsxs("div",{className:"space-y-1.5",children:[o.jsxs("label",{className:"text-xs font-medium text-slate-400 flex items-center gap-1.5",children:[o.jsx(_n,{size:13}),n==="zh"?"学号 / Student ID":"Student Access Key"]}),o.jsx("input",{type:"text",value:C,onChange:L=>{T(L.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"})]}),o.jsxs("div",{className:"space-y-1.5",children:[o.jsxs("label",{className:"text-xs font-medium text-slate-400 flex items-center gap-1.5",children:[o.jsx(wi,{size:13}),n==="zh"?"个人密码 / 临时班级密码":"Personal Password / Class Passcode"]}),o.jsx("input",{type:"password",required:!0,value:_,onChange:L=>E(L.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"})]}),o.jsxs("button",{type:"submit",disabled:F,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:[o.jsx("span",{children:F?n==="zh"?"正在连接学生终端...":"Entering Desk...":n==="zh"?"登录学生智慧桌面":"Login Interactive Desk"}),o.jsx(ta,{size:15})]})]})]})]})});function em({session:e,lang:t,onLogout:n,onProfile:s}){const[r,i]=p.useState(!1),a=p.useRef(null);p.useEffect(()=>{if(!r)return;const c=u=>{a.current&&!a.current.contains(u.target)&&i(!1)};return document.addEventListener("mousedown",c),()=>document.removeEventListener("mousedown",c)},[r]);const l=(c,u)=>t==="zh"?c:u;return o.jsxs("div",{className:"relative",ref:a,children:[o.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:[o.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?o.jsx("img",{src:e.avatar,alt:e.name,className:"w-full h-full object-cover"}):o.jsx(_n,{size:20})}),o.jsx(Ln,{size:14,className:`text-gray-400 transition-transform duration-200 ${r?"rotate-180":""}`})]}),r&&o.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:[o.jsxs("div",{className:"px-4 py-2 border-b border-gray-100",children:[o.jsx("p",{className:"text-sm font-semibold text-gray-800 truncate",title:e.name,children:e.name}),o.jsx("p",{className:"text-xs text-gray-400 truncate",children:e.username})]}),o.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:[o.jsx(_n,{size:16,className:"text-gray-400"}),l("个人资料","Profile")]}),o.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:[o.jsx(Hi,{size:16}),l("注销登录","Sign Out")]})]})]})}const tm=[{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"}],ps={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"}},Br="openlearn_theme",Sn="openlearn_custom_themes",Is={};function Zi(e){return Is[e]?Is[e]:e in ps?ps[e]:ps.light}function Vr(e){typeof document>"u"||document.documentElement.setAttribute("data-theme",e)}function nm(e,t){if(typeof document>"u")return;Is[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,a])=>` ${i}: ${a};`).join(`
2
- `);s.textContent=`[data-theme="${e}"] {
3
- ${r}
4
- }`}function sm(e){if(typeof document>"u")return;delete Is[e];const t=document.getElementById(`openlearn-custom-theme-${e}`);t&&t.parentNode&&t.parentNode.removeChild(t)}function Ur(e){if(!(typeof window>"u"))try{setTimeout(async()=>{try{const{broadcastThemeToIframes:t}=await je(async()=>{const{broadcastThemeToIframes:n}=await Promise.resolve().then(()=>iu);return{broadcastThemeToIframes:n}},void 0);t(e,Zi(e))}catch{}},0)}catch{}}const Ds=Qi((e,t)=>({theme:"light",availableThemes:[...tm],initTheme:()=>{if(typeof window>"u")return;try{const r=localStorage.getItem(Sn);if(r){const i=JSON.parse(r);Array.isArray(i)&&i.forEach(a=>{a&&a.spec&&a.spec.id&&t().registerTheme(a.spec,a.cssVariables)})}}catch{}const s=localStorage.getItem(Br)||"light";Vr(s),e({theme:s}),Ur(s)},setTheme:n=>{Vr(n),typeof window<"u"&&localStorage.setItem(Br,n),e({theme:n}),Ur(n)},registerTheme:(n,s)=>{s&&nm(n.id,s),e(r=>({availableThemes:[...r.availableThemes.filter(a=>a.id!==n.id),n]}))},unregisterTheme:n=>{sm(n),e(s=>{const r=s.availableThemes.filter(a=>a.id!==n),i=s.theme===n?"light":s.theme;return s.theme===n&&(Vr("light"),typeof window<"u"&&localStorage.setItem(Br,"light"),Ur("light")),{availableThemes:r,theme:i}})},saveCustomTheme:(n,s)=>{if(t().registerTheme(n,s),typeof window<"u")try{const r=localStorage.getItem(Sn);let i=r?JSON.parse(r):[];Array.isArray(i)||(i=[]),i=i.filter(a=>a.spec.id!==n.id),i.push({spec:n,cssVariables:s}),localStorage.setItem(Sn,JSON.stringify(i))}catch{}t().setTheme(n.id)},deleteCustomTheme:n=>{if(typeof window<"u")try{const s=localStorage.getItem(Sn);if(s){let r=JSON.parse(s);Array.isArray(r)&&(r=r.filter(i=>i.spec.id!==n),localStorage.setItem(Sn,JSON.stringify(r)))}}catch{}t().unregisterTheme(n)}})),rm=[{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"}}],pa={...ps.light};function im({isOpen:e,onClose:t,lang:n="zh"}){const{availableThemes:s,saveCustomTheme:r,deleteCustomTheme:i}=Ds(),a=p.useId(),[l,c]=p.useState("custom-mytheme"),[u,d]=p.useState("我的专属主题"),[h,m]=p.useState("自定义教学调色板配置"),[f,g]=p.useState({...pa}),[y,k]=p.useState("none"),[S,I]=p.useState(""),[C,T]=p.useState(!1),[_,E]=p.useState(null);if(!e)return null;const R=s.filter(N=>N.category==="custom"),B=N=>{E(N),setTimeout(()=>E(null),3e3)},F=N=>{c(N.id),d(N.label),m(N.description),g({...N.tokens}),B(`已载入预设: ${N.label}`)},M=N=>{c(N.id),d(N.label),m(N.description);const O=Zi(N.id);O&&Object.keys(O).length>0&&g({...O}),B(`已载入自定义主题: ${N.label}`)},v=(N,O)=>{g(x=>({...x,[N]:O}))},z=()=>{const N=l.trim().toLowerCase().replace(/[^a-z0-9_-]/g,"-");if(!N){alert("请输入有效的主题标识 (ID)");return}const O={id:N,label:u.trim()||"未命名主题",description:h.trim()||"自定义主题",previewBg:f["--bg-app"]||"#ffffff",previewPrimary:f["--color-primary"]||"#4f46e5",category:"custom"};r(O,f),B(`主题「${O.label}」已保存并成功激活!`)},L=()=>{I(JSON.stringify({version:"1.0",id:l,label:u,description:h,tokens:f},null,2)),k("export")},P=()=>{I(""),k("import")},j=()=>{try{const N=JSON.parse(S);if(!N.tokens||typeof N.tokens!="object")throw new Error("缺少合法的 tokens 字段");N.id&&c(N.id),N.label&&d(N.label),N.description&&m(N.description),g(O=>({...O,...N.tokens})),k("none"),B("主题配置导入成功!")}catch(N){alert(`导入失败: ${N.message||"JSON 格式解析错误"}`)}},A=()=>{navigator.clipboard.writeText(S),T(!0),setTimeout(()=>T(!1),2e3)},U=[{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 o.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:o.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:[o.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-theme shrink-0 bg-surface",children:[o.jsxs("div",{className:"flex items-center gap-3",children:[o.jsx("div",{className:"p-2 bg-primary-theme/10 rounded-xl text-primary-theme",children:o.jsx(Si,{size:22})}),o.jsxs("div",{children:[o.jsxs("h2",{className:"text-lg font-bold flex items-center gap-2 text-main",children:[n==="zh"?"主题可视化设计器":"Theme Visual Designer",o.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"})]}),o.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"})]})]}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsxs("button",{onClick:P,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:[o.jsx(na,{size:14}),n==="zh"?"导入配置":"Import"]}),o.jsxs("button",{onClick:L,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:[o.jsx(sa,{size:14}),n==="zh"?"导出配置":"Export"]}),o.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:o.jsx(tt,{size:18})})]})]}),_&&o.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:[o.jsx(et,{size:14}),_]}),o.jsxs("div",{className:"flex-1 flex flex-col md:flex-row overflow-hidden",children:[o.jsxs("div",{className:"w-full md:w-1/2 border-r border-theme overflow-y-auto p-6 space-y-6",children:[o.jsxs("section",{className:"space-y-3",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsxs("label",{className:"text-xs font-bold uppercase tracking-wider text-muted flex items-center gap-1.5",children:[o.jsx(Mn,{size:14,className:"text-amber-500"}),n==="zh"?"创意预设配色":"Creative Presets"]}),o.jsx("span",{className:"text-xs text-muted",children:"一键填入调色板"})]}),o.jsx("div",{className:"grid grid-cols-2 gap-2.5",children:rm.map(N=>o.jsxs("button",{onClick:()=>F(N),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:[o.jsxs("div",{className:"flex items-center justify-between w-full",children:[o.jsxs("div",{className:"font-semibold text-xs text-main flex items-center gap-2",children:[o.jsx("span",{className:"w-3 h-3 rounded-full border border-black/10 shrink-0",style:{backgroundColor:N.tokens["--color-primary"]}}),N.label]}),o.jsxs("div",{className:"flex items-center gap-1",children:[o.jsx("span",{className:"w-2.5 h-2.5 rounded-xs",style:{backgroundColor:N.tokens["--bg-app"]}}),o.jsx("span",{className:"w-2.5 h-2.5 rounded-xs",style:{backgroundColor:N.tokens["--bg-surface"]}})]})]}),o.jsx("p",{className:"text-xs text-muted mt-1.5 line-clamp-2 leading-relaxed opacity-85",children:N.description})]},N.id))})]}),o.jsxs("section",{className:"space-y-3 pt-2 border-t border-theme-subtle",children:[o.jsxs("label",{className:"text-xs font-bold uppercase tracking-wider text-muted flex items-center gap-1.5",children:[o.jsx(Hf,{size:14,className:"text-primary-theme"}),n==="zh"?"主题基础信息":"Theme Metadata"]}),o.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[o.jsxs("div",{children:[o.jsx("label",{htmlFor:`${a}-themeId`,className:"block text-xs font-medium text-muted mb-1",children:"主题标识 (ID)"}),o.jsx("input",{id:`${a}-themeId`,type:"text",value:l,onChange:N=>c(N.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"})]}),o.jsxs("div",{children:[o.jsx("label",{htmlFor:`${a}-label`,className:"block text-xs font-medium text-muted mb-1",children:"主题名称"}),o.jsx("input",{id:`${a}-label`,type:"text",value:u,onChange:N=>d(N.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"})]})]}),o.jsxs("div",{children:[o.jsx("label",{htmlFor:`${a}-description`,className:"block text-xs font-medium text-muted mb-1",children:"主题描述"}),o.jsx("input",{id:`${a}-description`,type:"text",value:h,onChange:N=>m(N.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"})]})]}),o.jsxs("section",{className:"space-y-3 pt-2 border-t border-theme-subtle",children:[o.jsxs("label",{className:"text-xs font-bold uppercase tracking-wider text-muted flex items-center gap-1.5",children:[o.jsx(Si,{size:14,className:"text-primary-theme"}),n==="zh"?"色彩变量调节 (Design Tokens)":"CSS Variables Token Tuning"]}),o.jsx("div",{className:"space-y-2.5",children:U.map(N=>{const O=f[N.key]||"#000000";return o.jsxs("div",{className:"flex items-center justify-between p-2.5 rounded-xl border border-theme hover:bg-surface-secondary/40 transition-colors",children:[o.jsxs("div",{className:"flex-1 min-w-0 pr-3",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("span",{className:"text-xs font-medium text-main",children:N.labelZh}),o.jsx("span",{className:"text-xs font-mono text-muted bg-surface-secondary px-1.5 py-0.5 rounded",children:N.key})]}),o.jsx("p",{className:"text-xs text-muted mt-0.5",children:N.desc})]}),o.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[o.jsx("div",{className:"relative flex items-center",children:o.jsx("input",{type:"color",value:O.startsWith("#")&&O.length===7?O:"#4f46e5",onChange:x=>v(N.key,x.target.value),className:"w-8 h-8 rounded-lg cursor-pointer border border-theme p-0.5 bg-surface",title:"打开系统拾色器"})}),o.jsx("input",{type:"text",value:O,onChange:x=>v(N.key,x.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"})]})]},N.key)})})]}),R.length>0&&o.jsxs("section",{className:"space-y-3 pt-2 border-t border-theme-subtle",children:[o.jsxs("label",{className:"text-xs font-bold uppercase tracking-wider text-muted flex items-center gap-1.5",children:[o.jsx(qf,{size:14,className:"text-primary-theme"}),n==="zh"?"已创建的自定义主题":"Saved Custom Themes"]}),o.jsx("div",{className:"space-y-2",children:R.map(N=>o.jsxs("div",{className:"flex items-center justify-between p-2.5 rounded-xl border border-theme bg-surface-secondary/30",children:[o.jsxs("div",{className:"flex items-center gap-2.5 min-w-0",children:[o.jsx("span",{className:"w-3.5 h-3.5 rounded-full border border-black/10 shrink-0",style:{backgroundColor:N.previewPrimary}}),o.jsxs("div",{className:"truncate",children:[o.jsx("div",{className:"text-xs font-semibold text-main truncate",children:N.label}),o.jsx("div",{className:"text-xs text-muted truncate",children:N.description})]})]}),o.jsxs("div",{className:"flex items-center gap-1.5 shrink-0 ml-2",children:[o.jsx("button",{onClick:()=>M(N),className:"px-2 py-1 text-xs rounded-md bg-surface border border-theme hover:bg-surface-secondary text-main transition-colors cursor-pointer",children:"编辑"}),o.jsx("button",{onClick:()=>{confirm(`确定删除自定义主题「${N.label}」吗?`)&&(i(N.id),B(`已删除主题「${N.label}」`))},className:"p-1 text-muted hover:text-red-500 rounded-md transition-colors cursor-pointer",title:"删除",children:o.jsx($l,{size:13})})]})]},N.id))})]})]}),o.jsxs("div",{className:"w-full md:w-1/2 flex flex-col p-6 bg-surface-secondary/30 overflow-y-auto",children:[o.jsxs("div",{className:"flex items-center justify-between mb-3 shrink-0",children:[o.jsxs("div",{className:"flex items-center gap-1.5 text-xs font-bold uppercase tracking-wider text-muted",children:[o.jsx(Ms,{size:14,className:"text-primary-theme"}),n==="zh"?"拟真沙盒视口 (Live Sandbox)":"Live Sandbox Preview"]}),o.jsxs("span",{className:"text-xs text-muted font-mono",children:["当前预览: ",u," (",l,")"]})]}),o.jsxs("div",{className:"flex-1 rounded-2xl border shadow-inner overflow-hidden flex flex-col transition-colors duration-200",style:{backgroundColor:f["--bg-app"]||"#f8fafc",borderColor:f["--border-theme"]||"#e2e8f0",color:f["--text-main"]||"#0f172a"},children:[o.jsxs("div",{className:"h-12 border-b px-4 flex items-center justify-between shrink-0",style:{backgroundColor:f["--bg-surface"]||"#ffffff",borderColor:f["--border-theme"]||"#e2e8f0"},children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("div",{className:"w-6 h-6 rounded-lg flex items-center justify-center font-bold text-white text-xs",style:{backgroundColor:f["--color-primary"]||"#4f46e5"},children:"OL"}),o.jsx("span",{className:"font-bold text-xs",style:{color:f["--text-main"]},children:"OpenLearn V2"})]}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("div",{className:"text-xs px-2 py-0.5 rounded-md font-mono",style:{backgroundColor:f["--bg-surface-secondary"]||"#f1f5f9",color:f["--text-muted"]||"#64748b"},children:"10:30:00"}),o.jsx("div",{className:"w-6 h-6 rounded-full flex items-center justify-center text-xs font-bold text-white",style:{backgroundColor:f["--color-primary"]||"#4f46e5"},children:"T"})]})]}),o.jsxs("div",{className:"p-4 space-y-4 flex-1 overflow-y-auto",children:[o.jsxs("div",{className:"p-4 rounded-xl border shadow-xs space-y-3",style:{backgroundColor:f["--bg-surface"]||"#ffffff",borderColor:f["--border-theme"]||"#e2e8f0"},children:[o.jsxs("div",{className:"flex items-start justify-between",children:[o.jsxs("div",{children:[o.jsx("h4",{className:"font-bold text-sm",style:{color:f["--text-main"]},children:"高中物理实验探究:机械能守恒定律"}),o.jsx("p",{className:"text-xs mt-1",style:{color:f["--text-muted"]},children:"DIS 光电门传感器毫秒级数据回传与曲线拟合分析"})]}),o.jsx("span",{className:"text-xs px-2 py-0.5 rounded-full font-medium",style:{backgroundColor:f["--bg-surface-secondary"],color:f["--color-primary"],border:`1px solid ${f["--border-theme"]}`},children:"进行中"})]}),o.jsxs("div",{className:"grid grid-cols-3 gap-2 pt-1",children:[o.jsxs("div",{className:"p-2 rounded-lg",style:{backgroundColor:f["--bg-surface-secondary"]},children:[o.jsx("div",{className:"text-xs",style:{color:f["--text-muted"]},children:"光电门测速 (v)"}),o.jsx("div",{className:"text-sm font-bold font-mono mt-0.5",style:{color:f["--text-main"]},children:"2.43 m/s"})]}),o.jsxs("div",{className:"p-2 rounded-lg",style:{backgroundColor:f["--bg-surface-secondary"]},children:[o.jsx("div",{className:"text-xs",style:{color:f["--text-muted"]},children:"动能增量 (ΔEk)"}),o.jsx("div",{className:"text-sm font-bold font-mono mt-0.5",style:{color:f["--color-primary"]},children:"0.589 J"})]}),o.jsxs("div",{className:"p-2 rounded-lg",style:{backgroundColor:f["--bg-surface-secondary"]},children:[o.jsx("div",{className:"text-xs",style:{color:f["--text-muted"]},children:"误差率 (Err)"}),o.jsx("div",{className:"text-sm font-bold font-mono mt-0.5",style:{color:f["--text-main"]},children:"0.84 %"})]})]}),o.jsxs("div",{className:"flex items-center gap-2 pt-2",children:[o.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:f["--color-primary"]||"#4f46e5"},children:"开始数据采集"}),o.jsx("button",{className:"px-3 py-1.5 rounded-lg text-xs font-medium border transition-colors cursor-pointer",style:{backgroundColor:f["--bg-surface-elevated"]||"#ffffff",borderColor:f["--border-theme"]||"#e2e8f0",color:f["--text-main"]||"#0f172a"},children:"重置实验"}),o.jsx("button",{className:"px-2 py-1.5 rounded-lg text-xs transition-colors cursor-pointer",style:{color:f["--text-muted"]},children:"查看教案"})]})]}),o.jsxs("div",{className:"p-3 rounded-xl border space-y-2",style:{backgroundColor:f["--bg-surface-elevated"]||"#ffffff",borderColor:f["--border-theme-subtle"]||"#f1f5f9"},children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsx("span",{className:"text-xs font-semibold",style:{color:f["--text-main"]},children:"互动白板区域 (Whiteboard Canvas)"}),o.jsx("span",{className:"text-xs font-mono",style:{color:f["--text-muted"]},children:"60 FPS"})]}),o.jsxs("div",{className:"h-28 rounded-lg border border-dashed flex items-center justify-center p-3 relative overflow-hidden",style:{backgroundColor:f["--bg-app"],borderColor:f["--border-theme"]},children:[o.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:f["--color-primary"]},children:o.jsx(qi,{size:20})}),o.jsx("div",{className:"absolute bottom-2 right-2 text-xs font-mono px-1.5 py-0.5 rounded border",style:{backgroundColor:f["--bg-surface"],borderColor:f["--border-theme"],color:f["--text-muted"]},children:"iframe Bridge Sync Ready"})]})]})]})]})]})]}),o.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-t border-theme shrink-0 bg-surface",children:[o.jsx("div",{className:"flex items-center gap-2",children:o.jsxs("button",{onClick:()=>{g({...pa}),B("已重置为系统默认调色板")},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:[o.jsx(Bl,{size:14}),n==="zh"?"重置默认":"Reset Defaults"]})}),o.jsxs("div",{className:"flex items-center gap-3",children:[o.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"}),o.jsxs("button",{onClick:z,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:[o.jsx(Wf,{size:15}),n==="zh"?"保存并激活主题":"Save & Activate Theme"]})]})]}),y!=="none"&&o.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:o.jsxs("div",{className:"bg-surface border border-theme rounded-2xl p-5 w-full max-w-lg shadow-2xl space-y-4",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsx("h3",{className:"font-bold text-sm text-main flex items-center gap-2",children:y==="export"?o.jsxs(o.Fragment,{children:[o.jsx(sa,{size:16,className:"text-primary-theme"}),n==="zh"?"导出主题配置 JSON":"Export Theme JSON"]}):o.jsxs(o.Fragment,{children:[o.jsx(na,{size:16,className:"text-primary-theme"}),n==="zh"?"导入主题配置 JSON":"Import Theme JSON"]})}),o.jsx("button",{onClick:()=>k("none"),className:"p-1 rounded-md text-muted hover:text-main cursor-pointer",children:o.jsx(tt,{size:16})})]}),o.jsx("div",{children:o.jsx("textarea",{value:S,readOnly:y==="export",onChange:N=>I(N.target.value),placeholder:y==="import"?"请在此粘贴主题导出的 JSON 字符串...":"",rows:10,className:"w-full p-3 font-mono text-xs rounded-xl border border-theme bg-surface-secondary text-main focus:outline-none focus:ring-1 focus:ring-primary-theme resize-none"})}),o.jsx("div",{className:"flex items-center justify-end gap-2",children:y==="export"?o.jsx(o.Fragment,{children:o.jsxs("button",{onClick:A,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:[C?o.jsx(et,{size:14}):o.jsx(rn,{size:14}),C?n==="zh"?"已复制":"Copied":n==="zh"?"复制到剪贴板":"Copy"]})}):o.jsxs(o.Fragment,{children:[o.jsx("button",{onClick:()=>k("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"}),o.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 om({lang:e="zh"}){const[t,n]=p.useState(!1),[s,r]=p.useState(!1),i=p.useRef(null),{theme:a,availableThemes:l,setTheme:c}=Ds();p.useEffect(()=>{function d(h){i.current&&!i.current.contains(h.target)&&n(!1)}return t&&document.addEventListener("mousedown",d),()=>{document.removeEventListener("mousedown",d)}},[t]);const u=d=>{switch(d){case"dark":return o.jsx(Qf,{size:16,className:"text-indigo-400"});case"eyecare":return o.jsx(Ms,{size:16,className:"text-emerald-500"});case"chalkboard":return o.jsx(Si,{size:16,className:"text-green-400"});case"light":default:return o.jsx(Gf,{size:16,className:"text-amber-500"})}};return o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"relative",ref:i,children:[o.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(a)}),t&&o.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:[o.jsxs("div",{className:"px-3 py-2 border-b border-theme-subtle mb-1",children:[o.jsx("div",{className:"text-xs font-semibold text-main uppercase tracking-wider",children:e==="zh"?"界面主题模式":"Interface Theme"}),o.jsx("div",{className:"text-xs text-muted mt-0.5",children:e==="zh"?"针对不同教学采光与场景优化":"Optimized for diverse lighting"})]}),o.jsx("div",{className:"space-y-1",children:l.map(d=>{const h=a===d.id;return o.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 ${h?"bg-surface-secondary text-main font-semibold shadow-xs":"text-muted hover:bg-surface-secondary hover:text-main"}`,children:[o.jsxs("div",{className:"flex items-center gap-2.5",children:[o.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}}),o.jsxs("div",{children:[o.jsx("div",{className:"font-medium text-main leading-none",children:d.label}),o.jsx("div",{className:"text-xs text-muted mt-1 leading-tight opacity-80",children:d.description})]})]}),h&&o.jsx(et,{size:14,className:"text-primary-theme shrink-0"})]},d.id)})}),o.jsx("div",{className:"pt-2 mt-1 border-t border-theme-subtle",children:o.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:[o.jsx(Mn,{size:14}),o.jsx("span",{children:e==="zh"?"🎨 自定义主题设计器...":"🎨 Theme Designer..."})]})})]})]}),o.jsx(im,{isOpen:s,onClose:()=>r(!1),lang:e})]})}const Hr="openlearn_font_scale",en=85,tn=140,qr=5,ms=100,ma=[{scale:90,labelZh:"紧凑 (90%)",labelEn:"Compact (90%)"},{scale:100,labelZh:"标准 (100%)",labelEn:"Standard (100%)"},{scale:110,labelZh:"中大 (110%)",labelEn:"Medium (110%)"},{scale:120,labelZh:"大号 (120%)",labelEn:"Large (120%)"},{scale:130,labelZh:"特大 (130%)",labelEn:"Extra Large (130%)"}];function Wr(e){if(typeof document>"u")return;const t=Math.min(tn,Math.max(en,Math.round(e)));document.documentElement.style.fontSize=`${t}%`,document.documentElement.style.setProperty("--app-font-scale",(t/100).toFixed(2)),document.documentElement.setAttribute("data-font-scale",String(t))}function Gr(e){if(!(typeof window>"u"))try{setTimeout(async()=>{try{const{broadcastFontScaleToIframes:t}=await je(async()=>{const{broadcastFontScaleToIframes:n}=await Promise.resolve().then(()=>iu);return{broadcastFontScaleToIframes:n}},void 0);t(e)}catch{}},0)}catch{}}const sn=Qi((e,t)=>({scale:ms,minScale:en,maxScale:tn,step:qr,initFontSize:()=>{if(typeof window>"u")return;let n=ms;try{const s=localStorage.getItem(Hr);if(s){const r=Number(s);!isNaN(r)&&r>=en&&r<=tn&&(n=r)}}catch{}Wr(n),e({scale:n}),Gr(n);try{window.addEventListener("storage",s=>{if(s.key===Hr&&s.newValue){const r=Number(s.newValue);!isNaN(r)&&r>=en&&r<=tn&&(Wr(r),e({scale:r}),Gr(r))}})}catch{}},setScale:n=>{const s=Math.min(tn,Math.max(en,Math.round(n)));if(Wr(s),typeof window<"u")try{localStorage.setItem(Hr,String(s))}catch{}e({scale:s}),Gr(s)},increaseScale:()=>{const n=t().scale,s=Math.min(tn,n+qr);t().setScale(s)},decreaseScale:()=>{const n=t().scale,s=Math.max(en,n-qr);t().setScale(s)},resetScale:()=>{t().setScale(ms)}}));function Xl({lang:e="zh"}){const[t,n]=p.useState(!1),s=p.useRef(null),{scale:r,minScale:i,maxScale:a,setScale:l,increaseScale:c,decreaseScale:u,resetScale:d}=sn();p.useEffect(()=>{function f(g){s.current&&!s.current.contains(g.target)&&n(!1)}return t&&document.addEventListener("mousedown",f),()=>{document.removeEventListener("mousedown",f)}},[t]);const h=ma.find(f=>f.scale===r),m=r===ms;return o.jsxs("div",{className:"relative",ref:s,children:[o.jsxs("button",{type:"button",onClick:()=>n(!t),title:e==="zh"?`界面字体缩放: ${r}%(点击调节)`:`Interface Font Scaling: ${r}% (Click to adjust)`,className:`p-2 hover:bg-surface-secondary transition-colors rounded-lg border shadow-3xs flex items-center justify-center shrink-0 cursor-pointer relative ${m?"bg-surface border-theme text-main":"bg-primary-theme-light border-primary-theme text-primary-theme font-bold"}`,"aria-label":"Font size selector","aria-expanded":t,children:[o.jsx(Jf,{size:16}),!m&&o.jsxs("span",{className:"absolute -bottom-1 -right-1 text-xs px-1 py-0.2 rounded-full bg-primary-theme text-white font-extrabold leading-none shadow-xs",children:[r,"%"]})]}),t&&o.jsxs("div",{className:"absolute right-0 mt-2 w-72 rounded-xl border border-theme bg-surface shadow-xl z-50 p-3 overflow-hidden animate-in fade-in zoom-in-95 duration-100 select-none",children:[o.jsxs("div",{className:"px-1 pb-2 border-b border-theme-subtle mb-2.5 flex items-center justify-between",children:[o.jsxs("div",{children:[o.jsx("div",{className:"text-xs font-semibold text-main",children:e==="zh"?"界面字号大小":"Interface Font Size"}),o.jsx("div",{className:"text-xs text-muted mt-0.5",children:e==="zh"?"全局等比缩放排版与文字":"Proportionally scale typography"})]}),!m&&o.jsxs("button",{type:"button",onClick:d,className:"flex items-center gap-1 text-xs text-muted hover:text-primary-theme transition-colors cursor-pointer px-1.5 py-0.5 rounded hover:bg-surface-secondary",title:e==="zh"?"恢复默认 100%":"Reset to 100%",children:[o.jsx(Bl,{size:11}),o.jsx("span",{children:e==="zh"?"重置":"Reset"})]})]}),o.jsxs("div",{className:"bg-surface-secondary/70 rounded-lg p-2 flex items-center justify-between mb-3 border border-theme-subtle",children:[o.jsx("button",{type:"button",onClick:u,disabled:r<=i,className:"w-8 h-8 rounded-md bg-surface border border-theme flex items-center justify-center text-main hover:bg-surface-elevated disabled:opacity-40 disabled:cursor-not-allowed transition-colors cursor-pointer shadow-3xs",title:e==="zh"?"减小字体 (A-)":"Decrease (A-)",children:o.jsx(Zf,{size:14})}),o.jsxs("div",{className:"text-center",children:[o.jsxs("div",{className:"text-sm font-black text-main leading-tight",children:[r,"%"]}),o.jsx("div",{className:"text-xs text-muted",children:h?e==="zh"?h.labelZh.split(" ")[0]:h.labelEn.split(" ")[0]:e==="zh"?"自定义比例":"Custom"})]}),o.jsx("button",{type:"button",onClick:c,disabled:r>=a,className:"w-8 h-8 rounded-md bg-surface border border-theme flex items-center justify-center text-main hover:bg-surface-elevated disabled:opacity-40 disabled:cursor-not-allowed transition-colors cursor-pointer shadow-3xs",title:e==="zh"?"增大字体 (A+)":"Increase (A+)",children:o.jsx(Yf,{size:14})})]}),o.jsxs("div",{className:"space-y-1 mb-3",children:[o.jsx("div",{className:"text-xs font-bold text-muted uppercase tracking-wider px-1",children:e==="zh"?"常用档位":"Presets"}),o.jsx("div",{className:"grid grid-cols-1 gap-1",children:ma.map(f=>{const g=r===f.scale;return o.jsxs("button",{type:"button",onClick:()=>l(f.scale),className:`w-full flex items-center justify-between px-2.5 py-1.5 rounded-lg text-left text-xs transition-all cursor-pointer ${g?"bg-primary-theme-light text-primary-theme font-bold border border-primary-theme/30":"text-main hover:bg-surface-secondary border border-transparent"}`,children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-current opacity-60"}),o.jsx("span",{children:e==="zh"?f.labelZh:f.labelEn})]}),g&&o.jsx(et,{size:13,className:"text-primary-theme shrink-0"})]},f.scale)})})]}),o.jsxs("div",{className:"p-2.5 rounded-lg border border-theme-subtle bg-surface-secondary/40 mb-2",children:[o.jsxs("div",{className:"text-xs text-muted mb-1 flex items-center justify-between",children:[o.jsx("span",{children:e==="zh"?"实时效果预览":"Live Preview"}),o.jsxs("span",{children:[r,"%"]})]}),o.jsx("p",{className:"text-xs text-main font-medium leading-relaxed",children:e==="zh"?"让每一个文字都清晰舒适,智能赋能教学。":"Clear and comfortable typography empowers modern teaching."})]}),o.jsx("div",{className:"text-xs text-muted/80 text-center px-1",children:e==="zh"?"快捷键:Ctrl + Alt + 加号/减号":"Shortcut: Ctrl + Alt + +/-"})]})]})}function am(e){const{activeRole:t,lang:n,teacherTab:s,studentViewStatus:r,session:i,activeStudentId:a,students:l,studentDashboardData:c,isNotificationsOpen:u,studentNotifications:d,unreadNotifications:h,readNotifications:m,dbConnected:f,dbStatus:g,siteInfo:y,setActiveStudentId:k,setReadNotifications:S,setIsSystemResourceLibraryOpen:I,setProfileOpen:C,setTeacherTab:T,setStudentViewStatus:_,setIsNotificationsOpen:E,setSelectedNotificationForModal:R,handleLogout:B,toggleLanguage:F,setActiveRole:M,isStudentLocked:v=!1,onBlockedNavigate:z}=e,L=t==="student"&&v,P=()=>{if(L){z?.();return}t==="teacher"?T("dashboard"):t==="student"&&_("dashboard")};return o.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:[o.jsxs("div",{className:"flex items-center gap-4 sm:gap-6",children:[o.jsxs("button",{onClick:P,className:"flex items-center gap-2.5 shrink-0 hover:opacity-80 transition-opacity cursor-pointer",title:L?n==="zh"?"全班专注锁定中,无法返回系统总览":"Class focus locked — cannot return to dashboard":n==="zh"?"返回系统总览":"Back to Dashboard",children:[y.logoUrl?o.jsx("img",{src:y.logoUrl,alt:"site logo",className:"h-8 w-8 object-contain rounded-lg shrink-0"}):o.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"}),o.jsxs("div",{className:"flex items-baseline gap-2",children:[o.jsx("span",{className:"text-base font-black text-slate-900 tracking-tight",children:y.siteName||"OpenLearn Next"}),o.jsxs("span",{className:"text-xs font-medium text-slate-400 tracking-tight",children:["v","0.3.21"]}),y.slogan&&o.jsx("span",{className:"hidden md:inline text-xs text-slate-400 font-normal truncate max-w-[200px]",children:y.slogan})]})]}),o.jsxs("button",{onClick:P,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"} ${L?"opacity-50":""}`,children:[L?o.jsx(wi,{size:16}):o.jsx(Vl,{size:16}),n==="zh"?"系统总览":"Dashboard"]}),t==="student"&&o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"text-slate-300 font-light text-lg select-none",children:"/"}),o.jsxs("h2",{className:"font-semibold text-gray-800 tracking-tight flex items-center gap-2",children:[o.jsx(Kf,{size:20,className:"text-gray-400"}),"Student Dashboard"]})]}),t==="student"&&i?.role==="teacher"&&o.jsxs("div",{className:"flex items-center gap-2 bg-amber-50/90 border border-amber-200/80 px-2.5 py-1 rounded-lg shadow-2xs",children:[o.jsxs("span",{className:"text-xs font-semibold text-amber-800 flex items-center gap-1",children:[o.jsx(Ms,{size:13,className:"text-amber-600"}),n==="zh"?"模拟学生:":"View as:"]}),o.jsxs("select",{className:"border border-amber-300 rounded px-1.5 py-0.5 text-xs bg-white text-gray-800 font-medium focus:ring-1 focus:ring-amber-400 focus:outline-hidden",value:a||"",onChange:j=>k(j.target.value),children:[o.jsxs("option",{value:"",children:["-- ",n==="zh"?"选择学生":"Select Student"," --"]}),l.map(j=>o.jsx("option",{value:j.id,children:j.name},j.id))]}),M&&o.jsxs("button",{type:"button",onClick:()=>M("teacher"),className:"ml-1 px-2.5 py-1 bg-amber-600 hover:bg-amber-700 active:bg-amber-800 text-white text-xs font-bold rounded-md flex items-center gap-1 transition-all cursor-pointer shadow-2xs",title:n==="zh"?"退出模拟学生并返回教师端工作台":"Exit student view and return to teacher workspace",children:[o.jsx(Hi,{size:12}),n==="zh"?"返回教师端":"Exit Student View"]})]})]}),o.jsxs("div",{className:"flex items-center gap-4 text-sm text-gray-500",children:[t==="student"&&a&&c&&o.jsxs("div",{className:"relative",children:[o.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:[o.jsx(Xf,{size:20}),h.length>0&&o.jsx("span",{className:"absolute top-1 right-1 bg-red-500 text-white text-xs font-bold px-1.5 py-0.5 rounded-full flex items-center justify-center min-w-[18px]",children:h.length})]}),u&&o.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:[o.jsxs("div",{className:"p-3 border-b border-gray-100 flex justify-between items-center bg-gray-50",children:[o.jsx("h3",{className:"font-semibold text-gray-800",children:"Notifications"}),h.length>0&&o.jsx("button",{onClick:async()=>{if(!a)return;try{const A=d.filter(U=>!m.has(U.id)).map(U=>fetch(`/api/students/${a}/read_notifications`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({notificationId:U.id})}));await Promise.all(A)}catch(A){console.error(A)}const j=new Set(m);d.forEach(A=>j.add(A.id)),S(j)},className:"text-xs text-indigo-600 hover:text-indigo-800 font-medium",children:"Mark all as read"})]}),o.jsx("div",{className:"max-h-96 overflow-y-auto",children:d.length===0?o.jsx("div",{className:"p-4 text-center text-sm text-gray-500 italic",children:"No notifications."}):o.jsx("div",{className:"divide-y divide-gray-100",children:d.map(j=>{const A=!m.has(j.id);return o.jsx("div",{className:`p-3 hover:bg-gray-50 cursor-pointer ${A?"bg-indigo-50/30":""}`,onClick:()=>{if(A){a&&fetch(`/api/students/${a}/read_notifications`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({notificationId:j.id})}).catch(console.error);const N=new Set(m);N.add(j.id),S(N)}const U=c?.assignments?.find(N=>N.id===j.relatedId);R({...j,assignment:U}),E(!1)},children:o.jsxs("div",{className:"flex gap-3",children:[o.jsx("div",{className:"mt-0.5",children:j.type==="new_assignment"?o.jsx(Ul,{size:16,className:"text-indigo-500"}):j.type==="rollcall_picked"?o.jsx(Mn,{size:16,className:"text-amber-500 animate-pulse"}):o.jsx(On,{size:16,className:"text-green-500"})}),o.jsxs("div",{className:"flex-1",children:[o.jsx("div",{className:`text-sm ${A?"font-semibold text-gray-900":"font-medium text-gray-700"}`,children:j.title}),o.jsx("div",{className:`text-xs mt-0.5 ${A?"text-gray-600":"text-gray-500"}`,children:j.message})]}),A&&o.jsx("div",{className:"w-2 h-2 rounded-full bg-indigo-500 mt-1"})]})},j.id)})})})]})]}),o.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:[o.jsx(vi,{size:14,className:"text-emerald-500 animate-pulse"}),n==="zh"?"系统资源库":"System Resource Library"]}),o.jsx("button",{onClick:F,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:o.jsx(vi,{size:16})}),o.jsx(Xl,{lang:n}),o.jsx(om,{lang:n}),(()=>{const j=g==="error"||!f?{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 o.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 ${j.bg}`,title:j.label,children:[o.jsx(ep,{size:15}),o.jsxs("span",{className:"absolute -top-0.5 -right-0.5 flex h-2.5 w-2.5",children:[o.jsx("span",{className:`animate-ping absolute inline-flex h-full w-full rounded-full opacity-75 ${j.ping}`}),o.jsx("span",{className:`relative inline-flex rounded-full h-2.5 w-2.5 ${j.dot}`})]})]})})(),o.jsx(em,{session:i,lang:n,onLogout:B,onProfile:()=>C(!0)})]})]})}const lm="openlearn_live_classroom_sync";class ga{constructor(t=lm){this.channel=null,this.isDestroyed=!1,this.messageListeners=[],typeof window<"u"&&typeof window.BroadcastChannel<"u"&&(this.channel=new BroadcastChannel(t),this.channel.onmessage=n=>{this.isDestroyed||!n.data||this.messageListeners.forEach(s=>{try{s(n.data)}catch(r){console.error("[ClassroomSyncChannel] Listener error:",r)}})})}onMessage(t){return this.messageListeners.push(t),()=>{this.messageListeners=this.messageListeners.filter(n=>n!==t)}}postMessage(t){if(!(this.isDestroyed||!this.channel))try{this.channel.postMessage(t)}catch(n){console.warn("[ClassroomSyncChannel] Failed to post message:",n)}}broadcastInitState(t){this.postMessage({type:"TEACHER_INIT_STATE",payload:t})}broadcastChangeLesson(t){this.postMessage({type:"TEACHER_CHANGE_LESSON",payload:{lessonId:t}})}broadcastChangeSegment(t){this.postMessage({type:"TEACHER_CHANGE_SEGMENT",payload:{segmentId:t}})}broadcastChangeTab(t){this.postMessage({type:"TEACHER_CHANGE_TAB",payload:{tab:t}})}broadcastLockClass(t){this.postMessage({type:"TEACHER_LOCK_CLASS",payload:{locked:t}})}broadcastPickStudent(t,n){this.postMessage({type:"TEACHER_PICK_STUDENT",payload:{studentId:t,studentName:n}})}broadcastSyncTimer(t,n){this.postMessage({type:"TEACHER_SYNC_TIMER",payload:{timeRemaining:t,isRunning:n}})}broadcastPingStudent(t,n){this.postMessage({type:"TEACHER_PING_STUDENT",payload:{studentId:t,message:n}})}broadcastFullscreen(t,n){this.postMessage({type:"TEACHER_BROADCAST_FULLSCREEN",payload:{elementId:t,lessonId:n}})}requestHandshake(){this.postMessage({type:"STUDENT_HANDSHAKE_REQUEST"})}acknowledgePick(t){this.postMessage({type:"STUDENT_ACKNOWLEDGE_PICK",payload:{studentId:t}})}sendHeartbeat(t){this.postMessage({type:"STUDENT_HEARTBEAT",payload:{studentId:t,timestamp:Date.now()}})}destroy(){this.isDestroyed=!0,this.messageListeners=[],this.channel&&(this.channel.close(),this.channel=null)}}const on=wt(e=>({remoteFullscreenElementId:null,setRemoteFullscreenElementId:t=>e({remoteFullscreenElementId:t}),clearRemoteFullscreen:()=>e({remoteFullscreenElementId:null})})),RC=e=>Os(on,e);function cm({open:e,session:t,lang:n,onClose:s,onSaved:r,onAvatar:i}){const[a,l]=p.useState(t.name),[c,u]=p.useState(!1),[d,h]=p.useState(null),m=p.useRef(null),[f,g]=p.useState(!1),[y,k]=p.useState(null),[S,I]=p.useState(!1),[C,T]=p.useState(""),[_,E]=p.useState(""),[R,B]=p.useState(""),[F,M]=p.useState(!1),[v,z]=p.useState(null),[L,P]=p.useState(!1);if(!e)return null;const j=(J,D)=>n==="zh"?J:D,A=t.role==="teacher"?t.subRole==="administrator"?j("管理员","Administrator"):j("教师","Teacher"):j("学生","Student"),U=a.trim(),N=U.length>0&&U!==t.name,O=async()=>{if(!(!N||c)){u(!0),h(null);try{const J=await fetch("/api/auth/profile",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:U})}),D=await J.json();if(!J.ok){h(D.error||(n==="zh"?"保存失败":"Save failed"));return}r(D.name??U)}catch{h(n==="zh"?"网络错误,请重试":"Network error, please retry")}finally{u(!1)}}},x=C.length>0&&_.length>=8&&/[a-zA-Z]/.test(_)&&/[0-9]/.test(_)&&_===R,oe=async()=>{if(!(!x||F)){M(!0),z(null);try{const J=await fetch("/api/auth/change-password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({oldPassword:C,newPassword:_})}),D=await J.json();if(!J.ok){z(D.error||(n==="zh"?"修改失败":"Change failed"));return}P(!0),T(""),E(""),B(""),I(!1)}catch{z(n==="zh"?"网络错误,请重试":"Network error, please retry")}finally{M(!1)}}},pe=async J=>{const D=J.target.files?.[0];if(J.target.value="",!!D){g(!0),k(null);try{const G=await new Promise((we,me)=>{const le=new FileReader;le.onload=()=>we(le.result),le.onerror=()=>me(le.error),le.readAsDataURL(D)}),re=await fetch("/api/auth/avatar",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({filename:D.name,base64Data:G})}),se=await re.json();if(!re.ok){k(se.error||(n==="zh"?"上传失败":"Upload failed"));return}i?.(se.avatar)}catch{k(n==="zh"?"网络错误,请重试":"Network error, please retry")}finally{g(!1)}}},b=async()=>{g(!0),k(null);try{const J=await fetch("/api/auth/avatar",{method:"DELETE"}),D=await J.json().catch(()=>({}));if(!J.ok){k(D.error||(n==="zh"?"移除失败":"Remove failed"));return}i?.(null)}catch{k(n==="zh"?"网络错误,请重试":"Network error, please retry")}finally{g(!1)}};return o.jsx("div",{className:"fixed inset-0 bg-black/40 backdrop-blur-xs flex items-center justify-center z-50 p-4",onClick:s,children:o.jsxs("div",{className:"bg-white rounded-2xl shadow-xl w-full max-w-md overflow-hidden",onClick:J=>J.stopPropagation(),children:[o.jsxs("div",{className:"flex items-center justify-between px-5 py-4 border-b border-gray-100",children:[o.jsx("h3",{className:"font-semibold text-gray-800",children:j("个人资料","Profile")}),o.jsx("button",{onClick:s,className:"text-gray-400 hover:text-gray-600 cursor-pointer",children:o.jsx(tt,{size:18})})]}),o.jsxs("div",{className:"p-5 space-y-5",children:[o.jsxs("div",{className:"flex items-center gap-3",children:[o.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?o.jsx("img",{src:t.avatar,alt:t.name,className:"w-full h-full object-cover"}):o.jsx(_n,{size:28})}),o.jsxs("div",{className:"min-w-0",children:[o.jsx("p",{className:"text-base font-semibold text-gray-800 truncate",children:t.name}),o.jsx("p",{className:"text-xs text-gray-400",children:A}),o.jsxs("div",{className:"mt-1.5 flex items-center gap-3",children:[o.jsx("button",{type:"button",onClick:()=>m.current?.click(),disabled:f,className:"text-xs text-indigo-600 hover:text-indigo-800 disabled:opacity-50 cursor-pointer",children:f?j("上传中…","Uploading…"):t.avatar?j("更换头像","Change avatar"):j("上传头像","Upload avatar")}),t.avatar&&o.jsx("button",{type:"button",onClick:b,disabled:f,className:"text-xs text-rose-500 hover:text-rose-700 disabled:opacity-50 cursor-pointer",children:j("移除","Remove")})]}),o.jsx("input",{ref:m,type:"file",accept:"image/png,image/jpeg,image/gif,image/webp",className:"hidden",onChange:pe})]})]}),y&&o.jsx("p",{className:"text-xs text-rose-500",children:y}),o.jsxs("div",{children:[o.jsx("label",{className:"block text-sm text-gray-500 mb-1",children:j("显示名称","Display Name")}),o.jsxs("div",{className:"flex gap-2",children:[o.jsx("input",{value:a,onChange:J=>l(J.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"}),o.jsx("button",{onClick:O,disabled:!N||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&&o.jsx("p",{className:"text-xs text-rose-500 mt-1",children:d})]}),o.jsxs("div",{className:"border-t border-gray-100 pt-4",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsxs("span",{className:"text-sm font-medium text-gray-700 flex items-center gap-2",children:[o.jsx(tp,{size:16,className:"text-gray-400"}),j("修改密码","Change Password")]}),!S&&!L&&o.jsx("button",{onClick:()=>{I(!0),z(null)},className:"text-sm text-indigo-600 hover:text-indigo-800 cursor-pointer",children:j("修改","Edit")})]}),L&&o.jsxs("p",{className:"mt-2 flex items-center gap-1.5 text-sm text-emerald-600",children:[o.jsx(On,{size:16}),j("密码已修改,其他设备的登录已失效","Password changed. Other devices were logged out.")]}),S&&o.jsxs("div",{className:"mt-3 space-y-3",children:[o.jsx("input",{type:"password",value:C,onChange:J=>T(J.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"}),o.jsx("input",{type:"password",value:_,onChange:J=>E(J.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"}),o.jsx("input",{type:"password",value:R,onChange:J=>B(J.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"}),v&&o.jsx("p",{className:"text-xs text-rose-500",children:v}),o.jsxs("div",{className:"flex gap-2 justify-end",children:[o.jsx("button",{onClick:()=>{I(!1),T(""),E(""),B(""),z(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")}),o.jsx("button",{onClick:oe,disabled:!x||F,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:F?j("提交中…","Submitting…"):j("提交","Submit")})]})]})]}),o.jsxs("div",{className:"border-t border-gray-100 pt-4 space-y-2",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsx("span",{className:"text-sm text-gray-400",children:j("用户名(登录账号)","Username (login)")}),o.jsx("span",{className:"text-sm font-medium text-gray-700 truncate max-w-[60%]",title:t.username,children:t.username||"-"})]}),o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsx("span",{className:"text-sm text-gray-400",children:j("角色","Role")}),o.jsx("span",{className:"text-sm font-medium text-gray-700",children:A})]})]})]})]})})}class um{constructor(){this.store=wt(()=>({items:new Map}))}register(t,n){const s=n||t.pluginId;this.store.setState(r=>{const i=new Map(r.items);return i.set(t.type,{config:{...t,pluginId:s},pluginId:s}),{items:i}})}unregister(t,n){this.store.setState(s=>{const r=s.items.get(t);if(!r||n&&r.pluginId!==n)return s;const i=new Map(s.items);return i.delete(t),{items:i}})}unregisterPlugin(t){this.store.setState(n=>{let s=!1;const r=new Map(n.items);for(const[i,a]of n.items)a.pluginId===t&&(r.delete(i),s=!0);return s?{items:r}:n})}get(t){return this.store.getState().items.get(t)?.config}getAll(){return Array.from(this.store.getState().items.values()).map(t=>t.config)}has(t){return this.store.getState().items.has(t)}getStore(){return this.store}}const Tn=new um;function MC(){return Os(Tn.getStore(),$f(e=>Array.from(e.items.values()).map(t=>t.config)))}const OC={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"}},DC=[{id:"present",labelZh:"内容呈现",labelEn:"Content"},{id:"assess",labelZh:"评估互动",labelEn:"Assessment"},{id:"manage",labelZh:"课堂管理",labelEn:"Classroom"},{id:"extension",labelZh:"插件扩展",labelEn:"Extensions"}],dm=[{type:"presentation",labelZh:"课件演示",labelEn:"Slides Deck",descriptionZh:"Markdown 幻灯片",descriptionEn:"Markdown slides",icon:np,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:hs,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:sp,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:vi,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:"互动课件 (Courseware)",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:"code",labelZh:"HTML 代码",labelEn:"HTML Code",kind:"textarea",placeholderZh:"<div>…</div>"}]},{type:"quiz",labelZh:"随堂测试",labelEn:"Interactive Quiz",descriptionZh:"选择题互动",descriptionEn:"Multiple choice",icon:Wi,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:Ul,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:rp,color:"cyan",group:"manage",defaultData:{allStudents:[]},editFields:[]},{type:"hello-world",labelZh:"问候插件",labelEn:"Hello World",descriptionZh:"欢迎问候",descriptionEn:"Welcome greeting",icon:Mn,color:"pink",group:"manage",defaultData:{},editFields:[]}],hm=dm.reduce((e,t)=>(e[t.type]=t,e),{});function fm(e){return hm[e]||Tn.get(e)}const ot=wt(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})})),pm=wt(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})})),mm=wt(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})})),gm=wt(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})})),xm=wt(e=>({studentDashboardData:null,notifications:[],setStudentDashboardData:t=>e({studentDashboardData:t}),setNotifications:t=>e({notifications:t})})),ve=wt(e=>({lang:ot.getState().lang,session:null,lessons:[],selectedLesson:null,elements:[],classes:[],students:[],liveClassSelectedClassId:null,liveClassIsActive:!1,teacherTab:ot.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:ot.getState().toasts,siteInfo:ot.getState().siteInfo,setLang:t=>{ot.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=>{ot.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=>{ot.getState().addToast(t)},removeToast:t=>{ot.getState().removeToast(t)},setSiteInfo:t=>{ot.getState().setSiteInfo(t)}}));ot.subscribe(e=>{ve.setState({lang:e.lang,teacherTab:e.teacherTab,toasts:e.toasts,siteInfo:e.siteInfo})});pm.subscribe(e=>{ve.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})});mm.subscribe(e=>{ve.setState({lessons:e.lessons,selectedLesson:e.selectedLesson,elements:e.elements,vfsNodes:e.vfsNodes})});gm.subscribe(e=>{ve.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})});xm.subscribe(e=>{ve.setState({studentDashboardData:e.studentDashboardData,notifications:e.notifications})});const de=e=>Os(ve,e);function ym(e,t){const n={};return(e[e.length-1]===""?[...e,""]:e).join((n.padRight?" ":"")+","+(n.padLeft===!1?"":" ")).trim()}const bm=/^[$_\p{ID_Start}][$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,wm=/^[$_\p{ID_Start}][-$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,Sm={};function xa(e,t){return(Sm.jsx?wm:bm).test(e)}const vm=/[ \t\n\f\r]/g;function Cm(e){return typeof e=="object"?e.type==="text"?ya(e.value):!1:ya(e)}function ya(e){return e.replace(vm,"")===""}class Dn{constructor(t,n,s){this.normal=n,this.property=t,s&&(this.space=s)}}Dn.prototype.normal={};Dn.prototype.property={};Dn.prototype.space=void 0;function ec(e,t){const n={},s={};for(const r of e)Object.assign(n,r.property),Object.assign(s,r.normal);return new Dn(n,s,t)}function Ei(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 km=0;const ne=Vt(),Se=Vt(),ji=Vt(),H=Vt(),he=Vt(),Bt=Vt(),$e=Vt();function Vt(){return 2**++km}const Ni=Object.freeze(Object.defineProperty({__proto__:null,boolean:ne,booleanish:Se,commaOrSpaceSeparated:$e,commaSeparated:Bt,number:H,overloadedBoolean:ji,spaceSeparated:he},Symbol.toStringTag,{value:"Module"})),Qr=Object.keys(Ni);class Yi extends De{constructor(t,n,s,r){let i=-1;if(super(t,n),ba(this,"space",r),typeof s=="number")for(;++i<Qr.length;){const a=Qr[i];ba(this,Qr[i],(s&Ni[a])===Ni[a])}}}Yi.prototype.defined=!0;function ba(e,t,n){n&&(e[t]=n)}function cn(e){const t={},n={};for(const[s,r]of Object.entries(e.properties)){const i=new Yi(s,e.transform(e.attributes||{},s),r,e.space);e.mustUseProperty&&e.mustUseProperty.includes(s)&&(i.mustUseProperty=!0),t[s]=i,n[Ei(s)]=s,n[Ei(i.attribute)]=s}return new Dn(t,n,e.space)}const tc=cn({properties:{ariaActiveDescendant:null,ariaAtomic:Se,ariaAutoComplete:null,ariaBusy:Se,ariaChecked:Se,ariaColCount:H,ariaColIndex:H,ariaColSpan:H,ariaControls:he,ariaCurrent:null,ariaDescribedBy:he,ariaDetails:null,ariaDisabled:Se,ariaDropEffect:he,ariaErrorMessage:null,ariaExpanded:Se,ariaFlowTo:he,ariaGrabbed:Se,ariaHasPopup:null,ariaHidden:Se,ariaInvalid:null,ariaKeyShortcuts:null,ariaLabel:null,ariaLabelledBy:he,ariaLevel:H,ariaLive:null,ariaModal:Se,ariaMultiLine:Se,ariaMultiSelectable:Se,ariaOrientation:null,ariaOwns:he,ariaPlaceholder:null,ariaPosInSet:H,ariaPressed:Se,ariaReadOnly:Se,ariaRelevant:null,ariaRequired:Se,ariaRoleDescription:he,ariaRowCount:H,ariaRowIndex:H,ariaRowSpan:H,ariaSelected:Se,ariaSetSize:H,ariaSort:null,ariaValueMax:H,ariaValueMin:H,ariaValueNow:H,ariaValueText:null,role:null},transform(e,t){return t==="role"?t:"aria-"+t.slice(4).toLowerCase()}});function nc(e,t){return t in e?e[t]:t}function sc(e,t){return nc(e,t.toLowerCase())}const Em=cn({attributes:{acceptcharset:"accept-charset",classname:"class",htmlfor:"for",httpequiv:"http-equiv"},mustUseProperty:["checked","multiple","muted","selected"],properties:{abbr:null,accept:Bt,acceptCharset:he,accessKey:he,action:null,allow:null,allowFullScreen:ne,allowPaymentRequest:ne,allowUserMedia:ne,alpha:ne,alt:null,as:null,async:ne,autoCapitalize:null,autoComplete:he,autoFocus:ne,autoPlay:ne,blocking:he,capture:null,charSet:null,checked:ne,cite:null,className:he,closedBy:null,colorSpace:null,cols:H,colSpan:H,command:null,commandFor:null,content:null,contentEditable:Se,controls:ne,controlsList:he,coords:H|Bt,crossOrigin:null,data:null,dateTime:null,decoding:null,default:ne,defer:ne,dir:null,dirName:null,disabled:ne,download:ji,draggable:Se,encType:null,enterKeyHint:null,fetchPriority:null,form:null,formAction:null,formEncType:null,formMethod:null,formNoValidate:ne,formTarget:null,headers:he,height:H,hidden:ji,high:H,href:null,hrefLang:null,htmlFor:he,httpEquiv:he,id:null,imageSizes:null,imageSrcSet:null,inert:ne,inputMode:null,integrity:null,is:null,isMap:ne,itemId:null,itemProp:he,itemRef:he,itemScope:ne,itemType:he,kind:null,label:null,lang:null,language:null,list:null,loading:null,loop:ne,low:H,manifest:null,max:null,maxLength:H,media:null,method:null,min:null,minLength:H,multiple:ne,muted:ne,name:null,nonce:null,noModule:ne,noValidate:ne,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:ne,optimum:H,pattern:null,ping:he,placeholder:null,playsInline:ne,popover:null,popoverTarget:null,popoverTargetAction:null,poster:null,preload:null,readOnly:ne,referrerPolicy:null,rel:he,required:ne,reversed:ne,rows:H,rowSpan:H,sandbox:he,scope:null,scoped:ne,seamless:ne,selected:ne,shadowRootClonable:ne,shadowRootCustomElementRegistry:ne,shadowRootDelegatesFocus:ne,shadowRootMode:null,shadowRootSerializable:ne,shape:null,size:H,sizes:null,slot:null,span:H,spellCheck:Se,src:null,srcDoc:null,srcLang:null,srcSet:null,start:H,step:null,style:null,tabIndex:H,target:null,title:null,translate:null,type:null,typeMustMatch:ne,useMap:null,value:Se,width:H,wrap:null,writingSuggestions:null,align:null,aLink:null,archive:he,axis:null,background:null,bgColor:null,border:H,borderColor:null,bottomMargin:H,cellPadding:null,cellSpacing:null,char:null,charOff:null,classId:null,clear:null,code:null,codeBase:null,codeType:null,color:null,compact:ne,declare:ne,event:null,face:null,frame:null,frameBorder:null,hSpace:H,leftMargin:H,link:null,longDesc:null,lowSrc:null,marginHeight:H,marginWidth:H,noResize:ne,noHref:ne,noShade:ne,noWrap:ne,object:null,profile:null,prompt:null,rev:null,rightMargin:H,rules:null,scheme:null,scrolling:Se,standby:null,summary:null,text:null,topMargin:H,valueType:null,version:null,vAlign:null,vLink:null,vSpace:H,allowTransparency:null,autoCorrect:null,autoSave:null,credentialless:ne,disablePictureInPicture:ne,disableRemotePlayback:ne,exportParts:Bt,part:he,prefix:null,property:null,results:H,security:null,unselectable:null},space:"html",transform:sc}),jm=cn({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:$e,accentHeight:H,accumulate:null,additive:null,alignmentBaseline:null,alphabetic:H,amplitude:H,arabicForm:null,ascent:H,attributeName:null,attributeType:null,azimuth:H,bandwidth:null,baselineShift:null,baseFrequency:null,baseProfile:null,bbox:null,begin:null,bias:H,by:null,calcMode:null,capHeight:H,className:he,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:H,diffuseConstant:H,direction:null,display:null,dur:null,divisor:H,dominantBaseline:null,download:ne,dx:null,dy:null,edgeMode:null,editable:null,elevation:H,enableBackground:null,end:null,event:null,exponent:H,externalResourcesRequired:null,fill:null,fillOpacity:H,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:Bt,g2:Bt,glyphName:Bt,glyphOrientationHorizontal:null,glyphOrientationVertical:null,glyphRef:null,gradientTransform:null,gradientUnits:null,handler:null,hanging:H,hatchContentUnits:null,hatchUnits:null,height:null,href:null,hrefLang:null,horizAdvX:H,horizOriginX:H,horizOriginY:H,id:null,ideographic:H,imageRendering:null,initialVisibility:null,in:null,in2:null,intercept:H,k:H,k1:H,k2:H,k3:H,k4:H,kernelMatrix:$e,kernelUnitLength:null,keyPoints:null,keySplines:null,keyTimes:null,kerning:null,lang:null,lengthAdjust:null,letterSpacing:null,lightingColor:null,limitingConeAngle:H,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:H,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:H,overlineThickness:H,paintOrder:null,panose1:null,path:null,pathLength:H,patternContentUnits:null,patternTransform:null,patternUnits:null,phase:null,ping:he,pitch:null,playbackOrder:null,pointerEvents:null,points:null,pointsAtX:H,pointsAtY:H,pointsAtZ:H,preserveAlpha:null,preserveAspectRatio:null,primitiveUnits:null,propagate:null,property:$e,r:null,radius:null,referrerPolicy:null,refX:null,refY:null,rel:$e,rev:$e,renderingIntent:null,repeatCount:null,repeatDur:null,requiredExtensions:$e,requiredFeatures:$e,requiredFonts:$e,requiredFormats:$e,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:H,specularExponent:H,spreadMethod:null,spacing:null,startOffset:null,stdDeviation:null,stemh:null,stemv:null,stitchTiles:null,stopColor:null,stopOpacity:null,strikethroughPosition:H,strikethroughThickness:H,string:null,stroke:null,strokeDashArray:$e,strokeDashOffset:null,strokeLineCap:null,strokeLineJoin:null,strokeMiterLimit:H,strokeOpacity:H,strokeWidth:null,style:null,surfaceScale:H,syncBehavior:null,syncBehaviorDefault:null,syncMaster:null,syncTolerance:null,syncToleranceDefault:null,systemLanguage:$e,tabIndex:H,tableValues:null,target:null,targetX:H,targetY:H,textAnchor:null,textDecoration:null,textRendering:null,textLength:null,timelineBegin:null,title:null,transformBehavior:null,type:null,typeOf:$e,to:null,transform:null,transformOrigin:null,u1:null,u2:null,underlinePosition:H,underlineThickness:H,unicode:null,unicodeBidi:null,unicodeRange:null,unitsPerEm:H,values:null,vAlphabetic:H,vMathematical:H,vectorEffect:null,vHanging:H,vIdeographic:H,version:null,vertAdvY:H,vertOriginX:H,vertOriginY:H,viewBox:null,viewTarget:null,visibility:null,width:null,widths:null,wordSpacing:null,writingMode:null,x:null,x1:null,x2:null,xChannelSelector:null,xHeight:H,y:null,y1:null,y2:null,yChannelSelector:null,z:null,zoomAndPan:null},space:"svg",transform:nc}),rc=cn({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()}}),ic=cn({attributes:{xmlnsxlink:"xmlns:xlink"},properties:{xmlnsXLink:null,xmlns:null},space:"xmlns",transform:sc}),oc=cn({properties:{xmlBase:null,xmlLang:null,xmlSpace:null},space:"xml",transform(e,t){return"xml:"+t.slice(3).toLowerCase()}}),Nm={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"},Tm=/[A-Z]/g,wa=/-[a-z]/g,Pm=/^data[-\w.:]+$/i;function Im(e,t){const n=Ei(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"&&Pm.test(t)){if(t.charAt(4)==="-"){const i=t.slice(5).replace(wa,zm);s="data"+i.charAt(0).toUpperCase()+i.slice(1)}else{const i=t.slice(4);if(!wa.test(i)){let a=i.replace(Tm,Am);a.charAt(0)!=="-"&&(a="-"+a),t="data"+a}}r=Yi}return new r(s,t)}function Am(e){return"-"+e.toLowerCase()}function zm(e){return e.charAt(1).toUpperCase()}const _m=ec([tc,Em,rc,ic,oc],"html"),Ki=ec([tc,jm,rc,ic,oc],"svg");function Lm(e){return e.join(" ").trim()}var Kt={},Jr,Sa;function Rm(){if(Sa)return Jr;Sa=1;var e=/\/\*[^*]*\*+([^/*][^*]*\*+)*\//g,t=/\n/g,n=/^\s*/,s=/^(\*?[-#/*\\\w]+(\[[0-9a-z_-]+\])?)\s*/,r=/^:\s*/,i=/^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^)]*?\)|[^};])+)/,a=/^[;\s]*/,l=/^\s+|\s+$/g,c=`
13
- `,u="/",d="*",h="",m="comment",f="declaration";function g(k,S){if(typeof k!="string")throw new TypeError("First argument must be a string");if(!k)return[];S=S||{};var I=1,C=1;function T(P){var j=P.match(t);j&&(I+=j.length);var A=P.lastIndexOf(c);C=~A?P.length-A:C+P.length}function _(){var P={line:I,column:C};return function(j){return j.position=new E(P),F(),j}}function E(P){this.start=P,this.end={line:I,column:C},this.source=S.source}E.prototype.content=k;function R(P){var j=new Error(S.source+":"+I+":"+C+": "+P);if(j.reason=P,j.filename=S.source,j.line=I,j.column=C,j.source=k,!S.silent)throw j}function B(P){var j=P.exec(k);if(j){var A=j[0];return T(A),k=k.slice(A.length),j}}function F(){B(n)}function M(P){var j;for(P=P||[];j=v();)j!==!1&&P.push(j);return P}function v(){var P=_();if(!(u!=k.charAt(0)||d!=k.charAt(1))){for(var j=2;h!=k.charAt(j)&&(d!=k.charAt(j)||u!=k.charAt(j+1));)++j;if(j+=2,h===k.charAt(j-1))return R("End of comment missing");var A=k.slice(2,j-2);return C+=2,T(A),k=k.slice(j),C+=2,P({type:m,comment:A})}}function z(){var P=_(),j=B(s);if(j){if(v(),!B(r))return R("property missing ':'");var A=B(i),U=P({type:f,property:y(j[0].replace(e,h)),value:A?y(A[0].replace(e,h)):h});return B(a),U}}function L(){var P=[];M(P);for(var j;j=z();)j!==!1&&(P.push(j),M(P));return P}return F(),L()}function y(k){return k?k.replace(l,h):h}return Jr=g,Jr}var va;function Mm(){if(va)return Kt;va=1;var e=Kt&&Kt.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(Kt,"__esModule",{value:!0}),Kt.default=n;const t=e(Rm());function n(s,r){let i=null;if(!s||typeof s!="string")return i;const a=(0,t.default)(s),l=typeof r=="function";return a.forEach(c=>{if(c.type!=="declaration")return;const{property:u,value:d}=c;l?r(u,d,c):d&&(i=i||{},i[u]=d)}),i}return Kt}var vn={},Ca;function Om(){if(Ca)return vn;Ca=1,Object.defineProperty(vn,"__esModule",{value:!0}),vn.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)},a=function(u,d){return d.toUpperCase()},l=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,l):u=u.replace(s,l),u.replace(t,a))};return vn.camelCase=c,vn}var Cn,ka;function Dm(){if(ka)return Cn;ka=1;var e=Cn&&Cn.__importDefault||function(r){return r&&r.__esModule?r:{default:r}},t=e(Mm()),n=Om();function s(r,i){var a={};return!r||typeof r!="string"||(0,t.default)(r,function(l,c){l&&c&&(a[(0,n.camelCase)(l,i)]=c)}),a}return s.default=s,Cn=s,Cn}var Fm=Dm();const $m=Dl(Fm),ac=lc("end"),Xi=lc("start");function lc(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 Bm(e){const t=Xi(e),n=ac(e);if(t&&n)return{start:t,end:n}}function Pn(e){return!e||typeof e!="object"?"":"position"in e||"type"in e?Ea(e.position):"start"in e||"end"in e?Ea(e):"line"in e||"column"in e?Ti(e):""}function Ti(e){return ja(e&&e.line)+":"+ja(e&&e.column)}function Ea(e){return Ti(e&&e.start)+"-"+Ti(e&&e.end)}function ja(e){return e&&typeof e=="number"?e:1}class ze extends Error{constructor(t,n,s){super(),typeof n=="string"&&(s=n,n=void 0);let r="",i={},a=!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&&(a=!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 l=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=l?l.column:void 0,this.fatal=void 0,this.file="",this.message=r,this.line=l?l.line:void 0,this.name=Pn(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=a&&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}}ze.prototype.file="";ze.prototype.name="";ze.prototype.reason="";ze.prototype.message="";ze.prototype.stack="";ze.prototype.column=void 0;ze.prototype.line=void 0;ze.prototype.ancestors=void 0;ze.prototype.cause=void 0;ze.prototype.fatal=void 0;ze.prototype.place=void 0;ze.prototype.ruleId=void 0;ze.prototype.source=void 0;const eo={}.hasOwnProperty,Vm=new Map,Um=/[A-Z]/g,Hm=new Set(["table","tbody","thead","tfoot","tr"]),qm=new Set(["td","th"]),cc="https://github.com/syntax-tree/hast-util-to-jsx-runtime";function Wm(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=eg(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=Xm(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"?Ki:_m,stylePropertyNameCase:t.stylePropertyNameCase||"dom",tableCellAlignToStyle:t.tableCellAlignToStyle!==!1},i=uc(r,e,void 0);return i&&typeof i!="string"?i:r.create(e,r.Fragment,{children:i||void 0},void 0)}function uc(e,t,n){if(t.type==="element")return Gm(e,t,n);if(t.type==="mdxFlowExpression"||t.type==="mdxTextExpression")return Qm(e,t);if(t.type==="mdxJsxFlowElement"||t.type==="mdxJsxTextElement")return Zm(e,t,n);if(t.type==="mdxjsEsm")return Jm(e,t);if(t.type==="root")return Ym(e,t,n);if(t.type==="text")return Km(e,t)}function Gm(e,t,n){const s=e.schema;let r=s;t.tagName.toLowerCase()==="svg"&&s.space==="html"&&(r=Ki,e.schema=r),e.ancestors.push(t);const i=hc(e,t.tagName,!1),a=tg(e,t);let l=no(e,t);return Hm.has(t.tagName)&&(l=l.filter(function(c){return typeof c=="string"?!Cm(c):!0})),dc(e,a,i,t),to(a,l),e.ancestors.pop(),e.schema=s,e.create(t,i,a,n)}function Qm(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)}Rn(e,t.position)}function Jm(e,t){if(t.data&&t.data.estree&&e.evaluater)return e.evaluater.evaluateProgram(t.data.estree);Rn(e,t.position)}function Zm(e,t,n){const s=e.schema;let r=s;t.name==="svg"&&s.space==="html"&&(r=Ki,e.schema=r),e.ancestors.push(t);const i=t.name===null?e.Fragment:hc(e,t.name,!0),a=ng(e,t),l=no(e,t);return dc(e,a,i,t),to(a,l),e.ancestors.pop(),e.schema=s,e.create(t,i,a,n)}function Ym(e,t,n){const s={};return to(s,no(e,t)),e.create(t,e.Fragment,s,n)}function Km(e,t){return t.value}function dc(e,t,n,s){typeof n!="string"&&n!==e.Fragment&&e.passNode&&(t.node=s)}function to(e,t){if(t.length>0){const n=t.length>1?t:t[0];n&&(e.children=n)}}function Xm(e,t,n){return s;function s(r,i,a,l){const u=Array.isArray(a.children)?n:t;return l?u(i,a,l):u(i,a)}}function eg(e,t){return n;function n(s,r,i,a){const l=Array.isArray(i.children),c=Xi(s);return t(r,i,a,l,{columnNumber:c?c.column-1:void 0,fileName:e,lineNumber:c?c.line:void 0},void 0)}}function tg(e,t){const n={};let s,r;for(r in t.properties)if(r!=="children"&&eo.call(t.properties,r)){const i=sg(e,r,t.properties[r]);if(i){const[a,l]=i;e.tableCellAlignToStyle&&a==="align"&&typeof l=="string"&&qm.has(t.tagName)?s=l:n[a]=l}}if(s){const i=n.style||(n.style={});i[e.stylePropertyNameCase==="css"?"text-align":"textAlign"]=s}return n}function ng(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 a=i.expression;a.type;const l=a.properties[0];l.type,Object.assign(n,e.evaluater.evaluateExpression(l.argument))}else Rn(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 l=s.value.data.estree.body[0];l.type,i=e.evaluater.evaluateExpression(l.expression)}else Rn(e,t.position);else i=s.value===null?!0:s.value;n[r]=i}return n}function no(e,t){const n=[];let s=-1;const r=e.passKeys?new Map:Vm;for(;++s<t.children.length;){const i=t.children[s];let a;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;a=c+"-"+u,r.set(c,u+1)}}const l=uc(e,i,a);l!==void 0&&n.push(l)}return n}function sg(e,t,n){const s=Im(e.schema,t);if(!(n==null||typeof n=="number"&&Number.isNaN(n))){if(Array.isArray(n)&&(n=s.commaSeparated?ym(n):Lm(n)),s.property==="style"){let r=typeof n=="object"?n:rg(e,String(n));return e.stylePropertyNameCase==="css"&&(r=ig(r)),["style",r]}return[e.elementAttributeNameCase==="react"&&s.space?Nm[s.property]||s.property:s.attribute,n]}}function rg(e,t){try{return $m(t,{reactCompat:!0})}catch(n){if(e.ignoreInvalidStyle)return{};const s=n,r=new ze("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=cc+"#cannot-parse-style-attribute",r}}function hc(e,t,n){let s;if(!n)s={type:"Literal",value:t};else if(t.includes(".")){const r=t.split(".");let i=-1,a;for(;++i<r.length;){const l=xa(r[i])?{type:"Identifier",name:r[i]}:{type:"Literal",value:r[i]};a=a?{type:"MemberExpression",object:a,property:l,computed:!!(i&&l.type==="Literal"),optional:!1}:l}s=a}else s=xa(t)&&!/^[a-z]/.test(t)?{type:"Identifier",name:t}:{type:"Literal",value:t};if(s.type==="Literal"){const r=s.value;return eo.call(e.components,r)?e.components[r]:r}if(e.evaluater)return e.evaluater.evaluateExpression(s);Rn(e)}function Rn(e,t){const n=new ze("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=cc+"#cannot-handle-mdx-estrees-without-createevaluater",n}function ig(e){const t={};let n;for(n in e)eo.call(e,n)&&(t[og(n)]=e[n]);return t}function og(e){let t=e.replace(Um,ag);return t.slice(0,3)==="ms-"&&(t="-"+t),t}function ag(e){return"-"+e.toLowerCase()}const Zr={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"]},lg={};function cg(e,t){const n=lg,s=typeof n.includeImageAlt=="boolean"?n.includeImageAlt:!0,r=typeof n.includeHtml=="boolean"?n.includeHtml:!0;return fc(e,s,r)}function fc(e,t,n){if(ug(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 Na(e.children,t,n)}return Array.isArray(e)?Na(e,t,n):""}function Na(e,t,n){const s=[];let r=-1;for(;++r<e.length;)s[r]=fc(e[r],t,n);return s.join("")}function ug(e){return!!(e&&typeof e=="object")}const Ta=document.createElement("i");function so(e){const t="&"+e+";";Ta.innerHTML=t;const n=Ta.textContent;return n.charCodeAt(n.length-1)===59&&e!=="semi"||n===t?!1:n}function ct(e,t,n,s){const r=e.length;let i=0,a;if(t<0?t=-t>r?0:r+t:t=t>r?r:t,n=n>0?n:0,s.length<1e4)a=Array.from(s),a.unshift(t,n),e.splice(...a);else for(n&&e.splice(t,n);i<s.length;)a=s.slice(i,i+1e4),a.unshift(t,0),e.splice(...a),i+=1e4,t+=1e4}function Ge(e,t){return e.length>0?(ct(e,e.length,0,t),e):t}const Pa={}.hasOwnProperty;function dg(e){const t={};let n=-1;for(;++n<e.length;)hg(t,e[n]);return t}function hg(e,t){let n;for(n in t){const r=(Pa.call(e,n)?e[n]:void 0)||(e[n]={}),i=t[n];let a;if(i)for(a in i){Pa.call(r,a)||(r[a]=[]);const l=i[a];fg(r[a],Array.isArray(l)?l:l?[l]:[])}}}function fg(e,t){let n=-1;const s=[];for(;++n<t.length;)(t[n].add==="after"?e:s).push(t[n]);ct(e,0,0,s)}function pc(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 an(e){return e.replace(/[\t\n\r ]+/g," ").replace(/^ | $/g,"").toLowerCase().toUpperCase()}const lt=Lt(/[A-Za-z]/),Be=Lt(/[\dA-Za-z]/),pg=Lt(/[#-'*+\--9=?A-Z^-~]/);function Pi(e){return e!==null&&(e<32||e===127)}const Ii=Lt(/\d/),mg=Lt(/[\dA-Fa-f]/),gg=Lt(/[!-/:-@[-`{-~]/);function ee(e){return e!==null&&e<-2}function Oe(e){return e!==null&&(e<0||e===32)}function ce(e){return e===-2||e===-1||e===32}const xg=Lt(/\p{P}|\p{S}/u),yg=Lt(/\s/);function Lt(e){return t;function t(n){return n!==null&&n>-1&&e.test(String.fromCharCode(n))}}function un(e){const t=[];let n=-1,s=0,r=0;for(;++n<e.length;){const i=e.charCodeAt(n);let a="";if(i===37&&Be(e.charCodeAt(n+1))&&Be(e.charCodeAt(n+2)))r=2;else if(i<128)/[!#$&-;=?-Z_a-z~]/.test(String.fromCharCode(i))||(a=String.fromCharCode(i));else if(i>55295&&i<57344){const l=e.charCodeAt(n+1);i<56320&&l>56319&&l<57344?(a=String.fromCharCode(i,l),r=1):a="�"}else a=String.fromCharCode(i);a&&(t.push(e.slice(s,n),encodeURIComponent(a)),s=n+r+1,a=""),r&&(n+=r,r=0)}return t.join("")+e.slice(s)}function fe(e,t,n,s){const r=s?s-1:Number.POSITIVE_INFINITY;let i=0;return a;function a(c){return ce(c)?(e.enter(n),l(c)):t(c)}function l(c){return ce(c)&&i++<r?(e.consume(c),l):(e.exit(n),t(c))}}const bg={tokenize:wg};function wg(e){const t=e.attempt(this.parser.constructs.contentInitial,s,r);let n;return t;function s(l){if(l===null){e.consume(l);return}return e.enter("lineEnding"),e.consume(l),e.exit("lineEnding"),fe(e,t,"linePrefix")}function r(l){return e.enter("paragraph"),i(l)}function i(l){const c=e.enter("chunkText",{contentType:"text",previous:n});return n&&(n.next=c),n=c,a(l)}function a(l){if(l===null){e.exit("chunkText"),e.exit("paragraph"),e.consume(l);return}return ee(l)?(e.consume(l),e.exit("chunkText"),i):(e.consume(l),a)}}const Sg={tokenize:vg},Ia={tokenize:Cg};function vg(e){const t=this,n=[];let s=0,r,i,a;return l;function l(C){if(s<n.length){const T=n[s];return t.containerState=T[1],e.attempt(T[0].continuation,c,u)(C)}return u(C)}function c(C){if(s++,t.containerState._closeFlow){t.containerState._closeFlow=void 0,r&&I();const T=t.events.length;let _=T,E;for(;_--;)if(t.events[_][0]==="exit"&&t.events[_][1].type==="chunkFlow"){E=t.events[_][1].end;break}S(s);let R=T;for(;R<t.events.length;)t.events[R][1].end={...E},R++;return ct(t.events,_+1,0,t.events.slice(T)),t.events.length=R,u(C)}return l(C)}function u(C){if(s===n.length){if(!r)return m(C);if(r.currentConstruct&&r.currentConstruct.concrete)return g(C);t.interrupt=!!(r.currentConstruct&&!r._gfmTableDynamicInterruptHack)}return t.containerState={},e.check(Ia,d,h)(C)}function d(C){return r&&I(),S(s),m(C)}function h(C){return t.parser.lazy[t.now().line]=s!==n.length,a=t.now().offset,g(C)}function m(C){return t.containerState={},e.attempt(Ia,f,g)(C)}function f(C){return s++,n.push([t.currentConstruct,t.containerState]),m(C)}function g(C){if(C===null){r&&I(),S(0),e.consume(C);return}return r=r||t.parser.flow(t.now()),e.enter("chunkFlow",{_tokenizer:r,contentType:"flow",previous:i}),y(C)}function y(C){if(C===null){k(e.exit("chunkFlow"),!0),S(0),e.consume(C);return}return ee(C)?(e.consume(C),k(e.exit("chunkFlow")),s=0,t.interrupt=void 0,l):(e.consume(C),y)}function k(C,T){const _=t.sliceStream(C);if(T&&_.push(null),C.previous=i,i&&(i.next=C),i=C,r.defineSkip(C.start),r.write(_),t.parser.lazy[C.start.line]){let E=r.events.length;for(;E--;)if(r.events[E][1].start.offset<a&&(!r.events[E][1].end||r.events[E][1].end.offset>a))return;const R=t.events.length;let B=R,F,M;for(;B--;)if(t.events[B][0]==="exit"&&t.events[B][1].type==="chunkFlow"){if(F){M=t.events[B][1].end;break}F=!0}for(S(s),E=R;E<t.events.length;)t.events[E][1].end={...M},E++;ct(t.events,B+1,0,t.events.slice(R)),t.events.length=E}}function S(C){let T=n.length;for(;T-- >C;){const _=n[T];t.containerState=_[1],_[0].exit.call(t,e)}n.length=C}function I(){r.write([null]),i=void 0,r=void 0,t.containerState._closeFlow=void 0}}function Cg(e,t,n){return fe(e,e.attempt(this.parser.constructs.document,t,n),"linePrefix",this.parser.constructs.disable.null.includes("codeIndented")?void 0:4)}function Aa(e){if(e===null||Oe(e)||yg(e))return 1;if(xg(e))return 2}function ro(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 Ai={name:"attention",resolveAll:kg,tokenize:Eg};function kg(e,t){let n=-1,s,r,i,a,l,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 h={...e[s][1].end},m={...e[n][1].start};za(h,-c),za(m,c),a={type:c>1?"strongSequence":"emphasisSequence",start:h,end:{...e[s][1].end}},l={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:{...a.start},end:{...l.end}},e[s][1].end={...a.start},e[n][1].start={...l.end},u=[],e[s][1].end.offset-e[s][1].start.offset&&(u=Ge(u,[["enter",e[s][1],t],["exit",e[s][1],t]])),u=Ge(u,[["enter",r,t],["enter",a,t],["exit",a,t],["enter",i,t]]),u=Ge(u,ro(t.parser.constructs.insideSpan.null,e.slice(s+1,n),t)),u=Ge(u,[["exit",i,t],["enter",l,t],["exit",l,t],["exit",r,t]]),e[n][1].end.offset-e[n][1].start.offset?(d=2,u=Ge(u,[["enter",e[n][1],t],["exit",e[n][1],t]])):d=0,ct(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 Eg(e,t){const n=this.parser.constructs.attentionMarkers.null,s=this.previous,r=Aa(s);let i;return a;function a(c){return i=c,e.enter("attentionSequence"),l(c)}function l(c){if(c===i)return e.consume(c),l;const u=e.exit("attentionSequence"),d=Aa(c),h=!d||d===2&&r||n.includes(c),m=!r||r===2&&d||n.includes(s);return u._open=!!(i===42?h:h&&(r||!m)),u._close=!!(i===42?m:m&&(d||!h)),t(c)}}function za(e,t){e.column+=t,e.offset+=t,e._bufferIndex+=t}const jg={name:"autolink",tokenize:Ng};function Ng(e,t,n){let s=0;return r;function r(f){return e.enter("autolink"),e.enter("autolinkMarker"),e.consume(f),e.exit("autolinkMarker"),e.enter("autolinkProtocol"),i}function i(f){return lt(f)?(e.consume(f),a):f===64?n(f):u(f)}function a(f){return f===43||f===45||f===46||Be(f)?(s=1,l(f)):u(f)}function l(f){return f===58?(e.consume(f),s=0,c):(f===43||f===45||f===46||Be(f))&&s++<32?(e.consume(f),l):(s=0,u(f))}function c(f){return f===62?(e.exit("autolinkProtocol"),e.enter("autolinkMarker"),e.consume(f),e.exit("autolinkMarker"),e.exit("autolink"),t):f===null||f===32||f===60||Pi(f)?n(f):(e.consume(f),c)}function u(f){return f===64?(e.consume(f),d):pg(f)?(e.consume(f),u):n(f)}function d(f){return Be(f)?h(f):n(f)}function h(f){return f===46?(e.consume(f),s=0,d):f===62?(e.exit("autolinkProtocol").type="autolinkEmail",e.enter("autolinkMarker"),e.consume(f),e.exit("autolinkMarker"),e.exit("autolink"),t):m(f)}function m(f){if((f===45||Be(f))&&s++<63){const g=f===45?m:h;return e.consume(f),g}return n(f)}}const Fs={partial:!0,tokenize:Tg};function Tg(e,t,n){return s;function s(i){return ce(i)?fe(e,r,"linePrefix")(i):r(i)}function r(i){return i===null||ee(i)?t(i):n(i)}}const mc={continuation:{tokenize:Ig},exit:Ag,name:"blockQuote",tokenize:Pg};function Pg(e,t,n){const s=this;return r;function r(a){if(a===62){const l=s.containerState;return l.open||(e.enter("blockQuote",{_container:!0}),l.open=!0),e.enter("blockQuotePrefix"),e.enter("blockQuoteMarker"),e.consume(a),e.exit("blockQuoteMarker"),i}return n(a)}function i(a){return ce(a)?(e.enter("blockQuotePrefixWhitespace"),e.consume(a),e.exit("blockQuotePrefixWhitespace"),e.exit("blockQuotePrefix"),t):(e.exit("blockQuotePrefix"),t(a))}}function Ig(e,t,n){const s=this;return r;function r(a){return ce(a)?fe(e,i,"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(a):i(a)}function i(a){return e.attempt(mc,t,n)(a)}}function Ag(e){e.exit("blockQuote")}const gc={name:"characterEscape",tokenize:zg};function zg(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 gg(i)?(e.enter("characterEscapeValue"),e.consume(i),e.exit("characterEscapeValue"),e.exit("characterEscape"),t):n(i)}}const xc={name:"characterReference",tokenize:_g};function _g(e,t,n){const s=this;let r=0,i,a;return l;function l(h){return e.enter("characterReference"),e.enter("characterReferenceMarker"),e.consume(h),e.exit("characterReferenceMarker"),c}function c(h){return h===35?(e.enter("characterReferenceMarkerNumeric"),e.consume(h),e.exit("characterReferenceMarkerNumeric"),u):(e.enter("characterReferenceValue"),i=31,a=Be,d(h))}function u(h){return h===88||h===120?(e.enter("characterReferenceMarkerHexadecimal"),e.consume(h),e.exit("characterReferenceMarkerHexadecimal"),e.enter("characterReferenceValue"),i=6,a=mg,d):(e.enter("characterReferenceValue"),i=7,a=Ii,d(h))}function d(h){if(h===59&&r){const m=e.exit("characterReferenceValue");return a===Be&&!so(s.sliceSerialize(m))?n(h):(e.enter("characterReferenceMarker"),e.consume(h),e.exit("characterReferenceMarker"),e.exit("characterReference"),t)}return a(h)&&r++<i?(e.consume(h),d):n(h)}}const _a={partial:!0,tokenize:Rg},La={concrete:!0,name:"codeFenced",tokenize:Lg};function Lg(e,t,n){const s=this,r={partial:!0,tokenize:_};let i=0,a=0,l;return c;function c(E){return u(E)}function u(E){const R=s.events[s.events.length-1];return i=R&&R[1].type==="linePrefix"?R[2].sliceSerialize(R[1],!0).length:0,l=E,e.enter("codeFenced"),e.enter("codeFencedFence"),e.enter("codeFencedFenceSequence"),d(E)}function d(E){return E===l?(a++,e.consume(E),d):a<3?n(E):(e.exit("codeFencedFenceSequence"),ce(E)?fe(e,h,"whitespace")(E):h(E))}function h(E){return E===null||ee(E)?(e.exit("codeFencedFence"),s.interrupt?t(E):e.check(_a,y,T)(E)):(e.enter("codeFencedFenceInfo"),e.enter("chunkString",{contentType:"string"}),m(E))}function m(E){return E===null||ee(E)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),h(E)):ce(E)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),fe(e,f,"whitespace")(E)):E===96&&E===l?n(E):(e.consume(E),m)}function f(E){return E===null||ee(E)?h(E):(e.enter("codeFencedFenceMeta"),e.enter("chunkString",{contentType:"string"}),g(E))}function g(E){return E===null||ee(E)?(e.exit("chunkString"),e.exit("codeFencedFenceMeta"),h(E)):E===96&&E===l?n(E):(e.consume(E),g)}function y(E){return e.attempt(r,T,k)(E)}function k(E){return e.enter("lineEnding"),e.consume(E),e.exit("lineEnding"),S}function S(E){return i>0&&ce(E)?fe(e,I,"linePrefix",i+1)(E):I(E)}function I(E){return E===null||ee(E)?e.check(_a,y,T)(E):(e.enter("codeFlowValue"),C(E))}function C(E){return E===null||ee(E)?(e.exit("codeFlowValue"),I(E)):(e.consume(E),C)}function T(E){return e.exit("codeFenced"),t(E)}function _(E,R,B){let F=0;return M;function M(j){return E.enter("lineEnding"),E.consume(j),E.exit("lineEnding"),v}function v(j){return E.enter("codeFencedFence"),ce(j)?fe(E,z,"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(j):z(j)}function z(j){return j===l?(E.enter("codeFencedFenceSequence"),L(j)):B(j)}function L(j){return j===l?(F++,E.consume(j),L):F>=a?(E.exit("codeFencedFenceSequence"),ce(j)?fe(E,P,"whitespace")(j):P(j)):B(j)}function P(j){return j===null||ee(j)?(E.exit("codeFencedFence"),R(j)):B(j)}}}function Rg(e,t,n){const s=this;return r;function r(a){return a===null?n(a):(e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),i)}function i(a){return s.parser.lazy[s.now().line]?n(a):t(a)}}const Yr={name:"codeIndented",tokenize:Og},Mg={partial:!0,tokenize:Dg};function Og(e,t,n){const s=this;return r;function r(u){return e.enter("codeIndented"),fe(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?a(u):n(u)}function a(u){return u===null?c(u):ee(u)?e.attempt(Mg,a,c)(u):(e.enter("codeFlowValue"),l(u))}function l(u){return u===null||ee(u)?(e.exit("codeFlowValue"),a(u)):(e.consume(u),l)}function c(u){return e.exit("codeIndented"),t(u)}}function Dg(e,t,n){const s=this;return r;function r(a){return s.parser.lazy[s.now().line]?n(a):ee(a)?(e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),r):fe(e,i,"linePrefix",5)(a)}function i(a){const l=s.events[s.events.length-1];return l&&l[1].type==="linePrefix"&&l[2].sliceSerialize(l[1],!0).length>=4?t(a):ee(a)?r(a):n(a)}}const Fg={name:"codeText",previous:Bg,resolve:$g,tokenize:Vg};function $g(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 Bg(e){return e!==96||this.events[this.events.length-1][1].type==="characterEscape"}function Vg(e,t,n){let s=0,r,i;return a;function a(h){return e.enter("codeText"),e.enter("codeTextSequence"),l(h)}function l(h){return h===96?(e.consume(h),s++,l):(e.exit("codeTextSequence"),c(h))}function c(h){return h===null?n(h):h===32?(e.enter("space"),e.consume(h),e.exit("space"),c):h===96?(i=e.enter("codeTextSequence"),r=0,d(h)):ee(h)?(e.enter("lineEnding"),e.consume(h),e.exit("lineEnding"),c):(e.enter("codeTextData"),u(h))}function u(h){return h===null||h===32||h===96||ee(h)?(e.exit("codeTextData"),c(h)):(e.consume(h),u)}function d(h){return h===96?(e.consume(h),r++,d):r===s?(e.exit("codeTextSequence"),e.exit("codeText"),t(h)):(i.type="codeTextData",u(h))}}class Ug{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&&kn(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),kn(this.left,t)}unshift(t){this.setCursor(0),this.right.push(t)}unshiftMany(t){this.setCursor(0),kn(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);kn(this.right,n.reverse())}else{const n=this.right.splice(this.left.length+this.right.length-t,Number.POSITIVE_INFINITY);kn(this.left,n.reverse())}}}function kn(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 yc(e){const t={};let n=-1,s,r,i,a,l,c,u;const d=new Ug(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,Hg(d,n)),n=t[n],u=!0);else if(s[1]._container){for(i=n,r=void 0;i--;)if(a=d.get(i),a[1].type==="lineEnding"||a[1].type==="lineEndingBlank")a[0]==="enter"&&(r&&(d.get(r)[1].type="lineEndingBlank"),a[1].type="lineEnding",r=i);else if(!(a[1].type==="linePrefix"||a[1].type==="listItemIndent"))break;r&&(s[1].end={...d.get(r)[1].start},l=d.slice(r,n),l.unshift(s),d.splice(r,n-r+1,l))}}return ct(e,0,Number.POSITIVE_INFINITY,d.slice(0)),!u}function Hg(e,t){const n=e.get(t)[1],s=e.get(t)[2];let r=t-1;const i=[];let a=n._tokenizer;a||(a=s.parser[n.contentType](n.start),n._contentTypeTextTrailing&&(a._contentTypeTextTrailing=!0));const l=a.events,c=[],u={};let d,h,m=-1,f=n,g=0,y=0;const k=[y];for(;f;){for(;e.get(++r)[1]!==f;);i.push(r),f._tokenizer||(d=s.sliceStream(f),f.next||d.push(null),h&&a.defineSkip(f.start),f._isInFirstContentOfListItem&&(a._gfmTasklistFirstContentOfListItem=!0),a.write(d),f._isInFirstContentOfListItem&&(a._gfmTasklistFirstContentOfListItem=void 0)),h=f,f=f.next}for(f=n;++m<l.length;)l[m][0]==="exit"&&l[m-1][0]==="enter"&&l[m][1].type===l[m-1][1].type&&l[m][1].start.line!==l[m][1].end.line&&(y=m+1,k.push(y),f._tokenizer=void 0,f.previous=void 0,f=f.next);for(a.events=[],f?(f._tokenizer=void 0,f.previous=void 0):k.pop(),m=k.length;m--;){const S=l.slice(k[m],k[m+1]),I=i.pop();c.push([I,I+S.length-1]),e.splice(I,2,S)}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 qg={resolve:Gg,tokenize:Qg},Wg={partial:!0,tokenize:Jg};function Gg(e){return yc(e),e}function Qg(e,t){let n;return s;function s(l){return e.enter("content"),n=e.enter("chunkContent",{contentType:"content"}),r(l)}function r(l){return l===null?i(l):ee(l)?e.check(Wg,a,i)(l):(e.consume(l),r)}function i(l){return e.exit("chunkContent"),e.exit("content"),t(l)}function a(l){return e.consume(l),e.exit("chunkContent"),n.next=e.enter("chunkContent",{contentType:"content",previous:n}),n=n.next,r}}function Jg(e,t,n){const s=this;return r;function r(a){return e.exit("chunkContent"),e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),fe(e,i,"linePrefix")}function i(a){if(a===null||ee(a))return n(a);const l=s.events[s.events.length-1];return!s.parser.constructs.disable.null.includes("codeIndented")&&l&&l[1].type==="linePrefix"&&l[2].sliceSerialize(l[1],!0).length>=4?t(a):e.interrupt(s.parser.constructs.flow,n,t)(a)}}function bc(e,t,n,s,r,i,a,l,c){const u=c||Number.POSITIVE_INFINITY;let d=0;return h;function h(S){return S===60?(e.enter(s),e.enter(r),e.enter(i),e.consume(S),e.exit(i),m):S===null||S===32||S===41||Pi(S)?n(S):(e.enter(s),e.enter(a),e.enter(l),e.enter("chunkString",{contentType:"string"}),y(S))}function m(S){return S===62?(e.enter(i),e.consume(S),e.exit(i),e.exit(r),e.exit(s),t):(e.enter(l),e.enter("chunkString",{contentType:"string"}),f(S))}function f(S){return S===62?(e.exit("chunkString"),e.exit(l),m(S)):S===null||S===60||ee(S)?n(S):(e.consume(S),S===92?g:f)}function g(S){return S===60||S===62||S===92?(e.consume(S),f):f(S)}function y(S){return!d&&(S===null||S===41||Oe(S))?(e.exit("chunkString"),e.exit(l),e.exit(a),e.exit(s),t(S)):d<u&&S===40?(e.consume(S),d++,y):S===41?(e.consume(S),d--,y):S===null||S===32||S===40||Pi(S)?n(S):(e.consume(S),S===92?k:y)}function k(S){return S===40||S===41||S===92?(e.consume(S),y):y(S)}}function wc(e,t,n,s,r,i){const a=this;let l=0,c;return u;function u(f){return e.enter(s),e.enter(r),e.consume(f),e.exit(r),e.enter(i),d}function d(f){return l>999||f===null||f===91||f===93&&!c||f===94&&!l&&"_hiddenFootnoteSupport"in a.parser.constructs?n(f):f===93?(e.exit(i),e.enter(r),e.consume(f),e.exit(r),e.exit(s),t):ee(f)?(e.enter("lineEnding"),e.consume(f),e.exit("lineEnding"),d):(e.enter("chunkString",{contentType:"string"}),h(f))}function h(f){return f===null||f===91||f===93||ee(f)||l++>999?(e.exit("chunkString"),d(f)):(e.consume(f),c||(c=!ce(f)),f===92?m:h)}function m(f){return f===91||f===92||f===93?(e.consume(f),l++,h):h(f)}}function Sc(e,t,n,s,r,i){let a;return l;function l(m){return m===34||m===39||m===40?(e.enter(s),e.enter(r),e.consume(m),e.exit(r),a=m===40?41:m,c):n(m)}function c(m){return m===a?(e.enter(r),e.consume(m),e.exit(r),e.exit(s),t):(e.enter(i),u(m))}function u(m){return m===a?(e.exit(i),c(a)):m===null?n(m):ee(m)?(e.enter("lineEnding"),e.consume(m),e.exit("lineEnding"),fe(e,u,"linePrefix")):(e.enter("chunkString",{contentType:"string"}),d(m))}function d(m){return m===a||m===null||ee(m)?(e.exit("chunkString"),u(m)):(e.consume(m),m===92?h:d)}function h(m){return m===a||m===92?(e.consume(m),d):d(m)}}function In(e,t){let n;return s;function s(r){return ee(r)?(e.enter("lineEnding"),e.consume(r),e.exit("lineEnding"),n=!0,s):ce(r)?fe(e,s,n?"linePrefix":"lineSuffix")(r):t(r)}}const Zg={name:"definition",tokenize:Kg},Yg={partial:!0,tokenize:Xg};function Kg(e,t,n){const s=this;let r;return i;function i(f){return e.enter("definition"),a(f)}function a(f){return wc.call(s,e,l,n,"definitionLabel","definitionLabelMarker","definitionLabelString")(f)}function l(f){return r=an(s.sliceSerialize(s.events[s.events.length-1][1]).slice(1,-1)),f===58?(e.enter("definitionMarker"),e.consume(f),e.exit("definitionMarker"),c):n(f)}function c(f){return Oe(f)?In(e,u)(f):u(f)}function u(f){return bc(e,d,n,"definitionDestination","definitionDestinationLiteral","definitionDestinationLiteralMarker","definitionDestinationRaw","definitionDestinationString")(f)}function d(f){return e.attempt(Yg,h,h)(f)}function h(f){return ce(f)?fe(e,m,"whitespace")(f):m(f)}function m(f){return f===null||ee(f)?(e.exit("definition"),s.parser.defined.push(r),t(f)):n(f)}}function Xg(e,t,n){return s;function s(l){return Oe(l)?In(e,r)(l):n(l)}function r(l){return Sc(e,i,n,"definitionTitle","definitionTitleMarker","definitionTitleString")(l)}function i(l){return ce(l)?fe(e,a,"whitespace")(l):a(l)}function a(l){return l===null||ee(l)?t(l):n(l)}}const ex={name:"hardBreakEscape",tokenize:tx};function tx(e,t,n){return s;function s(i){return e.enter("hardBreakEscape"),e.consume(i),r}function r(i){return ee(i)?(e.exit("hardBreakEscape"),t(i)):n(i)}}const nx={name:"headingAtx",resolve:sx,tokenize:rx};function sx(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"},ct(e,s,n-s+1,[["enter",r,t],["enter",i,t],["exit",i,t],["exit",r,t]])),e}function rx(e,t,n){let s=0;return r;function r(d){return e.enter("atxHeading"),i(d)}function i(d){return e.enter("atxHeadingSequence"),a(d)}function a(d){return d===35&&s++<6?(e.consume(d),a):d===null||Oe(d)?(e.exit("atxHeadingSequence"),l(d)):n(d)}function l(d){return d===35?(e.enter("atxHeadingSequence"),c(d)):d===null||ee(d)?(e.exit("atxHeading"),t(d)):ce(d)?fe(e,l,"whitespace")(d):(e.enter("atxHeadingText"),u(d))}function c(d){return d===35?(e.consume(d),c):(e.exit("atxHeadingSequence"),l(d))}function u(d){return d===null||d===35||Oe(d)?(e.exit("atxHeadingText"),l(d)):(e.consume(d),u)}}const ix=["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"],Ra=["pre","script","style","textarea"],ox={concrete:!0,name:"htmlFlow",resolveTo:cx,tokenize:ux},ax={partial:!0,tokenize:hx},lx={partial:!0,tokenize:dx};function cx(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 ux(e,t,n){const s=this;let r,i,a,l,c;return u;function u(b){return d(b)}function d(b){return e.enter("htmlFlow"),e.enter("htmlFlowData"),e.consume(b),h}function h(b){return b===33?(e.consume(b),m):b===47?(e.consume(b),i=!0,y):b===63?(e.consume(b),r=3,s.interrupt?t:x):lt(b)?(e.consume(b),a=String.fromCharCode(b),k):n(b)}function m(b){return b===45?(e.consume(b),r=2,f):b===91?(e.consume(b),r=5,l=0,g):lt(b)?(e.consume(b),r=4,s.interrupt?t:x):n(b)}function f(b){return b===45?(e.consume(b),s.interrupt?t:x):n(b)}function g(b){const J="CDATA[";return b===J.charCodeAt(l++)?(e.consume(b),l===J.length?s.interrupt?t:z:g):n(b)}function y(b){return lt(b)?(e.consume(b),a=String.fromCharCode(b),k):n(b)}function k(b){if(b===null||b===47||b===62||Oe(b)){const J=b===47,D=a.toLowerCase();return!J&&!i&&Ra.includes(D)?(r=1,s.interrupt?t(b):z(b)):ix.includes(a.toLowerCase())?(r=6,J?(e.consume(b),S):s.interrupt?t(b):z(b)):(r=7,s.interrupt&&!s.parser.lazy[s.now().line]?n(b):i?I(b):C(b))}return b===45||Be(b)?(e.consume(b),a+=String.fromCharCode(b),k):n(b)}function S(b){return b===62?(e.consume(b),s.interrupt?t:z):n(b)}function I(b){return ce(b)?(e.consume(b),I):M(b)}function C(b){return b===47?(e.consume(b),M):b===58||b===95||lt(b)?(e.consume(b),T):ce(b)?(e.consume(b),C):M(b)}function T(b){return b===45||b===46||b===58||b===95||Be(b)?(e.consume(b),T):_(b)}function _(b){return b===61?(e.consume(b),E):ce(b)?(e.consume(b),_):C(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,R):ce(b)?(e.consume(b),E):B(b)}function R(b){return b===c?(e.consume(b),c=null,F):b===null||ee(b)?n(b):(e.consume(b),R)}function B(b){return b===null||b===34||b===39||b===47||b===60||b===61||b===62||b===96||Oe(b)?_(b):(e.consume(b),B)}function F(b){return b===47||b===62||ce(b)?C(b):n(b)}function M(b){return b===62?(e.consume(b),v):n(b)}function v(b){return b===null||ee(b)?z(b):ce(b)?(e.consume(b),v):n(b)}function z(b){return b===45&&r===2?(e.consume(b),A):b===60&&r===1?(e.consume(b),U):b===62&&r===4?(e.consume(b),oe):b===63&&r===3?(e.consume(b),x):b===93&&r===5?(e.consume(b),O):ee(b)&&(r===6||r===7)?(e.exit("htmlFlowData"),e.check(ax,pe,L)(b)):b===null||ee(b)?(e.exit("htmlFlowData"),L(b)):(e.consume(b),z)}function L(b){return e.check(lx,P,pe)(b)}function P(b){return e.enter("lineEnding"),e.consume(b),e.exit("lineEnding"),j}function j(b){return b===null||ee(b)?L(b):(e.enter("htmlFlowData"),z(b))}function A(b){return b===45?(e.consume(b),x):z(b)}function U(b){return b===47?(e.consume(b),a="",N):z(b)}function N(b){if(b===62){const J=a.toLowerCase();return Ra.includes(J)?(e.consume(b),oe):z(b)}return lt(b)&&a.length<8?(e.consume(b),a+=String.fromCharCode(b),N):z(b)}function O(b){return b===93?(e.consume(b),x):z(b)}function x(b){return b===62?(e.consume(b),oe):b===45&&r===2?(e.consume(b),x):z(b)}function oe(b){return b===null||ee(b)?(e.exit("htmlFlowData"),pe(b)):(e.consume(b),oe)}function pe(b){return e.exit("htmlFlow"),t(b)}}function dx(e,t,n){const s=this;return r;function r(a){return ee(a)?(e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),i):n(a)}function i(a){return s.parser.lazy[s.now().line]?n(a):t(a)}}function hx(e,t,n){return s;function s(r){return e.enter("lineEnding"),e.consume(r),e.exit("lineEnding"),e.attempt(Fs,t,n)}}const fx={name:"htmlText",tokenize:px};function px(e,t,n){const s=this;let r,i,a;return l;function l(x){return e.enter("htmlText"),e.enter("htmlTextData"),e.consume(x),c}function c(x){return x===33?(e.consume(x),u):x===47?(e.consume(x),_):x===63?(e.consume(x),C):lt(x)?(e.consume(x),B):n(x)}function u(x){return x===45?(e.consume(x),d):x===91?(e.consume(x),i=0,g):lt(x)?(e.consume(x),I):n(x)}function d(x){return x===45?(e.consume(x),f):n(x)}function h(x){return x===null?n(x):x===45?(e.consume(x),m):ee(x)?(a=h,U(x)):(e.consume(x),h)}function m(x){return x===45?(e.consume(x),f):h(x)}function f(x){return x===62?A(x):x===45?m(x):h(x)}function g(x){const oe="CDATA[";return x===oe.charCodeAt(i++)?(e.consume(x),i===oe.length?y:g):n(x)}function y(x){return x===null?n(x):x===93?(e.consume(x),k):ee(x)?(a=y,U(x)):(e.consume(x),y)}function k(x){return x===93?(e.consume(x),S):y(x)}function S(x){return x===62?A(x):x===93?(e.consume(x),S):y(x)}function I(x){return x===null||x===62?A(x):ee(x)?(a=I,U(x)):(e.consume(x),I)}function C(x){return x===null?n(x):x===63?(e.consume(x),T):ee(x)?(a=C,U(x)):(e.consume(x),C)}function T(x){return x===62?A(x):C(x)}function _(x){return lt(x)?(e.consume(x),E):n(x)}function E(x){return x===45||Be(x)?(e.consume(x),E):R(x)}function R(x){return ee(x)?(a=R,U(x)):ce(x)?(e.consume(x),R):A(x)}function B(x){return x===45||Be(x)?(e.consume(x),B):x===47||x===62||Oe(x)?F(x):n(x)}function F(x){return x===47?(e.consume(x),A):x===58||x===95||lt(x)?(e.consume(x),M):ee(x)?(a=F,U(x)):ce(x)?(e.consume(x),F):A(x)}function M(x){return x===45||x===46||x===58||x===95||Be(x)?(e.consume(x),M):v(x)}function v(x){return x===61?(e.consume(x),z):ee(x)?(a=v,U(x)):ce(x)?(e.consume(x),v):F(x)}function z(x){return x===null||x===60||x===61||x===62||x===96?n(x):x===34||x===39?(e.consume(x),r=x,L):ee(x)?(a=z,U(x)):ce(x)?(e.consume(x),z):(e.consume(x),P)}function L(x){return x===r?(e.consume(x),r=void 0,j):x===null?n(x):ee(x)?(a=L,U(x)):(e.consume(x),L)}function P(x){return x===null||x===34||x===39||x===60||x===61||x===96?n(x):x===47||x===62||Oe(x)?F(x):(e.consume(x),P)}function j(x){return x===47||x===62||Oe(x)?F(x):n(x)}function A(x){return x===62?(e.consume(x),e.exit("htmlTextData"),e.exit("htmlText"),t):n(x)}function U(x){return e.exit("htmlTextData"),e.enter("lineEnding"),e.consume(x),e.exit("lineEnding"),N}function N(x){return ce(x)?fe(e,O,"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(x):O(x)}function O(x){return e.enter("htmlTextData"),a(x)}}const io={name:"labelEnd",resolveAll:yx,resolveTo:bx,tokenize:wx},mx={tokenize:Sx},gx={tokenize:vx},xx={tokenize:Cx};function yx(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&&ct(e,0,e.length,n),e}function bx(e,t){let n=e.length,s=0,r,i,a,l;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(a){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"&&(a=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[a][1].end}},d={type:"labelText",start:{...e[i+s+2][1].end},end:{...e[a-2][1].start}};return l=[["enter",c,t],["enter",u,t]],l=Ge(l,e.slice(i+1,i+s+3)),l=Ge(l,[["enter",d,t]]),l=Ge(l,ro(t.parser.constructs.insideSpan.null,e.slice(i+s+4,a-3),t)),l=Ge(l,[["exit",d,t],e[a-2],e[a-1],["exit",u,t]]),l=Ge(l,e.slice(a+1)),l=Ge(l,[["exit",c,t]]),ct(e,i,e.length,l),e}function wx(e,t,n){const s=this;let r=s.events.length,i,a;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 l;function l(m){return i?i._inactive?h(m):(a=s.parser.defined.includes(an(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(mx,d,a?d:h)(m):m===91?e.attempt(gx,d,a?u:h)(m):a?d(m):h(m)}function u(m){return e.attempt(xx,d,h)(m)}function d(m){return t(m)}function h(m){return i._balanced=!0,n(m)}}function Sx(e,t,n){return s;function s(h){return e.enter("resource"),e.enter("resourceMarker"),e.consume(h),e.exit("resourceMarker"),r}function r(h){return Oe(h)?In(e,i)(h):i(h)}function i(h){return h===41?d(h):bc(e,a,l,"resourceDestination","resourceDestinationLiteral","resourceDestinationLiteralMarker","resourceDestinationRaw","resourceDestinationString",32)(h)}function a(h){return Oe(h)?In(e,c)(h):d(h)}function l(h){return n(h)}function c(h){return h===34||h===39||h===40?Sc(e,u,n,"resourceTitle","resourceTitleMarker","resourceTitleString")(h):d(h)}function u(h){return Oe(h)?In(e,d)(h):d(h)}function d(h){return h===41?(e.enter("resourceMarker"),e.consume(h),e.exit("resourceMarker"),e.exit("resource"),t):n(h)}}function vx(e,t,n){const s=this;return r;function r(l){return wc.call(s,e,i,a,"reference","referenceMarker","referenceString")(l)}function i(l){return s.parser.defined.includes(an(s.sliceSerialize(s.events[s.events.length-1][1]).slice(1,-1)))?t(l):n(l)}function a(l){return n(l)}}function Cx(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 kx={name:"labelStartImage",resolveAll:io.resolveAll,tokenize:Ex};function Ex(e,t,n){const s=this;return r;function r(l){return e.enter("labelImage"),e.enter("labelImageMarker"),e.consume(l),e.exit("labelImageMarker"),i}function i(l){return l===91?(e.enter("labelMarker"),e.consume(l),e.exit("labelMarker"),e.exit("labelImage"),a):n(l)}function a(l){return l===94&&"_hiddenFootnoteSupport"in s.parser.constructs?n(l):t(l)}}const jx={name:"labelStartLink",resolveAll:io.resolveAll,tokenize:Nx};function Nx(e,t,n){const s=this;return r;function r(a){return e.enter("labelLink"),e.enter("labelMarker"),e.consume(a),e.exit("labelMarker"),e.exit("labelLink"),i}function i(a){return a===94&&"_hiddenFootnoteSupport"in s.parser.constructs?n(a):t(a)}}const Kr={name:"lineEnding",tokenize:Tx};function Tx(e,t){return n;function n(s){return e.enter("lineEnding"),e.consume(s),e.exit("lineEnding"),fe(e,t,"linePrefix")}}const gs={name:"thematicBreak",tokenize:Px};function Px(e,t,n){let s=0,r;return i;function i(u){return e.enter("thematicBreak"),a(u)}function a(u){return r=u,l(u)}function l(u){return u===r?(e.enter("thematicBreakSequence"),c(u)):s>=3&&(u===null||ee(u))?(e.exit("thematicBreak"),t(u)):n(u)}function c(u){return u===r?(e.consume(u),s++,c):(e.exit("thematicBreakSequence"),ce(u)?fe(e,l,"whitespace")(u):l(u))}}const Me={continuation:{tokenize:_x},exit:Rx,name:"list",tokenize:zx},Ix={partial:!0,tokenize:Mx},Ax={partial:!0,tokenize:Lx};function zx(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,a=0;return l;function l(f){const g=s.containerState.type||(f===42||f===43||f===45?"listUnordered":"listOrdered");if(g==="listUnordered"?!s.containerState.marker||f===s.containerState.marker:Ii(f)){if(s.containerState.type||(s.containerState.type=g,e.enter(g,{_container:!0})),g==="listUnordered")return e.enter("listItemPrefix"),f===42||f===45?e.check(gs,n,u)(f):u(f);if(!s.interrupt||f===49)return e.enter("listItemPrefix"),e.enter("listItemValue"),c(f)}return n(f)}function c(f){return Ii(f)&&++a<10?(e.consume(f),c):(!s.interrupt||a<2)&&(s.containerState.marker?f===s.containerState.marker:f===41||f===46)?(e.exit("listItemValue"),u(f)):n(f)}function u(f){return e.enter("listItemMarker"),e.consume(f),e.exit("listItemMarker"),s.containerState.marker=s.containerState.marker||f,e.check(Fs,s.interrupt?n:d,e.attempt(Ix,m,h))}function d(f){return s.containerState.initialBlankLine=!0,i++,m(f)}function h(f){return ce(f)?(e.enter("listItemPrefixWhitespace"),e.consume(f),e.exit("listItemPrefixWhitespace"),m):n(f)}function m(f){return s.containerState.size=i+s.sliceSerialize(e.exit("listItemPrefix"),!0).length,t(f)}}function _x(e,t,n){const s=this;return s.containerState._closeFlow=void 0,e.check(Fs,r,i);function r(l){return s.containerState.furtherBlankLines=s.containerState.furtherBlankLines||s.containerState.initialBlankLine,fe(e,t,"listItemIndent",s.containerState.size+1)(l)}function i(l){return s.containerState.furtherBlankLines||!ce(l)?(s.containerState.furtherBlankLines=void 0,s.containerState.initialBlankLine=void 0,a(l)):(s.containerState.furtherBlankLines=void 0,s.containerState.initialBlankLine=void 0,e.attempt(Ax,t,a)(l))}function a(l){return s.containerState._closeFlow=!0,s.interrupt=void 0,fe(e,e.attempt(Me,t,n),"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(l)}}function Lx(e,t,n){const s=this;return fe(e,r,"listItemIndent",s.containerState.size+1);function r(i){const a=s.events[s.events.length-1];return a&&a[1].type==="listItemIndent"&&a[2].sliceSerialize(a[1],!0).length===s.containerState.size?t(i):n(i)}}function Rx(e){e.exit(this.containerState.type)}function Mx(e,t,n){const s=this;return fe(e,r,"listItemPrefixWhitespace",s.parser.constructs.disable.null.includes("codeIndented")?void 0:5);function r(i){const a=s.events[s.events.length-1];return!ce(i)&&a&&a[1].type==="listItemPrefixWhitespace"?t(i):n(i)}}const Ma={name:"setextUnderline",resolveTo:Ox,tokenize:Dx};function Ox(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 a={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",a,t]),e.splice(i+1,0,["exit",e[s][1],t]),e[s][1].end={...e[i][1].end}):e[s][1]=a,e.push(["exit",a,t]),e}function Dx(e,t,n){const s=this;let r;return i;function i(u){let d=s.events.length,h;for(;d--;)if(s.events[d][1].type!=="lineEnding"&&s.events[d][1].type!=="linePrefix"&&s.events[d][1].type!=="content"){h=s.events[d][1].type==="paragraph";break}return!s.parser.lazy[s.now().line]&&(s.interrupt||h)?(e.enter("setextHeadingLine"),r=u,a(u)):n(u)}function a(u){return e.enter("setextHeadingLineSequence"),l(u)}function l(u){return u===r?(e.consume(u),l):(e.exit("setextHeadingLineSequence"),ce(u)?fe(e,c,"lineSuffix")(u):c(u))}function c(u){return u===null||ee(u)?(e.exit("setextHeadingLine"),t(u)):n(u)}}const Fx={tokenize:$x};function $x(e){const t=this,n=e.attempt(Fs,s,e.attempt(this.parser.constructs.flowInitial,r,fe(e,e.attempt(this.parser.constructs.flow,r,e.attempt(qg,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 Bx={resolveAll:Cc()},Vx=vc("string"),Ux=vc("text");function vc(e){return{resolveAll:Cc(e==="text"?Hx:void 0),tokenize:t};function t(n){const s=this,r=this.parser.constructs[e],i=n.attempt(r,a,l);return a;function a(d){return u(d)?i(d):l(d)}function l(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 h=r[d];let m=-1;if(h)for(;++m<h.length;){const f=h[m];if(!f.previous||f.previous.call(s,s.previous))return!0}return!1}}}function Cc(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 Hx(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,a=-1,l=0,c;for(;i--;){const u=r[i];if(typeof u=="string"){for(a=u.length;u.charCodeAt(a-1)===32;)l++,a--;if(a)break;a=-1}else if(u===-2)c=!0,l++;else if(u!==-1){i++;break}}if(t._contentTypeTextTrailing&&n===e.length&&(l=0),l){const u={type:n===e.length||c||l<2?"lineSuffix":"hardBreakTrailing",start:{_bufferIndex:i?a:s.start._bufferIndex+a,_index:s.start._index+i,line:s.end.line,column:s.end.column-l,offset:s.end.offset-l},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 qx={42:Me,43:Me,45:Me,48:Me,49:Me,50:Me,51:Me,52:Me,53:Me,54:Me,55:Me,56:Me,57:Me,62:mc},Wx={91:Zg},Gx={[-2]:Yr,[-1]:Yr,32:Yr},Qx={35:nx,42:gs,45:[Ma,gs],60:ox,61:Ma,95:gs,96:La,126:La},Jx={38:xc,92:gc},Zx={[-5]:Kr,[-4]:Kr,[-3]:Kr,33:kx,38:xc,42:Ai,60:[jg,fx],91:jx,92:[ex,gc],93:io,95:Ai,96:Fg},Yx={null:[Ai,Bx]},Kx={null:[42,95]},Xx={null:[]},ey=Object.freeze(Object.defineProperty({__proto__:null,attentionMarkers:Kx,contentInitial:Wx,disable:Xx,document:qx,flow:Qx,flowInitial:Gx,insideSpan:Yx,string:Jx,text:Zx},Symbol.toStringTag,{value:"Module"}));function ty(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 a=[],l=[];const c={attempt:R(_),check:R(E),consume:I,enter:C,exit:T,interrupt:R(E,{interrupt:!0})},u={code:null,containerState:{},defineSkip:y,events:[],now:g,parser:e,previous:null,sliceSerialize:m,sliceStream:f,write:h};let d=t.tokenize.call(u,c);return t.resolveAll&&i.push(t),u;function h(v){return a=Ge(a,v),k(),a[a.length-1]!==null?[]:(B(t,0),u.events=ro(i,u.events,u),u.events)}function m(v,z){return sy(f(v),z)}function f(v){return ny(a,v)}function g(){const{_bufferIndex:v,_index:z,line:L,column:P,offset:j}=s;return{_bufferIndex:v,_index:z,line:L,column:P,offset:j}}function y(v){r[v.line]=v.column,M()}function k(){let v;for(;s._index<a.length;){const z=a[s._index];if(typeof z=="string")for(v=s._index,s._bufferIndex<0&&(s._bufferIndex=0);s._index===v&&s._bufferIndex<z.length;)S(z.charCodeAt(s._bufferIndex));else S(z)}}function S(v){d=d(v)}function I(v){ee(v)?(s.line++,s.column=1,s.offset+=v===-3?2:1,M()):v!==-1&&(s.column++,s.offset++),s._bufferIndex<0?s._index++:(s._bufferIndex++,s._bufferIndex===a[s._index].length&&(s._bufferIndex=-1,s._index++)),u.previous=v}function C(v,z){const L=z||{};return L.type=v,L.start=g(),u.events.push(["enter",L,u]),l.push(L),L}function T(v){const z=l.pop();return z.end=g(),u.events.push(["exit",z,u]),z}function _(v,z){B(v,z.from)}function E(v,z){z.restore()}function R(v,z){return L;function L(P,j,A){let U,N,O,x;return Array.isArray(P)?pe(P):"tokenize"in P?pe([P]):oe(P);function oe(G){return re;function re(se){const we=se!==null&&G[se],me=se!==null&&G.null,le=[...Array.isArray(we)?we:we?[we]:[],...Array.isArray(me)?me:me?[me]:[]];return pe(le)(se)}}function pe(G){return U=G,N=0,G.length===0?A:b(G[N])}function b(G){return re;function re(se){return x=F(),O=G,G.partial||(u.currentConstruct=G),G.name&&u.parser.constructs.disable.null.includes(G.name)?D():G.tokenize.call(z?Object.assign(Object.create(u),z):u,c,J,D)(se)}}function J(G){return v(O,x),j}function D(G){return x.restore(),++N<U.length?b(U[N]):A}}}function B(v,z){v.resolveAll&&!i.includes(v)&&i.push(v),v.resolve&&ct(u.events,z,u.events.length-z,v.resolve(u.events.slice(z),u)),v.resolveTo&&(u.events=v.resolveTo(u.events,u))}function F(){const v=g(),z=u.previous,L=u.currentConstruct,P=u.events.length,j=Array.from(l);return{from:P,restore:A};function A(){s=v,u.previous=z,u.currentConstruct=L,u.events.length=P,l=j,M()}}function M(){s.line in r&&s.column<2&&(s.column=r[s.line],s.offset+=r[s.line]-1)}}function ny(e,t){const n=t.start._index,s=t.start._bufferIndex,r=t.end._index,i=t.end._bufferIndex;let a;if(n===r)a=[e[n].slice(s,i)];else{if(a=e.slice(n,r),s>-1){const l=a[0];typeof l=="string"?a[0]=l.slice(s):a.shift()}i>0&&a.push(e[r].slice(0,i))}return a}function sy(e,t){let n=-1;const s=[];let r;for(;++n<e.length;){const i=e[n];let a;if(typeof i=="string")a=i;else switch(i){case-5:{a="\r";break}case-4:{a=`
14
- `;break}case-3:{a=`\r
15
- `;break}case-2:{a=t?" ":" ";break}case-1:{if(!t&&r)continue;a=" ";break}default:a=String.fromCharCode(i)}r=i===-2,s.push(a)}return s.join("")}function ry(e){const s={constructs:dg([ey,...(e||{}).extensions||[]]),content:r(bg),defined:[],document:r(Sg),flow:r(Fx),lazy:{},string:r(Vx),text:r(Ux)};return s;function r(i){return a;function a(l){return ty(s,i,l)}}}function iy(e){for(;!yc(e););return e}const Oa=/[\0\t\n\r]/g;function oy(){let e=1,t="",n=!0,s;return r;function r(i,a,l){const c=[];let u,d,h,m,f;for(i=t+(typeof i=="string"?i.toString():new TextDecoder(a||void 0).decode(i)),h=0,t="",n&&(i.charCodeAt(0)===65279&&h++,n=void 0);h<i.length;){if(Oa.lastIndex=h,u=Oa.exec(i),m=u&&u.index!==void 0?u.index:i.length,f=i.charCodeAt(m),!u){t=i.slice(h);break}if(f===10&&h===m&&s)c.push(-3),s=void 0;else switch(s&&(c.push(-5),s=void 0),h<m&&(c.push(i.slice(h,m)),e+=m-h),f){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}h=m+1}return l&&(s&&c.push(-5),t&&c.push(t),c.push(null)),c}}const ay=/\\([!-/:-@[-`{-~])|&(#(?:\d{1,7}|x[\da-f]{1,6})|[\da-z]{1,31});/gi;function ly(e){return e.replace(ay,cy)}function cy(e,t,n){if(t)return t;if(n.charCodeAt(0)===35){const r=n.charCodeAt(1),i=r===120||r===88;return pc(n.slice(i?2:1),i?16:10)}return so(n)||e}const kc={}.hasOwnProperty;function uy(e,t,n){return t&&typeof t=="object"&&(n=t,t=void 0),dy(n)(iy(ry(n).document().write(oy()(e,t,!0))))}function dy(e){const t={transforms:[],canContainEols:["emphasis","fragment","heading","paragraph","strong"],enter:{autolink:i(te),autolinkProtocol:F,autolinkEmail:F,atxHeading:i(vt),blockQuote:i(me),characterEscape:F,characterReference:F,codeFenced:i(le),codeFencedFenceInfo:a,codeFencedFenceMeta:a,codeIndented:i(le,a),codeText:i(Ve,a),codeTextData:F,data:F,codeFlowValue:F,definition:i(St),definitionDestinationString:a,definitionLabelString:a,definitionTitleString:a,emphasis:i(Ut),hardBreakEscape:i(Ct),hardBreakTrailing:i(Ct),htmlFlow:i(Rt,a),htmlFlowData:F,htmlText:i(Rt,a),htmlTextData:F,image:i(Y),label:a,link:i(te),listItem:i(Ne),listItemValue:m,listOrdered:i(ae,h),listUnordered:i(ae),paragraph:i(Ue),reference:b,referenceString:a,resourceDestinationString:a,resourceTitleString:a,setextHeading:i(vt),strong:i(He),thematicBreak:i(Te)},exit:{atxHeading:c(),atxHeadingSequence:_,autolink:c(),autolinkEmail:we,autolinkProtocol:se,blockQuote:c(),characterEscapeValue:M,characterReferenceMarkerHexadecimal:D,characterReferenceMarkerNumeric:D,characterReferenceValue:G,characterReference:re,codeFenced:c(k),codeFencedFence:y,codeFencedFenceInfo:f,codeFencedFenceMeta:g,codeFlowValue:M,codeIndented:c(S),codeText:c(j),codeTextData:M,data:M,definition:c(),definitionDestinationString:T,definitionLabelString:I,definitionTitleString:C,emphasis:c(),hardBreakEscape:c(z),hardBreakTrailing:c(z),htmlFlow:c(L),htmlFlowData:M,htmlText:c(P),htmlTextData:M,image:c(U),label:O,labelText:N,lineEnding:v,link:c(A),listItem:c(),listOrdered:c(),listUnordered:c(),paragraph:c(),referenceString:J,resourceDestinationString:x,resourceTitleString:oe,resource:pe,setextHeading:c(B),setextHeadingLineSequence:R,setextHeadingText:E,strong:c(),thematicBreak:c()}};Ec(t,(e||{}).mdastExtensions||[]);const n={};return s;function s($){let q={type:"root",children:[]};const K={stack:[q],tokenStack:[],config:t,enter:l,exit:u,buffer:a,resume:d,data:n},Z=[];let X=-1;for(;++X<$.length;)if($[X][1].type==="listOrdered"||$[X][1].type==="listUnordered")if($[X][0]==="enter")Z.push(X);else{const Pe=Z.pop();X=r($,Pe,X)}for(X=-1;++X<$.length;){const Pe=t[$[X][0]];kc.call(Pe,$[X][1].type)&&Pe[$[X][1].type].call(Object.assign({sliceSerialize:$[X][2].sliceSerialize},K),$[X][1])}if(K.tokenStack.length>0){const Pe=K.tokenStack[K.tokenStack.length-1];(Pe[1]||Da).call(K,void 0,Pe[0])}for(q.position={start:It($.length>0?$[0][1].start:{line:1,column:1,offset:0}),end:It($.length>0?$[$.length-2][1].end:{line:1,column:1,offset:0})},X=-1;++X<t.transforms.length;)q=t.transforms[X](q)||q;return q}function r($,q,K){let Z=q-1,X=-1,Pe=!1,Ze,Fe,st,ht;for(;++Z<=K;){const ge=$[Z];switch(ge[1].type){case"listUnordered":case"listOrdered":case"blockQuote":{ge[0]==="enter"?X++:X--,ht=void 0;break}case"lineEndingBlank":{ge[0]==="enter"&&(Ze&&!ht&&!X&&!st&&(st=Z),ht=void 0);break}case"linePrefix":case"listItemValue":case"listItemMarker":case"listItemPrefix":case"listItemPrefixWhitespace":break;default:ht=void 0}if(!X&&ge[0]==="enter"&&ge[1].type==="listItemPrefix"||X===-1&&ge[0]==="exit"&&(ge[1].type==="listUnordered"||ge[1].type==="listOrdered")){if(Ze){let rt=Z;for(Fe=void 0;rt--;){const _e=$[rt];if(_e[1].type==="lineEnding"||_e[1].type==="lineEndingBlank"){if(_e[0]==="exit")continue;Fe&&($[Fe][1].type="lineEndingBlank",Pe=!0),_e[1].type="lineEnding",Fe=rt}else if(!(_e[1].type==="linePrefix"||_e[1].type==="blockQuotePrefix"||_e[1].type==="blockQuotePrefixWhitespace"||_e[1].type==="blockQuoteMarker"||_e[1].type==="listItemIndent"))break}st&&(!Fe||st<Fe)&&(Ze._spread=!0),Ze.end=Object.assign({},Fe?$[Fe][1].start:ge[1].end),$.splice(Fe||Z,0,["exit",Ze,ge[2]]),Z++,K++}if(ge[1].type==="listItemPrefix"){const rt={type:"listItem",_spread:!1,start:Object.assign({},ge[1].start),end:void 0};Ze=rt,$.splice(Z,0,["enter",rt,ge[2]]),Z++,K++,st=void 0,ht=!0}}}return $[q][1]._spread=Pe,K}function i($,q){return K;function K(Z){l.call(this,$(Z),Z),q&&q.call(this,Z)}}function a(){this.stack.push({type:"fragment",children:[]})}function l($,q,K){this.stack[this.stack.length-1].children.push($),this.stack.push($),this.tokenStack.push([q,K||void 0]),$.position={start:It(q.start),end:void 0}}function c($){return q;function q(K){$&&$.call(this,K),u.call(this,K)}}function u($,q){const K=this.stack.pop(),Z=this.tokenStack.pop();if(Z)Z[0].type!==$.type&&(q?q.call(this,$,Z[0]):(Z[1]||Da).call(this,$,Z[0]));else throw new Error("Cannot close `"+$.type+"` ("+Pn({start:$.start,end:$.end})+"): it’s not open");K.position.end=It($.end)}function d(){return cg(this.stack.pop())}function h(){this.data.expectingFirstListItemValue=!0}function m($){if(this.data.expectingFirstListItemValue){const q=this.stack[this.stack.length-2];q.start=Number.parseInt(this.sliceSerialize($),10),this.data.expectingFirstListItemValue=void 0}}function f(){const $=this.resume(),q=this.stack[this.stack.length-1];q.lang=$}function g(){const $=this.resume(),q=this.stack[this.stack.length-1];q.meta=$}function y(){this.data.flowCodeInside||(this.buffer(),this.data.flowCodeInside=!0)}function k(){const $=this.resume(),q=this.stack[this.stack.length-1];q.value=$.replace(/^(\r?\n|\r)|(\r?\n|\r)$/g,""),this.data.flowCodeInside=void 0}function S(){const $=this.resume(),q=this.stack[this.stack.length-1];q.value=$.replace(/(\r?\n|\r)$/g,"")}function I($){const q=this.resume(),K=this.stack[this.stack.length-1];K.label=q,K.identifier=an(this.sliceSerialize($)).toLowerCase()}function C(){const $=this.resume(),q=this.stack[this.stack.length-1];q.title=$}function T(){const $=this.resume(),q=this.stack[this.stack.length-1];q.url=$}function _($){const q=this.stack[this.stack.length-1];if(!q.depth){const K=this.sliceSerialize($).length;q.depth=K}}function E(){this.data.setextHeadingSlurpLineEnding=!0}function R($){const q=this.stack[this.stack.length-1];q.depth=this.sliceSerialize($).codePointAt(0)===61?1:2}function B(){this.data.setextHeadingSlurpLineEnding=void 0}function F($){const K=this.stack[this.stack.length-1].children;let Z=K[K.length-1];(!Z||Z.type!=="text")&&(Z=dt(),Z.position={start:It($.start),end:void 0},K.push(Z)),this.stack.push(Z)}function M($){const q=this.stack.pop();q.value+=this.sliceSerialize($),q.position.end=It($.end)}function v($){const q=this.stack[this.stack.length-1];if(this.data.atHardBreak){const K=q.children[q.children.length-1];K.position.end=It($.end),this.data.atHardBreak=void 0;return}!this.data.setextHeadingSlurpLineEnding&&t.canContainEols.includes(q.type)&&(F.call(this,$),M.call(this,$))}function z(){this.data.atHardBreak=!0}function L(){const $=this.resume(),q=this.stack[this.stack.length-1];q.value=$}function P(){const $=this.resume(),q=this.stack[this.stack.length-1];q.value=$}function j(){const $=this.resume(),q=this.stack[this.stack.length-1];q.value=$}function A(){const $=this.stack[this.stack.length-1];if(this.data.inReference){const q=this.data.referenceType||"shortcut";$.type+="Reference",$.referenceType=q,delete $.url,delete $.title}else delete $.identifier,delete $.label;this.data.referenceType=void 0}function U(){const $=this.stack[this.stack.length-1];if(this.data.inReference){const q=this.data.referenceType||"shortcut";$.type+="Reference",$.referenceType=q,delete $.url,delete $.title}else delete $.identifier,delete $.label;this.data.referenceType=void 0}function N($){const q=this.sliceSerialize($),K=this.stack[this.stack.length-2];K.label=ly(q),K.identifier=an(q).toLowerCase()}function O(){const $=this.stack[this.stack.length-1],q=this.resume(),K=this.stack[this.stack.length-1];if(this.data.inReference=!0,K.type==="link"){const Z=$.children;K.children=Z}else K.alt=q}function x(){const $=this.resume(),q=this.stack[this.stack.length-1];q.url=$}function oe(){const $=this.resume(),q=this.stack[this.stack.length-1];q.title=$}function pe(){this.data.inReference=void 0}function b(){this.data.referenceType="collapsed"}function J($){const q=this.resume(),K=this.stack[this.stack.length-1];K.label=q,K.identifier=an(this.sliceSerialize($)).toLowerCase(),this.data.referenceType="full"}function D($){this.data.characterReferenceType=$.type}function G($){const q=this.sliceSerialize($),K=this.data.characterReferenceType;let Z;K?(Z=pc(q,K==="characterReferenceMarkerNumeric"?10:16),this.data.characterReferenceType=void 0):Z=so(q);const X=this.stack[this.stack.length-1];X.value+=Z}function re($){const q=this.stack.pop();q.position.end=It($.end)}function se($){M.call(this,$);const q=this.stack[this.stack.length-1];q.url=this.sliceSerialize($)}function we($){M.call(this,$);const q=this.stack[this.stack.length-1];q.url="mailto:"+this.sliceSerialize($)}function me(){return{type:"blockquote",children:[]}}function le(){return{type:"code",lang:null,meta:null,value:""}}function Ve(){return{type:"inlineCode",value:""}}function St(){return{type:"definition",identifier:"",label:null,title:null,url:""}}function Ut(){return{type:"emphasis",children:[]}}function vt(){return{type:"heading",depth:0,children:[]}}function Ct(){return{type:"break"}}function Rt(){return{type:"html",value:""}}function Y(){return{type:"image",title:null,url:"",alt:null}}function te(){return{type:"link",title:null,url:"",children:[]}}function ae($){return{type:"list",ordered:$.type==="listOrdered",start:null,spread:$._spread,children:[]}}function Ne($){return{type:"listItem",spread:$._spread,checked:null,children:[]}}function Ue(){return{type:"paragraph",children:[]}}function He(){return{type:"strong",children:[]}}function dt(){return{type:"text",value:""}}function Te(){return{type:"thematicBreak"}}}function It(e){return{line:e.line,column:e.column,offset:e.offset}}function Ec(e,t){let n=-1;for(;++n<t.length;){const s=t[n];Array.isArray(s)?Ec(e,s):hy(e,s)}}function hy(e,t){let n;for(n in t)if(kc.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 Da(e,t){throw e?new Error("Cannot close `"+e.type+"` ("+Pn({start:e.start,end:e.end})+"): a different token (`"+t.type+"`, "+Pn({start:t.start,end:t.end})+") is open"):new Error("Cannot close document, a token (`"+t.type+"`, "+Pn({start:t.start,end:t.end})+") is still open")}function fy(e){const t=this;t.parser=n;function n(s){return uy(s,{...t.data("settings"),...e,extensions:t.data("micromarkExtensions")||[],mdastExtensions:t.data("fromMarkdownExtensions")||[]})}}function py(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 my(e,t){const n={type:"element",tagName:"br",properties:{},children:[]};return e.patch(t,n),[e.applyData(t,n),{type:"text",value:`
16
- `}]}function gy(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 xy(e,t){const n={type:"element",tagName:"del",properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function yy(e,t){const n={type:"element",tagName:"em",properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function by(e,t){const n=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",s=String(t.identifier).toUpperCase(),r=un(s.toLowerCase()),i=e.footnoteOrder.indexOf(s);let a,l=e.footnoteCounts.get(s);l===void 0?(l=0,e.footnoteOrder.push(s),a=e.footnoteOrder.length):a=i+1,l+=1,e.footnoteCounts.set(s,l);const c={type:"element",tagName:"a",properties:{href:"#"+n+"fn-"+r,id:n+"fnref-"+r+(l>1?"-"+l:""),dataFootnoteRef:!0,ariaDescribedBy:["footnote-label"]},children:[{type:"text",value:String(a)}]};e.patch(t,c);const u={type:"element",tagName:"sup",properties:{},children:[c]};return e.patch(t,u),e.applyData(t,u)}function wy(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 Sy(e,t){if(e.options.allowDangerousHtml){const n={type:"raw",value:t.value};return e.patch(t,n),e.applyData(t,n)}}function jc(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 a=r[r.length-1];return a&&a.type==="text"?a.value+=s:r.push({type:"text",value:s}),r}function vy(e,t){const n=String(t.identifier).toUpperCase(),s=e.definitionById.get(n);if(!s)return jc(e,t);const r={src:un(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:un(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 ky(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 Ey(e,t){const n=String(t.identifier).toUpperCase(),s=e.definitionById.get(n);if(!s)return jc(e,t);const r={href:un(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 jy(e,t){const n={href:un(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 Ny(e,t,n){const s=e.all(t),r=n?Ty(n):Nc(t),i={},a=[];if(typeof t.checked=="boolean"){const d=s[0];let h;d&&d.type==="element"&&d.tagName==="p"?h=d:(h={type:"element",tagName:"p",properties:{},children:[]},s.unshift(h)),h.children.length>0&&h.children.unshift({type:"text",value:" "}),h.children.unshift({type:"element",tagName:"input",properties:{type:"checkbox",checked:t.checked,disabled:!0},children:[]}),i.className=["task-list-item"]}let l=-1;for(;++l<s.length;){const d=s[l];(r||l!==0||d.type!=="element"||d.tagName!=="p")&&a.push({type:"text",value:`
18
- `}),d.type==="element"&&d.tagName==="p"&&!r?a.push(...d.children):a.push(d)}const c=s[s.length-1];c&&(r||c.type!=="element"||c.tagName!=="p")&&a.push({type:"text",value:`
19
- `});const u={type:"element",tagName:"li",properties:i,children:a};return e.patch(t,u),e.applyData(t,u)}function Ty(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=Nc(n[s])}return t}function Nc(e){const t=e.spread;return t??e.children.length>1}function Py(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 a=s[r];if(a.type==="element"&&a.tagName==="li"&&a.properties&&Array.isArray(a.properties.className)&&a.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 Iy(e,t){const n={type:"element",tagName:"p",properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function Ay(e,t){const n={type:"root",children:e.wrap(e.all(t))};return e.patch(t,n),e.applyData(t,n)}function zy(e,t){const n={type:"element",tagName:"strong",properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function _y(e,t){const n=e.all(t),s=n.shift(),r=[];if(s){const a={type:"element",tagName:"thead",properties:{},children:e.wrap([s],!0)};e.patch(t.children[0],a),r.push(a)}if(n.length>0){const a={type:"element",tagName:"tbody",properties:{},children:e.wrap(n,!0)},l=Xi(t.children[1]),c=ac(t.children[t.children.length-1]);l&&c&&(a.position={start:l,end:c}),r.push(a)}const i={type:"element",tagName:"table",properties:{},children:e.wrap(r,!0)};return e.patch(t,i),e.applyData(t,i)}function Ly(e,t,n){const s=n?n.children:void 0,i=(s?s.indexOf(t):1)===0?"th":"td",a=n&&n.type==="table"?n.align:void 0,l=a?a.length:t.children.length;let c=-1;const u=[];for(;++c<l;){const h=t.children[c],m={},f=a?a[c]:void 0;f&&(m.align=f);let g={type:"element",tagName:i,properties:m,children:[]};h&&(g.children=e.all(h),e.patch(h,g),g=e.applyData(h,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 Ry(e,t){const n={type:"element",tagName:"td",properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}const Fa=9,$a=32;function My(e){const t=String(e),n=/\r?\n|\r/g;let s=n.exec(t),r=0;const i=[];for(;s;)i.push(Ba(t.slice(r,s.index),r>0,!0),s[0]),r=s.index+s[0].length,s=n.exec(t);return i.push(Ba(t.slice(r),r>0,!1)),i.join("")}function Ba(e,t,n){let s=0,r=e.length;if(t){let i=e.codePointAt(s);for(;i===Fa||i===$a;)s++,i=e.codePointAt(s)}if(n){let i=e.codePointAt(r-1);for(;i===Fa||i===$a;)r--,i=e.codePointAt(r-1)}return r>s?e.slice(s,r):""}function Oy(e,t){const n={type:"text",value:My(String(t.value))};return e.patch(t,n),e.applyData(t,n)}function Dy(e,t){const n={type:"element",tagName:"hr",properties:{},children:[]};return e.patch(t,n),e.applyData(t,n)}const Fy={blockquote:py,break:my,code:gy,delete:xy,emphasis:yy,footnoteReference:by,heading:wy,html:Sy,imageReference:vy,image:Cy,inlineCode:ky,linkReference:Ey,link:jy,listItem:Ny,list:Py,paragraph:Iy,root:Ay,strong:zy,table:_y,tableCell:Ry,tableRow:Ly,text:Oy,thematicBreak:Dy,toml:es,yaml:es,definition:es,footnoteDefinition:es};function es(){}const Tc=-1,$s=0,An=1,As=2,oo=3,ao=4,lo=5,co=6,Pc=7,Ic=8,$y=typeof self=="object"?self:globalThis,Va=(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 $y[e](t)},By=(e,t)=>{const n=(r,i)=>(e.set(i,r),r),s=r=>{if(e.has(r))return e.get(r);const[i,a]=t[r];switch(i){case $s:case Tc:return n(a,r);case An:{const l=n([],r);for(const c of a)l.push(s(c));return l}case As:{const l=n({},r);for(const[c,u]of a)l[s(c)]=s(u);return l}case oo:return n(new Date(a),r);case ao:{const{source:l,flags:c}=a;return n(new RegExp(l,c),r)}case lo:{const l=n(new Map,r);for(const[c,u]of a)l.set(s(c),s(u));return l}case co:{const l=n(new Set,r);for(const c of a)l.add(s(c));return l}case Pc:{const{name:l,message:c}=a;return n(Va(l,c),r)}case Ic:return n(BigInt(a),r);case"BigInt":return n(Object(BigInt(a)),r);case"ArrayBuffer":return n(new Uint8Array(a).buffer,a);case"DataView":{const{buffer:l}=new Uint8Array(a);return n(new DataView(l),a)}}return n(Va(i,a),r)};return s},Ua=e=>By(new Map,e)(0),Xt="",{toString:Vy}={},{keys:Uy}=Object,En=e=>{const t=typeof e;if(t!=="object"||!e)return[$s,t];const n=Vy.call(e).slice(8,-1);switch(n){case"Array":return[An,Xt];case"Object":return[As,Xt];case"Date":return[oo,Xt];case"RegExp":return[ao,Xt];case"Map":return[lo,Xt];case"Set":return[co,Xt];case"DataView":return[An,n]}return n.includes("Array")?[An,n]:n.includes("Error")?[Pc,n]:[As,n]},ts=([e,t])=>e===$s&&(t==="function"||t==="symbol"),Hy=(e,t,n,s)=>{const r=(a,l)=>{const c=s.push(a)-1;return n.set(l,c),c},i=a=>{if(n.has(a))return n.get(a);let[l,c]=En(a);switch(l){case $s:{let d=a;switch(c){case"bigint":l=Ic,d=a.toString();break;case"function":case"symbol":if(e)throw new TypeError("unable to serialize "+c);d=null;break;case"undefined":return r([Tc],a)}return r([l,d],a)}case An:{if(c){let m=a;return c==="DataView"?m=new Uint8Array(a.buffer):c==="ArrayBuffer"&&(m=new Uint8Array(a)),r([c,[...m]],a)}const d=[],h=r([l,d],a);for(const m of a)d.push(i(m));return h}case As:{if(c)switch(c){case"BigInt":return r([c,a.toString()],a);case"Boolean":case"Number":case"String":return r([c,a.valueOf()],a)}if(t&&"toJSON"in a)return i(a.toJSON());const d=[],h=r([l,d],a);for(const m of Uy(a))(e||!ts(En(a[m])))&&d.push([i(m),i(a[m])]);return h}case oo:return r([l,a.toISOString()],a);case ao:{const{source:d,flags:h}=a;return r([l,{source:d,flags:h}],a)}case lo:{const d=[],h=r([l,d],a);for(const[m,f]of a)(e||!(ts(En(m))||ts(En(f))))&&d.push([i(m),i(f)]);return h}case co:{const d=[],h=r([l,d],a);for(const m of a)(e||!ts(En(m)))&&d.push(i(m));return h}}const{message:u}=a;return r([l,{name:c,message:u}],a)};return i},Ha=(e,{json:t,lossy:n}={})=>{const s=[];return Hy(!(t||n),!!t,new Map,s)(e),s},zs=typeof structuredClone=="function"?(e,t)=>t&&("json"in t||"lossy"in t)?Ua(Ha(e,t)):structuredClone(e):(e,t)=>Ua(Ha(e,t));function qy(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 Wy(e,t){return"Back to reference "+(e+1)+(t>1?"-"+t:"")}function Gy(e){const t=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",n=e.options.footnoteBackContent||qy,s=e.options.footnoteBackLabel||Wy,r=e.options.footnoteLabel||"Footnotes",i=e.options.footnoteLabelTagName||"h2",a=e.options.footnoteLabelProperties||{className:["sr-only"]},l=[];let c=-1;for(;++c<e.footnoteOrder.length;){const u=e.footnoteById.get(e.footnoteOrder[c]);if(!u)continue;const d=e.all(u),h=String(u.identifier).toUpperCase(),m=un(h.toLowerCase());let f=0;const g=[],y=e.footnoteCounts.get(h);for(;y!==void 0&&++f<=y;){g.length>0&&g.push({type:"text",value:" "});let I=typeof n=="string"?n:n(c,f);typeof I=="string"&&(I={type:"text",value:I}),g.push({type:"element",tagName:"a",properties:{href:"#"+t+"fnref-"+m+(f>1?"-"+f:""),dataFootnoteBackref:"",ariaLabel:typeof s=="string"?s:s(c,f),className:["data-footnote-backref"]},children:Array.isArray(I)?I:[I]})}const k=d[d.length-1];if(k&&k.type==="element"&&k.tagName==="p"){const I=k.children[k.children.length-1];I&&I.type==="text"?I.value+=" ":k.children.push({type:"text",value:" "}),k.children.push(...g)}else d.push(...g);const S={type:"element",tagName:"li",properties:{id:t+"fn-"+m},children:e.wrap(d,!0)};e.patch(u,S),l.push(S)}if(l.length!==0)return{type:"element",tagName:"section",properties:{dataFootnotes:!0,className:["footnotes"]},children:[{type:"element",tagName:i,properties:{...zs(a),id:"footnote-label"},children:[{type:"text",value:r}]},{type:"text",value:`
20
- `},{type:"element",tagName:"ol",properties:{},children:e.wrap(l,!0)},{type:"text",value:`
21
- `}]}}const Ac=(function(e){if(e==null)return Yy;if(typeof e=="function")return Bs(e);if(typeof e=="object")return Array.isArray(e)?Qy(e):Jy(e);if(typeof e=="string")return Zy(e);throw new Error("Expected function, string, or object as test")});function Qy(e){const t=[];let n=-1;for(;++n<e.length;)t[n]=Ac(e[n]);return Bs(s);function s(...r){let i=-1;for(;++i<t.length;)if(t[i].apply(this,r))return!0;return!1}}function Jy(e){const t=e;return Bs(n);function n(s){const r=s;let i;for(i in e)if(r[i]!==t[i])return!1;return!0}}function Zy(e){return Bs(t);function t(n){return n&&n.type===e}}function Bs(e){return t;function t(n,s,r){return!!(Ky(n)&&e.call(this,n,typeof s=="number"?s:void 0,r||void 0))}}function Yy(){return!0}function Ky(e){return e!==null&&typeof e=="object"&&"type"in e}const zc=[],Xy=!0,qa=!1,eb="skip";function tb(e,t,n,s){let r;typeof t=="function"&&typeof n!="function"?(s=n,n=t):r=t;const i=Ac(r),a=s?-1:1;l(e,void 0,[])();function l(c,u,d){const h=c&&typeof c=="object"?c:{};if(typeof h.type=="string"){const f=typeof h.tagName=="string"?h.tagName:typeof h.name=="string"?h.name:void 0;Object.defineProperty(m,"name",{value:"node ("+(c.type+(f?"<"+f+">":""))+")"})}return m;function m(){let f=zc,g,y,k;if((!t||i(c,u,d[d.length-1]||void 0))&&(f=nb(n(c,d)),f[0]===qa))return f;if("children"in c&&c.children){const S=c;if(S.children&&f[0]!==eb)for(y=(s?S.children.length:-1)+a,k=d.concat(S);y>-1&&y<S.children.length;){const I=S.children[y];if(g=l(I,y,k)(),g[0]===qa)return g;y=typeof g[1]=="number"?g[1]:y+a}}return f}}}function nb(e){return Array.isArray(e)?e:typeof e=="number"?[Xy,e]:e==null?zc:[e]}function _c(e,t,n,s){let r,i,a;typeof t=="function"&&typeof n!="function"?(i=void 0,a=t,r=n):(i=t,a=n,r=s),tb(e,i,l,r);function l(c,u){const d=u[u.length-1],h=d?d.children.indexOf(c):void 0;return a(c,h,d)}}const zi={}.hasOwnProperty,sb={};function rb(e,t){const n=t||sb,s=new Map,r=new Map,i=new Map,a={...Fy,...n.handlers},l={all:u,applyData:ob,definitionById:s,footnoteById:r,footnoteCounts:i,footnoteOrder:[],handlers:a,one:c,options:n,patch:ib,wrap:lb};return _c(e,function(d){if(d.type==="definition"||d.type==="footnoteDefinition"){const h=d.type==="definition"?s:r,m=String(d.identifier).toUpperCase();h.has(m)||h.set(m,d)}}),l;function c(d,h){const m=d.type,f=l.handlers[m];if(zi.call(l.handlers,m)&&f)return f(l,d,h);if(l.options.passThrough&&l.options.passThrough.includes(m)){if("children"in d){const{children:y,...k}=d,S=zs(k);return S.children=l.all(d),S}return zs(d)}return(l.options.unknownHandler||ab)(l,d,h)}function u(d){const h=[];if("children"in d){const m=d.children;let f=-1;for(;++f<m.length;){const g=l.one(m[f],d);if(g){if(f&&m[f-1].type==="break"&&(!Array.isArray(g)&&g.type==="text"&&(g.value=Wa(g.value)),!Array.isArray(g)&&g.type==="element")){const y=g.children[0];y&&y.type==="text"&&(y.value=Wa(y.value))}Array.isArray(g)?h.push(...g):h.push(g)}}}return h}}function ib(e,t){e.position&&(t.position=Bm(e))}function ob(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 a="children"in n?n.children:[n];n={type:"element",tagName:s,properties:{},children:a}}n.type==="element"&&i&&Object.assign(n.properties,zs(i)),"children"in n&&n.children&&r!==null&&r!==void 0&&(n.children=r)}return n}function ab(e,t){const n=t.data||{},s="value"in t&&!(zi.call(n,"hProperties")||zi.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 lb(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 Wa(e){let t=0,n=e.charCodeAt(t);for(;n===9||n===32;)t++,n=e.charCodeAt(t);return e.slice(t)}function Ga(e,t){const n=rb(e,t),s=n.one(e,void 0),r=Gy(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 cb(e,t){return e&&"run"in e?async function(n,s){const r=Ga(n,{file:s,...t});await e.run(r,s)}:function(n,s){return Ga(n,{file:s,...e||t})}}function Qa(e){if(e)throw e}var Xr,Ja;function ub(){if(Ja)return Xr;Ja=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"),h=u.constructor&&u.constructor.prototype&&e.call(u.constructor.prototype,"isPrototypeOf");if(u.constructor&&!d&&!h)return!1;var m;for(m in u);return typeof m>"u"||e.call(u,m)},a=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},l=function(u,d){if(d==="__proto__")if(e.call(u,d)){if(s)return s(u,d).value}else return;return u[d]};return Xr=function c(){var u,d,h,m,f,g,y=arguments[0],k=1,S=arguments.length,I=!1;for(typeof y=="boolean"&&(I=y,y=arguments[1]||{},k=2),(y==null||typeof y!="object"&&typeof y!="function")&&(y={});k<S;++k)if(u=arguments[k],u!=null)for(d in u)h=l(y,d),m=l(u,d),y!==m&&(I&&m&&(i(m)||(f=r(m)))?(f?(f=!1,g=h&&r(h)?h:[]):g=h&&i(h)?h:{},a(y,{name:d,newValue:c(I,g,m)})):typeof m<"u"&&a(y,{name:d,newValue:m}));return y},Xr}var db=ub();const ei=Dl(db);function _i(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 hb(){const e=[],t={run:n,use:s};return t;function n(...r){let i=-1;const a=r.pop();if(typeof a!="function")throw new TypeError("Expected function as last argument, not "+a);l(null,...r);function l(c,...u){const d=e[++i];let h=-1;if(c){a(c);return}for(;++h<r.length;)(u[h]===null||u[h]===void 0)&&(u[h]=r[h]);r=u,d?fb(d,l)(...u):a(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 fb(e,t){let n;return s;function s(...a){const l=e.length>a.length;let c;l&&a.push(r);try{c=e.apply(this,a)}catch(u){const d=u;if(l&&n)throw d;return r(d)}l||(c&&c.then&&typeof c.then=="function"?c.then(i,r):c instanceof Error?r(c):i(c))}function r(a,...l){n||(n=!0,t(a,...l))}function i(a){r(null,a)}}const at={basename:pb,dirname:mb,extname:gb,join:xb,sep:"/"};function pb(e,t){if(t!==void 0&&typeof t!="string")throw new TypeError('"ext" argument must be a string');Fn(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 a=-1,l=t.length-1;for(;r--;)if(e.codePointAt(r)===47){if(i){n=r+1;break}}else a<0&&(i=!0,a=r+1),l>-1&&(e.codePointAt(r)===t.codePointAt(l--)?l<0&&(s=r):(l=-1,s=a));return n===s?s=a:s<0&&(s=e.length),e.slice(n,s)}function mb(e){if(Fn(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 gb(e){Fn(e);let t=e.length,n=-1,s=0,r=-1,i=0,a;for(;t--;){const l=e.codePointAt(t);if(l===47){if(a){s=t+1;break}continue}n<0&&(a=!0,n=t+1),l===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 xb(...e){let t=-1,n;for(;++t<e.length;)Fn(e[t]),e[t]&&(n=n===void 0?e[t]:n+"/"+e[t]);return n===void 0?".":yb(n)}function yb(e){Fn(e);const t=e.codePointAt(0)===47;let n=bb(e,!t);return n.length===0&&!t&&(n="."),n.length>0&&e.codePointAt(e.length-1)===47&&(n+="/"),t?"/"+n:n}function bb(e,t){let n="",s=0,r=-1,i=0,a=-1,l,c;for(;++a<=e.length;){if(a<e.length)l=e.codePointAt(a);else{if(l===47)break;l=47}if(l===47){if(!(r===a-1||i===1))if(r!==a-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=a,i=0;continue}}else if(n.length>0){n="",s=0,r=a,i=0;continue}}t&&(n=n.length>0?n+"/..":"..",s=2)}else n.length>0?n+="/"+e.slice(r+1,a):n=e.slice(r+1,a),s=a-r-1;r=a,i=0}else l===46&&i>-1?i++:i=-1}return n}function Fn(e){if(typeof e!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(e))}const wb={cwd:Sb};function Sb(){return"/"}function Li(e){return!!(e!==null&&typeof e=="object"&&"href"in e&&e.href&&"protocol"in e&&e.protocol&&e.auth===void 0)}function vb(e){if(typeof e=="string")e=new URL(e);else if(!Li(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 Cb(e)}function Cb(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 ti=["history","path","basename","stem","extname","dirname"];class Lc{constructor(t){let n;t?Li(t)?n={path:t}:typeof t=="string"||kb(t)?n={value:t}:n=t:n={},this.cwd="cwd"in n?"":wb.cwd(),this.data={},this.history=[],this.messages=[],this.value,this.map,this.result,this.stored;let s=-1;for(;++s<ti.length;){const i=ti[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)ti.includes(r)||(this[r]=n[r])}get basename(){return typeof this.path=="string"?at.basename(this.path):void 0}set basename(t){si(t,"basename"),ni(t,"basename"),this.path=at.join(this.dirname||"",t)}get dirname(){return typeof this.path=="string"?at.dirname(this.path):void 0}set dirname(t){Za(this.basename,"dirname"),this.path=at.join(t||"",this.basename)}get extname(){return typeof this.path=="string"?at.extname(this.path):void 0}set extname(t){if(ni(t,"extname"),Za(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=at.join(this.dirname,this.stem+(t||""))}get path(){return this.history[this.history.length-1]}set path(t){Li(t)&&(t=vb(t)),si(t,"path"),this.path!==t&&this.history.push(t)}get stem(){return typeof this.path=="string"?at.basename(this.path,this.extname):void 0}set stem(t){si(t,"stem"),ni(t,"stem"),this.path=at.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 ze(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 ni(e,t){if(e&&e.includes(at.sep))throw new Error("`"+t+"` cannot be a path: did not expect `"+at.sep+"`")}function si(e,t){if(!e)throw new Error("`"+t+"` cannot be empty")}function Za(e,t){if(!e)throw new Error("Setting `"+t+"` requires `path` to be set too")}function kb(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const Eb=(function(e){const s=this.constructor.prototype,r=s[e],i=function(){return r.apply(i,arguments)};return Object.setPrototypeOf(i,s),i}),jb={}.hasOwnProperty;class uo extends Eb{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=hb()}copy(){const t=new uo;let n=-1;for(;++n<this.attachers.length;){const s=this.attachers[n];t.use(...s)}return t.data(ei(!0,{},this.namespace)),t}data(t,n){return typeof t=="string"?arguments.length===2?(oi("data",this.frozen),this.namespace[t]=n,this):jb.call(this.namespace,t)&&this.namespace[t]||void 0:t?(oi("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=ns(t),s=this.parser||this.Parser;return ri("parse",s),s(String(n),n)}process(t,n){const s=this;return this.freeze(),ri("process",this.parser||this.Parser),ii("process",this.compiler||this.Compiler),n?r(void 0,n):new Promise(r);function r(i,a){const l=ns(t),c=s.parse(l);s.run(c,l,function(d,h,m){if(d||!h||!m)return u(d);const f=h,g=s.stringify(f,m);Pb(g)?m.value=g:m.result=g,u(d,m)});function u(d,h){d||!h?a(d):i?i(h):n(void 0,h)}}}processSync(t){let n=!1,s;return this.freeze(),ri("processSync",this.parser||this.Parser),ii("processSync",this.compiler||this.Compiler),this.process(t,r),Ka("processSync","process",n),s;function r(i,a){n=!0,Qa(i),s=a}}run(t,n,s){Ya(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(a,l){const c=ns(n);r.run(t,c,u);function u(d,h,m){const f=h||t;d?l(d):a?a(f):s(void 0,f,m)}}}runSync(t,n){let s=!1,r;return this.run(t,n,i),Ka("runSync","run",s),r;function i(a,l){Qa(a),r=l,s=!0}}stringify(t,n){this.freeze();const s=ns(n),r=this.compiler||this.Compiler;return ii("stringify",r),Ya(t),r(t,s)}use(t,...n){const s=this.attachers,r=this.namespace;if(oi("use",this.frozen),t!=null)if(typeof t=="function")c(t,n);else if(typeof t=="object")Array.isArray(t)?l(t):a(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,...h]=u;c(d,h)}else a(u);else throw new TypeError("Expected usable value, not `"+u+"`")}function a(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");l(u.plugins),u.settings&&(r.settings=ei(!0,r.settings,u.settings))}function l(u){let d=-1;if(u!=null)if(Array.isArray(u))for(;++d<u.length;){const h=u[d];i(h)}else throw new TypeError("Expected a list of plugins, not `"+u+"`")}function c(u,d){let h=-1,m=-1;for(;++h<s.length;)if(s[h][0]===u){m=h;break}if(m===-1)s.push([u,...d]);else if(d.length>0){let[f,...g]=d;const y=s[m][1];_i(y)&&_i(f)&&(f=ei(!0,y,f)),s[m]=[u,f,...g]}}}}const Nb=new uo().freeze();function ri(e,t){if(typeof t!="function")throw new TypeError("Cannot `"+e+"` without `parser`")}function ii(e,t){if(typeof t!="function")throw new TypeError("Cannot `"+e+"` without `compiler`")}function oi(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 Ya(e){if(!_i(e)||typeof e.type!="string")throw new TypeError("Expected node, got `"+e+"`")}function Ka(e,t,n){if(!n)throw new Error("`"+e+"` finished async. Use `"+t+"` instead")}function ns(e){return Tb(e)?e:new Lc(e)}function Tb(e){return!!(e&&typeof e=="object"&&"message"in e&&"messages"in e)}function Pb(e){return typeof e=="string"||Ib(e)}function Ib(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const Ab="https://github.com/remarkjs/react-markdown/blob/main/changelog.md",Xa=[],el={allowDangerousHtml:!0},zb=/^(https?|ircs?|mailto|xmpp)$/i,_b=[{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 Lb(e){const t=Rb(e),n=Mb(e);return Ob(t.runSync(t.parse(n),n),e)}function Rb(e){const t=e.rehypePlugins||Xa,n=e.remarkPlugins||Xa,s=e.remarkRehypeOptions?{...e.remarkRehypeOptions,...el}:el;return Nb().use(fy).use(n).use(cb,s).use(t)}function Mb(e){const t=e.children||"",n=new Lc;return typeof t=="string"&&(n.value=t),n}function Ob(e,t){const n=t.allowedElements,s=t.allowElement,r=t.components,i=t.disallowedElements,a=t.skipHtml,l=t.unwrapDisallowed,c=t.urlTransform||Db;for(const d of _b)Object.hasOwn(t,d.from)&&(""+d.from+(d.to?"use `"+d.to+"` instead":"remove it")+Ab+d.id,void 0);return _c(e,u),Wm(e,{Fragment:o.Fragment,components:r,ignoreInvalidStyle:!0,jsx:o.jsx,jsxs:o.jsxs,passKeys:!0,passNode:!0});function u(d,h,m){if(d.type==="raw"&&m&&typeof h=="number")return a?m.children.splice(h,1):m.children[h]={type:"text",value:d.value},h;if(d.type==="element"){let f;for(f in Zr)if(Object.hasOwn(Zr,f)&&Object.hasOwn(d.properties,f)){const g=d.properties[f],y=Zr[f];(y===null||y.includes(d.tagName))&&(d.properties[f]=c(String(g||""),f,d))}}if(d.type==="element"){let f=n?!n.includes(d.tagName):i?i.includes(d.tagName):!1;if(!f&&s&&typeof h=="number"&&(f=!s(d,h,m)),f&&m&&typeof h=="number")return l&&d.children?m.children.splice(h,1,...d.children):m.children.splice(h,1),h}}}function Db(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||zb.test(e.slice(0,t))?e:""}const Rc=p.createContext(null);function Fb({children:e,host:t}){return o.jsx(Rc.Provider,{value:t,children:e})}function Mc(){const e=p.useContext(Rc);if(!e)throw new Error("usePluginHost must be used within PluginHostProvider");return e}const Oc="openlearn:dashboardVisibility";function $b(){try{const e=localStorage.getItem(Oc);if(e)return new Map(JSON.parse(e))}catch{}return new Map}function tl(e){try{localStorage.setItem(Oc,JSON.stringify([...e.entries()]))}catch{}}const Ee=Qi()((e,t)=>({activePlugins:[],extensionPoints:new Map,services:null,dashboardVisibility:$b(),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 l=new Map(r.extensionPoints);return l.set(n,[...i,s]),{extensionPoints:l}}),unregisterExtensionPoint:(n,s)=>e(r=>{const i=r.extensionPoints.get(n);if(!i)return r;const a=i.filter(c=>c.id!==s),l=new Map(r.extensionPoints);return a.length===0?l.delete(n):l.set(n,a),{extensionPoints:l}}),unregisterPluginExtensionPoints:n=>e(s=>{const r=new Map(s.extensionPoints);for(const[i,a]of r){const l=a.filter(c=>c.pluginId!==n);l.length===0?r.delete(i):r.set(i,l)}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),tl(i),{dashboardVisibility:i}}),setDashboardVisibilityBatch:n=>e(s=>{const r=new Map(s.dashboardVisibility);for(const[i,a]of n)r.set(i,a);return tl(r),{dashboardVisibility:r}})}));function Bb(){return o.jsx("div",{className:"w-full h-32 bg-gray-100 rounded-xl animate-pulse flex items-center justify-center",children:o.jsxs("div",{className:"flex flex-col items-center gap-2",children:[o.jsx(Gi,{size:24,className:"text-gray-400 animate-spin"}),o.jsx("span",{className:"text-xs text-gray-400",children:"Loading..."})]})})}class Vb extends Je.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 Ub({ext:e,route:t,slotProps:n,slot:s}){const r=Je.useRef(null),i=JSON.stringify(n||{});Je.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 l=s==="teacher.dashboard.widget"?"h-auto":"h-full min-h-0";return o.jsx("div",{ref:r,className:`w-full ${l}`})}const ai=new WeakMap;function Hb(e){const t=e.component,n=ai.get(t);if(n)return n;if(t.__isLazyFactory===!0){const s=Je.lazy(t);return ai.set(t,s),s}return ai.set(t,t),t}function FC({slot:e,fallback:t,lang:n,route:s,slotProps:r,placement:i}){let l=Mc().getExtensions(e);const c=Ee(h=>h.dashboardVisibility),u=de(h=>h.selectedLesson),d=de(h=>h.liveClassSelectedClassId);return i&&(l=l.filter(h=>(h.placement??"after")===i)),l.length===0?null:e==="teacher.tab"&&r?.renderType==="button"?o.jsx(o.Fragment,{children:l.map(h=>{const m=`${h.pluginId}/${h.id}`,f=r?.teacherTab===m,g=h.title||h.label||h.id;return o.jsxs("button",{onClick:()=>r?.setTeacherTab?.(m),className:`flex items-center gap-3 p-3 transition-colors text-sm font-medium rounded-xl ${f?"bg-indigo-50 text-indigo-700 font-bold":"text-gray-600 hover:bg-gray-50"} ${r?.mainNavCollapsed?"justify-center px-2":""}`,title:g,children:[o.jsx(Wi,{size:20,className:"shrink-0"}),o.jsx("span",{className:r?.mainNavCollapsed?"hidden":"hidden md:block",children:g})]},`${h.pluginId}/${h.id}`)})}):o.jsx(o.Fragment,{children:l.map(h=>{const m=typeof h.component=="function",f=typeof h.render=="function";return e==="teacher.dashboard.widget"&&c.get(h.pluginId)===!1||!m&&!f?null:o.jsx(Vb,{fallback:o.jsx("div",{className:"bg-red-50 border border-red-200 rounded-lg p-4 text-sm text-red-700",children:o.jsx("p",{children:n==="zh"?"扩展组件加载失败":"Extension failed to load"})}),children:o.jsx(p.Suspense,{fallback:t??o.jsx(Bb,{}),children:m?Je.createElement(Hb(h),{route:h.route||s,lessonId:u,classId:d,...h.slotProps,...r}):o.jsx(Ub,{ext:h,route:h.route||s,slotProps:{lessonId:u,classId:d,...h.slotProps,...r},slot:e})})},`${h.pluginId}/${h.id}`)})})}const qb=(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 Wb(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 nl(){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 Gb(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 Qb(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 Jb(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 Zb(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 ss={padding:"12px",color:"#e2e8f0",fontSize:"13px"},Yb={HelpCircle:hp,Vote:dp,BarChart3:up,MessagesSquare:cp,Users:Fl,FileText:Hl,Trophy:lp,CheckCircle2:On,BookOpen:qi};function Kb({name:e,className:t}){const n=e&&Yb[e]||Wi;return o.jsx(n,{size:18,className:t})}function Xb(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 Dc=({role:e,actorId:t,lang:n="en",classroomId:s,mode:r="launcher"})=>{const[i,a]=p.useState([]),[l,c]=p.useState(!0),[u,d]=p.useState(null),[h,m]=p.useState({}),[f,g]=p.useState([]),[y,k]=p.useState(!0),[S,I]=p.useState(null),[C,T]=p.useState(null),[_,E]=p.useState(!1),[R,B]=p.useState(null),F=de(N=>N.setTeacherTab),M=p.useMemo(()=>{const N=new Map;for(const O of i){const x=O.category;N.has(x)||N.set(x,[]),N.get(x).push(O)}return Array.from(N.entries())},[i]);p.useEffect(()=>{if(r!=="launcher")return;let N=!1;return c(!0),Wb(e).then(O=>{N||a(O)}).catch(O=>{N||d(O instanceof Error?O.message:String(O))}).finally(()=>{N||c(!1)}),()=>{N=!0}},[e,r]),p.useEffect(()=>{if(r!=="status")return;let N=!1;const O=async()=>{try{const oe=await nl();N||g(oe)}catch(oe){N||I(oe instanceof Error?oe.message:String(oe))}finally{N||k(!1)}};O();const x=setInterval(O,5e3);return()=>{N=!0,clearInterval(x)}},[r]);const v=async N=>{if(C){E(!0),B(null);try{await N(C),g(await nl())}catch(O){B(O instanceof Error?O.message:String(O))}finally{E(!1)}}},z=()=>v(Gb),L=()=>v(Qb),P=()=>v(Jb),j=()=>{T(null),F("live_class")};if(r==="status"){if(y)return o.jsx("div",{className:"bg-white border border-slate-200/80 rounded-2xl p-5 shadow-sm h-24 animate-pulse"});if(S||f.length===0)return null;const N=f.find(O=>O.id===C)||null;return o.jsxs("div",{className:"bg-white border border-slate-200/80 rounded-2xl p-5 shadow-sm",children:[o.jsxs("div",{className:"flex items-center justify-between mb-3",children:[o.jsxs("div",{className:"flex items-center gap-2 text-slate-800 font-extrabold",children:[o.jsx("span",{children:"🧩"}),o.jsx("span",{children:n==="zh"?"进行中的活动":"Activities in Progress"})]}),o.jsx("span",{className:"text-xs font-bold bg-indigo-50 text-indigo-700 px-2 py-0.5 rounded-full",children:f.length})]}),o.jsx("div",{className:"flex flex-col gap-2",children:f.map(O=>{const x=O.state==="running";return o.jsxs("button",{onClick:()=>T(O.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:[o.jsx(Kb,{name:O.icon,className:"text-indigo-600 shrink-0"}),o.jsxs("div",{className:"min-w-0 flex-1",children:[o.jsx("div",{className:"font-bold text-slate-800 truncate",children:O.name}),O.category&&o.jsx("div",{className:"text-xs text-slate-500 truncate",children:O.category})]}),o.jsxs("div",{className:"flex flex-col items-end gap-1 shrink-0",children:[o.jsx("span",{className:`text-xs font-bold px-2 py-0.5 rounded-full ${x?"bg-emerald-100 text-emerald-700":"bg-amber-100 text-amber-700"}`,children:x?n==="zh"?"进行中":"Running":n==="zh"?"已暂停":"Paused"}),o.jsxs("span",{className:"text-xs text-slate-400 flex items-center gap-1",children:[o.jsx(ip,{size:10})," ",Xb(O.startedAt,n)]})]})]},O.id)})}),N&&o.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/30 p-4",onClick:()=>T(null),children:o.jsxs("div",{className:"bg-white rounded-2xl shadow-xl w-full max-w-sm p-5",onClick:O=>O.stopPropagation(),children:[o.jsxs("div",{className:"flex items-center justify-between mb-3",children:[o.jsx("h3",{className:"font-bold text-slate-800",children:N.name}),o.jsx("button",{onClick:()=>T(null),className:"text-slate-400 hover:text-slate-600","aria-label":"close",children:o.jsx(tt,{size:18})})]}),o.jsxs("div",{className:"text-sm text-slate-500 mb-1",children:[n==="zh"?"状态":"Status",":"," ",N.state==="running"?n==="zh"?"进行中":"Running":n==="zh"?"已暂停":"Paused"]}),o.jsxs("div",{className:"text-sm text-slate-500 mb-4",children:[n==="zh"?"开始时间":"Started",":"," ",N.startedAt?new Date(N.startedAt).toLocaleString():"-"]}),R&&o.jsx("div",{className:"text-xs text-rose-600 mb-2",children:R}),o.jsxs("div",{className:"flex gap-2",children:[N.state==="running"?o.jsxs("button",{disabled:_,onClick:L,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:[o.jsx(op,{size:14})," ",n==="zh"?"暂停":"Pause"]}):o.jsxs("button",{disabled:_,onClick:P,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:[o.jsx(ap,{size:14})," ",n==="zh"?"恢复":"Resume"]}),o.jsx("button",{disabled:_,onClick:z,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:_?n==="zh"?"处理中…":"Working…":n==="zh"?"结束":"End"})]}),o.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 A=async N=>{m(O=>({...O,[N.id]:n==="zh"?"启动中…":"Starting…"}));try{const O=await Zb(N.id,{classroomId:s,role:e},t);m(x=>({...x,[N.id]:O.dispatched?n==="zh"?"已启动 ✓":"Started ✓":n==="zh"?"已通知 ✓":"Notified ✓"}))}catch(O){m(x=>({...x,[N.id]:O instanceof Error?O.message:String(O)}))}};if(l)return o.jsx("div",{style:ss,children:n==="zh"?"加载活动中…":"Loading activities…"});if(u)return o.jsxs("div",{style:ss,children:[o.jsxs("div",{style:{fontWeight:600,marginBottom:6},children:["🧩 ",n==="zh"?"活动中心":"Activity Center"]}),o.jsx("div",{style:{opacity:.7},children:u})]});const U=e==="teacher"?n==="zh"?"活动中心(教师)":"Activity Center":n==="zh"?"活动(学生)":"Activities";return i.length===0?o.jsxs("div",{style:ss,children:[o.jsxs("div",{style:{fontWeight:600,marginBottom:6},children:["🧩 ",U]}),o.jsx("div",{style:{opacity:.7},children:n==="zh"?"暂无可用活动。":"No activities available."})]}):o.jsxs("div",{style:ss,children:[o.jsxs("div",{style:{fontWeight:600,marginBottom:8},children:["🧩 ",U]}),M.map(([N,O])=>o.jsxs("div",{style:{marginBottom:10},children:[o.jsx("div",{style:{opacity:.6,fontSize:12,textTransform:"uppercase",marginBottom:4},children:N}),o.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:8},children:O.map(x=>o.jsxs("div",{style:{border:"1px solid #334155",borderRadius:8,padding:"8px 10px",minWidth:150,background:"#0f172a"},children:[o.jsxs("div",{style:{fontWeight:600},children:[x.icon?`${x.icon} `:"▫️ ",x.name]}),x.description&&o.jsx("div",{style:{opacity:.7,fontSize:12,margin:"2px 0 6px"},children:x.description}),o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[o.jsx("button",{onClick:()=>A(x),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"}),h[x.id]&&o.jsx("span",{style:{fontSize:12,opacity:.85},children:h[x.id]})]}),o.jsx("div",{style:{opacity:.5,fontSize:12,marginTop:4},children:x.provider==="official"?"official":x.provider})]},x.id))})]},N))]})},e0=Object.freeze(Object.defineProperty({__proto__:null,ActivityWorkspaceWidget:Dc},Symbol.toStringTag,{value:"Module"}));let sl=!1;function t0(){if(sl)return;sl=!0;const e=()=>je(()=>Promise.resolve().then(()=>e0),void 0).then(t=>({default:()=>o.jsx(Dc,{role:"teacher",mode:"status"})}));e.__isLazyFactory=!0,Ee.getState().registerExtensionPoint("teacher.dashboard.widget",{id:"official_activity_center",label:"Activity Center",icon:"Puzzle",pluginId:"openlearn-official",component:e})}const rl="@openlearn/frontend:IFrontendAPI",il="@openlearn/frontend:ISocketService",ol="@openlearn/frontend:IUIService",al="@openlearn/frontend:IStorageService",n0="@openlearn/frontend:ISemesterGradeService";var be=(e=>(e.INSTALLED="installed",e.ACTIVATING="activating",e.ACTIVE="active",e.DEACTIVATING="deactivating",e.INACTIVE="inactive",e.ERROR="error",e.UNINSTALLED="uninstalled",e))(be||{});const s0=p.lazy(()=>je(()=>import("./StudentView-BF2WjF4_.js"),[]).then(e=>({default:e.StudentView}))),r0=p.lazy(()=>je(()=>import("./TeacherView-BySyCiZG.js"),[]).then(e=>({default:e.TeacherView})));function i0(e){const{activeRole:t}=e;return o.jsx(p.Suspense,{fallback:o.jsxs("div",{className:"flex-1 flex flex-col items-center justify-center min-h-[50vh] text-slate-400 gap-3",children:[o.jsx(Gi,{className:"w-8 h-8 animate-spin text-indigo-500"}),o.jsx("span",{className:"text-sm font-medium tracking-wide",children:"正在加载工作台..."})]}),children:t==="student"?o.jsx(s0,{...e}):o.jsx(r0,{...e})})}const ho=p.createContext({});function fo(e){const t=p.useRef(null);return t.current===null&&(t.current=e()),t.current}const o0=typeof window<"u",Fc=o0?p.useLayoutEffect:p.useEffect,Vs=p.createContext(null),po=p.createContext({transformPagePoint:e=>e,isStatic:!1,reducedMotion:"never"});function ll(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function a0(...e){return t=>{let n=!1;const s=e.map(r=>{const i=ll(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():ll(e[r],null)}}}}function l0(...e){return p.useCallback(a0(...e),e)}class c0 extends p.Component{getSnapshotBeforeUpdate(t){const n=this.props.childRef.current;if($r(n)&&t.isPresent&&!this.props.isPresent&&this.props.pop!==!1){const s=n.offsetParent,r=$r(s)&&s.offsetWidth||0,i=$r(s)&&s.offsetHeight||0,a=getComputedStyle(n),l=this.props.sizeRef.current;l.height=parseFloat(a.height),l.width=parseFloat(a.width),l.top=n.offsetTop,l.left=n.offsetLeft,l.right=r-l.width-l.left,l.bottom=i-l.height-l.top,l.direction=a.direction}return null}componentDidUpdate(){}render(){return this.props.children}}function u0({children:e,isPresent:t,anchorX:n,anchorY:s,root:r,pop:i}){const a=p.useId(),l=p.useRef(null),c=p.useRef({width:0,height:0,top:0,left:0,right:0,bottom:0,direction:"ltr"}),{nonce:u}=p.useContext(po),d=e.props?.ref??e?.ref,h=l0(l,d);return p.useInsertionEffect(()=>{const{width:m,height:f,top:g,left:y,right:k,bottom:S,direction:I}=c.current;if(t||i===!1||!l.current||!m||!f)return;const C=I==="rtl",T=n==="left"?C?`right: ${k}`:`left: ${y}`:C?`left: ${y}`:`right: ${k}`,_=s==="bottom"?`bottom: ${S}`:`top: ${g}`;l.current.dataset.motionPopId=a;const E=document.createElement("style");u&&(E.nonce=u);const R=r??document.head;return R.appendChild(E),E.sheet&&E.sheet.insertRule(`
125
- [data-motion-pop-id="${a}"] {
126
- position: absolute !important;
127
- width: ${m}px !important;
128
- height: ${f}px !important;
129
- ${T}px !important;
130
- ${_}px !important;
131
- }
132
- `),()=>{l.current?.removeAttribute("data-motion-pop-id"),R.contains(E)&&R.removeChild(E)}},[t]),o.jsx(c0,{isPresent:t,childRef:l,sizeRef:c,pop:i,children:i===!1?e:p.cloneElement(e,{ref:h})})}const d0=({children:e,initial:t,isPresent:n,onExitComplete:s,custom:r,presenceAffectsLayout:i,mode:a,anchorX:l,anchorY:c,root:u})=>{const d=fo(h0),h=p.useId();let m=!0,f=p.useMemo(()=>(m=!1,{id:h,initial:t,isPresent:n,custom:r,onExitComplete:g=>{d.set(g,!0);for(const y of d.values())if(!y)return;s&&s()},register:g=>(d.set(g,!1),()=>d.delete(g))}),[n,d,s]);return i&&m&&(f={...f}),p.useMemo(()=>{d.forEach((g,y)=>d.set(y,!1))},[n]),p.useEffect(()=>{!n&&!d.size&&s&&s()},[n]),e=o.jsx(u0,{pop:a==="popLayout",isPresent:n,anchorX:l,anchorY:c,root:u,children:e}),o.jsx(Vs.Provider,{value:f,children:e})};function h0(){return new Map}function $c(e=!0){const t=p.useContext(Vs);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 a=p.useCallback(()=>e&&s&&s(i),[i,s,e]);return!n&&s?[!1,a]:[!0]}const rs=e=>e.key||"";function cl(e){const t=[];return p.Children.forEach(e,n=>{p.isValidElement(n)&&t.push(n)}),t}const Bc=({children:e,custom:t,initial:n=!0,onExitComplete:s,presenceAffectsLayout:r=!0,mode:i="sync",propagate:a=!1,anchorX:l="left",anchorY:c="top",root:u})=>{const[d,h]=$c(a),m=p.useMemo(()=>cl(e),[e]),f=a&&!d?[]:m.map(rs),g=p.useRef(!0),y=p.useRef(m),k=fo(()=>new Map),S=p.useRef(new Set),[I,C]=p.useState(m),[T,_]=p.useState(m);Fc(()=>{g.current=!1,y.current=m;for(let B=0;B<T.length;B++){const F=rs(T[B]);f.includes(F)?(k.delete(F),S.current.delete(F)):k.get(F)!==!0&&k.set(F,!1)}},[T,f.length,f.join("-")]);const E=[];if(m!==I){let B=[...m];for(let F=0;F<T.length;F++){const M=T[F],v=rs(M);f.includes(v)||(B.splice(F,0,M),E.push(M))}return i==="wait"&&E.length&&(B=E),_(cl(B)),C(m),null}const{forceRender:R}=p.useContext(ho);return o.jsx(o.Fragment,{children:T.map(B=>{const F=rs(B),M=a&&!d?!1:m===T||f.includes(F),v=()=>{if(S.current.has(F))return;if(k.has(F))S.current.add(F),k.set(F,!0);else return;let z=!0;k.forEach(L=>{L||(z=!1)}),z&&(R?.(),_(y.current),a&&h?.(),s&&s())};return o.jsx(d0,{isPresent:M,initial:!g.current||n?void 0:!1,custom:t,presenceAffectsLayout:r,mode:i,root:u,onExitComplete:M?void 0:v,anchorX:l,anchorY:c,children:B},F)})})},Vc=p.createContext({strict:!1}),ul={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 dl=!1;function f0(){if(dl)return;const e={};for(const t in ul)e[t]={isEnabled:n=>ul[t].some(s=>!!n[s])};Wl(e),dl=!0}function Uc(){return f0(),vp()}function p0(e){const t=Uc();for(const n in e)t[n]={...t[n],...e[n]};Wl(t)}const m0=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 _s(e){return e.startsWith("while")||e.startsWith("drag")&&e!=="draggable"||e.startsWith("layout")||e.startsWith("onTap")||e.startsWith("onPan")||e.startsWith("onLayout")||m0.has(e)}let Hc=e=>!_s(e);function g0(e){typeof e=="function"&&(Hc=t=>t.startsWith("on")?!_s(t):e(t))}try{g0(require("@emotion/is-prop-valid").default)}catch{}function x0(e,t,n){const s={};for(const r in e)r==="values"&&typeof e.values=="object"||Ji(e[r])||(Hc(r)||n===!0&&_s(r)||!t&&!_s(r)||e.draggable&&r.startsWith("onDrag"))&&(s[r]=e[r]);return s}const Us=p.createContext({});function y0(e,t){if(Gl(e)){const{initial:n,animate:s}=e;return{initial:n===!1||oa(n)?n:void 0,animate:oa(s)?s:void 0}}return e.inherit!==!1?t:{}}function b0(e){const{initial:t,animate:n}=y0(e,p.useContext(Us));return p.useMemo(()=>({initial:t,animate:n}),[hl(t),hl(n)])}function hl(e){return Array.isArray(e)?e.join(" "):e}const mo=()=>({style:{},transform:{},transformOrigin:{},vars:{}});function qc(e,t,n){for(const s in t)!Ji(t[s])&&!Cp(s,n)&&(e[s]=t[s])}function w0({transformTemplate:e},t){return p.useMemo(()=>{const n=mo();return kp(n,t,e),Object.assign({},n.vars,n.style)},[t])}function S0(e,t){const n=e.style||{},s={};return qc(s,n,e),Object.assign(s,w0(e,t)),s}function v0(e,t){const n={},s=S0(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 Wc=()=>({...mo(),attrs:{}});function C0(e,t,n,s){const r=p.useMemo(()=>{const i=Wc();return Ep(i,t,jp(s),e.transformTemplate,e.style),{...i.attrs,style:{...i.style}}},[t]);if(e.style){const i={};qc(i,e.style,e),r.style={...i,...r.style}}return r}const k0=["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 go(e){return typeof e!="string"||e.includes("-")?!1:!!(k0.indexOf(e)>-1||/[A-Z]/u.test(e))}function E0(e,t,n,{latestValues:s},r,i=!1,a){const c=(a??go(e)?C0:v0)(t,s,r,e),u=x0(t,typeof e=="string",i),d=e!==p.Fragment?{...u,...c,ref:n}:{},{children:h}=t,m=p.useMemo(()=>Ji(h)?h.get():h,[h]);return p.createElement(e,{...d,children:m})}function j0({scrapeMotionValuesFromProps:e,createRenderState:t},n,s,r){return{latestValues:N0(n,s,r,e),renderState:t()}}function N0(e,t,n,s){const r={},i=s(e,{});for(const m in i)r[m]=Np(i[m]);let{initial:a,animate:l}=e;const c=Gl(e),u=Tp(e);t&&u&&!c&&e.inherit!==!1&&(a===void 0&&(a=t.initial),l===void 0&&(l=t.animate));let d=n?n.initial===!1:!1;d=d||a===!1;const h=d?l:a;if(h&&typeof h!="boolean"&&!Ql(h)){const m=Array.isArray(h)?h:[h];for(let f=0;f<m.length;f++){const g=Pp(e,m[f]);if(g){const{transitionEnd:y,transition:k,...S}=g;for(const I in S){let C=S[I];if(Array.isArray(C)){const T=d?C.length-1:0;C=C[T]}C!==null&&(r[I]=C)}for(const I in y)r[I]=y[I]}}}return r}const Gc=e=>(t,n)=>{const s=p.useContext(Us),r=p.useContext(Vs),i=()=>j0(e,t,s,r);return n?i():fo(i)},T0=Gc({scrapeMotionValuesFromProps:Ip,createRenderState:mo}),P0=Gc({scrapeMotionValuesFromProps:Ap,createRenderState:Wc}),I0=Symbol.for("motionComponentSymbol");function A0(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 a=s.current;if(typeof a=="function")if(i){const l=a(i);typeof l=="function"&&(r.current=l)}else r.current?(r.current(),r.current=null):a(i);else a&&(a.current=i)},[t])}const Qc=p.createContext({});function nn(e){return e&&typeof e=="object"&&Object.prototype.hasOwnProperty.call(e,"current")}function z0(e,t,n,s,r,i){const{visualElement:a}=p.useContext(Us),l=p.useContext(Vc),c=p.useContext(Vs),u=p.useContext(po),d=u.reducedMotion,h=u.skipAnimations,m=p.useRef(null),f=p.useRef(!1);s=s||l.renderer,!m.current&&s&&(m.current=s(e,{visualState:t,parent:a,props:n,presenceContext:c,blockInitialAnimation:c?c.initial===!1:!1,reducedMotionConfig:d,skipAnimations:h,isSVG:i}),f.current&&m.current&&(m.current.manuallyAnimateOnMount=!0));const g=m.current,y=p.useContext(Qc);g&&!g.projection&&r&&(g.type==="html"||g.type==="svg")&&_0(m.current,n,r,y);const k=p.useRef(!1);p.useInsertionEffect(()=>{g&&k.current&&g.update(n,c)});const S=n[zp],I=p.useRef(!!S&&typeof window<"u"&&!window.MotionHandoffIsComplete?.(S)&&window.MotionHasOptimisedAnimation?.(S));return Fc(()=>{f.current=!0,g&&(k.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?.(S)}),I.current=!1),g.enteringChildren=void 0)}),g}function _0(e,t,n,s){const{layoutId:r,layout:i,drag:a,dragConstraints:l,layoutScroll:c,layoutRoot:u,layoutAnchor:d,layoutCrossfade:h}=t;e.projection=new n(e.latestValues,t["data-framer-portal-id"]?void 0:Jc(e.parent)),e.projection.setOptions({layoutId:r,layout:i,alwaysMeasureLayout:!!a||l&&nn(l),visualElement:e,animationType:typeof i=="string"?i:"both",initialPromotionConfig:s,crossfade:h,layoutScroll:c,layoutRoot:u,layoutAnchor:d})}function Jc(e){if(e)return e.options.allowProjection!==!1?e.projection:Jc(e.parent)}function li(e,{forwardMotionProps:t=!1,type:n}={},s,r){s&&p0(s);const i=n?n==="svg":go(e),a=i?P0:T0;function l(u,d){let h;const m={...p.useContext(po),...u,layoutId:L0(u)},{isStatic:f}=m,g=b0(u),y=a(u,f);if(!f&&typeof window<"u"){R0();const k=M0(m);h=k.MeasureLayout,g.visualElement=z0(e,y,m,r,k.ProjectionNode,i)}return o.jsxs(Us.Provider,{value:g,children:[h&&g.visualElement?o.jsx(h,{visualElement:g.visualElement,...m}):null,E0(e,u,A0(y,g.visualElement,d),y,f,t,i)]})}l.displayName=`motion.${typeof e=="string"?e:`create(${e.displayName??e.name??""})`}`;const c=p.forwardRef(l);return c[I0]=e,c}function L0({layoutId:e}){const t=p.useContext(ho).id;return t&&e!==void 0?t+"-"+e:e}function R0(e,t){p.useContext(Vc).strict}function M0(e){const t=Uc(),{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 O0(e,t){if(typeof Proxy>"u")return li;const n=new Map,s=(i,a)=>li(i,a,e,t),r=(i,a)=>s(i,a);return new Proxy(r,{get:(i,a)=>a==="create"?s:(n.has(a)||n.set(a,li(a,void 0,e,t)),n.get(a))})}const D0=(e,t)=>t.isSVG??go(e)?new _p(t):new Lp(t,{allowProjection:e!==p.Fragment});class F0 extends _t{constructor(t){super(t),t.animationState||(t.animationState=Rp(t))}updateAnimationControlsSubscription(){const{animate:t}=this.node.getProps();Ql(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 $0=0;class B0 extends _t{constructor(){super(...arguments),this.id=$0++,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:a}=this.node.getProps();if(typeof i=="string"||typeof i=="object"&&i!==null&&!Array.isArray(i)){const l=Mp(this.node,i,a);if(l){const{transition:c,transitionEnd:u,...d}=l;for(const h in d)this.node.getValue(h)?.jump(d[h])}}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 V0={animation:{Feature:F0},exit:{Feature:B0}};function $n(e){return{point:{x:e.pageX,y:e.pageY}}}const U0=e=>t=>Jl(t)&&e(t,$n(t));function zn(e,t,n,s){return Ts(e,t,U0(n),s)}const Zc=({current:e})=>e?e.ownerDocument.defaultView:null,fl=(e,t)=>Math.abs(e-t);function H0(e,t){const n=fl(e.x,t.x),s=fl(e.y,t.y);return Math.sqrt(n**2+s**2)}const pl=new Set(["auto","scroll"]);class Yc{constructor(t,n,{transformPagePoint:s,contextWindow:r=window,dragSnapToOrigin:i=!1,distanceThreshold:a=3,element:l}={}){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=f=>{this.handleScroll(f.target)},this.onWindowScroll=()=>{this.handleScroll(window)},this.updatePoint=()=>{if(!(this.lastMoveEvent&&this.lastMoveEventInfo))return;this.lastRawMoveEventInfo&&(this.lastMoveEventInfo=is(this.lastRawMoveEventInfo,this.transformPagePoint));const f=ci(this.lastMoveEventInfo,this.history),g=this.startEvent!==null,y=H0(f.offset,{x:0,y:0})>=this.distanceThreshold;if(!g&&!y)return;const{point:k}=f,{timestamp:S}=aa;this.history.push({...k,timestamp:S});const{onStart:I,onMove:C}=this.handlers;g||(I&&I(this.lastMoveEvent,f),this.startEvent=this.lastMoveEvent),C&&C(this.lastMoveEvent,f)},this.handlePointerMove=(f,g)=>{this.lastMoveEvent=f,this.lastRawMoveEventInfo=g,this.lastMoveEventInfo=is(g,this.transformPagePoint),nt.update(this.updatePoint,!0)},this.handlePointerUp=(f,g)=>{this.end();const{onEnd:y,onSessionEnd:k,resumeAnimation:S}=this.handlers;if((this.dragSnapToOrigin||!this.startEvent)&&S&&S(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const I=ci(f.type==="pointercancel"?this.lastMoveEventInfo:is(g,this.transformPagePoint),this.history);this.startEvent&&y&&y(f,I),k&&k(f,I)},!Jl(t))return;this.dragSnapToOrigin=i,this.handlers=n,this.transformPagePoint=s,this.distanceThreshold=a,this.contextWindow=r||window;const c=$n(t),u=is(c,this.transformPagePoint),{point:d}=u,{timestamp:h}=aa;this.history=[{...d,timestamp:h}];const{onSessionStart:m}=n;m&&m(t,ci(u,this.history)),this.removeListeners=Zl(zn(this.contextWindow,"pointermove",this.handlePointerMove),zn(this.contextWindow,"pointerup",this.handlePointerUp),zn(this.contextWindow,"pointercancel",this.handlePointerUp)),l&&this.startScrollTracking(l)}startScrollTracking(t){let n=t.parentElement;for(;n;){const s=getComputedStyle(n);(pl.has(s.overflowX)||pl.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),nt.update(this.updatePoint,!0))}updateHandlers(t){this.handlers=t}end(){this.removeListeners&&this.removeListeners(),this.removeScrollListeners&&this.removeScrollListeners(),this.scrollPositions.clear(),Op(this.updatePoint)}}function is(e,t){return t?{point:t(e.point)}:e}function ml(e,t){return{x:e.x-t.x,y:e.y-t.y}}function ci({point:e},t){return{point:e,delta:ml(e,Kc(t)),offset:ml(e,q0(t)),velocity:W0(t,.1)}}function q0(e){return e[0]}function Kc(e){return e[e.length-1]}function W0(e,t){if(e.length<2)return{x:0,y:0};let n=e.length-1,s=null;const r=Kc(e);for(;n>=0&&(s=e[n],!(r.timestamp-s.timestamp>la(t)));)n--;if(!s)return{x:0,y:0};s===e[0]&&e.length>2&&r.timestamp-s.timestamp>la(t)*2&&(s=e[1]);const i=Dp(r.timestamp-s.timestamp);if(i===0)return{x:0,y:0};const a={x:(r.x-s.x)/i,y:(r.y-s.y)/i};return a.x===1/0&&(a.x=0),a.y===1/0&&(a.y=0),a}function G0(e,{min:t,max:n},s){return t!==void 0&&e<t?e=s?Ps(t,e,s.min):Math.max(e,t):n!==void 0&&e>n&&(e=s?Ps(n,e,s.max):Math.min(e,n)),e}function gl(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 Q0(e,{top:t,left:n,bottom:s,right:r}){return{x:gl(e.x,n,r),y:gl(e.y,t,s)}}function xl(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 J0(e,t){return{x:xl(e.x,t.x),y:xl(e.y,t.y)}}function Z0(e,t){let n=.5;const s=ki(e),r=ki(t);return r>s?n=ca(t.min,t.max-s,e.min):s>r&&(n=ca(e.min,e.max-r,t.min)),Fp(0,1,n)}function Y0(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 Ri=.35;function K0(e=Ri){return e===!1?e=0:e===!0&&(e=Ri),{x:yl(e,"left","right"),y:yl(e,"top","bottom")}}function yl(e,t,n){return{min:bl(e,t),max:bl(e,n)}}function bl(e,t){return typeof e=="number"?e:e[t]||0}const X0=new WeakMap;class ew{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=$p(),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=h=>{n&&this.snapToCursor($n(h).point),this.stopAnimation()},a=(h,m)=>{const{drag:f,dragPropagation:g,onDragStart:y}=this.getProps();if(f&&!g&&(this.openDragLock&&this.openDragLock(),this.openDragLock=qp(f),!this.openDragLock))return;this.latestPointerEvent=h,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),Pt(S=>{let I=this.getAxisMotionValue(S).get()||0;if(Wp.test(I)){const{projection:C}=this.visualElement;if(C&&C.layout){const T=C.layout.layoutBox[S];T&&(I=ki(T)*(parseFloat(I)/100))}}this.originPoint[S]=I}),y&&nt.update(()=>y(h,m),!1,!0),ua(this.visualElement,"transform");const{animationState:k}=this.visualElement;k&&k.setActive("whileDrag",!0)},l=(h,m)=>{this.latestPointerEvent=h,this.latestPanInfo=m;const{dragPropagation:f,dragDirectionLock:g,onDirectionLock:y,onDrag:k}=this.getProps();if(!f&&!this.openDragLock)return;const{offset:S}=m;if(g&&this.currentDirection===null){this.currentDirection=nw(S),this.currentDirection!==null&&y&&y(this.currentDirection);return}this.updateAxis("x",m.point,S),this.updateAxis("y",m.point,S),this.visualElement.render(),k&&nt.update(()=>k(h,m),!1,!0)},c=(h,m)=>{this.latestPointerEvent=h,this.latestPanInfo=m,this.stop(h,m),this.latestPointerEvent=null,this.latestPanInfo=null},u=()=>{const{dragSnapToOrigin:h}=this.getProps();(h||this.constraints)&&this.startAnimation({x:0,y:0})},{dragSnapToOrigin:d}=this.getProps();this.panSession=new Yc(t,{onSessionStart:i,onStart:a,onMove:l,onSessionEnd:c,resumeAnimation:u},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:d,distanceThreshold:s,contextWindow:Zc(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:a}=r;this.startAnimation(a);const{onDragEnd:l}=this.getProps();l&&nt.postRender(()=>l(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||!os(t,r,this.currentDirection))return;const i=this.getAxisMotionValue(t);let a=this.originPoint[t]+s[t];this.constraints&&this.constraints[t]&&(a=G0(a,this.constraints[t],this.elastic[t])),i.set(a)}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&&nn(t)?this.constraints||(this.constraints=this.resolveRefConstraints()):t&&s?this.constraints=Q0(s.layoutBox,t):this.constraints=!1,this.elastic=K0(n),r!==this.constraints&&!nn(t)&&s&&this.constraints&&!this.hasMutatedConstraints&&Pt(i=>{this.constraints!==!1&&this.getAxisMotionValue(i)&&(this.constraints[i]=Y0(s.layoutBox[i],this.constraints[i]))})}resolveRefConstraints(){const{dragConstraints:t,onMeasureDragConstraints:n}=this.getProps();if(!t||!nn(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=Bp(s,r.root,this.visualElement.getTransformPagePoint());let a=J0(r.layout.layoutBox,i);if(n){const l=n(Vp(a));this.hasMutatedConstraints=!!l,l&&(a=Up(l))}return a}startAnimation(t){const{drag:n,dragMomentum:s,dragElastic:r,dragTransition:i,dragSnapToOrigin:a,onDragTransitionEnd:l}=this.getProps(),c=this.constraints||{},u=Pt(d=>{if(!os(d,n,this.currentDirection))return;let h=c&&c[d]||{};(a===!0||a===d)&&(h={min:0,max:0});const m=r?200:1e6,f=r?40:1e7,g={type:"inertia",velocity:s?t[d]:0,bounceStiffness:m,bounceDamping:f,timeConstant:750,restDelta:1,restSpeed:10,...i,...h};return this.startAxisValueAnimation(d,g)});return Promise.all(u).then(l)}startAxisValueAnimation(t,n){const s=this.getAxisMotionValue(t);return ua(this.visualElement,t),s.start(Hp(t,s,0,n,this.visualElement,!1))}stopAnimation(){Pt(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){Pt(n=>{const{drag:s}=this.getProps();if(!os(n,s,this.currentDirection))return;const{projection:r}=this.visualElement,i=this.getAxisMotionValue(n);if(r&&r.layout){const{min:a,max:l}=r.layout.layoutBox[n],c=i.get()||0;i.set(t[n]-Ps(a,l,.5)+c)}})}scalePositionWithinConstraints(){if(!this.visualElement.current)return;const{drag:t,dragConstraints:n}=this.getProps(),{projection:s}=this.visualElement;if(!nn(n)||!s||!this.constraints)return;this.stopAnimation();const r={x:0,y:0};Pt(a=>{const l=this.getAxisMotionValue(a);if(l&&this.constraints!==!1){const c=l.get();r[a]=Z0({min:c,max:c},this.constraints[a])}});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(),Pt(a=>{if(!os(a,t,null))return;const l=this.getAxisMotionValue(a),{min:c,max:u}=this.constraints[a];l.set(Ps(c,u,r[a]))}),this.visualElement.render()}addListeners(){if(!this.visualElement.current)return;X0.set(this.visualElement,this);const t=this.visualElement.current,n=zn(t,"pointerdown",u=>{const{drag:d,dragListener:h=!0}=this.getProps(),m=u.target,f=m!==t&&Gp(m);d&&h&&!f&&this.start(u)});let s;const r=()=>{const{dragConstraints:u}=this.getProps();nn(u)&&u.current&&(this.constraints=this.resolveRefConstraints(),s||(s=tw(t,u.current,()=>this.scalePositionWithinConstraints())))},{projection:i}=this.visualElement,a=i.addEventListener("measure",r);i&&!i.layout&&(i.root&&i.root.updateScroll(),i.updateLayout()),nt.read(r);const l=Ts(window,"resize",()=>this.scalePositionWithinConstraints()),c=i.addEventListener("didUpdate",(({delta:u,hasLayoutChanged:d})=>{this.isDragging&&d&&(Pt(h=>{const m=this.getAxisMotionValue(h);m&&(this.originPoint[h]+=u[h].translate,m.set(m.get()+u[h].translate))}),this.visualElement.render())}));return()=>{l(),n(),a(),c&&c(),s&&s()}}getProps(){const t=this.visualElement.getProps(),{drag:n=!1,dragDirectionLock:s=!1,dragPropagation:r=!1,dragConstraints:i=!1,dragElastic:a=Ri,dragMomentum:l=!0}=t;return{...t,drag:n,dragDirectionLock:s,dragPropagation:r,dragConstraints:i,dragElastic:a,dragMomentum:l}}}function wl(e){let t=!0;return()=>{if(t){t=!1;return}e()}}function tw(e,t,n){const s=da(e,wl(n)),r=da(t,wl(n));return()=>{s(),r()}}function os(e,t,n){return(t===!0||t===e)&&(n===null||n===e)}function nw(e,t=10){let n=null;return Math.abs(e.y)>t?n="y":Math.abs(e.x)>t&&(n="x"),n}class sw extends _t{constructor(t){super(t),this.removeGroupControls=fs,this.removeListeners=fs,this.controls=new ew(t)}mount(){const{dragControls:t}=this.node.getProps();t&&(this.removeGroupControls=t.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||fs}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 ui=e=>(t,n)=>{e&&nt.update(()=>e(t,n),!1,!0)};class rw extends _t{constructor(){super(...arguments),this.removePointerDownListener=fs}onPointerDown(t){this.session=new Yc(t,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:Zc(this.node)})}createPanHandlers(){const{onPanSessionStart:t,onPanStart:n,onPan:s,onPanEnd:r}=this.node.getProps();return{onSessionStart:ui(t),onStart:ui(n),onMove:ui(s),onEnd:(i,a)=>{delete this.session,r&&nt.postRender(()=>r(i,a))}}}mount(){this.removePointerDownListener=zn(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 di=!1;class iw 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),di&&i.root.didUpdate(),i.addEventListener("animationComplete",()=>{this.safeToRemove()}),i.setOptions({...i.options,layoutDependency:this.props.layoutDependency,onExitComplete:()=>this.safeToRemove()})),Jp.hasEverUpdated=!0}getSnapshotBeforeUpdate(t){const{layoutDependency:n,visualElement:s,drag:r,isPresent:i}=this.props,{projection:a}=s;return a&&(a.isPresent=i,t.layoutDependency!==n&&a.setOptions({...a.options,layoutDependency:n}),di=!0,r||t.layoutDependency!==n||n===void 0||t.isPresent!==i?a.willUpdate():this.safeToRemove(),t.isPresent!==i&&(i?a.promote():a.relegate()||nt.postRender(()=>{const l=a.getStack();(!l||!l.members.length)&&this.safeToRemove()}))),null}componentDidUpdate(){const{visualElement:t,layoutAnchor:n}=this.props,{projection:s}=t;s&&(s.options.layoutAnchor=n,s.root.didUpdate(),Qp.postRender(()=>{!s.currentAnimation&&s.isLead()&&this.safeToRemove()}))}componentWillUnmount(){const{visualElement:t,layoutGroup:n,switchLayoutGroup:s}=this.props,{projection:r}=t;di=!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 Xc(e){const[t,n]=$c(),s=p.useContext(ho);return o.jsx(iw,{...e,layoutGroup:s,switchLayoutGroup:p.useContext(Qc),isPresent:t,safeToRemove:n})}const ow={pan:{Feature:rw},drag:{Feature:sw,ProjectionNode:Yl,MeasureLayout:Xc}};function Sl(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&&nt.postRender(()=>i(t,$n(t)))}class aw extends _t{mount(){const{current:t}=this.node;t&&(this.unmount=Zp(t,(n,s)=>(Sl(this.node,s,"Start"),r=>Sl(this.node,r,"End"))))}unmount(){}}class lw extends _t{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=Zl(Ts(this.node.current,"focus",()=>this.onFocus()),Ts(this.node.current,"blur",()=>this.onBlur()))}unmount(){}}function vl(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&&nt.postRender(()=>i(t,$n(t)))}class cw extends _t{mount(){const{current:t}=this.node;if(!t)return;const{globalTapTarget:n,propagate:s}=this.node.props;this.unmount=Yp(t,(r,i)=>(vl(this.node,i,"Start"),(a,{success:l})=>vl(this.node,a,l?"End":"Cancel")),{useGlobalTarget:n,stopPropagation:s?.tap===!1})}unmount(){}}const Mi=new WeakMap,hi=new WeakMap,uw=e=>{const t=Mi.get(e.target);t&&t(e)},dw=e=>{e.forEach(uw)};function hw({root:e,...t}){const n=e||document;hi.has(n)||hi.set(n,{});const s=hi.get(n),r=JSON.stringify(t);return s[r]||(s[r]=new IntersectionObserver(dw,{root:e,...t})),s[r]}function fw(e,t,n){const s=hw(t);return Mi.set(e,n),s.observe(e),()=>{Mi.delete(e),s.unobserve(e)}}const pw={some:0,all:1};class mw extends _t{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,a={root:n?n.current:void 0,rootMargin:s,threshold:typeof r=="number"?r:pw[r]},l=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:h}=this.node.getProps(),m=u?d:h;m&&m(c)};this.stopObserver=fw(this.node.current,a,l)}mount(){this.startObserver()}update(){if(typeof IntersectionObserver>"u")return;const{props:t,prevProps:n}=this.node;["amount","margin","root"].some(gw(t,n))&&this.startObserver()}unmount(){this.stopObserver?.(),this.hasEnteredView=!1,this.isInView=!1}}function gw({viewport:e={}},{viewport:t={}}={}){return n=>e[n]!==t[n]}const xw={inView:{Feature:mw},tap:{Feature:cw},focus:{Feature:lw},hover:{Feature:aw}},yw={layout:{ProjectionNode:Yl,MeasureLayout:Xc}},bw={...V0,...xw,...ow,...yw},xs=O0(bw,D0);async function Ls(e){if(typeof window>"u")return!1;try{if(navigator.clipboard&&window.isSecureContext)return await navigator.clipboard.writeText(e),!0}catch{}try{const t=document.createElement("textarea");t.value=e,t.style.position="fixed",t.style.left="-999999px",t.style.top="-999999px",t.setAttribute("readonly",""),document.body.appendChild(t),t.focus(),t.select();const n=document.execCommand("copy");return document.body.removeChild(t),n}catch(t){return console.error("[OpenLearn Clipboard] Failed to copy text to clipboard:",t),!1}}function ww(){const e=de(i=>i.toasts),[t,n]=p.useState(null),s=async(i,a)=>{i.stopPropagation();const l=`[${a.title}] ${a.message}`;await Ls(l)&&(n(a.id),setTimeout(()=>n(null),2e3))},r=i=>{switch(i){case"error":return{border:"border-l-4 border-rose-500",iconBg:"bg-rose-50 text-rose-600 dark:bg-rose-950/60 dark:text-rose-400",icon:o.jsx(bi,{size:16})};case"warning":return{border:"border-l-4 border-amber-500",iconBg:"bg-amber-50 text-amber-600 dark:bg-amber-950/60 dark:text-amber-400",icon:o.jsx(Ns,{size:16})};case"info":return{border:"border-l-4 border-blue-500",iconBg:"bg-blue-50 text-blue-600 dark:bg-blue-950/60 dark:text-blue-400",icon:o.jsx(fp,{size:16})};case"success":default:return{border:"border-l-4 border-emerald-500",iconBg:"bg-emerald-50 text-emerald-600 dark:bg-emerald-950/60 dark:text-emerald-400",icon:o.jsx(On,{size:16})}}};return o.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:o.jsx(Bc,{children:e.map(i=>{const a=r(i.type),l=t===i.id;return o.jsxs(xs.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 dark:bg-slate-900 ring-1 ring-black/5 shadow-2xl rounded-xl p-4 flex gap-3 ${a.border} overflow-hidden text-gray-900 dark:text-gray-100`,id:`toast-${i.id}`,children:[o.jsxs("div",{className:"flex-1 min-w-0",children:[o.jsxs("div",{className:"flex items-center justify-between gap-2",children:[o.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[o.jsx("span",{className:`p-1 rounded-full shrink-0 ${a.iconBg}`,children:a.icon}),o.jsx("p",{className:"font-semibold text-sm font-sans truncate",children:i.title})]}),(i.type==="error"||i.type==="warning")&&o.jsxs("button",{type:"button",onClick:c=>s(c,i),className:`text-xs font-bold px-1.5 py-0.5 rounded transition-all flex items-center gap-1 cursor-pointer shrink-0 ${l?"bg-emerald-600 text-white":"bg-gray-100 hover:bg-gray-200 dark:bg-slate-800 dark:hover:bg-slate-700 text-gray-600 dark:text-gray-300"}`,title:"复制错误内容",children:[l?o.jsx(et,{size:11}):o.jsx(rn,{size:11}),o.jsx("span",{children:l?"已复制":"复制"})]})]}),o.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400 mt-2 leading-relaxed font-sans break-words",children:i.message})]}),o.jsx("button",{type:"button",onClick:()=>ve.getState().removeToast(i.id),className:"text-gray-400 hover:text-gray-600 dark:hover:text-gray-200 hover:bg-gray-50 dark:hover:bg-slate-800 rounded p-1 h-fit transition-colors shrink-0 cursor-pointer",children:o.jsx(tt,{size:14})})]},i.id)})})})}function Sw({showRightSidebar:e,setShowRightSidebar:t,rightSidebarTab:n,setRightSidebarTab:s,effectiveAgentProviderId:r,agentProviderId:i,setAgentProviderId:a,aiProviders:l,selectedAgentProvider:c,chatLog:u,loading:d,input:h,setInput:m,handleSend:f,chatAttachments:g,setChatAttachments:y,handleChatFileChange:k,handleChatDrop:S,onClearAgentMemory:I,events:C,lang:T,t:_}){const E=p.useRef(null);return p.useEffect(()=>{E.current?.scrollIntoView({behavior:"smooth"})},[u]),o.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?o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"flex bg-gray-100 p-1 m-4 rounded-lg shrink-0",children:[o.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:[o.jsx(Fr,{size:14})," Agent"]}),o.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:[o.jsx(hs,{size:14})," Shell"]}),o.jsx("button",{onClick:()=>t(!1),className:"ml-1 p-1.5 text-gray-400 hover:text-gray-600 rounded-md",children:o.jsx(pp,{size:14})})]}),n==="agent"?o.jsxs("div",{className:"flex-1 flex flex-col min-h-0",children:[o.jsx("div",{className:"p-4 border-b border-gray-100 shrink-0",children:o.jsxs("div",{className:"flex items-start justify-between gap-3",children:[o.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[o.jsx("div",{className:"p-1.5 bg-indigo-50 text-indigo-600 rounded-lg",children:o.jsx(Fr,{size:16})}),o.jsxs("div",{className:"min-w-0",children:[o.jsx("h2",{className:"font-semibold text-gray-900 text-sm",children:_.agentTitle}),o.jsx("p",{className:"text-xs text-gray-500",children:_.agentSubtitle}),o.jsxs("button",{onClick:I,title:T==="zh"?"清除内核助手的对话记忆":"Clear the kernel assistant's conversation memory",className:"mt-1 inline-flex items-center gap-1 text-xs text-gray-400 hover:text-red-500 transition-colors",children:["🧹 ",T==="zh"?"清除记忆":"Clear memory"]})]})]}),o.jsxs("div",{className:"flex flex-col items-end gap-1.5 min-w-[150px] max-w-[50%]",children:[o.jsx("span",{className:"text-xs font-semibold uppercase tracking-[0.18em] text-gray-400",children:T==="zh"?"AI 提供商":"AI Provider"}),o.jsxs("div",{className:"relative w-full",children:[l.length===0?o.jsx("select",{disabled:!0,value:"",className:"w-full appearance-none rounded-xl border border-amber-200 bg-amber-50/50 px-3 py-2 pr-9 text-xs font-medium text-amber-700 shadow-xs outline-none cursor-not-allowed",children:o.jsx("option",{value:"",children:T==="zh"?"未配置 AI 提供商":"No AI Provider"})}):o.jsx("select",{value:r,onChange:R=>a(R.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-xs font-medium text-gray-700 shadow-xs outline-none transition-colors focus:border-indigo-400 focus:ring-2 focus:ring-indigo-100",children:l.map(R=>o.jsx("option",{value:R.id,children:R.name},R.id))}),o.jsx(Ln,{size:12,className:"pointer-events-none absolute right-3 top-1/2 -translate-y-1/2 text-gray-400"})]}),o.jsx("div",{className:"text-xs text-gray-400 truncate w-full text-right",title:c?.model_name||"",children:c?`${c.model_name}`:T==="zh"?"未配置提供商":"No Provider"})]})]})}),l.length===0&&o.jsxs("div",{className:"mx-4 mt-3 p-3 bg-amber-50 border border-amber-200/80 rounded-xl text-xs text-amber-900 flex items-start gap-2 shadow-xs shrink-0",children:[o.jsx(Ns,{size:15,className:"shrink-0 text-amber-600 mt-0.5"}),o.jsxs("div",{className:"flex-1 leading-relaxed",children:[o.jsx("span",{className:"font-semibold",children:T==="zh"?"未配置 AI 提供商":"No AI Provider Configured"}),o.jsx("p",{className:"mt-0.5 text-amber-700",children:T==="zh"?"请前往「系统管理 -> AI 提供商管理」添加大模型服务(如 DeepSeek、Qwen、OpenAI 等)。":'Please configure an AI provider in "System Management -> AI Provider Management" to use the AI assistant.'})]})]}),o.jsxs("div",{className:"flex-1 overflow-y-auto p-4 space-y-4",children:[u.map((R,B)=>o.jsx("div",{className:`flex flex-col ${R.role==="user"?"items-end":"items-start"}`,children:o.jsx("div",{className:`px-4 py-2.5 rounded-2xl max-w-[85%] text-xs whitespace-pre-wrap ${R.role==="user"?"bg-indigo-600 text-white rounded-br-none":"bg-gray-100 text-gray-800 rounded-bl-none"}`,children:R.content})},B)),d&&o.jsx("div",{className:"flex items-start",children:o.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:[o.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-gray-400 animate-bounce"}),o.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-gray-400 animate-bounce",style:{animationDelay:"0.1s"}}),o.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-gray-400 animate-bounce",style:{animationDelay:"0.2s"}})]})}),o.jsx("div",{ref:E})]}),o.jsxs("form",{onSubmit:f,className:"p-3 border-t border-gray-100 bg-white shrink-0 font-sans",onDragOver:R=>R.preventDefault(),onDrop:S,children:[g.length>0&&o.jsx("div",{className:"flex flex-wrap gap-1 mb-2 px-1",children:g.map((R,B)=>o.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-xs",children:[o.jsx(Hl,{size:10,className:"shrink-0"}),o.jsx("span",{className:"truncate max-w-[100px]",title:R.name,children:R.name}),o.jsx("button",{type:"button",onClick:()=>y(F=>F.filter((M,v)=>v!==B)),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:o.jsx(tt,{size:10})})]},B))}),o.jsxs("div",{className:"flex items-center gap-1.5",children:[o.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:[o.jsx(mp,{size:14}),o.jsx("input",{type:"file",multiple:!0,className:"hidden",onChange:k,accept:".csv,.txt,.json,.md"})]}),o.jsxs("div",{className:"relative flex-1",children:[o.jsx("input",{type:"text",value:h,disabled:l.length===0,onChange:R=>m(R.target.value),placeholder:l.length===0?T==="zh"?"请先配置 AI 提供商":"Please configure AI provider first":_.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 disabled:opacity-60 disabled:cursor-not-allowed"}),o.jsx("button",{type:"submit",disabled:d||!h.trim()||l.length===0,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 cursor-pointer disabled:cursor-not-allowed",children:o.jsx(gp,{size:10})})]})]})]})]}):o.jsxs("div",{className:"flex-1 flex flex-col bg-black text-green-400 font-mono text-xs min-h-0 mx-4 mb-4 rounded-xl shadow-inner border border-gray-800 overflow-hidden",children:[o.jsx("div",{className:"p-3 border-b border-gray-800 flex items-center justify-between shrink-0 bg-gray-900",children:o.jsxs("div",{className:"flex items-center gap-2 text-gray-300 font-sans tracking-wide",children:[o.jsx(hs,{size:14}),o.jsx("span",{className:"text-xs",children:_.eventStream})]})}),o.jsx("div",{className:"p-3 overflow-y-auto flex-1 flex flex-col gap-1 select-text",children:C.length===0?o.jsx("div",{className:"text-gray-600 italic",children:"Waiting for events..."}):C.map((R,B)=>o.jsxs("div",{className:"flex flex-col gap-1 hover:bg-gray-800/50 p-2 rounded mb-1",children:[o.jsxs("div",{className:"flex items-center gap-2 justify-between",children:[o.jsxs("span",{className:"text-gray-500 shrink-0 text-xs",children:["[",new Date(R.timestamp).toLocaleTimeString(),"]"]}),o.jsx("span",{className:"text-blue-400 shrink-0 truncate text-xs",title:R.source,children:R.source})]}),o.jsx("div",{className:"text-green-300 font-bold",children:R.type}),o.jsx("div",{className:"text-gray-400 break-words mt-1 leading-tight",children:R.payload})]},B))})]})]}):o.jsxs("div",{className:"flex flex-col items-center py-6 h-full text-gray-400 w-full",onClick:()=>t(!0),children:[o.jsx(Fr,{size:18,className:"mb-6 hover:text-indigo-500"}),o.jsx(hs,{size:18,className:"hover:text-indigo-500"}),o.jsx("div",{className:"mt-8 flex-1 flex flex-col justify-end pb-8",children:o.jsx("div",{className:"uppercase tracking-widest text-xs rotate-180",style:{writingMode:"vertical-rl"},children:"OS Core Options"})})]})})}const vw=p.lazy(()=>je(()=>import("./ImportModal-CVXHZ1Ei.js"),[]).then(e=>({default:e.ImportModal}))),Cw=p.lazy(()=>je(()=>import("./CourseWizardModal-m7TDgcB2.js"),[]).then(e=>({default:e.CourseWizardModal}))),kw=p.lazy(()=>je(()=>import("./ImportLessonsModal-hKRuw9p4.js"),[]).then(e=>({default:e.ImportLessonsModal}))),Ew=p.lazy(()=>je(()=>import("./QuizGeneratorModal-BFCJe1cm.js"),[]).then(e=>({default:e.QuizGeneratorModal}))),jw=p.lazy(()=>je(()=>import("./StudentPreviewModal-BXbKzQgo.js"),[]).then(e=>({default:e.StudentPreviewModal}))),Nw=p.lazy(()=>je(()=>import("./ProcessLogsModal-gZ9LILYM.js"),[]).then(e=>({default:e.ProcessLogsModal}))),Tw=p.lazy(()=>je(()=>import("./CloudDriveModal-Bi-aMuax.js"),[]).then(e=>({default:e.CloudDriveModal}))),Pw=p.lazy(()=>je(()=>import("./SystemResourceLibraryModal-Ce-Dis6M.js"),[]).then(e=>({default:e.SystemResourceLibraryModal}))),Iw=p.lazy(()=>je(()=>import("./BatchPickerModal-C9FH3J57.js"),[]).then(e=>({default:e.BatchPickerModal}))),Aw=p.lazy(()=>je(()=>import("./ExportWeightModal-C4d-0uTM.js"),[]).then(e=>({default:e.ExportWeightModal}))),zw=p.lazy(()=>je(()=>import("./NotificationDetailModal-1MOkBDr_.js"),[]).then(e=>({default:e.NotificationDetailModal}))),_w=p.lazy(()=>je(()=>import("./HelpTour-00eT17Vg.js"),[]).then(e=>({default:e.HelpTour}))),Lw=p.lazy(()=>je(()=>import("./CoursewareHubPanel-C4LQjt4v.js"),[]).then(e=>({default:e.CoursewareHubPanel})));function Rw(e){const{lang:t,t:n,showImportModal:s=!1,setShowImportModal:r=()=>{},handleImportFile:i=()=>{},importError:a=null,importSuccess:l=null,isImporting:c=!1,downloadCSVTemplate:u=()=>{},addToast:d=()=>{},generateTemplateContent:h=()=>"",isImportLessonsOpen:m=!1,setIsImportLessonsOpen:f=()=>{},importStatus:g="idle",setIsDraggingImport:y=()=>{},handleCSVFileChange:k=()=>{},downloadCsvTemplate:S=()=>{},isDraggingImport:I=!1,previewImportData:C=[],setPreviewImportData:T=()=>{},setImportStatus:_=()=>{},importProgress:E=0,importProgressTotal:R=0,importErrorMsg:B="",setImportErrorMsg:F=()=>{},handleCSVImportSubmit:M=()=>{},lessons:v=[],fetchClassDashboard:z=()=>{},isLessonPreviewVisible:L=!1,setIsLessonPreviewVisible:P=()=>{},selectedLesson:j=null,previewFullscreenPanel:A="none",setPreviewFullscreenPanel:U=()=>{},previewLessonTab:N="whiteboard",setPreviewLessonTab:O=()=>{},activeRole:x="teacher",elements:oe=[],activeSegmentId:pe=null,setActiveSegmentId:b=()=>{},fetchElements:J=()=>{},currentVfsParent:D=null,setCurrentVfsParent:G=()=>{},vfsNodes:re=[],previewSelectedCourseware:se=null,setPreviewSelectedCourseware:we=()=>{},showProcessLogs:me=null,setShowProcessLogs:le=()=>{},processLogsContent:Ve="",isCloudDriveOpen:St=!1,setIsCloudDriveOpen:Ut=()=>{},cloudDrivePreviewNode:vt=null,setCloudDrivePreviewNode:Ct=()=>{},isSystemResourceLibraryOpen:Rt=!1,setIsSystemResourceLibraryOpen:Y=()=>{},systemResourceTab:te="system",setSystemResourceTab:ae=()=>{},selectedLibraryResourceId:Ne=null,setSelectedLibraryResourceId:Ue=()=>{},loadingLibraryResources:He=!1,libraryResources:dt=[],fetchLibraryResources:Te=()=>{},classes:$=[],expandedClassId:q=null,isExportWeightModalOpen:K=!1,setIsExportWeightModalOpen:Z=()=>{},quizzesWeight:X=40,setQuizzesWeight:Pe=()=>{},assignmentsWeight:Ze=60,setAssignmentsWeight:Fe=()=>{},handleQuizzesWeightChange:st=()=>{},handleAssignmentsWeightChange:ht=()=>{},customCategoryOverrides:ge={},setCustomCategoryOverrides:rt=()=>{},classDashboardMap:_e={},exportClassId:Ws="",exportClassName:Bn="",csvPreviewData:Gs=null,handleExportGrades:kt=()=>{},setSelectedAssignment:Ht=()=>{},setStudentViewStatus:hn=()=>{},setQuizStudentAnswers:Qs=()=>{},setSubAssignmentTab:Js=()=>{},isTourOpen:Zs=!1,setIsTourOpen:Ys=()=>{},handleSeedSuccess:Ks=()=>{},setTeacherTab:Xs=()=>{},showCoursewareHub:er=!1,setShowCoursewareHub:tr=()=>{}}=e,ke=e.courseWizard,nr=ke?.isCourseWizardOpen??e.isCourseWizardOpen??!1,sr=ke?.setIsCourseWizardOpen??e.setIsCourseWizardOpen??(()=>{}),rr=ke?.wizardStep??e.wizardStep??1,fn=ke?.setWizardStep??e.setWizardStep??(()=>{}),pn=ke?.wizardIsSubmitting??e.wizardIsSubmitting??!1,Vn=ke?.wizardCourseTitle??e.wizardCourseTitle??"",ir=ke?.setWizardCourseTitle??e.setWizardCourseTitle??(()=>{}),qt=ke?.wizardCourseDescription??e.wizardCourseDescription??"",or=ke?.setWizardCourseDescription??e.setWizardCourseDescription??(()=>{}),Re=ke?.wizardCourseCategory??e.wizardCourseCategory??"",Un=ke?.setWizardCourseCategory??e.setWizardCourseCategory??(()=>{}),ar=ke?.wizardCourseTimeline??e.wizardCourseTimeline??[],Hn=ke?.setWizardCourseTimeline??e.setWizardCourseTimeline??(()=>{}),lr=ke?.wizardCourseContent??e.wizardCourseContent??"",Wt=ke?.setWizardCourseContent??e.setWizardCourseContent??(()=>{}),cr=ke?.handleDeployWizardCourse??e.handleDeployWizardCourse??(()=>{}),xe=e.quizGenerator,ur=xe?.isQuizGeneratorOpen??e.isQuizGeneratorOpen??!1,dr=xe?.setIsQuizGeneratorOpen??e.setIsQuizGeneratorOpen??(()=>{}),hr=xe?.quizGenMode??e.quizGenMode??"scan_lesson",fr=xe?.setQuizGenMode??e.setQuizGenMode??(()=>{}),pr=xe?.quizGenSelectedLessonId??e.quizGenSelectedLessonId??"",mr=xe?.setQuizGenSelectedLessonId??e.setQuizGenSelectedLessonId??(()=>{}),gr=xe?.quizGenTopic??e.quizGenTopic??"",xr=xe?.setQuizGenTopic??e.setQuizGenTopic??(()=>{}),Mt=xe?.isGeneratingSuggestions??e.isGeneratingSuggestions??!1,yr=xe?.setIsGeneratingSuggestions??e.setIsGeneratingSuggestions??(()=>{}),br=xe?.suggestedObjectives??e.suggestedObjectives??[],wr=xe?.setSuggestedObjectives??e.setSuggestedObjectives??(()=>{}),qn=xe?.suggestedQuestions??e.suggestedQuestions??[],Wn=xe?.setSuggestedQuestions??e.setSuggestedQuestions??(()=>{}),Sr=xe?.quizGenTimeLimit??e.quizGenTimeLimit??0,vr=xe?.setQuizGenTimeLimit??e.setQuizGenTimeLimit??(()=>{}),Gn=xe?.savingQuiz??e.savingQuiz??!1,mn=xe?.setSavingQuiz??e.setSavingQuiz??(()=>{}),gn=xe?.quizGeneratorClassId??e.quizGeneratorClassId??null,Ye=e.classBatch,Cr=Ye?.batchPicker??e.batchPicker??null,ye=Ye?.setBatchPicker??e.setBatchPicker??(()=>{}),Ot=Ye?.batchPickerLesson??e.batchPickerLesson??"",Qn=Ye?.setBatchPickerLesson??e.setBatchPickerLesson??(()=>{}),Jn=Ye?.batchPickerDate??e.batchPickerDate??"",Le=Ye?.setBatchPickerDate??e.setBatchPickerDate??(()=>{}),ft=Ye?.batchPickerTargetClass??e.batchPickerTargetClass??"",kr=Ye?.setBatchPickerTargetClass??e.setBatchPickerTargetClass??(()=>{}),Er=Ye?.confirmBatchPicker??e.confirmBatchPicker??(()=>{}),Zn=e.studentNotificationsHook,Gt=Zn?.selectedNotificationForModal??e.selectedNotificationForModal??null,jr=Zn?.setSelectedNotificationForModal??e.setSelectedNotificationForModal??(()=>{});return o.jsxs(p.Suspense,{fallback:null,children:[o.jsx(vw,{show:s,onClose:()=>r(!1),lang:t,handleImportFile:i,importError:a,importSuccess:l,isImporting:c,downloadCSVTemplate:u}),o.jsx(Cw,{isCourseWizardOpen:nr,setIsCourseWizardOpen:sr,lang:t,wizardStep:rr,setWizardStep:fn,wizardIsSubmitting:pn,wizardCourseTitle:Vn,setWizardCourseTitle:ir,wizardCourseDescription:qt,setWizardCourseDescription:or,wizardCourseCategory:Re,setWizardCourseCategory:Un,wizardCourseTimeline:ar,setWizardCourseTimeline:Hn,wizardCourseContent:lr,setWizardCourseContent:Wt,addToast:d,generateTemplateContent:h,handleDeployWizardCourse:cr}),o.jsx(kw,{isImportLessonsOpen:m,setIsImportLessonsOpen:f,lang:t,importStatus:g,setIsDraggingImport:y,handleCSVFileChange:k,downloadCsvTemplate:S,isDraggingImport:I,previewImportData:C,setPreviewImportData:T,setImportStatus:_,importProgress:E,importProgressTotal:R,importErrorMsg:B,setImportErrorMsg:F,handleCSVImportSubmit:M}),o.jsx(Ew,{isQuizGeneratorOpen:ur,setIsQuizGeneratorOpen:dr,lessons:v,quizGenMode:hr,setQuizGenMode:fr,quizGenSelectedLessonId:pr,setQuizGenSelectedLessonId:mr,quizGenTopic:gr,setQuizGenTopic:xr,isGeneratingSuggestions:Mt,setIsGeneratingSuggestions:yr,suggestedObjectives:br,setSuggestedObjectives:wr,suggestedQuestions:qn,setSuggestedQuestions:Wn,quizGenTimeLimit:Sr,setQuizGenTimeLimit:vr,savingQuiz:Gn,setSavingQuiz:mn,quizGeneratorClassId:gn,fetchClassDashboard:z}),o.jsx(jw,{isLessonPreviewVisible:L,setIsLessonPreviewVisible:P,lessons:v,selectedLesson:j,previewFullscreenPanel:A,setPreviewFullscreenPanel:U,previewLessonTab:N,setPreviewLessonTab:O,activeRole:x,elements:oe,activeSegmentId:pe,setActiveSegmentId:b,fetchElements:J,currentVfsParent:D,setCurrentVfsParent:G,vfsNodes:re,previewSelectedCourseware:se,setPreviewSelectedCourseware:we}),o.jsx(Nw,{showProcessLogs:me,setShowProcessLogs:le,processLogsContent:Ve,t:n}),o.jsx(Tw,{isOpen:St,onClose:()=>Ut(!1),vfsNodes:re,currentVfsParent:D,setCurrentVfsParent:G,cloudDrivePreviewNode:vt,setCloudDrivePreviewNode:Ct}),o.jsx(Pw,{isSystemResourceLibraryOpen:Rt,setIsSystemResourceLibraryOpen:Y,lang:t,systemResourceTab:te,setSystemResourceTab:ae,selectedLibraryResourceId:Ne,setSelectedLibraryResourceId:Ue,vfsNodes:re,currentVfsParent:D,setCurrentVfsParent:G,cloudDrivePreviewNode:vt,setCloudDrivePreviewNode:Ct,loadingLibraryResources:He,libraryResources:dt,fetchLibraryResources:Te}),o.jsx(Iw,{batchPicker:Cr,setBatchPicker:ye,batchPickerLesson:Ot,setBatchPickerLesson:Qn,batchPickerDate:Jn,setBatchPickerDate:Le,batchPickerTargetClass:ft,setBatchPickerTargetClass:kr,lessons:v,classes:$,expandedClassId:q,confirmBatchPicker:Er,lang:t}),o.jsx(Aw,{isExportWeightModalOpen:K,setIsExportWeightModalOpen:Z,lang:t,quizzesWeight:X,setQuizzesWeight:Pe,assignmentsWeight:Ze,setAssignmentsWeight:Fe,handleQuizzesWeightChange:st,handleAssignmentsWeightChange:ht,customCategoryOverrides:ge,setCustomCategoryOverrides:rt,classDashboardMap:_e,exportClassId:Ws,exportClassName:Bn,csvPreviewData:Gs,handleExportGrades:kt}),o.jsx(zw,{notification:Gt,onClose:()=>jr(null),lang:t,onOpenWorkspace:pt=>{Ht(pt),hn("assignment"),Qs({}),Js("quiz")}}),o.jsx(_w,{isOpen:Zs,onClose:()=>Ys(!1),lang:t,onSeedSuccess:Ks,onJumpTab:pt=>Xs(pt)}),er&&o.jsx(Lw,{onClose:()=>tr(!1),lang:t})]})}const Mw=["whiteboard.","courseware.","quiz.","rollcall."];class Ow{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&&Mw.some(s=>t.type.startsWith(s))&&this.socketBridge(t)}}const eu=new Ow,Cl=new Map;async function Dw(e){const t=Cl.get(e);if(t)return t;try{const n=await fetch(`/api/courseware/attempts/${encodeURIComponent(e)}/adopt`,{method:"POST",headers:{"Content-Type":"application/json"},body:"{}"});if(!n.ok)return n.status!==401&&console.warn(`[LMS Bridge] Attempt adopt failed: HTTP ${n.status}`),e;const s=await n.json();return typeof s?.attemptId=="string"&&s.attemptId?(Cl.set(e,s.attemptId),s.attemptId):e}catch(n){return console.warn("[LMS Bridge] Attempt adopt request failed:",n),e}}async function tu(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 l=Array.from(document.querySelectorAll("iframe")).find(c=>c.contentWindow===e.source);if(l&&l.contentWindow){const c=l.contentWindow;c.__LMS_STUDENT__?.attempt_id&&(n=c.__LMS_STUDENT__.attempt_id)}}catch{}if(!n||typeof n!="string")return;if(n=await Dw(n),s==="LMS_CONFIG"){as("courseware.config_reported",n,t.config??r);return}if(s==="LMS_GET_PROGRESS"){const l=t.requestId,c=e.source;if(l&&c&&typeof c.postMessage=="function"){if(typeof document<"u"&&!Array.from(document.querySelectorAll("iframe")).some(f=>f.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:l,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),a=s==="LMS_SAVE_PROGRESS"||s==="saveProgress";if(i){as("courseware.submitted",n,r);try{const l=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:"completed",extra:r})});if(!l.ok){const c=await l.text().catch(()=>"");console.error(`[LMS Bridge] Backend rejected attempt submission: HTTP ${l.status}`,c)}}catch(l){console.error("[LMS Bridge] Failed to submit attempt data to backend:",l)}}else if(a){as("courseware.progress_saved",n,r);try{const l=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})});if(!l.ok){const c=await l.text().catch(()=>"");console.error(`[LMS Bridge] Backend rejected progress save: HTTP ${l.status}`,c)}}catch(l){console.error("[LMS Bridge] Failed to save progress to backend:",l)}}else{as("courseware.event_logged",n,r);try{const l=await fetch(`/api/courseware/attempts/${encodeURIComponent(n)}/log`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({eventType:s||"log",payload:r})});if(!l.ok){const c=await l.text().catch(()=>"");console.error(`[LMS Bridge] Backend rejected event log: HTTP ${l.status}`,c)}}catch(l){console.error("[LMS Bridge] Failed to log event to backend:",l)}}}function as(e,t,n){eu.publish({id:Kl(),type:e,source:"courseware-bridge",payload:{attemptId:t,data:n},timestamp:Date.now(),correlationId:t});try{const s=n??{};je(async()=>{const{whiteboardEventSlot:r}=await Promise.resolve().then(()=>US);return{whiteboardEventSlot:r}},void 0).then(({whiteboardEventSlot:r})=>{r.ingest({source:"iframe.bridge",type:e,attemptId:t,coursewareUuid:typeof s.courseware_uuid=="string"?s.courseware_uuid:void 0,payload:{...s,attemptId:t},raw:n})})}catch{}}function Fw(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 nu(e){p.useEffect(()=>{if(!e)return;const t=n=>{tu(n)};return window.addEventListener("message",t),()=>{window.removeEventListener("message",t)}},[e])}function su(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{}}function ru(e){if(!(typeof document>"u"))try{const t=Math.min(140,Math.max(85,Math.round(e)));document.querySelectorAll("iframe").forEach(s=>{try{s.contentWindow?.postMessage({type:"LMS_HOST_COMMAND",event:"font-scale:changed",payload:{scale:t,fontScale:(t/100).toFixed(2)}},"*"),s.contentWindow?.postMessage({type:"LMS_FONT_SCALE_CHANGED",scale:t,fontScale:(t/100).toFixed(2)},"*")}catch{}})}catch{}}const iu=Object.freeze(Object.defineProperty({__proto__:null,broadcastFontScaleToIframes:ru,broadcastThemeToIframes:su,processLmsMessage:tu,sendCommandToCourseware:Fw,useLmsBridge:nu},Symbol.toStringTag,{value:"Module"}));function $w(e){const{session:t,showProcessLogs:n,activeStudentId:s,currentVfsParent:r,selectedLesson:i,selectedAssignment:a,expandedClassId:l,fetchLessons:c,fetchPlugins:u,fetchRegisteredCommands:d,fetchEvents:h,fetchApprovals:m,fetchProcesses:f,fetchClasses:g,fetchTodaySchedules:y,fetchStudents:k,fetchLabs:S,fetchVfs:I,fetchProcessLogs:C,fetchClassStudents:T,fetchElements:_}=e,E=p.useRef(r),R=p.useRef(i),B=p.useRef(a),F=p.useRef(l);p.useEffect(()=>{E.current=r},[r]),p.useEffect(()=>{R.current=i},[i]),p.useEffect(()=>{B.current=a},[a]),p.useEffect(()=>{F.current=l},[l]),p.useEffect(()=>{if(!t)return;const M=t.role==="student",v=t.role==="teacher",z=v&&(t.subRole==="administrator"||t.username==="admin"||t.userId==="usr_admin");c(),u(),d(),y().catch(()=>{}),z&&(h(),m(),f()),v?(g(),k(),S(),I(E.current)):M&&E.current&&I(E.current);let L=!1;const P=setInterval(async()=>{if(!L){L=!0;try{if(z&&(await h(),await m(),await f(),n&&await C(n)),await c(),await d(),await y().catch(()=>{}),v&&(await g(),await k(),await S(),await I(E.current),F.current&&await T(F.current)),R.current&&await _(R.current),B.current){const j=s||B.current.student_id;await _(`assignment-${B.current.id}-student-${j}`)}}finally{L=!1}}},2e3);return()=>clearInterval(P)},[t,n,s]),p.useEffect(()=>{t&&(t.role==="teacher"||r)&&I(r)},[r,t]),p.useEffect(()=>{i&&_(i)},[i])}function Bw(e){const{lang:t,t:n,selectedLesson:s,effectiveAgentProviderId:r,expandedClassId:i,fetchLessons:a,fetchClasses:l,fetchStudents:c,fetchClassStudents:u,fetchClassProgress:d,fetchClassDashboard:h,fetchElements:m}=e,[f,g]=p.useState([{role:"agent",content:n.agentIntro||""}]),[y,k]=p.useState(""),[S,I]=p.useState(!1),[C,T]=p.useState([]);p.useEffect(()=>{f.length===1&&f[0].role==="agent"&&g([{role:"agent",content:n.agentIntro}])},[t,n.agentIntro]);const _=p.useCallback(async M=>{try{const v=await fetch(`/api/agent/conversations?lessonId=${encodeURIComponent(M||"")}`);if(!v.ok)return;const z=await v.json(),L=Array.isArray(z.messages)?z.messages:[];L.length>0?g(L.map(P=>({role:P.role==="assistant"?"agent":"user",content:P.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(()=>{_(s)},[s,_]),{chatLog:f,setChatLog:g,input:y,setInput:k,loading:S,setLoading:I,chatAttachments:C,setChatAttachments:T,handleChatFileChange:M=>{M.target.files&&Array.from(M.target.files).forEach(v=>{const z=new FileReader;z.onload=L=>{L.target?.result&&T(P=>[...P,{name:v.name,content:L.target.result}])},v.name.endsWith(".zip")?z.readAsDataURL(v):z.readAsText(v)})},handleChatDrop:M=>{M.preventDefault(),M.dataTransfer.files&&Array.from(M.dataTransfer.files).forEach(v=>{const z=new FileReader;z.onload=L=>{L.target?.result&&T(P=>[...P,{name:v.name,content:L.target.result}])},v.name.endsWith(".zip")?z.readAsDataURL(v):z.readAsText(v)})},handleSend:async M=>{if(M.preventDefault(),!y.trim()||S)return;const v=[...C];let z=y;v.length>0&&(z+=`
133
- (📁 ${t==="zh"?"附件":"Attachments"}: ${v.map(L=>L.name).join(", ")})`),g(L=>[...L,{role:"user",content:z}]),k(""),T([]),I(!0);try{const L=await fetch("/api/agent/chat",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({message:y,lang:t,currentLessonId:s,attachments:v,providerId:r||null})}),P=await L.json();let j="";!L.ok||P.success===!1?j=`⚠️ ${P.message||P.error||(t==="zh"?"未知系统错误":"Unknown System Error")}`:(j=P.agentText||"",P.toolResults&&P.toolResults.length>0&&(j+=`
134
-
135
- ${n.executedCommands}`+P.toolResults.map(A=>A.callName).join(", "))),g(A=>[...A,{role:"agent",content:j}]),await a(),await l(),await c(),i&&(await u(i),await d(i),await h(i)),s&&await m(s)}catch{g(L=>[...L,{role:"agent",content:n.simulationError}])}finally{I(!1)}},handleClearAgentMemory:E,restoreAgentMemory:_}}const ut=Object.create(null);ut.open="0";ut.close="1";ut.ping="2";ut.pong="3";ut.message="4";ut.upgrade="5";ut.noop="6";const ys=Object.create(null);Object.keys(ut).forEach(e=>{ys[ut[e]]=e});const Oi={type:"error",data:"parser error"},ou=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",au=typeof ArrayBuffer=="function",lu=e=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,xo=({type:e,data:t},n,s)=>ou&&t instanceof Blob?n?s(t):kl(t,s):au&&(t instanceof ArrayBuffer||lu(t))?n?s(t):kl(new Blob([t]),s):s(ut[e]+(t||"")),kl=(e,t)=>{const n=new FileReader;return n.onload=function(){const s=n.result.split(",")[1];t("b"+(s||""))},n.readAsDataURL(e)};function El(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}let fi;function Vw(e,t){if(ou&&e.data instanceof Blob)return e.data.arrayBuffer().then(El).then(t);if(au&&(e.data instanceof ArrayBuffer||lu(e.data)))return t(El(e.data));xo(e,!1,n=>{fi||(fi=new TextEncoder),t(fi.encode(n))})}const jl="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Nn=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let e=0;e<jl.length;e++)Nn[jl.charCodeAt(e)]=e;const Uw=e=>{let t=e.length*.75,n=e.length,s,r=0,i,a,l,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=Nn[e.charCodeAt(s)],a=Nn[e.charCodeAt(s+1)],l=Nn[e.charCodeAt(s+2)],c=Nn[e.charCodeAt(s+3)],d[r++]=i<<2|a>>4,d[r++]=(a&15)<<4|l>>2,d[r++]=(l&3)<<6|c&63;return u},Hw=typeof ArrayBuffer=="function",yo=(e,t)=>{if(typeof e!="string")return{type:"message",data:cu(e,t)};const n=e.charAt(0);return n==="b"?{type:"message",data:qw(e.substring(1),t)}:ys[n]?e.length>1?{type:ys[n],data:e.substring(1)}:{type:ys[n]}:Oi},qw=(e,t)=>{if(Hw){const n=Uw(e);return cu(n,t)}else return{base64:!0,data:e}},cu=(e,t)=>{switch(t){case"blob":return e instanceof Blob?e:new Blob([e]);case"arraybuffer":default:return e instanceof ArrayBuffer?e:e.buffer}},uu="",Ww=(e,t)=>{const n=e.length,s=new Array(n);let r=0;e.forEach((i,a)=>{xo(i,!1,l=>{s[a]=l,++r===n&&t(s.join(uu))})})},Gw=(e,t)=>{const n=e.split(uu),s=[];for(let r=0;r<n.length;r++){const i=yo(n[r],t);if(s.push(i),i.type==="error")break}return s};function Qw(){return new TransformStream({transform(e,t){Vw(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 pi;function ls(e){return e.reduce((t,n)=>t+n.length,0)}function cs(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 Jw(e,t){pi||(pi=new TextDecoder);const n=[];let s=0,r=-1,i=!1;return new TransformStream({transform(a,l){for(n.push(a);;){if(s===0){if(ls(n)<1)break;const c=cs(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(ls(n)<2)break;const c=cs(n,2);r=new DataView(c.buffer,c.byteOffset,c.length).getUint16(0),s=3}else if(s===2){if(ls(n)<8)break;const c=cs(n,8),u=new DataView(c.buffer,c.byteOffset,c.length),d=u.getUint32(0);if(d>Math.pow(2,21)-1){l.enqueue(Oi);break}r=d*Math.pow(2,32)+u.getUint32(4),s=3}else{if(ls(n)<r)break;const c=cs(n,r);l.enqueue(yo(i?c:pi.decode(c),t)),s=0}if(r===0||r>e){l.enqueue(Oi);break}}}})}const du=4;function Ce(e){if(e)return Zw(e)}function Zw(e){for(var t in Ce.prototype)e[t]=Ce.prototype[t];return e}Ce.prototype.on=Ce.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(t),this};Ce.prototype.once=function(e,t){function n(){this.off(e,n),t.apply(this,arguments)}return n.fn=t,this.on(e,n),this};Ce.prototype.off=Ce.prototype.removeListener=Ce.prototype.removeAllListeners=Ce.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};Ce.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};Ce.prototype.emitReserved=Ce.prototype.emit;Ce.prototype.listeners=function(e){return this._callbacks=this._callbacks||{},this._callbacks["$"+e]||[]};Ce.prototype.hasListeners=function(e){return!!this.listeners(e).length};const Hs=typeof Promise=="function"&&typeof Promise.resolve=="function"?t=>Promise.resolve().then(t):(t,n)=>n(t,0),Qe=typeof self<"u"?self:typeof window<"u"?window:Function("return this")(),Yw="arraybuffer";function hu(e,...t){return t.reduce((n,s)=>(e.hasOwnProperty(s)&&(n[s]=e[s]),n),{})}const Kw=Qe.setTimeout,Xw=Qe.clearTimeout;function qs(e,t){t.useNativeTimers?(e.setTimeoutFn=Kw.bind(Qe),e.clearTimeoutFn=Xw.bind(Qe)):(e.setTimeoutFn=Qe.setTimeout.bind(Qe),e.clearTimeoutFn=Qe.clearTimeout.bind(Qe))}const eS=1.33;function tS(e){return typeof e=="string"?nS(e):Math.ceil((e.byteLength||e.size)*eS)}function nS(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 fu(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}function sS(e){let t="";for(let n in e)e.hasOwnProperty(n)&&(t.length&&(t+="&"),t+=encodeURIComponent(n)+"="+encodeURIComponent(e[n]));return t}function rS(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 iS extends Error{constructor(t,n,s){super(t),this.description=n,this.context=s,this.type="TransportError"}}class bo extends Ce{constructor(t){super(),this.writable=!1,qs(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 iS(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=yo(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=sS(t);return n.length?"?"+n:""}}class oS extends bo{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)};Gw(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,Ww(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]=fu()),!this.supportsBinary&&!n.sid&&(n.b64=1),this.createUri(t,n)}}let pu=!1;try{pu=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}const aS=pu;function lS(){}class cS extends oS{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}}let ln=class bs extends Ce{constructor(t,n,s){super(),this.createRequest=t,qs(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=hu(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=bs.requestsCount++,bs.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=lS,t)try{this._xhr.abort()}catch{}typeof document<"u"&&delete bs.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()}};ln.requestsCount=0;ln.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",Nl);else if(typeof addEventListener=="function"){const e="onpagehide"in Qe?"pagehide":"unload";addEventListener(e,Nl,!1)}}function Nl(){for(let e in ln.requests)ln.requests.hasOwnProperty(e)&&ln.requests[e].abort()}const uS=(function(){const e=mu({xdomain:!1});return e&&e.responseType!==null})();class dS extends cS{constructor(t){super(t);const n=t&&t.forceBase64;this.supportsBinary=uS&&!n}request(t={}){return Object.assign(t,{xd:this.xd},this.opts),new ln(mu,this.uri(),t)}}function mu(e){const t=e.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!t||aS))return new XMLHttpRequest}catch{}if(!t)try{return new Qe[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}const gu=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative";class hS extends bo{get name(){return"websocket"}doOpen(){const t=this.uri(),n=this.opts.protocols,s=gu?{}:hu(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;xo(s,this.supportsBinary,i=>{try{this.doWrite(s,i)}catch{}r&&Hs(()=>{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]=fu()),this.supportsBinary||(n.b64=1),this.createUri(t,n)}}const mi=Qe.WebSocket||Qe.MozWebSocket;class fS extends hS{createSocket(t,n,s){return gu?new mi(t,n,s):n?new mi(t,n):new mi(t)}doWrite(t,n){this.ws.send(n)}}class pS extends bo{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=Jw(Number.MAX_SAFE_INTEGER,this.socket.binaryType),s=t.readable.pipeThrough(n).getReader(),r=Qw();r.readable.pipeTo(t.writable),this._writer=r.writable.getWriter();const i=()=>{s.read().then(({done:l,value:c})=>{l||(this.onPacket(c),i())}).catch(l=>{})};i();const a={type:"open"};this.query.sid&&(a.data=`{"sid":"${this.query.sid}"}`),this._writer.write(a).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&&Hs(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var t;(t=this._transport)===null||t===void 0||t.close()}}const mS={websocket:fS,webtransport:pS,polling:dS},gS=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,xS=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function Di(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=gS.exec(e||""),i={},a=14;for(;a--;)i[xS[a]]=r[a]||"";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=yS(i,i.path),i.queryKey=bS(i,i.query),i}function yS(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 bS(e,t){const n={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(s,r,i){r&&(n[r]=i)}),n}const Fi=typeof addEventListener=="function"&&typeof removeEventListener=="function",ws=[];Fi&&addEventListener("offline",()=>{ws.forEach(e=>e())},!1);class zt extends Ce{constructor(t,n){if(super(),this.binaryType=Yw,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=Di(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=Di(n.host).host);qs(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=rS(this.opts.query)),Fi&&(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"})},ws.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(t){const n=Object.assign({},this.opts.query);n.EIO=du,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&&zt.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",zt.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+=tS(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,Hs(()=>{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(zt.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(),Fi&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const s=ws.indexOf(this._offlineEventListener);s!==-1&&ws.splice(s,1)}this.readyState="closed",this.id=null,this.emitReserved("close",t,n),this.writeBuffer=[],this._prevBufferLen=0}}}zt.protocol=du;class wS extends zt{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;zt.priorWebsocketSuccess=!1;const r=()=>{s||(n.send([{type:"ping",data:"probe"}]),n.once("packet",h=>{if(!s)if(h.type==="pong"&&h.data==="probe"){if(this.upgrading=!0,this.emitReserved("upgrading",n),!n)return;zt.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 a=h=>{const m=new Error("probe error: "+h);m.transport=n.name,i(),this.emitReserved("upgradeError",m)};function l(){a("transport closed")}function c(){a("socket closed")}function u(h){n&&h.name!==n.name&&i()}const d=()=>{n.removeListener("open",r),n.removeListener("error",a),n.removeListener("close",l),this.off("close",c),this.off("upgrading",u)};n.once("open",r),n.once("error",a),n.once("close",l),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 SS=class extends wS{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=>mS[r]).filter(r=>!!r)),super(t,s)}};function vS(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=Di(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 CS=typeof ArrayBuffer=="function",kS=e=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer,xu=Object.prototype.toString,ES=typeof Blob=="function"||typeof Blob<"u"&&xu.call(Blob)==="[object BlobConstructor]",jS=typeof File=="function"||typeof File<"u"&&xu.call(File)==="[object FileConstructor]";function wo(e){return CS&&(e instanceof ArrayBuffer||kS(e))||ES&&e instanceof Blob||jS&&e instanceof File}function Ss(e,t){if(!e||typeof e!="object")return!1;if(Array.isArray(e)){for(let n=0,s=e.length;n<s;n++)if(Ss(e[n]))return!0;return!1}if(wo(e))return!0;if(e.toJSON&&typeof e.toJSON=="function"&&arguments.length===1)return Ss(e.toJSON(),!0);for(const n in e)if(Object.prototype.hasOwnProperty.call(e,n)&&Ss(e[n]))return!0;return!1}function NS(e){const t=[],n=e.data,s=e;return s.data=vs(n,t),s.attachments=t.length,{packet:s,buffers:t}}function vs(e,t,n){if(!e)return e;if(wo(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]=vs(e[r],t);return s}else if(typeof e=="object"&&!(e instanceof Date)){if(e.toJSON&&typeof e.toJSON=="function"&&!n)return vs(e.toJSON(),t,!0);const s={};for(const r in e)Object.prototype.hasOwnProperty.call(e,r)&&(s[r]=vs(e[r],t));return s}return e}function TS(e,t){return e.data=$i(e.data,t),delete e.attachments,e}function $i(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]=$i(e[n],t);else if(typeof e=="object")for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&(e[n]=$i(e[n],t));return e}const PS=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];var ie;(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"})(ie||(ie={}));class IS{constructor(t){this.replacer=t}encode(t){return(t.type===ie.EVENT||t.type===ie.ACK)&&Ss(t)?this.encodeAsBinary({type:t.type===ie.EVENT?ie.BINARY_EVENT:ie.BINARY_ACK,nsp:t.nsp,data:t.data,id:t.id}):[this.encodeAsString(t)]}encodeAsString(t){let n=""+t.type;return(t.type===ie.BINARY_EVENT||t.type===ie.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=NS(t),s=this.encodeAsString(n.packet),r=n.buffers;return r.unshift(s),r}}class So extends Ce{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===ie.BINARY_EVENT;s||n.type===ie.BINARY_ACK?(n.type=s?ie.EVENT:ie.ACK,this.reconstructor=new AS(n)):super.emitReserved("decoded",n)}else if(wo(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(ie[s.type]===void 0)throw new Error("unknown packet type "+s.type);if(s.type===ie.BINARY_EVENT||s.type===ie.BINARY_ACK){const i=n+1;for(;t.charAt(++n)!=="-"&&n!=t.length;);const a=t.substring(i,n);if(a!=Number(a)||t.charAt(n)!=="-")throw new Error("Illegal attachments");const l=Number(a);if(!zS(l)||l<1)throw new Error("Illegal attachments");if(l>this.opts.maxAttachments)throw new Error("too many attachments");s.attachments=l}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 a=t.charAt(n);if(a==null||Number(a)!=a){--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(So.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 ie.CONNECT:return Tl(n);case ie.DISCONNECT:return n===void 0;case ie.CONNECT_ERROR:return typeof n=="string"||Tl(n);case ie.EVENT:case ie.BINARY_EVENT:return Array.isArray(n)&&(typeof n[0]=="number"||typeof n[0]=="string"&&PS.indexOf(n[0])===-1);case ie.ACK:case ie.BINARY_ACK:return Array.isArray(n)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class AS{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=TS(this.reconPack,this.buffers);return this.finishedReconstruction(),n}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}const zS=Number.isInteger||function(e){return typeof e=="number"&&isFinite(e)&&Math.floor(e)===e};function Tl(e){return Object.prototype.toString.call(e)==="[object Object]"}const _S=Object.freeze(Object.defineProperty({__proto__:null,Decoder:So,Encoder:IS,get PacketType(){return ie}},Symbol.toStringTag,{value:"Module"}));function Xe(e,t,n){return e.on(t,n),function(){e.off(t,n)}}const LS=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class yu extends Ce{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=[Xe(t,"open",this.onopen.bind(this)),Xe(t,"packet",this.onpacket.bind(this)),Xe(t,"error",this.onerror.bind(this)),Xe(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(LS.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 a={type:ie.EVENT,data:n};if(a.options={},a.options.compress=this.flags.compress!==!1,typeof n[n.length-1]=="function"){const d=this.ids++,h=n.pop();this._registerAckCallback(d,h),a.id=d}const l=(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&&!l||(c?(this.notifyOutgoingListeners(a),this.packet(a)):this.sendBuffer.push(a)),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 l=0;l<this.sendBuffer.length;l++)this.sendBuffer[l].id===t&&this.sendBuffer.splice(l,1);n.call(this,new Error("operation has timed out"))},r),a=(...l)=>{this.io.clearTimeoutFn(i),n.apply(this,l)};a.withError=!0,this.acks[t]=a}emitWithAck(t,...n){return new Promise((s,r)=>{const i=(a,l)=>a?r(a):s(l);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:ie.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 ie.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 ie.EVENT:case ie.BINARY_EVENT:this.onevent(t);break;case ie.ACK:case ie.BINARY_ACK:this.onack(t);break;case ie.DISCONNECT:this.ondisconnect();break;case ie.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:ie.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:ie.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 dn(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}dn.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};dn.prototype.reset=function(){this.attempts=0};dn.prototype.setMin=function(e){this.ms=e};dn.prototype.setMax=function(e){this.max=e};dn.prototype.setJitter=function(e){this.jitter=e};class Bi extends Ce{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,qs(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 dn({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||_S;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 SS(this.uri,this.opts);const n=this.engine,s=this;this._readyState="opening",this.skipReconnect=!1;const r=Xe(n,"open",function(){s.onopen(),t&&t()}),i=l=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",l),t?t(l):this.maybeReconnectOnOpen()},a=Xe(n,"error",i);if(this._timeout!==!1){const l=this._timeout,c=this.setTimeoutFn(()=>{r(),i(new Error("timeout")),n.close()},l);this.opts.autoUnref&&c.unref(),this.subs.push(()=>{this.clearTimeoutFn(c)})}return this.subs.push(r),this.subs.push(a),this}connect(t){return this.open(t)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const t=this.engine;this.subs.push(Xe(t,"ping",this.onping.bind(this)),Xe(t,"data",this.ondata.bind(this)),Xe(t,"error",this.onerror.bind(this)),Xe(t,"close",this.onclose.bind(this)),Xe(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){Hs(()=>{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 yu(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 jn={};function Cs(e,t){typeof e=="object"&&(t=e,e=void 0),t=t||{};const n=vS(e,t.path||"/socket.io"),s=n.source,r=n.id,i=n.path,a=jn[r]&&i in jn[r].nsps,l=t.forceNew||t["force new connection"]||t.multiplex===!1||a;let c;return l?c=new Bi(s,t):(jn[r]||(jn[r]=new Bi(s,t)),c=jn[r]),n.query&&!t.query&&(t.query=n.queryKey),c.socket(n.path,t)}Object.assign(Cs,{Manager:Bi,Socket:yu,io:Cs,connect:Cs});class RS{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 Rs=null;function bu(e){Rs=e}function MS(){if(!Rs)throw new Error("Socket instance not initialized. Call setSocketInstance() first.");return Rs}function OS(){return Rs}class DS{constructor(t){this.socket=t,bu(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 FS{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),a=document.createElement("a");a.href=i,a.download=n,document.body.appendChild(a),a.click(),document.body.removeChild(a),URL.revokeObjectURL(i)}}class $S{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)}}const wu=200;function BS(e){return{id:e.id,type:e.type,source:`whiteboard.slot.${e.source}`,payload:{lessonId:e.lessonId,elementId:e.elementId,coursewareUuid:e.coursewareUuid,attemptId:e.attemptId,studentId:e.studentId,studentName:e.studentName,...e.payload,__raw:e.raw},timestamp:e.timestamp,correlationId:e.lessonId}}class Su{constructor(t={}){this.buffer=[],this.subscriptions=[],this.byType=new Map,this.capacity=t.capacity??wu,this.persist=t.persist??!1}ingest(t){const n={id:Kl(),timestamp:Date.now(),...t};this.buffer.push(n),this.buffer.length>this.capacity&&this.buffer.shift(),this.dispatch(n);try{const s=BS(n);eu.publish(s)}catch(s){typeof console<"u"&&console.warn("[WhiteboardEventSlot] frontendEventBus publish failed:",s)}return this.persist&&typeof indexedDB<"u"&&this.persistEvent(n),n}emit(t,n,s={}){return this.ingest({...s,type:t,source:s.source??"manual",payload:n})}subscribe(t,n,s={}){const r={filter:t,handler:n};if(this.subscriptions.push(r),t.types)for(const i of t.types)this.byType.has(i)||this.byType.set(i,new Set),this.byType.get(i).add(r);if(s.replay&&s.replay>0){const i=this.query(t,{limit:s.replay});queueMicrotask(()=>{for(const a of i)try{n(a)}catch(l){console.error("[WhiteboardEventSlot] replay handler error:",l)}})}return()=>{const i=this.subscriptions.indexOf(r);if(i>=0&&this.subscriptions.splice(i,1),t.types)for(const a of t.types)this.byType.get(a)?.delete(r)}}query(t={},n={}){const s=n.limit??this.capacity,r=n.since??0,i=[];for(let a=this.buffer.length-1;a>=0;a--){const l=this.buffer[a];if(l.timestamp<r||Pl(l,t)&&(i.push(l),i.length>=s))break}return i}stats(){const t={},n={};for(const s of this.buffer)t[s.type]=(t[s.type]??0)+1,n[s.source]=(n[s.source]??0)+1;return{total:this.buffer.length,byType:t,bySource:n}}clear(){this.buffer=[]}size(){return this.buffer.length}dispatch(t){const n=t.type?this.byType.get(t.type):void 0,s=n?Array.from(n):this.subscriptions;for(const r of s)if(Pl(t,r.filter))try{r.handler(t)}catch(i){console.error("[WhiteboardEventSlot] handler error:",i)}}async persistEvent(t){if(!(typeof indexedDB>"u"))try{const n=await VS(),s=n.transaction("events","readwrite");s.objectStore("events").put(t),await new Promise((i,a)=>{s.oncomplete=()=>i(),s.onerror=()=>a(s.error)}),n.close()}catch{}}}function Pl(e,t){return!(t.types&&t.types.length>0&&!t.types.includes(e.type)||t.sources&&t.sources.length>0&&!t.sources.includes(e.source)||t.lessonId&&e.lessonId!==t.lessonId||t.elementId&&e.elementId!==t.elementId||t.coursewareUuid&&e.coursewareUuid!==t.coursewareUuid||t.studentId&&e.studentId!==t.studentId||t.predicate&&!t.predicate(e))}let us=null;function VS(){return us||(us=new Promise((e,t)=>{const n=indexedDB.open("whiteboard-event-slot",1);n.onupgradeneeded=()=>{const s=n.result;s.objectStoreNames.contains("events")||s.createObjectStore("events",{keyPath:"id"})},n.onsuccess=()=>e(n.result),n.onerror=()=>t(n.error)}),us)}const At=new Su({capacity:wu,persist:!1}),US=Object.freeze(Object.defineProperty({__proto__:null,WhiteboardEventSlot:Su,whiteboardEventSlot:At},Symbol.toStringTag,{value:"Module"})),Vi=new Set;function HS(e){return Vi.add(e),()=>{Vi.delete(e)}}const Il=30,Al=(e,t)=>Math.min(e,t.length);function vo(e){const t=new Date(e.timestamp).toLocaleString(),n=[`### [${e.type.toUpperCase()}] ${e.title}`,`- **发生时间**: ${t}`,`- **页面路径**: ${e.url||"N/A"}`,`- **错误摘要**: ${e.message}`];return e.endpoint&&n.push(`- **请求接口**: \`${e.endpoint}\` (HTTP ${e.status||"Unknown"})`),e.componentStack&&n.push("- **组件堆栈**:","```",e.componentStack.trim(),"```"),e.stack&&n.push("- **调用栈 (Stack Trace)**:","```",e.stack.trim(),"```"),n.join(`
136
- `)}function vu(e){const t=new Date(e.timestamp).toLocaleString(),n=[`### [学生端异常] ${e.studentName||e.studentId} - ${e.title}`,`- **学生信息**: ${e.studentName||"未知"} (\`${e.studentId}\`)`,`- **关联课节**: ${e.lessonId||"未指定"}`,`- **关联班级**: ${e.classId||"未指定"}`,`- **发生时间**: ${t}`,`- **页面路径**: ${e.url||"N/A"}`,`- **错误摘要**: ${e.message}`];return e.endpoint&&n.push(`- **请求接口**: \`${e.endpoint}\` (HTTP ${e.status||"Unknown"})`),e.componentStack&&n.push("- **组件堆栈**:","```",e.componentStack.trim(),"```"),e.stack&&n.push("- **调用栈 (Stack Trace)**:","```",e.stack.trim(),"```"),n.join(`
137
- `)}function qS(e,t=[]){const n=new Date().toLocaleString(),s=typeof window<"u"?window.location.href:"Unknown",r=typeof navigator<"u"?navigator.userAgent:"Unknown";if(e.length===0&&t.length===0)return`# 🛠️ OpenLearn 系统诊断报告
138
- - 生成时间: ${n}
139
- - 暂无记录的系统异常。`;const i=e.length+t.length,a=["# 🛠️ OpenLearn 系统异常诊断报告",`- **生成时间**: ${n}`,`- **当前页面**: ${s}`,`- **异常总数**: ${i} 项`,`- **本机异常数**: ${e.length} 项`,`- **学生端异常数**: ${t.length} 项`,`- **运行环境**: ${r}`,"","---",""].join(`
140
- `),l=e.length>0?`## 💻 本机异常记录 (${e.length})
141
-
142
- `+e.map((u,d)=>`#### 错误 #${d+1} (${u.type.toUpperCase()})
143
- `+vo(u)).join(`
144
-
145
- ---
146
-
147
- `):"",c=t.length>0?`## 🎒 学生端异常记录 (${t.length})
148
-
149
- `+t.map((u,d)=>`#### 学生异常 #${d+1}
150
- `+vu(u)).join(`
151
-
152
- ---
153
-
154
- `):"";return[a,l,c].filter(Boolean).join(`
155
-
156
- ---
157
-
158
- `)}const $t=wt((e,t)=>({errors:[],studentErrors:[],activeTab:"local",isErrorCenterOpen:!1,unreadCount:0,addError:n=>{const s=Date.now(),r=n.url||(typeof window<"u"?window.location.href:""),i=n.userAgent||(typeof navigator<"u"?navigator.userAgent:""),a=t().errors.findIndex(c=>c.type===n.type&&c.message===n.message&&s-c.timestamp<2e3);if(a>=0)return t().errors[a];const l={id:`err_${s}_${Math.random().toString(36).slice(2,7)}`,timestamp:n.timestamp||s,url:r,userAgent:i,type:n.type,title:n.title,message:n.message,stack:n.stack,componentStack:n.componentStack,endpoint:n.endpoint,status:n.status};return e(c=>{const u=[l,...c.errors].slice(0,Il);return{errors:u,unreadCount:Al(c.unreadCount+1,u)}}),Vi.forEach(c=>{try{c(l)}catch(u){console.error("[ErrorStore] Error in errorListener:",u)}}),l},removeError:n=>e(s=>{const r=s.errors.filter(i=>i.id!==n);return{errors:r,unreadCount:Al(s.unreadCount,r)}}),clearErrors:()=>e({errors:[],unreadCount:0}),addStudentError:n=>{const s=Date.now(),r=n.timestamp||s;e(i=>i.studentErrors.some(u=>u.studentId===n.studentId&&u.type===n.type&&u.message===n.message&&Math.abs(r-u.timestamp)<2e3)?i:{studentErrors:[{...n,id:n.id||`st_err_${s}_${Math.random().toString(36).slice(2,7)}`,timestamp:r},...i.studentErrors].slice(0,Il)})},removeStudentError:n=>e(s=>({studentErrors:s.studentErrors.filter(r=>r.id!==n)})),clearStudentErrors:()=>e({studentErrors:[]}),setIsErrorCenterOpen:n=>e({isErrorCenterOpen:n,unreadCount:n?0:t().unreadCount}),setActiveTab:n=>e({activeTab:n}),markAllRead:()=>e({unreadCount:0})}));function it(e){return Os($t,e||(t=>t))}function WS(e){const{session:t,host:n,activeRole:s,activeStudentId:r,selectedLesson:i,activeSegmentId:a,studentViewStatus:l,lang:c,students:u,addToast:d,setOnlineStudentIds:h,setActiveStudentLessons:m,setLessons:f,setActiveSegmentId:g,setLiveClassStudentProgress:y,setLiveClassAcknowledgedMap:k,setLiveClassFeed:S,setSelectedLesson:I,setStudentViewStatus:C,studentLessonTab:T,setStudentLessonTab:_,selectedAssignment:E,setSelectedAssignment:R,setLocalProgressPercent:B,fetchStudentDashboard:F,fetchStudents:M,fetchElements:v}=e,z=p.useRef(null),L=p.useRef(s),P=p.useRef(r),j=p.useRef(c),A=p.useRef(u),U=p.useRef(d),N=p.useRef(i),O=p.useRef(null),x=p.useRef(l),oe=p.useRef(T),pe=p.useRef(null);return p.useEffect(()=>{L.current=s},[s]),p.useEffect(()=>{P.current=r},[r]),p.useEffect(()=>{j.current=c},[c]),p.useEffect(()=>{A.current=u},[u]),p.useEffect(()=>{U.current=d},[d]),p.useEffect(()=>{N.current=i},[i]),p.useEffect(()=>{x.current=l},[l]),p.useEffect(()=>{oe.current=T},[T]),p.useEffect(()=>{O.current=E},[E]),p.useEffect(()=>{if(!t)return;const b=Cs();z.current=b,bu(b),n.isInitialized()||n.initialize(new RS,new DS(b),new FS(U.current),new $S("__app__")),L.current==="student"&&P.current&&b.emit("register-student",{studentId:P.current,name:A.current.find(D=>D.id===P.current)?.name||P.current}),b.emit("join-room","whiteboard-broadcast"),b.on("presence-update",D=>{h(D.onlineStudentIds),m(D.activeStudentLessons)}),b.on("lesson-progress-mode-changed",D=>{const{lessonId:G,progressMode:re,progressConditions:se}=D;f(we=>we.map(me=>me.id===G?{...me,progress_mode:re,progress_conditions:se}:me))}),b.on("student-active-segment-changed",D=>{const{activeSegmentId:G}=D;g(G)}),b.on("student-pinged",D=>{const G=D.message||(j.current==="zh"?"⚠️ 学习进度预警:老师注意到您的进度有些落后,请抓紧时间跟上!":"⚠️ Progress Alert: The teacher noticed you are falling behind. Please keep up!");d(j.current==="zh"?"⚠️ 学习进度预警":"⚠️ Progress Warning",G,"warning")}),b.on("student-progress-updated",D=>{const{studentId:G,progressPercent:re,completed:se}=D;y(we=>{const me=we.findIndex(le=>le.student_id===G);if(me!==-1){const le=[...we];return le[me]={...le[me],progress_percent:re,completed:se?1:0},le}else return[...we,{student_id:G,progress_percent:re,completed:se?1:0}]})}),b.on("student-error-alert",D=>{if(!(!D||!D.error)&&(L.current==="teacher"||t?.role==="administrator")){$t.getState().addStudentError({...D.error,studentId:D.studentId,studentName:D.studentName||D.studentId,lessonId:D.lessonId,classId:D.classId});const G=D.studentName?`${D.studentName} (${D.studentId})`:D.studentId;d(j.current==="zh"?"学生端异常提醒":"Student Exception Alert",`${G}: ${D.error.title||D.error.message}`,"warning")}}),b.on("assignment-graded-toast",D=>{if(L.current==="student"&&P.current&&D.studentId===P.current){const G=D.assignmentTitle||D.assignmentId,re=j.current==="zh"?`您的作业"${G}"已完成评分!得分:${D.score}%。建议反馈已收到,快去查看。`:`Your assignment "${G}" was graded. Score: ${D.score}%. Tutoring feedback has been posted.`;d(j.current==="zh"?"🎓 作业已评分":"🎓 Assignment Graded",re,"success"),F(P.current)}}),b.on("student-picked",D=>{if(L.current==="student"&&P.current&&D.studentId===P.current){const G=j.current==="zh"?"闪电警报!您已被老师在课程随机提问点名中抽中!请立即集中注意力参与课堂。":"Attention alert! You have been randomly picked by the teacher! Please pay immediate attention.";d(j.current==="zh"?"⚡️ 随机点名提问":"⚡️ Classroom Pick Alert",G,"warning"),F(P.current)}S(G=>[{id:`feed-pick-${D.studentId}-${D.pickedTime||Date.now()}`,time:new Date(D.pickedTime||Date.now()).toLocaleTimeString(),type:"picked",message:j.current==="zh"?`点名互动:随机抽中学生【${D.studentName}】。`:`Classroom Pick: Randomly selected student "${D.studentName}".`},...G])}),b.on("student-acknowledged",D=>{const{studentId:G}=D;k(re=>{const se=new Map(re);return se.set(G,!0),se}),S(re=>[{id:`feed-ack-${G}-${Date.now()}`,time:new Date().toLocaleTimeString(),type:"checkin",message:j.current==="zh"?`学生已确认收到提问点名(学生 ID: ${G})。`:`Student acknowledged the classroom call (Student ID: ${G}).`},...re]),M()}),b.on("class-lock-status-changed",D=>{const{lessonId:G,locked:re}=D;L.current==="student"&&P.current?(Promise.resolve(M()).then(()=>{re&&G&&(I(G),C("lesson"),d(j.current==="zh"?"🔒 课程已被锁定":"🔒 Lesson Locked",j.current==="zh"?"老师已锁定当前授课,您将无法切换到其他页面。":"The teacher has locked the active lesson. You cannot leave this page.","info"))}),F(P.current)):M()}),b.on("whiteboard-sync",D=>{const{roomId:G,type:re}=D||{};re==="refresh"&&G&&(v(G),!N.current&&L.current==="student"&&(I(G),C("lesson")),b.emit("join-room",G))});const J=()=>{on.getState().clearRemoteFullscreen();const D=pe.current;pe.current=null,D&&(_(D.lessonTab),D.viewStatus==="assignment"&&(R(D.assignment??null),D.lessonId&&I(D.lessonId),C("assignment")))};return b.on("whiteboard-fullscreen-changed",D=>{if(L.current!=="student")return;const G=D?.lessonId,re=D?.elementId??null;if(!re){J();return}if(!G)return;const se=x.current;(se==="lesson"?N.current===G:se==="assignment")&&(on.getState().remoteFullscreenElementId||(pe.current={viewStatus:se,lessonTab:oe.current,lessonId:N.current,assignment:se==="assignment"?O.current:null}),on.getState().setRemoteFullscreenElementId(re),se==="assignment"&&R(null),I(G),v(G),C("lesson"),_("whiteboard"))}),b.on("connect",()=>{J()}),b.on("whiteboard-quiz-answered",D=>{try{if(!D)return;At.ingest({source:"widget.quiz",type:"quiz.answered",lessonId:D.lessonId,elementId:D.elementId,studentId:D.studentId,studentName:D.studentName,payload:{answer:D.answer,score:typeof D.score=="number"?D.score:void 0,isCorrect:!!D.isCorrect,correctAnswer:D.correctAnswer,question:D.question,time:D.time},raw:D})}catch(G){console.error("[useClassroomSocket] quiz.answered ingest failed",G)}}),b.on("courseware-attempt-updated",D=>{try{if(!D||typeof D.attemptId!="string")return;const G=D.type==="log"?"courseware.event_logged":D.type==="submit"?"courseware.submitted":D.type==="promote"?"courseware.finished":"courseware.event_logged";At.ingest({source:"iframe.bridge",type:G,attemptId:D.attemptId,payload:{attemptId:D.attemptId,attemptType:D.type},raw:D})}catch(G){console.error("[useClassroomSocket] courseware-attempt-updated ingest failed",G)}}),()=>{b.disconnect(),z.current=null}},[t,s,r]),p.useEffect(()=>{z.current&&s==="student"&&r&&(l==="lesson"&&i?(z.current.emit("enter-lesson",{studentId:r,lessonId:i}),fetch(`/api/students/${r}/progress`).then(b=>b.json()).then(b=>{if(Array.isArray(b)){const J=b.find(D=>D.lesson_id===i);B(J?J.progress_percent:0)}}).catch(console.error)):z.current.emit("leave-lesson",{studentId:r}))},[l,i,s,r]),p.useEffect(()=>{s==="teacher"&&i&&a&&z.current&&z.current.emit("teacher-broadcast-segment",{lessonId:i,activeSegmentId:a})},[a,i,s]),{socketRef:z}}const GS=`exports.default = {
159
- manifest: {
160
- id: "@my-scope/hello-world",
161
- name: "Hello World Plugin",
162
- version: "1.0.0",
163
- capabilitiesProposed: ["lesson:read"]
164
- },
165
- activate: async (ctx) => {
166
- ctx.log.info('Hello World plugin activated');
167
- }
168
- };`;function QS(e){const{session:t,host:n,lang:s,addToast:r,setChatLog:i,setTeacherTab:a,fetchLessons:l}=e,[c,u]=p.useState([]),[d,h]=p.useState([]),[m,f]=p.useState(!1),[g,y]=p.useState(null),[k,S]=p.useState(""),[I,C]=p.useState(""),[T,_]=p.useState(""),[E,R]=p.useState(""),[B,F]=p.useState(null),[M,v]=p.useState(!1),[z,L]=p.useState("store"),[P,j]=p.useState(GS),[A,U]=p.useState(!1),[N,O]=p.useState([]),[x,oe]=p.useState([]),[pe,b]=p.useState({}),J=p.useRef(new Set),D=p.useCallback(async()=>{try{const Y=await fetch("/api/plugins");if(Y.ok){const te=await Y.json();u(te)}}catch(Y){console.warn("Failed to fetch plugins",Y)}},[]),G=p.useCallback(async()=>{try{const Y=await fetch("/api/ai-providers");if(Y.ok){const te=await Y.json();h(te)}}catch(Y){console.warn("Failed to fetch AI Providers",Y)}},[]);p.useEffect(()=>{D(),t&&t.role!=="student"&&G()},[D,G,t?.role]);const re=p.useCallback(async()=>{try{const Y=await fetch("/api/events");Y.ok&&O(await Y.json())}catch{}},[]),se=p.useCallback(async()=>{try{const Y=await fetch("/api/approvals");Y.ok&&oe(await Y.json())}catch{}},[]);return{plugins:c,setPlugins:u,fetchPlugins:D,aiProviders:d,setAiProviders:h,fetchAIProviders:G,isAIProviderModalOpen:m,setIsAIProviderModalOpen:f,editingAIProvider:g,setEditingAIProvider:y,providerName:k,setProviderName:S,providerApiUrl:I,setProviderApiUrl:C,providerApiKey:T,setProviderApiKey:_,providerModelName:E,setProviderModelName:R,testingProviderId:B,setTestingProviderId:F,showPluginModal:M,setShowPluginModal:v,storeTab:z,setStoreTab:L,pluginCode:P,setPluginCode:j,installingPlugin:A,setInstallingPlugin:U,events:N,setEvents:O,fetchEvents:re,approvals:x,setApprovals:oe,fetchApprovals:se,scoreOverrides:pe,setScoreOverrides:b,handleSaveAIProvider:async()=>{if(!k.trim()||!I.trim()||!E.trim()){r(s==="zh"?"表单不完整":"Incomplete Form",s==="zh"?"请填写提供商名称、API 基础地址与模型标识。":"Please fill in Name, API URL, and Model Name.","warning");return}try{let Y;if(g?Y=await fetch(`/api/ai-providers/${g.id}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:k,api_url:I,api_key:T,model_name:E})}):Y=await fetch("/api/ai-providers",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:k,api_url:I,api_key:T,model_name:E})}),Y.ok)r(s==="zh"?"保存成功":"Saved Successfully",s==="zh"?`AI 提供商 [${k}] 已保存。`:`AI Provider [${k}] has been updated.`,"success"),f(!1),y(null),S(""),C(""),_(""),R(""),G();else{const te=await Y.json().catch(()=>({}));r(s==="zh"?"保存失败":"Failed to Save",te.error||(s==="zh"?"无法写入数据库":"Failed to write to database"),"warning")}}catch(Y){console.error(Y),r(s==="zh"?"保存异常":"Execution Error",Y.message||"Error occurred","warning")}},handleDeleteAIProvider:async(Y,te)=>{if(confirm(s==="zh"?`确定要删除 AI 提供商 [${te}] 吗?此操作无法撤销。`:`Are you sure you want to delete AI Provider [${te}]?`))try{(await fetch(`/api/ai-providers/${Y}`,{method:"DELETE"})).ok?(r(s==="zh"?"删除成功":"Deleted Successfully",s==="zh"?`AI 提供商 [${te}] 已经被清除。`:`AI Provider [${te}] has been removed.`,"success"),G()):r(s==="zh"?"删除失败":"Failed to Delete","Database error","warning")}catch(ae){console.error(ae),r(s==="zh"?"操作异常":"Execution Error",ae.message||"Error occurred","warning")}},handleTestAIProvider:async Y=>{F(Y.id);try{const te=await fetch("/api/ai-providers/test",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({api_url:Y.api_url,api_key:Y.api_key,model_name:Y.model_name})}),ae=await te.json();te.ok&&ae.success?r(s==="zh"?"测试通过":"Test Succeeded",s==="zh"?`成功连接至 [${Y.name}]。${ae.message}`:`Successfully connected to [${Y.name}]. ${ae.message}`,"success"):r(s==="zh"?"测试失败":"Test Failed",ae.error||"Connection error","warning")}catch(te){console.error(te),r(s==="zh"?"连接异常":"Connection Exception",te.message||"Error occurred","warning")}finally{F(null)}},handleInstallPlugin:async()=>{if(P.trim()){U(!0);try{const te=await(await fetch("/api/plugins",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sourceCode:P})})).json();te.success?(await D(),v(!1),i(ae=>[...ae,{role:"agent",content:`[System] Plugin "${te.manifest.name}" installed successfully. You can now prompt me to use it.`}])):alert("Plugin installation failed: "+te.error)}catch(Y){alert("Error: "+Y.message)}finally{U(!1)}}},handleZipPluginUpload:async(Y,te,ae)=>{U(!0);const Ne=ae?.mode==="update";try{const Ue={"Content-Type":"application/octet-stream","X-Filename":encodeURIComponent(Y.name),"X-Execution-Mode":te,"X-Install-Mode":Ne?"update":"install","X-Allow-Downgrade":ae?.allowDowngrade?"true":"false"};ae?.targetPluginId&&(Ue["X-Target-Plugin-Id"]=encodeURIComponent(ae.targetPluginId));const He=Ne&&ae?.targetPluginId?`/api/plugins/${encodeURIComponent(ae.targetPluginId)}/update-zip-raw`:"/api/plugins/upload-zip-raw",dt=await fetch(He,{method:"POST",headers:Ue,body:Y}),Te=await dt.json().catch(()=>({}));if(!dt.ok||!Te.success){const Z=Te.error||"Unknown error";throw r(s==="zh"?Ne?"更新失败":"安装失败":Ne?"Update Failed":"Installation Failed",Z,"error"),new Error(Z)}const $=Te.pluginId||Te.manifest?.pluginId||Te.manifest?.id,q=!!(Te.updated||Ne);if(!q&&$)await fetch(`/api/plugins/${encodeURIComponent($)}/toggle`,{method:"POST"}).catch(()=>{});else if(q&&Te.wasActive&&$)try{await n.deactivatePlugin($)}catch{}a("plugins"),L("store"),await D(),setTimeout(()=>{D()},1e3);const K=Te.manifest?.name||$||Y.name;if(q){const Z=Te.oldVersion||"?",X=Te.newVersion||Te.manifest?.version||"?";r(s==="zh"?"插件更新成功":"Plugin Updated",s==="zh"?`"${K}" 已从 v${Z} 更新到 v${X}(配置与数据已保留)`:`"${K}" updated v${Z} → v${X} (config & data preserved)`,"success"),i(Pe=>[...Pe,{role:"agent",content:`[System] Plugin "${K}" updated ${Z} → ${X}.`}])}else r(s==="zh"?"插件安装成功":"Plugin Installed",s==="zh"?`三方插件 "${K}" 已成功上传并以 [${te==="worker"?"Worker 隔离":"VM 嵌入"}] 模式激活运行!`:`Plugin "${K}" installed and activated in [${te}] mode!`,"success"),i(Z=>[...Z,{role:"agent",content:`[System] Plugin "${K}" installed successfully from ZIP file.`}])}catch(Ue){const He=Ue?.message?String(Ue.message):"";throw He&&He!=="Failed to fetch"&&He!=="Network error"||r(s==="zh"?"网络错误":"Network Error",He||"Network error","error"),Ue}finally{U(!1)}},handleTogglePlugin:async Y=>{if(!J.current.has(Y)){J.current.add(Y);try{const te=await fetch(`/api/plugins/${encodeURIComponent(Y)}/toggle`,{method:"POST"}),ae=await te.json().catch(()=>({}));if(te.ok)await D();else{const Ne=ae.error||"Unknown error";Ne.includes("requires human approval")||Ne.includes("queued")?(alert(s==="zh"?'该操作已加入"待审批高危操作"列表,请在右侧侧边栏中通过审批以生效。':"This action has been queued. Please approve it in the Pending Approvals list on the right side."),await se()):alert((s==="zh"?"切换插件状态失败: ":"Failed to toggle plugin: ")+Ne)}}catch(te){console.error("Failed to toggle plugin:",te),alert(s==="zh"?"网络错误,切换插件失败":"Network error, failed to toggle plugin")}finally{J.current.delete(Y)}}},handleDeletePlugin:async Y=>{if(window.confirm(s==="zh"?"确定要彻底删除该插件吗?删除后此插件相关的功能将无法使用。":"Are you sure you want to completely delete this plugin? This cannot be undone."))try{const te=await fetch(`/api/plugins/${encodeURIComponent(Y)}`,{method:"DELETE"});if(te.ok)a("plugins"),L("store"),await D(),i(ae=>[...ae,{role:"agent",content:"[System] Plugin uninstalled and deleted."}]);else{const ae=await te.json().catch(()=>({}));alert(ae.error||(s==="zh"?"删除插件失败":"Failed to delete plugin"))}}catch(te){console.error("Failed to delete plugin:",te),alert(s==="zh"?"删除插件失败":"Failed to delete plugin")}},handleApprove:async(Y,te)=>{try{const Ne=await(await fetch(`/api/approvals/${Y}/approve`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({payloadOverride:te})})).json();Ne.success?(await se(),await l(),await D()):alert("Action failed: "+Ne.error)}catch(ae){console.error(ae)}},handleReject:async Y=>{try{await fetch(`/api/approvals/${Y}/reject`,{method:"POST"}),await se(),await D()}catch(te){console.error(te)}}}}function JS(e){const{lang:t,addToast:n,fetchLessons:s,setSelectedLesson:r,setTeacherTab:i}=e,[a,l]=p.useState(!1),[c,u]=p.useState(1),[d,h]=p.useState(""),[m,f]=p.useState("Mathematics"),[g,y]=p.useState(""),[k,S]=p.useState(""),[I,C]=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"}]),[T,_]=p.useState(!1);return{isCourseWizardOpen:a,setIsCourseWizardOpen:l,wizardStep:c,setWizardStep:u,wizardCourseTitle:d,setWizardCourseTitle:h,wizardCourseCategory:m,setWizardCourseCategory:f,wizardCourseDescription:g,setWizardCourseDescription:y,wizardCourseContent:k,setWizardCourseContent:S,wizardCourseTimeline:I,setWizardCourseTimeline:C,wizardIsSubmitting:T,setWizardIsSubmitting:_,handleDeployWizardCourse:async()=>{if(!d.trim()){alert(t==="zh"?"请输入课程标题!":"Please provide a course title!");return}_(!0);try{const R=k.trim()||`Course outline for ${d} (${m})`,B=await fetch("/api/lessons",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({title:d,content:R})});if(B.ok){const M=(await B.json()).result?.lessonId;M&&await fetch(`/api/lessons/${M}/timeline`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({timeline:I})}),await s(),M&&(r(M),i("lesson_editor")),n(t==="zh"?"⭐ 课程发布成功":"⭐ Course Deployed Successfully",t==="zh"?`课程《${d}》已成功保存到核心SQLite并已自动激活!`:`Course "${d}" is now live in SQLite and auto-activated.`,"success"),l(!1),h(""),f("Mathematics"),y(""),S(""),u(1)}else n("Error","SQLite save failed","warning")}catch(R){console.error(R),n("Error","Launch Exception","warning")}finally{_(!1)}}}}function ZS(){const[e,t]=p.useState(!1),[n,s]=p.useState(null),[r,i]=p.useState("scan_lesson"),[a,l]=p.useState(""),[c,u]=p.useState(""),[d,h]=p.useState(!1),[m,f]=p.useState([]),[g,y]=p.useState([]),[k,S]=p.useState(!1),[I,C]=p.useState({}),[T,_]=p.useState(10),[E,R]=p.useState("quiz"),B=p.useRef(I);return p.useEffect(()=>{B.current=I},[I]),{isQuizGeneratorOpen:e,setIsQuizGeneratorOpen:t,quizGeneratorClassId:n,setQuizGeneratorClassId:s,quizGenMode:r,setQuizGenMode:i,quizGenSelectedLessonId:a,setQuizGenSelectedLessonId:l,quizGenTopic:c,setQuizGenTopic:u,isGeneratingSuggestions:d,setIsGeneratingSuggestions:h,suggestedObjectives:m,setSuggestedObjectives:f,suggestedQuestions:g,setSuggestedQuestions:y,savingQuiz:k,setSavingQuiz:S,quizStudentAnswers:I,setQuizStudentAnswers:C,quizGenTimeLimit:T,setQuizGenTimeLimit:_,quizStudentAnswersRef:B,subAssignmentTab:E,setSubAssignmentTab:R}}function YS(e){const{lang:t,classes:n,expandedClassId:s,fetchClasses:r,fetchClassStudents:i,handleExportAllClassesCombined:a}=e,[l,c]=p.useState(!1),[u,d]=p.useState(new Set),[h,m]=p.useState(new Set),[f,g]=p.useState(null),[y,k]=p.useState(""),[S,I]=p.useState(""),[C,T]=p.useState("");return{batchMode:l,setBatchMode:c,selectedClassIds:u,setSelectedClassIds:d,selectedStudentIds:h,setSelectedStudentIds:m,batchPicker:f,setBatchPicker:g,batchPickerLesson:y,setBatchPickerLesson:k,batchPickerDate:S,setBatchPickerDate:I,batchPickerTargetClass:C,setBatchPickerTargetClass:T,toggleClassSelection:N=>{d(O=>{const x=new Set(O);return x.has(N)?x.delete(N):x.add(N),x})},toggleSelectAllClasses:()=>{d(N=>N.size===n.length&&n.length>0?new Set:new Set(n.map(O=>O.id)))},toggleStudentSelection:N=>{m(O=>{const x=new Set(O);return x.has(N)?x.delete(N):x.add(N),x})},toggleSelectAllStudents:N=>{m(O=>O.size===N.length&&N.length>0?new Set:new Set(N.map(x=>x.id)))},handleBatchDeleteClasses:async()=>{if(u.size!==0&&confirm(t==="zh"?`确认彻底删除选中的 ${u.size} 个班级吗?该操作不可恢复。`:`Delete ${u.size} selected classes permanently?`)){for(const N of u)await fetch(`/api/classes/${N}`,{method:"DELETE"});d(new Set),await r()}},handleBatchExportClasses:async()=>{u.size!==0&&await a(n.filter(N=>u.has(N.id)))},handleBatchSetPasscode:async()=>{if(u.size===0)return;const N=window.prompt(t==="zh"?"请输入临时班级密码(留空则清除):":"Enter temporary passcode (leave empty to clear):");if(N!==null){for(const O of u)await fetch(`/api/classes/${O}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({class_passcode:N===""?null:N})});d(new Set),await r()}},handleBatchScheduleClasses:()=>{u.size!==0&&(k(""),I(new Date().toISOString().split("T")[0]),g("schedule"))},handleBatchDeleteStudents:async()=>{if(!(h.size===0||!s)&&confirm(t==="zh"?`确认彻底删除选中的 ${h.size} 名学生账号吗?将删除其全部关联数据,不可恢复。`:`Permanently delete ${h.size} selected student accounts?`)){for(const N of h)await fetch(`/api/students/${N}`,{method:"DELETE"});m(new Set),await i(s)}},handleBatchResetPassword:async()=>{if(h.size===0||!s)return;const N=window.prompt(t==="zh"?"请输入要为选中学生设置的新密码:":"Enter new password for selected students:");if(!(N===null||N.trim()==="")){for(const O of h)await fetch(`/api/students/${O}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:N})});m(new Set),await i(s)}},handleBatchTransferStudents:()=>{h.size===0||!s||(T(""),g("transfer"))},handleBatchSetLockedLesson:()=>{h.size===0||!s||(k(""),g("lockedLesson"))},confirmBatchPicker:async()=>{if(s){if(f==="schedule"){if(!y){alert(t==="zh"?"请选择课程":"Please select a lesson");return}for(const N of u)await fetch(`/api/classes/${N}/schedules`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({lessonId:y,scheduledDate:S+" 09:00:00",status:"scheduled"})});d(new Set)}else if(f==="lockedLesson"){if(!y){alert(t==="zh"?"请选择课程":"Please select a lesson");return}for(const N of h)await fetch(`/api/students/${N}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({locked_lesson_id:y})});m(new Set)}else if(f==="transfer"){if(!C||C===s){alert(t==="zh"?"请选择不同的目标班级":"Please select a different target class");return}for(const N of h)await fetch(`/api/classes/${s}/students/${N}`,{method:"DELETE"}),await fetch(`/api/classes/${C}/students`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({studentId:N})});m(new Set)}g(null),s&&await i(s)}}}}function KS(){const[e,t]=p.useState([]),[n,s]=p.useState(!1),[r,i]=p.useState({lab_id:null,seats:[]}),[a,l]=p.useState(!1),[c,u]=p.useState([]),[d,h]=p.useState({}),[m,f]=p.useState({}),[g,y]=p.useState(null),[k,S]=p.useState(""),[I,C]=p.useState(""),T=p.useCallback(async()=>{try{s(!0);const F=await fetch("/api/labs");F.ok&&t(await F.json())}catch(F){console.error(F)}finally{s(!1)}},[]),_=p.useCallback(async F=>{try{const M=await fetch(`/api/classes/${F}/seats`);if(M.ok){const v=await M.json();i(v)}}catch(M){console.error(M)}},[]),E=p.useCallback(async()=>{try{const F=new Date().toISOString().split("T")[0],M=await fetch(`/api/schedules/today?date=${F}`);if(M.ok){const v=await M.json();v.success&&v.schedules&&u(v.schedules)}}catch(F){console.warn("Failed to fetch today schedules",F)}},[]),R=p.useCallback(async F=>{try{const M=await fetch(`/api/classes/${F}/schedules`);if(M.ok){const v=await M.json();h(z=>({...z,[F]:v}))}}catch{}},[]),B=p.useCallback(async F=>{try{const M=await fetch(`/api/schedules/${F}/attendance`);if(M.ok){const v=await M.json();f(z=>({...z,[F]:v}))}}catch{}},[]);return{computerLabs:e,setComputerLabs:t,loadingLabs:n,setLoadingLabs:s,fetchLabs:T,classSeats:r,setClassSeats:i,savingSeats:a,setSavingSeats:l,fetchClassSeats:_,todaySchedules:c,setTodaySchedules:u,fetchTodaySchedules:E,classSchedulesMap:d,setClassSchedulesMap:h,fetchClassSchedules:R,scheduleAttendanceMap:m,setScheduleAttendanceMap:f,fetchScheduleAttendance:B,expandedScheduleId:g,setExpandedScheduleId:y,newScheduleDate:k,setNewScheduleDate:S,newScheduleLessonId:I,setNewScheduleLessonId:C}}function XS(e){const{selectedLesson:t,lessons:n,setLessons:s}=e,[r,i]=p.useState([]),[a,l]=p.useState("seg-1"),[c,u]=p.useState(null),[d,h]=p.useState(null),[m,f]=p.useState("none"),[g,y]=p.useState(null),[k,S]=p.useState(!0),I=p.useRef(null),C=async(T,_)=>{f("saving");try{(await fetch(`/api/lessons/${T}/timeline`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({timeline:_})})).ok?(s(R=>R.map(B=>B.id===T?{...B,timeline:JSON.stringify(_)}:B)),i(_),f("saved"),y(new Date)):f("error")}catch(E){console.error("Failed to save timeline:",E),f("error")}};return p.useEffect(()=>{if(t){const T=n.find(_=>_.id===t);if(T){let _=[];if(T.timeline)try{_=typeof T.timeline=="string"?JSON.parse(T.timeline):T.timeline}catch{_=[{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 _=[{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(_);const E=I.current!==t;I.current=t,_.length>0?(E||!_.some(R=>R.id===a))&&l(_[0].id):l(null)}}},[t,n]),{timelineSegments:r,setTimelineSegments:i,activeSegmentId:a,setActiveSegmentId:l,segmentToEdit:c,setSegmentToEdit:u,draggedSegmentIdx:d,setDraggedSegmentIdx:h,editorSaveStatus:m,setEditorSaveStatus:f,editorLastSavedTime:g,setEditorLastSavedTime:y,editorPanelsExpanded:k,setEditorPanelsExpanded:S,saveTimeline:C}}function ev(e,t,n){const[s,r]=p.useState(new Set),[i,a]=p.useState(null),[l,c]=p.useState(!1),u=p.useMemo(()=>{if(e!=="student"||!t)return[];const h=[],m=t.assignments||[];for(const g of m)if(!g.submission_status)h.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 y=!!g.feedback;h.push({id:`graded-${g.id}`,type:"graded",title:y?n==="zh"?"收到新成绩与反馈":"Grade & Feedback Posted":n==="zh"?"新成绩发布":"Assignment Graded",message:y?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 f=t.rollcalls||[];for(const g of f)h.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 h.sort((g,y)=>y.date-g.date)},[e,t,n]),d=p.useMemo(()=>u.filter(h=>!s.has(h.id)),[u,s]);return{studentNotifications:u,unreadNotifications:d,readNotifications:s,setReadNotifications:r,selectedNotificationForModal:i,setSelectedNotificationForModal:a,isNotificationsOpen:l,setIsNotificationsOpen:c}}function Cu(e){if(e==null)return"";const t=String(e);return t.includes(",")||t.includes('"')||t.includes(`
169
- `)?`"${t.replace(/"/g,'""')}"`:t}async function tv(e){const{classId:t,className:n,students:s,dashData:r,lang:i,addToast:a,setIsGeneratingPDFReport:l}=e;l(c=>({...c,[t]:!0}));try{if(!r){a(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(A=>{d[A.id]={id:A.id,name:A.name,totalGradesSum:0,gradedCount:0,submittedCount:0,totalCount:0}}),c.forEach(A=>{const U=A.student_id;d[U]&&(d[U].totalCount++,(A.submission_status==="submitted"||A.submission_status==="graded")&&d[U].submittedCount++,A.score!==null&&A.score!==void 0&&(d[U].totalGradesSum+=A.score,d[U].gradedCount++))});const h=Object.values(d).map(A=>{const U=A.gradedCount>0?A.totalGradesSum/A.gradedCount:0,N=A.totalCount>0?A.submittedCount/A.totalCount*100:0;return{...A,avgScore:U,submissionRate:N}});h.sort((A,U)=>U.avgScore-A.avgScore);let m=0,f=0,g=0,y=0;c.forEach(A=>{y++,(A.submission_status==="submitted"||A.submission_status==="graded")&&g++,A.score!==null&&A.score!==void 0&&(m+=A.score,f++)});const k=f>0?m/f:0,S=y>0?g/y*100:0,I={};u.forEach(A=>{I[A.id]={id:A.id,title:A.title,scores:[],submittedCount:0,totalCount:0}}),c.forEach(A=>{const U=A.assignment_id;I[U]&&(I[U].totalCount++,(A.submission_status==="submitted"||A.submission_status==="graded")&&I[U].submittedCount++,A.score!==null&&A.score!==void 0&&I[U].scores.push(A.score))});const C=Object.values(I).map(A=>{const U=A.scores.length,N=A.scores.reduce((b,J)=>b+J,0),O=U>0?N/U:0,x=U>0?Math.max(...A.scores):0,oe=U>0?Math.min(...A.scores):0,pe=A.totalCount>0?A.submittedCount/A.totalCount*100:0;return{...A,avg:O,max:x,min:oe,subRate:pe}}),T=new Sp({orientation:"p",unit:"mm",format:"a4"}),_=[15,23,42],E=[79,70,229],R=[51,65,85],B=[226,232,240],F=A=>{T.setDrawColor(B[0],B[1],B[2]),T.setLineWidth(.3),T.line(14,A,196,A)};T.setFillColor(_[0],_[1],_[2]),T.rect(0,0,210,42,"F"),T.setTextColor(255,255,255),T.setFont("helvetica","bold"),T.setFontSize(20),T.text("CLASS PERFORMANCE REPORT",14,18),T.setFont("helvetica","normal"),T.setFontSize(10),T.setTextColor(194,205,225),T.text("Academic Insights • Generative Report Summary",14,25),T.text(`Classroom: ${n} | Date: ${new Date().toLocaleDateString()} ${new Date().toLocaleTimeString()}`,14,32),T.setFillColor(E[0],E[1],E[2]),T.rect(172,10,24,24,"F"),T.setFont("helvetica","bold"),T.setFontSize(14),T.setTextColor(255,255,255),T.text("OS",180,26);let M=52;T.setTextColor(_[0],_[1],_[2]),T.setFont("helvetica","bold"),T.setFontSize(12),T.text("I. EXECUTIVE OVERVIEW",14,M),M+=6;const v=[["Classroom/Subject Name",n],["Total Enrolled Students",`${s.length} student(s)`],["Curriculum Items (Assignments/Quizzes)",`${u.length} items`],["Global Assignment Submission Rate",`${S.toFixed(1)}%`],["Class Average Performance Score",`${k.toFixed(1)}%`]];T.autoTable({startY:M,head:[["Metric Indicator","Class-wide Metric Value"]],body:v,theme:"striped",headStyles:{fillColor:_,textColor:[255,255,255],fontStyle:"bold",fontSize:9},bodyStyles:{textColor:R,fontSize:9.5},margin:{left:14,right:14}}),M=T.lastAutoTable.finalY+12,T.setTextColor(_[0],_[1],_[2]),T.setFont("helvetica","bold"),T.setFontSize(12),T.text("II. STUDENT RANKING DISTRIBUTION",14,M),M+=6;const z=h.map((A,U)=>{let N="Excellent";return A.avgScore>=90?N="Excellent (A)":A.avgScore>=75?N="Good (B)":A.avgScore>=60?N="Satisfactory (C)":N="Needs Improvement (D)",[`${U+1}`,A.name,`${A.submittedCount}/${A.totalCount} (${A.submissionRate.toFixed(0)}%)`,`${A.avgScore.toFixed(1)}%`,N]});T.autoTable({startY:M,head:[["Rank","Student Name","Completion Rate","Average Score","Academic Standing Tier"]],body:z,theme:"grid",headStyles:{fillColor:E,textColor:[255,255,255],fontStyle:"bold",fontSize:9.5},bodyStyles:{textColor:R,fontSize:9.5},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}}),M=T.lastAutoTable.finalY+12,M>210&&(T.addPage(),M=20),T.setTextColor(_[0],_[1],_[2]),T.setFont("helvetica","bold"),T.setFontSize(12),T.text("III. ASSIGNMENT PERFORMANCE METRICS",14,M),M+=6;const L=C.map(A=>[A.title,`${A.subRate.toFixed(0)}%`,`${A.avg.toFixed(1)}%`,`${A.min.toFixed(0)}% - ${A.max.toFixed(0)}%`]);T.autoTable({startY:M,head:[["Assignment/Quiz Title","Submission Rate","Average Grade","Range (Min - Max)"]],body:L.length>0?L:[["No assignment performance records found.","-","-","-"]],theme:"striped",headStyles:{fillColor:[100,116,139],textColor:[255,255,255],fontStyle:"bold",fontSize:9.5},bodyStyles:{textColor:R,fontSize:9.5},columnStyles:{1:{halign:"center"},2:{halign:"center",fontStyle:"bold"},3:{halign:"center"}},margin:{left:14,right:14}}),M=T.lastAutoTable.finalY+15,F(275),T.setFontSize(8),T.setTextColor(148,163,184),T.text("Generated by OpenLearn Next • Educational Operating System",14,282),T.text("Page 1 of 1 • Internal Educational Audit",196,282,{align:"right"});const P=n.replace(/[^a-z0-9]/gi,"_").toLowerCase(),j=new Date().toISOString().split("T")[0];T.save(`Class_Report_${P}_${j}.pdf`),a(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),a(i==="zh"?"❌ PDF 报告生成失败":"❌ PDF Report Failed",c.message||"Error occurred during PDF generation","warning")}finally{l(c=>({...c,[t]:!1}))}}function nv(e){const{className:t,students:n,dashData:s,qWeight:r=40,aWeight:i=60,overrides:a={}}=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 l=s.assignments||[],c=s.performance||[],u=l.map(C=>{let T="assignment";if(a[C.id])T=a[C.id];else{const _=C.content&&C.content.startsWith('{"quizType":"mcq_learning_objectives"'),E=C.title&&(C.title.toLowerCase().includes("quiz")||C.title.toLowerCase().includes("test")||C.title.includes("测验")||C.title.includes("测试"));T=_||E?"quiz":"assignment"}return{...C,category:T}}),d=["Student Name","Student Email"];u.forEach(C=>{const T=C.category==="quiz"?"Quiz":"Assignment";d.push(`${T}: ${C.title}`)}),d.push("Quizzes Average","Assignments Average",`Weighted Average (${r}% Quizzes, ${i}% Assignments)`,"Simple Average Score","Submitted Count","Total Items");const h=[d];n.forEach(C=>{const T=[C.name,C.email];let _=0,E=0,R=0,B=0,F=0,M=0,v=0;u.forEach(N=>{const O=c.find(x=>x.assignment_id===N.id&&x.student_id===C.id);if(O&&O.score!==null&&O.score!==void 0){T.push(`${O.score}%`);const x=Number(O.score);N.category==="quiz"?(_+=x,E++):(R+=x,B++),F+=x,M++,v++}else O&&O.submission_status==="submitted"?(T.push("Pending Grade"),v++):T.push("Not Submitted")});const z=E>0?Math.round(_/E):null,L=B>0?Math.round(R/B):null;let P="N/A";if(z!==null&&L!==null){const N=z*(r/100)+L*(i/100);P=`${Math.round(N)}%`}else z!==null?P=`${z}%`:L!==null&&(P=`${L}%`);const j=z!==null?`${z}%`:"N/A",A=L!==null?`${L}%`:"N/A",U=M>0?`${Math.round(F/M)}%`:"N/A";T.push(j,A,P,U,`${v}`,`${l.length}`),h.push(T.map(Cu))});const m=h.map(C=>C.join(",")).join(`
170
- `),f=new Blob(["\uFEFF"+m],{type:"text/csv;charset=utf-8;"}),g=URL.createObjectURL(f),y=document.createElement("a"),k=t.replace(/[^a-z0-9]/gi,"_").toLowerCase(),S=new Date().toISOString().split("T")[0],I=`${k}_grades_report_${S}.csv`;y.setAttribute("href",g),y.setAttribute("download",I),y.style.visibility="hidden",document.body.appendChild(y),y.click(),document.body.removeChild(y),URL.revokeObjectURL(g)}function sv(e){const{exportClassId:t,classStudentsMap:n,classDashboardMap:s,quizzesWeight:r,assignmentsWeight:i,customCategoryOverrides:a,lang:l}=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||[],h=u.performance||[],m=d.map(k=>{let S="assignment";if(a[k.id])S=a[k.id];else{const I=k.content&&k.content.startsWith('{"quizType":"mcq_learning_objectives"'),C=k.title&&(k.title.toLowerCase().includes("quiz")||k.title.toLowerCase().includes("test")||k.title.includes("测验")||k.title.includes("测试"));S=I||C?"quiz":"assignment"}return{...k,category:S}}),f=["Student Name","Student Email"];m.forEach(k=>{const S=k.category==="quiz"?"Quiz":"Assignment";f.push(`${S}: ${k.title}`)}),f.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(k=>{const S=[k.name,k.email];let I=0,C=0,T=0,_=0,E=0,R=0,B=0;m.forEach(j=>{const A=h.find(U=>U.assignment_id===j.id&&U.student_id===k.id);if(A&&A.score!==null&&A.score!==void 0){S.push(`${A.score}%`);const U=Number(A.score);j.category==="quiz"?(I+=U,C++):(T+=U,_++),E+=U,R++,B++}else A&&A.submission_status==="submitted"?(S.push(l==="zh"?"待评分":"Pending Grade"),B++):S.push(l==="zh"?"未提交":"Not Submitted")});const F=C>0?Math.round(I/C):null,M=_>0?Math.round(T/_):null;let v="N/A";if(F!==null&&M!==null){const j=F*(r/100)+M*(i/100);v=`${Math.round(j)}%`}else F!==null?v=`${F}%`:M!==null&&(v=`${M}%`);const z=F!==null?`${F}%`:"N/A",L=M!==null?`${M}%`:"N/A",P=R>0?`${Math.round(E/R)}%`:"N/A";S.push(z,L,v,P,`${B}`,`${d.length}`),g.push(S)}),{headers:f,rows:g,totalStudents:c.length}}function rv(e){const{classes:t,classStudentsMap:n,classDashboardMap:s,lang:r}=e,a=[["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 h=n[d.id]||[],m=s[d.id];if(!m||!m.assignments||h.length===0)return;const f=m.assignments||[],g=f.map(y=>{const k=y.content&&y.content.startsWith('{"quizType":"mcq_learning_objectives"'),S=y.title&&(y.title.toLowerCase().includes("quiz")||y.title.toLowerCase().includes("test")||y.title.includes("测验")||y.title.includes("测试"));return{...y,category:k||S?"quiz":"assignment"}});h.forEach(y=>{let k=0,S=0,I=0,C=0,T=0,_=0;g.forEach(v=>{const z=m.performance?.find(L=>L.student_id===y.id&&L.assignment_id===v.id&&L.submission_status==="graded"&&L.score!==null);if(z){const L=Number(z.score);T+=L,_++,v.category==="quiz"?(k+=L,S++):(I+=L,C++)}});const E=S>0?Math.round(k/S):null,R=C>0?Math.round(I/C):null;let B=0;E!==null&&R!==null?B=Math.round(E*.4+R*.6):E!==null?B=Math.round(E):R!==null&&(B=Math.round(R));const F=_>0?Math.round(T/_):0,M=[d.name,y.name,y.email,E!==null?`${E}%`:"N/A",R!==null?`${R}%`:"N/A",`${B}%`,`${F}%`,`${_}`,`${f.length}`];a.push(M)})}),a.length<=1){alert(r==="zh"?"暂无可导出的成绩数据。请确保班级中有已评分的作业。":"No graded performance data available to export.");return}const l="data:text/csv;charset=utf-8,\uFEFF"+a.map(d=>d.map(Cu).join(",")).join(`
171
- `),c=encodeURI(l),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 iv(e){const{lang:t,classes:n,classStudentsMap:s,classDashboardMap:r,fetchClassStudents:i,fetchClassDashboard:a,fetchClassProgress:l,addToast:c=()=>{}}=e,[u,d]=p.useState(!1),[h,m]=p.useState(""),[f,g]=p.useState(""),[y,k]=p.useState(40),[S,I]=p.useState(60),[C,T]=p.useState({}),[_,E]=p.useState(!1),[R,B]=p.useState(!1),[F,M]=p.useState(null),[v,z]=p.useState(!1),[L,P]=p.useState({}),j=p.useCallback(b=>{const J=Math.min(100,Math.max(0,b));k(J),I(100-J)},[]),A=p.useCallback(b=>{const J=Math.min(100,Math.max(0,b));I(J),k(100-J)},[]),U=p.useMemo(()=>sv({exportClassId:h,classStudentsMap:s,classDashboardMap:r,quizzesWeight:y,assignmentsWeight:S,customCategoryOverrides:C,lang:t}),[h,y,S,C,s,r,t]),N=p.useCallback(async(b,J)=>{M(b);try{await i(b),await a(b),await l(b),m(b),g(J),k(40),I(60),T({}),d(!0)}catch(D){console.error(D)}finally{M(null),E(!1)}},[i,a,l]),O=p.useCallback((b,J,D=40,G=60,re={})=>{nv({className:J,students:s[b]||[],dashData:r[b],qWeight:D,aWeight:G,overrides:re})},[s,r]),x=p.useCallback(async(b,J)=>{await i(b),await a(b),await l(b),await tv({classId:b,className:J,students:s[b]||[],dashData:r[b],lang:t,addToast:c,setIsGeneratingPDFReport:P})},[s,r,t,c,i,a,l]),oe=p.useCallback(async()=>{z(!0);try{await rv({classes:n,classStudentsMap:s,classDashboardMap:r,lang:t})}catch(b){console.error("Export all classes error:",b)}finally{z(!1),E(!1)}},[n,s,r,t]),pe=p.useCallback((b,J)=>{const D=r[J];if(!D||!D.performance)return null;const G=Date.now()-2592e6,se=D.performance.filter(le=>le.student_id===b).filter(le=>le.submitted_at&&le.submitted_at>=G&&le.score!==null&&le.score!==void 0);if(se.length===0)return null;const me=se.reduce((le,Ve)=>le+Number(Ve.score),0)/se.length;return me<60?Math.round(me):null},[r]);return{isExportWeightModalOpen:u,setIsExportWeightModalOpen:d,exportClassId:h,setExportClassId:m,exportClassName:f,setExportClassName:g,quizzesWeight:y,setQuizzesWeight:k,assignmentsWeight:S,setAssignmentsWeight:I,customCategoryOverrides:C,setCustomCategoryOverrides:T,exportDropdownOpen:_,setExportDropdownOpen:E,exportTooltipOpen:R,setExportTooltipOpen:B,loadingExportClassId:F,setLoadingExportClassId:M,isExportingAllCombined:v,setIsExportingAllCombined:z,isGeneratingPDFReport:L,setIsGeneratingPDFReport:P,handleQuizzesWeightChange:j,handleAssignmentsWeightChange:A,csvPreviewData:U,triggerExportForClass:N,handleExportGrades:O,handleGeneratePDFReport:x,handleExportAllClassesCombined:oe,get30DayAverageWarning:pe}}function ov(e){const[t,n]=p.useState(""),[s,r]=p.useState("recent"),[i,a]=p.useState(!1),[l,c]=p.useState(!1),[u,d]=p.useState(!1),[h,m]=p.useState(null),f=p.useMemo(()=>{let g=[...e];if(t.trim()){const y=t.toLowerCase();g=g.filter(k=>k.title.toLowerCase().includes(y)||k.content.toLowerCase().includes(y))}if(i&&(g=g.filter(y=>(y.enrollment_count||0)>0)),l&&(g=g.filter(y=>y.content&&y.content.trim().length>0)),u){const y=new Date(new Date().getFullYear(),new Date().getMonth(),1).getTime();g=g.filter(k=>(k.created_at||0)>=y)}return s==="recent"?g.sort((y,k)=>(k.created_at||0)-(y.created_at||0)):s==="alphabetical"?g.sort((y,k)=>y.title.localeCompare(k.title)):s==="enrollment"&&g.sort((y,k)=>(k.enrollment_count||0)-(y.enrollment_count||0)),g},[e,t,s,i,l,u]);return{lessonsSearchQuery:t,setLessonsSearchQuery:n,lessonsSortOrder:s,setLessonsSortOrder:r,filterEnrollment:i,setFilterEnrollment:a,filterHasContent:l,setFilterHasContent:c,filterThisMonth:u,setFilterThisMonth:d,copyingLessonId:h,setCopyingLessonId:m,filteredAndSortedLessons:f}}function zl(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
172
- 高一A班,基础英语课程,王华,wanghua@example.com`:`Class 101,Introduction to English,John Doe,john@example.com
173
- 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
174
- 李四,lisi@example.com`:`Alice Cooper,alice@example.com
175
- Bob Dylan,bob@example.com`);const i=new Blob(["\uFEFF"+s+`
176
- `+r],{type:"text/csv;charset=utf-8;"}),a=URL.createObjectURL(i),l=document.createElement("a");l.href=a,l.setAttribute("download",n),document.body.appendChild(l),l.click(),document.body.removeChild(l)}async function av(e,t){const{lang:n,fetchClasses:s,fetchStudents:r}=t;return new Promise((i,a)=>{const l=new FileReader;l.onload=async c=>{try{const u=c.target?.result;if(!u)throw new Error("File content is empty");let d=[],h=[],m=!0;if(e.name.endsWith(".json")){const f=JSON.parse(u);if(!Array.isArray(f))throw new Error("JSON structure must be an array");f.some(y=>y.className||y.name&&(y.students||y.classDescription))?(m=!0,d=f.map(y=>{const k=y.name||y.className||y.class_name,S=y.description||y.classDescription||"",I=y.students||y.studentList||[],C=(Array.isArray(I)?I:[]).map(T=>({name:T.name||T.studentName||"",email:T.email||T.studentEmail||""})).filter(T=>T.name);return{name:k,description:S,students:C}}).filter(y=>y.name)):(m=!1,h=f.map(y=>({name:y.name||y.studentName||y.student_name||"",email:y.email||y.studentEmail||y.student_email||""})).filter(y=>y.name))}else{const f=u.split(/\r?\n/);if(f.length<2)throw new Error("CSV has empty or insufficient data");const g=f[0].split(",").map(C=>C.trim().toLowerCase()),y=g.findIndex(C=>C.includes("class name")||C.includes("班级名称")||C.includes("班级")||C.includes("classname")||C.includes("class_name")),k=g.findIndex(C=>C.includes("class desc")||C.includes("班级描述")||C.includes("描述")||C.includes("class_desc")),S=g.findIndex(C=>C.includes("student name")||C.includes("学生姓名")||C.includes("姓名")||C.includes("学生")||C.includes("studentname")||C.includes("student_name")),I=g.findIndex(C=>C.includes("student email")||C.includes("学生邮箱")||C.includes("邮箱")||C.includes("email")||C.includes("studentemail")||C.includes("student_email"));if(S===-1)throw new Error('CSV is missing column: "Student Name" (学生姓名/姓名/学生)');if(y!==-1){m=!0;const C={};for(let T=1;T<f.length;T++){const _=f[T].trim();if(!_)continue;const R=(_.match(/(".*?"|[^",]+)(?=\s*,|\s*$)/g)||_.split(",")).map(z=>z.replace(/^"|"$/g,"").trim()),B=R[y];if(!B)continue;const F=k!==-1&&R[k]||"",M=S!==-1&&R[S]||"",v=I!==-1&&R[I]||"";C[B]||(C[B]={name:B,description:F,students:[]}),M&&C[B].students.push({name:M,email:v})}d=Object.values(C)}else{m=!1;for(let C=1;C<f.length;C++){const T=f[C].trim();if(!T)continue;const E=(T.match(/(".*?"|[^",]+)(?=\s*,|\s*$)/g)||T.split(",")).map(F=>F.replace(/^"|"$/g,"").trim()),R=S!==-1&&E[S]||"",B=I!==-1&&E[I]||"";R&&h.push({name:R,email:B})}}}if(m){if(d.length===0)throw new Error("No valid class elements found inside file.");const f=await fetch("/api/classes/import",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({classes:d})});if(!f.ok){const y=await f.json();throw new Error(y.error||"Server importation failed")}const g=await f.json();await s(),await r(),i({success:!0,message:n==="zh"?`成功导入 ${g.imported.length} 个班级数据!`:`Successfully imported ${g.imported.length} classes data!`})}else{if(h.length===0)throw new Error("No valid student elements found inside file.");const f=await fetch("/api/students/import",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({students:h})});if(!f.ok){const y=await f.json();throw new Error(y.error||"Server student importation failed")}const g=await f.json();await r(),i({success:!0,message:n==="zh"?`成功导入 ${g.imported.filter(y=>y.new).length} 名新学者,匹配并更新了其中的 ${g.imported.filter(y=>!y.new).length} 名同学!`:`Successfully imported ${g.imported.filter(y=>y.new).length} new students and updated ${g.imported.filter(y=>!y.new).length} existing ones!`})}}catch(u){a(u)}},l.onerror=()=>{a(new Error("Failed to read file from disk."))},l.readAsText(e)})}function lv(e,t){return new Promise((n,s)=>{const r=new FileReader;r.onload=i=>{try{const a=i.target?.result;if(!a)throw new Error("Empty CSV file");const l=a.split(/\r?\n/);if(l.length<2)throw new Error(t==="zh"?"CSV 文件行数不足,请包含标题和至少一行数据。":"CSV is missing content or headers.");const c=l[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 h=[];for(let m=1;m<l.length;m++){const f=l[m].trim();if(!f)continue;const y=(f.match(/(".*?"|[^",]+)(?=\s*,|\s*$)/g)||f.split(",")).map(I=>I.replace(/^"|"$/g,"").trim()),k=y[u],S=y[d];k&&S&&h.push({title:k,content:S})}if(h.length===0)throw new Error(t==="zh"?"未能从 CSV 解析出有效课程数据。":"No valid courses found in CSV.");n(h)}catch(a){s(a)}},r.onerror=()=>{s(new Error(t==="zh"?"无法读取选取的 CSV 文件!":"Failure to read the CSV!"))},r.readAsText(e)})}async function cv(e,t){const{lang:n,setImportProgress:s,fetchLessons:r}=t;let i=0;for(let a=0;a<e.length;a++){const l=e[a];try{const c=await fetch("/api/lessons",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({title:l.title,content:l.content})});if(c.ok)i++;else{const u=await c.json();console.warn(`Failed to import item ${a+1}:`,u)}}catch(c){console.warn(`Error importing item ${a+1}:`,c)}s(a+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 uv(){const e=de(v=>v.session),t=typeof window<"u"&&(new URLSearchParams(window.location.search).get("mode")==="student_live"||window.location.hash.includes("student_live")),n=e?.role==="student"||t,s=it(v=>v.errors),r=it(v=>v.studentErrors),i=it(v=>v.activeTab),a=it(v=>v.setActiveTab),l=it(v=>v.isErrorCenterOpen),c=it(v=>v.setIsErrorCenterOpen),u=it(v=>v.clearErrors),d=it(v=>v.clearStudentErrors),h=it(v=>v.removeError),m=it(v=>v.removeStudentError),[f,g]=p.useState(!1),[y,k]=p.useState(null),[S,I]=p.useState(new Set),[C,T]=p.useState(!1),_=s.length+(n?0:r.length),E=s.length>0||!n&&r.length>0,R=v=>{I(z=>{const L=new Set(z);return L.has(v)?L.delete(v):L.add(v),L})},B=async()=>{const v=qS(s,n?[]:r);await Ls(v)&&(g(!0),setTimeout(()=>g(!1),2500))},F=async(v,z,L=!1)=>{v.stopPropagation();const P=L?vu(z):vo(z);await Ls(P)&&(k(z.id),setTimeout(()=>k(null),2500))},M=v=>{switch(v){case"react":return o.jsx("span",{className:"px-2 py-0.5 rounded-full text-xs font-bold bg-rose-100 text-rose-700 dark:bg-rose-950/60 dark:text-rose-400 border border-rose-200 dark:border-rose-800",children:"React"});case"api":return o.jsx("span",{className:"px-2 py-0.5 rounded-full text-xs font-bold bg-purple-100 text-purple-700 dark:bg-purple-950/60 dark:text-purple-400 border border-purple-200 dark:border-purple-800",children:"API 5xx"});case"promise":return o.jsx("span",{className:"px-2 py-0.5 rounded-full text-xs font-bold bg-amber-100 text-amber-700 dark:bg-amber-950/60 dark:text-amber-400 border border-amber-200 dark:border-amber-800",children:"Promise"});default:return o.jsx("span",{className:"px-2 py-0.5 rounded-full text-xs font-bold bg-blue-100 text-blue-700 dark:bg-blue-950/60 dark:text-blue-400 border border-blue-200 dark:border-blue-800",children:"Runtime"})}};return o.jsxs(o.Fragment,{children:[E&&!l&&!C&&(n?o.jsxs(xs.button,{type:"button",initial:{opacity:0,scale:.8},animate:{opacity:1,scale:1},exit:{opacity:0,scale:.8},className:"fixed bottom-5 left-5 z-40 w-8 h-8 rounded-full bg-slate-900/80 hover:bg-slate-900 text-rose-400 border border-rose-500/40 shadow-lg flex items-center justify-center cursor-pointer transition-all hover:scale-105 select-none",onClick:()=>c(!0),id:"system-error-pill",title:`系统状态提示: ${s.length} 处异常`,children:[o.jsx(Ns,{size:15}),o.jsx("span",{className:"absolute -top-1 -right-1 min-w-[16px] h-4 px-1 rounded-full bg-rose-500 text-white text-[10px] font-bold flex items-center justify-center leading-none shadow-xs border border-slate-900",children:s.length})]}):o.jsxs(xs.div,{initial:{opacity:0,y:20,scale:.95},animate:{opacity:1,y:0,scale:1},exit:{opacity:0,scale:.9},className:"fixed bottom-5 left-5 z-40 flex items-center gap-2 bg-slate-900/90 hover:bg-slate-900 backdrop-blur-md text-white px-3.5 py-2 rounded-2xl shadow-xl border border-rose-500/40 cursor-pointer select-none transition-all group",onClick:()=>{s.length===0&&r.length>0&&a("student"),c(!0)},id:"system-error-pill",children:[o.jsxs("div",{className:"relative flex items-center justify-center",children:[o.jsx("span",{className:"animate-ping absolute inline-flex h-3 w-3 rounded-full bg-rose-400 opacity-75"}),o.jsx("span",{className:"relative inline-flex rounded-full h-2 w-2 bg-rose-500"})]}),o.jsx(Ns,{size:15,className:"text-rose-400 group-hover:scale-110 transition-transform"}),o.jsxs("div",{className:"text-xs font-semibold flex items-center gap-1.5",children:[o.jsx("span",{children:"捕获到"}),o.jsx("span",{className:"bg-rose-500/80 text-white font-mono px-1.5 py-0.2 rounded-md text-xs font-bold",children:_}),o.jsx("span",{children:"处系统异常"}),r.length>0&&o.jsxs("span",{className:"text-[10px] text-rose-300 font-normal",children:["(含学生端 ",r.length,")"]})]}),o.jsx("button",{type:"button",className:"text-xs font-bold text-rose-300 hover:text-white bg-white/10 hover:bg-white/20 px-2 py-0.5 rounded-lg transition-colors ml-1",children:"查看与复制"}),o.jsx("button",{type:"button",onClick:v=>{v.stopPropagation(),T(!0)},className:"text-gray-400 hover:text-gray-200 p-0.5 hover:bg-white/10 rounded transition-colors ml-0.5",title:"暂时隐藏胶囊",children:o.jsx(tt,{size:13})})]})),o.jsx(Bc,{children:l&&o.jsx("div",{className:"fixed inset-0 bg-gray-900/60 backdrop-blur-xs flex items-center justify-center p-4 z-50 overflow-hidden select-text",children:o.jsxs(xs.div,{initial:{opacity:0,scale:.95,y:10},animate:{opacity:1,scale:1,y:0},exit:{opacity:0,scale:.95,y:10},className:"bg-white dark:bg-slate-900 border border-gray-200 dark:border-gray-800 rounded-2xl shadow-2xl w-full max-w-3xl max-h-[85vh] flex flex-col overflow-hidden text-gray-900 dark:text-gray-100",children:[o.jsxs("div",{className:"px-5 py-4 border-b border-gray-200 dark:border-gray-800 flex items-center justify-between bg-gray-50/80 dark:bg-slate-850/80 shrink-0",children:[o.jsxs("div",{className:"flex items-center gap-3",children:[o.jsx("div",{className:"p-2 bg-rose-500/10 text-rose-600 dark:text-rose-400 border border-rose-500/20 rounded-xl",children:o.jsx(xp,{size:18})}),o.jsxs("div",{children:[o.jsx("div",{className:"flex items-center gap-2",children:o.jsxs("h2",{className:"text-sm font-bold flex items-center gap-2",children:[o.jsx("span",{children:"系统异常诊断中心 (System Diagnostics)"}),o.jsxs("span",{className:"text-xs font-normal text-gray-500 dark:text-gray-400",children:["(",_," 项记录)"]})]})}),o.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400 mt-0.5",children:"自动捕获运行时、Promise 及接口 5xx 异常,支持一键导出 Markdown 格式排查报告。"})]})]}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsxs("button",{type:"button",onClick:B,disabled:_===0,className:`px-3 py-1.5 rounded-lg text-xs font-bold transition-all flex items-center gap-1.5 shadow-xs cursor-pointer ${f?"bg-emerald-600 text-white":"bg-indigo-600 hover:bg-indigo-700 text-white disabled:opacity-40 disabled:cursor-not-allowed"}`,title:"复制所有异常报告为 Markdown 文本",children:[f?o.jsx(et,{size:13}):o.jsx(rn,{size:13}),o.jsx("span",{children:f?"已复制全部!":"一键复制全部诊断日志"})]}),o.jsx("button",{type:"button",onClick:()=>{!n&&i==="student"?d():u()},disabled:i==="student"?r.length===0:s.length===0,className:"p-1.5 text-gray-500 hover:text-rose-600 dark:text-gray-400 dark:hover:text-rose-400 hover:bg-gray-100 dark:hover:bg-slate-800 rounded-lg transition-colors disabled:opacity-40 disabled:cursor-not-allowed cursor-pointer",title:i==="student"?"清空学生端异常记录":"清空记录",children:o.jsx($l,{size:16})}),o.jsx("button",{type:"button",onClick:()=>c(!1),className:"p-1.5 text-gray-500 hover:text-gray-800 dark:text-gray-400 dark:hover:text-gray-200 hover:bg-gray-100 dark:hover:bg-slate-800 rounded-lg transition-colors cursor-pointer",children:o.jsx(tt,{size:16})})]})]}),!n&&o.jsxs("div",{className:"px-5 py-2 border-b border-gray-200 dark:border-gray-800 bg-gray-50/50 dark:bg-slate-900/50 flex items-center gap-2",children:[o.jsxs("button",{type:"button",onClick:()=>a("local"),className:`px-3 py-1.5 rounded-lg text-xs font-bold transition-all flex items-center gap-1.5 cursor-pointer ${i==="local"?"bg-white dark:bg-slate-800 text-indigo-600 dark:text-indigo-400 shadow-xs border border-gray-200 dark:border-gray-700":"text-gray-500 hover:text-gray-800 dark:text-gray-400"}`,children:[o.jsx(yp,{size:13}),o.jsxs("span",{children:["本机异常 (",s.length,")"]})]}),o.jsxs("button",{type:"button",onClick:()=>a("student"),className:`px-3 py-1.5 rounded-lg text-xs font-bold transition-all flex items-center gap-1.5 cursor-pointer ${i==="student"?"bg-white dark:bg-slate-800 text-rose-600 dark:text-rose-400 shadow-xs border border-gray-200 dark:border-gray-700":"text-gray-500 hover:text-gray-800 dark:text-gray-400"}`,children:[o.jsx(js,{size:14}),o.jsxs("span",{children:["学生端异常 (",r.length,")"]}),r.length>0&&o.jsx("span",{className:"inline-block w-2 h-2 rounded-full bg-rose-500 animate-pulse"})]})]}),o.jsx("div",{className:"flex-1 overflow-y-auto p-4 space-y-3 min-h-0 bg-slate-50/50 dark:bg-slate-950/30",children:!n&&i==="student"?r.length===0?o.jsxs("div",{className:"py-16 text-center text-gray-400 dark:text-gray-500 space-y-2",children:[o.jsx(et,{size:32,className:"mx-auto text-emerald-500 opacity-80"}),o.jsx("p",{className:"text-sm font-semibold",children:"暂无学生端上报的系统异常"}),o.jsx("p",{className:"text-xs opacity-75",children:"全班学生端运行良好,未发生未捕获的前端崩溃或接口 5xx 故障。"})]}):r.map((v,z)=>{const L=S.has(v.id),P=y===v.id;return o.jsxs("div",{className:"bg-white dark:bg-slate-900 border border-gray-200 dark:border-gray-800 rounded-xl overflow-hidden shadow-2xs hover:border-gray-300 dark:hover:border-gray-700 transition-colors",children:[o.jsxs("div",{onClick:()=>R(v.id),className:"px-4 py-3 flex items-start justify-between gap-3 cursor-pointer select-none hover:bg-gray-50/50 dark:hover:bg-slate-850/50 transition-colors",children:[o.jsxs("div",{className:"flex items-start gap-2.5 min-w-0 flex-1",children:[o.jsx("span",{className:"text-gray-400 mt-0.5 shrink-0",children:L?o.jsx(Ln,{size:15}):o.jsx(Ci,{size:15})}),o.jsxs("div",{className:"space-y-1 min-w-0 flex-1",children:[o.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[o.jsxs("span",{className:"px-2 py-0.5 rounded-full text-xs font-bold bg-rose-100 text-rose-700 dark:bg-rose-950/60 dark:text-rose-400 border border-rose-200 dark:border-rose-800 flex items-center gap-1",children:[o.jsx(js,{size:11}),o.jsx("span",{children:v.studentName||v.studentId})]}),M(v.type),o.jsxs("span",{className:"font-bold text-xs text-gray-900 dark:text-gray-100 truncate",children:["#",r.length-z," ",v.title]}),o.jsx("span",{className:"text-xs text-gray-400 font-mono",children:new Date(v.timestamp).toLocaleTimeString()})]}),o.jsx("p",{className:"text-xs text-rose-600 dark:text-rose-400 font-mono break-all line-clamp-2",children:v.message}),o.jsxs("div",{className:"flex items-center gap-3 text-xs text-gray-500 font-mono truncate",children:[o.jsxs("span",{children:["学生学号/ID: ",v.studentId]}),v.lessonId&&o.jsxs("span",{children:["课节: ",v.lessonId]}),v.classId&&o.jsxs("span",{children:["班级: ",v.classId]}),v.endpoint&&o.jsxs("span",{children:["接口: ",v.endpoint]})]})]})]}),o.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[o.jsxs("button",{type:"button",onClick:j=>F(j,v,!0),className:`px-2.5 py-1 rounded-lg text-xs font-bold transition-all flex items-center gap-1 cursor-pointer ${P?"bg-emerald-600 text-white":"bg-gray-100 hover:bg-gray-200 text-gray-700 dark:bg-slate-800 dark:hover:bg-slate-700 dark:text-gray-200"}`,title:"一键复制此条学生错误报告",children:[P?o.jsx(et,{size:11}):o.jsx(rn,{size:11}),o.jsx("span",{children:P?"已复制":"复制"})]}),o.jsx("button",{type:"button",onClick:j=>{j.stopPropagation(),m(v.id)},className:"p-1 text-gray-400 hover:text-rose-600 rounded transition-colors cursor-pointer",title:"移除此项",children:o.jsx(tt,{size:13})})]})]}),L&&o.jsxs("div",{className:"px-4 py-3 bg-slate-900 text-slate-200 border-t border-gray-100 dark:border-gray-800 text-xs font-mono space-y-2.5",children:[o.jsxs("div",{className:"flex items-center justify-between text-xs text-slate-400 border-b border-slate-800 pb-1.5",children:[o.jsxs("span",{children:["学生: ",v.studentName||"未知"," (",v.studentId,")"]}),o.jsxs("span",{children:["页面地址: ",v.url||"未知"]}),o.jsxs("span",{children:["时间: ",new Date(v.timestamp).toLocaleString()]})]}),v.stack&&o.jsxs("div",{children:[o.jsx("span",{className:"text-rose-400 font-bold block mb-1",children:"Stack Trace:"}),o.jsx("pre",{className:"whitespace-pre-wrap text-xs leading-relaxed max-h-48 overflow-y-auto opacity-90",children:v.stack})]}),v.componentStack&&o.jsxs("div",{className:"pt-2 border-t border-slate-800",children:[o.jsx("span",{className:"text-amber-400 font-bold block mb-1",children:"Component Stack:"}),o.jsx("pre",{className:"whitespace-pre-wrap text-xs leading-relaxed max-h-36 overflow-y-auto opacity-80",children:v.componentStack})]})]})]},v.id)}):s.length===0?o.jsxs("div",{className:"py-16 text-center text-gray-400 dark:text-gray-500 space-y-2",children:[o.jsx(et,{size:32,className:"mx-auto text-emerald-500 opacity-80"}),o.jsx("p",{className:"text-sm font-semibold",children:"暂无捕获到的系统异常"}),o.jsx("p",{className:"text-xs opacity-75",children:"系统运行顺畅,所有模块均在正常状态下运作。"})]}):s.map((v,z)=>{const L=S.has(v.id),P=y===v.id;return o.jsxs("div",{className:"bg-white dark:bg-slate-900 border border-gray-200 dark:border-gray-800 rounded-xl overflow-hidden shadow-2xs hover:border-gray-300 dark:hover:border-gray-700 transition-colors",children:[o.jsxs("div",{onClick:()=>R(v.id),className:"px-4 py-3 flex items-start justify-between gap-3 cursor-pointer select-none hover:bg-gray-50/50 dark:hover:bg-slate-850/50 transition-colors",children:[o.jsxs("div",{className:"flex items-start gap-2.5 min-w-0 flex-1",children:[o.jsx("span",{className:"text-gray-400 mt-0.5 shrink-0",children:L?o.jsx(Ln,{size:15}):o.jsx(Ci,{size:15})}),o.jsxs("div",{className:"space-y-1 min-w-0 flex-1",children:[o.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[M(v.type),o.jsxs("span",{className:"font-bold text-xs text-gray-900 dark:text-gray-100 truncate",children:["#",s.length-z," ",v.title]}),o.jsx("span",{className:"text-xs text-gray-400 font-mono",children:new Date(v.timestamp).toLocaleTimeString()})]}),o.jsx("p",{className:"text-xs text-rose-600 dark:text-rose-400 font-mono break-all line-clamp-2",children:v.message}),v.endpoint&&o.jsxs("p",{className:"text-xs text-gray-500 font-mono truncate",children:["接口: ",v.endpoint]})]})]}),o.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[o.jsxs("button",{type:"button",onClick:j=>F(j,v,!1),className:`px-2.5 py-1 rounded-lg text-xs font-bold transition-all flex items-center gap-1 cursor-pointer ${P?"bg-emerald-600 text-white":"bg-gray-100 hover:bg-gray-200 text-gray-700 dark:bg-slate-800 dark:hover:bg-slate-700 dark:text-gray-200"}`,title:"一键复制此条错误报告",children:[P?o.jsx(et,{size:11}):o.jsx(rn,{size:11}),o.jsx("span",{children:P?"已复制":"复制"})]}),o.jsx("button",{type:"button",onClick:j=>{j.stopPropagation(),h(v.id)},className:"p-1 text-gray-400 hover:text-rose-600 rounded transition-colors cursor-pointer",title:"移除此项",children:o.jsx(tt,{size:13})})]})]}),L&&o.jsxs("div",{className:"px-4 py-3 bg-slate-900 text-slate-200 border-t border-gray-100 dark:border-gray-800 text-xs font-mono space-y-2.5",children:[o.jsxs("div",{className:"flex items-center justify-between text-xs text-slate-400 border-b border-slate-800 pb-1.5",children:[o.jsxs("span",{children:["页面地址: ",v.url||"未知"]}),o.jsxs("span",{children:["时间: ",new Date(v.timestamp).toLocaleString()]})]}),v.stack&&o.jsxs("div",{children:[o.jsx("span",{className:"text-rose-400 font-bold block mb-1",children:"Stack Trace:"}),o.jsx("pre",{className:"whitespace-pre-wrap text-xs leading-relaxed max-h-48 overflow-y-auto opacity-90",children:v.stack})]}),v.componentStack&&o.jsxs("div",{className:"pt-2 border-t border-slate-800",children:[o.jsx("span",{className:"text-amber-400 font-bold block mb-1",children:"Component Stack:"}),o.jsx("pre",{className:"whitespace-pre-wrap text-xs leading-relaxed max-h-36 overflow-y-auto opacity-80",children:v.componentStack})]})]})]},v.id)})})]})})})]})}function dv(){p.useEffect(()=>{if(typeof window>"u")return;const e=i=>{const a=i.reason,l=a instanceof Error?a.message:typeof a=="string"?a:JSON.stringify(a)||"Unhandled promise rejection",c=a instanceof Error?a.stack:void 0;$t.getState().addError({type:"promise",title:"未捕获的异步异常 (Unhandled Promise)",message:l,stack:c}),console.warn("[GlobalErrorCapture] Caught unhandled rejection:",a)},t=i=>{if(!i.message&&!i.error)return;const a=i.message||(i.error?.message??"Unknown script error"),l=i.error?.stack;$t.getState().addError({type:"runtime",title:"JavaScript 运行时错误 (Runtime Error)",message:a,stack:l}),console.warn("[GlobalErrorCapture] Caught window error:",i.error||i.message)},n=window.fetch,s=async(...i)=>{try{const a=await n(...i);if(!a.ok&&a.status>=500)try{const c=await a.clone().text();let u="";try{const m=JSON.parse(c);u=m.error||m.message||m.details||c}catch{u=c.slice(0,300)}const d=i[0],h=typeof d=="string"?d:d instanceof Request?d.url:String(d);$t.getState().addError({type:"api",title:`服务端接口错误 (HTTP ${a.status})`,message:u||`Request failed with status ${a.status}`,endpoint:h,status:a.status})}catch{}return a}catch(a){const l=i[0],c=typeof l=="string"?l:l instanceof Request?l.url:String(l);throw c&&(c.startsWith("/api")||c.includes("/api/"))&&$t.getState().addError({type:"api",title:"网络请求失败 (Network Disconnected / Error)",message:a?.message||"Failed to fetch API endpoint",endpoint:c,stack:a?.stack}),a}},r=HS(i=>{try{const a=ve.getState(),l=typeof window<"u"&&(new URLSearchParams(window.location.search).get("mode")==="student_live"||window.location.hash.includes("student_live"));if(!(a.session?.role==="student"||l))return;const u=typeof window<"u"?new URLSearchParams(window.location.search):null,d=a.session?.userId||u?.get("studentId")||"anonymous_student",h=a.session?.name||a.session?.username||u?.get("studentName")||d,m=a.selectedLesson||u?.get("lessonId")||null,f=a.liveClassSelectedClassId||u?.get("classId")||null,g={studentId:d,studentName:h,lessonId:m,classId:f,error:i},y=OS();if(y&&y.connected)y.emit("student-client-error",g);else{const k="/api/diagnostics/report",S=JSON.stringify(g);typeof navigator<"u"&&navigator.sendBeacon?navigator.sendBeacon(k,new Blob([S],{type:"application/json"})):fetch(k,{method:"POST",headers:{"Content-Type":"application/json"},body:S}).catch(()=>{})}}catch(a){console.warn("[GlobalErrorCapture] Failed to report student error:",a)}});return window.fetch=s,window.addEventListener("unhandledrejection",e),window.addEventListener("error",t),()=>{window.fetch=n,window.removeEventListener("unhandledrejection",e),window.removeEventListener("error",t),r()}},[])}function hv(e){return"#/"+e}function _l(e){const t=e.replace(/^#/,"");return!t||t==="/"?null:t.replace(/^\//,"")}t0();const Ll="openlearnv2.agentProviderId";function fv(){dv();const e=de(w=>w.lang),t=de(w=>w.setLang),n=fa[e]??fa.zh,[s,r]=p.useState(!1),i=typeof window<"u"&&(new URLSearchParams(window.location.search).get("mode")==="student_live"||window.location.hash.includes("student_live")),a=typeof window<"u"?new URLSearchParams(window.location.search).get("studentId"):null,l=typeof window<"u"?new URLSearchParams(window.location.search).get("lessonId"):null;typeof window<"u"&&new URLSearchParams(window.location.search).get("classId");const[c,u]=p.useState(!0),[d,h]=p.useState(null),m=de(w=>w.liveClassSelectedClassId),f=de(w=>w.setLiveClassSelectedClassId),g=de(w=>w.liveClassIsActive),y=de(w=>w.setLiveClassIsActive),[k,S]=p.useState(0),[I,C]=p.useState([]),[T,_]=p.useState(new Map),E=Mc(),[R,B]=p.useState([]),[F,M]=p.useState({}),[v,z]=p.useState([]),[L,P]=p.useState(0),[j,A]=p.useState(!1),[U,N]=p.useState(null),[O,x]=p.useState(!1),[oe,pe]=p.useState("system"),[b,J]=p.useState(null),[D,G]=p.useState([]),[re,se]=p.useState(!1),[we,me]=p.useState(!1),le=async()=>{try{se(!0);const w=await fetch("/api/resources");if(w.ok){const V=await w.json();G(V)}}catch(w){console.warn("Error fetching library resources:",w)}finally{se(!1)}};Je.useEffect(()=>{Ds.getState().initTheme(),sn.getState().initFontSize();const w=V=>{(V.ctrlKey||V.metaKey)&&V.altKey&&(V.key==="+"||V.key==="="?(V.preventDefault(),sn.getState().increaseScale()):V.key==="-"||V.key==="_"?(V.preventDefault(),sn.getState().decreaseScale()):V.key==="0"&&(V.preventDefault(),sn.getState().resetScale()))};return window.addEventListener("keydown",w),()=>window.removeEventListener("keydown",w)},[]),Je.useEffect(()=>{O&&le()},[O]);const Ve=de(w=>w.lessons),St=de(w=>w.setLessons),{lessonsSearchQuery:Ut,setLessonsSearchQuery:vt,lessonsSortOrder:Ct,setLessonsSortOrder:Rt,filterEnrollment:Y,setFilterEnrollment:te,filterHasContent:ae,setFilterHasContent:Ne,filterThisMonth:Ue,setFilterThisMonth:He,copyingLessonId:dt,setCopyingLessonId:Te,filteredAndSortedLessons:$}=ov(Ve),[q,K]=p.useState([]),Z=de(w=>w.selectedLesson),X=de(w=>w.setSelectedLesson),Pe=de(w=>w.elements),Ze=de(w=>w.setElements),[Fe,st]=p.useState(!1),[ht,ge]=p.useState("idle"),[rt,_e]=p.useState(0),[Ws,Bn]=p.useState(0),[Gs,kt]=p.useState(""),[Ht,hn]=p.useState([]),[Qs,Js]=p.useState(!1),[Zs,Ys]=p.useState(!1),[Ks,Xs]=p.useState("agent"),[er,tr]=p.useState(!1),[ke,nr]=p.useState([]),[sr,rr]=p.useState([]),[fn,pn]=p.useState(null),[Vn,ir]=p.useState(""),qt=de(w=>w.classes),or=de(w=>w.setClasses),Re=de(w=>w.students),Un=de(w=>w.setStudents),{computerLabs:ar,fetchLabs:Hn,todaySchedules:lr,fetchTodaySchedules:Wt,classSchedulesMap:cr,fetchClassSchedules:xe,scheduleAttendanceMap:ur,fetchScheduleAttendance:dr,expandedScheduleId:hr,setExpandedScheduleId:fr,newScheduleDate:pr,setNewScheduleDate:mr,newScheduleLessonId:gr,setNewScheduleLessonId:xr}=KS(),[Mt,yr]=p.useState(null),br=p.useRef(null),wr=w=>{yr(w),br.current=w},[qn,Wn]=p.useState({}),[Sr,vr]=p.useState(null),Gn=p.useRef(null),[mn,gn]=p.useState(null),Ye=w=>{const V=fm(w);V&&gn({type:w,data:{...V.defaultData}})},Cr=async w=>{mn&&await Gn.current?.addElementAtCenter(mn.type,w),gn(null)},ye=de(w=>w.session),Ot=de(w=>w.setSession),Qn=de(w=>w.siteInfo),Jn=de(w=>w.setSiteInfo),[Le,ft]=p.useState("teacher"),[kr,Er]=p.useState(!0),[Zn,Gt]=p.useState(!0),[jr,pt]=p.useState("normal");p.useEffect(()=>{if(!ye)return;const w=async()=>{try{const W=await fetch("/api/db-status");if(W.ok){const Q=await W.json().catch(()=>({}));Q.status==="warning"||Q.warning?pt("warning"):pt("normal"),Gt(!0)}else W.status===429||W.status===503?(pt("warning"),Gt(!0)):(pt("error"),Gt(!1))}catch{pt("error"),Gt(!1)}};w();const V=setInterval(w,5e3);return()=>clearInterval(V)},[ye]),p.useEffect(()=>{(async()=>{try{const V=await fetch("/api/auth/session");if(V.ok){const W=await V.json();if(W.session)if(Ot(W.session),i){ft("student"),We("lesson");const Q=a||W.session.studentId;Q&&yn(Q),l&&X(l),Nt()}else ft(W.session.role),W.session.role==="student"&&W.session.studentId&&(yn(W.session.studentId),Nt())}}catch(V){console.warn("Session check failed",V)}finally{Er(!1)}})()},[]),p.useEffect(()=>{(async()=>{try{const V=await fetch("/api/site-settings");if(V.ok){const W=await V.json();Jn({siteName:W.siteName||"",slogan:W.slogan||"",logoUrl:W.logoUrl||null})}}catch(V){console.warn("Failed to fetch site settings:",V)}})()},[]);const Qt=de(w=>w.teacherTab),Ke=de(w=>w.setTeacherTab);p.useEffect(()=>{const w=()=>{const W=_l(window.location.hash);W&&W!==ve.getState().teacherTab&&Ke(W)};window.addEventListener("hashchange",w);const V=_l(window.location.hash);return V&&Ke(V),()=>window.removeEventListener("hashchange",w)},[Ke]),p.useEffect(()=>{const w=hv(Qt);window.location.hash!==w&&(window.location.hash=w)},[Qt,Ke]);const[ku,Nr]=p.useState(!1),[Eu,ju]=p.useState(!1),[Nu,Tu]=p.useState(!1);p.useEffect(()=>{ye?.subRole==="administrator"&&localStorage.getItem("edu_os_tour_completed")!=="true"&&Nr(!0)},[ye]);const Pu=async w=>{await Zt(),await mt(),await Wt().catch(()=>{}),f(w.classId),X(w.lessonId),y(!0),Ae(e==="zh"?"示范课堂准备就绪":"Demo Classroom Ready",e==="zh"?"示范班级与课件已加载,已自动开启授课状态!":"Demo class & courseware loaded. Live class session is now active!","success")};p.useEffect(()=>{Qt==="live_class"&&r(!0)},[Qt]);const{timelineSegments:Iu,activeSegmentId:Tr,setActiveSegmentId:xn,draggedSegmentIdx:Au,setDraggedSegmentIdx:zu,editorSaveStatus:_u,setEditorSaveStatus:Lu,editorLastSavedTime:Ru,setEditorLastSavedTime:Mu,editorPanelsExpanded:Ou,setEditorPanelsExpanded:Du,saveTimeline:Fu}=XS({selectedLesson:Z,lessons:Ve,setLessons:St}),[ue,yn]=p.useState(null),[Pr,$u]=p.useState(null),[Bu,Vu]=p.useState(!1),Ae=(w,V,W="info")=>{const Q=Math.random().toString(36).substring(2,9);ve.getState().addToast({id:Q,title:w,message:V,type:W}),setTimeout(()=>{ve.getState().removeToast(Q)},6e3)},qe=Le==="student"&&(!!ue&&!!Re.find(w=>w.id===ue)?.locked_lesson_id||Bu),Ir=()=>{Ae(e==="zh"?"🔒 全班专注锁定":"🔒 Class Focus Locked",e==="zh"?"老师已开启全班专注锁定,暂时无法切换页面,请跟随教师当前授课内容。":"The teacher locked the class focus. Navigation is disabled — please follow the current lesson.","warning")},mt=async()=>{try{const w=await fetch("/api/lessons");if(w.ok){const V=await w.json();St(V),!ve.getState().selectedLesson&&V.length>0&&X(V[0].id)}}catch(w){console.warn("Failed to fetch lessons",w)}},Co=p.useRef(()=>{}),ko=JS({lang:e,addToast:Ae,fetchLessons:mt,setSelectedLesson:X,setTeacherTab:Ke}),{isCourseWizardOpen:Dv,setIsCourseWizardOpen:Uu,wizardStep:Fv,setWizardStep:Hu,wizardCourseTitle:$v,setWizardCourseTitle:Bv,wizardCourseCategory:Vv,setWizardCourseCategory:Uv,wizardCourseDescription:Hv,setWizardCourseDescription:qv,wizardCourseContent:Wv,setWizardCourseContent:Gv,wizardCourseTimeline:Qv,setWizardCourseTimeline:Jv,wizardIsSubmitting:Zv,handleDeployWizardCourse:Yv}=ko,{plugins:Et,fetchPlugins:qu,aiProviders:gt,fetchAIProviders:Wu,testingProviderId:Gu,storeTab:Qu,setStoreTab:Ju,pluginCode:Zu,setPluginCode:Yu,installingPlugin:Ku,events:Xu,fetchEvents:ed,approvals:td,fetchApprovals:nd,scoreOverrides:sd,setScoreOverrides:rd,handleInstallPlugin:id,handleZipPluginUpload:od,handleTogglePlugin:ad,handleDeletePlugin:ld,handleApprove:cd,handleReject:ud}=QS({session:ye,host:E,lang:e,addToast:Ae,setChatLog:w=>Co.current(w),setTeacherTab:Ke,fetchLessons:mt}),[Dt,Eo]=p.useState(()=>typeof window>"u"?"":window.localStorage.getItem(Ll)||""),Ar=gt.some(w=>w.id===Dt)?Dt:gt[0]?.id||"",dd=gt.find(w=>w.id===Ar)||null,[jt,jo]=p.useState("dashboard"),No=p.useRef(qe),To=p.useRef(jt);p.useEffect(()=>{No.current=qe,To.current=jt},[qe,jt]),p.useEffect(()=>{qe&&(u(!0),jo("lesson"))},[qe]);const We=w=>{const V=typeof w=="function"?w(To.current):w;if(No.current&&V!=="lesson"){Ir();return}jo(w)},[Po,Jt]=p.useState("whiteboard"),[hd,fd]=p.useState(null),[xt,Yn]=p.useState(null),[pd,Io]=p.useState(!1),[md,Ao]=p.useState(null),[gd,zo]=p.useState("whiteboard"),[xd,yd]=p.useState("none"),[bd,wd]=p.useState("none"),[Sd,_o]=p.useState(!0);p.useEffect(()=>{jt!=="lesson"&&_o(!0)},[jt]);const Lo=ZS(),{isQuizGeneratorOpen:Kv,setIsQuizGeneratorOpen:vd,quizGeneratorClassId:Xv,setQuizGeneratorClassId:Cd,quizGenMode:eC,setQuizGenMode:kd,quizGenSelectedLessonId:tC,setQuizGenSelectedLessonId:Ed,quizGenTopic:nC,setQuizGenTopic:jd,isGeneratingSuggestions:sC,setIsGeneratingSuggestions:rC,suggestedObjectives:iC,setSuggestedObjectives:Nd,suggestedQuestions:oC,setSuggestedQuestions:Td,savingQuiz:aC,setSavingQuiz:lC,quizStudentAnswers:Pd,setQuizStudentAnswers:Ro,quizGenTimeLimit:cC,setQuizGenTimeLimit:uC,quizStudentAnswersRef:Id,subAssignmentTab:Ad,setSubAssignmentTab:Mo}=Lo,[zd,_d]=p.useState(""),[Ld,Rd]=p.useState("all"),[Md,Od]=p.useState("grid"),[Dd,Fd]=p.useState({}),[$d,Bd]=p.useState({}),[Vd,Ud]=p.useState({}),Oo=ev(Le,Pr,e),{studentNotifications:Hd,unreadNotifications:qd,readNotifications:Do,setReadNotifications:Kn,selectedNotificationForModal:Wd,setSelectedNotificationForModal:Gd,isNotificationsOpen:Qd,setIsNotificationsOpen:Jd}=Oo;p.useEffect(()=>{ue&&fetch(`/api/students/${ue}/read_notifications`).then(w=>w.ok?w.json():[]).then(w=>{Kn(new Set(w))}).catch(w=>{console.warn("Failed to load read notifications from DB",w),Kn(new Set)})},[ue]);const Zd=p.useRef(null),Yd=w=>{vr(w),Zd.current=w},[Kd,Xd]=p.useState({}),[eh,th]=p.useState({}),[dC,hC]=p.useState({}),[fC,pC]=p.useState({}),[nh,mC]=p.useState(null),[sh,rh]=p.useState("dueDate"),[gC,xC]=p.useState(null),[ih,oh]=p.useState({}),[ah,Fo]=p.useState(!1),[lh,$o]=p.useState(!1),[ch,zr]=p.useState(null),[uh,_r]=p.useState(null),[Lr,dh]=p.useState(null),hh=p.useRef(null),Bo=w=>{dh(w),hh.current=w};p.useEffect(()=>{typeof window<"u"&&window.localStorage.setItem(Ll,Dt)},[Dt]),p.useEffect(()=>{gt.length>0&&!gt.some(w=>w.id===Dt)&&Eo(gt[0].id)},[gt,Dt]);const fh=async(w,V,W)=>{try{if((await fetch(`/api/classes/${w}/schedules`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({lessonId:V,scheduledDate:W})})).ok)return await xe(w),!0}catch(Q){console.error("Quick schedule class failed",Q)}return!1},ph=async(w,V,W)=>{try{const Q=V||W||"Assignment",Ie=await fetch(`/api/classes/${w}/assignments/generate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({topic:Q})});if(Ie.ok){const yt=await Ie.json().catch(()=>({}));return await bn(w),yt.id||"assignment-created"}}catch(Q){console.error("Quick generate assignment failed",Q)}return null},mh=async(w,V)=>{try{const W=await fetch("/api/lessons",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({title:w,content:V})});if(W.ok){const Q=await W.json().catch(()=>({}));return await mt(),Q.id||"lesson-created"}}catch(W){console.error("Quick create lesson failed",W)}return""},gh=()=>{zl("class",e)},xh=async w=>{if(w){if(!w.name.toLowerCase().endsWith(".csv")){ge("error"),kt(e==="zh"?"只支持包含 .csv 后缀名的文件!":"Only files ending in .csv are supported!");return}ge("parsing"),kt("");try{const V=await lv(w,e);hn(V),ge("idle")}catch(V){ge("error"),kt(V.message||String(V))}}},yh=async()=>{if(Ht.length===0)return;ge("importing"),_e(0),Bn(Ht.length);const w=await cv(Ht,{lang:e,setImportProgress:_e,fetchLessons:mt});w.success?ge("success"):(ge("error"),kt(w.errorMsg||""))},bh=async w=>{const V=await fetch(`/api/lessons/${w}`,{method:"DELETE"});if(!V.ok){const W=await V.json().catch(()=>({}));throw new Error(W.error||"Failed to delete course")}await mt(),Z===w&&X(null),Ae(e==="zh"?"课程已删除":"Course Deleted",e==="zh"?"课程及其所有关联数据已被删除。":"The course and all associated data have been deleted.","success")},wh=async w=>{Te(w);try{const V=await fetch(`/api/lessons/${w}/clone`,{method:"POST"});if(!V.ok){const W=await V.json().catch(()=>({}));throw new Error(W.error||"Failed to copy course")}await mt(),Ae(e==="zh"?"复制成功":"Course Copied",e==="zh"?"课程已成功复制。":"Course has been copied successfully.","success")}catch(V){Ae(e==="zh"?"复制失败":"Copy Failed",V.message||(e==="zh"?"复制课程时发生错误。":"An error occurred while copying the course."),"error")}finally{Te(null)}},Vo=async()=>{try{const w=await fetch("/api/commands/registered");if(!w.ok)return;const V=w.headers.get("content-type");if(V&&V.includes("application/json")){const W=await w.json();Array.isArray(W)&&K(W)}}catch(w){console.warn("Failed to fetch registered commands",w)}},Sh=async w=>{if(ye)try{const V=await fetch(`/api/vfs${w?`?parentId=${w}`:""}`);if(V.ok){const W=await V.json();nr(W)}}catch(V){console.warn("Failed to fetch VFS nodes",V)}},vh=async()=>{try{const w=await fetch("/api/processes");w.ok&&rr(await w.json())}catch{}},Zt=async()=>{try{const w=await fetch("/api/classes");w.ok&&or(await w.json())}catch{}},Nt=async()=>{try{const w=await fetch("/api/students");w.ok&&Un(await w.json())}catch{}},Yt=async w=>{try{const V=await fetch(`/api/classes/${w}/students`);if(V.ok){const W=await V.json();Wn(Q=>({...Q,[w]:W}))}}catch{}},Rr=async w=>{try{const V=await fetch(`/api/classes/${w}/progress`);if(V.ok){const W=await V.json();th(Q=>({...Q,[w]:W}))}}catch{}},[Mr,Ch]=p.useState({}),bn=async w=>{try{const V=await fetch(`/api/classes/${w}/dashboard`);if(V.ok){const W=await V.json();Ch(Q=>({...Q,[w]:W}))}}catch{}},kh=iv({lang:e,classes:qt,classStudentsMap:qn,classDashboardMap:Mr,fetchClassStudents:Yt,fetchClassDashboard:bn,fetchClassProgress:Rr}),{isExportWeightModalOpen:Eh,setIsExportWeightModalOpen:Uo,exportClassId:jh,setExportClassId:Nh,exportClassName:Th,setExportClassName:Ph,quizzesWeight:Ih,setQuizzesWeight:Ho,assignmentsWeight:Ah,setAssignmentsWeight:qo,customCategoryOverrides:zh,setCustomCategoryOverrides:Wo,exportDropdownOpen:_h,setExportDropdownOpen:Lh,exportTooltipOpen:Rh,setExportTooltipOpen:Mh,loadingExportClassId:Oh,isExportingAllCombined:Dh,isGeneratingPDFReport:Fh,handleQuizzesWeightChange:$h,handleAssignmentsWeightChange:Bh,csvPreviewData:Vh,triggerExportForClass:Uh,handleExportGrades:Hh,handleGeneratePDFReport:qh,handleExportAllClassesCombined:Go,get30DayAverageWarning:Wh}=kh,Qo=YS({lang:e,classes:qt,expandedClassId:Mt,fetchClasses:Zt,fetchClassStudents:Yt,handleExportAllClassesCombined:Go}),{batchMode:Gh,setBatchMode:Qh,selectedClassIds:Jh,setSelectedClassIds:Zh,selectedStudentIds:Yh,setSelectedStudentIds:Kh,batchPicker:yC,setBatchPicker:bC,batchPickerLesson:wC,setBatchPickerLesson:SC,batchPickerDate:vC,setBatchPickerDate:CC,batchPickerTargetClass:kC,setBatchPickerTargetClass:EC,toggleClassSelection:Xh,toggleSelectAllClasses:ef,toggleStudentSelection:tf,toggleSelectAllStudents:nf,handleBatchDeleteClasses:sf,handleBatchExportClasses:rf,handleBatchSetPasscode:of,handleBatchScheduleClasses:af,handleBatchDeleteStudents:lf,handleBatchResetPassword:cf,handleBatchTransferStudents:uf,handleBatchSetLockedLesson:df,confirmBatchPicker:jC}=Qo,Or=async w=>{try{const V=await fetch(`/api/students/${w}/dashboard`);if(V.ok){const W=await V.json();$u(W),W.profile&&W.profile.locked_lesson_id&&(X(W.profile.locked_lesson_id),We("lesson"))}}catch{}},hf=async(w=!1)=>{if(!xt)return;const W=xt?.content&&xt.content.startsWith('{"quizType":"mcq_learning_objectives"')?JSON.stringify(Id.current):"Submitted via Whiteboard";try{(await fetch(`/api/assignments/${xt.id}/submissions`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({studentId:ue,content:W})})).ok&&(w&&alert("Time is up! Your assessment was successfully submitted automatically."),await Or(ue),We("dashboard"),Yn(null))}catch(Q){console.error(Q)}};p.useEffect(()=>{if(ye&&Le==="student"&&ue){Or(ue);const w=Re.find(V=>V.id===ue);w&&w.locked_lesson_id&&(X(w.locked_lesson_id),We("lesson"))}},[ye,Le,ue,Re]);const ff=p.useRef(Le),pf=p.useRef(ue),mf=p.useRef(e),gf=p.useRef(Re),xf=p.useRef(Ae),Xn=p.useRef(new Set);p.useRef(new Set),p.useEffect(()=>{ff.current=Le},[Le]),p.useEffect(()=>{pf.current=ue},[ue]),p.useEffect(()=>{mf.current=e},[e]),p.useEffect(()=>{gf.current=Re},[Re]),p.useEffect(()=>{xf.current=Ae},[Ae]),p.useEffect(()=>{if(!E.isInitialized()||Et.length===0)return;const w=Ee.getState(),V=Et.filter(Q=>Q.status==="active");for(const Q of V){if(!Q.has_frontend||Xn.current.has(Q.id))continue;const Ie=w.activePlugins.find(bt=>bt.id===Q.id),yt=!!(Ie&&Q.version&&Ie.version!==Q.version);if(!(!Ie||yt||Ie.state!==be.ACTIVE&&Ie.state!==be.ACTIVATING))continue;Xn.current.add(Q.id);const Ko=()=>{if(!w.activePlugins.find(bt=>bt.id===Q.id))w.addPlugin({id:Q.id,name:Q.name,version:Q.version,state:be.INSTALLED,executionMode:"inline"});else if(yt)try{Ee.setState(bt=>({activePlugins:bt.activePlugins.map(wn=>wn.id===Q.id?{...wn,version:Q.version,name:Q.name}:wn)}))}catch{}try{const bt=JSON.parse(Q.manifest);E.activateRemotePlugin(Q.id,bt).catch(wn=>{console.error(`[App] Failed to activate remote plugin "${Q.name}":`,wn)}).finally(()=>{Xn.current.delete(Q.id)})}catch(bt){Xn.current.delete(Q.id),console.error(`[App] Failed to parse manifest for plugin "${Q.name}":`,bt)}};Ie&&Ie.state===be.ACTIVE&&yt?E.deactivatePlugin(Q.id).catch(()=>{}).finally(Ko):Ko()}const W=Et.filter(Q=>Q.status!=="active");for(const Q of W){if(!Q.has_frontend)continue;const Ie=w.activePlugins.find(yt=>yt.id===Q.id);Ie&&Ie.state===be.ACTIVE&&E.deactivatePlugin(Q.id).catch(yt=>{console.error(`[App] Failed to deactivate remote plugin "${Q.name}":`,yt)})}},[Et,E]),Je.useEffect(()=>{if(!E.isInitialized()||Et.length===0)return;const w=Ee.getState();for(const V of Et)V.status==="active"&&(w.dashboardVisibility.has(V.id)||w.setDashboardVisibility(V.id,!0))},[Et,E]);const yf=async w=>{if(Le==="student"&&ue&&Z)try{await fetch(`/api/students/${ue}/progress`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({lessonId:Z,completed:w===100,progressPercent:w})})}catch(V){console.error("Failed to update student progress:",V)}},bf=async(w,V)=>{try{const W=await fetch(`/api/classes/${w}/lessons/${V}/progress`);W.ok&&z(await W.json())}catch{}};p.useEffect(()=>{m&&Z?bf(m,Z):z([])},[m,Z]),p.useEffect(()=>{m&&Yt(m)},[m]);const wf=async w=>{try{const V=await fetch(`/api/students/${w}/progress`);if(V.ok){const W=await V.json();Xd(Q=>({...Q,[w]:W}))}}catch{}},Jo=async w=>{try{const V=await fetch(`/api/processes/${w}/logs`);if(V.ok){const W=await V.json();ir(W.logs||""),pn(w)}}catch{}},Zo=p.useRef(""),Tt=async w=>{try{const V=await fetch(`/api/lessons/${w}/whiteboard`);if(!V.ok)return;const W=await V.json(),Q=JSON.stringify(W);Q!==Zo.current&&(Zo.current=Q,Ze(W))}catch{}},Sf=p.useRef(null);p.useRef(null);const vf=p.useRef(null);p.useEffect(()=>{Sf.current=Z},[Z]),p.useEffect(()=>{vf.current=xt},[xt]),nu(ye);const{chatLog:Cf,setChatLog:kf,input:Ef,setInput:jf,loading:Nf,chatAttachments:Tf,setChatAttachments:Pf,handleChatFileChange:If,handleChatDrop:Af,handleSend:zf,handleClearAgentMemory:_f}=Bw({lang:e,t:n,selectedLesson:Z,effectiveAgentProviderId:Ar,expandedClassId:Mt,fetchLessons:mt,fetchClasses:Zt,fetchStudents:Nt,fetchClassStudents:Yt,fetchClassProgress:Rr,fetchClassDashboard:bn,fetchElements:Tt});Co.current=kf,$w({session:ye,showProcessLogs:fn,activeStudentId:ue,currentVfsParent:Lr,selectedLesson:Z,selectedAssignment:xt,expandedClassId:Mt,fetchLessons:mt,fetchPlugins:qu,fetchRegisteredCommands:Vo,fetchEvents:ed,fetchApprovals:nd,fetchProcesses:vh,fetchClasses:Zt,fetchTodaySchedules:Wt,fetchStudents:Nt,fetchLabs:Hn,fetchVfs:Sh,fetchProcessLogs:Jo,fetchClassStudents:Yt,fetchElements:Tt});const{socketRef:Lf}=WS({session:ye,host:E,activeRole:Le,activeStudentId:ue,selectedLesson:Z,activeSegmentId:Tr,studentViewStatus:jt,lang:e,students:Re,addToast:Ae,setOnlineStudentIds:B,setActiveStudentLessons:M,setLessons:St,setActiveSegmentId:xn,setLiveClassStudentProgress:z,setLiveClassAcknowledgedMap:_,setLiveClassFeed:C,setSelectedLesson:X,setStudentViewStatus:We,studentLessonTab:Po,setStudentLessonTab:Jt,selectedAssignment:xt,setSelectedAssignment:Yn,setLocalProgressPercent:P,fetchStudentDashboard:Or,fetchStudents:Nt,fetchElements:Tt}),Rf=w=>{zl(w,e)},Mf=async w=>{$o(!0),zr(null),_r(null);try{const V=await av(w,{lang:e,fetchClasses:Zt,fetchStudents:Nt});_r(V.message)}catch(V){zr(V.message||String(V))}finally{$o(!1)}},Of=()=>{t(e==="zh"?"en":"zh")},Df=p.useCallback(w=>{Ot(w),w.role==="teacher"?(ft("teacher"),Ke("dashboard")):(ft("student"),yn(w.studentId),Nt())},[]),Yo=async()=>{try{await fetch("/api/auth/logout",{method:"POST"})}catch(w){console.error("Logout failed",w)}Ot(null)},[Ff,Dr]=p.useState(!1);return p.useEffect(()=>{if(!i)return;const w=new ga;w.requestHandshake();const V=w.onMessage(W=>{switch(W.type){case"TEACHER_INIT_STATE":{const Q=W.payload;Q.selectedLesson&&(X(Q.selectedLesson),Tt(Q.selectedLesson)),Q.activeSegmentId&&xn(Q.activeSegmentId),Q.activeTab&&Jt(Q.activeTab),Q.liveClassTimeRemaining!==void 0&&S(Q.liveClassTimeRemaining),Q.fullscreenElementId!==void 0&&(on.getState().setRemoteFullscreenElementId(Q.fullscreenElementId),Q.fullscreenElementId&&Jt("whiteboard")),We("lesson");break}case"TEACHER_CHANGE_LESSON":{c&&W.payload.lessonId&&(X(W.payload.lessonId),Tt(W.payload.lessonId),We("lesson"));break}case"TEACHER_CHANGE_SEGMENT":{c&&W.payload.segmentId&&xn(W.payload.segmentId);break}case"TEACHER_CHANGE_TAB":{c&&W.payload.tab&&Jt(W.payload.tab);break}case"TEACHER_LOCK_CLASS":{Vu(!!W.payload.locked),W.payload.locked?(u(!0),We("lesson"),Ae(e==="zh"?"🔒 全班专注锁定":"🔒 Class Focus Lock",e==="zh"?"老师已开启全班专注锁定,界面将保持同步授课。":"Teacher locked screen for class.","warning")):Ae(e==="zh"?"🔓 屏幕已解锁":"🔓 Screen Unlocked",e==="zh"?"老师已解除锁定,您可以自由浏览或答题。":"Screen unlocked.","info");break}case"TEACHER_PICK_STUDENT":{(!ue||ue===W.payload.studentId||a===W.payload.studentId)&&h(W.payload);break}case"TEACHER_SYNC_TIMER":{S(W.payload.timeRemaining);break}case"TEACHER_PING_STUDENT":{(!ue||ue===W.payload.studentId)&&Ae(e==="zh"?"⚠️ 课堂提醒":"⚠️ Classroom Alert",W.payload.message||(e==="zh"?"老师提醒您集中注意力跟上教学进度!":"Please keep up with class!"),"warning");break}case"TEACHER_BROADCAST_FULLSCREEN":{const{elementId:Q,lessonId:Ie}=W.payload;on.getState().setRemoteFullscreenElementId(Q),Q&&(Ie&&Ie!==Z&&(X(Ie),Tt(Ie)),We("lesson"),Jt("whiteboard"));break}}});return()=>{V(),w.destroy()}},[i,c,ue,a,e]),kr?o.jsxs("div",{className:"min-h-screen bg-slate-900 flex flex-col items-center justify-center p-4 relative overflow-hidden font-sans",children:[o.jsx(Gi,{size:48,className:"text-indigo-500 animate-spin"}),o.jsx("span",{className:"text-white text-sm mt-4 font-semibold tracking-wide",children:e==="zh"?"正在连接安全核心数据库...":"Connecting Secure OS Core Database..."})]}):ye?o.jsx(o.Fragment,{children:o.jsxs("div",{className:"flex h-screen bg-app text-main font-sans transition-colors duration-150",children:[o.jsxs("div",{className:"flex-1 flex flex-col bg-app h-full overflow-hidden",children:[ye?.role==="teacher"&&Le==="student"&&!i&&o.jsxs("div",{className:"bg-gradient-to-r from-amber-500 via-amber-600 to-orange-500 text-white px-6 py-1.5 flex items-center justify-between text-xs font-medium shadow-sm z-30 shrink-0 border-b border-amber-600/30",children:[o.jsxs("div",{className:"flex items-center gap-2.5",children:[o.jsxs("span",{className:"bg-black/20 text-amber-100 px-2 py-0.5 rounded font-bold uppercase tracking-wider text-xs flex items-center gap-1",children:[o.jsx(Ms,{size:12}),e==="zh"?"学生模拟模式":"Student View Mode"]}),o.jsx("span",{children:e==="zh"?`您当前正在以学生身份(${Re.find(w=>w.id===ue)?.name||"未选择"})预览系统界面与交互。`:`You are currently previewing the platform as student (${Re.find(w=>w.id===ue)?.name||"None"}).`})]}),o.jsxs("button",{type:"button",onClick:()=>ft("teacher"),className:"bg-white text-amber-800 hover:bg-amber-50 active:bg-amber-100 font-bold px-3 py-1 rounded-md shadow-xs transition-all flex items-center gap-1.5 cursor-pointer text-xs",children:[o.jsx(Hi,{size:13}),e==="zh"?"退出模拟并返回教师端":"Exit Student View"]})]}),i?o.jsxs("header",{className:"h-13 bg-surface/95 backdrop-blur-md border-b border-theme px-4 flex items-center justify-between z-20 shrink-0 select-none shadow-xs",children:[o.jsxs("div",{className:"flex items-center gap-3",children:[o.jsx("div",{className:"w-8 h-8 rounded-lg bg-gradient-to-tr from-pink-500 to-rose-600 flex items-center justify-center text-white font-black shadow-sm text-sm",children:"🎓"}),o.jsxs("div",{children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("h1",{className:"text-sm font-black text-main tracking-wide",children:e==="zh"?"互动课堂 · 学生端":"Interactive Classroom · Student Client"}),o.jsxs("span",{className:"flex items-center gap-1 text-xs font-bold text-emerald-600 dark:text-emerald-400 bg-emerald-500/10 border border-emerald-500/20 px-2 py-0.5 rounded-full",children:[o.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-emerald-500 animate-pulse"}),e==="zh"?"已与教师中控台实时联动":"Synced with Teacher"]})]}),o.jsxs("div",{className:"text-xs text-muted flex items-center gap-2",children:[o.jsx("span",{children:ue?`学生: ${Re.find(w=>w.id===ue)?.name||ue}`:"学生端"}),o.jsx("span",{children:"•"}),o.jsx("span",{children:Z?`课节: ${Ve.find(w=>w.id===Z)?.title||Z}`:"等待教师推流课节..."})]})]})]}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsxs("button",{type:"button",onClick:()=>{if(qe){Ir();return}u(!c)},disabled:qe,className:`px-3 py-1.5 rounded-lg text-xs font-bold border transition-all flex items-center gap-1.5 shadow-2xs ${qe?"cursor-not-allowed":"cursor-pointer"} ${c?"bg-indigo-50 dark:bg-indigo-950/40 text-indigo-600 dark:text-indigo-400 border-indigo-200 dark:border-indigo-800":"bg-surface text-muted border-theme hover:text-main"} ${qe?"opacity-70":""}`,title:qe?e==="zh"?"全班专注锁定中,已强制跟随教师步调":"Class focus is locked; following the teacher is enforced":e==="zh"?"开启后,教师端切换课节/环节/Tab时,学生端将自动同步跟随":"Follow teacher navigation",children:[o.jsx(ql,{size:12,className:c?"animate-spin":""}),o.jsx("span",{children:e==="zh"?`跟随教师步调: ${c?"开":"关"}`:`Follow Teacher: ${c?"ON":"OFF"}`})]}),o.jsx(Xl,{lang:e}),o.jsx("button",{type:"button",onClick:()=>{document.fullscreenElement?document.exitFullscreen().catch(()=>{}):document.documentElement.requestFullscreen().catch(()=>{})},className:"p-1.5 text-muted hover:text-main rounded-lg border border-theme hover:bg-surface-secondary transition-colors cursor-pointer",title:e==="zh"?"切换全屏":"Toggle Fullscreen",children:o.jsx(bp,{size:14})}),o.jsx("button",{type:"button",onClick:()=>window.close(),className:"px-2.5 py-1.5 text-xs font-bold text-rose-600 hover:text-rose-700 bg-rose-50 dark:bg-rose-950/30 border border-rose-200 dark:border-rose-900 rounded-lg transition-colors cursor-pointer",title:e==="zh"?"关闭学生端Tab":"Close Tab",children:e==="zh"?"关闭Tab":"Close Tab"})]})]}):o.jsx(am,{activeRole:Le,setActiveRole:ft,lang:e,teacherTab:Qt,studentViewStatus:jt,session:ye,activeStudentId:ue,students:Re,studentDashboardData:Pr,isNotificationsOpen:Qd,studentNotifications:Hd,unreadNotifications:qd,readNotifications:Do,selectedNotificationForModal:Wd,dbConnected:Zn,dbStatus:jr,siteInfo:Qn,setActiveStudentId:yn,setReadNotifications:Kn,setIsSystemResourceLibraryOpen:x,setProfileOpen:Dr,setTeacherTab:Ke,setStudentViewStatus:We,setIsNotificationsOpen:Jd,setSelectedNotificationForModal:Gd,handleLogout:Yo,toggleLanguage:Of,isStudentLocked:qe,onBlockedNavigate:Ir}),o.jsx(cm,{open:Ff,session:ye,lang:e,onClose:()=>Dr(!1),onSaved:w=>{ye&&Ot({...ye,name:w}),Dr(!1)},onAvatar:w=>{ye&&Ot({...ye,avatar:w??void 0})}}),o.jsx(i0,{students:Re,activeStudentId:ue,isStudentLocked:qe,studentViewStatus:jt,studentDashboardData:Pr,readNotifications:Do,setReadNotifications:Kn,addToast:Ae,lang:e,setSelectedLesson:X,setStudentViewStatus:We,setSelectedAssignment:Yn,setQuizStudentAnswers:Ro,setSubAssignmentTab:Mo,lessons:Ve,selectedLesson:Z,studentFullscreenPanel:bd,setStudentFullscreenPanel:wd,timelineSegments:Iu,activeSegmentId:Tr,setActiveSegmentId:xn,localProgressPercent:L,setLocalProgressPercent:P,updateStudentProgress:yf,isStudentLessonContentCollapsed:Sd,setIsStudentLessonContentCollapsed:_o,studentLessonTab:Po,setStudentLessonTab:Jt,elements:Pe,activeRole:Le,fetchElements:Tt,currentVfsParent:Lr,setCurrentVfsParent:Bo,vfsNodes:ke,studentSelectedCourseware:hd,setStudentSelectedCourseware:fd,selectedAssignment:xt,quizStudentAnswers:Pd,submitQuizAssignment:hf,subAssignmentTab:Ad,mainNavCollapsed:s,setMainNavCollapsed:r,teacherTab:Qt,setTeacherTab:Ke,session:ye,todaySchedules:lr,t:n,classes:qt,approvals:td,processes:sr,isApprovalsCollapsed:Eu,setIsApprovalsCollapsed:ju,isProcessesCollapsed:Nu,setIsProcessesCollapsed:Tu,scoreOverrides:sd,setScoreOverrides:rd,handleApprove:cd,handleReject:ud,showLogs:er,setShowLogs:tr,processLogsContent:Vn,showProcessLogs:fn,fetchProcessLogs:Jo,setShowProcessLogs:pn,handleQuickScheduleClass:fh,handleQuickGenerateAssignment:ph,handleQuickCreateLesson:mh,setActiveRole:ft,editorSaveStatus:_u,setEditorSaveStatus:Lu,editorLastSavedTime:Ru,setEditorLastSavedTime:Mu,setIsLessonPreviewVisible:Io,setPreviewLessonTab:zo,setPreviewSelectedCourseware:Ao,handlePaletteActivate:Ye,draggedSegmentIdx:Au,setDraggedSegmentIdx:zu,saveTimeline:Fu,editorPanelsExpanded:Ou,setEditorPanelsExpanded:Du,whiteboardRef:Gn,paletteEdit:mn,handlePaletteConfirm:Cr,setPaletteEdit:gn,plugins:Et,liveClassSelectedClassId:m,setLiveClassSelectedClassId:f,liveClassIsActive:g,setLiveClassIsActive:y,liveClassTimeRemaining:k,setLiveClassTimeRemaining:S,liveClassFeed:I,setLiveClassFeed:C,liveClassAcknowledgedMap:T,setLiveClassAcknowledgedMap:_,onlineStudentIds:R,activeStudentLessons:F,liveClassStudentProgress:v,storeTab:Qu,setStoreTab:Ju,pluginCode:Zu,setPluginCode:Yu,installingPlugin:Ku,onInstall:id,onZipUpload:od,onToggle:ad,onDelete:ld,lessonsSearchQuery:Ut,setLessonsSearchQuery:vt,lessonsSortOrder:Ct,setLessonsSortOrder:Rt,filteredLessons:$,onOpenImportLessons:()=>{ge("idle"),_e(0),Bn(0),kt(""),hn([]),st(!0)},onOpenCourseWizard:()=>{Hu(1),Uu(!0)},onViewCourse:w=>{Ke("lesson_editor"),X(w)},onDeleteCourse:bh,onCopyCourse:wh,filterEnrollment:Y,setFilterEnrollment:te,filterHasContent:ae,setFilterHasContent:Ne,filterThisMonth:Ue,setFilterThisMonth:He,copyingLessonId:dt,onSchedulesUpdated:Wt,onLogout:Yo,aiProviders:gt,testingProviderId:Gu,onAIProvidersChanged:Wu,onTriggerTour:()=>Nr(!0),siteInfo:Qn,onSiteInfoChanged:Jn,computerLabs:ar,onRefresh:Hn,registeredCommands:q,fetchRegisteredCommands:Vo,batchMode:Gh,selectedClassIds:Jh,setSelectedClassIds:Zh,setSelectedStudentIds:Kh,setBatchMode:Qh,expandedClassId:Mt,setExpandedClassId:wr,exportTooltipOpen:Rh,setExportTooltipOpen:Mh,exportDropdownOpen:_h,setExportDropdownOpen:Lh,isExportingAllCombined:Dh,loadingExportClassId:Oh,classStudentsMap:qn,setClassStudentsMap:Wn,expandedStudentId:Sr,setExpandedStudentId:Yd,selectedStudentIds:Yh,rosterViewMode:Md,setRosterViewMode:Od,rosterSearchQuery:zd,setRosterSearchQuery:_d,rosterTagFilter:Ld,setRosterTagFilter:Rd,toggleSelectAllStudents:nf,handleBatchDeleteStudents:lf,handleBatchResetPassword:cf,handleBatchTransferStudents:uf,handleBatchSetLockedLesson:df,toggleStudentSelection:tf,get30DayAverageWarning:Wh,studentProgressMap:Kd,studentActiveTabs:Vd,setStudentActiveTabs:Ud,setStudents:Un,fetchClassStudents:Yt,fetchStudents:Nt,parseCSV:Kp,setImportError:zr,setImportSuccess:_r,setShowImportModal:Fo,fetchClasses:Zt,classSubmissionFilters:Dd,setClassSubmissionFilters:Fd,classActiveTabs:$d,setClassActiveTabs:Bd,classProgressMap:eh,classSchedulesMap:cr,classDashboardMap:Mr,assignmentSortOrder:sh,setAssignmentSortOrder:rh,isGeneratingPDFReport:Fh,handleGeneratePDFReport:qh,setExportClassId:Nh,setExportClassName:Ph,setQuizzesWeight:Ho,setAssignmentsWeight:qo,setCustomCategoryOverrides:Wo,setIsExportWeightModalOpen:Uo,isGeneratingAssignment:nh,setQuizGeneratorClassId:Cd,setQuizGenMode:kd,setQuizGenSelectedLessonId:Ed,setQuizGenTopic:jd,setSuggestedObjectives:Nd,setSuggestedQuestions:Td,setIsQuizGeneratorOpen:vd,setActiveStudentId:yn,isGrading:ih,setIsGrading:oh,fetchClassDashboard:bn,newScheduleDate:pr,setNewScheduleDate:mr,newScheduleLessonId:gr,setNewScheduleLessonId:xr,expandedScheduleId:hr,setExpandedScheduleId:fr,fetchScheduleAttendance:dr,scheduleAttendanceMap:ur,toggleSelectAllClasses:ef,handleBatchDeleteClasses:sf,handleBatchExportClasses:rf,handleBatchSetPasscode:of,handleBatchScheduleClasses:af,handleExportAllClassesCombined:Go,triggerExportForClass:Uh,fetchClassProgress:Rr,fetchClassSchedules:xe,fetchStudentProgress:wf,toggleClassSelection:Xh,socketRef:Lf,setShowCoursewareHub:me,fetchTodaySchedules:Wt})]}),o.jsx(Sw,{showRightSidebar:Zs,setShowRightSidebar:Ys,rightSidebarTab:Ks,setRightSidebarTab:Xs,effectiveAgentProviderId:Ar,agentProviderId:Dt,setAgentProviderId:Eo,aiProviders:gt,selectedAgentProvider:dd,chatLog:Cf,loading:Nf,input:Ef,setInput:jf,handleSend:zf,chatAttachments:Tf,setChatAttachments:Pf,handleChatFileChange:If,handleChatDrop:Af,onClearAgentMemory:_f,events:Xu,lang:e,t:n}),o.jsx(Rw,{lang:e,t:n,courseWizard:ko,quizGenerator:Lo,classBatch:Qo,studentNotificationsHook:Oo,showImportModal:ah,setShowImportModal:Fo,handleImportFile:Mf,importError:ch,importSuccess:uh,isImporting:lh,downloadCSVTemplate:Rf,addToast:Ae,generateTemplateContent:qb,isImportLessonsOpen:Fe,setIsImportLessonsOpen:st,importStatus:ht,setIsDraggingImport:Js,handleCSVFileChange:xh,downloadCsvTemplate:gh,isDraggingImport:Qs,previewImportData:Ht,setPreviewImportData:hn,setImportStatus:ge,importProgress:rt,importProgressTotal:Ws,importErrorMsg:Gs,setImportErrorMsg:kt,handleCSVImportSubmit:yh,lessons:Ve,fetchClassDashboard:bn,isLessonPreviewVisible:pd,setIsLessonPreviewVisible:Io,selectedLesson:Z,previewFullscreenPanel:xd,setPreviewFullscreenPanel:yd,previewLessonTab:gd,setPreviewLessonTab:zo,activeRole:Le,elements:Pe,activeSegmentId:Tr,setActiveSegmentId:xn,fetchElements:Tt,currentVfsParent:Lr,setCurrentVfsParent:Bo,vfsNodes:ke,previewSelectedCourseware:md,setPreviewSelectedCourseware:Ao,showProcessLogs:fn,setShowProcessLogs:pn,processLogsContent:Vn,isCloudDriveOpen:j,setIsCloudDriveOpen:A,cloudDrivePreviewNode:U,setCloudDrivePreviewNode:N,isSystemResourceLibraryOpen:O,setIsSystemResourceLibraryOpen:x,systemResourceTab:oe,setSystemResourceTab:pe,selectedLibraryResourceId:b,setSelectedLibraryResourceId:J,loadingLibraryResources:re,libraryResources:D,fetchLibraryResources:le,classes:qt,expandedClassId:Mt,isExportWeightModalOpen:Eh,setIsExportWeightModalOpen:Uo,quizzesWeight:Ih,setQuizzesWeight:Ho,assignmentsWeight:Ah,setAssignmentsWeight:qo,handleQuizzesWeightChange:$h,handleAssignmentsWeightChange:Bh,customCategoryOverrides:zh,setCustomCategoryOverrides:Wo,classDashboardMap:Mr,exportClassId:jh,exportClassName:Th,csvPreviewData:Vh,handleExportGrades:Hh,setSelectedAssignment:Yn,setStudentViewStatus:We,setQuizStudentAnswers:Ro,setSubAssignmentTab:Mo,isTourOpen:ku,setIsTourOpen:Nr,handleSeedSuccess:Pu,setTeacherTab:Ke,showCoursewareHub:we,setShowCoursewareHub:me}),d&&o.jsx("div",{className:"fixed inset-0 z-[9999] bg-black/60 backdrop-blur-xs flex items-center justify-center p-4 animate-in fade-in duration-200",children:o.jsxs("div",{className:"bg-surface border-2 border-amber-500 rounded-2xl shadow-2xl p-6 max-w-md w-full text-center space-y-4 animate-in zoom-in-95 duration-300",children:[o.jsx("div",{className:"w-16 h-16 bg-amber-500/20 text-amber-500 rounded-full flex items-center justify-center mx-auto animate-bounce",children:o.jsx(Mn,{size:36})}),o.jsx("h3",{className:"text-xl font-black text-main",children:e==="zh"?"⚡️ 闪电点名:老师选中了你!":"⚡️ Classroom Pick: Teacher Selected You!"}),o.jsx("p",{className:"text-sm text-muted",children:e==="zh"?o.jsxs(o.Fragment,{children:["老师在课堂点名中抽中了【",o.jsx("span",{className:"font-bold text-amber-600 dark:text-amber-400",children:d.studentName}),"】,请立即集中注意力参与课堂互动回答!"]}):o.jsxs(o.Fragment,{children:["The teacher selected"," ",o.jsx("span",{className:"font-bold text-amber-600 dark:text-amber-400",children:d.studentName})," ","to answer in class. Please respond now!"]})}),o.jsx("div",{className:"pt-2",children:o.jsxs("button",{type:"button",onClick:()=>{const w=new ga;w.acknowledgePick(d.studentId),w.destroy(),h(null),Ae(e==="zh"?"🙋‍♂️ 已确认答到":"🙋‍♂️ Acknowledged",e==="zh"?"已向老师中控台发送举手答到信号!":"Sent acknowledge signal to teacher!","success")},className:"w-full py-3 bg-gradient-to-r from-amber-500 to-orange-600 hover:from-amber-600 hover:to-orange-700 text-white font-black text-sm rounded-xl shadow-lg shadow-amber-500/30 transition-all active:scale-95 cursor-pointer flex items-center justify-center gap-2",children:[o.jsx(On,{size:18}),o.jsx("span",{children:e==="zh"?"🙋‍♂️ 我已准备好 / 确认答到 (反馈给老师)":"🙋‍♂️ Ready / Acknowledge to Teacher"})]})})]})}),o.jsx(ww,{}),o.jsx(uv,{})]})}):o.jsx(Xp,{onLoginSuccess:Df,lang:e})}class pv{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 mv=/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[0-9a-f]{4}-[0-9a-f]{12}\./i;function gv(e,t){const n=t+".";return e.startsWith(n)||mv.test(e)?e:n+e}let xv=0;function yv(e,t){const s={student_id:"teacher_preview",student_name:"Teacher (Preview)",class_id:"",attempt_id:`att_srcdoc_${t}_${Date.now()}_${++xv}`},r={uuid:t,name:"Whiteboard HTML Applet"};return`<!DOCTYPE html>
177
- <html><head>
178
- <script>
179
- window.__LMS_STUDENT__ = ${JSON.stringify(s)};
180
- window.__LMS_COURSEWARE__ = ${JSON.stringify(r)};
181
- (function() {
182
- try {
183
- // Override window.postMessage (self-targeting, always works)
184
- var origPM = window.postMessage;
185
- window.postMessage = function(msg, targetOrigin, transfer) {
186
- var origin = (targetOrigin === 'null' || targetOrigin === null) ? '*' : targetOrigin;
187
- try { return origPM.call(this, msg, origin, transfer); }
188
- catch(err) { if (err.name === 'SyntaxError') return origPM.call(this, msg, '*', transfer); throw err; }
189
- };
190
- // Shadow window.parent / window.top with Proxy to intercept .postMessage()
191
- // Direct assignment (window.parent.postMessage = ...) silently fails on cross-origin WindowProxy
192
- function proxyWin(realRef, propName) {
193
- try {
194
- var safePost = function(msg, targetOrigin, transfer) {
195
- var origin = (targetOrigin === 'null' || targetOrigin === null) ? '*' : targetOrigin;
196
- try { return realRef.postMessage.call(realRef, msg, origin, transfer); }
197
- catch(err) { if (err.name === 'SyntaxError') return realRef.postMessage.call(realRef, msg, '*', transfer); throw err; }
198
- };
199
- var px = new Proxy(realRef, {
200
- get: function(t, p) {
201
- if (p === 'postMessage') return safePost;
202
- try { var v = t[p]; return typeof v === 'function' ? v.bind(t) : v; } catch(e) { return undefined; }
203
- }
204
- });
205
- Object.defineProperty(window, propName, { get: function() { return px; }, configurable: true });
206
- } catch(e) {}
207
- }
208
- if (window.parent && window.parent !== window) proxyWin(window.parent, 'parent');
209
- try { if (window.top && window.top !== window) proxyWin(window.top, 'top'); } catch(e) {}
210
- } catch(e) {}
211
- })();
212
- <\/script>
213
- <script src="/bridge.js?cw=${encodeURIComponent(t||"")}"><\/script>
214
- </head><body>
215
- ${e||""}
216
- </body></html>`}class bv{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 ks=new bv,wv=4;let ds=0;const Ui=new Set;function Rl(){return ds>=wv?null:(ds+=1,()=>{ds=Math.max(0,ds-1);for(const e of Ui)e()})}function Sv(e){return Ui.add(e),()=>{Ui.delete(e)}}function vv(e,t){const[n,s]=p.useState(!e),[r,i]=p.useState(!1),a=p.useRef(null);return p.useEffect(()=>{if(!e||n)return;const l=t.current;if(!l)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(l),()=>c.disconnect()},[e,n,t]),p.useEffect(()=>{if(!n){a.current?.(),a.current=null,i(!1);return}const l=Rl();if(l)a.current=l,i(!0);else{const c=Sv(()=>{const u=Rl();u&&(c(),a.current=u,i(!0))});return()=>c()}},[n]),p.useEffect(()=>()=>{a.current?.()},[]),r}function Ft(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){const t=Number(e);return Number.isFinite(t)?t:void 0}}const Cv=new Set(["guest","teacher","teacher_preview"]);function kv(e){const t=e.filter(i=>typeof i.score=="number").slice().sort((i,a)=>a.score-i.score),n=new Map;let s=0,r=null;return t.forEach((i,a)=>{const l=i.score;(r===null||l<r)&&(s=a+1,r=l),n.set(i.attemptId,s)}),n}function Ev(e,t){return e.slice().sort((n,s)=>{const r=t.get(n.attemptId)??Number.MAX_SAFE_INTEGER,i=t.get(s.attemptId)??Number.MAX_SAFE_INTEGER;return r!==i?r-i:(n.studentName||n.studentId).localeCompare(s.studentName||s.studentId,"zh-Hans-CN")})}function jv({data:e,lessonId:t,elementId:n,className:s,title:r,lazy:i=!0}){const a=Je.useRef(null),l=vv(i,a),{theme:c}=Ds(),{scale:u}=sn(),d=de(P=>P.session),[h,m]=p.useState([]),[f,g]=p.useState(!1);p.useEffect(()=>{const P=e.coursewareUuid;if(!P)return;let j=!1;const A=()=>{fetch(`/api/courseware/attempts?coursewareUuid=${encodeURIComponent(P)}`).then(x=>x.ok?x.json():[]).then(x=>{j||m(Array.isArray(x)?x:[])}).catch(()=>{})};A();let U=null,N=null;const O=()=>A();try{U=MS(),U.on("courseware-attempt-updated",O)}catch{N=setInterval(A,5e3)}return()=>{j=!0,U&&U.off("courseware-attempt-updated",O),N&&clearInterval(N)}},[e.coursewareUuid]);const y=()=>{su(c,Zi(c)),ru(u)};p.useEffect(()=>{const P=n??e.title??void 0,j=e.coursewareUuid;if(!P&&!j||!l)return;const A=a.current?.querySelector("iframe");if(!A||!(A instanceof HTMLIFrameElement)||!A.contentWindow)return;const U=N=>{if(N.source!==A.contentWindow)return;const O=N.data;if(!(!O||typeof O!="object"))if(O.type==="LMS_SUBMIT"){const x=O.payload??{};At.ingest({source:"iframe.postMessage",type:"courseware.submitted",lessonId:t,elementId:P,coursewareUuid:j,attemptId:typeof O.attempt_id=="string"?O.attempt_id:void 0,payload:{score:Ft(x.score??x.grade),total:Ft(x.total??x.fullScore),completion:Ft(x.completion??x.progress),comment:typeof x.comment=="string"?x.comment:void 0},raw:O})}else if(O.type==="LMS_SAVE_PROGRESS"){const x=O.payload??{};At.ingest({source:"iframe.postMessage",type:"courseware.progress_saved",lessonId:t,elementId:P,coursewareUuid:j,attemptId:typeof O.attempt_id=="string"?O.attempt_id:void 0,payload:{score:Ft(x.score),completion:Ft(x.completion??x.progress)},raw:O})}else if(O.type==="LMS_FINISH")At.ingest({source:"iframe.postMessage",type:"courseware.finished",lessonId:t,elementId:P,coursewareUuid:j,attemptId:typeof O.attempt_id=="string"?O.attempt_id:void 0,payload:{},raw:O});else if(O.type==="courseware:score"||O.type==="openlearn-cw-sdk:score"){const x=O.payload??O;At.ingest({source:"applet.score",type:"courseware.submitted",lessonId:t,elementId:P,coursewareUuid:j,payload:{score:Ft(x.score),total:Ft(x.total),detail:x.detail,source:typeof O.source=="string"?O.source:"openlearn-cw-sdk"},raw:O})}else typeof O.type=="string"&&O.type.startsWith("LMS_")&&At.ingest({source:"iframe.postMessage",type:"courseware.unknown",lessonId:t,elementId:P,coursewareUuid:j,payload:{originalType:O.type},raw:O})};return window.addEventListener("message",U),()=>window.removeEventListener("message",U)},[l,n,e.title,e.coursewareUuid,t]);const k=ks.resolve(e,{lessonId:t}),S=e.coursewareUuid?`/runtime/${e.coursewareUuid}/`:e.resourceId?`/api/resources/${e.resourceId}/`:k??void 0,I=h.filter(P=>P.finished_at!==null&&P.finished_at!==void 0),C=I.filter(P=>P.score!==null&&P.score!==void 0),T=C.length>0?C.reduce((P,j)=>P+(j.score||0),0)/C.length:null,_=60,E=d?.role==="student"&&(d.studentId||d.userId)||null,R=kv(h),B=I.filter(P=>!Cv.has(P.studentId)||P.studentId===E),F=Ev(B,R),M=E?B.find(P=>P.studentId===E)??null:null,v=M?R.get(M.attemptId)??null:null,z=R.size,L=!!e.coursewareUuid&&h.length>0;return o.jsxs("div",{ref:a,className:(s??"w-full h-full")+" relative",children:[l?o.jsx("iframe",{className:"w-full h-full border-none",src:S,srcDoc:S?void 0:yv(e.code||"",t),sandbox:"allow-scripts allow-forms allow-downloads",referrerPolicy:"no-referrer",title:r??e.title??"Interactive Courseware",credentialless:"true",onLoad:y}):o.jsx("div",{className:"w-full h-full flex items-center justify-center text-xs text-gray-400 bg-slate-50 rounded-xl",children:"课件未加载"}),L&&o.jsxs(o.Fragment,{children:[o.jsx("button",{type:"button",onClick:()=>g(P=>!P),"data-testid":"courseware-scores-toggle",className:"absolute top-2 right-2 z-[60] px-3 py-1.5 bg-white/95 backdrop-blur-sm rounded-lg shadow-lg border border-gray-200 text-xs font-medium text-gray-700 hover:bg-white transition-colors",children:f?"隐藏成绩":`查看成绩 (${F.length})`}),f&&o.jsxs("div",{"data-testid":"courseware-scores-panel",className:"absolute top-12 right-2 z-[60] w-72 max-h-96 overflow-auto bg-white/95 backdrop-blur-sm rounded-xl shadow-lg border border-gray-200 p-3",children:[o.jsx("div",{className:"text-xs text-gray-400 mb-2 flex items-center justify-between",children:o.jsxs("span",{children:[F.length," 人已提交",T!==null&&` · 均分 ${T.toFixed(1)}`]})}),E&&o.jsx("div",{"data-testid":"courseware-my-score",className:"text-xs text-blue-700 bg-blue-50 border border-blue-100 rounded-lg px-2 py-1.5 mb-2",children:M?`我的成绩 ${typeof M.score=="number"?M.score:"—"}${v!==null?` · 全班第 ${v}/${z} 名`:""}`:"我还没有提交"}),F.length===0?o.jsx("div",{className:"text-xs text-gray-400 text-center py-4",children:"暂无提交"}):o.jsx("div",{className:"space-y-1.5",children:F.map(P=>{const j=typeof P.score=="number"?P.score:null,A=typeof P.completion=="number"?Math.round(P.completion*100):null,U=R.get(P.attemptId),N=!!E&&P.studentId===E;return o.jsxs("div",{className:`flex items-center justify-between gap-2 text-xs rounded-md px-1.5 py-1 ${N?"bg-blue-50 ring-1 ring-blue-200":""}`,"data-testid":`courseware-attempt-row-${P.attemptId}`,children:[o.jsx("span",{className:"w-4 shrink-0 text-right font-mono text-gray-400",children:U??"-"}),o.jsxs("span",{className:"font-medium text-gray-700 truncate flex-1",children:[P.studentName||P.studentId,N&&o.jsx("span",{className:"ml-1 font-normal text-blue-600",children:"(我)"})]}),o.jsxs("span",{className:`font-mono font-bold ${j!==null&&j>=_?"text-green-600":"text-red-500"}`,children:[j!==null?j:"-",A!==null&&o.jsxs("span",{className:"ml-1 text-gray-400 font-normal",children:[A,"%"]})]})]},P.attemptId)})})]})]})]})}class Nv{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 Es=new Nv,BC=({type:e,title:t,data:n,containerSize:s,onClose:r,lessonId:i,elementId:a,dismissible:l=!0,readOnly:c=!1})=>{Je.useEffect(()=>{if(!l)return;const g=y=>{y.key==="Escape"&&r()};return window.addEventListener("keydown",g),()=>window.removeEventListener("keydown",g)},[r,l]);const u=l?r:()=>{},d=Es.get(e),[h,m]=p.useState({width:window.innerWidth,height:window.innerHeight});p.useEffect(()=>{const g=()=>m({width:window.innerWidth,height:window.innerHeight});return window.addEventListener("resize",g),()=>window.removeEventListener("resize",g)},[]);const f=o.jsx("div",{className:"fixed inset-0 z-[99999] bg-black/60 flex items-center justify-center",style:{pointerEvents:"auto"},children:o.jsxs("div",{className:"relative bg-white rounded-xl shadow-2xl overflow-hidden flex flex-col",style:{width:Math.max(400,h.width-32),height:Math.max(300,h.height-32)},children:[o.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:[o.jsx("span",{className:"truncate",children:t}),l?o.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:[o.jsx(ra,{size:14})," 退出全屏"]}):o.jsx("span",{className:`px-2 py-1 rounded-md text-xs font-bold flex items-center gap-1 select-none ${c?"bg-amber-100 text-amber-800 border border-amber-300":"bg-indigo-100 text-indigo-600"}`,title:c?"教师已开启全班专注锁定,当前为只读演示视图":"由教师端控制,无法在本地退出",children:c?"🔒 全班专注锁定中 · 演示视图":o.jsxs(o.Fragment,{children:[o.jsx(ra,{size:12})," 教师同步视图"]})})]}),l&&o.jsx("div",{className:"absolute top-3 right-3 z-10",children:o.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:o.jsx(tt,{size:16})})}),o.jsxs("div",{className:"flex-1 overflow-auto p-6 relative",style:{pointerEvents:c?"none":"auto"},children:[d?o.jsx(d,{elementType:e,data:n,onClose:u,containerSize:h,lessonId:i,elementId:a}):o.jsx(Pv,{elementType:e,data:n,onClose:u,containerSize:h,lessonId:i}),c&&o.jsx("div",{"data-testid":"fullscreen-readonly-lock-cover",className:"absolute inset-0 z-50 cursor-not-allowed bg-transparent select-none",style:{pointerEvents:"auto"},title:"🔒 全班专注锁定中:组件为只读跟随模式",onClick:g=>{g.stopPropagation(),g.preventDefault()},onPointerDown:g=>{g.stopPropagation(),g.preventDefault()}})]})]})});return Bf.createPortal(f,document.body)},Tv=[{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 Pv({data:e,lessonId:t}){const n=Tv.find(l=>e[l.field]!==void 0&&e[l.field]!==null&&e[l.field]!=="");if(!n)return o.jsxs("div",{className:"flex flex-col items-center justify-center h-full gap-4 text-gray-500",children:[o.jsx(qi,{size:48,className:"opacity-30"}),o.jsx("div",{className:"text-sm font-medium",children:"自动识别渲染"}),o.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:a}=n;if(s==="markdown")return o.jsx("div",{className:"prose prose-sm max-w-none",children:o.jsx(Lb,{children:String(e.markdown)})});if(s==="code")return o.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 o.jsx("div",{className:"flex items-start h-full",children:o.jsx("div",{className:"text-lg whitespace-pre-wrap leading-relaxed",children:String(e.text)})});if(s==="question"){const l=Array.isArray(e.options)?e.options:[];return o.jsxs("div",{className:"max-w-2xl mx-auto space-y-6",children:[o.jsx("h3",{className:"text-xl font-bold text-gray-800",children:e.question}),o.jsx("div",{className:"flex flex-col gap-3",children:l.map((c,u)=>o.jsxs("div",{className:"px-5 py-4 text-left bg-gray-50 border-2 border-gray-200 rounded-xl text-base",children:[o.jsxs("span",{className:"font-bold text-indigo-600 mr-3",children:["ABCDEFGHIJKLMNOPQRSTUVWXYZ"[u],"."]}),c]},u))})]})}return s==="url"?o.jsx("div",{className:"flex items-center justify-center h-full",children:o.jsx("a",{href:String(e.url),target:"_blank",rel:"noopener noreferrer",className:"text-indigo-600 underline text-lg",children:String(e.url)})}):s==="src"?o.jsx("div",{className:"flex items-center justify-center h-full",children:o.jsx("img",{src:String(e.src),alt:"",className:"max-w-full max-h-full object-contain rounded-lg"})}):s==="coursewareUuid"?o.jsx(jv,{data:{coursewareUuid:String(e.coursewareUuid)},lessonId:t,className:"w-full h-full rounded-xl border"}):s==="equation"?o.jsx("div",{className:"flex items-center justify-center h-full",children:o.jsx("div",{className:"text-2xl font-mono text-gray-800 bg-gray-50 px-8 py-4 rounded-xl border",children:String(e.equation)})}):o.jsx("div",{className:"flex items-center justify-center h-full",children:o.jsxs("div",{className:"text-center",children:[o.jsx("div",{className:"text-4xl mb-2",children:r}),o.jsx("div",{className:"text-lg font-semibold text-gray-800",children:i}),o.jsx("pre",{className:"mt-4 text-xs text-gray-500 max-w-md overflow-auto",children:JSON.stringify(e,null,2)})]})})}class Iv{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 gi=new Iv,Av=["@openlearn/frontend:IFrontendAPI","@openlearn/frontend:ISocketService","@openlearn/frontend:IUIService","@openlearn/frontend:IStorageService","@openlearn/frontend:ISemesterGradeService"];class zv{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 pv;await i.register(rl,t),await i.register(il,n),await i.register(ol,s),await i.register(al,r),await i.register(n0,new _v(t)),this.registry=i,this.initialized=!0,Ee.getState().initialize(i)}getRegistry(){return this.registry}isInitialized(){return this.initialized}async installPlugin(t,n){this.sourceCodes.set(t.id,n),Ee.getState().addPlugin({id:t.id,name:t.name,version:t.version,state:be.INSTALLED,executionMode:"inline"})}async activateRemotePlugin(t,n){const s=Ee.getState(),r=s.activePlugins.find(i=>i.id===t);if(!(r&&(r.state===be.ACTIVE||r.state===be.ACTIVATING))){s.updatePluginState(t,be.ACTIVATING);try{const i=`/plugins/${t}/frontend.js`,a=await fetch(i);if(!a.ok)throw new Error(`Failed to fetch frontend.js for plugin "${t}": HTTP ${a.status}`);let l=await a.text();window.HostSharedDeps&&(l=Rv(l));const c=new Blob([l],{type:"text/javascript"}),u=URL.createObjectURL(c);let d;try{d=await import(u)}finally{URL.revokeObjectURL(u)}const h=d.default??d;if(typeof h.activate!="function")throw new Error("Invalid remote frontend plugin: missing activate function");const m=await this.buildContext(t,n);await Promise.race([h.activate(m),new Promise((f,g)=>setTimeout(()=>g(new Error("Activation timeout (5000ms)")),5e3))]),this.pluginModules.set(t,{manifest:n,activate:h.activate,deactivate:typeof h.deactivate=="function"?h.deactivate:void 0}),s.updatePluginState(t,be.ACTIVE)}catch(i){throw console.error(`[FrontendPluginHost] Failed to activate remote plugin "${t}":`,i),s.updatePluginState(t,be.ERROR),this.unregisterPluginResources(t),i}}}async activatePlugin(t){const n=Ee.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,be.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),a=i.default??i,l=a.manifest??i.manifest,c=a.activate??i.activate,u=a.deactivate??i.deactivate;if(!l||typeof c!="function")throw new Error("Invalid plugin: missing manifest or activate function");if(l.id!==t)throw new Error(`Manifest id mismatch: expected "${t}", got "${l.id}"`);if(l.classroomTools)for(const h of l.classroomTools)n.registerExtensionPoint("classroom.tool",{id:h.id,label:h.name,icon:h.icon,component:()=>Promise.resolve({default:(()=>null)}),pluginId:t});const d=await this.buildContext(t,l);await Promise.race([c(d),new Promise((h,m)=>setTimeout(()=>m(new Error("Activation timeout (5000ms)")),5e3))]),this.pluginModules.set(t,{manifest:l,activate:c,deactivate:typeof u=="function"?u:void 0}),n.updatePluginState(t,be.ACTIVE)}catch(r){throw n.updatePluginState(t,be.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=Ee.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,be.ACTIVATING);try{let a;if(this.registry)try{a=await this.registry.resolve("@openlearn/frontend:ISocketService")}catch{}const{serviceHost:l}=await this.workerManager.createWorker(t,i,r,Av,a);this.pluginModules.set(t,{manifest:i,activate:async()=>{},deactivate:async()=>{await this.workerManager.terminateWorker(t)}}),s.updatePluginState(t,be.ACTIVE)}catch(a){throw s.updatePluginState(t,be.ERROR),this.unregisterPluginResources(t),a}}async deactivatePlugin(t){const n=Ee.getState(),s=n.activePlugins.find(r=>r.id===t);if(!(!s||s.state!==be.ACTIVE)){n.updatePluginState(t,be.DEACTIVATING);try{const r=this.pluginModules.get(t);r?.deactivate&&await Promise.race([r.deactivate(),new Promise((i,a)=>setTimeout(()=>a(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,be.INACTIVE)}}}async uninstallPlugin(t){const n=Ee.getState();n.activePlugins.find(r=>r.id===t)?.state===be.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 Ee.getState().getExtensions(t)}unregisterPluginResources(t){Ee.getState().unregisterPluginExtensionPoints(t),Es.unregisterPlugin(t),gi.unregisterPlugin(t),ks.unregisterPlugin(t),Tn.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(rl),r=await this.registry.resolve(il),i=await this.registry.resolve(ol),a=await this.registry.resolve(al);return{services:{frontendApi:s,socketService:r,uiService:i,storageService:a},pluginId:t,manifest:n,ui:{registerExtensionPoint:(l,c)=>{Ee.getState().registerExtensionPoint(l,{...c,pluginId:t})},unregisterExtensionPoint:(l,c)=>{Ee.getState().unregisterExtensionPoint(l,c)},registerFullscreenRenderer:(l,c)=>{Es.register(l,c,t)},unregisterFullscreenRenderer:l=>{Es.unregister(l,t)},registerPropertyEditor:(l,c)=>{gi.register(l,c,t)},unregisterPropertyEditor:l=>{gi.unregister(l,t)},registerCoursewareSource:l=>{ks.register(l,t)},unregisterCoursewareSource:l=>{ks.unregister(l,t)},registerPaletteItem:l=>{Tn.register(l,t)},unregisterPaletteItem:l=>{Tn.unregister(l,t)}},navigation:{getTeacherTab:()=>ve.getState().teacherTab,setTeacherTab:l=>ve.getState().setTeacherTab(l),setSelectedLesson:l=>ve.getState().setSelectedLesson(l),subscribeTeacherTab:l=>{let c=ve.getState().teacherTab;return ve.subscribe(u=>{const d=u.teacherTab;d!==c&&(c=d,l(d))})}},context:{get:()=>{const l=ve.getState();return{lessonId:l.selectedLesson,classId:l.liveClassSelectedClassId}},subscribe:l=>{const c=ve.getState();let u={lessonId:c.selectedLesson,classId:c.liveClassSelectedClassId};return ve.subscribe(d=>{const h={lessonId:d.selectedLesson,classId:d.liveClassSelectedClassId};(h.lessonId!==u.lessonId||h.classId!==u.classId)&&(u=h,l(h))})}},invokeCommand:async(l,c)=>{if(!s)throw new Error(`Plugin "${t}" cannot invoke command: frontendApi is not available. Has FrontendPluginHost initialized?`);const u=gv(l,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:l=>{const c=l.slot||"teacher.dashboard.widget";Ee.getState().registerExtensionPoint(c,{...l,pluginId:t})},registerMenu:l=>{const c=l.slot||"teacher.panel";Ee.getState().registerExtensionPoint(c,{...l,pluginId:t})},registerToolbarButton:l=>{Ee.getState().registerExtensionPoint("classroom.tool",{...l,pluginId:t})}}}}class _v{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")}}const Ml={react:"window.HostSharedDeps.React","react-dom":"window.HostSharedDeps.ReactDOM","react-dom/client":"(window.HostSharedDeps.ReactDOMClient || window.HostSharedDeps.ReactDOM)","react/jsx-runtime":"window.HostSharedDeps.jsxRuntime",recharts:"window.HostSharedDeps.Recharts","lucide-react":"window.HostSharedDeps.LucideReact"};function Ol(e){return e.split(",").map(t=>t.trim()).filter(Boolean).map(t=>t.replace(/^type\s+/,"")).map(t=>t.replace(/\s+as\s+/,": ")).join(", ")}function Lv(e,t){e=e.replace(/\/\*[\s\S]*?\*\//g,"").replace(/\/\/.*$/gm,"").trim();const n=[],s=e.match(/^([a-zA-Z_$][\w$]*)\s*,\s*\*\s*as\s+([a-zA-Z_$][\w$]*)$/);if(s)return n.push(`const ${s[1]} = ${t}?.default ?? ${t};`),n.push(`const ${s[2]} = ${t};`),n.join(" ");const r=e.match(/^([a-zA-Z_$][\w$]*)\s*,\s*\{([\s\S]*)\}$/);if(r){const c=r[1],u=Ol(r[2]);return n.push(`const ${c} = ${t}?.default ?? ${t};`),u&&n.push(`const { ${u} } = ${t};`),n.join(" ")}const i=e.match(/^\*\s*as\s+([a-zA-Z_$][\w$]*)$/);if(i)return`const ${i[1]} = ${t};`;const a=e.match(/^\{([\s\S]*)\}$/);if(a)return`const { ${Ol(a[1])} } = ${t};`;const l=e.match(/^([a-zA-Z_$][\w$]*)$/);return l?`const ${l[1]} = ${t}?.default ?? ${t};`:null}function Rv(e){let t=e.replace(/import\s+['"]([^'"]+)['"];?/g,(n,s)=>Ml[s]?`/* [HostSharedDeps] ${n} */`:n);return t=t.replace(/import\s+([\s\S]*?)\s+from\s+['"]([^'"]+)['"];?/g,(n,s,r)=>{const i=Ml[r];if(!i)return n;const a=Lv(s,i);return a||n}),t}class Mv extends Je.Component{constructor(t){super(t),this.state={hasError:!1,error:null,errorInfo:null,copied:!1,showDetails:!1},this.handleCopy=async()=>{const{error:n,errorInfo:s}=this.state;if(!n)return;const r=vo({type:"react",title:"React 组件渲染致命异常",message:n.message||String(n),stack:n.stack,componentStack:s?.componentStack||void 0,timestamp:Date.now(),url:typeof window<"u"?window.location.href:""});await Ls(r)&&(this.setState({copied:!0}),setTimeout(()=>this.setState({copied:!1}),2500))},this.handleReset=()=>{this.setState({hasError:!1,error:null,errorInfo:null,copied:!1,showDetails:!1})},this.handleGoHome=()=>{typeof window<"u"&&(window.location.href="/")},this.props=t}static getDerivedStateFromError(t){return{hasError:!0,error:t}}componentDidCatch(t,n){this.setState({errorInfo:n}),$t.getState().addError({type:"react",title:"React 组件渲染异常",message:t?.message||String(t),stack:t?.stack,componentStack:n?.componentStack||void 0}),console.error("[GlobalErrorBoundary] Unhandled React render exception:",t,n)}render(){if(this.state.hasError){const{error:t,errorInfo:n,copied:s,showDetails:r}=this.state,i=this.props.fallbackTitle||"界面渲染遇到意外错误";return o.jsx("div",{className:"min-h-screen bg-slate-50 dark:bg-slate-950 flex items-center justify-center p-4 select-text",children:o.jsxs("div",{className:"max-w-2xl w-full bg-white dark:bg-slate-900 rounded-2xl shadow-xl border border-rose-200 dark:border-rose-900/60 overflow-hidden",children:[o.jsxs("div",{className:"bg-gradient-to-r from-rose-500 to-red-600 px-6 py-5 text-white flex items-center gap-3.5",children:[o.jsx("div",{className:"p-2.5 bg-white/20 rounded-xl backdrop-blur-xs shrink-0",children:o.jsx(wp,{size:24,className:"text-white"})}),o.jsxs("div",{className:"flex-1 min-w-0",children:[o.jsx("h1",{className:"text-lg font-bold leading-snug",children:i}),o.jsx("p",{className:"text-xs text-rose-100 mt-0.5",children:"OpenLearn 捕获到界面异常,已阻止整页崩溃并为您保留了诊断报告。"})]})]}),o.jsxs("div",{className:"p-6 space-y-4",children:[o.jsxs("div",{children:[o.jsx("label",{className:"text-xs font-bold text-gray-500 dark:text-gray-400 uppercase tracking-wider block mb-1.5",children:"错误摘要 (Error Summary)"}),o.jsxs("div",{className:"bg-rose-50 dark:bg-rose-950/40 border border-rose-200 dark:border-rose-900/50 rounded-xl p-3.5 text-rose-900 dark:text-rose-200 text-sm font-mono break-all",children:[t?.name,": ",t?.message||"未知异常"]})]}),o.jsxs("div",{className:"border border-gray-200 dark:border-gray-800 rounded-xl overflow-hidden",children:[o.jsxs("button",{type:"button",onClick:()=>this.setState({showDetails:!r}),className:"w-full px-4 py-2.5 bg-gray-50 dark:bg-slate-800/60 hover:bg-gray-100 dark:hover:bg-slate-800 flex items-center justify-between text-xs font-semibold text-gray-700 dark:text-gray-300 transition-colors cursor-pointer",children:[o.jsx("span",{children:"查看调用堆栈与排查信息"}),r?o.jsx(Ln,{size:14}):o.jsx(Ci,{size:14})]}),r&&o.jsxs("div",{className:"p-4 bg-slate-900 text-slate-200 text-xs font-mono max-h-64 overflow-y-auto space-y-3 leading-relaxed",children:[t?.stack&&o.jsxs("div",{children:[o.jsx("span",{className:"text-rose-400 font-bold block mb-1",children:"Stack Trace:"}),o.jsx("pre",{className:"whitespace-pre-wrap text-xs opacity-90",children:t.stack})]}),n?.componentStack&&o.jsxs("div",{className:"pt-2 border-t border-slate-800",children:[o.jsx("span",{className:"text-amber-400 font-bold block mb-1",children:"Component Stack:"}),o.jsx("pre",{className:"whitespace-pre-wrap text-xs opacity-80",children:n.componentStack})]})]})]}),o.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 pt-2",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsxs("button",{type:"button",onClick:this.handleCopy,className:`px-4 py-2 rounded-xl text-xs font-bold transition-all flex items-center gap-1.5 shadow-sm cursor-pointer ${s?"bg-emerald-600 text-white shadow-emerald-600/30":"bg-indigo-600 hover:bg-indigo-700 text-white shadow-indigo-600/30"}`,children:[s?o.jsx(et,{size:14}):o.jsx(rn,{size:14}),o.jsx("span",{children:s?"✓ 诊断报告已复制!":"一键复制错误报告"})]}),o.jsxs("button",{type:"button",onClick:this.handleReset,className:"px-3.5 py-2 rounded-xl text-xs font-semibold bg-gray-100 dark:bg-slate-800 hover:bg-gray-200 dark:hover:bg-slate-700 text-gray-700 dark:text-gray-200 transition-colors flex items-center gap-1.5 cursor-pointer",children:[o.jsx(ql,{size:14}),o.jsx("span",{children:"重新加载界面"})]})]}),o.jsxs("button",{type:"button",onClick:this.handleGoHome,className:"px-3 py-2 rounded-xl text-xs font-medium text-gray-500 hover:text-gray-800 dark:text-gray-400 dark:hover:text-gray-100 transition-colors flex items-center gap-1 cursor-pointer",children:[o.jsx(Vl,{size:14}),o.jsx("span",{children:"返回系统主页"})]})]})]})]})})}return this.props.children}}window.React=xi;window.ReactDOM=yi;window.HostSharedDeps={React:xi,ReactDOM:yi,ReactDOMClient:ea,Recharts:ha,LucideReact:ia,jsxRuntime:Xo,react:xi,"react-dom":yi,"react-dom/client":ea,"react/jsx-runtime":Xo,recharts:ha,"lucide-react":ia};const Ov=new zv;Vf.createRoot(document.getElementById("root")).render(o.jsx(p.StrictMode,{children:o.jsx(Mv,{children:o.jsx(Fb,{host:Ov,children:o.jsx(fv,{})})})}));export{Bc as A,OC as C,Ub as D,FC as E,BC as F,jv as H,Lb as M,dm as P,de as a,MC as b,DC as c,ga as d,it as e,$t as f,fm as g,qb as h,eu as i,Ds as j,sn as k,Cs as l,xs as m,RC as n,MS as o,gi as p,Tn as q,gv as r,Es as s,su as t,Ee as u,Zi as v,At as w};