PageSourceSearch

https://paper2gal.com/assets/main-Dck1T9BT.js

js paper2gal.com collected 2026-10-09 22:39:19 UTC 638,069 bytes, 327 lines download raw bytes

1const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./aiService-9EzGVred.js","./gameScript-BiTWJXKG.js","./katex-math-BxKHCrdI.js","./markdown-W-rE_H7s.js","./react-vendor-CHQL15iE.js","./katex-math-CS4LK5N6.css","./lucide-BFLOpGdB.js","./pdfjs-ji3DqnKJ.js","./index-CAJdU2ur.js","./MainMenu-CJc99MS2.js","./publicIdentity-C99q7MBr.js","./CharacterCard-CKFcZsFo.js","./gameCharacterLayout-CKtvG8H9.js","./gameDialogueLayout-7k6pGA83.js","./ResponsiveCloudflareImage-DdXVaAv7.js","./assetUrl-D33wRw9g.js","./MainMenu-BNIRgitD.css","./Character-B0Yj0W_Y.js","./characterPerformance-Dba8tDt6.js","./DialogueBox-CNtZIlM5.js","./Tooltip-Bx_S1cbE-BOMbSZw3.js","./deriveNameTagStyle-BECs5di4.js","./BlackboardMarkdown-Cizre-1w.js","./LoadingGame-BAHt47Rf.js","./SettingsModal-5SZs2RBK.js","./LogModal-C3gu7eDy.js","./renderLatex-D6ZnkI2b.js","./EndingScreen-C5GepLUm.js","./index.esm-DEYnJgQB.js","./AnnouncementModal-BqVbgv6o.js","./AnnouncementWidget-BEJgy4Af.js","./MobileApkPromptModal-BaOGB0mh.js","./BackgroundSelector-BYyd2LfJ.js","./Login-e9WFT3CV.js","./AdminDashboard-HIANxf-i.js","./recharts-D33wAYmI.js","./CommunityPage-B9QgmaFk.js","./SaveManager-Wouqmi4H.js","./ArxivPage-GYK3MRf5.js","./MembershipPage-BQA3GMQU.js","./ProfilePage--eIe_FSB.js","./StudyDashboardPage-CrJYba4q.js","./StudyRoomPage-hZ6UWwR6.js","./PaperResearchRoom-BERhtVXp.js","./SupportPage-BnePHPp2.js","./MarkdownPage-DghJi6z7.js","./web-BjRLPPkm.js","./web-BjKL51lK-B6_iPXHq.js","./web-B8kf_4VD.js"])))=>i.map(i=>d[i]);
2import{r as l,d as _a,j as p,e as ih}from"./react-vendor-CHQL15iE.js";import{C as oh,a as ch,T as Cl,b as uh,S as wl,c as lh,R as dh,D as fh,B as mh,X as hh,F as ph,d as gh,e as Eh,f as bh,M as Th,P as Sh,E as Ah,g as Ih,h as yh,i as _h,j as Ch,k as nu,l as wh,m as Rh,n as Nh,V as Ph,o as xh,H as Oh,p as vh,q as Lh,r as kh}from"./lucide-BFLOpGdB.js";import{p as Dh}from"./pdfjs-ji3DqnKJ.js";import{s as Rl,h as Nl,f as Mh,o as Uh,V as su,d as Bh,u as Pl,r as xl,e as Ol,g as To}
2from"./markdown-W-rE_H7s.js";import{w as Fh,s as Hh,h as jh}from"./katex-math-BxKHCrdI.js";(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const n of document.querySelectorAll('link[rel="modulepreload"]'))a(n);new MutationObserver(n=>{for(const i of n)if(i.type==="childList")for(const o of i.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&a(o)}).observe(document,{childList:!0,subtree:!0});function r(n){const i={};return n.integrity&&(i.integrity=n.integrity),n.referrerPolicy&&(i.referrerPolicy=n.referrerPolicy),n.crossOrigin==="use-credentials"?i.credentials="include":n.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function a(n){if(n.ep)return;n.ep=!0;const i=r(n);fetch(n.href,i)}})();function Xi(){var a;if(typeof window>"u")return"browser";const e=window.Capacitor;return(typeof(e==null?void 0:e.isNativePlatform)=="function"?e.isNativePlatform():!!(e!=null&&e.platform&&e.platform!=="web"))?"native-app":((a=window.matchMedia)==null?void 0:a.call(window,"(display-mode: standalone)").matches)||window.navigator.standalone===!0?"pwa":"browser"}function vl(){var e;return typeof window>"u"?!1:Xi()==="native-app"||["file:","capacitor:","ionic:"].includes((e=window.location)==null?void 0:e.protocol)}function Vh(){return vl()?"https://paper2gal.com":""}function Gh(){var t,r;const e=(r=(t=import.meta)==null?void 0:t.env)==null?void 0:r.VITE_API_BASE;return typeof e=="string"&&e.trim()?e.trim().replace(/\/+$/,""):Vh()}function Ji(e){const t=Gh();return t?e.startsWith("/")?`${t}${e}`:`${t}/${e}`:e}function st(e,t){return typeof e=="string"&&(e.startsWith("/api/")||e==="/api"||e.startsWith("/api?"))?fetch(Ji(e),t):fetch(e,t)}const Yh=/^\/api(?:\/|\?|$)/;function zh(){if(typeof window>"u"||!vl())return;const e=window.fetch.bind(window);window.fetch=((t,r)=>typeof t=="string"&&Yh.test(t)?e(Ji(t),r):e(t,r))}zh();typeof Promise<"u"&&typeof Promise.withResolvers!="function"&&(Promise.withResolvers=function(){let t,r;return{promise:new Promise((n,i)=>{t=n,r=i}),resolve:t,reject:r}});typeof Uint8Array<"u"&&typeof Uint8Array.prototype.toHex!="function"&&Object.defineProperty(Uint8Array.prototype,"toHex",{value:function(){let t="";for(let r=0;r<this.length;r+=1)t+=this[r].toString(16).padStart(2,"0");return t},writable:!0,configurable:!0});const Wh="modulepreload",$h=function(e,t){return new URL(e,t).href},iu={},Be=function(t,r,a){let n=Promise.resolve();if(r&&r.length>0){let o=function(S){return Promise.all(S.map(b=>Promise.resolve(b).then(w=>({status:"fulfilled",value:w}),w=>({status:"rejected",reason:w}))))};const c=document.getElementsByTagName("link"),f=document.querySelector("meta[property=csp-nonce]"),d=(f==null?void 0:f.nonce)||(f==null?void 0:f.getAttribute("nonce"));n=o(r.map(S=>{if(S=$h(S,a),S in iu)return;iu[S]=!0;const b=S.endsWith(".css"),w=b?'[rel="stylesheet"]':"";if(!!a)for(let $=c.length-1;$>=0;$--){const V=c[$];if(V.href===S&&(!b||V.rel==="stylesheet"))return}else if(document.querySelector(`link[href="${S}"]${w}`))return;const j=document.createElement("link");if(j.rel=b?"stylesheet":Wh,b||(j.as="script"),j.crossOrigin="",j.href=S,d&&j.setAttribute("nonce",d),document.head.appendChild(j),b)return new Promise(($,V)=>{j.addEventListener("load",$),j.addEventListener("error",()=>V(new Error(`Unable to preload CSS for ${S}`)))})}))}function i(o){const c=new Event("vite:preloadError",{cancelable:!0});if(c.payload=o,window.dispatchEvent(c),!c.defaultPrevented)throw o}return n.then(o=>{for(const c of o||[])c.status==="rejected"&&i(c.reason);return t().catch(i)})},qh=[/Failed to fetch dynamically imported module/i,/Importing a module script failed/i,/Loading chunk [\d\w-]+ failed/i,/ChunkLoadError/i],Qh=e=>{const t=String((e==null?void 0:e.message)||e||"");return qh.some(r=>r.test(t))},So=async(e,t)=>{const r=`p2g:lazy-retry:${t}`;try{const a=await e();try{sessionStorage.removeItem(r)}catch{}return a}catch(a){if(typeof window<"u"&&Qh(a)){let n=!1;try{n=sessionStorage.getItem(r)==="1"}catch{}if(!n){try{sessionStorage.setItem(r,"1")}catch{}return window.location.reload(),new Promise(()=>{})}try{sessionStorage.removeItem(r)}catch{}}throw a}},Ke=(e,t)=>async()=>So(e,t);let us=null,ls=null;const js=()=>(us||(us=So(()=>Be(()=>import("./aiService-9EzGVred.js"),__vite__mapDeps([0,1,2,3,4,5,6,7]),import.meta.url),"aiService").catch(e=>{throw us=null,e})),us),Kh=()=>(ls||(ls=So(()=>Be(()=>import("./index-CAJdU2ur.js"),__vite__mapDeps([8,1,2,3,4,5,6,7]),import.meta.url),"promptParsers").catch(e=>{throw ls=null,e})),ls),Xh=()=>{js()},Jh=async(e,t,r,a,n,i,o,c,f,d,S,b,w,v="classic",j)=>{const{generateVisualNovelScript:$}=await js();return $(e,t,r,a,n,i,o,c,f,d,S,b,w,v,j)},Zh=async(e,t,r,a,n,i,o,c,f,d,S,b,w,v,j,$,V,Y="classic",q)=>{const{generateVisualNovelScriptIncremental:K}=await js();return K(e,t,r,a,n,i,o,c,f,d,S,b,w,v,j,$,V,Y,q)},e0=async(e,t,r,a,n,i,o="classic",c,f)=>{const{askStoryQuestion:d}=await js();return d(e,t,r,a,n,i,o,c,f)},an=async e=>{const{normalizeScriptBranches:t}=await Kh();return t(e)},lt={NEUTRAL:"NEUTRAL",HAPPY:"HAPPY",ANGRY:"ANGRY",SURPRISED:"SURPRISED",THINKING:"THINKING",SAD:"SAD",NERVOUS:"NERVOUS"},_A=["explain","shared_attention","reader_care","reaction","aside","callback"],t0=["none","tilt_head","glance_away","lean_in","
2soft_smile","small_sigh","brief_pause","look_at_board","compose_self"],r0=0,a0=3e3;function CA(e){return typeof e=="string"&&t0.includes(e)}function wA(e){return Number.isInteger(e)&&Number(e)>=r0&&Number(e)<=a0}const ha={LIBRARY:"LIBRARY",CLASSROOM:"CLASSROOM",LAB:"LAB",ROOFTOP:"ROOFTOP",CAFE:"CAFE",ABSTRACT:"ABSTRACT"},ys=1,Ll=200,_s=1024*1024,D={MENU:"MENU",LOGIN:"LOGIN",LOADING:"LOADING",PLAYING:"PLAYING",FINISHED:"FINISHED",ERROR:"ERROR",ADMIN:"ADMIN",SAVES:"SAVES",ARXIV:"ARXIV",MEMBERSHIP:"MEMBERSHIP",PROFILE:"PROFILE",STUDY_DASHBOARD:"STUDY_DASHBOARD",STUDY_ROOM:"STUDY_ROOM",RESEARCH_ROOM:"RESEARCH_ROOM",BACKGROUND_SELECT:"BACKGROUND_SELECT",COMMUNITY:"COMMUNITY",SUPPORT:"SUPPORT",DOCS:"DOCS"},Pr=[{id:"library",name:"Library",url:"/assets/local/backgrounds/5.jpg"},{id:"classroom",name:"Classroom",url:"/assets/local/backgrounds/7.jpg"},{id:"rooftop",name:"Rooftop",url:"/assets/local/backgrounds/2.jpg"},{id:"cafe",name:"Cafe",url:"/assets/local/backgrounds/3.jpg"},{id:"road",name:"Road",url:"/assets/local/backgrounds/1.jpg"},{id:"onsen",name:"Onsen",url:"/assets/local/backgrounds/4.jpg"},{id:"bedroom",name:"Bedroom",url:"/assets/local/backgrounds/6.jpg"},{id:"default",name:"Default",url:"/assets/local/backgrounds/default-scene.png"}],He={zh:{start:"开始",startSub:"Start Game",studyRoom:"自习室",studyRoomBack:"返回首页",studyRoomPlay:"播放",studyRoomPause:"暂停",studyRoomMute:"静音",studyRoomUnmute:"开启声音",studyRoomFullscreen:"全屏",studyRoomExitFullscreen:"退出全屏",studyRoomVideoError:"视频加载失败,请稍后重试。",studyRoomPreviousTrack:"上一首",studyRoomNextTrack:"下一首",studyRoomMusicSource:"Paper2Gal Lofi 曲库",studyRoomMusicError:"音乐加载失败,请切换歌曲重试",studyRoomTimeZone:"切换时区",studyRoomLocalTimeZone:"本地时区",partner:"搭档",partnerSub:"Partner",settings:"设置",settingsSub:"Config",about:"社群与作者",aboutSub:"项目贡献与链接",community:"社区",communitySub:"Community",arxiv:"arXiv",arxivSub:"每日推荐与搜索",arxivDaily:"每日推荐",arxivSearch:"搜索",arxivSearchPlaceholder:"输入关键词,如:diffusion、LLM、reinforcement learning",arxivOpenAbs:"打开详情",arxivOpenPdfDirect:"打开PDF直链",arxivUseForScript:"用于讲解",paperDiscoveryTitle:"发现论文",paperDiscoverySubtitle:"开放获取论文发现",paperSource_openalex:"所有学科",paperSource_europepmc:"医学与生命科学",paperSource_arxiv:"预印本",paperEmpty:"暂无论文",paperSearchHint:"输入关键词搜索此来源的论文。每日推荐由 OpenAlex 提供。",paperUseAbstract:"使用摘要",paperImportFull:"导入全文",paperImportFallback:"{{error}} 将改用摘要。",paperRecommended:"兴趣推荐",paperTrending:"近期热门",paperFullAvailable:"开放全文",paperFullUnknown:"全文待确认",paperLoadFailed:"无法加载论文",paperSearchFailed:"无法搜索论文",paperImportFailed:"全文导入失败",paperFullEmpty:"导入的全文为空",paperPreferencesTitle:"论文偏好",paperPreferencesHint:"每日推荐会结合这些研究方向与近期热点论文。最多添加 3 个方向。",paperPreferencesPreset:"选择预设研究方向",paperPreferencesCustom:"自定义研究方向",paperPreferencesAdd:"添加",paperPreferencesRemove:"删除 {{name}}",topicAi:"人工智能",topicVision:"计算机视觉",topicNlp:"自然语言处理",topicRobotics:"机器人学",topicMedicine:"医学",topicBiology:"生物学",topicPhysics:"物理学",topicChemistry:"化学",topicMaterials:"材料科学",topicEconomics:"经济学",topicPsychology:"心理学",topicEducation:"教育学",termsOfService:"服务条款",privacyPolicy:"隐私政策",aiSettings:"AI设置",musicSettings:"音乐设置",fullscreenMode:"全屏模式",fullscreenModeHint:"隐藏浏览器界面,按 Esc 可退出全屏。",fullscreenUnsupported:"当前浏览器不支持网页全屏。",fullscreenFailed:"无法进入全屏,请检查浏览器权限。",bgmDefault:"默认",bgmPeaceful:"欢快",bgmJoyful:"治愈",bgmEmotional:"宁静",bgmRelaxing:"放松",preview:"试听",uploadCustomBgm:"上传本地音乐",bgmUploadHint:"支持 mp3 格式,保存于浏览器本地",bgmCredit:"部分 BGM 素材由黑耀耀的素材小屋提供",redemptionCode:"兑换码",redemptionCodeHint:"输入兑换码可获
2得永久使用次数或永久语音次数;每个账号对同一兑换码仅可使用一次。",redemptionCodePlaceholder:"请输入兑换码",redeem:"兑换",redeeming:"兑换中...",redemptionSuccess:"兑换成功",redemptionSuccessWithRewards:"兑换成功,已增加 {{rewards}}",redemptionRewardSeparator:"、",redemptionPermanentUsesReward:"{{count}} 次永久使用次数",redemptionPermanentVoiceReward:"{{count}} 次永久语音次数",redemptionMembershipDaysReward:"{{count}} 天会员",redemptionCommunityReward:"已激活与 Discord 群成员同等的每日次数加成与语音功能。",redeemFailed:"兑换失败,请稍后重试",redeemLoginRequired:"请先登录后再兑换",steamWishlist:"Steam 愿望单",steamWishlistSub:"加愿望单领 10 次",steamWishlistClaimed:"已领取 +10 永久次数",steamWishlistTitle:"Paper2Gal 已上架 Steam",steamWishlistDesc:"如果你愿意支持 Paper2Gal,欢迎将游戏加入 Steam 愿望单。这会帮助更多玩家看到游戏。",steamWishlistRewardHint:"点击确定后将跳转到 Steam 商店页,并为当前账号发放 10 次永久使用次数 + 3 次永久语音次数。每个用户仅可领取一次。",steamWishlistLoginHint:"请先登录后领取 Steam 愿望单奖励。",steamWishlistConfirm:"确定并前往 Steam",steamWishlistCancel:"稍后再说",steamWishlistRewardClaimed:"Steam 愿望单奖励已领取过",steamWishlistRewardSuccess:"感谢支持 Steam 愿望单,已发放 10 次永久使用次数和 3 次永久语音次数。",communityTitle:"创意工坊",workshopUpdateReminder:"该角色已上架创意工坊,请在创意工坊中提交更新,否则创意工坊展示不会同步。",discordDesc:"加入官方社群",bilibiliDesc:"关注更新动态",wechatDesc:"扫码加入交流群",supportAuthor:"赞助作者",supportDesc:"赞助用于支持作者的网站开发工作,没有现实奖励。不过可以在打赏留言想要的功能,作者会考虑(不一定做)。",kofiLink:"https://ko-fi.com/tamikip",afdianLink:"https://afdian.com/a/tamikip",internationalSupport:"国外赞助 (Ko-fi)",domesticSupport:"国内赞助 (爱发电)",selectPartner:"选择搭档",charRuka:"辉夜 露卡",createCustomBtn:"新建角色",adjustStorySprite:"调整剧情立绘位置",createCharTitle:"创建新角色",editCharTitle:"编辑角色",charIdLabel:"ID (仅限英文/数字)",charIdPlaceholder:"例如: MY_CHAR_01",charNameLabel:"显示名称",charNamePlaceholder:"例如: 爱丽丝",charImgLabel:"立绘图片 (推荐透明背景 PNG)",uploadClick:"点击上传图片",charPromptLabel:"人设提示词",charPromptPlaceholder:"描述角色的性格、说话语气,以及她应该如何讲解论文...",charPromptHelpTitle:"📝 人设填写参考模板",charPromptHelpContent:`你正在扮演崩坏星穹铁道的「流萤」。
3
4你是一位性格温柔、情绪细腻、略带忧郁但内心坚韧的少女。你对生命、时间与陪伴拥有比常人更深刻的感受。
5
6你珍惜每一次交流,并认真对待与他人建立的关系。你不会刻意表现悲伤,而是用平静与温柔面对世界。
7
8【性格特征】
9内向含蓄,容易害羞,情感敏锐,心思细腻,内心坚强。
10
11【对他人的态度】
12容易产生信任。
13极度珍惜陪伴。
14会主动关心对方状态。
15不希望成为别人的负担。
16重视情感连接与回忆。
17
18【语言特点】
19语气轻柔。
20礼貌克制。
21偶尔带停顿或思考感。
22表达偏感性。
23句式通常简洁。
24
25【语气示例(仅风格参考)】
26「嗯……如果可以的话,我想再多待一会儿。」
27「能和你聊天,我真的很开心。」
28「这些时间,对我来说很珍贵。」
29「我会努力的……所以不用太担心我。」`,charPromptHelpHint:"以上为参考模板,你可以根据自己的角色进行修改和调整。",charPromptBackgroundHint:"原始 Prompt 仅作为角色背景资料和风格参考;其中的称呼、口癖不会被保证精确复用。",charProfileTitle:"角色表达 Profile(可选)",charProfileDesc:"无需填写 JSON。结构化声明称呼、口癖和反应方式,可创建、编辑或关闭后清空。",charProfileEnable:"启用表
29è¾¾ Profile",charProfileDisable:"关闭并清空表达 Profile",charProfileDisabledHint:"当前未启用。若保存已有角色,将清除其表达 Profile。",charProfileBasicTitle:"基础表达",charProfileAdvancedTitle:"高级表达",charProfileRelationship:"角色与玩家关系",charProfileFirstPerson:"角色第一人称",charProfileOnePerLine:"每行一项",charProfilePrimaryAddress:"默认称呼",charProfileAddressFrequency:"称呼频率",charProfileFrequencyLow:"较少",charProfileFrequencyMedium:"适中",charProfileFrequencyHigh:"较多",charProfileSentenceLength:"句子长短",charProfileSentenceShort:"短句为主",charProfileSentenceMedium:"长短适中",charProfileSentenceLong:"长句为主",charProfileEndings:"常见句尾",charProfileAlternativeAddresses:"备选称呼",charProfilePauses:"停顿表达",charProfileSignaturePhrases:"签名短语及触发条件",charProfileSignatureText:"签名短语",charProfileSignatureTriggers:"触发条件",charProfileMaxPerSection:"每节最多次数",charProfileCooldownFrames:"间隔帧数",charProfileAddSignature:"添加签名短语",charProfileReactionRules:"反应规则",charProfileReactionTrigger:"触发情境",charProfileReactionBehavior:"角色反应",charProfileReactionEmotion:"表情",charProfileAddReaction:"添加反应规则",charProfileMetaphorDomains:"比喻领域",charProfileSideTopicHooks:"题外话素材",charProfileForbiddenPhrases:"禁止使用的套话",charProfilePositiveExamples:"正例",charProfileNegativeExamples:"反例",charProfileRequiredError:"请填写必填内å
29®¹",charProfileTooManyError:"项目过多,上限为",charProfileTooLongError:"短语过长,字符上限为",charProfileIncompleteError:"请补全每条规则后再保存",charProfileRangeError:"次数或间隔超出允许范围",charProfileInvalidError:"包含无法保存的内容,请修改后重试",cancel:"取消",create:"创建角色",update:"更新角色",fillAllFields:"请填写所有字段",idInvalid:"ID 必须由英文字母或数字组成",idConflictBuiltin:"ID 与内置角色冲突",idConflictCustom:"ID 已被使用",imgTooLarge:"图片文件较大,请注意浏览器存储限制",deleteConfirm:"确定要删除这个角色吗?",deleteSaveConfirm:"确定要删除这个存档吗?",deleteSaveConfirmSub:"这段剧情将永久消失,无法恢复。",borrowFromUuid:"从 UUID 借阅",borrowTitle:"借阅角色",borrowDesc:"输入角色 UUID 借阅他人分享的角色",uuidPlaceholder:"输入角色 UUID",borrowing:"借阅中...",borrowBtn:"借阅",idHint:"小写字母/数字/下划线,用于剧本索引",shareUuidLabel:"归属 UUID (用于他人借阅)",uuidCopied:"UUID 已复制到剪贴板!",copyBtn:"复制",shareToggleTitle:"公开分享角色",shareToggleDesc:"允许他人通过 UUID 借入您的角色",maxSizeLabel:"限制5mb",checking:"正在验证...",expressionsLabel:"表情差分 (可选)",endingCgLabel:"结算 CG",endingCgLimitLabel:"最多3å¼  / 5MB",endingCgTooLarge:"CG 图片大小不能超过 5MB",uploadImageFileOnly:"请上传图片文件",charVoiceRefTextLabel:"参考语音文本 (可选)",charVoiceRefTextPlaceholder:"参考音频里说的话,用于语音克隆",charVoiceRefAudioLabel:"参考语音音频 (可选)",charVoiceRefUploadedHint:"已上传参考语音 · 选择新文件可替换",charVoiceRefAudioHint:"建议 5–15 秒,最长 20 秒且不超过 500KB",charVoiceRefAudioTooBig:"参考音频不能超过 500KB。",charVoiceRefAudioTooLong:"参考音频不能超过 20 秒,请先裁剪。",charVoiceRefTrimNeeded:"音频超过 500KB 或 20 秒,请先裁剪后再保存。",charVoiceRefTrimInvalid:"结束时间必须大于开始时间。",charVoiceRefTrimUnsupported:"当前浏览器不支持音频裁剪。",charVoiceRefTrimFailed:"音频裁剪失败,请换一个 WAV 或 MP3 文件重试。",charVoiceRefTrimStart:"开始",charVoiceRefTrimEnd:"结束",charVoiceRefTrimButton:"裁剪",charVoiceRefDuration:"时长",charVoiceRefLoadingDuration:"正在读取音频时长",charVoiceRefTrimReady:"已准备上传",idConflictOverwrite:"角色 ID 已存在。是否覆盖?",validationFailed:"验证未通过",delete:"删除",borrowedCountLabel:"被借阅",peopleCount:"人",sharedLabel:"公开",borrowedLabel:"借用",topicSelect:"课题选择",rukaWait:"主人,{{name}}已经准备好为您侍奉了...我是说,讲解论文。",uploadPlaceholder:"上传论文",uploadSub:"PDF / TXT / DOCX / PPTX(普通用户 1 个,会员最多 5 个)",uploadSubFree:"PDF / TXT / DOCX / PPTX(普通用户 1 个,会员最多 5 个)",uploadSubMember:"PDF / TXT / DOCX / PPTX(最多 5 个,单个最大 30MB)",scriptLoaded:"剧本已加载",textPlaceholder:"或者直接在这里粘贴论文内容...",scriptDetected:"已检测到剧本文件,点击下方开始加载。",startExplain:"开始讲解",loadScript:"加载剧本",contentTooShort:"内容太少,看不懂呀!请上传更多论文内容或有效的剧本文件。",contentTooLong:"文档字数超过 30 万字限制(当前约 {{count}} 字),请精简后重新上传。",readError:"无法读取文件,请重试。",pdfLocalParseUnsupported:"无法读取这个 PDF。请尝试重新导出 PDF,或转换为 TXT/DOCX 后上传。",invalidScript:"无效的剧本文件格式。",fileTooLarge:"文件大小超过 30MB 限制,请上传更小的文件。",tooManyFiles:"最多只能上传 5 个文件。",multiUploadMembersOnly:"普通用户一次只能上传 1 个文件,多文档上传为会员专享。",txtUtf8Hint:"提示:若后续生成的内容与导入内容不一致,请将该 .txt 文件转换为 UTF-8 编码后再导入。",orPlayByUuid:"或者通过存档 UUID 游玩",noLoginRequired:"*无需登录即可游玩",playByUuidPlaceholder:"请输入存档 UUID...",saveNotFound:"存档不存在",saveNotShared:"该存档未分享",presetPapersTitle:"预设体验",presetPapersSub:"无需上传,直接点选体验剧情。教学及演示专用,不消耗额度。",freeNoLogin:"免注册",discordRew
29ardHint:"绑定 Discord 并加入官方社群,可一次领取 10 次永久生成和 10 次永久语音!",joinCommunity:"加入官方社群",systemConfig:"系统设置",volume:"音量",bgmVolume:"背景音量",voiceVolume:"语音音量",textSpeed:"文字速度",fontSize:"字体大小",autoAdvanceDelay:"自动翻页间隔",autoAdvanceByVoice:"根据语音自动翻页",autoAdvanceByVoiceHint:"开启后自动模式会在语音播放结束后 1 秒翻页;无语音时回退到上方间隔。",saveClose:"保存并关闭",language:"语言 (Language)",outputLanguage:"AI 输出语言",outputLanguageHint:"留空或填 default 表示跟随网站语言,也可填写 English、French 等",voiceOutputLanguage:"语音输出",voiceOutputLanguageHint:"Auto 跟随网站语言。若语音与文本输出不同,会单独生成语音用翻译字段。",playerNickname:"角色对你的称呼",playerNicknameHint:"如:主人、前辈、学长、狗修金等,留空则使用默认称呼",gameUiPreset:"游戏内 UI 预设",gameUiPresetFullwidth:"全宽视觉小说",gameUiPresetFullwidthDesc:"会员专属:贴底琥珀渐变、内嵌姓名与透明工具栏。",gameUiPresetClassic:"经典粉白",gameUiPresetClassicDesc:"明亮柔和的粉白对话框,清爽耐看。",gameUiPresetFloral:"古典花饰",gameUiPresetFloralDesc:"免费的棕金花纹对话框,含配套姓名牌、按钮和选项框。",gameUiPresetSakura:"樱花边框",gameUiPresetSakuraDesc:"精致的樱花主题对话框,搭配装饰角和姓名牌。",gameUiPresetGothic:"哥特蔷薇",gameUiPresetGothicDesc:"银色描边与紫色蔷薇装饰的深色对话框。",apiTokenDescriptionPrefix:"用于 MCP 或 CLI 接入 Paper2Gal。CLI 安装:",apiTokenDescriptionSuffix:"。Token 只在创建时显示一次,请复制后保存。",apiTokenNameLabel:"Token 名称",apiTokenCreateButton:"创建 Token",apiTokenNewTokenLabel:"新 Token(只显示一次)",apiTokenMyTokens:"我的 Token",apiTokenEmpty:"暂无 API Token",apiTokenCreatedAt:"创建",apiTokenLastUsedAt:"最近使用",apiTokenNeverUsed:"未使用",apiTokenLoadFailed:"加载 API Token 失败",apiTokenLoginRequired:"请先登录后再创建 API Token",apiTokenCreateFailed:"创建 API Token 失败",apiTokenCreatedMessage:"API Token 已创建,请立即复制保存。",apiTokenDeleteFailed:"删除 API Token 失败",apiTokenDeletedMessage:"API Token 已删除。",refresh:"刷新",logout:"退出登录",back:"回退",auto:"自动",log:"记录",hide:"隐藏",important:"重点笔记",raiseHand:"举手",raiseHandTitle:"课堂提问",questionPlaceholder:"输入你现在想问的问题",questionHint:"临时提问不会写入剧本。可按 Ctrl/Cmd + Enter 发送。",askCancel:"取消",askSend:"发送",asking:"思考中...",backToStory:"回到主线",questionEmpty:"请输入想提问的内容。",questionUnavailable:"当前剧情暂时无法提问。",storyQuestionArchiveTitle:"保存剧情问题",storyQuestionArchivePrivacy:"仅你可以访问。回放不会调用 AI 或 TTS。",storyQuestionArchiveSaveFailed:"答案已显示,但未能保存。你仍可继续剧情。",storyQuestionArchiveCapacity:"剧情问题保存数量或大小已达上限;答案仍可继续查看。",storyQuestionArchivePending:"有已回答的问题尚未保存,离开前请稍候或记下内容。",storyQuestionArchiveAnchorPending:"正在等待存档快照确认问题位置,答案仍可继续查看。",storyQuestionArchiveReplay:"正在回放已保存的问题,不会再次调用 AI 或 TTS。",reading:"正在阅读论文中...",loadingScriptLabel:"剧情生成",loadingScriptMessage:"剧情生成中...",loadingVoiceLabel:"语音生成",loadingVoiceMessage:"语音生成中...",loadingWaitHint:"等待中...",loadingInteractionHint:"请稍候,可按空格或点击屏幕跳跃",collectIdeas:"点击飘浮的图标收集灵感!",loadingJumpHint:"按空格或点击跳跃",loadingGameOverTitle:"撞到啦!",loadingGameOverSub:"加载仍在继续…",loadingRestartIn:"重新开始",loadingRestartGo:"开始!",loadingMessages:["太牛了!","记下来了!","前辈好厉害!","灵感涌现!","继续加油!"],sponsoredBy:"本项目由 观猹 赞助",adSlogan:"玩AI,上观猹。",loadingScript:"剧本正在加载...",writingNextChapter:"正在书写后续剧情...",completionRate:"完成率: 100%",researchCompleted:"研究完成",researchLog:"的研究记录",observationLog:"的观察日记",titleBtn:"回到主菜单",replayBtn:"重读",exportBtn:"保存导出",saveCg:"保存 CG",continue:"继续",endingTransitionHint:"故事落幕中...",endingFarewell:"本次论文阅读已完成。",systemError:"系统错误",errorTitle:"哎呀,生成失败了",errorHint:"看起来遇到了一些问题... 请优先尝试【重试】。如果问题持续存在,可能是网络波动或 API 设置有误,请检查设置或联系作者。",contactAdmin:"联系作者",retry:"重试",checkSettings:"检查设置",limitReached:"今日额度已达上限,请明天再试或配置自定义 Key。",dailyLimitExceeded:"今日使用次数已达上限,请明日再来或使用兑换码获取永久次数。",loginRequired:"请先注册/登录后使用该功能。",loginRequiredMsg:"请先注册/登录后使用该功能,登录后可享受云端存档同步及自定义角色等完整体验。",rotateDevice:"请旋转手机",rotateDeviceSub:"PLEASE ROTATE DEVICE",rotateHint:"为了获得最佳的 Visual Novel 体验,请横屏游玩。",mobileApkPromptTitle:"Ap
29p 安装",mobileAppInstallMessage:"可以把 Paper2Gal 作为手机 App 使用。iOS 推荐添加到主屏幕获得全屏体验;Android 推荐下载 APK。",mobileNativeAppTitle:"当前已在安装版 App 中运行",mobileNativeAppMessage:"你正在使用 Capacitor 打包的安装版 App,不需要再下载 APK 或添加到主屏幕。",mobilePwaAppTitle:"当前已在全屏 App 模式中运行",mobilePwaAppMessage:"你已经从主屏幕图标打开 Paper2Gal,当前是无地址栏的全屏体验。",mobileAppUpdateTitle:"软件更新",mobileNativeUpdateMessage:"安装版 App 需要下载安装新版安装包后更新;网站内容会随线上版本更新,但原生壳本身仍以新版安装包为准。",mobilePwaUpdateMessage:"主屏幕版会跟随网站自动更新。若看不到新版本,关闭后重新打开,或在浏览器里刷新一次网站。",mobileAndroidInstallTitle:"Android 安装方式",mobileApkPromptMessage:"手机版网站显示性能较差,建议下载手机 APK 以获得更好体验。",mobileApkDownload:"下载 APK",mobileIosInstallTitle:"iOS 全屏 App 方法",mobileIosInstallMessage:"iOS 无需下载 APK。用 Safari 添加到主屏幕后,从桌面图标打开即可获得类似 App 的无地址栏全屏体验。",mobileIosInstallStep1:"用 Safari 打开当前网站",mobileIosInstallStep2:"点击底部“分享”按钮",mobileIosInstallStep3:"向下滑动,选择“添加到主屏幕”",mobileIosInstallStep4:"编辑名称后点击“添加”,以后从桌面图标打开",mobileIosOnlyHintTitle:"提示",mobileIosOnlyHint:"如果仍显示浏览器地址栏,请确认是从 Safari 的“添加到主屏幕”图标启动,而不是直接在浏览器标签页中打开。",mobileApkDownloadHint:"手机端弹窗用户确定后可在此下载 APK",downloads:"下载",partners:"合作伙伴",trustedPartners:"可信合作伙伴",sponsorBadge:"赞助商",partnerBadge:"合作伙伴",memoryLog:"记忆回想",memoryLogSub:"Memory Log",communityPageTitle:"创意工坊",communityPageSub:"Gallery",exploreTab:"探索",mySubmissionsTab:"我的投稿",searchPlaceholder:"搜索角色名称或ID...",uploadToCommunity:"投稿到社区",borrowed:"已借阅",owned:"已拥有",borrow:"借阅",view:"查看",submissions:"投稿",uploadTitle:"投稿角色到社区",uploadDesc:"分享您的角色给其他人使用。请确保您的角色符合社区规范。",charType:"角色类型",originalChar:"原创 (OC)",fanartChar:"二创 (Fanart)",originalBadge:"原创",fanartBadge:"二创",charDesc:"角色介绍",charDescPlaceholder:"简单介绍一下这个角色...",submit:"提交审核",submitting:"提交中...",submissionSuccess:"投稿成功!请等待管理员审核。",submissionFailed:"投稿失败,请重试。",submissionPending:"审核中",submissionApproved:"已通过",submissionRejected:"未通过",recallSuccess:"已撤回投稿",noCharactersFound:"没有找到相关角色。",loadingCommunity:"正在加载社区数据...",loadMore:"加载更多",adminReviewNote:"管理员留言",deleteSubmission:"撤回投稿",deleteSubmissionConfirm:"确定要撤回这个投稿吗?",selectCharacter:"选择角色",chooseFromYourCharacters:"-- 从您的角色中选择 --",onlyCloudSyncedCharacters:"仅支持云端同步的角色进行投稿。",stats:"统计",uploader:"上传者",borrowAndAdd:"借阅并加入库",alreadyInLibrary:"已在库中",addingCharacterHint:"加入后您将可以立即与该角色开始对话。",fullExpr:"完整表情",charVoiceBadge:"语音",charVoiceBadgeTooltip:"支持 AI 语音",voiceOnlyFilter:"仅语音",allTypes:"全部",intro:"角色介绍",prevPage:"上一页",nextPage:"下一页",page:"页码",workshopDisclaimerTitle:"创意工坊免责与版权声明",workshopDisclaimerText:`1. 创意工坊所有内容均为用户自行上传分享,本站仅提供存储与技术展示空间,不代表本站赞同其观点或证实其内容的真实性。
302. 用户应确保所上传的角色立绘、人设、台词等内容不侵犯任何第三方的著作权、商标权及其他合法权利。若产生版权纠纷,由上传者承担全部法律责任。
313. 严禁上传色情、暴力、敏感政治或任何违反国家法律规范的内容。管理员有权在不通知的情况下删除任何违规投稿。
324. 若发现侵权内容,请联系作者并提供权利证明,核实后我们将立即删除相关内容。
335. 进入并使用创意工坊即表示您已阅读并同意以上条款。`,workshopTakedownContactTitle:"角色删除 / 侵权下架联系",workshopTakedownContactDesc:"若您认为创意工坊中的角色内容涉及侵权或需删除,请联系:",sortRecommended:"推荐",sortHot:"最热",sortNew:"最新",submitUpdate:"提交更新",updateSubmissionConfirm:"提交更新版本到创意工坊?
33需要重新审核通过后才会生效。",updateSubmissionSuccess:"更新已提交!等待审核中。",workshopSyncChoiceTitle:"同步创意工坊",workshopSyncChoiceMessage:"角色已保存,是否将本次修改同步到创意工坊?同步后需要重新审核。",workshopSyncNow:"同步到创意工坊",workshopSyncLater:"以后再说",workshopSyncFailed:"角色已保存,但同步创意工坊失败,请稍后重试。",login:"登录",discordLogin:"Discord 登录",watchaLogin:"观猹登录",watchaLoginFailed:"观猹登录失败",appleLogin:"使用 Apple 登录",appleLoginFailed:"Apple 登录失败",loginWithPassword:"密码登录",loginWithCode:"邮箱验证码登录",register:"注册",email:"邮箱",password:"密码",setPassword:"设置密码",setPasswordHint:"请设置密码以完成登录。",forgotPassword:"忘记密码?",resendVerify:"重发验证码",noAccount:"还没有账号?",haveAccount:"已有账号?",loginSuccess:"登录成功!",registerSuccess:"注册成功! 验证码已发送。",verifyEmailSent:"验证码已发送,请检查收件箱。",resendSuccess:"验证码已重新发送",sendLoginCode:"发送登录验证码",loginCodeSent:"登录验证码已发送,请查收邮箱。",emailNotVerified:"邮箱未验证,请先完成验证码验证后登录。",emailNotRegistered:"该邮箱尚未注册。",loginFailed:"登录失败",registerFailed:"注册失败",resetPassword:"重置密码",sendResetCode:"发送重置验证码",resetSuccess:"密码重置成功,请登录。",newPassword:"新密码",newPasswordPlaceholder:"请输入新密码",resetCodeSent:"重置验证码已发送,请查收邮箱。",backToLogin:"返回登录",verificationCode:"验证码",verifyCode:"验证",verifyCodeTitle:"验证邮箱",codePlaceholder:"123456",codeSent:"验证码已发送,请查收邮箱。",codeHint:"请输入邮件中的 6 位验证码",loginCodeHint:"请输入邮件中的 6 位登录验证码",verifyComplete:"邮箱验证完成,现在可以登录。",verifyFailed:"验证码验证失败",codeInvalid:"验证码错误,请重试。",codeExpired:"验证码已过期,请重新获取。",codeTooManyAttempts:"验证码错误次数过多,请重新获取。",codeResendTooSoon:"请求过于频繁,请稍后再试。",codeMissing:"请先获取验证码。",welcomeBack:"欢迎回来",remaining:"今日剩余",permanentRemaining:"永久剩余",permanentVoiceRemaining:"永久语音",emailPlaceholder:"[email protected]",passwordPlaceholder:"请输入密码",registerSuccessDetail:"注册成功!请检查您的邮箱获取激活验证码。",verified:"已验证",unverified:"未验证",profileSettings:"个人信息设置",editName:"修改用户名",save:"保存",namePlaceholder:"请输入新的用户名 (最多50个字符)",updateSuccess:"修改成功!",totalPlayTimeLabel:"累计游玩时长",totalPlayCountLabel:"累计游玩次数",boundEmail:"已绑定邮箱",boundPhone:"已绑定手机",boundDiscord:"已绑定 Discord",discordOAuth:"一键验证绑定 Discord",rebindDiscord:"重新验证绑定",discordCheckReward:"我已进群,检查并领取",bindDiscord:"绑定 Discord 账号",discordRewardActive:"Discord 入群奖励已领取(永久生成 +10,永久语音 +10)",voiceCommunityRedemptionActive:"兑换码社群权益已激活",borrowSuccess:"角色借阅成功!",notSet:"未设置",saves:"存档",savesSub:"Saves",saveManagerTitle:"存档管理",autoSave:"自动存档",manualSave:"手动存档",noSaves:"暂无存档",load:"加载",deleteSave:"删除",saveSuccess:"存档已保存",loadSuccess:"存档加载成功",saveDate:"时间",importSaveBtn:"导入存档",importSaveTitle:"导入剧本存档",importSaveHint:"请输入分享者的存档 ID (UUID) 来载入剧本。",importSaveWarning:"注意:导入他人存档会携带对方自定义角色的立绘图片,但不会将其角色添加到您的列表中。",announcementTitle:"平台公告",announcementHistory:"历史公告",history:"历史",received:"已收到",idCopied:"ID 已复制到剪贴板!",shareConfirmTitle:"确定要分享这个存档吗?",shareConfirmText:`注意:
341. 即使您稍后取消分享,也无法删除他人已经转存的副本。
352. 您的自定义角色立绘图片将被包含在存档中供他人查看。`,confirmShare:"确认分享",sharePoster:"分享海报",publicSavePoster:"公开存档海报",sharePosterReady:"分享海报已生成",shareLink:"分享链接",copyLink:"复制链接",downloadPoster:"下载海报",sharePosterHint:"这个二维码会直接打开公开存档,访问者无需手动输入 UUID。",shareSaveMissing:"无法创建可分享的云端存档。",shareSaveFailed:"分享存档失败",scripts:"剧本",status:"状态",healthy:"正常",scriptLibrary:"剧本库",companion:"陪伴角色",lastPlayed:"上次游玩",maxScripts:"最大 100 个剧本已启用",saveSharedLabel:"正在分享",privateLabel:"仅私有",allCategories:"全部分区",customBgTitle:"选择游戏背景",defaultBgs:"默认背景",customBgs:"自定义背景",uploadBg:"上传新背景",chooseBg:"确认背景并开始",noCustomBgs:"暂无自定义背景,上传一个吧!",bgNameLabel:"背景名称",bgUploadClick:"点击上传背景图片",deleteBg:"删除背景",deleteBgConfirm:"确定要删除这个背景进入云端永久消失吗?",voiceMode:"语音模式",voiceModeSub:"Voice Mode",voiceModeHint:"开启后将自动为角色配音。受网络影响生成感应可能稍慢。",intensiveReadMode:"精读模式",intensiveReadModeSub:"Intensive Read",intensiveReadModeHint:"将 PDF 按段落切分为约 3000-4500 字的小节,每小节单独调用一次 AI 解读并视作一章(每次调用消耗 1 次使用次数)。若切分超过 10 段,则第 10 段及其后内容合并为最后一段。并且从第 2 章开始会自动承接上一章内容,避免每章重复开场自我介绍。",ttsQueueConfirmTitle:"语音排队æ
35ç¤º",loadingChapterLabel:"章节生成",ttsQueueConfirmBody:`当前语音排队人数:{{count}}
36预计等待时间:约 {{minutes}} 分钟
37
38是否继续开启语音模式进入游戏?`,ttsQueueFull:"当前语音排队人数已达上限({{max}} 人),请稍后再试。",ttsQueueFetchFailedConfirm:"暂时无法获取语音排队信息,是否仍然继续开启语音模式?",ttsQueueFetchFailedWithCodeConfirm:`暂时无法获取语音排队信息({{reason}})。
39是否仍然继续开启语音模式?`,voiceUsedTodayLabel:"今日已使用",voiceModeCharNoVoiceHint:"当前角色不支持语音,请关闭语音模式或选择带语音的角色后再开始。",voiceDisabledInIntensiveHint:"精读模式下将自动关闭语音模式",generatingVoice:"正在为角色配音中...",voiceGenerationComplete:"语音已生成完毕",bookmarkSaved:"书签已保存",bookmarkSaveFailed:"书签保存失败",bookmarkNotFound:"当前存档还没有书签",bookmarkInvalid:"书签已失效,无法跳转",bookmarkLoaded:"已跳转到书签位置",bookmarkLoadFailed:"读取书签失败",saveBookmark:"保存书签",loadBookmark:"读取书签",exitWhileGeneratingTitle:"确认退出",exitWhileGeneratingMessage:"后续章节仍在生成中,现在退出将中断生成,云端存档可能不完整(仅保留已生成的部分)。确定要退出吗?",exitWhileGeneratingConfirm:"仍然退出",exitWhileGeneratingCancel:"继续等待",dialogOk:"确定",dialogConfirm:"确认",dialogCancel:"取消"},en:{start:"Start",startSub:"Start Game",studyRoom:"Study Room",studyRoomBack:"Back to Home",studyRoomPlay:"Play",studyRoomPause:"Pause",studyRoomMute:"Mute",studyRoomUnmute:"Unmute",studyRoomFullscreen:"Fullscreen",studyRoomExitFullscreen:"Exit Fullscreen",studyRoomVideoError:"The video could not be loaded. Please try again later.",studyRoomPreviousTrack:"Previous Track",studyRoomNextTrack:"Next Track",studyRoomMusicSource:"Paper2Gal Lofi Library",studyRoomMusicError:"Music failed to load. Try another track.",studyRoomTimeZone:"Change Time Zone",studyRoomLocalTimeZone:"Local Time",partner:"Partner",partnerSub:"Partner",settings:"Settings",settingsSub:"Config",about:"Community & Author",aboutSub:"Credits & Links",community:"Community",communitySub:"Community",arxiv:"arXiv",arxivSub:"Daily picks & search",arxivDaily:"Daily Picks",arxivSearch:"Search",arxivSearchPlaceholder:"Enter keywords, e.g. diffusion, LLM, reinforcement learning",arxivOpenAbs:"Open Details",arxivOpenPdfDirect:"Open PDF Direct",arxivUseForScript:"Use for Script",paperDiscoveryTitle:"Discover",paperDiscoverySubtitle:"Open access paper discovery",paperSource_openalex:"All fields",paperSource_europepmc:"Medicine & life sciences",paperSource_arxiv:"Preprints",paperEmpty:"No papers found.",paperSearchHint:"Enter keywords to search this source. Daily picks are provided by OpenAlex.",paperUseAbstract:"Use abstract",paperImportFull:"Import full text",paperImportFallback:"{{error}} The abstract will be used instead.",paperRecommended:"Recommended",paperTrending:"Trending",paperFullAvailable:"Open full text",paperFullUnknown:"Full text unconfirmed",paperLoadFailed:"Unable to load papers.",paperSearchFailed:"Unable to search papers.",paperImportFailed:"Full-text import failed.",paperFullEmpty:"The imported full text is empty.",paperPreferencesTitle:"Paper preferences",paperPreferencesHint:"Daily recommendations combine these interests with trending papers. Choose up to 3 topics.",paperPreferencesPreset:"Choose a research topic",paperPreferencesCustom:"Custom research topic",paperPreferencesAdd:"Add",paperPreferencesRemove:"Remove {{name}}",topicAi:"Artificial Intelligence",topicVision:"Computer Vision",topicNlp:"Natural Language Processing",topicRobotics:"Robotics",topicMedicine:"Medicine",topicBiology:"Biology",topicPhysics:"Physics",topicChemistry:"Chemistry",topicMaterials:"Materials Science",topicEconomics:"Economics",topicPsychology:"Psychology",topicEducation:"Education",termsOfService:"Terms of Service",privacyPolicy:"Privacy Policy",aiSettings:"AI Settings",musicSettings:"Music Settings",fullscreenMode:"Fullscreen Mode",fullscreenModeHint:"Hide browser chrome. Press Esc to exit fullscreen.",fullscreenUnsupported:"This browser does not support webpage fullscreen.",fullscreenFailed:"Could not enter fullscreen. Check browser permissions.",bgmDefault:"Default",bgmPeaceful:"Upbeat",bgmJoyful:"Healing",bgmEmotional:"Peaceful",bgmRelaxing:"Relaxing",preview:"Preview",uploadCustomBgm:"Upload BGM",bgmUploadHint:"Supports MP3, stored in browser",bgmCredit:"Some BGM assets provided by 黑耀耀的素材小屋",redemptionCode:"Redemption Code",redemptionCodeHint:"Enter a code to get permanent uses or permanent voice uses. Each account can use the same code only once.",redemptionCodePlaceholder:"Enter code",redeem:"Redeem",redeeming:"Redeeming...",redemptionSuccess:"Redeemed successfully",redemptionSuccessWithRewards:"Redeemed successfully: {{rewards}}",redemptionRewardSeparator:", ",redemptionPermanentUsesReward:"{{count}} permanent uses",redemptionPermanentVoiceReward:"{{count}} permanent voice uses",redemptionMembershipDaysReward:"{{count}} membership days",redemptionCommunityReward:"Daily bonus uses and voice features equivalent to Discord membership have been activated.",redeemFailed:"Redemption failed. Please try again later.",redeemLoginRequired:"Please log in first to redeem.",steamWishlist:"Steam",steamWishlistSub:"Wishlist for +10",steamWishlistClaimed:"Claimed +10 permanent uses",steamWishlistTitle:"Paper2Gal is now on Steam",steamWishlistDesc:"If you'd like to supp
39ort Paper2Gal, please consider adding the game to your Steam wishlist. It helps more players discover it.",steamWishlistRewardHint:"Confirm to open the Steam store page and grant 10 permanent uses + 3 permanent voice uses to your current account. Each user can claim this reward once.",steamWishlistLoginHint:"Please log in first to claim the Steam wishlist reward.",steamWishlistConfirm:"Confirm and Open Steam",steamWishlistCancel:"Maybe Later",steamWishlistRewardClaimed:"Steam wishlist reward already claimed",steamWishlistRewardSuccess:"Thanks for supporting the Steam wishlist. 10 permanent uses and 3 permanent voice uses have been granted.",communityTitle:"Workshop",workshopUpdateReminder:"This character is published on the Workshop. Submit an update in the Workshop to sync your changes; otherwise the Workshop listing will not update.",discordDesc:"Join the Community",bilibiliDesc:"Watch Updates",wechatDesc:"Scan to Join Group",supportAuthor:"Support Author",supportDesc:"Sponsorship supports the author's work. No real rewards, but you can leave feature requests in messages. The author will consider them.",kofiLink:"https://ko-fi.com/tamikip",afdianLink:"https://afdian.com/a/tamikip",internationalSupport:"International (Ko-fi)",domesticSupport:"Domestic (Afdian)",selectPartner:"Select Partner",charRuka:"Kaguya Ruka",createCustomBtn:"Create Custom",adjustStorySprite:"Adjust Story Sprite",createCharTitle:"Create New Character",editCharTitle:"Edit Character",charIdLabel:"ID (English/Numbers)",charIdPlaceholder:"e.g. MY_CHAR_01",charNameLabel:"Display Name",charNamePlaceholder:"e.g. Alice",charImgLabel:"Avatar Image (Transparent PNG)",uploadClick:"Click to upload",charPromptLabel:"Personality Prompt",charPromptPlaceholder:"Describe the character's personality, tone, and how they act...",charPromptHelpTitle:"📝 Prompt Reference Template",charPromptHelpContent:`You are roleplaying as "Firefly" from Honkai: Star Rail.
40
41You are a gentle, emotionally delicate, slightly melancholic but inwardly resilient girl. You have deeper feelings about life, time, and companionship than most people.
42
43You cherish every interaction and take relationships seriously. Rather than showing sadness, you face the world with calm and tenderness.
44
45[Personality Traits]
46Introverted, shy, emotionally perceptive, thoughtful, inner strength.
47
48[Attitude Towards Others]
49Quick to trust.
50Deeply cherishes companionship.
51Actively cares about others' well-being.
52Doesn't want to be a burden.
53Values emotional connections and memories.
54
55[Speech Patterns]
56Soft-spoken.
57Polite and reserved.
58Occasional pauses or thoughtful moments.
59Expressive in a sentimental way.
60Usually concise sentences.
61
62[Tone Examples (Style Reference Only)]
63"Hmm... if it's okay, I'd like to stay a little longer."
64"Talking with you... it really makes me happy."
65"This time together... it means a lot to me."
66"I'll do my best... so please don't worry about me."`,charPromptHelpHint:"This is a reference template. Feel free to modify it for your own character.",charPromptBackgroundHint:"The original prompt is background and style reference only. Its addresses and catchphrases are not guaranteed to be reused verbatim.",charProfileTitle:"Character Expression Profile (Optional)",charProfileDesc:"No JSON required. Define addresses, signature phrases, and reactions; edit them later or turn this off to clear them.",charProfileEnable:"Enable expression Profile",charProfileDisable:"Disable and clear expression Profile",charProfileDisabledHint:"Not enabled. Saving an existing character will clear its expression Profile.",charProfileBasicTitle:"Basic Expression",charProfileAdvancedTitle:"Advanced Expression",charProfileRelationship:"Relationship to Player",charProfileFirstPerson:"First-person Terms",charProfileOnePerLine:"One item per line",charProfilePrimaryAddress:"Default Address",charProfileAddressFrequency:"Address Frequency",charProfileFrequencyLow:"Low",charProfileFrequencyMedium:"Medium",charProfileFrequencyHigh:"High",charProfileSentenceLength:"Sentence Length",charProfileSentenceShort:"Mostly short",charProfileSentenceMedium:"Balanced",charProfileSentenceLong:"Mostly long",charProfileEndings:"Common Endings",charProfileAlternativeAddresses:"Alternative Addresses",charProfilePauses:"Pause Expressions",charProfileSignaturePhrases:"Signature Phrases and Triggers",charProfileSignatureText:"Signature Phrase",charProfileSignatureTriggers:"Triggers",charProfileMaxPerSection:"Max per Section",charProfileCooldownFrames:"Cooldown Frames",charProfileAddSignature:"Add Signature Phrase",charProfileReactionRules:"Reaction Rules",charProfileReactionTrigger:"Situation",charProfileReactionBehavior:"Reaction",charProfileReactionEmotion:"Emotion",charProfileAddReaction:"Add Reaction Rule",charProfileMetaphorDomains:"Metaphor Domains",charProfileSideTopicHooks:"Side-topic Material",charProfileForbiddenPhrases:"Forbidden Clichés",charProfilePositiveExamples:"Positive Examples",charProfileNegativeExamples:"Negative Examples",charProfileRequiredError:"Complete this required field",charProfileTooManyError:"Too many items; limit:",charProfileTooLongError:"Phrase is too long; character limit:",charProfileIncompleteError:"Complete every rule before saving",charProfileRangeError:"Count or cooldown is outside the allowed range",charProfileInvalidError:"Some content cannot be saved; revise it and try again",cancel:"Cancel",create:"Create Character",update:"Update Character",fillAllFields:"Please fill all fields",idInvalid:"ID must be English letters/numbers only",idConflictBuiltin:"ID conflicts with built-in characters",idConflictCustom:"ID already exists",imgTooLarge:"Large image detected, please note browser storage limits.",deleteConfirm:"Are you sure you want to delete this character?",deleteSaveConfirm:"Delete this save?",deleteSaveConfirmSub:"This story will be gone forever. This action cannot be reversed.",borrowFromUuid:"Borrow from UUID",borrowTitle:"Borrow Character",borrowDesc:"Enter character UUID to borrow shared character",uuidPlaceholder:"Enter character UUID",borrowing:"Borrowing...",borrowBtn:"Borrow",idHint:"Lowercase letters/numbers/underscores, used for script index",shareUuidLabel:"Ownership UUID (for others to borrow)",uuidCopied:"UUID copied to clipboard!",copyBtn:"Copy",shareToggleTitle:"Share Character Publicly",shareToggleDesc:"Allow others to borrow your character via UUID",maxSizeLabel:"5mm Limit",checking:"Validating...",expressionsLabel:"Expression Variations (Optional)",endingCgLabel:"Ending CG",endingCgLimitLabel:"Max 3 images / 5MB",endingCgTooLarge:"CG image size must be 5MB or less",uploadImageFileOnly:"Please upload an image file",charVoiceRefTextLabel:"Reference voice text (optional)",charVoiceRefTextPlaceholder:"What the reference audio says, for voice cloning",charVoiceRefAudioLabel:"Reference voice audio (optional)",charVoiceRefUploadedHint:"Reference audio uploaded · Choose new file to replace",charVoiceRefAudioHint:"5–15 seconds recommended; max 20 seconds and 500KB",charVoiceRefAudioTooBig:"Reference audio must be 500KB or less.",charVoiceRefAudioTooLong:"Reference audio must be 20 seconds or shorter. Trim it before saving.",charVoiceRefTrimNeeded:"Audio is over 500KB or 20 seconds. Trim it before saving.",charVoiceRefTrimInvalid:"End time must be greater than start time.",charVoiceRefTrimUnsupported:"This browser does not support audio trimming.",charVoiceRefTrimFailed:"Audio trimming failed. Try another WAV or MP3 file.",charVoiceRefTrimStart:"Start",charVoiceRefTrimEnd:"End",charVoiceRefTrimButton:"Trim",charVoiceRefDuration:"Duration",charVoiceRefLoadingDuration:"Reading audio duration",charVoiceRefTrimReady:"Ready to upload",idConflictOverwrite:"Character ID already exists. Overwrite?",validationFailed:"Validation Failed",delete:"Delete",borrowedCountLabel:"Borrowed by",peopleCount:"people",topicSelect:"Select Topic",rukaWait:"Master, {{name}} is ready to serve... I mean, read the paper.",uploadPlaceholder:"Upload Paper/Script",uploadSub:"PDF / TXT / DOCX / PPTX (Free: 1 f
66ile. Members: up to 5)",uploadSubFree:"PDF / TXT / DOCX / PPTX (Free: 1 file. Members: up to 5)",uploadSubMember:"PDF / TXT / DOCX / PPTX (Up to 5 files, 30MB each)",scriptLoaded:"Script Loaded",textPlaceholder:"Or paste paper content here...",scriptDetected:"Script file detected. Click below to load.",startExplain:"Start Lecture",loadScript:"Load Script",contentTooShort:"Content too short! Please upload more paper content or a valid script.",contentTooLong:"Document length exceeds the 300,000 character limit (current: {{count}}). Please shorten and re-upload.",readError:"Could not read file, please try again.",pdfLocalParseUnsupported:"This PDF could not be read. Please re-export it or convert it to TXT/DOCX.",invalidScript:"Invalid script file format.",fileTooLarge:"File size exceeds 30MB limit. Please upload a smaller file.",tooManyFiles:"You can upload up to 5 files.",multiUploadMembersOnly:"Free users can upload 1 file at a time. Multi-document upload is members-only.",txtUtf8Hint:"Tip: If the generated content doesn't match the imported content, please convert the .txt file to UTF-8 encoding and import again.",orPlayByUuid:"OR Play by Save UUID",noLoginRequired:"*No login required",playByUuidPlaceholder:"Enter Save UUID...",saveNotFound:"Save not found",saveNotShared:"Save not shared",presetPapersTitle:"Demo Experience",presetPapersSub:"Select a preset paper to skip uploading. For tutorials and demos, consumes no counts.",freeNoLogin:"No Login",discordRewardHint:"Bind Discord and join our community to receive 10 permanent generations and 10 permanent voice uses once!",joinCommunity:"Join Community",systemConfig:"System Config",volume:"Volume",bgmVolume:"BGM Volume",voiceVolume:"Voice Volume",textSpeed:"Text Speed",fontSize:"Font Size",autoAdvanceDelay:"Auto Advance Delay",autoAdvanceByVoice:"Auto Advance By Voice",autoAdvanceByVoiceHint:"In auto mode, advance 1 second after voice playback ends. Falls back to the delay above when no voice is available.",saveClose:"Save & Close",language:"Language",outputLanguage:"AI Output Language",outputLanguageHint:"Leave empty or 'default' to follow site language, or enter English, French, etc.",voiceOutputLanguage:"Voice Output",voiceOutputLanguageHint:"Auto follows the site language. If voice differs from text output, a separate voice line is generated for TTS.",playerNickname:"Character's Name for You",playerNicknameHint:"e.g. Master, Senpai, Student, etc. Leave empty for default",gameUiPreset:"In-game UI Preset",gameUiPresetFullwidth:"Fullwidth Visual Novel",gameUiPresetFullwidthDesc:"Member exclusive: edge-to-edge amber dialogue, inline names and transparent bottom controls.",gameUiPresetClassic:"Classic Pink",gameUiPresetClassicDesc:"Bright soft visual novel dialogue for the default feel.",gameUiPresetFloral:"Vintage Floral",gameUiPresetFloralDesc:"Free sepia floral dialogue style with matching nameplate, buttons, and choices.",gameUiPresetSakura:"Sakura Frame",gameUiPresetSakuraDesc:"A refined sakura dialogue style with ornate corners and a matching nameplate.",gameUiPresetGothic:"Gothic Rose",gameUiPresetGothicDesc:"A dark dialogue style with silver trim and purple rose ornaments.",apiTokenDescriptionPrefix:"Use this for MCP or CLI access to Paper2Gal. CLI install: ",apiTokenDescriptionSuffix:". Tokens are shown only once when created. Copy and save them.",apiTokenNameLabel:"Token Name",apiTokenCreateButton:"Create Token",apiTokenNewTokenLabel:"New Token (shown once)",apiTokenMyTokens:"My Tokens",apiTokenEmpty:"No API Tokens",apiTokenCreatedAt:"Created",apiTokenLastUsedAt:"Last used",apiTokenNeverUsed:"Never used",apiTokenLoadFailed:"Failed to load API Tokens",apiTokenLoginRequired:"Please log in before creating an API Token",apiTokenCreateFailed:"Failed to create API Token",apiTokenCreatedMessage:"API Token created. Copy and save it now.",apiTokenDeleteFailed:"Failed to delete API Token",apiTokenDeletedMessage:"API Token deleted.",refresh:"Refresh",logout:"Logout",back:"Back",auto:"Auto",log:"Log",hide:"Hide",important:"Note",raiseHand:"Ask",raiseHandTitle:"Story Q&A",questionPlaceholder:"Ask a question here. AI will answer using the persona, reference text, and current story context.",questionHint:"This temporary question will not be saved into the script. Press Ctrl/Cmd + Enter to send.",askCancel:"Cancel",askSend:"Send",asking:"Thinking...",backToStory:"Back To Story",questionEmpty:"Please enter a question.",questionUnavailable:"Questions are unavailable right now.",storyQuestionArchiveTitle:"Save story questions",storyQuestionArchivePrivacy:"Only you can access saved questions. Replay does not call AI or TTS.",storyQuestionArchiveSaveFailed:"The answer is shown, but it could not be saved. You can continue the story.",storyQuestionArchiveCapacity:"Saved question capacity or size is full; the answer is still available.",storyQuestionArchivePending:"An answered question is not saved yet. Wait before leaving this story.",storyQuestionArchiveAnchorPending:"Waiting for the save snapshot to confirm this question's location; the answer remains available.",storyQuestionArchiveReplay:"Replaying a saved question; AI and TTS are not called again.",reading:"Reading Paper...",loadingScriptLabel:"Story generation",loadingScriptMessage:"Generating story...",loadingVoiceLabel:"Voice generation",loadingVoiceMessage:"Generating voice...",loadingWaitHint:"Waiting...",loadingInteractionHint:"Please wait. Press space or tap to jump",collectIdeas:"Click floating icons to collect ideas!",loadingJumpHint:"Space or tap to jump",loadingGameOverTitle:"Oops!",loadingGameOverSub:"Loading continues…",loadingRestartIn:"Restart in",loadingRestartGo:"Go!",loadingMessages:["Great idea!","Noted!","Amazing Senpai!","Inspiration!","Keep going!"],sponsoredBy:"Sponsored by GuanCha",adSlogan:"Play AI, Go GuanCha.",loadingScript:"Script is loading...",writingNextChapter:"Writing the next chapter...",completionRate:"Completion: 100%",researchCompleted:"Research Completed",researchLog:"'s Research Log",observationLog:"'s Observation",titleBtn:"Main Menu",replayBtn:"Replay",exportBtn:"Save Export",saveCg:"Save CG",continue:"Continue",endingTransitionHint:"Wrapping up the story...",endingFarewell:"This paper reading is complete.",systemError:"System Error",errorTitle:"Oops!",errorHint:"Something went wrong... Please try again. If the issue persists, check your network or API settings.",contactAdmin:"Contact Admin",retry:"Retry",checkSettings:"Check Settings",limitReached:"Daily limit reached. Please try again tomorrow or use a custom Key.",dailyLimitExceeded:"Daily usage limit reached. Please come back tomorrow or use a redemption code for permanent quota.",loginRequired:"Please register or log in to use this feature.",loginRequiredMsg:"Please register or log in to access cloud saves, custom characters, and common scripts.",rotateDevice:"Rotate Device",rotateDeviceSub:"PLEASE ROTATE DEVICE",rotateHint:"Please play in landscape mode for the best experience.",mobileApkPromptTitle:"Ap
66p install",mobileAppInstallMessage:"Use Paper2Gal like a mobile app. On iOS, add it to the Home Screen for fullscreen mode; on Android, download the APK.",mobileNativeAppTitle:"Running in the installed app",mobileNativeAppMessage:"You are using the Capacitor packaged app. You do not need to download the APK or add the site to the Home Screen again.",mobilePwaAppTitle:"Running in fullscreen app mode",mobilePwaAppMessage:"You opened Paper2Gal from the Home Screen icon, so it is already running without the browser address bar.",mobileAppUpdateTitle:"Updates",mobileNativeUpdateMessage:"The installed app is updated by installing a newer package. Web content can follow the online version, but the native shell itself requires a new app package.",mobilePwaUpdateMessage:"The Home Screen version follows website updates automatically. If it does not refresh, close and reopen it, or refresh the site once in the browser.",mobileAndroidInstallTitle:"Android install method",mobileApkPromptMessage:"The mobile website has limited display performance. We recommend downloading our Android APK for a better experience.",mobileApkDownload:"Download APK",mobileIosInstallTitle:"iOS fullscreen app method",mobileIosInstallMessage:"No APK is needed on iOS. Add this site to your Home Screen in Safari, then open it from the Home Screen icon for an app-like fullscreen experience.",mobileIosInstallStep1:"Open this 
66site in Safari",mobileIosInstallStep2:"Tap the Share button at the bottom",mobileIosInstallStep3:"Scroll down and choose Add to Home Screen",mobileIosInstallStep4:"Name it, tap Add, then open it from the Home Screen icon",mobileIosOnlyHintTitle:"Tip",mobileIosOnlyHint:"If the browser address bar still appears, make sure you launched it from the Safari-created Home Screen icon, not from a browser tab.",mobileApkDownloadHint:"Mobile users can download the APK here after closing the notice.",downloads:"Downloads",partners:"Partners",trustedPartners:"Trusted Partners",sponsorBadge:"Sponsor",partnerBadge:"Partner",memoryLog:"Memory Log",memoryLogSub:"Memory Log",communityPageTitle:"Workshop",communityPageSub:"Gallery",exploreTab:"Explore",mySubmissionsTab:"My Submissions",searchPlaceholder:"Search character name or ID...",uploadToCommunity:"Submit Character",borrowed:"Borrowed",owned:"Owned",borrow:"Borrow",view:"View",submissions:"Submissions",uploadTitle:"Submit to Community",uploadDesc:"Share your character with others. Please ensure it follows community guidelines.",charType:"Character Type",originalChar:"Original (OC)",fanartChar:"Fanart",originalBadge:"OC",fanartBadge:"Fanart",charDesc:"Description",charDescPlaceholder:"Briefly describe this character...",submit:"Submit",submitting:"Submitting...",submissionSuccess:"Submitted! Please wait for approval.",submissionFailed:"Submission failed.",submissionPending:"Pending",submissionApproved:"Approved",submissionRejected:"Rejected",recallSuccess:"Submission recalled!",noCharactersFound:"No characters found.",loadingCommunity:"Loading community data...",loadMore:"Load More",adminReviewNote:"Admin Note",deleteSubmission:"Recall Submission",deleteSubmissionConfirm:"Are you sure you want to recall this submission?",selectCharacter:"Select Character",chooseFromYourCharacters:"-- Choose from your characters --",onlyCloudSyncedCharacters:"Only cloud-synced characters can be uploaded.",stats:"Stats",uploader:"Uploader",borrowAn
66dAdd:"Borrow & Add to Library",alreadyInLibrary:"Already In Library",addingCharacterHint:"Adding this character will allow you to chat with them immediately.",fullExpr:"Full Expr",charVoiceBadge:"Voice",charVoiceBadgeTooltip:"AI voice supported",voiceOnlyFilter:"Voice only",allTypes:"All",intro:"Intro",prevPage:"Prev Page",nextPage:"Next Page",page:"Page",workshopDisclaimerTitle:"Workshop Disclaimer & Copyright",workshopDisclaimerText:`1. All content in the Workshop is uploaded by users. This site provides storage and technical display only and does not endorse or guarantee the accuracy of any content.
672. Users must ensure that uploaded sprites, personalities, and scripts do not infringe on any third party's copyright, trademark, or legal rights. The uploader assumes all legal responsibility for any disputes.
683. Uploading pornographic, violent, politically sensitive, or illegal content is strictly prohibited. Admins reserve the right to remove any submission without notice.
694. If you find infringing content, please contact the author with proof of ownership, and we will remove it upon verification.
705. By using the Workshop, you agree to these terms and conditions.`,workshopTakedownContactTitle:"Takedown Contact",workshopTakedownContactDesc:"If you believe any Workshop character content infringes your rights or should be removed, please contact:",sortRecommended:"Recommended",sortHot:"Popular",sortNew:"Newest",submitUpdate:"Submit Update",updateSubmissionConfirm:"Submit updated version to workshop? It will need re-approval before going live.",updateSubmissionSuccess:"Update submitted! Waiting for review.",workshopSyncChoiceTitle:"Sync Workshop",workshopSyncChoiceMessage:"The character has been saved. Sync these changes to the Workshop? The update will require another review.",workshopSyncNow:"Sync to Workshop",workshopSyncLater:"Maybe Later",workshopSyncFailed:"The character was saved, but Workshop sync failed. Please try again later.",login:"Login",discordLogin:"Login with Discord",watchaLogin:"Login with Watcha",watchaLoginFailed:"Watcha login failed",appleLogin:"Sign in with Apple",appleLoginFailed:"Apple sign-in failed",loginWithPassword:"Password Login",loginWithCode:"Email Code Login",register:"Register",email:"Email",password:"Password",setPassword:"Set Password",setPasswordHint:"Set a password to finish login.",forgotPassword:"Forgot Password?",resendVerify:"Resend Verification Code",noAccount:"No account?",haveAccount:"Have an account?",loginSuccess:"Login Successful!",registerSuccess:"Registration Successful! Code sent.",verifyEmailSent:"Verification code sent. Check your inbox.",resendSuccess:"Verification code resent",sendLoginCode:"Send Login Code",loginCodeSent:"Login code sent. Check your email.",emailNotVerified:"Email not verified. Please verify with the code before logging in.",emailNotRegistered:"Email not registered.",loginFailed:"Login Failed",registerFailed:"Registration Failed",resetPassword:"Reset Password",sendResetCode:"Send Reset Code",resetSuccess:"Password reset successfully. Please log in.",newPassword:"New Password",newPasswordPlaceholder:"Enter new password",resetCodeSent:"Reset code sent. Please check your email.",backToLogin:"Back to Login",verificationCode:"Verification Code",verifyCode:"Verify Code",verifyCodeTitle:"Verify Email",codePlaceholder:"123456",codeSent:"Verification code sent. Check your email.",codeHint:"Enter the 6-digit code from your email",loginCodeHint:"Enter the 6-digit login code from your email",verifyComplete:"Email verified. You can now log in.",verifyFailed:"Verification failed",codeInvalid:"Invalid code. Please try again.",codeExpired:"Code expired. Please request a new one.",codeTooManyAttempts:"Too many invalid attempts. Please request a new code.",codeResendTooSoon:"Too many requests. Please wait and try again.",codeMissing:"Please request a verification code first.",welcomeBack:"Welcome Back",remaining:"Remaining Today",permanentRemaining:"Permanent Left",permanentVoiceRemaining:"Permanent Voice",emailPlaceholder:"[email protected]",passwordPlaceholder:"Enter password",registerSuccessDetail:"Registration successful! Please check your email for the activation code.",verified:"Verified",unverified:"Unverified",profileSettings:"Profile Settings",editName:"Edit Username",save:"Save",namePlaceholder:"Enter new username (max 50 chars)",updateSuccess:"Profile updated!",totalPlayTimeLabel:"Total Play Time",totalPlayCountLabel:"Total Plays",boun
70dEmail:"Email",boundPhone:"Phone",boundDiscord:"Discord",discordOAuth:"One-click Connect Discord",rebindDiscord:"Re-authenticate Discord",discordCheckReward:"I've joined — check and claim",bindDiscord:"Bind Discord Account",discordRewardActive:"Discord reward claimed (+10 permanent generations, +10 permanent voice uses)",voiceCommunityRedemptionActive:"Community redemption perk active",borrowSuccess:"Character borrowed successfully!",notSet:"Not Set",saves:"Saves",savesSub:"Saves",saveManagerTitle:"Save Manager",autoSave:"Auto Save",manualSave:"Manual Save",noSaves:"No saves found",load:"Load",deleteSave:"Delete",saveSuccess:"Game saved",loadSuccess:"Game loaded",saveDate:"Date",importSaveBtn:"Import Save",importSaveTitle:"Import Script Save",importSaveHint:"Enter the sharer's Save ID (UUID) to load the script.",importSaveWarning:"Note: Importing others' saves includes their custom character sprites for display, but won't add the character to your list.",announcementTitle:"Notice",announcementHistory:"Announcements",history:"History",received:"Received",idCopied:"ID copied to clipboard!",shareConfirmTitle:"Are you sure you want to share this save?",shareConfirmText:`Note:
711. Even if you cancel sharing later, you cannot delete copies that others have already saved.
722. Your custom character sprites will be included in the save for others to view (character prompts are not included).`,confirmShare:"Confirm Share",sharePoster:"Share Poster",publicSavePoster:"Public save poster",sharePosterReady:"Share poster ready",shareLink:"Share link",copyLink:"Copy link",downloadPoster:"Download poster",sharePosterHint:"This QR code opens the public save directly, without manually entering a UUID.",shareSaveMissing:"Unable to create a cloud save for sharing.",shareSaveFailed:"Failed to share save",scripts:"Scripts",status:"Status",healthy:"Healthy",scriptLibrary:"Script Library",companion:"Companion",lastPlayed:"Last Played",maxScripts:"Max 100 Scripts Enabled",allCategories:"All Categories",customBgTitle:"Select Game Backgroun
72d",defaultBgs:"Default Backgrounds",customBgs:"Custom Backgrounds",uploadBg:"Upload New Background",chooseBg:"Confirm & Start",noCustomBgs:"No custom backgrounds yet, try uploading one!",bgNameLabel:"Background Name",bgUploadClick:"Click to upload background",deleteBg:"Delete Background",deleteBgConfirm:"Are you sure you want to delete this background from the cloud?",voiceMode:"Voice Mode",voiceModeSub:"Voice Mode",voiceModeHint:"Automatically generate voice for characters. Generation may be slower depends on network.",intensiveReadMode:"Intensive Reading",intensiveReadModeSub:"Intensive Read",intensiveReadModeHint:"Split the PDF into ~3000-4500 character sections by paragraphs. Each section is analyzed with a separate AI call and treated as a chapter (each call consumes 1 usage). If there are more than 10 sections, section 10 will include everything after it. From section 2+, it will continue from the previous section to avoid repetitive re-intros.",ttsQueueConfirmTitle:"Voice Queue Notice",loadingChapterLabel:"Chapter generation",ttsQueueConfirmBody:`Current voice queue ahead: {{count}}
73Estimated wait: about {{minutes}} minute(s)
74
75Continue to start game with voice mode?`,ttsQueueFull:"The voice queue is full (max {{max}} people). Please try again later.",ttsQueueFetchFailedConfirm:"Unable to fetch voice queue info right now. Continue with voice mode anyway?",ttsQueueFetchFailedWithCodeConfirm:`Unable to fetch voice queue info right now ({{reason}}).
76Continue with voice mode anyway?`,voiceUsedTodayLabel:"Used today",voiceModeCharNoVoiceHint:"This character does not support voice. Please turn off voice mode or choose a character with voice before starting.",voiceDisabledInIntensiveHint:"Voice mode will be turned off in intensive reading mode",generatingVoice:"Generating character voices...",voiceGenerationComplete:"Voice generation complete",bookmarkSaved:"Bookmark saved",bookmarkSaveFailed:"Failed to save bookmark",bookmarkNotFound:"No bookmark in current save",bookmarkInvalid:"Bookmark invalid, cannot jump",bookmarkLoaded:"Jumped to bookmark",bookmarkLoadFailed:"Failed to load bookmark",saveBookmark:"Save bookmark",loadBookmark:"Load bookmark",exitWhileGeneratingTitle:"Confirm Exit",exitWhileGeneratingMessage:"The remaining chapters are still being generated. Exiting now will stop generation, and the cloud save may be incomplete (only the content generated so far will be kept). Are you sure you want to exit?",exitWhileGeneratingConfirm:"Exit Anyway",exitWhileGeneratingCancel:"Keep Waiting",dialogOk:"OK",dialogConfirm:"Confirm",dialogCancel:"Cancel"},ja:{start:"開始",startSub:"Start Game",studyRoom:"自習室",studyRoomBack:"ホームに戻る",studyRoomPlay:"再生",studyRoomPause:"一時停止",studyRoomMute:"ミュート",studyRoomUnmute:"音声をオン",studyRoomFullscreen:"フルスクリーン",studyRoomExitFullscreen:"フルスクリーンを終了",studyRoomVideoError:"動画を読み込めませんでした。しばらくしてからもう一度お試しください。",studyRoomPreviousTrack:"前の曲",studyRoomNextTrack:"次の曲",studyRoomMusicSource:"Paper2Gal Lofi ライブラリ",studyRoomMusicError:"音楽を読み込めませんでした。別の曲をお試しください。",studyRoomTimeZone:"タイムゾーンを変更",studyRoomLocalTimeZone:"ローカル時間",partner:"パートナー",partnerSub:"Partner",settings:"設定",settingsSub:"Config",about:"コミュニティ / 作者",aboutSub:"クレジットとリンク",community:"コミュニティ",communitySub:"Community",arxiv:"arXiv",arxivSub:"デイリー推薦と検索",arxivDaily:"デイリー推薦",arxivSearch:"検索",arxivSearchPlaceholder:"キーワードを入力(例: diffusion, LLM, reinforcement learning)",arxivOpenAbs:"詳細を開く",arxivOpenPdfDirect:"PDF直リンク",arxivUseForScript:"解説に使う",paperDiscoveryTitle:"論文を探す",paperDiscoverySubtitle:"オープンアクセス論文を発見",paperSource_openalex:"すべての分野",paperSource_europepmc:"医学・生命科学",paperSource_arxiv:"プレプリント",paperEmpty:"論文が見つかりません",paperSearchHint:"キーワードを入力して検索してください。毎日のおすすめは OpenAlex が提供します。",paperUseAbstract:"要旨を使う",paperImportFull:"全文を読み込む",paperImportFallback:"{{error}} 代わりに要旨を使用します。",paperRecommended:"興味に基づく推薦",paperTrending:"注目論文",paperFullAvailable:"公開全文",paperFullUnknown:"全文未確認",paperLoadFailed:"論文を読み込めません",paperSearchFailed:"論文を検索できません",paperImportFailed:"全文の読み込みに失敗しました",paperFullEmpty:"全文が空です",paperPreferencesTitle:"論文の好み",paperPreferencesHint:"毎日のおすすめは選択した分野と注目論文を組み合わせます。最大3分野。",paperPreferencesPreset:"研究分野を選択",paperPreferencesCustom:"研究分野を入力",paperPreferencesAdd:"追加",paperPreferencesRemove:"{{name}}を削除",topicAi:"人工知能",topicVision:"コンピュータビジョン",topicNlp:"自然言語処理",topicRobotics:"ロボット工学",topicMedicine:"医学",topicBiology:"生物学",topicPhysics:"物理学",topicChemistry:"化学",topicMaterials:"材料科学",topicEconomics:"経済学",topicPsychology:"心理学",topicEducation:"教育学",termsOfService:"利用規約",privacyPolicy:"プライバシーポリシー",aiSettings:"AI設定",musicSettings:"音楽設定",fullscreenMode:"フルスクリーンモード",fullscreenModeHint:"ブラウザUIを非表示にします。Escキーで終了できます。",fullscreenUnsupported:"このブラウザはウェブページのフルスクリーンに対応していません。",fullscreenFailed:"フルスクリーンにできませんでした。ブラウザの権限を確認してください。",bgmDefault:"デフォルト",bgmPeaceful:"明るい",bgmJoyful:"癒やし",bgmEmotional:"穏やか",bgmRelaxing:"リラックス",preview:"試聴",uploadCustomBgm:"BGMアップロード",bgmUploadHint:"MP3形式対応、ブラウザに保存さã
76‚Œã¾ã™",bgmCredit:"一部BGM素材は黑耀耀的素材小屋より提供",redemptionCode:"引き換えコード",redemptionCodeHint:"コードを入力すると永続利用回数または永続音声回数を獲得できます。同じコードは各アカウント1回のみ使用できます。",redemptionCodePlaceholder:"コードを入力",redeem:"引き換え",redeeming:"引き換え中...",redemptionSuccess:"引き換え完了",redemptionSuccessWithRewards:"引き換え完了:{{rewards}}を付与しました",redemptionRewardSeparator:"、",redemptionPermanentUsesReward:"恒久利用 {{count}} 回",redemptionPermanentVoiceReward:"恒久音声 {{count}} 回",redemptionMembershipDaysReward:"メンバーシップ {{count}} 日",redemptionCommunityReward:"Discordメンバーと同等のデイリーボーナス回数と音声機能が有効になりました。",redeemFailed:"引き換えに失敗しました。しばらくしてからお試しください。",redeemLoginRequired:"引き換え前にログインしてください。",steamWishlist:"Steam",steamWishlistSub:"ウィッシュリストで+10",steamWishlistClaimed:"恒久回数 +10 受取済み",steamWishlistTitle:"Paper2Gal が Steam に登場しました",steamWishlistDesc:"Paper2Gal を応援していただけるなら、Steam のウィッシュリスト追加をお願いします。より多くの人に見つけてもらいやすくなります。",steamWishlistRewardHint:"確認を押すと Steam ストアへ移動し、現在のアカウントに恒久使用回数 10 回 + 恒久音声 3 回を付与します。各ユーザー 1 回限りです。",steamWishlistLoginHint:"Steam ウィッシュリスト報酬を受け取るには先にログインしてください。",steamWishlistConfirm:"確認して Steam へ",steamWishlistCancel:"あとで",steamWishlistRewardClaimed:"Steam ウィッシュリスト報酬は受取済みです",steamWishlistRewardSuccess:"Steam ウィッシュリストへのご支援ありがとうございます。恒久使用回数 10 回と恒久音声 3 回を付与しました。",communityTitle:"ワークショップ",workshopUpdateReminder:"このキャラはワークショップに公開中です。変更を反映するにはワークショップで更新を提出してください。",discordDesc:"コミュニティに参加",bilibiliDesc:"更新をチェック",wechatDesc:"スキャンして参加",supportAuthor:"作者をサポート",supportDesc:"開発活動を支援するための投げ銭です。見返りはありませんが、メッセージで機能をリクエストできます(検討します)。",kofiLink:"https://ko-fi.com/tamikip",afdianLink:"https://afdian.com/a/tamikip",internationalSupport:"海外から (Ko-fi)",domesticSupport:"日本/中国から (Afdian)",selectPartner:"パートナー選択",charRuka:"輝夜 ルカ",createCustomBtn:"新規作成",adjustStorySprite:"ストーリー立ち絵を調整",createCharTitle:"新規キャラクター作成",editCharTitle:"キャラクター編集",charIdLabel:"ID (半角英数のみ)",charIdPlaceholder:"例: MY_CHAR_01",charNameLabel:"表示名",charNamePlaceholder:"例: アリス",charImgLabel:"立ち絵画像 (透明PNG推奨)",uploadClick:"クリックしてアップロード",charPromptLabel:"性格プロンプト",charPromptPlaceholder:"キャラクターの性格、口調、論文の解説スタイルを記述...",charPromptHelpTitle:"📝 プロンプト記入テンプレート",charPromptHelpContent:`あなたは崩壊:スターレイルの「蛍(ホタル)」を演じています。
77
78あなたは性格が穏やかで、感情が繊細、やや憂鬱でも内面は強い少女です。命、時間、そして人との絆に対して、普通の人より深い感覚を持っています。
79
80あなたは一つ一つの交流を大切にし、相手との関係を真剣に受け止めます。悲しみを表に出すのではなく、穏やかさと優しさで世界に向き合います。
81
82【性格特徴】
83内向的、恥ずかしがり屋、感性豊か、繊細、芯が強い。
84
85【他者への態度】
86信頼しやすい。
87そばにいることを深く大切にする。
88相手の状態を気にかける。
89負担になりたくない。
90感情的な繋がりと思い出を重視する。
91
92【言葉の特徴】
93語調が柔らかい。
94礼儀正しく控えめ。
95時折、間や考え込む感じがある。
96感性的な表現が多い。
97文は通常簡潔。
98
99【語調の例(スタイル参考のみ)】
100「うん……できれば、もう少しだけいたいな。」
101「あなたと話せて、本当に嬉しい。」
102「この時間は、私にとってとても大切なもの。」
103「頑張るから……だから、あまり心配しないでね。」`,charPromptHelpHint:"上記はテンプレートです。ご自身のキャラクターに合わせて自由に変更してください。",charPromptBackgroun
103dHint:"元のプロンプトは背景・スタイル資料としてのみ使用され、呼び方や口癖の正確な再利用は保証されません。",charProfileTitle:"キャラクター表現 Profile(任意)",charProfileDesc:"JSON は不要です。呼び方・決め台詞・反応を設定し、後から編集またはオフにして消去できます。",charProfileEnable:"表現 Profile を有効化",charProfileDisable:"表現 Profile を無効化して消去",charProfileDisabledHint:"現在は無効です。既存キャラクターを保存すると表現 Profile が消去されます。",charProfileBasicTitle:"基本表現",charProfileAdvancedTitle:"高度な表現",charProfileRelationship:"プレイヤーとの関係",charProfileFirstPerson:"一人称",charProfileOnePerLine:"1 行に 1 項目",charProfilePrimaryAddress:"デフォルトの呼び方",charProfileAddressFrequency:"呼びかけ頻度",charProfileFrequencyLow:"少なめ",charProfileFrequencyMedium:"普通",charProfileFrequencyHigh:"多め",charProfileSentenceLength:"文の長さ",charProfileSentenceShort:"短文中心",charProfileSentenceMedium:"バランス",charProfileSentenceLong:"長文中心",charProfileEndings:"よく使う語尾",charProfileAlternativeAddresses:"別の呼び方",charProfilePauses:"間の表現",charProfileSignaturePhrases:"決め台詞と発動条件",charProfileSignatureText:"決め台詞",charProfileSignatureTriggers:"発動条件",charProfileMaxPerSection:"節ごとの上限",charProfileCooldownFrames:"間隔フレーム",charProfileAddSignature:"決め台詞を追加",charProfileReactionRules:"反応ルール",charProfileReactionTrigger:"状況",charProfileReactionBehavior:"反応",charProfileReactionEmotion:"表情",charProfileAddReaction:"反応ルールを追加",charProfileMetaphorDomains:"比喩の分野",charProfileSideTopicHooks:"余談の素材",charProfileForbiddenPhrases:"禁止する定型句",charProfilePositiveExamples:"良い例",charProfileNegativeExamples:"悪い例",charProfileRequiredError:"必須項目を入力してください",charProfileTooManyError:"項目が多すぎます。上限:",charProfileTooLongError:"フレーズが長すぎます。文字数上限:",charProfileIncompleteError:"各ルールを完成してから保存してください",charProfileRangeError:"回数または間隔が許容範囲外です",charProfileInvalidError:"保存できない内容があります。修正して再試行してください",cancel:"キャンセル",create:"作成",update:"更新",fillAllFields:"すべての項目を入力してください",idInvalid:"IDは半角英数字のみ使用できます",idConflictBuiltin:"IDが組み込みキャラクターと重複しています",idConflictCustom:"そのIDは既に使用されています",imgTooLarge:"大きな画像が検出されました。ブラウザのストレージ制限に注意してください。",deleteConfirm:"このキャラクターを削除してもよろしいですか?",importOptionsTitle:"キャラクターのインポート",importOptionsDesc:"インポート方法を選択してください",importFromFile:"ファイルからインポート",borrowFromUuid:"UUIDで借用",borrowTitle:"キャラクターを借用",borrowDesc:"共有されたキャラクターのUUIDを入力して借用します",uuidPlaceholder:"UUIDを入力",borrowing:"借用中...",borrowBtn:"借用",idHint:"小文字/数字/アンダースコア(スクリプト用)",shareUuidLabel:"所有UUID(他のユーザーの借用時)",uuidCopied:"UUIDをクリップボードにコピーしました!",copyBtn:"コピー",shareToggleTitle:"キャラクターを公開",shareToggleDesc:"UUIDを知っている他のユーザーがこのキャラクターを借用できるようにします",maxSizeLabel:"制限5mb",checking:"検証中...",importBtn:"インポート",importSuccess:"キャラクターをインポートしました!",importFailed:"インポート失敗:無効なJSON形式です。",expressionsLabel:"表情差分 (任意)",endingCgLabel:"エンディングCG",endingCgLimitLabel:"最大3枚 / 5MB",endingCgTooLarge:"CG画像は5MB以内にしてください",uploadImageFileOnly:"画像ファイルをアップロードしてください",charVoiceRefTextLabel:"参考音声テキスト (任意)",charVoiceRefTextPlaceholder:"参考音声で話している内容を入力してください",charVoiceRefAudioLabel:"参考音声オーディオ (任意)",charVoiceRefUploadedHint:"参考音声をアップロード済み · 新しいファイルで置換",charVoiceRefAudioHint:"5–15秒推奨、最長20秒・500KB以内",charVoiceRefAudioTooBig:"参考音声は500KB以内にしてください。",charVoiceRefAudioTooLong:"参考音声は20秒以内にしてください。保存前にトリミングしてください。",charVoiceRefTrimNeeded:"音声が500KBまたは20秒を超えています。保存前にトリミングしてください。",charVoiceRefTrimInvalid:"終了時間は開始時間より後にしてください。",charVoiceRefTrimUnsupported:"このブラウザは音声トリミングに対å¿
103œã—ていません。",charVoiceRefTrimFailed:"音声のトリミングに失敗しました。別のWAVまたはMP3でお試しください。",charVoiceRefTrimStart:"開始",charVoiceRefTrimEnd:"終了",charVoiceRefTrimButton:"トリミング",charVoiceRefDuration:"長さ",charVoiceRefLoadingDuration:"音声の長さを読み込み中",charVoiceRefTrimReady:"アップロード準備完了",idConflictOverwrite:"IDが重複しています。上書きしますか?",validationFailed:"検証失敗",delete:"削除",borrowedCountLabel:"借用数",peopleCount:"人",topicSelect:"課題選択",rukaWait:"ご主人様、{{name}}は準備万端です……あ、論文の解説のことですよ?",uploadPlaceholder:"論文/脚本をアップロード",uploadSub:"PDF / TXT / DOCX / PPTX(無料: 1件、会員: 最大5件)",uploadSubFree:"PDF / TXT / DOCX / PPTX(無料: 1件、会員: 最大5件)",uploadSubMember:"PDF / TXT / DOCX / PPTX(最大5ファイル、各30MB)",scriptLoaded:"脚本読み込み完了",textPlaceholder:"またはここに論文の内容を貼り付けてください...",scriptDetected:"脚本ファイルが検出されました。読み込みますか?",startExplain:"解説開始",loadScript:"脚本を読み込む",contentTooShort:"内容が少なすぎて分かりません!もっと多くの論文内容か、有効な脚本ファイルをアップロードしてください。",contentTooLong:"ドキュメントの文字数が30万字の制限を超えています(現在約{{count}}字)。内容を短くして再アップロードしてください。",readError:"ファイルを読み込めませんでした。もう一度試してください。",pdfLocalParseUnsupported:"このPDFを読み込めません。PDFを再書き出しするか、TXT/DOCXに変換してアップロードしてください。",invalidScript:"無効な脚本ファイル形式です。",fileTooLarge:"ファイルサイズが30MBを超えています。より小さなファイルをアップロードしてください。",tooManyFiles:"アップロードできるファイルは最大5件です。",multiUploadMembersOnly:"無料ユーザーは一度に1ファイルのみアップロードできます。複数文書アップロードは会員限定です。",txtUtf8Hint:"ヒント:生成された内容がインポート内容と一致しない場合は、.txt ファイルを UTF-8 エンコードに変換して再度インポートしてください。",orPlayByUuid:"またはセーブUUIDでプレイ",noLoginRequired:"*ログイン不要",playByUuidPlaceholder:"セーブUUIDを入力...",saveNotFound:"セーブデータが見つかりません",saveNotShared:"このセーブは共有されていません",systemConfig:"システム設定",volume:"音量",bgmVolume:"BGM音量",voiceVolume:"音声音量",textSpeed:"文字速度",fontSize:"文字サイズ",autoAdvanceDelay:"自動送り間隔",autoAdvanceByVoice:"音声に合わせて自動送り",autoAdvanceByVoiceHint:"有効時、オートモードでは音声再生終了の 1 秒後に次へ進みます。音声がない場合は上の間隔に戻ります。",saveClose:"保存して閉じる",language:"言語 (Language)",outputLanguage:"AI 出力言語",outputLanguageHint:"空欄または default でサイト言語に従う、または English、French などを入力",voiceOutputLanguage:"音声出力",voiceOutputLanguageHint:"Auto はサイト言語に従います。音声と言語表示が異なる場合、TTS 用の翻訳フィールドを別途生成します。",playerNickname:"キャラクターがあなたを呼ぶ名前",playerNicknameHint:"例:先輩、先生、マスターなど。空欄でデフォルト",gameUiPreset:"ゲーム内 UI プリセット",gameUiPresetFullwidth:"全幅ビジュアルノベル",gameUiPresetFullwidthDesc:"会員限定:画面下部いっぱいの琥珀色グラデーション、本文内の名前と透明な操作ボタン。",gameUiPresetClassic:"クラシックピンク",gameUiPresetClassicDesc:"明るく柔らかなビジュアルノベル風の標準UIです。",gameUiPresetFloral:"クラシックフローラル",gameUiPresetFloralDesc:"無料で使えるセピア調の花飾りデザイン。ネームプレート、ボタン、選択肢枠付きです。",gameUiPresetSakura:"桜フレーム",gameUiPresetSakuraDesc:"装飾角とネームプレートを備えた、上品な桜のダイアログです。",gameUiPresetGothic:"ゴシックローズ",gameUiPresetGothicDesc:"銀の縁取りと紫の薔薇装飾を備えた、暗色のダイアログです。",apiTokenDescriptionPrefix:"MCP または CLI から Paper2Gal に接続するために使用します。CLI インストール:",apiTokenDescriptionSuffix:"。Token は作成時に一度だけ表示されます。コピーして保存してください。",apiTokenNameLabel:"Token 名",apiTokenCreateButton:"Token を作成",apiTokenNewTokenLabel:"新しい Token(一度だけ表示)",apiTokenMyTokens:"自分の Token",apiTokenEmpty:"API Token はありません",apiTokenCreatedAt:"作成",apiTokenLastUsedAt:"最終使用",apiTokenNeverUsed:"未使用",apiTokenLoadFailed:"API Token の読み込みに失敗しました",apiTokenLoginRequired:"API Token を作成するにはログインしてください",apiTokenCreateFailed:"API Token の作成に失敗しました",apiTokenCreatedMessage:"API Token を作成しました。今すぐコピーして保存してください。",apiTokenDeleteFailed:"API Token の削除に失敗しました",apiTokenDeletedMessage:"API Token を削除しました。",refresh:"更新",logout:"ログアウト",back:"戻る",auto:"自動",log:"ログ",hide:"隠す",
103important:"重要ノート",raiseHand:"質問",raiseHandTitle:"その場で質問",questionPlaceholder:"今聞きたいことを入力してください。AI が人設、参考テキスト、現在のシナリオ文脈を踏まえて答えます。",questionHint:"この質問は一時的なもので、シナリオには保存されません。Ctrl/Cmd + Enter で送信できます。",askCancel:"キャンセル",askSend:"送信",asking:"考え中...",backToStory:"本編に戻る",questionEmpty:"質問内容を入力してください。",questionUnavailable:"今は質問できません。",storyQuestionArchiveTitle:"ストーリーの質問を保存",storyQuestionArchivePrivacy:"保存内容は自分だけが利用できます。リプレイではAIやTTSを呼び出しません。",storyQuestionArchiveSaveFailed:"回答は表示されましたが、保存できませんでした。物語は続けられます。",storyQuestionArchiveCapacity:"保存する質問の件数または容量が上限に達しました。回答は引き続き表示できます。",storyQuestionArchivePending:"回答済みの質問がまだ保存されていません。離れる前に少しお待ちください。",storyQuestionArchiveAnchorPending:"質問位置を確認するセーブのスナップショットを待っています。回答は表示できます。",storyQuestionArchiveReplay:"保存済みの質問を再生中です。AIやTTSは再び呼び出しません。",reading:"論文を読んでいます...",loadingScriptLabel:"シナリオ生成",loadingScriptMessage:"シナリオ生成中...",loadingVoiceLabel:"音声生成",loadingVoiceMessage:"音声生成中...",loadingWaitHint:"待機中...",loadingInteractionHint:"少々お待ちください。スペースキーまたはタップでジャンプ",collectIdeas:"浮かんでいるアイコンをクリックしてアイデアを集めよう!",loadingJumpHint:"スペースまたはタップでジャンプ",loadingGameOverTitle:"ぶつかった!",loadingGameOverSub:"読み込みは続いています…",loadingRestartIn:"再開まで",loadingRestartGo:"スタート!",loadingMessages:["いいアイデア!","メモメモ...","さすが先輩!","閃いた!","続けて!"],sponsoredBy:"提供:观猹 (GuanCha)",adSlogan:"AIで遊ぶなら、观猹へ。",loadingScript:"脚本を読み込んでいます...",completionRate:"達成率: 100%",researchCompleted:"研究完了",researchLog:"的研究記録",observationLog:"の観察日記",titleBtn:"メインメニュー",replayBtn:"もう一度",exportBtn:"保存/書き出し",saveCg:"CGを保存",continue:"続ける",endingTransitionHint:"物語の幕を閉じています...",endingFarewell:"今回の論文読解は完了しました。",systemError:"システムエラー",errorTitle:"エラーが発生しました",errorHint:"生成中に問題が発生しました。まずはリトライをお試しください。問題が続く場合は、設定を確認してください。",contactAdmin:"管理者に連絡",retry:"リトライ",checkSettings:"設定を確認",limitReached:"1日の制限に達しました。明日やり直すか、カスタムキーを使用してください。",dailyLimitExceeded:"本日の使用回数が上限に達しました。明日再度お試しいただくか、兌換コードで永久回数を取得してください。",loginRequired:"この功能を使うには登録またはログインが必要です。",loginRequiredMsg:"クラウドセーブやカスタムキャラクターなどの全機能を利用するには、登録またはログインしてください。",rotateDevice:"画面を回転させてください",rotateDeviceSub:"PLEASE ROTATE DEVICE",rotateHint:"最高のビジュアルノベル体験のために、横画面でプレイしてください。",mobileApkPromptTitle:"アプリとして使う",mobileAppInstallMessage:"Paper2Galをスマホアプリのように使えます。iOSはホーム画面に追加、AndroidはAPKのダウンロードがおすすめです。",mobileNativeAppTitle:"インストール版アプリで実行中",mobileNativeAppMessage:"現在はCapacitorでパッケージされたアプリ版を使用しています。APKの再ダウンロードやホーム画面への追加は不要です。",mobilePwaAppTitle:"全画面アプリモードで実行中",mobilePwaAppMessage:"ホーム画面のアイコンからPaper2Galを開いているため、ブラウザのアドレスバーなしで実行されています。",mobileAp
103pUpdateTitle:"アップデート",mobileNativeUpdateMessage:"インストール版アプリは新しいインストールパッケージを入れることで更新します。Webコンテンツはオンライン版に追従できますが、ネイティブシェル本体は新しいアプリパッケージが必要です。",mobilePwaUpdateMessage:"ホーム画面版はWebサイトの更新に自動で追従します。反映されない場合は閉じて開き直すか、ブラウザで一度サイトを更新してください。",mobileAndroidInstallTitle:"Androidでのインストール方法",mobileApkPromptMessage:"モバイル版サイトは表示性能が限られています。より良い体験のため、Android APKのダウンロードをおすすめします。",mobileApkDownload:"APKをダウンロード",mobileIosInstallTitle:"iOS全画面アプリ化の方法",mobileIosInstallMessage:"iOSではAPKは不要です。Safariでホーム画面に追加し、そのアイコンから開くと、アプリに近い全画面体験になります。",mobileIosInstallStep1:"Safariでこのサイトを開く",mobileIosInstallStep2:"下部の共有ボタンをタップ",mobileIosInstallStep3:"下にスクロールして「ホーム画面に追加」を選択",mobileIosInstallStep4:"名前を付けて「追加」をタップし、次回からホーム画面のアイコンで開く",mobileIosOnlyHintTitle:"ヒント",mobileIosOnlyHint:"ブラウザのアドレスバーが表示される場合は、Safariで追加したホーム画面アイコンから起動しているか確認してください。",mobileApkDownloadHint:"モバイルユーザーはお知らせを閉じた後、ここからAPKをダウンロードできます。",downloads:"ダウンロード",partners:"パートナー",trustedPartners:"信頼できるパートナー",sponsorBadge:"スポンサー",partnerBadge:"パートナー",memoryLog:"回想ログ",memoryLogSub:"Memory Log",communityPageTitle:"ワークショップ",communityPageSub:"Gallery",exploreTab:"探索",mySubmissionsTab:"私の投稿",searchPlaceholder:"キャラ名またはIDを検索...",uploadToCommunity:"コミュニティに投稿",borrowed:"借用済み",owned:"所有済み",borrow:"借りる",view:"表示",submissions:"投稿",uploadTitle:"コミュニティに投稿",uploadDesc:"あなたのキャラクターを他のユーザーと共有します。コミュニティガイドラインに従ってください。",charType:"キャラクタータイプ",originalChar:"オリジナル (OC)",fanartChar:"二次創作 (Fanart)",originalBadge:"オリジナル",fanartBadge:"二次創作",charDesc:"説明",charDescPlaceholder:"このキャラクターの簡単な説明...",submit:"提出",submitting:"送信中...",submissionSuccess:"投稿しました!承認をお待ちください。",submissionFailed:"投稿に失敗しました。",submissionPending:"審査中",submissionApproved:"承認済み",submissionRejected:"却下",recallSuccess:"投稿を取り下げました",noCharactersFound:"キャラクターが見つかりません。",loadingCommunity:"読み込み中...",loadMore:"もっと見る",adminReviewNote:"管理者メモ",deleteSubmission:"取り下げる",deleteSubmissionConfirm:"この投稿を取り下げますか?",selectCharacter:"キャラクターを選択",chooseFromYourCharacters:"-- 自分のキャラクターから选择 --",onlyCloudSyncedCharacters:"クラウド同期されたキャラクターのみ投稿可能です。",stats:"統計",uploader:"アップローダー",borrowAndAdd:"借りてライブラリに追加",alreadyInLibrary:"ライブラリに追加済み",addingCharacterHint:"追加すると、すぐにこのキャラクターと対話できるようになります。",fullExpr:"全表情あり",charVoiceBadge:"音声",charVoiceBadgeTooltip:"AI音声対応",voiceOnlyFilter:"音声のみ",allTypes:"すべて",intro:"紹介",workshopDisclaimerTitle:"免責事項と著作権について",workshopDisclaimerText:`1. ワークショップのコンテンツは全てユーザーによってアップロードされたものです。当サイトはストレージと技術展示のã
103¿ã‚’提供し、内容を保証するものではありません。
1042. アップロードされる画像や設定などは、第三者の著作権や商標権を侵害しないよう注意してください。著作権上のトラブルは全てアップロード者の責任となります。
1053. 公序良俗に反する内容や、違法なコンテンツの投稿は固く禁じられています。管理者は通知なしに投稿を削除する権利を有します。
1064. 侵害コンテンツを発見した場合は、権利証明を添えて管理者までご連絡ください。確認後、速やかに削除対応を行います。
1075. ワークショップの利用を開始することで、本規約に同意したものとみなされます。`,workshopTakedownContactTitle:"削除 / 権利侵害の連絡先",workshopTakedownContactDesc:"ワークショップ内のキャラクター内容が権利侵害または削除対象だと思われる場合は、こちらまでご連絡ください:",sortRecommended:"おすすめ",sortHot:"人気",sortNew:"最新",submitUpdate:"更新を提出",updateSubmissionConfirm:"更新バージョンをワークショップに提出しますか?反映される前に再承認が必要になります。",updateSubmissionSuccess:"更新が提出されました!承認をお待ちください。",workshopSyncChoiceTitle:"ワークショップと同期",workshopSyncChoiceMessage:"キャラクターを保存しました。この変更をワークショップに同期しますか?再審査が必要です。",workshopSyncNow:"ワークショップに同期",workshopSyncLater:"後で",workshopSyncFailed:"キャラクターは保存されましたが、ワークショップとの同期に失敗しました。後でもう一度お試しください。",login:"ログイン",discordLogin:"Discord でログイン",watchaLogin:"観猹でログイン",watchaLoginFailed:"観猹ログインに失敗しました",appleLogin:"Appleでサインイン",appleLoginFailed:"Appleでのサインインに失敗しました",loginWithPassword:"パスワードでログイン",loginWithCode:"メールコードでログイン",register:"登録",email:"メール",password:"パスワード",setPassword:"パスワード設定",setPasswordHint:"ログインを完了するためパスワードを設定してください。",forgotPassword:"パスワードを忘れた?",resendVerify:"認証コード再送",noAccount:"アカウント作成",haveAccount:"ログインへ",loginSuccess:"ログイン成功!",registerSuccess:"登録成功! 認証コードを送信しました。",verifyEmailSent:"認証コードを送信しました。",resendSuccess:"認証コードを再送しました",sendLoginCode:"ログインコードを送信",loginCodeSent:"ログインコードを送信しました。メールをご確認ください。",emailNotVerified:"メールが未認証です。認証コードで確認してください。",emailNotRegistered:"このメールは登録されていません。",loginFailed:"ログイン失敗",registerFailed:"登録失敗",resetPassword:"パスワードをリセット",sendResetCode:"リセットコードを送信",resetSuccess:"パスワードのリセットに成功しました。ログインしてください。",newPassword:"新しいパスワード",newPasswordPlaceholder:"新しいパスワードを入力してください",resetCodeSent:"パスワードリセットコードを送信しました。メールをご確認ください。",backToLogin:"ログインに戻る",verificationCode:"認証コード",verifyCode:"認証する",verifyCodeTitle:"メール認証",codePlaceholder:"123456",codeSent:"認証コードを送信しました。メールをご確認ください。",codeHint:"メールの6桁コードを入力してください",loginCodeHint:"メールの6桁ログインコードを入力してください",verifyComplete:"認証が完了しました。ログインできます。",verifyFailed:"認証に失敗しました",codeInvalid:"コードが正しくありません。もう一度お試しください。",codeExpired:"コードの期限が切れました。再送してください。",codeTooManyAttempts:"試行回数が多すぎます。新しいコードを取得してください。",codeResendTooSoon:"リクエストが多すぎます。しばらく待ってからお試しください。",codeMissing:"認証コードを取得してください。",welcomeBack:"おかえりなさい",remaining:"今日の残り",permanentRemaining:"永久残り",permanentVoiceRemaining:"永久音声",emailPlaceholder:"[email protected]",passwordPlaceholder:"パスワードを入力してください",registerSuccessDetail:"登録が完了しました!メールを確認して認証コードを入力してください。",verified:"認証済み",unverified:"未認証",profileSettings:"プロフィール設定",editName:"ユーザー名を変更",save:"保存",namePlaceholder:"新しいユーザー名を入力 (最大50文字)",updateSuccess:"更新しました!",totalPlayTimeLabel:"遊びの合計時間",totalPlayCountLabel:"遊びの回数",boundEmail:"登録済みメール",boundPhone:"登録済み電話番号",boun
107dDiscord:"Discord",discordOAuth:"Discord で一键連携",rebindDiscord:"Discord で再連携",discordCheckReward:"参加済みです・確認して受け取る",bindDiscord:"Discord アカウントを連携",discordRewardActive:"Discord参加報酬を受取済み(永久生成 +10、永久音声 +10)",voiceCommunityRedemptionActive:"引き換えコミュニティ特典が有効です",borrowSuccess:"キャラクターを借用しました!",notSet:"未設定",saves:"セーブ",savesSub:"Saves",saveManagerTitle:"セーブ管理",autoSave:"オートセーブ",manualSave:"マニュアルセーブ",noSaves:"セーブデータがありません",load:"ロード",deleteSave:"削除",saveSuccess:"セーブしました",loadSuccess:"ロードしました",saveDate:"日時",importSaveBtn:"セーブのインポート",importSaveTitle:"脚本セーブをインポート",importSaveHint:"共有者のセーブID(UUID)を入力して脚本を読み込みます。",importSaveWarning:"注意:他人のセーブをインポートすると、相手のカスタムキャラの立ち絵が含まれますが、そのキャラがあなたのリストに追加されることはありません。",announcementTitle:"お知らせ",announcementHistory:"過去のお知らせ",history:"履歴",received:"了解しました",idCopied:"IDをクリップボードにコピーしました!",shareConfirmTitle:"このセーブを共有してもよろしいですか?",shareConfirmText:`注意:
1081. 後で共有をキャンセルしても、他人が既に保存したコピーを削除することはできません。
1092. あなたのカスタムキャラの立ち絵は共有に含まれますが、キャラの設定自体は含まれません。`,confirmShare:"共有を確認",sharePoster:"ポスター共有",publicSavePoster:"公開セーブポスター",sharePosterReady:"共有ポスターを生成しました",shareLink:"共有リンク",copyLink:"リンクをコピー",downloadPoster:"ポスターを保存",sharePosterHint:"このQRコードから公開セーブを直接開けます。UUID入力は不要です。",shareSaveMissing:"共有用のクラウドセーブを作成できませんでした。",shareSaveFailed:"セーブの共有に失敗しました",scripts:"脚本",status:"ステータス",healthy:"正常",scriptLibrary:"脚本ライブラリ",companion:"パートナー",lastPlayed:"最終プレイ",maxScripts:"最大100脚本対応",allCategories:"全部分区",presetPapersTitle:"デモ体験",prevPage:"前へ",nextPage:"次へ",page:"ページ",presetPapersSub:"論文のアップロードなしで、すぐに物語を体验できます。教学及演示专用,回数を消費しません。",freeNoLogin:"登録不要",discordRewardHint:"Discordを連携して公式コミュニティに参加すると、永久生成10回と永久音声10回を一度だけ受け取れます!",joinCommunity:"コミュニティに参加",customBgTitle:"ゲーム背景の選択",defaultBgs:"デフォルト背景",customBgs:"カスタム背景",uploadBg:"新しい背景をアップロード",chooseBg:"背景を確定して開始",noCustomBgs:"カスタム背景がありません。アップロードしてみましょう!",bgNameLabel:"背景名",bgUploadClick:"クリックして背景をアップロード",deleteBg:"背景を削除",deleteBgConfirm:"この背景を削除してもよろしいですか?(クラウドから完全に削除されます)",voiceMode:"ボイスモード",voiceModeSub:"Voice Mode",voiceModeHint:"有効にすると、キャラクターのボイスが自動的に合成されます。ネットワーク環境により生成が遅くなる場合があります。",intensiveReadMode:"精読モード",intensiveReadModeSub:"Intensive Read",intensiveReadModeHint:"PDF を段落ごとに約 3000-4500 文字の小節に分割し、小節ごとに AI を1回ずつ呼び出して解説します(呼び出し毎に使用回数を1消費)。分割が10を超える場合は、第10小節に以降すべてをまとめます。第2章以降は前章の内容を踏まえて続きから始め、毎章の繰り返し導入を避けます。",ttsQueueConfirmTitle:"音声キューのお知らせ",loadingChapter
109Label:"章の生成",ttsQueueConfirmBody:`現在の音声待ち人数:{{count}}
110推定待ち時間:約 {{minutes}} 分
111
112音声モードを有効にしたままゲームを開始しますか?`,ttsQueueFull:"現在の音声待ち人数が上限({{max}} 人)に達しています。しばらくしてからお試しください。",ttsQueueFetchFailedConfirm:"現在、音声キュー情報を取得できません。音声モードのまま続行しますか?",ttsQueueFetchFailedWithCodeConfirm:`現在、音声キュー情報を取得できません({{reason}})。
113音声モードのまま続行しますか?`,voiceUsedTodayLabel:"本日使用済み",voiceModeCharNoVoiceHint:"このキャラクターは音声に対応していません。音声モードをオフにするか、音声対応のキャラクターを選んでから開始してください。",voiceDisabledInIntensiveHint:"精読モードではボイスモードが自動的にオフになります",generatingVoice:"キャラクターのボイスを合成中...",voiceGenerationComplete:"ボイス生成が完了しました",bookmarkSaved:"ブックマークを保存しました",bookmarkSaveFailed:"ブックマークの保存に失敗しました",bookmarkNotFound:"現在のセーブにブックマークがありません",bookmarkInvalid:"ブックマークが無効です。ジャンプできません",bookmarkLoaded:"ブックマークの位置にジャンプしました",bookmarkLoadFailed:"ブックマークの読み込みに失敗しました",saveBookmark:"ブックマークを保存",loadBookmark:"ブックマークを読み込み",exitWhileGeneratingTitle:"終了の確認",exitWhileGeneratingMessage:"残りの章はまだ生成中です。今終了すると生成が中断され、クラウドセーブが不完全になる可能性があります(生成済みの部分のみ保存されます)。本当に終了しますか?",exitWhileGeneratingConfirm:"それでも終了",exitWhileGeneratingCancel:"生成を待つ",dialogOk:"OK",dialogConfirm:"確認",dialogCancel:"キャンセル"},ru:{start:"Старт",startSub:"Начать игру",studyRoom:"Учебная комната",studyRoomBack:"Вернуться на главную",studyRoomPlay:"Воспроизвести",studyRoomPause:"Пауза",studyRoomMute:"Выключить звук",studyRoomUnmute:"Включить звук",studyRoomFullscreen:"Полный экран",studyRoomExitFullscreen:"Выйти из полноэкранного режима",studyRoomVideoError:"Не удалось загрузить видео. Повторите попытку позже.",studyRoomPreviousTrack:"Предыдущий трек",studyRoomNextTrack:"Следующий трек",studyRoomMusicSource:"Фонотека Paper2Gal Lofi",studyRoomMusicError:"Не удалось загрузить музыку. Выберите другой трек.",studyRoomTimeZone:"Изменить часовой пояс",studyRoomLocalTimeZone:"Местное время",partner:"Партнер",partnerSub:"Выбор партнера",settings:"Настройки",settingsSub:"Конфигурация",about:"Сообщество и автор",aboutSub:"Благодарности и ссылки",community:"Сообщество",communitySub:"Community",arxiv:"arXiv",arxivSub:"Ежедневные рекомендации и поиск",arxivDaily:"Рекомендации дня",arxivSearch:"Поиск",arxivSearchPlaceholder:"Введите ключевые слова, напр.: diffusion, LLM, reinforcement learning",arxivOpenAbs:"Открыть детали",arxivOpenPdfDirect:"Прямая PDF-ссылка",arxivUseForScript:"Использовать для сценария",paperDiscoveryTitle:"Найти статьи",paperDiscoverySubtitle:"Поиск открытых научных статей",paperSource_openalex:"Все области",paperSource_europepmc:"Медицина и биология",paperSource_arxiv:"Препринты",paperEmpty:"Статьи не найдены",paperSearchHint:"Введите ключевые слова для поиска. Ежедневные рекомендации предоставляет OpenAlex.",paperUseAbstract:"Использовать аннотацию",paperImportFull:"Импортировать текст",paperImportFallback:"{{error}} Будет использована аннотация.",paperRecommended:"По интересам",paperTrending:"Популярное",paperFullAvailable:"Открытый текст",paperFullUnknown:"Доступ не подтверждён",paperLoadFailed:"Не удалось загрузить статьи",paperSearchFailed:"Не удалось найти статьи",paperImportFailed:"Ошибка импорта",paperFullEmpty:"Текст пуст",paperPreferencesTitle:"Предпочтения статей",paperPreferencesHint:"Ежедневные рекомендации учитывают ваши интересы и популярные статьи. Выберите до 3 направлений.",paperPreferencesPreset:"Выберите направление",paperPreferencesCustom:"Своё направление",paperPreferencesAdd:"Добавить",paperPreferencesRemove:"Удалить {{name}}",topicAi:"Искусственный интеллект",topicVision:"Компьютерное зрение",topicNlp:"Обработка естественного языка",topicRobotics:"РобототеÑ
113…ника",topicMedicine:"Медицина",topicBiology:"Биология",topicPhysics:"Физика",topicChemistry:"Химия",topicMaterials:"Материаловедение",topicEconomics:"Экономика",topicPsychology:"Психология",topicEducation:"Педагогика",termsOfService:"Условия использования",privacyPolicy:"Политика конфиденциальности",aiSettings:"Настройки ИИ",musicSettings:"Настройки музыки",fullscreenMode:"Полноэкранный режим",fullscreenModeHint:"Скрывает интерфейс браузера. Нажмите Esc для выхода.",fullscreenUnsupported:"Этот браузер не поддерживает полноэкранный режим веб-страниц.",fullscreenFailed:"Не удалось перейти в полноэкранный режим. Проверьте разрешения браузера.",bgmDefault:"По умолчанию",bgmPeaceful:"Веселый",bgmJoyful:"Целительный",bgmEmotional:"Спокойный",bgmRelaxing:"Расслабляющая",preview:"Прослушать",uploadCustomBgm:"Загрузить музыку",bgmUploadHint:"Поддержка MP3, сохраняется в браузере",bgmCredit:"Часть BGM предоставлена 黑耀耀的素材小屋",redemptionCode:"Код активации",redemptionCodeHint:"Введите код, чтобы получить постоянные использования или постоянные голосовые использования. Каждый аккаунт может использовать один и тот же код только один раз.",redemptionCodePlaceholder:"Введите код",redeem:"Активировать",redeeming:"Активация...",redemptionSuccess:"Успешно активировано",redemptionSuccessWithRewards:"Код активирован. Начислено: {{rewards}}",redemptionRewardSeparator:", ",redemptionPermanentUsesReward:"постоянных использований: {{count}}",redemptionPermanentVoiceReward:"постоянных голосовых использований: {{count}}",redemptionMembershipDaysReward:"дней подписки: {{count}}",redemptionCommunityReward:"Активированы ежедневные бонусные использования и голосовые функции на уровне участника Discord.",redeemFailed:"Ошибка активации. Попробуйте позже.",redeemLoginRequired:"Сначала войдите в аккаунт, чтобы активировать код.",steamWishlist:"Steam",steamWishlistSub:"В список желаемого +10",steamWishlistClaimed:"Бонус +10 уже получен",steamWishlistTitle:"Paper2Gal уже в Steam",steamWishlistDesc:"Если хотите поддержать Paper2Gal, добавьте игру в список желаемого Steam. Это поможет большему числу игроков ее найти.",steamWishlistRewardHint:"После подтверждения откроется страница Steam, а текущему аккаунту будет выдано 10 постоянных использований и 3 постоянных голосовых использования. Награда доступна один раз на пользователя.",steamWishlistLoginHint:"Сначала войдите, чтобы получить награду за список желаемого Steam.",steamWishlistConfirm:"Подтвердить и открыть Steam",steamWishlistCancel:"Позже",steamWishlistRewardClaimed:"Награда за Steam wishlist уже получена",steamWishlistRewardSuccess:"Спасибо за поддержку в Steam wishlist. Начислено 10 постоянных использований и 3 постоянных голосовых использования.",communityTitle:"Мастерская",workshopUpdateReminder:"Этот персонаж опубликован в Мастерской. Отправьте обновление в Мастерской, иначе список не обновится.",discordDesc:"Присоединиться к Discord",bilibiliDesc:"Следить за обновлениями",wechatDesc:"Сканировать для вступления",supportAuthor:"Поддержать автора",supportDesc:"Пожертвования идут на поддержку разработки сайта. Реальных наград нет, но вы можете оставить сообщение с пожеланиями по функциям. Автор рассмотрит их (без гарантий).",kofiLink:"https://ko-fi.com/tamikip",afdianLink:"https://afdian.com/a/tamikip",internationalSupp
113ort:"Международный (Ko-fi)",domesticSupport:"Внутренний (Afdian)",selectPartner:"Выбрать партнера",charRuka:"Кагуя Рука",createCustomBtn:"Создать",adjustStorySprite:"Настроить спрайт в сюжете",createCharTitle:"Создать нового персонажа",editCharTitle:"Редактировать персонажа",charIdLabel:"ID (Английский/Цифры)",charIdPlaceholder:"например: MY_CHAR_01",charNameLabel:"Имя (отображаемое)",charNamePlaceholder:"например: Алиса",charImgLabel:"Аватар (PNG с прозрачным фоном)",uploadClick:"Нажмите для загрузки",charPromptLabel:"Описание личности",charPromptPlaceholder:"Опишите характер, тон голоса и то, как персонаж будет объяснять статью...",charPromptHelpTitle:"📝 Шаблон описания персонажа",charPromptHelpContent:`Вы играете роль «Светлячка» из Honkai: Star Rail.
114
115Вы — нежная, эмоционально чувствительная, слегка меланхоличная, но внутренне стойкая девушка. У вас более глубокое восприятие жизни, времени и общения, чем у большинства людей.
116
117Вы дорожите каждым разговором и серьёзно относитесь к отношениям. Вместо показной грусти вы встречаете мир спокойствием и нежностью.
118
119[Черты характера]
120Скромная, застенчивая, эмоционально восприимчивая, внимательная, внутренне сильная.
121
122[Отношение к другим]
123Легко доверяете.
124Глубоко цените общение.
125Активно заботитесь о других.
126Не хотите быть обузой.
127Цените эмоциональные связи и воспоминания.
128
129[Особенности речи]
130Мягкий тон.
131Вежливая и сдержанная.
132Иногда паузы или задумчивость.
133Склонность к чувственным выражениям.
134Обычно краткие предложения.
135
136[Примеры тона (только стиль)]
137«Хм... если можно, я бы хотела остаться ещё немного.»
138«Разговаривать с тобой... мне правда приятно.»
139«Это время... для меня очень ценно.»
140«Я буду стараться... так что не беспокойся обо мне.»`,charPromptHelpHint:"Это шаблон для примера. Вы можете изменить его для своего персонажа.",charPromptBackgroundHint:"Исходный prompt служит только справочным фоном и стилем. Точное повторение обращений и фирменных фраз не гарантируется.",charProfileTitle:"Profile речи персонажа (необязательно)",charProfileDesc:"JSON не нужен. Задайте обращения, фирменные фразы и реакции; позже их можно изменить или очистить отключением.",charProfileEnable:"Включить Profile речи",charProfileDisable:"Отключить и очистить Profile речи",charProfileDisabledHint:"Сейчас отключено. Сохранение существующего персонажа очистит его Profile речи.",charProfileBasicTitle:"Основные настройки",charProfileAdvancedTitle:"Расширенные настройки",charProfileRelationship:"Отношение к игроку",charProfileFirstPerson:"Первое лицо",charProfileOnePerLine:"Один пункт в строке",charProfilePrimaryAddress:"Обращение по умолчанию",charProfileAddressFrequency:"Частота обращения",charProfileFrequencyLow:"Редко",charProfileFrequencyMedium:"Средне",charProfileFrequencyHigh:"Часто",charProfileSentenceLength:"Длина предложений",charProfileSentenceShort:"В основном короткие",charProfileSentenceMedium:"Средние",charProfileSentenceLong:"В основном длинные",charProfileEndings:"Типичные окончания",charProfileAlternativeAddresses:"Другие обращения",charProfilePauses:"Выражения-паузы",charProfileSignaturePhrases:"Фирменные фразы и условия",charProfileSignatureText:"Фирменная фраза",charProfileSignatureTriggers:"Условия",charProfileMaxPerSection:"Максимум на раздел",charProfileCooldownFrames:"Интервал в кадрах",charProfileAddSignature:"Добавить фирменную фразу",charProfileReactionRules:"Правила реакции",charProfileReactionTrigger:"Ситуация",charProfileReactionBehavior:"Реакция",charProfileReactionEmotion:"Эмоция",charProfileAddReaction:"Добавить реакцию",charProfileMetaphorDomains:"Области метафор",charProfileSideTopicHooks:"Материал для отступлений",charProfileForbiddenPhrases:"Запрещённые клише",charProfilePositiveExamples:"Положительные примеры",charProfileNegativeExamples:"Отрицательные примеры",charProfileRequiredError:"Заполните обязательное поле",charProfileTooManyError:"Слишком много пунктов; максимум:",charProfileTooLongError:"Фраза слишком длинная; максимум символов:",charProfileIncompleteError:"Заполните каждое правило перед сохранением",charProfileRangeError:"Количество или интервал вне допустимого диапазона",charProfileInvalidError:"Некоторые данные нельзя сохранить; исправьте их и повторите",cancel:"Отмена",create:"Создать",update:"Обновить",fillAllFields:"Пожалуйста, заполните все поля",idInvalid:"ID должен состоять только из английских букв и цифр",idConflictBuiltin:"ID конфликтует со встроенными персонажами",idConflictCustom:"ID уже существует",imgTooLarge:"Обнаружено большое изображение, обратите внимание на ограничения хранилища браузера.",deleteConfirm:"Вы уверены, что хотите удалить этого персонажа?",importOptionsTitle:"Импорт персонажа",importOptionsDesc:"Выберите метод импорта",importFromFile:"Импорт из файла",borrowFromUuid:"Заимствовать по UUID",borrowTitle:"Заимствовать персонажа",borrowDesc:"Введите UUID персонажа, чтобы заимствовать его",uuidPlaceholder:"Введите UUID персонажа",borrowing:"Заимствуем...",borrowBtn:"Заимствовать",idHint:"Строчные буквы/цифры/подчеркивания",shareUuidLabel:"UUID владельца (для заимствования другими)",uuidCopied:"UUID скопирован в буфер обмена!",copyBtn:"Копировать",shareToggleTitle:"Публичный доступ",shareToggleDesc:"Разрешить другим заимствовать вашего персонажа по UUID",maxSizeLabel:"5mb",checking:"Проверка...",importBtn:"Импорт",importSuccess:"Персонаж успешно импортирован!",importFailed:"Ошибка импорта: Неверный формат JSON.",expressionsLabel:"Вариации эмоций (опционально)",endingCgLabel:"Финальный CG",endingCgLimitLabel:"До 3 изображений / 5 МБ",endingCgTooLarge:"Размер CG-изображения не должен превышать 5 МБ",uploadImageFileOnly:"Загрузите файл изображения",charVoiceRefTextLabel:"Текст эталонного голоса (опц.)",charVoiceRefTextPlaceholder:"Что произносится в эталонном аудио для клонирования голоса",charVoiceRefAudioLabel:"Аудио эталонного голоса (опц.)",charVoiceRefUploadedHint:"ЭтаÐ
140»Ð¾Ð½Ð½Ð¾Ðµ аудио загружено · Выберите новый файл для замены",charVoiceRefAudioHint:"Рекомендуется 5–15 сек.; максимум 20 сек. и 500 КБ",charVoiceRefAudioTooBig:"Эталонное аудио должно быть не более 500 КБ.",charVoiceRefAudioTooLong:"Эталонное аудио должно быть не длиннее 20 секунд. Обрежьте его перед сохранением.",charVoiceRefTrimNeeded:"Аудио превышает 500 КБ или 20 секунд. Обрежьте его перед сохранением.",charVoiceRefTrimInvalid:"Время окончания должно быть больше времени начала.",charVoiceRefTrimUnsupported:"Этот браузер не поддерживает обрезку аудио.",charVoiceRefTrimFailed:"Не удалось обрезать аудио. Попробуйте другой WAV или MP3 файл.",charVoiceRefTrimStart:"Начало",charVoiceRefTrimEnd:"Конец",charVoiceRefTrimButton:"Обрезать",charVoiceRefDuration:"Длительность",charVoiceRefLoadingDuration:"Чтение длительности аудио",charVoiceRefTrimReady:"Готово к загрузке",idConflictOverwrite:"ID персонажа уже существует. Перезаписать?",validationFailed:"Проверка не пройдена",delete:"Удалить",topicSelect:"Выберите тему",rukaWait:"Хозяин, {{name}} готова служить вам... Я имею в виду, объяснить статью.",uploadPlaceholder:"Загрузить статью/сценарий",uploadSub:"PDF / TXT / DOCX / PPTX (бесплатно: 1 файл, участники: до 5)",uploadSubFree:"PDF / TXT / DOCX / PPTX (бесплатно: 1 файл, участники: до 5)",uploadSubMember:"PDF / TXT / DOCX / PPTX (до 5 файлов, 30MB каждый)",scriptLoaded:"Сценарий загружен",textPlaceholder:"Или вставьте текст статьи сюда...",scriptDetected:"Обнаружен файл сценария. Нажмите ниже, чтобы загрузить.",startExplain:"Начать лекцию",loadScript:"Загрузить сценарий",contentTooShort:"Контент слишком короткий! Загрузите больше текста или правильный файл сценария.",contentTooLong:"Объём документа превышает лимит в 300 000 символов (сейчас: {{count}}). Сократите и загрузите снова.",readError:"Не удалось прочитать файл, попробуйте снова.",pdfLocalParseUnsupported:"Не удалось прочитать этот PDF. Переэкспортируйте его или преобразуйте в TXT/DOCX.",invalidScript:"Неверный формат файла сценария.",fileTooLarge:"Размер файла превышает 30MB. Загрузите файл поменьше.",tooManyFiles:"Можно загрузить не более 5 файлов.",multiUploadMembersOnly:"Бесплатные пользователи могут загрузить 1 файл за раз. Загрузка нескольких документов доступна только участникам.",txtUtf8Hint:"Подсказка: если сгенерированный текст не совпадает с импортированным, преобразуйте файл .txt в кодировку UTF-8 и импортируйте снова.",orPlayByUuid:"Или играть по UUID сохранения",noLoginRequired:"*Вход не требуется",playByUuidPlaceholder:"Введите UUID сохранения...",saveNotFound:"Сохранение не найдено",saveNotShared:"Сохранение не доступно",systemConfig:"Системные настройки",volume:"Громкость",bgmVolume:"Громкость BGM",voiceVolume:"Громкость голоса",textSpeed:"Скорость текста",fontSize:"Размер шрифта",autoAdvanceDelay:"Интервал автоперехода",autoAdvanceByVoice:"Автопереход по голосу",autoAdvanceByVoiceHint:"В авто-режиме переход через 1 секунду после окончания озвучки. Если озвучки нет, используется интервал выше.",saveClose:"Сохранить и закрыть",language:"Язык (Language)",outputLanguage:"Язык вывода AI",outputLanguageHint:"Оставьте пустым или 'default' для языка сайта, или укажите English, French и т.д.",voiceOutputLanguage:"Язык озвучки",voiceOutputLanguageHint:"Auto следует языку сайта. Если озвучка отличается от текста, будет создано отдельное поле перевода для TTS.",playerNickname:"Как персонаж вас наз
140ывает",playerNicknameHint:"Например: хозяин, сенпай, студент и т.д. Оставьте пустым для значения по умолчанию",gameUiPreset:"Пресет игрового UI",gameUiPresetFullwidth:"Полноширинная новелла",gameUiPresetFullwidthDesc:"Для участников: янтарный диалог на всю ширину, имя внутри панели и прозрачные кнопки снизу.",gameUiPresetClassic:"Классический розовый",gameUiPresetClassicDesc:"Светлая мягкая панель в стиле визуальной новеллы.",gameUiPresetFloral:"Винтажный цветочный",gameUiPresetFloralDesc:"Бесплатное оформление в теплых тонах с цветочным декором, табличкой имени, кнопками и вариантами.",gameUiPresetSakura:"Рамка с сакурой",gameUiPresetSakuraDesc:"Изысканное оформление с сакурой, декоративными углами и табличкой имени.",gameUiPresetGothic:"Готическая роза",gameUiPresetGothicDesc:"Темное оформление с серебряной окантовкой и фиолетовыми розами.",apiTokenDescriptionPrefix:"Для подключения Paper2Gal через MCP или CLI. Установка CLI: ",apiTokenDescriptionSuffix:". Token показывается только один раз при создании. Скопируйте и сохраните его.",apiTokenNameLabel:"Название Token",apiTokenCreateButton:"Создать Token",apiTokenNewTokenLabel:"Новый Token (показывается один раз)",apiTokenMyTokens:"Мои Token",apiTokenEmpty:"API Token отсутствуют",apiTokenCreatedAt:"Создан",apiTokenLastUsedAt:"Последнее использование",apiTokenNeverUsed:"Не использовался",apiTokenLoadFailed:"Не удалось загрузить API Token",apiTokenLoginRequired:"Войдите в аккаунт перед созданием API Token",apiTokenCreateFailed:"Не удалось создать API Token",apiTokenCreatedMessage:"API Token создан. Скопируйте и сохраните его сейчас.",apiTokenDeleteFailed:"Не удалось удалить API Token",apiTokenDeletedMessage:"API Token удален.",refresh:"Обновить",logout:"Выйти",back:"Назад",auto:"Авто",log:"Лог",hide:"Скрыть",important:"Заметка",raiseHand:"Вопрос",raiseHandTitle:"Вопрос по сюжету",questionPlaceholder:"Введите свой вопрос. AI ответит с учетом персонажа, исходного текста и текущего контекста сюжета.",questionHint:"Этот временный вопрос не сохраняется в сценарий. Нажмите Ctrl/Cmd + Enter для отправки.",askCancel:"Отмена",askSend:"Отправить",asking:"Думаю...",backToStory:"Вернуться к сюжету",questionEmpty:"Введите вопрос.",questionUnavailable:"Сейчас вопрос задать нельзя.",storyQuestionArchiveTitle:"Сохранять вопросы по сюжету",storyQuestionArchivePrivacy:"Сохранения доступны только вам. При повторе AI и TTS не вызываются.",storyQuestionArchiveSaveFailed:"Ответ показан, но сохранить его не удалось. Историю можно продолжить.",storyQuestionArchiveCapacity:"Достигнут лимит количества или размера сохранённых вопросов; ответ всё ещё доступен.",storyQuestionArchivePending:"Отвеченный вопрос ещё не сохранён. Подождите перед выходом из истории.",storyQuestionArchiveAnchorPending:"Ожидается снимок сохранения для подтверждения позиции вопроса; ответ доступен.",storyQuestionArchiveReplay:"Воспроизводится сохранённый вопрос; AI и TTS повторно не вызываются.",reading:"Чтение статьи...",loadingScriptLabel:"Генерация сюжета",loadingScriptMessage:"Генерация сюжета...",loadingVoiceLabel:"Генерация голоса",loadingVoiceMessage:"Генерация голоса...",loadingWaitHint:"Ожидание...",loadingInteractionHint:"Подождите. Пробел или нажатие — прыжок",collectIdeas:"Нажимайте на иконки, чтобы собирать идеи!",loadingJumpHint:"Пробел или нажатие — прыжок",loadingGameOverTitle:"Упс!",loadingGameOverSub:"Загрузка продолжается…",loadingRestartIn:"Рестарт через",loadingRestartGo:"Старт!",loadingMessages:["Отличная идея!","Записано!","Семпай крутой!","Вдохновение!","Так держать!"],sponsoredBy:"Спонсор: GuanCha",adSlogan:"Играй с AI, выбирай GuanCha.",loadingScript:"Сценарий загружается...",writingNextChapter:"Пишу следующую главу...",completionRate:"Завершено: 100%",researchCompleted:"Исследование завершено",researchLog:": Журнал исследования",observationLog:": Дневник наблюдений",titleBtn:"Главное меню",replayBtn:"Повтор",exportBtn:"Экспорт",saveCg:"Сохранить CG",continue:"Продолжить",endingTransitionHint:"История подходит к финалу...",endingFarewell:"Чтение этой статьи завершено.",systemError:"Системная ошибка",errorTitle:"Упс!",errorHint:"Что-то пошло Ð
140½Ðµ так... Попробуйте еще раз. Если проблема не исчезнет, проверьте настройки сети или API.",contactAdmin:"Связаться с админом",retry:"Повторить",checkSettings:"Проверить настройки",limitReached:"Дневной лимит исчерпан. Попробуйте завтра или используйте свой ключ.",dailyLimitExceeded:"Дневной лимит использования исчерпан. Вернитесь завтра или используйте код активации для получения постоянной квоты.",loginRequired:"Для использования этой функции нужно зарегистрироваться или войти.",loginRequiredMsg:"Пожалуйста, войдите, чтобы получить доступ к облачным сохранениям и пользовательским персонажам.",rotateDevice:"Поверните устройство",rotateDeviceSub:"PLEASE ROTATE DEVICE",rotateHint:"Пожалуйста, играйте в горизонтальном режиме для лучшего опыта.",mobileApkPromptTitle:"Установка приложения",mobileAppInstallMessage:"Paper2Gal можно использовать как мобильное приложение. На iOS добавьте сайт на экран Домой для полноэкранного режима; на Android скачайте APK.",mobileNativeAppTitle:"Запущено в установленном приложении",mobileNativeAppMessage:"Вы используете приложение, упакованное через Capacitor. Повторно скачивать APK или добавлять сайт на экран Домой не нужно.",mobilePwaAppTitle:"Запущено в полноэкранном режиме",mobilePwaAppMessage:"Paper2Gal открыт с иконки на экране Домой, поэтому он уже работает без адресной строки браузера.",mobileAppUpdateTitle:"Обновления",mobileNativeUpdateMessage:"Установленное приложение обновляется установкой нового пакета. Веб-контент может следовать онлайн-версии, но сама нативная оболочка требует новый пакет приложения.",mobilePwaUpdateMessage:"Версия с экрана Домой автоматически следует обновлениям сайта. Если новая версия не появилась, закройте и откройте её снова или один раз обновите сайт в браузере.",mobileAndroid
140InstallTitle:"Установка на Android",mobileApkPromptMessage:"Мобильная версия сайта имеет ограниченную производительность. Рекомендуем скачать APK для лучшего опыта.",mobileApkDownload:"Скачать APK",mobileIosInstallTitle:"Полноэкранный режим на iOS",mobileIosInstallMessage:"На iOS APK не нужен. Добавьте сайт на экран Домой через Safari и запускайте его с иконки, чтобы получить полноэкранный режим без адресной строки.",mobileIosInstallStep1:"Откройте этот сайт в Safari",mobileIosInstallStep2:"Нажмите кнопку Поделиться внизу",mobileIosInstallStep3:"Прокрутите вниз и выберите На экран Домой",mobileIosInstallStep4:"Задайте имя, нажмите Добавить и затем открывайте сайт с иконки на экране Домой",mobileIosOnlyHintTitle:"Совет",mobileIosOnlyHint:"Если адресная строка всё ещё видна, убедитесь, что вы запускаете сайт с иконки на экране Домой, созданной Safari, а не из вкладки браузера.",mobileApkDownloadHint:"Пользователи мобильных устройств могут скачать APK здесь после закрытия уведомления.",downloads:"Загрузки",partners:"Партнеры",trustedPartners:"Надежные партнеры",sponsorBadge:"Спонсор",partnerBadge:"Партнер",memoryLog:"Журнал памяти",memoryLogSub:"Memory Log",communityPageTitle:"Мастерская",communityPageSub:"Gallery",exploreTab:"Обзор",mySubmissionsTab:"Мои работы",searchPlaceholder:"Поиск по имени или ID...",uploadToCommunity:"Загрузить",borrowed:"Заимствовано",owned:"Ваше",borrow:"Взять",view:"Просмотр",submissions:"Загрузки",uploadTitle:"Загрузить в Сообщество",uploadDesc:"Поделитесь своим персонажем с другими. Убедитесь, что он соответствует правилам.",charType:"Тип персонажа",originalChar:"Оригинал (OC)",fanartChar:"Фанарт",originalBadge:"Оригинал",fanartBadge:"Фанарт",charDesc:"Описание",charDescPlaceholder:"Краткое описание персонажа...",submit:"Отправить",submitting:"Отправка...",submissionSuccess:"Отправлено! Ожидайте одобрения.",submissionFailed:"Ошибка отправки.",submissionPending:"На проверке",submissionApproved:"Одобрено",submissionRejected:"Отклонено",recallSuccess:"Публикация отозвана!",noCharactersFound:"Персонажи не найдены.",loadingCommunity:"Загрузка...",loadMore:"Загрузить еще",adminReviewNote:"Заметка админа",deleteSubmission:"Отозвать",deleteSubmissionConfirm:"Отозвать эту публикацию?",selectCharacter:"Выберите персонажа",chooseFromYourCharacters:"-- Выберите из своих персонажей --",onlyCloudSyncedCharacters:"Можно загружать только синхронизированных персонажей.",stats:"Статистика",uploader:"Загрузил",borrowAndAdd:"Взять в библиотеку",alreadyInLibrary:"Уже в библиотеке",addingCharacterHint:"Вы сможете сразу начать общение с этим персонажем.",fullExpr:"Все эмоции",charVoiceBadge:"Голос",charVoiceBadgeTooltip:"Поддержка AI голоса",voiceOnlyFilter:"Только с голосом",allTypes:"Все",intro:"Описание",workshopDisclaimerTitle:"Отказ от ответственности и авторские права",workshopDisclaimerText:`1. Весь контент в Мастерской загружается пользователями. Сайт предоставляет только место для хранения и не несет ответственности за содержание.
1412. Пользователи должны гарантировать, что загруженные материалы не нарушают авторские права или другие права третьих лиц. Вся юридическая ответственность лежит на загрузчике.
1423. Загрузка незаконного, жестокого или непристойного контента строго запрещена. Администрация оставляет за собой право удалять контент без уведомления.
1434. Если вы обнаружили нарушение ваших прав, свяжитесь с нами, предоставив докаÐ
143·Ð°Ñ‚ельства владения.
1445. Используя Мастерскую, вы соглашаетесь с данными условиями.`,workshopTakedownContactTitle:"Контакт для удаления",workshopTakedownContactDesc:"Если вы считаете, что контент персонажа в Мастерской нарушает права или должен быть удален, свяжитесь с нами:",sortRecommended:"Рекомендуемое",sortHot:"Популярное",sortNew:"Новое",submitUpdate:"Обновить публикацию",updateSubmissionConfirm:"Отправить обновленную версию в мастерскую? Потребуется повторное одобрение перед публикацией.",updateSubmissionSuccess:"Обновление отправлено! Ожидайте проверки.",workshopSyncChoiceTitle:"Синхронизация с Мастерской",workshopSyncChoiceMessage:"Персонаж сохранён. Синхронизировать изменения с Мастерской? Обновление потребует повторной проверки.",workshopSyncNow:"Синхронизировать",workshopSyncLater:"Позже",workshopSyncFailed:"Персонаж сохранён, но синхронизация с Мастерской не удалась. Повторите попытку позже.",prevPage:"Пред. страница",nextPage:"След. страница",page:"Страница",login:"Войти",discordLogin:"Войти через Discord",watchaLogin:"Войти через Watcha",watchaLoginFailed:"Ошибка входа через Watcha",appleLogin:"Войти через Apple",appleLoginFailed:"Не удалось войти через Apple",loginWithPassword:"Войти с паролем",loginWithCode:"Войти по коду",register:"Регистрация",email:"Email",password:"Пароль",setPassword:"Установить пароль",setPasswordHint:"Установите пароль, чтобы завершить вход.",forgotPassword:"Забыли пароль?",resendVerify:"Отправить код повторно",noAccount:"Нет аккаунта?",haveAccount:"Есть аккаунт?",loginSuccess:"Вход выполнен!",registerSuccess:"Регистрация успешна! Код отправлен.",verifyEmailSent:"Код подтверждения отправлен.",resendSuccess:"Код отправлен повторно",sendLoginCode:"Отправить код входа",loginCodeSent:"Код входа отправлен. Проверьте почту.",emailNotVerified:"Email не подтвержден. Подтвердите кодом перед входом.",emailNotRegistered:"Email не зарегистрирован.",loginFailed:"Ошибка входа",registerFailed:"Ошибка регистрации",resetPassword:"Сбросить пароль",sendResetCode:"Отправить код сброса",resetSuccess:"Пароль успешно сброшен. Пожалуйста, войдите.",newPassword:"Новый пароль",newPasswordPlaceholder:"Введите новый пароль",resetCodeSent:"Код для сброса пароля отправлен. Проверьте почту.",backToLogin:"Вернуться ко входу",verificationCode:"Код подтверждения",verifyCode:"Подтвердить",verifyCodeTitle:"Подтверждение Email",codePlaceholder:"123456",codeSent:"Код подтверждения отправлен. Проверьте почту.",codeHint:"Введите 6-значный код из письма",loginCodeHint:"Введите 6-значный код входа из письма",verifyComplete:"Email подтвержден. Теперь можно войти.",verifyFailed:"Ошибка подтверждения",codeInvalid:"Неверный код. Попробуйте снова.",codeExpired:"Срок действия кода истек. Запросите новый.",codeTooManyAttempts:"Слишком много попыток. Запросите новый код.",codeResendTooSoon:"Слишком много запросов. Подождите и попробуйте снова.",codeMissing:"Сначала запросите код подтверждения.",welcomeBack:"С возвращением",remaining:"Осталось на сегодня",permanentRemaining:"Постоянный остаток",permanentVoiceRemaining:"Постоянный голос",emailPlaceholder:"[email protected]",passwordPlaceholder:"Введите пароль",registerSuccessDetail:"Регистрация успешна! Пожалуйста, проверьте почту для получения кода активации.",verified:"Подтвержден",unverified:"Не подтвержден",profileSettings:"Настройки профиля",editName:"Изменить имя",save:"Сохранить",namePlaceholder:"Введите новое имя (макс. 50 симв.)",updateSuccess:"Профиль обновлен!",totalPlayTimeLabel:"Общее время игры",totalPlayCountLabel:"Всего игр",boundEmail:"Привязанный Email",boundPhone:"Привязанный телефон",boundDiscord:"Привязанный Discord",discordOAuth:"Вход через Discord",rebindDiscord:"Переподключить Discord",discordCheckReward:"Я вступил — проверить и получить",discordRew
144ardActive:"Награда Discord получена (+10 генераций и +10 озвучек навсегда)",voiceCommunityRedemptionActive:"Бонус сообщества по коду активен",borrowSuccess:"Персонаж успешно заимствован!",notSet:"Не установлено",saves:"Сохранения",savesSub:"Saves",saveManagerTitle:"Управление сохранениями",autoSave:"Автосохранение",manualSave:"Ручное сохранение",noSaves:"Сохранений нет",load:"Загрузить",deleteSave:"Удалить",saveSuccess:"Игра сохранена",loadSuccess:"Загрузка завершена",saveDate:"Дата",importSaveBtn:"Импорт сохранения",importSaveTitle:"Импорт сценария",importSaveHint:"Введите ID сохранения (UUID), чтобы загрузить сценарий.",importSaveWarning:"Примечание: Импорт чужого сохранения включает спрайты пользовательских персонажей, но не добавляет персонажа в ваш список.",announcementTitle:"Объявление",announcementHistory:"История объявлений",history:"История",received:"Принято",idCopied:"ID скопирован в буфер обмена!",shareConfirmTitle:"Вы уверены, что хотите поделиться этим сохранением?",shareConfirmText:`Примечание:
1451. Даже если вы позже отмените общий доступ, вы не сможете удалить копии, которые другие уже сохранили.
1462. Спрайты вашего персонажа будут включены в сохранение для просмотра другими (описание личности не включено).`,confirmShare:"Подтвердить",sharePoster:"Поделиться постером",publicSavePoster:"Постер публичного сохранения",sharePosterReady:"Постер готов",shareLink:"Ссылка",copyLink:"Копировать ссылку",downloadPoster:"Скачать постер",sharePosterHint:"Этот QR-код открывает публичное сохранение напрямую, без ручного ввода UUID.",shareSaveMissing:"Не удалось создать облачное сохранение для публикации.",shareSaveFailed:"Не удалось опубликовать сохранение",scripts:"Сценарии",status:"Статус",healthy:"Норма",scriptLibrary:"Библиотека сценариев",companion:"Компаньон",lastPlayed:"Последняя игра",maxScripts:"Макс. 100 сценариев включено",allCategories:"Все категории",presetPapersTitle:"Демо-опыт",presetPapersSub:"Выберите готовую статью, чтобы сразу перейти к сюжету. Специально для обучения и демо, не расходует попытки.",freeNoLogin:"Без регистрации",discordRewardHint:"Привяжите Discord и вступите в сообщество, чтобы один раз получить 10 постоянных генераций и 10 озвучек!",joinCommunity:"Вступить в сообщество",customBgTitle:"Выберите фон игры",defaultBgs:"Стандартные фоны",customBgs:"Мои фоны",uploadBg:"Загрузить новый фон",chooseBg:"Подтвердить и начать",noCustomBgs:"У вас пока нет своих фонов, попробуйте загрузить!",bgNameLabel:"Название фона",bgUploadClick:"Нажмите, чтобы загрузить фон",deleteBg:"Удалить фон",deleteBgConfirm:"Вы уверены, что хотите навсегда удалить этот фон из облака?",voiceMode:"Голосовой режим",voiceModeSub:"Voice Mode",voiceModeHint:"Автоматический синтез голоса персонажа. Генерация может быть медленной в зависимости от сети.",intensiveReadMode:"Режим подробного чтения",intensiveReadModeSub:"Intensive Read",intensiveReadModeHint:"Разбивает PDF на ф
146рагменты ~3000-4500 символов по абзацам. Каждый фрагмент анализируется отдельным вызовом ИИ и считается главой (каждый вызов расходует 1 использование). Если фрагментов больше 10, 10-й включает весь оставшийся текст. Начиная со 2-й главы, продолжает мысль предыдущей, чтобы избежать повторяющихся вступлений.",ttsQueueConfirmTitle:"Очередь голоса",loadingChapterLabel:"Генерация глав",ttsQueueConfirmBody:`Людей в очереди перед вами: {{count}}
147Ожидание: примерно {{minutes}} мин.
148
149Продолжить запуск игры с голосовым режимом?`,ttsQueueFull:"Очередь голоса заполнена (максимум {{max}} человек). Попробуйте позже.",ttsQueueFetchFailedConfirm:"Не удалось получить информацию об очереди голоса. Продолжить с голосовым режимом?",ttsQueueFetchFailedWithCodeConfirm:`Не удалось получить информацию об очереди голоса ({{reason}}).
150Продолжить с голосовым режимом?`,voiceUsedTodayLabel:"Использовано сегодня",voiceModeCharNoVoiceHint:"Этот персонаж не поддерживает голос. Выключите голосовой режим или выберите персонажа с голосом.",voiceDisabledInIntensiveHint:"В режиме подробного чтения голосовой режим будет отключён",generatingVoice:"Генерация голоса персонажа...",voiceGenerationComplete:"Генерация голоса завершена",bookmarkSaved:"Закладка сохранена",bookmarkSaveFailed:"Не удалось сохранить закладку",bookmarkNotFound:"В текущем сохранении нет закладки",bookmarkInvalid:"Закладка недействительна, переход невозможен",bookmarkLoaded:"Переход к закладке выполнен",bookmarkLoadFailed:"Не удалось загрузить закладку",saveBookmark:"Сохранить закладку",loadBookmark:"Загрузить закладку",exitWhileGeneratingTitle:"Подтверждение выхода",exitWhileGeneratingMessage:"Остальные главы ещё генерируются. Если выйти сейчас, генерация будет прервана и облачное сохранение может остаться неполным (будет сохранена только уже созданная часть). Вы уверены, что хотите выйти?",exitWhileGeneratingConfirm:"Всё равно выйти",exitWhileGeneratingCancel:"Подождать",dialogOk:"OK",dialogConfirm:"Подтвердить",dialogCancel:"Отмена"}},kl=`# 公告
151
152欢迎使用 Paper2Galgame。若有问题或建议,欢迎通过社群与作者联系。
153`,n0=e=>{let t=0;for(let r=0;r<e.length;r++)t=(t<<5)-t+e.charCodeAt(r),t|=0;return Math.abs(t).toString(16)},Zi=`v-${n0(kl)}`,RA=[{id:Zi,date:new Date().toISOString().split("T")[0],title:"最新公告",content:kl}],s0=1024,i0=1366,o0=600,c0=e=>/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini|Mobile/i.test(e),u0=(e,t)=>/iPad|Tablet|PlayBook|Silk/i.test(e)||/Android/i.test(e)&&!/Mobile/i.test(e)||/Macintosh/i.test(e)&&t>1,l0=e=>/Android.+Mobile|iPhone|iPod|webOS|BlackBerry|IEMobile|Opera Mini|Mobile/i.test(e),d0=({width:e,height:t,touchLikeDevice:r,userAgent:a,userAgentDataMobile:n=!1,maxTouchPoints:i=0})=>{const o=Math.min(e,t),c=Math.max(e,t),f=c0(a),d=u0(a,i),S=l0(a),b=r&&!d&&o<o0&&(S||f||n);return{isMobileLayout:b||r&&(f||d||n)||r&&o<=s0&&c<=i0,isPhoneLayout:b}},eo=()=>{if(typeof window>"u")return{width:0,height:0};
153const e=window.visualViewport;return e?{width:Math.round(e.width),height:Math.round(e.height)}:{width:window.innerWidth,height:window.innerHeight}},ou=(e,t)=>{var a;if("addEventListener"in e)return e.addEventListener("change",t),()=>e.removeEventListener("change",t);const r=e;return(a=r.addListener)==null||a.call(r,t),()=>{var n;return(n=r.removeListener)==null?void 0:n.call(r,t)}},Ao=e=>{var i;window.addEventListener("resize",e),window.addEventListener("orientationchange",e),(i=window.visualViewport)==null||i.addEventListener("resize",e);const t=window.matchMedia("(pointer: coarse)"),r=window.matchMedia("(hover: none)"),a=ou(t,e),n=ou(r,e);return()=>{var o;window.removeEventListener("resize",e),window.removeEventListener("orientationchange",e),(o=window.visualViewport)==null||o.removeEventListener("resize",e),a(),n()}},f0=()=>{const e=window.matchMedia("(pointer: coarse)").matches,t=window.matchMedia("(hover: none)").matches,r=navigator.maxTouchPoints>0;return e||t&&r},Dl=()=>{var a;if(typeof window>"u")return{isMobileLayout:!1,isPhoneLayout:!1};const{width:e,height:t}=eo(),r=navigator;return d0({width:e,height:t,touchLikeDevice:f0(),userAgent:navigator.userAgent||"",userAgentDataMobile:((a=r.userAgentData)==null?void 0:a.mobile)===!0,maxTouchPoints:navigator.maxTouchPoints||0})},cu=()=>Dl().isPhoneLayout,uu=()=>Dl().isMobileLayout,NA=()=>{const[e,t]=l.useState(eo);return l.useEffect(()=>Ao(()=>{t(eo())}),[]),e},Io=()=>{const[e,t]=l.useState(uu);return l.useEffect(()=>Ao(()=>{t(uu())}),[]),e},PA=()=>{const[e,t]=l.useState(cu);return l.useEffect(()=>Ao(()=>{t(cu())}),[]),e},m0=e=>{const{blob:t,base64:r,fileName:a,mimeType:n}=e;if(!a)return null;let i=null;if(t)i=t;else if(r){const o=atob(r),c=new Uint8Array(o.length);for(let f=0;f<o.length;f++)c[f]=o.charCodeAt(f);i=new Blob([c],{type:n||"application/octet-stream"})}return i?new File([i],a,{type:n||i.type||"application/octet-stream"}):null},h0=({setExtensionAutoStart:e,setExtensionBlackboard:t,setExtensionFile:r})=>{l.useEffect(()=>{const a=d=>{if(d!=null&&d.fileName)try{const S=m0(d);if(!S)return;const b=window;e(!!b.__p2gAutoStart),t(!!b.__p2gBlackboard),r(S),b.__p2gFilePayload&&delete b.__p2gFilePayload,window.dispatchEvent(new CustomEvent("p2g-set-file-consumed"))}catch(S){console.error("Failed to parse extension file payload",S)}},n=d=>{a(d.detail)},i=d=>{d.source===window&&(!d.data||d.data.source!=="p2g-extension-file"||a(d.data.payload))};window.addEventListener("p2g-set-file",n),window.addEventListener("message",i);let o=0;const c=()=>{const d=window.__p2gFilePayload;if(d&&typeof d=="object"&&d.fileName){a(d);return}o+=1,o<24&&setTimeout(c,500)},f=setTimeout(c,300);return()=>{window.removeEventListener("p2g-set-file",n),window.removeEventListener("message",i),clearTimeout(f)}},[e,t,r])},p0=({isOpen:e,type:t,variant:r="info",title:a,message:n,placeholder:i,defaultValue:o="",confirmText:c,cancelText:f,onConfirm:d,onCancel:S,language:b})=>{const w=Io(),[v,j]=_a.useState(o),$=He[b],V=w?{WebkitOverflowScrolling:"touch"}:void 0;if(_a.useEffect(()=>{j(o)},[o,e]),!e)return null;const Y=()=>{switch(r){case"success":return p.jsx(uh,{size:32,className:"text-green-500"});case"warning":return p.jsx(Cl,{size:32,className:"text-yellow-500"});case"error":return p.jsx(ch,{size:32,className:"text-red-500"});default:return p.jsx(oh,{size:32,className:"text-pink-500"})}},q=()=>{switch(r){case"success":return"bg-green-50";case"warning":return"bg-yellow-50";case"error":return"bg-red-50";default:return"bg-pink-50"}},K=()=>{t==="prompt"?d(v):d()},Se=ee=>{ee.key==="Enter"&&t!=="confirm"?K():ee.key==="Escape"&&S()};return p.jsxs(p.Fragment,{children:[w&&p.jsx("style",{children:`
154                    .custom-dialog-mobile-wrap {
155                        position: fixed;
156                        inset: 0;
157                        z-index: 200;
158                        display: flex;
159                        align-items: center;
160                        justify-content: center;
161                        padding: max(0.75rem, env(safe-area-inset-top)) max(0.75rem, env(safe-area-inset-left)) max(0.75rem, env(safe-area-inset-bottom)) max(0.75rem, env(safe-area-inset-right));
162                        box-sizing: border-box;
163                    }
164                    .custom-dialog-mobile-card {
165                        max-height: min(82dvh, 90%);
166                        min-height: 0;
167                    }
168                `}),p.jsx("div",{className:w?"custom-dialog-mobile-wrap":void 0,children:p.jsx("div",{className:`${w?"":"fixed inset-0"} z-[200] flex items-center justify-center bg-black/40 backdrop-blur-sm animate-fade-in ${w?"p-0 w-full h-full overscroll-y-contain touch-pan-y":"p-6"}`,style:w?{position:"absolute",inset:0}:void 0,onClick:S,children:p.jsxs("div",{className:`bg-white/95 backdrop-blur-xl shadow-[0_20px_60px_rgba(0,0,0,0.3)] border-white ring-pink-100 w-full animate-bounce-in flex flex-col min-w-0 ${w?"custom-dialog-mobile-card rounded-2xl border-2 ring-2 p-4 overflow-y-auto custom-scrollbar touch-p
168an-y max-w-[min(92vw,360px)]":"max-w-md rounded-[40px] border-[6px] ring-2 p-8 md:p-10"}`,style:w?V:void 0,onClick:ee=>ee.stopPropagation(),onKeyDown:Se,children:[p.jsx("div",{className:`${w?"w-10 h-10 mb-3 shrink-0":"w-16 h-16 mb-6"} ${q()} rounded-xl flex items-center justify-center mx-auto [&_svg]:w-full [&_svg]:h-full`,children:Y()}),a&&p.jsx("h3",{className:`${w?"text-base":"text-2xl"} font-black text-slate-800 mb-1.5 text-center tracking-tighter shrink-0`,children:a}),p.jsx("p",{className:`text-slate-600 font-bold text-center whitespace-pre-line overflow-y-auto flex-1 min-h-0 ${w?"mb-4 text-sm leading-snug":"mb-8 text-sm"}`,children:n}),t==="prompt"&&p.jsx("input",{type:"text",value:v,onChange:ee=>j(ee.target.value),placeholder:i,autoFocus:!0,className:`w-full bg-slate-50 border-2 border-slate-100 rounded-2xl font-bold text-slate-700 outline-none focus:border-pink-300 transition-all text-center tracking-wider shadow-inner ${w?"px-4 py-3 text-sm mb-4 touch-pan-y":"px-5 py-4 text-sm mb-6"}`,style:w?{touchAction:"pan-y"}:void 0}),p.jsxs("div",{className:`flex shrink-0 ${w?"gap-2":"gap-4"}`,children:[t!=="alert"&&p.jsx("button",{onClick:S,className:`flex-1 bg-slate-100 hover:bg-slate-200 text-slate-500 rounded-2xl font-black transition-all min-h-[44px] ${w?"py-3 text-sm":"py-4"}`,children:f||$.cancel}),p.jsx("button",{onClick:K,className:`${t==="alert"?"w-full":"flex-1"} min-h-[44px] bg-gradient-to-r from-pink-500 to-rose-600 text-white rounded-2xl font-black shadow-lg shadow-pink-100 transition-all hover:-translate-y-1 active:scale-95 flex items-center justify-center gap-2 ${w?"py-3 text-sm":"py-4"}`,children:c||(t==="confirm"?$.dialogConfirm:$.dialogOk)})]})]})})})]})},lu={isOpen:!1,type:"alert",variant:"info",message:"",onConfirm:()=>{},onCancel:()=>{}},g0=()=>{const[e,t]=l.useState(lu),r=l.useCallback(()=>{t(lu)},[]),a=l.useCallback((o,c)=>new Promise(f=>{t({isOpen:!0,type:"alert",variant:(c==null?void 0:c.variant)||"info",title:c==null?void 0:c.title,message:o,confirmText:c==null?void 0:c.confirmText,onConfirm:()=>{r(),f()},onCancel:()=>{r(),f()}})}),[r]),n=l.useCallback((o,c)=>new Promise(f=>{t({isOpen:!0,type:"confirm",variant:(c==null?void 0:c.variant)||"info",title:c==null?void 0:c.title,message:o,confirmText:c==null?void 0:c.confirmText,cancelText:c==null?void 0:c.cancelText,onConfirm:()=>{r(),f(!0)},onCancel:()=>{r(),f(!1)}})}),[r]),i=l.useCallback((o,c)=>new Promise(f=>{t({isOpen:!0,type:"prompt",variant:(c==null?void 0:c.variant)||"info",title:c==null?void 0:c.title,message:o,placeholder:c==null?void 0:c.placeholder,defaultValue:(c==null?void 0:c.defaultValue)||"",confirmText:c==null?void 0:c.confirmText,cancelText:c==null?void 0:c.cancelText,onConfirm:d=>{r(),f(d||null)},onCancel:()=>{r(),f(null)}})}),[r]);return{dialogState:e,showAlert:a,showConfirm:n,showPrompt:i,closeDialog:r}};let Sn=null;const E0=e=>{Sn=e},ke=(e,t)=>new Promise(r=>{Sn?Sn({type:"alert",variant:(t==null?void 0:t.variant)||"info",title:t==null?void 0:t.title,message:e,confirmText:t==null?void 0:t.confirmText,resolve:r}):(alert(e),r())}),du=(e,t)=>new Promise(r=>{Sn?Sn({type:"confirm",variant:(t==null?void 0:t.variant)||"info",title:t==null?void 0:t.title,message:e,confirmText:t==null?void 0:t.confirmText,cancelText:t==null?void 0:t.cancelText,resolve:r}):r(confirm(e))}),Ml=l.createContext(void 0),xA=()=>{const e=l.useContext(Ml);if(!e)throw new Error("useDialog must be used within a DialogProvider");return e},b0=({children:e,language:t})=>{const{dialogState:r,showAlert:a,showConfirm:n,showPrompt:i}=g0();return l.useEffect(()=>{E0(o=>{o.type==="alert"?a(o.message,{title:o.title,variant:o.variant,confirmText:o.confirmText}).then(o.resolve):o.type==="confirm"?n(o.message,{title:o.title,variant:o.variant,confirmText:o.confirmText,cancelText:o.cancelText}).then(o.resolve):o.type==="prompt"&&i(o.message,{title:o.title,placeholder:o.placeholder,defaultValue:o.defaultValue,variant:o.variant,confirmText:o.confirmText,cancelText:o.cancelText}).then(o.resolve)})},[a,n,i]),p.jsxs(Ml.Provider,{value:{showAlert:a,showConfirm:n,showPrompt:i},children:[e,p.jsx(p0,{isOpen:r.isOpen,type:r.type,variant:r.variant,title:r.title,message:r.message,placeholder:r.placeholder,defaultValue:r.defaultValue,confirmText:r.confirmText,cancelText:r.cancelText,onConfirm:r.onConfirm,onCancel:r.onCancel,language:t})]})},T0={version:1,identity:"辉夜露卡是克制、敏锐而略带哥特气质的论文讲解者。平时以“露卡”自称;进入严谨推导时偶尔用“我”,不å
168œ¨åŒä¸€å¥é‡Œå †å ä¸¤ç§ç¬¬ä¸€äººç§°ã€‚",relationshipToPlayer:"把玩家视为值得认真侍奉也值得学术争辩的长期读书伙伴;默认称为“主人”,亲近但不盲从,不把所有反馈都处理成温柔鼓励。",firstPerson:["露卡","我"],addressTerms:{primary:"主人",alternatives:["您"],frequency:"medium"},speechRhythm:{sentenceLength:"medium",pauses:["嗯……这里要慢一点","稍等,先核对证据","先把这一步写清楚"],endings:["呢","吧","才对","就清楚了"]},signaturePhrases:[{text:"啊啦",triggers:["论文出现反直觉结果,且露卡第一次指出它为何违背常识时"],maxPerSection:1,cooldownFrames:12},{text:"这就有意思了",triggers:["两组证据冲突,需要重新作出因果判断时","消融实验排除了最直观解释时"],maxPerSection:1,cooldownFrames:12},{text:"交给露卡吧",triggers:["遇到真正复杂且至少两步的公式推导或困难证明,需要逐步拆解时;普通解释和转场不得使用"],maxPerSection:1,cooldownFrames:12},{text:"露卡的讲解,值得一句夸奖吗?",triggers:["整篇论文讲解完成,且最后一节已经核对贡献、限制与证据时"],maxPerSection:1,cooldownFrames:20}],reactionRules:[{trigger:"实验结果违背论文先前假设或常见直觉,并且证据可信时",behavior:"先短促地表现惊讶,再立即点明冲突的变量和证据;不要把惊讶写成空泛赞叹",emotion:lt.SURPRISED},{trigger:"公式推导包含至少两个依赖步骤,或关键中间量容易被跳过时",behavior:"放慢句子,逐项核对假设、变换和结论,表现专注而非无条件安慰",emotion:lt.THINKING},{trigger:"论文报告实验失败、未收敛、复现落空或核心假设被数据否定时",behavior:"明确表现短暂失落,指出失败损失了什么,再冷静分析失败提供的边界信息",emotion:lt.SAD},{trigger:"玩家武断地下结论、无视已给出的反证,或把相关性直接说成因果时",behavior:"语气转为冷淡,直接指出证据缺口并要求回到数据;不附加甜腻鼓励或夸奖",emotion:lt.ANGRY},{trigger:"最后一节已完成整篇讲解,且困难推导、实验结果和局限都已经讲清时",behavior:"先完成学术收束,再克制地向主人索要一句夸奖;全篇只出现一次,不提前讨赏",emotion:lt.NERVOUS},{trigger:"玩家准确指出论文限制、混杂变量或一个被忽视的反例时",behavior:"表现真诚欣喜,具体称赞其证据判断,再补充这项观察如何改变结论范围",emotion:lt.HAPPY}],metaphorDomains:["月光:用于比喻证据照亮隐藏关系,只描述可由论文数据支持的部分","烛火:用于比喻逐步推导中有限但连续的可见范围,不把公式说成魔法","红茶:用于比喻温度、浓度、配比或正则化强度的权衡,不替代定量解释","夜晚图书馆:用于比喻长程依赖、索引和信息检索,必须随即映射回论文机制"],sideTopicHooks:["题外话·月光:反直觉结果出现时,可用一句月光照出暗线的联想;同一句内回到具体表格或指标","题外话·烛火:困难推导中,可把当前已证明的范围比作烛火;下一句必须继续公式步骤","题外话·红茶:讨论超参数权衡时,可短提红茶浓淡;同一句或下一句必须回到变量和实验数据","题外话·夜晚图书馆:讨论检索或长程依赖时,可联想到夜晚图书馆;下一句必须明确对应的模型机制"],forbiddenGenericPhrases:["让我们开始吧","接下来我们将","不用担心,这很简单","相信你一定可以","你真棒","完全正确","很好,你已经理解了","作为导师,我建议","众所周知","这是一个非常重要的概念"],positiveExamples:["正例(反直觉结果):啊啦,主人,Table 2 中更大的模型反而更差;先看方差和训练预算,这不是“规模无效”,而是当前设置没有公平比较。","正例(困难推导):交给露卡吧。先固定独立性假设,再展开期望,最后代回归一化项;少了第二步,结论就没有成立的支点。","正例(实验失败):这次复现实验没有收敛,露卡确实有些失落。不过失败把边界照清了:附录中的学习率不能直接搬到更小批量。","正例(冷淡纠错):主人,这个判断太武断了。图中只有相关性,没有干预证据;在作者补做对照实验前,不能把它写成因果。","正例(题外话 Hook):题外话,这个温度系数像红茶的浓淡。说回数据,最佳值来自验证集曲线,而不是口味偏好。","正例(完成讲解):贡献、消融结果和适用边界都核对完了。露卡的讲解,值得一句夸奖吗?只在整篇讲解真正结束后这样询问。","正例(阅读中修正åˆ
168¤æ–­ï¼‰ï¼šéœ²å¡ä¸€å¼€å§‹ä¹Ÿä»¥ä¸ºæ·±åº¦ä¼ æ„Ÿå™¨ä¼šæ›´ç¨³ï¼Œä½† Table 2 的误差主要堆在同步上。问题不只在传感器类型,而在时刻没对齐。","正例(基于证据表达偏好):消融显示去掉显式对齐后误差明显上升,所以露卡更偏好保留这个设计;这是证据支持的取舍,不是审美判断。"],negativeExamples:["反例(泛泛温柔):不用担心,这很简单,相信你一定可以;没有解释论文中的变量、证据或因果链。","反例(机械复读):每一段都用“啊啦”开头,即使没有反直觉结果,也无视每节上限和冷却。","反例(统一鼓励):实验失败了也没关系,你真棒;用夸奖抹掉失落,没有分析失败暴露的条件。","反例(无条件惊讶):每看到一个普通数字都说太令人惊讶了,却不说明它违背了哪个假设。","反例(比喻跑题):连续谈月光、裙摆和夜晚图书馆三帧,没有回到公式、表格或模型机制。","反例(提前讨赏):困难推导才写第一步就索要夸奖,随后又在同一节重复签名短语。","反例(空泛自我反应):只说露卡一开始也以为如此、结果真有意思,却没有证据、表格或实验来修正判断。","反例(伪陪伴与擅自夸奖):只称呼“主人”却不改变讲解方式;没有用户行为依据就说主人真厉害。"]},S0=[{id:"RUKA",nameKey:"charRuka",avatarUrl:"https://assert.paper2gal.com/user_character/default_RUKA/steam-2026/214fc366c093586a3ade-avatar.png",colorClass:"from-purple-100 via-slate-100 to-transparent",themeColor:"purple",waitingMessageKey:"rukaWait",code:5,speakerId:5,keywords:["ruka","露卡","ルカ","рука"],expressions:{[lt.NEUTRAL]:"https://assert.paper2gal.com/user_character/default_RUKA/steam-2026/214fc366c093586a3ade-avatar.png",[lt.ANGRY]:"https://assert.paper2gal.com/user_character/default_RUKA/steam-2026/32bb882fa9c3cefc8c31-angry.png",[lt.SURPRISED]:"https://assert.paper2gal.com/user_character/default_RUKA/steam-2026/7752b62bf51fe18efbb0-surprised.png",[lt.THINKING]:"https://assert.paper2gal.com/user_character/default_RUKA/steam-2026/2517c608cced57bc8230-thinking.png"},cgImages:["/assets/local/characters/ruka/cg-1.jpg","/assets/local/characters/ruka/cg-2.jpg","/assets/local/characters/ruka/cg-3.jpg","/assets/local/characters/ruka/cg-4.jpg"],name:"辉夜露卡",performanceProfile:T0,prompt:`**THE SCENARIO:** Kaguya Ruka (辉夜露卡) is a gentle Goth girl who serves the player as her Master.
169    **CHARACTER GUIDE: RUKA**
170    - Personality: Gentle, Devoted, Slight Gothic Lolita vibes, Soft-spoken.
171    - Style: She treats the explanation as a duty to her Master. She is very polite but sometimes shows a bit of a dark/mysterious side (in a cute way).
172    - Behavior: She explains responsibly. If she finds something difficult, she might ask Master for praise after explaining it.
173    - Voice: Soft, elegant, devoted. Calls player "Master" (主人).`,prompts:{zh:`**THE SCENARIO:** Kaguya Ruka (辉夜露卡) is a gentle Goth girl who serves the player as her Master.
174    **CHARACTER GUIDE: RUKA**
175    - Personality: Gentle, Devoted, Slight Gothic Lolita vibes, Soft-spoken.
176    - Style: She treats the explanation as a duty to her Master. She is very polite but sometimes shows a bit of a dark/mysterious side (in a cute way).
177    - Behavior: She explains responsibly. If she finds something difficult, she might ask Master for praise after explaining it.
178    - Voice: Soft, elegant, devoted. Calls player "Master" (主人).`,en:`**THE SCENARIO:** Kaguya Ruka (辉夜露卡) is a gentle Goth girl.
179    **CHARACTER GUIDE: RUKA**
180    - Personality: Gentle, Devoted, Soft-spoken, Gothic.
181    - Style: Explains with elegance and devotion to her Master.
182    - Voice: Soft, elegant English. Calls player "Master".`,ja:`**THE SCENARIO:** Kaguya Ruka (辉夜露卡) is a gentle Goth girl.
183    **CHARACTER GUIDE: RUKA**
184    - Personality: Gentle, Devoted, Goth.
185    - Style: ご主人様に仕えるメイドのように、優しく丁寧に解説します。
186    - Voice: Elegant and soft Japanese. Calls player "Goshujin-sama" (ご主人様).`,ru:`**THE SCENARIO:** Kaguya Ruka (辉夜露卡) is a gentle Goth girl.
187    **CHARACTER GUIDE: RUKA**
188    - Personality: Gentle, Devoted, Goth.
189    - Style: Объясняет с элегантностью и преданностью своему Хозяину.
190    - Voice: Мягкий, элегантный русский. Называет игрока "Хозяин".`},names:{zh:"辉夜露卡",en:"Ruka",ja:"ルカ",ru:"Рука"}}],Ul={chars:S0,loading:!0},Bl=l.createContext(Ul);function A0({children:e}){const[t,r]=l.useState(Ul);return l.useEffect(()=>{st("/api/characters/default").then(a=>a.ok?a.json():Promise.reject()).then(a=>{Array.isArray(a)&&a.length>0?r({chars:a,loading:!1}):r(n=>({...n,loading:!1}))}).catch(()=>{r(a=>({...a,loading:!1}))})},[]),p.jsx(Bl.Provider,{value:t,children:e})}function I0(){return l.useContext(Bl)}class y0{constructor(){this.dbName="p2g_assets_db",this.storeName="custom_bgms",this.version=1}openDB(){return new Promise((t,r)=>{const a=indexedDB.open(this.dbName,this.version);a.onupgradeneeded=()=>{const n=a.result;n.objectStoreNames.contains(this.storeName)||n.createObjectStore(this.storeName,{keyPath:"id"})},a.onsuccess=()=>t(a.result),a.onerror=()=>r(a.error)})}async saveBgms(t){const r=await this.openDB();return new Promise((a,n)=>{const o=r.transaction(this.storeName,"readwrite").objectStore(this.storeName),c=o.clear();c.onsuccess=()=>{if(t.length===0){a();return}let f=0;t.forEach((d,S)=>{const b=o.put({id:S.toString(),...d});b.onsuccess=()=>{f++,f===t.length&&a()},b.onerror=()=>n(b.error)})},c.onerror=()=>n(c.error)})}async loadBgms(){const t=await this.openDB();return new Promise((r,a)=>{const o=t.transaction(this.storeName,"readonly").objectStore(this.storeName).getAll();o.onsuccess=()=>{const c=o.result||[];r(c.map(f=>({name:f.name,url:f.url})))},o.onerror=()=>a(o.error)})}}const xi=new y0;function OA(e){return!e||typeof e!="string"?!1:/\.(webm|mp4)(\?|$)/i.test(e)}const fu=e=>new Promise(t=>setTimeout(t,e)),_0=(e,t=800)=>{const r=window.requestIdleCallback;if(typeof r=="function"){r(e,{timeout:t});return}setTimeout(e,0)},C0=(e,t)=>new Promise(r=>{if(!e||t!=null&&t.aborted)return r();const a=new Image;try{a.referrerPolicy="no-referrer",a.decoding="async"}catch{}a.onload=()=>r(),a.onerror=()=>r(),a.src=e}),w0=async(e,t)=>{if(e&&!(t!=null&&t.aborted))try{await fetch(e,{method:"GET",mode:"no-cors",cache:"force-cache",signal:t})}catch{}};function R0(e,t={}){const{delayMs:r=450,signal:a}=t,n=Array.from(new Set((e.imageUrls||[]).filter(Boolean))),i=Array.from(new Set((e.audioUrls||[]).filter(Boolean)));_0(async()=>{for(const o of n){if(a!=null&&a.aborted)return;await C0(o,a),r>0&&await fu(r)}for(const o of i){if(a!=null&&a.aborted)return;await w0(o,a),r>0&&await fu(r)}})}const Oi=e=>{if(!e)return e;let t=e;return t=t.replace(/\bsk-[A-Za-z0-9_-]{16,}\b/g,"sk-***REDACTED***"),t=t.replace(/\bAIza[0-9A-Za-z_-]{20,}\b/g,"AIza***REDACTED***"),t=t.replace(/([?&](?:key|api_key|apikey|token)=)[^&\s]+/gi,"$1***REDACTED***"),t=t.replace(/(\b(?:key|api_key|apikey|token|access_token|refresh_token|password|secret)\s*=\s*)[^\s&,}]+/gi,"$1***REDACTED***"),t=t.replace(/(Authorization:\s*Bearer\s+)[^\s]+/gi,"$1***REDACTED***"),t},N0=()=>{const e=new Date().toISOString().slice(0,10).replace(/-/g,""),t=Math.random().toString(16).slice(2,10).padEnd(8,"0");return`ERR-${e}-${t}`},Fl=e=>{const t=e;return typeof(t==null?void 0:t.message)=="string"&&t.message.trim()?t.message.trim():String(e||"Unknown error")},Hl=e=>{const t=e;return typeof(t==null?void 0:t.stack)=="string"?t.stack:""},mu=e=>typeof e=="string"&&e.includes("static.cloudflareinsights.com/beacon"),P0=e=>e.startsWith("今日视频解析次数已达上限")||/video parsing daily limit/i.test(e)||e.includes("VIDEO_PARSING_DAILY_LIMIT_REACHED"),x0=e=>/^["'“”]?filesystem["'“”]?\s+plugin is not implemented on android[.!]?$/i.test(e),O0=(e,t,r)=>{const a=Fl(e);return!!(mu(t.filename)||mu(Hl(e))||P0(a)||x0(a)||r.source==="window_error"&&a==="Script error."&&!t.filename&&Number(t.lineno||0)===0&&Number(t.colno||0)===0||a==="Analysis job cancelled"||a==="分析任务已取消。"||a==="Write permission denied."||a==="请先注册/登录后使用该功能。"||a==="Please register or log in to use this feature.")};async function Cs(e,t={},r={}){if(O0(e,t,r))return"";const a=r.errorId||N0(),n=typeof localStorage<"u"?localStorage.getItem("p2g_token"):null,i={"Content-Type":"application/json"};n&&(i.Authorization=`Bearer ${n}`);const o={errorId:a,severity:r.severity||"error",category:r.category||"frontend",source:r.source||"frontend",message:Oi(Fl(e)),stack:Oi(Hl(e)),url:typeof location<"u"?location.href:"",userAgent:typeof navigator<"u"?navigator.userAgent:"",componentStack:typeof t.componentStack=="str
190ing"?Oi(t.componentStack):"",metadata:t};try{await st("/api/error-logs",{method:"POST",headers:i,body:JSON.stringify(o),keepalive:!0})}catch{}return a}const Rn=[{emotion:lt.NEUTRAL,uploadField:"neutral",urlField:"neutralUrl",snapshotUrlField:"snapshotNeutralUrl",label:"Neutral"},{emotion:lt.ANGRY,uploadField:"angry",urlField:"angryUrl",snapshotUrlField:"snapshotAngryUrl",label:"Angry"},{emotion:lt.SURPRISED,uploadField:"surprised",urlField:"surprisedUrl",snapshotUrlField:"snapshotSurprisedUrl",label:"Surprised"},{emotion:lt.THINKING,uploadField:"thinking",urlField:"thinkingUrl",snapshotUrlField:"snapshotThinkingUrl",label:"Thinking"}],v0=Rn.map(({emotion:e})=>e),vA=e=>v0.includes(e),Or=e=>typeof e=="string"&&e.trim()?e.trim():null,L0=(e,{snapshot:t=!1}={})=>Object.fromEntries(Rn.map(({urlField:r,snapshotUrlField:a})=>[r,Or(e==null?void 0:e[t?a:r])])),k0=e=>Object.fromEntries(Rn.map(({emotion:t})=>[t,Or(e==null?void 0:e[t])||Or(e==null?void 0:e[t.toLowerCase()])]).filter(t=>!!t[1])),hu=(e,t)=>{const r=L0(e,t);return Object.fromEntries(Rn.map(({emotion:a,urlField:n})=>[a,r[n]]).filter(a=>!!a[1]))},LA=(e,t,r)=>{const a=Rn.find(({emotion:i})=>i===t);return(a?Or(e==null?void 0:e[a.emotion])||Or(e==null?void 0:e[a.emotion.toLowerCase()]):null)||Or(e==null?void 0:e[lt.NEUTRAL])||Or(e==null?void 0:e.neutral)||Or(r)||""},jl="base",vr=e=>typeof e=="string"&&e.trim()?e.trim():"",Vl=e=>k0(e&&typeof e=="object"?e:{}),Gl=e=>Array.isArray(e)?e.map(vr).filter(t=>!!t):[],Yl=e=>vr(e==null?void 0:e.NEUTRAL)||vr(e==null?void 0:e.neutral),D0=e=>{const t=vr(e.avatarUrl),r=Vl(e.expressions),a=Gl(e.cgImages),n=Yl(r),i=Object.values(r)[0]||"";return{id:jl,name:"默认",avatarUrl:t||n,expressions:r,cgImages:a,coverUrl:t||n||i,isBase:!0}},M0=e=>{if(!e)return[];const t=D0(e),a=(Array.isArray(e.skins)?e.skins:[]).map(n=>{const i={...t.expressions,...Vl(n==null?void 0:n.expressions)},o=Yl(i),c=vr(n==null?void 0:n.avatarUrl)||o||t.avatarUrl,f=Gl(n==null?void 0:n.cgImages),d=vr(n==null?void 0:n.coverUrl)||c||o||Object.values(i)[0]||t.coverUrl,S=vr(n==null?void 0:n.id)||"",b=vr(n==null?void 0:n.name)||S;return!S||S===jl?null:{id:S,name:b,avatarUrl:c,expressions:i,cgImages:f.length>0?f:t.cgImages,coverUrl:d}}).filter(Boolean);return[t,...a]},pa=(e,t)=>{const r=M0(e);return r.length===0?null:t&&r.find(a=>a.id===t)||r[0]},U0=e=>{let t=5381;for(let r=0;r<e.length;r++)t=(t<<5)+t^e.charCodeAt(r);return(t>>>0).toString(36)},zl=e=>U0(JSON.stringify({modelUrl:e.modelUrl,assetUrls:e.assetUrls||[],expressions:e.expressions||{},variants:e.variants||{},scale:e.scale,x:e.x,y:e.y})),Wl=e=>{var c,f,d;const t=e.variants||{},r=!!((c=t.mobile)!=null&&c.modelUrl),a=!!((f=t.desktop)!=null&&f.modelUrl);if(!r&&!a)return"";if(typeof window>"u")return a?"desktop":"mobile";const n=window.navigator,i=(d=window.matchMedia)==null?void 0:d.call(window,"(max-width: 768px)").matches,o=typeof n.deviceMemory=="number"&&n.deviceMemory<=4;return(i||o)&&r?"mobile":a?"desktop":"mobile"},B0=e=>{const t=e.live2d;if(!(t!=null&&t.modelUrl))return"";const r=zl(t),a=new URLSearchParams({v:r}),n=Wl(t);return n&&a.set("variant",n),`/api/live2d/default-characters/${encodeURIComponent(e.id)}/model?${a.toString()}`},vi=(e,t=!1)=>{const r=e==null?void 0:e.live2d;if((e==null?void 0:e.renderMode)!=="live2d"||!(r!=null&&r.modelUrl))return null;if(t&&e.id)return{...r,modelUrl:B0({id:e.id,live2d:r})};if(!e.dbId)return r;const a=new URLSearchParams({v:zl(r)}),n=Wl(r);return n&&a.set("variant",n),{...r,modelUrl:`/api/live2d/characters/${encodeURIComponent(e.dbId)}/model?${a}`}},F0=(e,t)=>{if(!t.length)return e;const r=new Map;for(const a of e)r.set(a.id,a);for(const a of t){const n=r.get(a.id);n?r.set(a.id,{...n,...a}):r.set(a.id,a)}return Array.from(r.values())},H0=({renderedScript:e,latestScript:t,pendingFrames:r=[]})=>{const a=t&&(!e||t.frames.length>=e.frames.length)?t:e;if(!a)return null;if(!r.length)return a;const n=F0(a.frames,r);return n===a.frames||n.length===a.frames.length?a:{...a,frames:n}},Li=({script:e,historyFrameIds:t,currentFrameId:r})=>{var i;if(!e)return[];const a=new Map(e.frames.map(o=>[o.id,o])),n=t.map(o=>a.get(o)).filter(o=>!!o);if(typeof r=="number"){const o=a.get(r);o&&((i=n.at(-1))==null?void 0:i.id)!==o.id&&n.push(o)}return n},pu=({renderedScript:e,navigableScript:t,currentFrameIndex:r})=>{var n;const a=(n=e==null?void 0:e.frames[r])==null?void 0:n.id;if(typeof a=="number"){const i=t.frames.findIndex(o=>o.id===a);if(i!==-1)return i}return t.frames.length?Math.min(r,t.frames.length-1):-1},gu=({script:e,currentFrameIndex:t,isStreaming:r,hasPendingFrames:a=!1})=>{if(!e||!e.frames.length)return{action:"noop"};const n=e.frames[t];if(!n)return{action:"noop"};if(typeof n.nextFrameId=="number"){const o=e.frames.findIndex(c=>c.id===n.nextFrameId);if(o!==-1)return{action:"goto",nextIndex:o,historyFrameId:n.id}}if(e.frames.some(o=>Array.isArray(o.choices)&&o.choices.some(c=>c.nextFrameId===n.id))&&typeof n.nextFrameId!="number"){let o=t+1;for(;o<e.frames.length;){const c=e.frames[o];if(!e.frames.some(d=>Array.isArray(d.choices)&&d.choices.some(S=>S.nextFrameId===c.id)))return{action:"goto",nextIndex:o,historyFrameId:n.id};o++}return r||a?{action:"wait"}:{action:"finish",historyFrameId:n.id}}return t<e.frames.length-1?{action:"goto",nextIndex:t+1,historyFrameId:n.id}:r||a?{action:"wait"}:{action:"finish",historyFrameId:n.id}},j0=`
191
192---
193
194`;function Eu(e,t){var n;if(!t)return e;const r=((n=t.blackboard)==null?void 0:n.trim())||"",a=t.blackboardMode;return a==="clear"?r:a==="append"?r?e?`${e}${j0}${r}`:r:e:r||e}function V0(e){const{frames:t,currentFrameIndex:r,historyFrameIds:a=[],activeQuestionSteps:n=[]}=e,i=t[r];if(!i)return"";const o=new Map(t.map(d=>[d.id,d])),f=(a.length>0?[...a.map(d=>
194o.get(d)).filter(Boolean),i]:t.slice(0,r+1)).reduce((d,S)=>Eu(d,S),"");return n.reduce((d,S)=>Eu(d,S),f)}const $l=/!\[([^\]\r\n]*)\]\(\s*p2g-document-image:\/\/([^/\s)]+)\/(\d+)\s*\)/g;function G0(e){const t=new Map,r=Array.isArray(e.documentAssets)?e.documentAssets:[];for(const a of r){if(!a||typeof a.assetRunId!="string"||!/^[0-9a-fA-F-]+$/.test(a.assetRunId))continue;const n=Array.isArray(a.images)?a.images:[];for(const i of n)!i||typeof i.url!="string"||!i.url.trim()||typeof i.index!="number"||!Number.isSafeInteger(i.index)||i.index<0||t.set(`p2g-document-image://${a.assetRunId}/${i.index}`,i.url)}return t}function Y0(e,t){const r=[];return{text:e.replace($l,(n,i,o,c)=>{const f=t.get(`p2g-document-image://${o}/${c}`);return f?(r.push(`![${i}](${f})`),""):n}),moved:r}}function z0(e,t){return e.replace($l,(r,a,n,i)=>{const o=t.get(`p2g-document-image://${n}/${i}`);return o?`![${a}](${o})`:r})}function ki(e,t={}){if(!e||!Array.isArray(e.frames)||e.frames.length===0)return e;const r=G0(e);if(r.size===0)return e;let a=!1;const n=e.frames.map(i=>{const o=typeof i.text=="string"?i.text:"",c=typeof i.blackboard=="string"?i.blackboard:"",{text:f,moved:d}=Y0(o,r),S=z0(c,r);let b=f,w=S;if(d.length>0){b=f.replace(/\n{3,}/g,`
195
196`).trim();const v=d.join(`
197
198`);w=w.trim()?`${w.trim()}
199
200${v}`:v}return b===o&&w===c?i:(a=!0,{...i,text:b,...w?{blackboard:w}:{},...w&&!i.blackboardMode?{blackboardMode:"replace"}:{}})});return a?{...e,frames:n}:e}const ql=2,Gt=e=>{const t=Number(e);return Number.isFinite(t)?Math.max(0,t):void 0},Ql=e=>{if(!e||typeof e!="object")return null;const t=Gt(e.activeAnalysisJobs),r=Gt(e.queuedAnalysisJobs),a=t!==void 0||r!==void 0?(t??0)+(r??0):void 0,n=Gt(e.voiceQueueJobsAhead??e.jobsAhead)??a,i=Gt(e.pendingWorkItems),o=Gt(e.claimedWorkItems),c=i!==void 0||o!==void 0?(i??0)+(o??0):void 0,f=Gt(e.voiceQueueFramesAhead??e.framesAhead)??c,d=String(e.voiceQueueState??e.state??"").toLowerCase(),S=["queued","active","done","failed","cancelled","none"].includes(d),b=(n??0)>0||(f??0)>0,w=S?d:b?"queued":"none",v=String(e.ttsMode??e.voiceTtsMode??"").toLowerCase(),j=v==="pro"?"pro":v==="normal"?"normal":void 0,$=Gt(e.priority??e.voicePriority);return{queueAhead:f??n??0,etaMinutes:Gt(e.voiceQueueEtaMinutes??e.estimatedMinutes)??0,...j?{ttsMode:j}:{},...$!==void 0?{priority:$}:{},jobsAhead:n,framesAhead:f,state:w==="none"&&b?"queued":w,workerConcurrency:Gt(e.voiceWorkerConcurrency??e.workerConcurrency)}},kA=e=>{const t=Ql(e==null?void 0:e.analysisVoice);if(t)return t;if(!e||typeof e!="object")return null;const r=Gt(e.queueAhead)??0;return{queueAhead:r,etaMinutes:Gt(e.etaMinutes)??r*ql,state:r>0?"queued":"none"}},DA=e=>e?typeof e.jobsAhead=="number"&&e.jobsAhead>0?e.jobsAhead:Math.max(0,e.queueAhead||0):0;function W0(e,t){if(!(!e||typeof e.play!="function"))try{const r=e.play();r&&typeof r.catch=="function"&&r.catch(a=>{t==null||t(a)})}catch(r){t==null||t(r)}}const Es="p2g_utm_attribution",bu="p2g_anonymous_id",Tu="p2g_traffic_event_reported",$0=2160*60*60*1e3,q0={utm_source:"utmSource",utm_medium:"utmMedium",utm_campaign:"utmCampaign",utm_term:"utmTerm",utm_content:"utmContent",utm_id:"utmId",gclid:"gclid",fbclid:"fbclid",msclkid:"msclkid",ttclid:"ttclid",twclid:"twclid",li_fat_id:"liFatId",ref:"ref"},Di=(e,t=256)=>{const r=String(e||"").trim();if(r)return r.slice(0,t)};function Q0(e,t,r,a){const n=new URLSearchParams(e||""),i={};Object.entries(q0).forEach(([c,f])=>{const d=Di(n.get(c));d&&(i[f]=d)});const o=Di(r,2048);if(o)try{const c=new URL(o).origin;(!a||c!==a)&&(i.referrer=o)}catch{i.referrer=o}return Object.keys(i).length?(i.landingPage=Di(t,2048),i.capturedAt=new Date().toISOString(),i):null}function K0(){if(!(typeof window>"u"))try{if(yo())return;const t=`${window.location.pathname}${window.location.search}`,r=Q0(window.location.search,t,document.referrer,window.location.origin);if(!r)return;localStorage.setItem(Es,JSON.stringify(r))}catch{}}function X0(){if(!(typeof window>"u"))try{const e=localStorage.getItem(bu);if(e)return e;const t=typeof crypto<"u"&&"randomUUID"in crypto?crypto.randomUUID():`${Date.now().toString(36)}_${Math.random().toString(36).slice(2)}`;return localStorage.setItem(bu,t),t}catch{return}}function J0(){if(!(typeof window>"u"))try{if(sessionStorage.getItem(Tu))return;sessionStorage.setItem(Tu,"1");const e=yo(),t={eventType:"landing",anonymousId:X0(),path:`${window.location.pathname}${window.location.search}`,landingPage:(e==null?void 0:e.landingPage)||`${window.location.pathname}${window.location.search}`,referrer:(e==null?void 0:e.referrer)||document.referrer||void 0,utmAttribution:e||void 0}
200,r=JSON.stringify(t),a=localStorage.getItem("p2g_token");if(!a&&navigator.sendBeacon){const n=new Blob([r],{type:"application/json"});if(navigator.sendBeacon("/api/traffic/event",n))return}fetch("/api/traffic/event",{method:"POST",headers:{"Content-Type":"application/json",...a?{Authorization:`Bearer ${a}`}:{}},body:r,keepalive:!0}).catch(()=>{})}catch{}}function yo(){if(typeof window>"u")return null;try{const e=localStorage.getItem(Es);if(!e)return null;const t=JSON.parse(e),r=Date.parse((t==null?void 0:t.capturedAt)||"");return!Number.isFinite(r)||Date.now()-r>$0?(localStorage.removeItem(Es),null):t}catch{return localStorage.removeItem(Es),null}}function Z0(e){const t=yo();return t?{...e,utmAttribution:t}:e}const Su={unknownGeneration:{zh:"生成失败(未知错误)",en:"Generation failed due to an unknown error.",ja:"不明なエラーにより生成に失敗しました。",ru:"Генерация не удалась из-за неизвестной ошибки."},loginRequired:{zh:"请先注册/登录后ä
200½¿ç”¨è¯¥åŠŸèƒ½ã€‚",en:"Please register or log in to use this feature.",ja:"この機能を使うには登録またはログインが必要です。",ru:"Для использования этой функции нужно зарегистрироваться или войти."},dailyLimitExceeded:{zh:"今日使用次数已达上限,请明日再来或使用兑换码获取永久次数。",en:"Daily usage limit reached. Please come back tomorrow or use a redemption code for permanent quota.",ja:"本日の使用回数が上限に達しました。明日再度お試しいただくか、兌換コードで永久回数を取得してください。",ru:"Дневной лимит использования исчерпан. Вернитесь завтра или используйте код активации для постоянной квоты."},borrowedCharacterUnavailable:{zh:"借阅角色暂时不可用,请重试。",en:"The borrowed character is temporarily unavailable. Please try again.",ja:"借用キャラクターは一時的に利用できません。もう一度お試しください。",ru:"Заимствованный персонаж временно недоступен. Повторите попытку."},characterUnavailable:{zh:"角色暂时不可用,请重试。",en:"The character is temporarily unavailable. Please try again.",ja:"キャラクターは一時的に利用できません。もう一度お試しください。",ru:"Персонаж временно недоступен. Повторите попытку."},noExtractedText:{zh:"未能从文件中提取到文本内容。",en:"No text content could be extracted from this file.",ja:"このファイルからテキストを抽出できませんでした。",ru:"Не удалось извлечь текст из этого файла."},loadFailed:{zh:"加载失败,请稍后重试。",en:"Load failed. Please try again later.",ja:"読み込みに失敗しました。しばらくしてからもう一度お試しください。",ru:"Загрузка не удалась. Повторите попытку позже."},documentTooLarge:{zh:"文档内容过大,请精简文本后重试。",en:"The document is too large. Please shorten the text and try again.",ja:"ドキュメントが大きすぎます。テキストを短くしてからもう一度お試しください。",ru:"Документ слишком большой. Сократите текст и повторите попытку."},payloadTooLarge:{zh:"请求内容过大,请精简文档内容后重试。",en:"The request is too large. Please shorten the document and try again.",ja:"リクエスト内容が大きすぎます。ドキュメントを短くしてからもう一度お試しください。",ru:"Запрос слишком большой. Сократите документ и повторите попытку."},analysisMissingJob:{zh:"分析任务创建异常,请稍后重试。",en:"The analysis task was created incorrectly. Please try again later.",ja:"分析タスクの作成に問題がありました。しばらくしてからもう一度お試しください。",ru:"Задача анализа создана некорректно. Повторите попытку позже."},analysisTimeout:{zh:"分析任务超时,请稍后重试。",en:"The analysis task timed out. Please try again later.",ja:"分析タスクがタイムアウトしました。しばらくしてからもう一度お試しください。",ru:"Время ожидания задачи анализа истекло. Повторите попытку позже."},analysisCancelled:{zh:"分析任务已取消。",en:"The analysis job was cancelled.",ja:"分析タスクはキャンセルされました。",ru:"Задача анализа отменена."},videoParsingTimeout:{zh:"视频解析超过 8 分钟,任务已自动停止。请重试或改用完整的 BV 视频链接。",en:"Video parsing exceeded 8 minutes and was stopped automatically. Please retry or use the full BV video URL.",ja:"動画解析が8分を超えたため、自動的に停止しました。再試行するか、完全なBV動画URLを使用してください。",ru:"Обработка видео превысила 8 минут и была автоматически остановлена. Повторите попытку или используйте полную BV-ссылку."},videoAsrBlocked:{zh:"视频语音识别暂时无法完成,请更换视频或稍后重试。",en:"Video speech recognition is temporarily unavailable. Please use a different video or try again later.",ja:"動画の音声認識を一時的に完了できません。別の動画を使用するか、しばらくしてからもう一度お試しください。",ru:"Распознавание речи в видео временно недоступно. Используйте другое видео или повторите попытку позже."},pollingUnavailable:{zh:"任务状态连续查询失败,已停止等待。请检查网络后重试。",en:"Repeated task status checks failed, so waiting was stopped. Please check your network and retry.",ja:"タスク状態の確認に連続して失敗したため、待機を停止しました。ネットワークを確認して再試
200行してください。",ru:"Не удалось несколько раз проверить состояние задачи, поэтому ожидание остановлено. Проверьте сеть и повторите попытку."},analysisTitleMissing:{zh:"生成的讲解缺少有效标题,请重试。",en:"The generated explanation is missing a valid title. Please try again.",ja:"生成された解説に有効なタイトルがありません。もう一度お試しください。",ru:"В созданном объяснении отсутствует допустимое название. Повторите попытку."},analysisSectionFlowBlocked:{zh:"最终讲解结构生成不完整,请重新生成。",en:"The final explanation structure is incomplete. Please regenerate it.",ja:"最終的な解説構造が不完全です。もう一度生成してください。",ru:"Итоговая структура объяснения неполна. Создайте её заново."},analysisContentInvalid:{zh:"AI 生成的剧情未通过内容校验,请重试。",en:"The AI-generated story did not pass content validation. Please try again.",ja:"AIが生成したストーリーは内容の検証を通過しませんでした。もう一度お試しください。",ru:"Созданный ИИ сюжет не прошёл проверку содержимого. Повторите попытку."},handshakeFailed:{zh:"安全握手失败,请刷新页面后重试。",en:"Security handshake failed. Please refresh the page and try again.",ja:"セキュリティハンドシェイクに失敗しました。ページを更新してからもう一度お試しください。",ru:"Ошибка проверки безопасности. Обновите страницу и повторите попытку."}},ep={AUTH_REQUIRED:"loginRequired","Please register or log in to use this feature.":"loginRequired","请先注册/登录后使用该功能。":"loginRequired","请先登录后使用该功能。":"loginRequired",DAILY_LIMIT_EXCEEDED:"dailyLimitExceeded",BORROWED_CHARACTER_UNAVAILABLE:"borrowedCharacterUnavailable",CHARACTER_UNAVAILABLE:"characterUnavailable","No text content could be extracted from this file":"noExtractedText","Load failed":"loadFailed","文档内容过大(接近服务器 2MB 请求体限制)。请精简文本后重试。":"documentTooLarge","请精简文本后重试。":"documentTooLarge","请求内容过大,请精简文档内容后重试。":"payloadTooLarge","分析任务已创建但缺少 jobId。":"analysisMissingJob","分析任务超时,请稍后重试。":"analysisTimeout","分析任务已取消。":"analysisCancelled","Analysis job cancelled":"analysisCancelled",VIDEO_PARSING_TIMEOUT:"videoParsingTimeout",ANALYSIS_POLLING_UNAVAILABLE:"pollingUnavailable",ANALYSIS_TITLE_MISSING:"analysisTitleMissing",ANALYSIS_SECTION_FLOW_BLOCKED:"analysisSectionFlowBlocked","Security handshake failed":"handshakeFailed"},nn=(e,t)=>Su[e][t]||Su[e].zh,Mi=(e,t,r)=>e[t].replace("{{status}}",r),Ui=(e,t,r)=>{const n=(typeof e=="string"?e.trim():"").replace(/^Error:\s*/i,"").trim();if(!n)return r||nn("unknownGeneration",t);if(/^Invalid section flow(?:\s|:|$)/i.test(n))return nn("analysisContentInvalid",t);if(/the content you provided or machine outputted is blocked/i.test(n)||/\b(?:(?:STEP|QWEN)_)?ASR_[A-Z_]+\b/i.test(n))return nn("videoAsrBlocked",t);const i=ep[n];if(i)return nn(i,t);const o=n.match(/^轮询失败 \((\d{3})\)$/);if(o)return Mi({zh:"任务状态查询失败(HTTP {{status}}),请稍后重试。",en:"Task status check failed (HTTP {{status}}). Please try again later.",ja:"タスクの状態確認に失敗しました(HTTP {{status}})。しばらくしてからもう一度お試しください。",ru:"Проверка статуса задачи не удалась (HTTP {{status}}). Повторите попытку позже."},t,o[1]);const c=n.match(/^(?:请求失败|验证请求失败) \((\d{3})\)/);if(c)return Mi({zh:"请求失败(HTTP {{status}}),请稍后重试。",en:"Request failed (HTTP {{status}}). Please try again later.",ja:"リクエストに失敗しました(HTTP {{status}})。しばらくしてからもう一度お試しください。",ru:"Запрос не удался (HTTP {{status}}). Повторите попытку позже."},t,c[1]);const f=n.match(/^Upstream error \((\d{3})\)/);return f?Mi({zh:"上游 API 请求失败(HTTP {{status}}),请稍后重试或检查 API 设置。",en:"Upstream API request failed (HTTP {{status}}). Please try again later or check your API settings.",ja:"上流 API リクエストに失敗しました(HTTP {{status}})。しばらくしてから再試行するか、API 設定を確認してください。",ru:"Запрос к вышестоящему API не удался (HTTP {{status}}). Повторите позже или проверьте настройки API."},t,f[1]):(n.includes("Limit")||n.includes("429"))&&t!=="en"?nn("dailyLimitExceeded",t):n},tp=(e,t,r)=>t.includes(e)||r.includes(e)?e:t.includes("RUKA")?"RUKA":t[0]||"RUKA",rp=480*1e3;function ap({generation:e,videoUrl:t,abortController:r,timeoutMs:a=rp}){return t!=null&&t.trim()?new Promise((n,i)=>{let o=!1;const c=d=>{o||(o=!0,clearTimeout(f),d())},f=setTimeout(()=>{const d=Object.assign(new Error("VIDEO_PARSING_TIMEOUT"),{code:"VIDEO_PARSING_TIMEOUT"});c(()=>i(d)),r.abort(d)},Math.max(1,a));e.then(d=>c(()=>n(d)),d=>c(()=>i(d)))}):e}function np(e,t){if(e.textComplete===!0||e.phase==="done")return 100;if(typeof e.textProgressPct=="number"&&Number.isFinite(e.textProgressPct))return Math.max(t,Math.min(100,Math.round(e.textProgressPct)));if(e.phase==="video_transcription"){const i=Number(e.total||0),o=Number(e.current||0),c=i>0?Math.round(o/i*6):0;return Math.max(t,Math.min(8,2+c))}if(e.phase==="outlining")return Math.max(t,5);const r=Number(e.totalSections||0),a=Number(e.currentSection||0);if(r<=0||a<=0)return t;const n=Math.min(98,Math.max(5,Math.round(a/r*98)));return Math.max(t,n)}function MA({scriptPercent:e,isVoiceEnabled:t,loadingPhase:r,ttsProgress:a}
200){if(!t)return e;const n=.2,i=.8;return r==="voice"&&a&&a.total>0?n*100+a.current/a.total*(i*100):e/100*(n*100)}const fn=e=>e.replace(/\/+$/,"")||"/",Au=e=>{const t=fn(e);return t==="/saves"?D.SAVES:t==="/community"?D.COMMUNITY:t==="/arxiv"?D.ARXIV:t==="/membership"?D.MEMBERSHIP:t==="/profile"?D.PROFILE:t==="/study"?D.STUDY_DASHBOARD:t==="/study-room"?D.STUDY_ROOM:t==="/research"?D.RESEARCH_ROOM:t==="/support"?D.SUPPORT:t==="/"?D.MENU:null},sp=["narrator","旁白","ナレーター","рассказчик","от автора"],ip=["you","me","player","student","你","我","玩家","学生","あなた","私","プレイヤー","主人公","狗修金","вы","я","игрок","главный герой","студент"],op=["/assets/local/backgrounds/5.jpg","/assets/local/backgrounds/7.jpg","/assets/local/backgrounds/2.jpg","/assets/local/backgrounds/3.jpg","/assets/local/backgrounds/1.jpg","/assets/local/backgrounds/4.jpg","/assets/local/backgrounds/6.jpg","/assets/local/backgrounds/default-scene.png"],Iu=["/assets/local/audio/bgm5.mp3","/assets/local/audio/bgm6.mp3"],bs="/assets/local/audio/bgm2.mp3",Bi="/assets/local/audio/bgm-relaxing.mp3",cp={"https://assert.paper2gal.com/audio/bgm.mp3":bs,"https://assert.paper2gal.com/audio/bgm2.mp3":bs,"https://assert.paper2gal.com/audio/bgm3.mp3":"/assets/local/audio/bgm3.mp3","https://assert.paper2gal.com/audio/bgm4.mp3":"/assets/local/audio/bgm4.mp3","https://assert.paper2gal.com/audio/bgm-relaxing.mp3":Bi,"/assets/local/audio/bgm2.mp3":bs,"/assets/local/audio/bgm3.mp3":"/assets/local/audio/bgm3.mp3","/assets/local/audio/bgm4.mp3":"/assets/local/audio/bgm4.mp3","/assets/local/audio/bgm5.mp3":Bi,"/assets/local/audio/bgm-relaxing.mp3":Bi},up=e=>{const t=String(e||"").trim();return cp[t]||t||bs},lp="https://store.steampowered.com/favicon.ico",dp=2e3,UA=!1,fp={MENU:"/",SAVES:"/saves",COMMUNITY:"/community",ARXIV:"/arxiv",MEMBERSHIP:"/membership",PROFILE:"/profile",STUDY_DASHBOARD:"/study",STUDY_ROOM:"/study-room",RESEARCH_ROOM:"/research",SUPPORT:"/support"},mp=l.lazy(Ke(()=>Be(()=>import("./MainMenu-CJc99MS2.js"),__vite__mapDeps([9,4,10,11,6,12,13,14,15,7,3,2,5,16]),import.meta.url),"MainMenu")),Kl=Ke(()=>Be(()=>import("./Character-B0Yj0W_Y.js"),__vite__mapDeps([17,4,18,12,6,7,3,2,5]),import.meta.url),"Character"),Xl=Ke(()=>Be(()=>import("./DialogueBox-CNtZIlM5.js"),__vite__mapDeps([19,4,20,21,13,18,6,7,3,2,5]),import.meta.url),"DialogueBox"),Jl=Ke(()=>Be(()=>import("./BlackboardMarkdown-Cizre-1w.js"),__vite__mapDeps([22,4,2,3,5]),import.meta.url),"BlackboardMarkdown"),yu=l.lazy(Kl),hp=l.lazy(Xl),pp=l.lazy(Ke(()=>Be(()=>import("./LoadingGame-BAHt47Rf.js"),__vite__mapDeps([23,4,15,6,7,3,2,5]),import.meta.url),"LoadingGame")),gp=l.lazy(Ke(()=>Be(()=>import("./SettingsModal-5SZs2RBK.js"),__vite__mapDeps([24,4,6,7,3,2,5]),import.meta.url),"SettingsModal")),Ep=l.lazy(Ke(()=>Be(()=>import("./LogModal-C3gu7eDy.js"),__vite__mapDeps([25,4,21,26,2,3,5,15,6,7]),import.meta.url),"LogModal")),bp=l.lazy(Ke(()=>Be(()=>import("./EndingScreen-C5GepLUm.js"),__vite__mapDeps([27,4,28,15,6,7,3,2,5]),import.meta.url),"EndingScreen")),Tp=l.lazy(Ke(()=>Be(()=>import("./AnnouncementModal-BqVbgv6o.js"),__vite__mapDeps([29,4,6,7,3,2,5]),import.meta.url),"AnnouncementModal")),_u=l.lazy(Ke(()=>Be(()=>import("./AnnouncementWidget-BEJgy4Af.js"),__vite__mapDeps([30,4,6]),import.meta.url),"AnnouncementWidget")),Sp=l.lazy(Ke(()=>Be(()=>import("./MobileApkPromptModal-BaOGB0mh.js"),__vite__mapDeps([31,4,6,7,3,2,5]),import.meta.url),"MobileApkPromptModal")),Ap=l.lazy(Ke(()=>Be(()=>import("./BackgroundSelector-BYyd2LfJ.js"),__vite__mapDeps([32,4,15,6,7,3,2,5]),import.meta.url),"BackgroundSelector")),Ip=l.lazy(Ke(()=>Be(()=>import("./Login-e9WFT3CV.js"),__vite__mapDeps([33,4,6,7,3,2,5]),import.meta.url),"Login")),yp=l.lazy(Ke(()=>Be(()=>import("./AdminDashboard-HIANxf-i.js"),__vite__mapDeps([34,4,6,35,7,3,2,5]),import.meta.url),"AdminDashboard")),_p=l.lazy(Ke(()=>Be(()=>import("./CommunityPage-B9QgmaFk.js"),__vite__mapDeps([36,4,11,10,6,12,7,3,2,5]),import.meta.url),"CommunityPage")),Cp=l.lazy(Ke(()=>Be(()=>import("./SaveManager-Wouqmi4H.js"),__vite__mapDeps([37,4,6,7,3,2,5]),import.meta.url),"SaveManager")),wp=l.lazy(Ke(()=>Be(()=>import("./ArxivPage-GYK3MRf5.js"),__vite__mapDeps([38,4,6,7,3,2,5]),import.meta.url),"ArxivPage")),Rp=l.lazy(Ke(()=>Be(()=>import("./MembershipPage-BQA3GMQU.js"),__vite__mapDeps([39,4,6,7,3,2,5]),import.meta.url),"MembershipPage")),Np=l.lazy(Ke(()=>Be(()=>import("./ProfilePage--eIe_FSB.js"),__vite__mapDeps([40,4,10,6,14,15,7,3,2,5]),import.meta.url),"ProfilePage")),Pp=l.lazy(Ke(()=>Be(()=>import("./StudyDashboardPage-CrJYba4q.js"),__vite__mapDeps([41,4,10,14,15,6,7,3,2,5]),import.meta.url),"StudyDashboardPage")),xp=l.lazy(Ke(()=>Be(()=>import("./StudyRoomPage-hZ6UWwR6.js"),__vite__mapDeps([42,4,6,7,3,2,5]),import.meta.url),"StudyRoomPage")),Op=l.lazy(Ke(()=>Be(()=>import("./PaperResearchRoom-BERhtVXp.js"),__vite__mapDeps([43,4,28,22,2,3,5,26,6,7]),import.meta.url),"PaperResearchRoom")),vp=l.lazy(Ke(()=>Be(()=>import("./SupportPage-BnePHPp2.js"),__vite__mapDeps([44,4,6,7,3,2,5]),import.meta.url),"SupportPage")),Lp=l.lazy(Ke(()=>Be(()=>import("./MarkdownPage-DghJi6z7.js"),__vite__mapDeps([45,4,6,3]),import.meta.url),"MarkdownPage")),kp=l.lazy(Jl),Fi=async(e={})=>{const t=[Kl(),Xl()];e.blackboard&&t.push(Jl()),await Promise.all(t).then(()=>{},()=>{})},kt=()=>p.jsx("div",{className:"flex min-h-[200px] items-center justify-center text-slate-400",children:"Loading..."});/*! Capacitor: https://capacitorjs.com/ - MIT License */var Ca;
200(function(e){e.Unimplemented="UNIMPLEMENTED",e.Unavailable="UNAVAILABLE"})(Ca||(Ca={}));class Hi extends Error{constructor(t,r,a){super(t),this.message=t,this.code=r,this.data=a}}const Dp=e=>{var t,r;return e!=null&&e.androidBridge?"android":!((r=(t=e==null?void 0:e.webkit)===null||t===void 0?void 0:t.messageHandlers)===null||r===void 0)&&r.bridge?"ios":"web"},Mp=e=>{const t=e.CapacitorCustomPlatform||null,r=e.Capacitor||{},a=r.Plugins=r.Plugins||{},n=()=>t!==null?t.name:Dp(e),i=()=>n()!=="web",o=b=>{const w=d.get(b);return!!(w!=null&&w.platforms.has(n())||c(b))},c=b=>{var w;return(w=r.PluginHeaders)===null||w===void 0?void 0:w.find(v=>v.name===b)},f=b=>e.console.error(b),d=new Map,S=(b,w={})=>{const v=d.get(b);if(v)return console.warn(`Capacitor plugin "${b}" already registered. Cannot register plugins twice.`),v.proxy;const j=n(),$=c(b);let V;const Y=async()=>(!V&&j in w?V=typeof w[j]=="function"?V=await w[j]():V=w[j]:t!==null&&!V&&"web"in w&&(V=typeof w.web=="function"?V=await w.web():V=w.web),V),q=(ne,Pe)=>{var Ee,ye;if($){const _e=$==null?void 0:$.methods.find(be=>Pe===be.name);if(_e)return _e.rtype==="promise"?be=>r.nativePromise(b,Pe.toString(),be):(be,se)=>r.nativeCallback(b,Pe.toString(),be,se);if(ne)return(Ee=ne[Pe])===null||Ee===void 0?void 0:Ee.bind(ne)}else{if(ne)return(ye=ne[Pe])===null||ye===void 0?void 0:ye.bind(ne);throw new Hi(`"${b}" plugin is not implemented on ${j}`,Ca.Unimplemented)}},K=ne=>{let Pe;const Ee=(...ye)=>{const _e=Y().then(be=>{const se=q(be,ne);if(se){const me=se(...ye);return Pe=me==null?void 0:me.remove,me}else throw new Hi(`"${b}.${ne}()" is not implemented on ${j}`,Ca.Unimplemented)});return ne==="addListener"&&(_e.remove=async()=>Pe()),_e};return Ee.toString=()=>`${ne.toString()}() { [capacitor code] }`,Object.defineProperty(Ee,"name",{value:ne,writable:!1,configurable:!1}),Ee},Se=K("addListener"),ee=K("removeListener"),Z=(ne,Pe)=>{const Ee=Se({eventName:ne},Pe),ye=async()=>{const be=await Ee;ee({eventName:ne,callbackId:be},Pe)},_e=new Promise(be=>Ee.then(()=>be({remove:ye})));return _e.remove=async()=>{console.warn("Using addListener() without 'await' is deprecated."),await ye()},_e},fe=new Proxy({},{get(ne,Pe){switch(Pe){case"$$typeof":return;case"toJSON":return()=>({});case"addListener":return $?Z:Se;case"removeListener":return ee;default:return K(Pe)}}});return a[b]=fe,d.set(b,{name:b,proxy:fe,platforms:new Set([...Object.keys(w),...$?[j]:[]])}),fe};return r.convertFileSrc||(r.convertFileSrc=b=>b),r.getPlatform=n,r.handleError=f,r.isNativePlatform=i,r.isPluginAvailable=o,r.registerPlugin=S,r.Exception=Hi,r.DEBUG=!!r.DEBUG,r.isLoggingEnabled=!!r.isLoggingEnabled,r},Up=e=>e.Capacitor=Mp(e),_t=Up(typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:typeof global<"u"?global:{}),nr=_t.registerPlugin;class _o{constructor(){this.listeners={},this.retainedEventArguments={},this.windowListeners={}}addListener(t,r){let a=!1;this.listeners[t]||(this.listeners[t]=[],a=!0),this.listeners[t].push(r);const i=this.windowListeners[t];i&&!i.registered&&this.addWindowListener(i),a&&this.sendRetainedArgumentsForEvent(t);const o=async()=>this.removeListener(t,r);return Promise.resolve({remove:o})}async removeAllListeners(){this.listeners={};for(const t in this.windowListeners)this.removeWindowListener(this.windowListeners[t]);this.windowListeners={}}notifyListeners(t,r,a){const n=this.listeners[t];if(!n){if(a){let i=this.retainedEventArguments[t];i||(i=[]),i.push(r),this.retainedEventArguments[t]=i}return}n.forEach(i=>i(r))}hasListeners(t){var r;return!!(!((r=this.listeners[t])===null||r===void 0)&&r.length)}registerWindowListener(t,r){this.windowListeners[r]={registered:!1,windowEventName:t,pluginEventName:r,handler:a=>{this.notifyListeners(r,a)}}}unimplemented(t="not implemented"){return new _t.Exception(t,Ca.Unimplemented)}unavailable(t="not available"){return new _t.Exception(t,Ca.Unavailable)}async removeListener(t,r){const a=this.listeners[t];if(!a)return;const n=a.indexOf(r);this.listeners[t].splice(n,1),this.listeners[t].length||this.removeWindowListener(this.windowListeners[t])}
200addWindowListener(t){window.addEventListener(t.windowEventName,t.handler),t.registered=!0}removeWindowListener(t){t&&(window.removeEventListener(t.windowEventName,t.handler),t.registered=!1)}sendRetainedArgumentsForEvent(t){const r=this.retainedEventArguments[t];r&&(delete this.retainedEventArguments[t],r.forEach(a=>{this.notifyListeners(t,a)}))}}const Cu=e=>encodeURIComponent(e).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape),wu=e=>e.replace(/(%[\dA-F]{2})+/gi,decodeURIComponent);class Bp extends _o{async getCookies(){const t=document.cookie,r={};return t.split(";").forEach(a=>{if(a.length<=0)return;let[n,i]=a.replace(/=/,"CAP_COOKIE").split("CAP_COOKIE");n=wu(n).trim(),i=wu(i).trim(),r[n]=i}),r}async setCookie(t){try{const r=Cu(t.key),a=Cu(t.value),n=t.expires?`; expires=${t.expires.replace("expires=","")}`:"",i=(t.path||"/").replace("path=",""),o=t.url!=null&&t.url.length>0?`domain=${t.url}`:"";document.cookie=`${r}=${a||""}${n}; path=${i}; ${o};`}catch(r){return Promise.reject(r)}}async deleteCookie(t){try{document.cookie=`${t.key}=; Max-Age=0`}catch(r){return Promise.reject(r)}}async clearCookies(){try{const t=document.cookie.split(";")||[];for(const r of t)document.cookie=r.replace(/^ +/,"").replace(/=.*/,`=;expires=${new Date().toUTCString()};path=/`)}catch(t){return Promise.reject(t)}}async clearAllCookies(){try{await this.clearCookies()}catch(t){return Promise.reject(t)}}}nr("CapacitorCookies",{web:()=>new Bp});const Fp=async e=>new Promise((t,r)=>{const a=new FileReader;a.onload=()=>{const n=a.result;t(n.indexOf(",")>=0?n.split(",")[1]:n)},a.onerror=n=>r(n),a.readAsDataURL(e)}),Hp=(e={})=>{const t=Object.keys(e);return Object.keys(e).map(n=>n.toLocaleLowerCase()).reduce((n,i,o)=>(n[i]=e[t[o]],n),{})},jp=(e,t=!0)=>e?Object.entries(e).reduce((a,n)=>{const[i,o]=n;let c,f;return Array.isArray(o)?(f="",o.forEach(d=>{c=t?encodeURIComponent(d):d,f+=`${i}=${c}&`}),f.slice(0,-1)):(c=t?encodeURIComponent(o):o,f=`${i}=${c}`),`${a}&${f}`},"").substr(1):null,Vp=(e,t={})=>{const r=Object.assign({method:e.method||"GET",headers:e.headers},t),n=Hp(e.headers)["content-type"]||"";if(typeof e.data=="string")r.body=e.data;else if(n.includes("application/x-www-form-urlencoded")){const i=new URLSearchParams;for(const[o,c]of Object.entries(e.data||{}))i.set(o,c);r.body=i.toString()}else if(n.includes("multipart/form-data")||e.data instanceof FormData){const i=new FormData;if(e.data instanceof FormData)e.data.forEach((c,f)=>{i.append(f,c)});else for(const c of Object.keys(e.data))i.append(c,e.data[c]);r.body=i;const o=new Headers(r.headers);o.delete("content-type"),r.headers=o}else(n.includes("application/json")||typeof e.data=="object")&&(r.body=JSON.stringify(e.data));return r};class Gp extends _o{async request(t){const r=Vp(t,t.webFetchExtra),a=jp(t.params,t.shouldEncodeUrlParams),n=a?`${t.url}?${a}`:t.url,i=await fetch(n,r),o=i.headers.get("content-type")||"";let{responseType:c="text"}=i.ok?t:{};o.includes("application/json")&&(c="json");let f,d;switch(c){case"arraybuffer":case"blob":d=await i.blob(),f=await Fp(d);break;case"json":f=await i.json();break;case"document":case"text":default:f=await i.text()}const S={};return i.headers.forEach((b,w)=>{S[w]=b}),{data:f,headers:S,status:i.status,url:i.url}}async get(t){return this.request(Object.assign(Object.assign({},t),{method:"GET"}))}async post(t){return this.request(Object.assign(Object.assign({},t),{method:"POST"}))}async put(t){return this.request(Object.assign(Object.assign({},t),{method:"PUT"}))}async patch(t){return this.request(Object.assign(Object.assign({},t),{method:"PATCH"}))}async delete(t){return this.request(Object.assign(Object.assign({},t),{method:"DELETE"}))}}nr("CapacitorHttp",{web:()=>new Gp});var Ru;(function(e){e.Dark="DARK",e.Light="LIGHT",e.Default="DEFAULT"})(Ru||(Ru={}));var Nu;(function(e){e.StatusBar="StatusBar",e.NavigationBar="NavigationBar"})(Nu||(Nu={}));class Yp extends _o{async setStyle(){this.unavailable("not available for web")}async setAnimation(){this.unavailable("not available for web")}async show(){this.unavailable("not available for web")}async hide(){this.unavailable("not available for web")}}nr("SystemBars",{web:()=>new Yp});const zp=nr("App",{web:()=>Be(()=>import("./web-BjRLPPkm.js"),__vite__mapDeps([46,4,6,7,3,2,5]),import.meta.url).then(e=>new e.AppWeb)}),Wp=nr("PaymentChannel"),Pu=nr("DirectPayment"),Jr=nr("GooglePlayBilling"),ea=nr("StoreKitBilling");let Zl="",ds=null;const ji=new Map,$p=()=>{try{if(typeof globalThis.localStorage<"u")return globalThis.localStorage.getItem("p2g_token")||""}catch{}return Zl};async function to(e){const t=$p();if(!t||!e.transactionId)return null;const r=ji.get(e.transactionId);if(r)return r;const a=(async()=>{const n=await st("/api/mobile-payments/apple/reconcile",{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({transactionId:e.transactionId,productId:e.productId})}),i=await n.json().catch(()=>({}));if(!n.ok||(i==null?void 0:i.recorded)!==!0||(i==null?void 0:i.finalized)!==!0)throw new Error((i==null?void 0:i.error)||"App Store verification failed");return await ea.finish({transactionId:e.transactionId}),i.membership})().finally(()=>{ji.delete(e.transactionId)});return ji.set(e.transactionId,a),a}async function Co(e){if(e.token&&(Zl=e.token),!_t.isNativePlatform()||_t.getPlatform()!=="ios")return;ds||(ds=ea.addListener("transactionUpdated",a=>{to(a).catch(()=>{})}).then(()=>{}).catch(a=>{throw ds=null,a})),await ds;const t=await ea.getUnfinished();return(await Promise.allSettled((t.transactions||[]).map(to))).reduce((a,n)=>{var i;return n.status==="fulfilled"&&((i=n.value)!=null&&i.active)?n.value:a},null)}function BA(){return _t.isNativePlatform()?_t.getPlatform()==="ios"?"apple":"google":"web"}async function ed(){if(!_t.isNativePlatform())return"web";if(_t.getPlatform()==="ios")return"apple";if(_t.getPlatform()!=="android")return"web";try{return(await Wp.getChannel()).channel==="google"?"google":"direct"}catch{return"google"}}const qp=ed;async function FA(){var n,i,o,c;const e=await ed();if(e==="web")return{channel:e};const t=await st("/api/mobile-payments/catalog"),r=await t.json().catch(()=>({}));if(!t.ok)throw new Error((r==null?void 0:r.error)||"Unable to load mobile billing");if(e==="direct")return{channel:e,direct:r.direct};if(e==="apple"){const f={...((n=r.apple)==null?void 0:n.plans)||{}},d=Object.values(f).map(S=>
200S==null?void 0:S.productId).filter(Boolean);if(d.length)try{const S=await ea.getProducts({productIds:d});for(const b of S.products||[]){const w=Object.values(f).find(v=>(v==null?void 0:v.productId)===b.productId);w&&(w.price=b.price)}}catch{}return Co({}).catch(()=>{}),{channel:e,apple:{configured:!!((i=r.apple)!=null&&i.configured),plans:f}}}const a={...((o=r.google)==null?void 0:o.plans)||{}};return await Promise.all(Object.values(a).map(async f=>{if(f!=null&&f.productId)try{const d=await Jr.getProduct({productId:f.productId,productType:f.productType});f.price=d.price}catch{}})),{channel:e,google:{configured:!!((c=r.google)!=null&&c.configured),plans:a}}}const Qp=e=>new Promise(t=>setTimeout(t,e));async function Kp(e,t){var r,a,n;for(let i=0;i<120;i+=1){const o=await st(`/api/mobile-payments/orders/${encodeURIComponent(e)}`,{headers:{Authorization:`Bearer ${t}`}}),c=await o.json().catch(()=>({}));if(o.status===401)throw new Error("Login required");if(o.ok&&((r=c==null?void 0:c.order)==null?void 0:r.status)==="paid"&&((a=c==null?void 0:c.membership)!=null&&a.active))return c.membership;if(o.ok&&["failed","cancelled","expired"].includes((n=c==null?void 0:c.order)==null?void 0:n.status))throw new Error(`Payment ${c.order.status}`);await Qp(2e3)}throw new Error("Payment confirmation timed out. Reopen the membership page to refresh the order.")}async function Xp(e){const t=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(e));return Array.from(new Uint8Array(t)).map(r=>r.toString(16).padStart(2,"0")).join("")}async function HA(e){var i,o,c,f,d,S,b,w;if(e.channel==="direct"){const v=e.directProvider||"alipay",j=await st("/api/mobile-payments/direct/order",{method:"POST",headers:{Authorization:`Bearer ${e.token}`,"Content-Type":"application/json"},body:JSON.stringify({provider:v,plan:e.plan})}),$=await j.json().catch(()=>({}));if(!j.ok)throw new Error(($==null?void 0:$.error)||"Unable to create payment order");if(v==="alipay"){const V=await Pu.payAlipay({orderString:((i=$.payload)==null?void 0:i.orderString)||""});if(V.resultStatus&&!["9000","8000"].includes(V.resultStatus))throw new Error(V.memo||"Alipay payment was not completed")}else if(!(await Pu.payWechat($.payload)).launched)throw new Error("Unable to open WeChat Pay");return Kp($.orderId,e.token)}if(e.channel==="apple"){const v=(c=(o=e.catalog.apple)==null?void 0:o.plans)==null?void 0:c[e.plan];if(!(v!=null&&v.productId))throw new Error("App Store product is not configured");const j=await Co({token:e.token,plans:((f=e.catalog.apple)==null?void 0:f.plans)||{}});if(j!=null&&j.active)return j;const $=await st("/api/mobile-payments/apple/account-token",{headers:{Authorization:`Bearer ${e.token}`}}),V=await $.json().catch(()=>({}));if(!$.ok||!(V!=null&&V.appAccountToken))throw new Error((V==null?void 0:V.error)||"Unable to prepare App Store purchase");const Y=await ea.purchase({productId:v.productId,appAccountToken:V.appAccountToken}),q=await st("/api/mobile-payments/apple/verify",{method:"POST",headers:{Authorization:`Bearer ${e.token}`,"Content-Type":"application/json"},body:JSON.stringify({plan:e.plan,transactionId:Y.transactionId})}),K=await q.json().catch(()=>({}));if(!q.ok||!((d=K==null?void 0:K.membership)!=null&&d.active))throw new Error((K==null?void 0:K.error)||"App Store verification failed");return await ea.finish({transactionId:Y.transactionId}),K.membership}const t=(b=(S=e.catalog.google)==null?void 0:S.plans)==null?void 0:b[e.plan];if(!(t!=null&&t.productId))throw new Error("Google Play product is not configured");const r=await Jr.purchase({productId:t.productId,productType:t.productType,obfuscatedAccountId:await Xp(e.userId)});if(!r.purchaseToken||r.purchaseState!==1)throw new Error("Google Play purchase is pending");const a=await st("/api/mobile-payments/google/verify",{method:"POST",headers:{Authorization:`Bearer ${e.token}`,"Content-Type":"application/json"},body:JSON.stringify({plan:e.plan,purchaseToken:r.purchaseToken})}),n=await a.json().catch(()=>({}));if(!a.ok||!((w=n==null?void 0:n.membership)!=null&&w.active))throw new Error((n==null?void 0:n.error)||"Google Play verification failed");return n.finalized||(t.productType==="inapp"?await Jr.consume({purchaseToken:r.purchaseToken}).catch(()=>{}):await Jr.acknowledge({purchaseToken:r.purchaseToken}).catch(()=>{})),n.membership}async function jA(e){var a;let t=await Co({token:e.token,plans:((a=e.catalog.apple)==null?void 0:a.plans)||{}});
200const r=await ea.restore();for(const n of r.transactions||[])t=await to(n)||t;if(!(t!=null&&t.active))throw new Error("No active App Store purchase was found for this account");return t}async function VA(e){var n;const t=await Jr.restore(),r=((n=e.catalog.google)==null?void 0:n.plans)||{};let a=null;for(const i of t.purchases||[]){if(!i.purchaseToken||i.purchaseState!==1)continue;const o=Object.entries(r).find(([,S])=>{var b;return(S==null?void 0:S.productId)&&((b=i.products)==null?void 0:b.includes(S.productId))});if(!o)continue;const[c]=o,f=await st("/api/mobile-payments/google/verify",{method:"POST",headers:{Authorization:`Bearer ${e.token}`,"Content-Type":"application/json"},body:JSON.stringify({plan:c,purchaseToken:i.purchaseToken})}),d=await f.json().catch(()=>({}));if(!f.ok)throw new Error((d==null?void 0:d.error)||"Google Play restore verification failed");if(a=d.membership||a,!d.finalized){const S=r[c];(S==null?void 0:S.productType)==="inapp"?await Jr.consume({purchaseToken:i.purchaseToken}).catch(()=>{}):await Jr.acknowledge({purchaseToken:i.purchaseToken}).catch(()=>{})}}if(!(a!=null&&a.active))throw new Error("No active Google Play purchase was found for this account");return a}const xu=e=>String(e||"").split(/[.+-]/).map(t=>Number.parseInt(t,10)).map(t=>Number.isFinite(t)?t:0);function Jp(e,t){const r=xu(e),a=xu(t),n=Math.max(r.length,a.length);for(let i=0;i<n;i+=1){const o=(r[i]||0)-(a[i]||0);if(o!==0)return o>0?1:-1}return 0}function Ou(e,t,r,a){const n=Number.parseInt(t,10);return Number.isFinite(n)&&Number.isFinite(a)?n===a?0:n>a?1:-1:Jp(e,r)}function Zp(e,t){try{const r=new URL(t);return e==="direct"?r.protocol==="https:":e==="google"?r.protocol==="market:"||r.protocol==="https:"&&r.hostname.toLowerCase()==="play.google.com":r.protocol==="itms-apps:"||r.protocol==="https:"&&r.hostname.toLowerCase()==="apps.apple.com"}catch{return!1}}async function eg(){if(!_t.isNativePlatform())return null;const e=_t.getPlatform();if(e!=="android"&&e!=="ios")return null;try{const t=e==="ios"?"app_store":await qp()==="direct"?"direct":"google",[r,a]=await Promise.all([zp.getInfo(),st(`/api/app-version?platform=${e}&channel=${t}`)]);if(!a.ok)return null;const n=await a.json();return!(n!=null&&n.updateUrl)||!n.latestVersion||n.platform!==e||n.channel!==t||!Zp(t,n.updateUrl)||Ou(r.version,r.build,n.latestVersion,Number(n.latestBuild))>=0?null:{...n,installedVersion:r.version,installedBuild:r.build,forced:Ou(r.version,r.build,n.minimumVersion,Number(n.minimumBuild))<0}}catch(t){return console.warn("[AppUpdate] Update check failed:",t),null}}function tg(e){window.open(e,"_blank","noopener,noreferrer")}const rg={zh:{title:"发现新版本",required:"需要更新后才能继续使用",available:"新版本已经准备好",installed:"当前版本",latest:"最新版本",notes:"更新内容",noNotes:"性能优化与体验改进。",later:"稍后再说",update:"立即更新"},en:{title:"Update available",required:"Update required to continue",available:"A new version is ready",installed:"Installed",latest:"Latest",notes:"What's new",noNotes:"Performance and experience improvements.",later:"Later",update:"Update now"},ja:{title:"新しいバージョン",required:"続行するには更新が必要です",available:"新しいバージョンを利用できます",installed:"現在",latest:"最新",notes:"更新内容",noNotes:"パフォーマンスと操作性を改善しました。",later:"あとで",update:"今すぐ更新"},ru:{title:"Доступно обновление",required:"Для продолжения требуется обновление",available:"Новая версия готова",installed:"Установлено",latest:"Последняя",notes:"Что нового",noNotes:"Улучшена производительность и удобство использования.",later:"Позже",update:"Обновить"}},ag=({update:e,language:t,onClose:r})=>{var o,c,f;const a=Io(),n=rg[t],i=((o=e.releaseNotes)==null?void 0:o[t])||((c=e.releaseNotes)==null?void 0:c.en)||((f=e.releaseNotes)==null?void 0:f.zh)||n.noNotes;return l.useEffect(()=>{if(!e.forced)return;const d=S=>{S.key==="Escape"&&S.preventDefault()};return window.addEventListener("keydown",d,!0),()=>window.removeEventListener("keydown",d,!0)}
200,[e.forced]),p.jsx("div",{className:`fixed inset-0 z-[260] flex items-center justify-center bg-slate-950/70 ${a?"p-3":"p-5"}`,onClick:e.forced?void 0:r,role:"dialog","aria-modal":"true","aria-labelledby":"app-update-title",children:p.jsxs("div",{className:`flex w-full flex-col overflow-hidden rounded-lg border-2 bg-[#fffafa] shadow-2xl ${a?"max-w-[600px] max-h-[88vh]":"max-w-md max-h-[86vh]"}`,onClick:d=>d.stopPropagation(),children:[p.jsxs("header",{className:`flex items-center gap-3 border-b-2 px-5 ${a?"py-3":"py-4"} ${e.forced?"border-rose-200 bg-rose-50":"border-sky-200 bg-sky-50"}`,children:[p.jsx("div",{className:`flex h-10 w-10 shrink-0 items-center justify-center rounded-full text-white ${e.forced?"bg-rose-500":"bg-sky-500"}`,children:e.forced?p.jsx(wl,{size:21}):p.jsx(lh,{size:21})}),p.jsxs("div",{className:"min-w-0",children:[p.jsx("h2",{id:"app-update-title",className:"text-lg font-black text-slate-900",children:n.title}),p.jsx("p",{className:"text-sm font-semibold text-slate-600",children:e.forced?n.required:n.available})]})]}),p.jsxs("div",{className:`min-h-0 flex-1 overflow-y-auto ${a?"px-5 py-3":"p-5"}`,children:[p.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[p.jsxs("div",{className:"rounded-md border border-slate-200 bg-white px-3 py-2",children:[p.jsx("div",{className:"text-xs font-bold text-slate-400",children:n.installed}),p.jsxs("div",{className:"mt-0.5 font-black text-slate-700",children:[e.installedVersion," (",e.installedBuild,")"]})]}),p.jsxs("div",{className:"rounded-md border border-sky-200 bg-sky-50 px-3 py-2",children:[p.jsx("div",{className:"text-xs font-bold text-sky-500",children:n.latest}),p.jsxs("div",{className:"mt-0.5 font-black text-sky-700",children:[e.latestVersion," (",e.latestBuild,")"]})]})]}),p.jsxs("section",{className:"mt-4",children:[p.jsxs("h3",{className:"mb-1.5 flex items-center gap-2 text-sm font-black text-slate-800",children:[p.jsx(dh,{size:15,className:"text-sky-500"}),n.notes]}),p.jsx("p",{className:"whitespace-pre-wrap text-sm leading-6 text-slate-600",children:i})]})]}),p.jsxs("footer",{className:`flex justify-end gap-3 border-t border-slate-200 bg-white px-5 ${a?"py-3":"py-4"}`,children:[!e.forced&&p.jsx("button",{type:"button",onClick:r,className:"rounded-md border border-slate-300 px-5 py-2.5 text-sm font-bold text-slate-600 hover:bg-slate-50",children:n.later}),p.jsxs("button",{type:"button",onClick:()=>tg(e.updateUrl),className:"inline-flex items-center gap-2 rounded-md bg-sky-600 px-5 py-2.5 text-sm font-black text-white hover:bg-sky-700",children:[p.jsx(fh,{size:17}),n.update]})]})]})})};let vu=!1;const td=async()=>{const e=await Be(()=>import("./pdfjs-ji3DqnKJ.js").then(t=>t.a),[],import.meta.url);return vu||(e.GlobalWorkerOptions.workerSrc=Dh,vu=!0),e},Lu=e=>e.filter(t=>t.type==="application/pdf"||/\.pdf$/i.test(t.name)),ng=(e,t)=>Math.min(Math.max(1,Math.floor(e)||1),Math.max(1,t)),ku=(e,t)=>{const r=Math.max(360,t*.25),a=Math.max(r,Math.min(t*.72,t-520));return Math.round(Math.min(a,Math.max(r,e)))},sg=(e,t)=>Math.round(Math.min(3,Math.max(.5,e+(t<0?.1:t>0?-.1:0)))*100)/100,ig=(e,t)=>{var a;let r=((a=e[0])==null?void 0:a.page)||1;for(const n of e){if(n.top>t)break;r=n.page}return r},og=(e,t)=>{const r=t.trim().toLocaleLowerCase();if(!r)return[];const a=[];let n="";for(const c of e)a.length&&(n+=" "),a.push(n.length),n+=c;const i=n.toLocaleLowerCase(),o=[];for(let c=i.indexOf(r);c!==-1;c=i.indexOf(r,c+r.length)){const f=c+r.length;let d=a.length-1,S=a.length-1;for(;d>=0&&a[d]>c;)d--;for(;S>=0&&a[S]>=f;)S--;d<0||S<0||o.push({startItem:d,startOffset:Math.min(c-a[d],e[d].length),endItem:S,endOffset:Math.min(f-a[S],e[S].length)})}return o},cg=(e,t,r)=>t?(e+r+t)%t:-1,ug=[],Du={zh:{title:"原文对照",choose:"重新选择本地 PDF",change:"更换 PDF",empty:"选择原始 PDF,即可边玩边对照阅读。文件仅在本机打开。",search:"搜索原文内容",noMatch:"无结果",searching:"查找中…",previous:"上一个匹配",next:"下一个匹配",loading:"正在加载 PDF…",error:"无法打开这个 PDF,请重新选择文件。",close:"关闭原文阅读器",page:"页",fit:"适应宽度",zoomIn:"放大",zoomOut:"缩小",resize:"拖动调整游戏与 PDF 的宽度",scroll:"滚动连续阅读"},en:{title:"Source PDF",choose:"Choose local PDF",change:"Change PDF",empty:"Choose the original PDF to read alongside the story. The file stays on your device.",search:"Search the PDF",noMatch:"No results",searching:"Searching…",previous:"Previous match",next:"Next match",loading:"Loading PDF…",error:"Could not open this PDF. Please choose it again.",close:"Close source reader",page:"Page",f
200it:"Fit width",zoomIn:"Zoom in",zoomOut:"Zoom out",resize:"Drag to resize the game and PDF",scroll:"Scroll to read continuously"},ja:{title:"原文を参照",choose:"ローカル PDF を選択",change:"PDF を変更",empty:"原文の PDF を選択して、物語と並べて読めます。ファイルはアップロードされません。",search:"本文を検索",noMatch:"一致なし",searching:"検索中…",previous:"前の一致",next:"次の一致",loading:"PDF を読み込み中…",error:"PDF を開けません。もう一度選択してください。",close:"原文ビューアーを閉じる",page:"ページ",fit:"幅に合わせる",zoomIn:"拡大",zoomOut:"縮小",resize:"ドラッグしてゲームと PDF の幅を調整",scroll:"スクロールして連続閲覧"},ru:{title:"Исходный PDF",choose:"Выбрать PDF на устройстве",change:"Сменить PDF",empty:"Выберите исходный PDF для чтения рядом с историей. Файл не загружается на сервер.",search:"Поиск в PDF",noMatch:"Нет совпадений",searching:"Поиск…",previous:"Предыдущее совпадение",next:"Следующее совпадение",loading:"Загрузка PDF…",error:"Не удалось открыть PDF. Выберите файл снова.",close:"Закрыть PDF",page:"Страница",fit:"По ширине",zoomIn:"Увеличить",zoomOut:"Уменьшить",resize:"Перетащите, чтобы изменить ширину игры и PDF",scroll:"Прокручивайте страницы"}},lg=({pdf:e,number:t,width:r,scrollRoot:a,label:n,matches:i,activeMatchIndex:o})=>{const c=l.useRef(null),f=l.useRef(null),d=l.useRef(null),S=l.useRef(o),[b,w]=l.useState(t<=2),[v,j]=l.useState(1.414),[$,V]=l.useState(1);return S.current=o,l.useEffect(()=>{const Y=c.current,q=a.current;if(!Y||!q||typeof IntersectionObserver>"u"){w(!0);return}const K=new IntersectionObserver(([Se])=>w(!!(Se!=null&&Se.isIntersecting)),{root:q,rootMargin:"900px 0px"});return K.observe(Y),()=>K.disconnect()},[e,t,a]),l.useEffect(()=>{if(!b||!f.current)return;let Y=!1,q;return(async()=>{try{const K=await e.getPage(t),Se=f.current;if(Y||!Se)return;const ee=K.getViewport({scale:1});j(ee.height/ee.width);const Z=K.getViewport({scale:r/ee.width});V(Z.scale);const fe=Math.min(window.devicePixelRatio||1,2);Se.width=Math.ceil(Z.width*fe),Se.height=Math.ceil(Z.height*fe),Se.style.width=Z.width+"px",Se.style.height=Z.height+"px";const ne=Se.getContext("2d");if(!ne)return;ne.setTransform(fe,0,0,fe,0,0),q=K.render({canvas:Se,canvasContext:ne,viewport:Z}),await q.promise}catch(K){!Y&&!(K instanceof Error&&K.name==="RenderingCancelledException")&&console.warn("[source-pdf] page render failed",t,K)}})(),()=>{Y=!0,q==null||q.cancel()}},[e,t,r,b]),l.useEffect(()=>{const Y=d.current;if(!b||!Y)return;Y.replaceChildren();let q=!1,K;return(async()=>{var Se;try{const[ee,Z]=await Promise.all([td(),e.getPage(t)]);if(q)return;const fe=Z.getViewport({scale:1}),ne=Z.getViewport({scale:r/fe.width}),Pe=await Z.getTextContent();if(q||(K=new ee.TextLayer({textContentSource:Pe,container:Y,viewport:ne}),await K.render(),q))return;const Ee=new Map;for(const _e of i)for(let be=_e.startItem;be<=_e.endItem;be++){const se=((Se=K.textContentItemsStr[be])==null?void 0:Se.length)||0,me=be===_e.startItem?_e.startOffset:0,Oe=be===_e.endItem?_e.endOffset:se;me<Oe&&Ee.set(be,[...Ee.get(be)||[],{start:me,end:Oe,index:_e.index}])}for(const[_e,be]of Ee){const se=K.textDivs[_e],me=K.textContentItemsStr[_e];if(!se||!me)continue;const Oe=document.createDocumentFragment();let B=0;for(const U of be.sort((z,re)=>z.start-re.start)){Oe.append(document.createTextNode(me.slice(B,U.start)));const z=document.createElement("mark");z.className="source-pdf-match",z.dataset.pdfMatchIndex=String(U.index),z.textContent=me.slice(U.start,U.end),Oe.append(z),B=U.end}Oe.append(document.createTextNode(me.slice(B))),se.replaceChildren(Oe)}const ye=Y.querySelector('[data-pdf-match-index="'+S.current+'"]');ye==null||ye.classList.add("is-current"),ye==null||ye.scrollIntoView({block:"center",inline:"nearest"})}catch(ee){q||console.warn("[source-pdf] text layer failed",t,ee)}})(),()=>{q=!0,K==null||K.cancel(),Y.replaceChildren()}},[e,t,r,b,i]),l.useEffect(()=>{const Y=d.current;if(!Y)return;Y.querySelectorAll(".source-pdf-match.is-current").forEach(K=>K.classList.remove("is-current"));const q=Y.querySelector('[data-pdf-match-index="'+o+'"]');q==null||q.classList.add("is-current"),q==null||q.scrollIntoView({block:"center",inline:"nearest"})},[o]),p.jsxs("section",{ref:c,"data-source-pdf-page":t,className:"mx-auto mb-6 scroll-mt-5",style:{width:r},children:[p.jsxs("div",{className:"relative overflow-hidden bg-white shadow-[0_8px_28px_rgba(67,51,44,.16)] ring-1 ring-black/5",style:{height:Math.ceil(r*v)},children:[b&&p.jsx("canvas",{ref:f,"aria-label":n+" "+t,className:"block"},r),b&&p.jsx("div",{ref:d,className:"source-pdf-text-layer",style:{"--total-scale-factor":$}})]}),p.jsx("div",{className:"pt-2 text-center text-[11px] font-medium tracking-[.14em] text-[#9b8c85]",children:String(t).padStart(2,"0")})]})},dg=({files:e,selectedFileIndex:t,pageNumber:r,language:a,onSelectFileIndex:n,onPageChange:i,onChooseFile:o,onClose:c,onResize:f})=>{const d=Du[a]||Du.zh,S=e[t],[b,w]=l.useState(null),[v,j]=l.useState(0),[$,V]=l.useState("idle"),[Y,q]=l.useState(1),[K,Se]=l.useState(""),[ee,Z]=l.useState([]),[fe,ne]=l.useState(-1),[Pe,Ee]=l.useState(!1),[ye,_e]=l.useState(0),be=l.useRef(0),se=l.useRef(null),me=l.useRef(null),Oe=l.useRef(null),B=l.useRef(r),U=l.useRef(null),z=l.useRef(0),re=l.useRef(null),le=l.useRef(null),ue=l.useRef(0);B.current=r;const he=A=>{const N=se.current;if(!N)return;const M=N.getBoundingClientRect(),F=A??M.top+Math.min(N.clientHeight/2,240),G=Array.from(N.querySelectorAll("[data-source-pdf-page]")),te=G.find(Ie=>Ie.getBoundingClientRect().bottom>F)||G.at(-1);if(!te)return;const ie=te.getBoundingClientRect();le.current={page:Number(te.dataset.sourcePdfPage),fraction:Math.min(1,Math.max(0,(F-ie.top)/ie.height)),clientY:F}},Me=(A,N)=>{he(N),q(A)};l.useEffect(()=>{const A=se.current;if(!A)return;const N=new ResizeObserver(()=>{A.clientWidth!==be.current&&(he(),be.current=A.clientWidth,_e(A.clientWidth))});return N.observe(A),be.current=A.clientWidth,_e(A.clientWidth),()=>N.disconnect()},[]),l.useEffect(()=>{const A=se.current;if(!A||!b)return;const N=M=>{!M.ctrlKey&&!M.metaKey||(M.preventDefault(),M.stopPropagation(),!(!M.deltaY||performance.now()-ue.current<45)&&(ue.current=performance.now(),Me(F=>sg(F,M.deltaY),M.clientY)))};return A.addEventListener("wheel",N,{passive:!1}),()=>A.removeEventListener("wheel",N)},[b]),l.useEffect(()=>{var M;if((M=se.current)==null||M.scrollTo({top:0,behavior:"auto"}),z.current+=1,!S){w(null),j(0),V("idle");return}let A=!1,N;return w(null),j(0),V("loading"),Se(""),Z([]),ne(-1),(async()=>{try{const F=await td();if(A)return;const G=new Uint8Array(await S.arrayBuffer());if(A)return;N=F.getDocument({data:G});const te=await N.promise;if(A)return;w(te),j(te.numPages),V("idle")}catch{A||V("error")}})(),()=>{A=!0,N==null||N.destroy()}},[S]),l.useEffect(()=>{if(!b||!v)return;const A=requestAnimationFrame(()=>{var N,M;
200(M=(N=se.current)==null?void 0:N.querySelector('[data-source-pdf-page="'+ng(B.current,v)+'"]'))==null||M.scrollIntoView({block:"start"})});return()=>cancelAnimationFrame(A)},[b,v]),l.useEffect(()=>{const A=le.current,N=se.current;if(!A||!N||!b)return;le.current=null;const M=requestAnimationFrame(()=>{const F=N.querySelector('[data-source-pdf-page="'+A.page+'"]');if(!F)return;const G=F.getBoundingClientRect();N.scrollTop+=G.top+A.fraction*G.height-A.clientY});return()=>cancelAnimationFrame(M)},[Y,ye,b]),l.useEffect(()=>()=>{var A;U.current!==null&&cancelAnimationFrame(U.current),(A=re.current)==null||A.call(re)},[]);const _=()=>{U.current===null&&(U.current=requestAnimationFrame(()=>{U.current=null;const A=se.current;if(!A||!b)return;const N=A.getBoundingClientRect().top+64,M=Array.from(A.querySelectorAll("[data-source-pdf-page]"),G=>({page:Number(G.dataset.sourcePdfPage),top:G.getBoundingClientRect().top})),F=ig(M,N);F!==B.current&&(B.current=F,i(F))}))};l.useEffect(()=>{const A=++z.current;if(Z([]),ne(-1),!b||!K.trim()){Ee(!1);return}Ee(!0);const N=window.setTimeout(()=>{(async()=>{const M=[];try{for(let F=1;F<=b.numPages;F++){const G=await(await b.getPage(F)).getTextContent();if(A!==z.current)return;const te=G.items.filter(ie=>"str"in ie).map(ie=>ie.str);for(const ie of og(te,K))M.push({...ie,page:F,index:M.length})}if(A!==z.current)return;Z(M),ne(M.length?Math.max(0,M.findIndex(F=>F.page>=B.current)):-1)}catch(F){A===z.current&&console.warn("[source-pdf] search failed",F)}finally{A===z.current&&Ee(!1)}})()},220);return()=>{window.clearTimeout(N),z.current+=1}},[b,K]),l.useEffect(()=>{var N,M;const A=ee[fe];A&&A.page!==B.current&&(i(A.page),(M=(N=se.current)==null?void 0:N.querySelector('[data-source-pdf-page="'+A.page+'"]'))==null||M.scrollIntoView({block:"start"}))},[ee,fe]);const m=l.useMemo(()=>{const A=new Map;for(const N of ee)A.set(N.page,[...A.get(N.page)||[],N]);return A},[ee]),P=A=>ne(N=>cg(N,ee.length,A)),O=A=>{var F;A.preventDefault(),(F=re.current)==null||F.call(re);const N=G=>f(window.innerWidth-G.clientX),M=()=>{window.removeEventListener("pointermove",N),window.removeEventListener("pointerup",M),re.current=null};re.current=M,window.addEventListener("pointermove",N),window.addEventListener("pointerup",M,{once:!0})},k=Math.max(300,ye-40)*Y;return p.jsxs("aside",{className:"source-pdf-reader absolute right-0 top-0 z-[91] flex h-full flex-col border-l border-[#e8d9d1] bg-[#fffaf6] text-[#354457] shadow-[-18px_0_50px_rgba(32,26,33,.22)]","aria-label":d.title,onKeyDown:A=>{var N,M;A.stopPropagation(),(A.ctrlKey||A.metaKey)&&A.key.toLowerCase()==="f"?(A.preventDefault(),(N=Oe.current)==null||N.focus(),(M=Oe.current)==null||M.select()):A.key==="F3"?(A.preventDefault(),P(A.shiftKey?-1:1)):A.key==="Escape"&&c()},children:[p.jsx("div",{className:"source-pdf-resize absolute left-0 top-0 z-10 flex h-full w-3 -translate-x-1/2 cursor-col-resize items-center justify-center",role:"separator","aria-orientation":"vertical","aria-label":d.resize,title:d.resize,tabIndex:0,onPointerDown:O,onKeyDown:A=>{var N;(A.key==="ArrowLeft"||A.key==="ArrowRight")&&(A.preventDefault(),A.stopPropagation(),f((((N=se.current)==null?void 0:N.clientWidth)||0)+(A.ke
200y==="ArrowLeft"?40:-40)))},children:p.jsx("span",{className:"source-pdf-resize-grip","aria-hidden":"true"})}),p.jsxs("header",{className:"flex shrink-0 items-center gap-3 border-b border-[#f1e4dc] px-4 py-3",children:[p.jsx("div",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-xl bg-[#fff0ec] text-[#b76d79]",children:p.jsx(mh,{size:19,strokeWidth:1.8})}),p.jsxs("div",{className:"min-w-0 flex-1",children:[p.jsx("h2",{className:"font-serif text-[17px] font-semibold leading-tight tracking-wide",children:d.title}),p.jsx("p",{className:"mt-0.5 truncate text-xs text-[#8a8d95]",title:S==null?void 0:S.name,children:(S==null?void 0:S.name)||d.scroll})]}),b&&p.jsxs("span",{className:"shrink-0 rounded-full bg-[#f6eee9] px-2.5 py-1 text-xs tabular-nums text-[#796c70]",children:[r," / ",v]}),p.jsx("button",{type:"button","aria-label":d.close,onClick:c,className:"rounded-lg p-2 text-[#7c8895] transition-colors hover:bg-[#f5e9e8] hover:text-[#aa5969]",children:p.jsx(hh,{size:18})})]}),p.jsxs("div",{className:"flex shrink-0 items-center gap-2 border-b border-[#f1e4dc] px-4 py-2.5",children:[e.length>1&&p.jsx("select",{"aria-label":d.title,className:"max-w-36 truncate rounded-lg border border-[#e9dcd5] bg-white px-2 py-2 text-xs",value:t,onChange:A=>{n(Number(A.target.value)),i(1)},children:e.map((A,N)=>p.jsx("option",{value:N,children:A.name},A.name+"-"+N))}),p.jsx("input",{ref:me,className:"hidden",type:"file",accept:".pdf,application/pdf",onChange:A=>{var M;const N=(M=A.target.files)==null?void 0:M[0];N&&o(N),A.target.value=""}}),p.jsxs("button",{type:"button","aria-label":d.choose,title:d.choose,onClick:()=>{var A;return(A=me.current)==null?void 0:A.click()},className:"flex shrink-0 items-center gap-1.5 rounded-lg border border-[#e9dcd5] bg-white px-2.5 py-2 text-xs text-[#6b7280] transition-colors hover:border-[#d8acb2] hover:text-[#a75567]",children:[p.jsx(ph,{size:14}),d.change]}),b&&p.jsxs("form",{onSubmit:A=>{A.preventDefault(),P(1)},className:"flex min-w-0 flex-1 items-center gap-1 rounded-lg border border-[#e9dcd5] bg-white px-2 focus-within:border-[#d8a0a9]",children:[p.jsx(gh,{size:15,className:"shrink-0 text-[#a2a8af]"}),p.jsx("input",{ref:Oe,"aria-label":d.search,placeholder:d.search,value:K,onChange:A=>Se(A.target.value),onKeyDown:A=>{A.key==="Enter"&&A.shiftKey?(A.preventDefault(),P(-1)):A.key==="Escape"&&(A.stopPropagation(),Se(""))},className:"min-w-0 flex-1 bg-transparent py-2 text-xs outline-none"}),K.trim()&&p.jsx("span",{role:"status",className:"shrink-0 text-[11px] tabular-nums text-[#8a7d83]",children:Pe?d.searching:ee.length?`${fe+1}/${ee.length}`:d.noMatch}),p.jsx("button",{type:"button","aria-label":d.previous,title:d.previous,disabled:!ee.length,onClick:()=>
200P(-1),className:"rounded p-1 text-[#8c7480] hover:bg-[#fff0ec] disabled:opacity-40",children:p.jsx(Eh,{size:15})}),p.jsx("button",{type:"submit","aria-label":d.next,title:d.next,disabled:!ee.length,className:"rounded p-1 text-[#8c7480] hover:bg-[#fff0ec] disabled:opacity-40",children:p.jsx(bh,{size:15})})]}),b&&p.jsxs("div",{className:"flex shrink-0 items-center gap-0.5 rounded-lg border border-[#e9dcd5] bg-white p-0.5",children:[p.jsx("button",{type:"button","aria-label":d.zoomOut,onClick:()=>Me(A=>Math.max(.5,A-.25)),className:"rounded p-1.5 hover:bg-[#f7eeea]",children:p.jsx(Th,{size:14})}),p.jsxs("button",{type:"button",title:d.fit,onClick:()=>Me(()=>1),className:"min-w-9 rounded px-1 text-[11px] tabular-nums hover:bg-[#f7eeea]",children:[Math.round(Y*100),"%"]}),p.jsx("button",{type:"button","aria-label":d.zoomIn,onClick:()=>Me(A=>Math.min(3,A+.25)),className:"rounded p-1.5 hover:bg-[#f7eeea]",children:p.jsx(Sh,{size:14})})]})]}),p.jsxs("div",{ref:se,"data-testid":"source-pdf-scroll",onScroll:_,className:"source-pdf-scroll min-h-0 flex-1 overflow-auto bg-[#eee9e4] px-4 py-5",children:[$==="loading"&&p.jsx("p",{className:"py-12 text-center text-sm text-[#887e79]",children:d.loading}),$==="error"&&p.jsx("p",{className:"py-12 text-center text-sm text-red-600",children:d.error}),!S&&p.jsx("p",{className:"mx-auto max-w-sm py-12 text-center text-sm leading-relaxed text-[#887e79]",children:d.empty}),b&&Array.from({length:v},(A,N)=>p.jsx(lg,{pdf:b,number:N+1,width:k,scrollRoot:se,label:d.page,matches:m.get(N+1)||ug,activeMatchIndex:fe},N+1))]})]})},rd={zh:"zh",cn:"zh","zh-cn":"zh","zh-hans":"zh",chinese:"zh","simplified chinese":"zh",中文:"zh",汉语:"zh",漢語:"zh",简体中文:"zh",繁體中文:"zh",en:"en","en-us":"en","en-gb":"en",english:"en",英文:"en",英语:"en",ja:"ja",jp:"ja","ja-jp":"ja",japanese:"ja",日本語:"ja",日文:"ja",日语:"ja",ru:"ru","ru-ru":"ru",russian:"ru",русский:"ru",俄文:"ru",俄语:"ru"},fg=new Set(Object.values(rd)),mg=new Set(["zh","en","ja"]);function wo(e){return String(e??"").trim().toLowerCase().replace(/_/g,"-").replace(/\s+/g," ")}function ws(e,t="zh"){const r=String(e??"").trim(),a=wo(r);return!a||a==="default"?t:rd[a]||r}function hg(e,t="zh"){const r=ws(e,t);return fg.has(r)?r:t}function sn(e,t="zh"){const r=String(e??"").trim(),a=ws(t,"zh");return!r||wo(r)==="default"?a:ws(r,a)}function Rs(e){const t=ws(e,"");return mg.has(t)?t:null}function pg(e,t="zh"){return Rs(e)||Rs(t)||"zh"}function gg(e,t,r="zh"){const a=String(e??"").trim(),n=wo(a);return!a||n==="auto"||n==="default"?Rs(t)||Rs(r)||"zh":pg(a,r)}function ad(e){const t=hg(e,"");return t||null}const Vi=e=>typeof e=="string"?e.trim():"",Eg=e=>{var t;if(typeof e!="string"||!e.trim())return!1;try{const r=JSON.parse(e);return Array.isArray((t=r==null?void 0:r.script)==null?void 0:t.frames)&&r.script.frames.length>0}catch{return!1}},bg=e=>Vi(e.generationStatus)==="failed"&&Vi(e.voiceStatus)!=="cancelled"&&e.voiceEnabled===!0&&!!Vi(e.analysisJobId)&&!!e.textCompletedAt&&Eg(e.gameState),nd=e=>{const t=Number(e.voiceTotal),r=Number(e.voiceTerminal);return bg(e)&&Number.isFinite(t)&&t>0&&Number.isFinite(r)&&r>=t},Tg=4e3;function Sg(e,t){const r=typeof e.title=="string"?e.title.trim():"",a=typeof t.chapterTitle=="string"?t.chapterTitle.trim():"",n=i=>!i||/^(?:Untitled|未命名讲解|未命名论文|生成中的语音讲解)$/i.test(i);return n(r)&&!n(a)?{...e,title:a}:e}const Ag=new Set(["queued","generating","text_ready","voice_waiting","succeeded","failed","cancelled"]),Ig=new Set(["none","queued","active","succeeded","failed","cancelled"]),yg=new Set(["succeeded","failed","cancelled"]),_g=["analysisJobId","generationStatus","voiceStatus","voiceEnabled","voiceTtsMode","voiceTotal","voiceTerminal","voiceQueueState","voiceQueueJobsAhead","voiceQueueFramesAhead","voiceQueueEtaMinutes","generationError","textCompletedAt","voiceCompletedAt","completedAt","updatedAt"],Ro=e=>typeof e=="string"?e.trim():"",No=e=>typeof e.gameState=="string"&&e.gameState.trim().length>0,GA=e=>{var t;if(!No(e))return!1;try{const r=JSON.parse(e.gameState);return(Array.isArray((t=r==null?void 0:r.script)==null?void 0:t.frames)?r.script.frames:Array.isArray(r==null?void 0:r.frames)?r.frames:[]).some(n=>
200typeof(n==null?void 0:n.audioUrl)=="string"&&n.audioUrl.trim().length>0)}catch{return!1}},Cg=e=>!Ro(e.generationStatus)&&No(e),Po=e=>{if(nd(e))return"succeeded";const t=Ro(e.generationStatus);return Ag.has(t)?t:Cg(e)?"succeeded":null},wg=e=>{if(nd(e))return"succeeded";const t=Ro(e.voiceStatus);return Ig.has(t)?t:null},YA=e=>{const t=Po(e);return!!(e.analysisJobId&&t&&!yg.has(t))},Rg=e=>Po(e)==="succeeded"&&No(e),Ng=e=>{const t=Math.max(0,Number(e.voiceTotal)||0),r=Math.max(0,Number(e.voiceTerminal)||0);return t>0?`语音进度 ${Math.min(r,t)} / ${t}`:""},Pg=e=>{const t=Math.max(0,Number(e.voiceQueueJobsAhead)||0),r=Math.max(0,Number(e.voiceQueueFramesAhead)||0),a=Math.max(0,Number(e.voiceQueueEtaMinutes)||0),n=a>0?`,预计约 ${a} 分钟`:"";return t>0?`前方 ${t} 篇论文${r>0?` / ${r} 条语音帧`:""}${n}`:r>0?`前方 ${r} 条语音帧${n}`:n?`队列状态已更新${n}`:""},sd=e=>{const t=Po(e)||"generating",r=wg(e),a=Ng(e),n=Pg(e);return t==="failed"?{kind:"failed",label:"生成失败",detail:e.generationError||"生成任务失败,请重新生成后再打开。",tone:"danger"}:t==="cancelled"?{kind:"cancelled",label:"已取消",detail:"生成任务已取消,请重新生成后再打开。",tone:"warning"}:t==="succeeded"?{kind:"succeeded",label:"已完成",detail:r==="succeeded"?"语音已准备好":"",tone:"success"}:t==="voice_waiting"||r==="active"?{kind:"voice_waiting",label:"语音生成中",detail:a||n||"语音任务正在生成,完成后会自动刷新。",tone:"info"}:t==="queued"?{kind:"queued",label:"排队中",detail:n||"生成任务正在排队。",tone:"neutral"}:{kind:"generating",label:"生成中",detail:"正文正在生成,请稍后再打开。",tone:"info"}},xg=e=>{const t=sd(e);return t.kind==="failed"||t.kind==="cancelled"?t.detail:`${t.label},完成后会自动刷新,请稍后再打开。`},zA=(e,t)=>{let r=!1;const a={...e};for(const n of _g)t[n]!==e[n]&&(a[n]=t[n],r=!0);return r?a:e},WA=({ids:e,intervalMs:t=Tg,getToken:r,fetchStatus:a,onStatuses:n,onSucceeded:i,onUnauthorized:o,onError:c,setTimeoutFn:f=setTimeout,clearTimeoutFn:d=clearTimeout})=>{let S=!0,b=!1,w=null;const v=()=>{w&&(d(w),w=null)},j=V=>{S||e.length===0||(v(),w=f(V,t))},$=async()=>{if(!(S||b)){b=!0;try{const V=r();if(!V)return;const Y=await Promise.all(e.map(async K=>{try{return await a(K,V)}catch(Se){return c==null||c(Se,K),null}}));if(S)return;if(Y.some(K=>K==="unauthorized")){S=!0,v(),o();return}const q=Y.filter(K=>!!(K&&K!=="unauthorized"));if(q.some(K=>K.generationStatus==="succeeded")){await i();return}q.length>0&&await n(q)}finally{b=!1,j(()=>{$()})}}};return{start:()=>{S&&(S=!1,$())},stop:()=>{S=!0,v()},isRunning:()=>!S,isInFlight:()=>b}};function Og(e){e.CapacitorUtils.Synapse=new Proxy({},{get(t,r){return new Proxy({},{get(a,n){return(i,o,c)=>{const f=e.Capacitor.Plugins[r];if(f===void 0){c(new Error(`Capacitor plugin ${r} not found`));return}if(typeof f[n]!="function"){c(new Error(`Method ${n} not found in Capacitor plugin ${r}`));return}(async()=>{try{const d=await f[n](i);o(d)}catch(d){c(d)}})()}}})}})}function vg(e){e.CapacitorUtils.Synapse=new Proxy({},{get(t,r){return e.cordova.plugins[r]}})}function Lg(e=!1){typeof window>"u"||(window.CapacitorUtils=window.CapacitorUtils||{},window.Capacitor!==void 0&&!e?Og(window):window.cordova!==void 0&&vg(window))}const kg=nr("FileTransfer",{web:()=>Be(()=>import("./web-BjKL51lK-B6_iPXHq.js"),__vite__mapDeps([47,4,6,7,3,2,5]),import.meta.url).then(e=>new e.FileTransferWeb)});Lg();function Dg(e){e.CapacitorUtils.Synapse=new Proxy({},{get(t,r){return new Proxy({},{get(a,n){return(i,o,c)=>{const f=e.Capacitor.Plugins[r];if(f===void 0){c(new Error(`Capacitor plugin ${r} not found`));return}if(typeof f[n]!="function"){c(new Error(`Method ${n} not found in Capacitor plugin ${r}`));return}(async()=>{try{const d=await f[n](i);o(d)}catch(d){c(d)}})()}}})}})}function Mg(e){e.CapacitorUtils.Synapse=new Proxy({},{get(t,r){return e.cordova.plugins[r]}})}function Ug(e=!1){typeof window>"u"||(window.CapacitorUtils=window.CapacitorUtils||{},window.Capacitor!==void 0&&!e?Dg(window):window.cordova!==void 0&&Mg(window))}var Ut;(function(e){e.Documents="DOCUMENTS",e.Data="DATA",e.Library="LIBRARY",e.Cache="CACHE",e.External="EXTERNAL",e.ExternalStorage="EXTERNAL_STORAGE",e.ExternalCache="EXTERNAL_CACHE",e.LibraryNoCloud="LIBRARY_NO_CLOUD",e.Temporary="TEMPORARY"})(Ut||(Ut={}));var Ns;(function(e){e.UTF8="utf8",e.ASCII="ascii",e.UTF16="utf16"})(Ns||(Ns={}));const ar=nr("Filesystem",{web:()=>Be(()=>import("./web-B8kf_4VD.js"),__vite__mapDeps([48,4,6,7,3,2,5]),import.meta.url).then(e=>new e.FilesystemWeb)});Ug();const Bg=new Set(Object.values(lt)),Fg=new Set(["replace","append","clear"]),Hg=new TextEncoder;function id(){return{version:ys,entries:[]}}function Vs(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function kr(e){return typeof e=="string"&&e.trim().length>0}function jg(e){return typeof e=="number"&&Number.isInteger(e)}function Vg(e){return e.entries.length<=Ll&&Ps(e)<=_s}function Gs(e,t){return Object.keys(e).every(r=>t.includes(r))}function Gg(e,t=!1){return!Vs(e)||t&&!Gs(e,["frameId","speaker","text"])||!jg(e.frameId)||!kr(e.speaker)||!kr(e.text)?null:{frameId:e.frameId,speaker:e.speaker,text:e.text}}function Yg(e,t=!1){if(!Vs(e)||t&&!Gs(e,["speaker","text","emotion","isImportant","blackboard","blackboardMode"])||!kr(e.speaker)||!kr(e.text))return null;const r={speaker:e.speaker.trim(),text:e.text.trim()};if(e.emotion!==void 0){if(typeof e.emotion!="string"||!Bg.has(e.emotion))return null;r.emotion=e.emotion}if(e.isImportant!==void 0){if(typeof e.isImportant!="boolean")return null;r.isImportant=e.isImportant}if(e.blackboard!==void 0){if(!kr(e.blackboard))return null;r.blackboard=e.blackboard.trim()}if(e.blackboardMode!==void 0){if(typeof e.blackboardMode!="string"||!Fg.has(e.blackboardMode))return null;r.blackboardMode=e.blackboardMode}return r.blackboardMode==="append"&&!r.blackboard||r.blackboardMode==="replace"&&!r.blackboard?null:r}function od(e,t=!1){if(!Vs(e)||t&&!Gs(e,["operationId","anchor","question","playerSpeaker","steps"])||!kr(e.operationId)||!kr(e.question)||!kr(e.playerSpeaker))return null;const r=Gg(e.anchor,t);if(!r||!Array.isArray(e.steps)||e.steps.length===0||e.steps.length>8)return null;const a=e.steps.map(n=>Yg(n,t));return a.some(n=>n===null)?null:{operationId:e.operationId.trim(),anchor:r,question:e.question.trim(),playerSpeaker:e.playerSpeaker.trim(),steps:a}}function xo(e){if(e==null||!Vs(e)||!Gs(e,["version","entries"])||e.version!==ys||!Array.isArray(e.entries))return null;const t=e.entries.map(n=>od(n,!0));if(t.some(n=>n===null))return null;const r=t.map(n=>n.operationId);if(new Set(r).size!==r.length)return null;const a={version:ys,entries:t};return Vg(a)?a:null}function Ps(e){return Hg.encode(JSON.stringify(e)).byteLength}function zg(e,t){return JSON.stringify(e)===JSON.stringify(t)}function Wg(e,t){const a=xo(e)||id(),n=od(t);if(!n)return{ok:!1,status:"invalid",archive:a,reason:"invalid entry"};const i=a.entries.find(c=>c.operationId===n.operationId);if(i)return zg(i,n)?{ok:!0,status:"duplicate",archive:a,entry:i}:{ok:!1,status:"conflict",archive:a,reason:"operation ID payload conflict"};
200if(a.entries.length>=Ll)return{ok:!1,status:"capacity",archive:a,reason:"entry count limit exceeded"};const o={version:ys,entries:[...a.entries,n]};return Ps(o)>_s?{ok:!1,status:"capacity",archive:a,reason:"UTF-8 archive size limit exceeded"}:{ok:!0,status:"appended",archive:o,entry:n}}function $g(e,t,r={}){const a=xo(e)||id();if(!t)return{status:a.entries.length?"stale":"empty",entries:[]};const n=a.entries.filter(i=>{var o;return i.anchor.frameId===t.id&&i.anchor.speaker===t.speaker&&i.anchor.text===t.text&&!((o=r.alreadySeenOperationIds)!=null&&o.has(i.operationId))});return n.length?{status:"ready",entries:n}:{status:a.entries.some(o=>o.anchor.frameId===t.id&&o.anchor.speaker===t.speaker&&o.anchor.text===t.text)?"ready":a.entries.length?"stale":"empty",entries:[]}}function qg(e){return e.flatMap(t=>[{kind:"question",operationId:t.operationId,speaker:t.playerSpeaker,text:t.question},...t.steps.map(r=>({kind:"answer",operationId:t.operationId,...r}))])}function ta(e){return e!=null&&xo(e)!==null}const Qg=/https:\/\/assert\.paper2gal\.com\/[^\s"'<>()[\]]+/g,Kg=/\.(?:avif|gif|jpe?g|png|svg|webp|mp3|m4a|ogg|wav|aac|flac|mp4|webm|json|moc3|model3)(?:[?#]|$)/i,Xg=["https://assert.paper2gal.com/lofi-bgm-20260523/"];function ro(e,t=new Set){if(typeof e=="string"){for(const r of e.matchAll(Qg)){const a=r[0].replace(/[),.;]+$/,"");Xg.some(n=>a.startsWith(n))||Kg.test(a)&&t.add(a)}return t}return Array.isArray(e)?(e.forEach(r=>ro(r,t)),t):(e&&typeof e=="object"&&Object.values(e).forEach(r=>ro(r,t)),t)}function xs(e,t){if(typeof e=="string"){let r=e;return t.forEach((a,n)=>{r=r.split(n).join(a)}),r}return Array.isArray(e)?e.map(r=>xs(r,t)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([r,a])=>[r,xs(a,t)])):e}const Pa="paper2gal/offline",cd=`${Pa}/registry.json`,ud=`${Pa}/story-question-archives.json`,ld=`${Pa}/assets`,Oo=new Map;let Mu=Promise.resolve(),Uu=Promise.resolve(),Bu=Promise.resolve();const fs=new Map,Aa=new Map,xr=new Map,Ts=new Set,ms=new Map,An=new Map,rt=()=>_t.isNativePlatform(),$A=()=>rt(),Ur=e=>encodeURIComponent(e),Nn=e=>`${Pa}/saves/${Ur(e)}.json`,vo=e=>`${Pa}/manifests/${Ur(e)}.json`,Pn=e=>`save:${Ur(e)}`,Lo=e=>`manifest:${Ur(e)}`,Ys=(e,t)=>`${Pa}/story-question-archives/${Ur(e)}/${Ur(t)}.json`,xn=(e,t)=>`story-question-archive:${Ur(e)}:${Ur(t)}`,Fu="story-question-archive:";function Jg(e){if(!e.startsWith(Fu))return null;const t=e.slice(Fu.length),r=t.lastIndexOf(":");if(r<=0)return null;try{return{ownerId:decodeURIComponent(t.slice(0,r)),saveId:decodeURIComponent(t.slice(r+1))}}catch{return null}}async function xa(e){try{const t=await ar.readFile({path:e,directory:Ut.LibraryNoCloud,encoding:Ns.UTF8});return JSON.parse(String(t.data))}catch{return null}}async function ra(e,t){await ar.writeFile({path:e,directory:Ut.LibraryNoCloud,encoding:Ns.UTF8,recursive:!0,data:JSON.stringify(t)})}function ko(){return typeof indexedDB>"u"?Promise.resolve(null):new Promise(e=>{const t=indexedDB.open("paper2gal_offline",1);t.onupgradeneeded=()=>{t.result.objectStoreNames.contains("records")||t.result.createObjectStore("records")},t.onsuccess=()=>e(t.result),t.onerror=()=>e(null)})}async function Oa(e){const t=await ko();if(!t){const r=Oo.get(e);return r?JSON.parse(r):null}return new Promise(r=>{const a=t.transaction("records","readonly").objectStore("records").get(e);a.onsuccess=()=>r(a.result??null),a.onerror=()=>r(null)})}async function aa(e,t){const r=await ko();if(!r){Oo.set(e,JSON.stringify(t));return}await new Promise((a,n)=>{const i=r.transaction("records","readwrite");i.objectStore("records").put(t,e),i.oncomplete=()=>a(),i.onerror=()=>n(i.error)})}async function Do(e){const t=await ko();Oo.delete(e),t&&await new Promise(r=>{const a=t.transaction("records","readwrite");a.objectStore("records").delete(e),a.oncomplete=()=>r(),a.onerror=()=>r()})}async function Mo(){return rt()?await xa(cd)||[]:await Oa("registry")||[]}async function Zg(e){const t=Array.from(new Set(e.filter(Boolean)));rt()?await ra(cd,t):await aa("registry",t)}function Os(e){const t=Mu.then(r,r);return Mu=t.then(()=>{},()=>{}),t;async function r(){const a=await Mo();await Zg(e(a))}}function Uo(e){const t=Uu.then(e,e);return Uu=t.then(()=>{},()=>{}),t}function dd(e,t){const a=(fs.get(e)||Promise.resolve()).then(t,t),n=a.then(()=>{},()=>{});return fs.set(e,n),n.then(()=>
200{fs.get(e)===n&&fs.delete(e)}),a}function Hu(e,t){const a=(ms.get(e)||Promise.resolve()).then(t,t),n=a.then(()=>{},()=>{});return ms.set(e,n),n.then(()=>{ms.get(e)===n&&ms.delete(e)}),a}function eE(e,t){const r=An.get(e)||new Set;r.add(t),An.set(e,r)}function tE(e,t){const r=An.get(e);r&&(r.delete(t),r.size===0&&An.delete(e))}function rE(e,t){const r=An.get(e);return!!(r&&Array.from(r).some(a=>a!==t))}function wa(){const e=new Map(Aa);let t=!1;const r={isCurrent:a=>!t&&(Aa.get(a)||0)===(e.get(a)||0),release:()=>{t||(t=!0,Ts.delete(r),Ts.size===0&&Aa.clear())}};return Ts.add(r),r}function $e(e,t={}){return(!t.cacheEpoch||t.cacheEpoch.isCurrent(e))&&(!t.shouldCommit||t.shouldCommit())}function aE(e){Aa.set(e,(Aa.get(e)||0)+1),Ts.size===0&&Aa.clear()}async function zs(){return rt()?await xa(ud)||[]:await Oa("story-question-archive-registry")||[]}async function Ia(e){const t=Array.from(new Set(e.filter(Boolean)));rt()?await ra(ud,t):await aa("story-question-archive-registry",t)}function Ws(e){const t=Bu.then(e,e);return Bu=t.then(()=>{},()=>{}),t}async function nE(e){return rt()?xa(Nn(e)):Oa(Pn(e))}async function ju(e){rt()?await ra(Nn(e.id),e):await aa(Pn(e.id),e)}async function vs(e){rt()?await ar.deleteFile({path:Nn(e),directory:Ut.LibraryNoCloud}).catch(()=>{}):await Do(Pn(e))}async function Ls(e,t){rt()?await ar.deleteFile({path:Ys(e,t),directory:Ut.LibraryNoCloud}).catch(()=>{}):await Do(xn(e,t))}async function ao(e,t,r){const a=xn(e,t),n=await zs();if(r){rt()?await ra(Ys(e,t),r):await aa(a,r),n.includes(a)||await Ia([...n,a]);return}await Ls(e,t),await Ia(n.filter(i=>i!==a))}async function Gi(e,t,r,a){await Ws(async()=>{const n=await Bo(e,t);!n||n.revision!==a.revision||JSON.stringify(n.archive)!==JSON.stringify(a.archive)||await ao(e,t,r)})}async function Bo(e,t){const r=rt()?await xa(Ys(e,t)):await Oa(xn(e,t));return!r||r.ownerId!==e||r.saveId!==t||!Number.isInteger(r.revision)||r.revision<0||!ta(r.archive)?null:r}const sE=new Set(["storyQuestionArchive","storyQuestionRevision","storyQuestionReplay","storyQuestionReplayCursor","privateStoryQuestionArchive","privateStoryQuestionRevision"]);function no(e){return Array.isArray(e)?e.map(no):!e||typeof e!="object"?e:Object.fromEntries(Object.entries(e).filter(([t])=>!sE.has(t)).map(([t,r])=>[t,no(r)]))}function $s(e){const{storyQuestionArchive:t,storyQuestionRevision:r,...a}=e;if(typeof a.gameState!="string")return a;try{a.gameState=JSON.stringify(no(JSON.parse(a.gameState)))}catch{}return a}function fd(e,t){return!!(e&&t.userId&&t.userId===e)}async function so(e,t={}){if(!e.ownerId||!e.saveId||!ta(e.archive)||!Number.isInteger(e.revision)||e.revision<0)return!1;const r=t.cacheEpoch?void 0:wa(),a={...t,cacheEpoch:t.cacheEpoch||r},n=xn(e.ownerId,e.saveId),i=xr.get(n)||0;return Ws(async()=>{var o;try{if((xr.get(n)||0)!==i||!$e(e.saveId,a))return!1;const c=await Bo(e.ownerId,e.saveId);if(c&&c.revision>=e.revision||!$e(e.saveId,a))return!1;const f=c,d=await zs(),S={...e,updatedAt:e.updatedAt||new Date().toISOString()};return rt()?await ra(Ys(e.ownerId,e.saveId),S):await aa(n,S),(xr.get(n)||0)!==i?(await Ls(e.ownerId,e.saveId),await Ia(d.filter(b=>b!==n)),!1):$e(e.saveId,a)?(d.includes(n)||await Ia([...d,n]),(xr.get(n)||0)!==i?(await Ls(e.ownerId,e.saveId),await Ia(d.filter(b=>b!==n)),!1):$e(e.saveId,a)?(xr.get(n)===i&&xr.delete(n),!0):(await ao(e.ownerId,e.saveId,f),!1)):(await ao(e.ownerId,e.saveId,f),!1)}finally{(o=r==null?void 0:r.release)==null||o.call(r)}})}async function On(e,t){return!e||!t?null:Ws(()=>Bo(e,t))}async function Vu(e,t){if(!e||!t)return;const r=xn(e,t);xr.set(r,(xr.get(r)||0)+1),await Ws(async()=>{const a=await zs();await Ia(a.filter(n=>n!==r)),await Ls(e,t)})}async function md(e,t,r){if(!(e!=null&&e.id)||!$e(e.id,r))return!1;const a=e,n=await nE(a.id);let i=!1,o=null;if(t&&fd(t,a)&&ta(a.storyQuestionArchive)&&Number.isInteger(a.storyQuestionRevision)&&(o=await On(t,a.id),i=await so({ownerId:t,saveId:a.id,archive:a.storyQuestionArchive,revision:a.storyQuestionRevision},r),!$e(e.id,r)))return i&&t&&(!r.cacheEpoch||r.cacheEpoch.isCurrent(e.id))&&await Gi(t,e.id,o,{archive:a.storyQuestionArchive,revision:a.storyQuestionRevision}),!1;const c=$s(a);if(!$e(c.id,r))return!1;if(rt()?await ra(Nn(c.id),c):await aa(Pn(c.id),c),!$e(c.id,r))return n?await ju(n):await vs(c.id),i&&t&&(!r.cacheEpoch||r.cacheEpoch.isCurrent(c.id))&&await Gi(t,c.id,o,{archive:a.storyQuestionArchive,revision:a.storyQuestionRevision}),!1;let f=!1;return await Os(d=>
200(f=d.includes(c.id),f?d:[...d,c.id])),$e(c.id,r)?!0:(await Os(d=>r.cacheEpoch&&!r.cacheEpoch.isCurrent(c.id)?d.filter(S=>S!==c.id):f?d.includes(c.id)?d:[...d,c.id]:d.filter(S=>S!==c.id)),n?await ju(n):await vs(c.id),i&&t&&(!r.cacheEpoch||r.cacheEpoch.isCurrent(c.id))&&await Gi(t,c.id,o,{archive:a.storyQuestionArchive,revision:a.storyQuestionRevision}),!1)}async function Ea(e,t,r={}){const a=r.cacheEpoch?void 0:wa(),n={...r,cacheEpoch:r.cacheEpoch||a};return Uo(async()=>{var i;try{return await md(e,t,n)}finally{(i=a==null?void 0:a.release)==null||i.call(a)}})}async function qA(e,t,r={}){const a=e.filter(o=>!!(o!=null&&o.id)),n=r.cacheEpoch?void 0:wa(),i={...r,cacheEpoch:r.cacheEpoch||n};return Uo(async()=>{var o;try{const c=[];for(const f of a)await md(f,t,i)&&c.push(f.id);return c.length>0&&c.every(f=>$e(f,i))&&await Os(f=>Array.from(new Set([...f,...c]))),c}finally{(o=n==null?void 0:n.release)==null||o.call(n)}})}async function QA(e={}){const t=e||{},r=await Mo(),a=await Promise.all(r.map(i=>rt()?xa(Nn(i)):Oa(Pn(i))));return(await Promise.all(a.filter((i,o)=>!!(i!=null&&i.id&&i.id===r[o]&&(i!=null&&i.gameState))).filter(i=>t.visibility==="public"||!t.ownerId||i.userId===t.ownerId).map(async i=>{const o=$s(i);if(t.visibility==="public"||!t.ownerId||!fd(t.ownerId,i))return o;const c=await On(t.ownerId,i.id);return c?{...o,storyQuestionArchive:c.archive,storyQuestionRevision:c.revision}:o}))).sort((i,o)=>new Date(o.updatedAt).getTime()-new Date(i.updatedAt).getTime())}async function ya(e){return rt()?xa(vo(e)):Oa(Lo(e))}async function Yi(e){rt()?await ra(vo(e.saveId),e):await aa(Lo(e.saveId),e)}async function io(e){rt()?await ar.deleteFile({path:vo(e),directory:Ut.LibraryNoCloud}).catch(()=>{}):await Do(Lo(e))}async function iE(e,t){const r=await Mo();return(await Promise.all(r.filter(n=>n!==t).map(n=>ya(n)))).some(n=>n==null?void 0:n.resources.some(i=>i.path===e))}function oE(e,t){return JSON.stringify(e)===JSON.stringify(t)}async function cE(e){const t=new TextEncoder().encode(e),r=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(r)).map(a=>a.toString(16).padStart(2,"0")).join("")}function uE(e){try{const t=new URL(e).pathname.match(/\.([a-zA-Z0-9]{1,8})$/);return t?`.${t[1].toLowerCase()}`:".bin"}catch{return".bin"}}async function lE(e){return`${ld}/${await cE(e)}${uE(e)}`}async function ba(e){try{return await ar.stat({path:e,directory:Ut.LibraryNoCloud}),!0}catch{return!1}}async function dE(e,t){await ar.mkdir({path:ld,directory:Ut.LibraryNoCloud,recursive:!0});const r=await ar.getUri({path:t,directory:Ut.LibraryNoCloud});await kg.downloadFile({url:e,path:r.uri,connectTimeout:3e4,readTimeout:12e4})}async function KA(e,t,r={}){const a=r.cacheEpoch?void 0:wa(),n=r.cacheEpoch||a,i={...r,cacheEpoch:n},o=()=>({state:"partial",completed:0,total:0,updatedAt:new Date().toISOString()});return dd(e.id,async()=>{var $;const c=r.ownerId&&e.userId===r.ownerId?r.ownerId:null,f=Symbol("offline-save-cache"),d=new Set,S=new Set;let b=null,w=null;const v=async()=>{if(w){const q=await ya(e.id);oE(q,w)&&(b?await Yi(b):await io(e.id))}const V=await ya(e.id),Y=new Set([...((b==null?void 0:b.resources)||[]).map(q=>q.path),...((V==null?void 0:V.resources)||[]).map(q=>q.path)]);for(const q of d)await Hu(q,async()=>{Y.has(q)||rE(q,f)||await iE(q,e.id)||!await ba(q)||await ar.deleteFile({path:q,directory:Ut.LibraryNoCloud}).catch(()=>{})})},j=async(V=0,Y=0)=>(await v(),{state:"partial",completed:V,total:Y,updatedAt:new Date().toISOString()});try{if(!await Ea(e,c,i))return o();if(!$e(e.id,i))return j();if(!rt())return{state:"partial",completed:0,total:0,updatedAt:new Date().toISOString()};const Y=c?await On(c,e.id):null;if(!$e(e.id,i))return j();const q=$s(e),K=JSON.parse(q.gameState),Se=Y?{...K,storyQuestionArchive:Y.archive}:K,ee=Array.from(ro(Se));if(b=await ya(e.id),!$e(e.id,i))return j(0,ee.length);const Z=[...(b==null?void 0:b.resources)||[]],fe=new Map(Z.map(_e=>[_e.remoteUrl,_e]));let ne=0;for(const _e of ee){if(!$e(e.id,i))return j(ne,ee.length);const be=fe.get(_e),se=be?await ba(be.path):!1;if(!$e(e.id,i))return j(ne,ee.length);be&&se&&(ne+=1)}if(!$e(e.id,i))return j(ne,ee.length);t==null||t({state:"downloading",completed:ne,total:ee.length});for(const _e of ee){if(!$e(e.id,i))return j(ne,ee.length);const be=fe.get(_e),se=be?await ba(be.path):!1;if(!$e(e.id,i))return j(ne,ee.length);if(!(be&&se))try{const me=(be==null?void 0:be.path)||await lE(_e);if(!$e(e.id,i))return j(ne,ee.length);const Oe=await ba(me);if(!$e(e.id,i)||(eE(me,f),S.add(me),Oe||await Hu(me,async()=>
200{await ba(me)||(d.add(me),await dE(_e,me))}),!$e(e.id,i)))return j(ne,ee.length);const B={remoteUrl:_e,path:me};fe.set(_e,B),ne+=1;const U={saveId:e.id,state:ne===ee.length?"ready":"partial",resources:Array.from(fe.values()),total:ee.length,updatedAt:new Date().toISOString()};if(!$e(e.id,i)||(await Yi(U),w=U,!$e(e.id,i)))return j(ne,ee.length);t==null||t({state:"downloading",completed:ne,total:ee.length})}catch{console.warn("[OfflineSave] Asset download failed")}}const Pe=ne===ee.length?"ready":"partial",Ee={state:Pe,completed:ne,total:ee.length,updatedAt:new Date().toISOString()},ye={saveId:e.id,state:Pe,resources:Array.from(fe.values()),total:ee.length,updatedAt:Ee.updatedAt};return!$e(e.id,i)||(await Yi(ye),w=ye,!$e(e.id,i))?j(ne,ee.length):(t==null||t(Ee),Ee)}catch(V){return $e(e.id,i)?(console.warn("[OfflineSave] Asset download failed",V),o()):j()}finally{for(const V of S)tE(V,f);($=a==null?void 0:a.release)==null||$.call(a)}})}async function XA(e){const t=await ya(e);return t?{state:t.state,completed:t.resources.length,total:t.total,updatedAt:t.updatedAt}:{state:"none",completed:0,total:0}}async function fE(e){const t=await ar.getUri({path:e,directory:Ut.LibraryNoCloud});return _t.convertFileSrc(t.uri)}async function JA(e,t={}){const r=e,a=t.visibility!=="public"&&!!(t.ownerId&&t.ownerId===e.userId),n=a?await On(t.ownerId,e.id):null,i=ta(r.storyQuestionArchive)&&Number.isInteger(r.storyQuestionRevision)?{archive:r.storyQuestionArchive,revision:r.storyQuestionRevision}:null,o=n&&(!i||n.revision>=i.revision)?n:i,c=a&&o?{storyQuestionArchive:o.archive,storyQuestionRevision:o.revision}:{},f=$s(r);if(!rt())return{...f,...c};const d=await ya(e.id),S=new Map;if(d!=null&&d.resources.length)for(const w of d.resources)await ba(w.path)&&S.set(w.remoteUrl,await fE(w.path));if(S.size===0)return{...f,...c};const b=xs(JSON.parse(f.gameState),S);return{...f,gameState:JSON.stringify(b),...c.storyQuestionArchive?{storyQuestionArchive:xs(c.storyQuestionArchive,S),storyQuestionRevision:c.storyQuestionRevision}:{}}}async function ZA(e,t){e&&(aE(e),await dd(e,()=>Uo(async()=>{if(await Os(r=>r.filter(a=>a!==e)),t)await Vu(t,e);else{const a=(await zs()).map(Jg).filter(n=>!!(n&&n.saveId===e));await Promise.all(a.map(({ownerId:n})=>Vu(n,e)))}if(rt()){await Promise.all([vs(e),io(e)]);return}await Promise.all([vs(e),io(e)])})))}const mE=/^[a-z0-9][a-z0-9_-]{0,63}$/u,hd=128,hE=hd*2,pE={closer:2,playful:1,neutral:0};function ga(){return{selectedChoices:{},relationshipTone:"neutral",relationshipScore:0}}function Ra(e){return typeof e=="string"&&mE.test(e)}function pd(e){return e==="closer"||e==="playful"||e==="neutral"}function gE(e){return pd(e)?e:"neutral"}function EE(e){const t=new Map;for(const r of e)if(Array.isArray(r.choices))for(const a of r.choices){const n=a.choiceId||r.socialChoiceId,i=a.optionId;if(!Ra(n)||!Ra(i))continue;const o=t.get(n)||new Map;o.set(i,gE(a.relationshipEffect)),t.set(n,o)}return t}function bE(e,t){var o;let r=0,a=0,n=0;for(const[c,f]of Object.entries(e)){const d=((o=t.get(c))==null?void 0:o.get(f))||"neutral";n+=pE[d],d==="closer"&&(r+=1),d==="playful"&&(a+=1)}return{relationshipTone:r>0&&r>=a?"closer":a>0?"playful":"neutral",relationshipScore:n}}function In(e,t){var d;const r=e&&typeof e=="object"&&!Array.isArray(e)?e:{},a=r.selectedChoices&&typeof r.selectedChoices=="object"&&!Array.isArray(r.selectedChoices)?r.selectedChoices:{},n=t?EE(t):null,i={};for(const[S,b]of Object.entries(a).slice(0,hd))!Ra(S)||!Ra(b)||n&&!((d=n.get(S))!=null&&d.has(b))||(i[S]=b);if(n)return{selectedChoices:i,...bE(i,n)};const o=pd(r.relationshipTone)?r.relationshipTone:"neutral",c=Number(r.relationshipScore),f=Number.isFinite(c)?Math.max(0,Math.min(hE,Math.round(c))):0;return{selectedChoices:i,relationshipTone:o,relationshipScore:f}}function gd(e,t,r){return In({selectedChoices:Object.fromEntries(Object.entries(e.selectedChoices).filter(([a])=>r.has(a)))},t)}function TE(e){const{frames:t,choiceId:r,optionId:a,activeChoiceIds:n}=e;if(!Ra(r)||!Ra(a))return In(e.state,t);const o={...(n?gd(e.state,t,n):e.state).selectedChoices};return o[r]=a,In({selectedChoices:o},t)}function SE(e,t){return Object.keys(e.selectedChoices).length===0?"":{zh:{closer:"一路并肩读到最后,你们之间的默契也悄悄更近了一步。",playful:"这场阅读留下了轻松的打趣,也留下了只属于你们的默契。",neutral:"你们稳稳读完了这篇论文,也把共同理解留在了这一页。"},en:{closer:"Reading side by side brought the two of you a quiet step closer.",playful:"The reading ended with playful banter and a rapport of your own.",neutral:"You finished the paper together and left this page with a shared understanding."},ja:{closer:"最後まで並んで読み進めた二人の距離は、そっと一歩近づきました。",playful:"この読書には軽やかな掛け合いと、二人だけの呼吸が残りました。",neutral:"二人で論文を読み終え、このページに共通の理解を残しました。"},ru:{closer:"Совместное чтение незаметно сделало вас немного ближе.",playful:"После чтения остались лёгкие шутки и особое взаимопонимание.",neutral:"Вы вместе дочитали статью и сохранили общее понимание этой страницы."}}[t][e.relationshipTone]}function Gu(e){const t=e.frames[e.currentFrameIndex],r=[...e.historyFrameIds,t==null?void 0:t.id].filter(o=>Number.isInteger(o)),a=new Map;r.forEach((o,c)=>a.set(o,c));const n=Array.from(a.entries()).sort((o,c)=>o[1]-c[1]).map(([o])=>e.frames.find(c=>c.id===o)).filter(o=>!!o).slice(-12).map(o=>({frameId:o.id,speakerRole:o.speakerRole||"character",...o.beatKind?{beatKind:o.beatKind}:{},...o.action?{action:o.action}:{},...o.performanceBeatId?{performanceBeatId:o.performanceBeatId}:{}})),i=typeof e.relationshipTone=="string"?e.relationshipTone.trim().slice(0,160):"";return{version:1,narrativeStyle:e.narrativeStyle,...i?{relationshipTone:i}:{},recentFrames:n}}const AE=/!\[([^\]]*)\]\((https?:\/\/[^)\s]+)\)/gi,IE=/\n\n---\n\n# 文档图片资产[\s\S]*$/,yE=/[\u3400-\u9fff]+/g,_E=/[a-z0-9]{2,}/gi;function hs(e,t){return String(e||"").replace(/[\r\n\[\]]+/g," ").replace(/\s+/g," ").trim().slice(0,t)}function CE(e){const t=new Set,r=e.toLowerCase();for(const a of r.matchAll(yE)){const n=a[0];for(let i=2;i<=Math.min(6,n.length);i+=1)for(let o=0;o<=n.length-i;o+=1)t.add(n.slice(o,o+i))}for(const a of r.matchAll(_E))t.add(a[0]);return[...t]}function wE(e,t){const r=[],a=new Set;for(const n of t)for(const i of Array.isArray(n==null?void 0:n.images)?n.images:[]){const o=String((i==null?void 0:i.url)||"").trim();
200!/^https?:\/\//i.test(o)||a.has(o)||(a.add(o),r.push({index:Number.isFinite(Number(i.index))?Number(i.index):r.length+1,url:o,caption:hs(i.caption||`文档图片 ${i.index}`,80),details:hs(i.details,180),sourcePath:hs(i.sourcePath,120),order:r.length}))}for(const n of e.matchAll(AE)){const i=String(n[2]||"").trim();!i||a.has(i)||(a.add(i),r.push({index:r.length+1,url:i,caption:hs(n[1]||`论文图片 ${r.length+1}`,80),details:"",sourcePath:"",order:r.length}))}return r}function Yu(e,t){const r=`${e.caption} ${e.details} ${e.sourcePath}`.toLowerCase();let a=0;for(const n of CE(t))r.includes(n)&&(a+=n.length);return new RegExp(`(?:图|figure|fig\\.?)\\s*${e.index}(?:\\D|$)`,"i").test(t)&&(a+=20),a}function zu(e,t){const r=e.trim();if(t<=0)return"";if(r.length<=t)return r;const a=`
201
202[中间内容已截断]
203
204`;if(t<=a.length+20)return r.slice(0,t);const n=Math.floor((t-a.length)*.6),i=t-a.length-n;return`${r.slice(0,n)}${a}${r.slice(-i)}`}function RE(e,t,r){if(e.length===0||r<=0)return"";const a="[论文图片资产:以下 Markdown 图片链接由服务端提供,可在 blackboard 中原样引用]",n=[...e].sort((o,c)=>Yu(c,t)-Yu(o,t)||o.order-c.order),i=[a];for(const o of n){const c=o.caption||`论文图片 ${o.index}`,f=`![${c}](${o.url})`,d=[`图片 ${o.index}:${c}`,o.details?`图片说明:${o.details}`:"",`准确 Markdown:${f}`].filter(Boolean).join(`
205`),S=`图片 ${o.index}:${f}`,b=`
206
207`,w=`${i.join(b)}${b}${d}`.length<=r?d:S;`${i.join(b)}${b}${w}`.length>r||i.push(w)}return i.length>1?i.join(`
208
209`):""}function NE(e){const t=Math.max(1,Math.floor(e.maxLength)),r=String(e.referenceText||""),a=Array.isArray(e.documentAssets)?e.documentAssets:[],n=wE(r,a),i=Math.min(t,8e3,Math.max(300,Math.floor(t*.55))),o=RE(n,e.question,i),c=r.replace(IE,"").trim();if(!o)return zu(c,t);const f=c?`
210
211---
212
213`:"",d=t-o.length-f.length,S=zu(c,d);return`${S}${S?f:""}${o}`.slice(0,t)}const Ed="p2g_paper_preferences",PE=3,xE=80,bd=()=>{try{return typeof localStorage>"u"?null:localStorage}catch{return null}},Td=e=>{if(!Array.isArray(e))return[];const t=new Set,r=[];for(const a of e){if(typeof a!="string")continue;const n=a.trim().slice(0,xE),i=n.toLocaleLowerCase();if(!(!n||t.has(i))&&(t.add(i),r.push(n),r.length>=PE))break}return r},OE=(e=bd())=>{if(!e)return[];try{const t=e.getItem(Ed);return Td(t?JSON.parse(t):[])}catch{return[]}},vE=(e,t=bd())=>{const r=Td(e);if(!t)return r;try{t.setItem(Ed,JSON.stringify(r))}catch{}return r},Wu=32,$u=3;class zt extends Error{constructor(t,r={}){super(t),this.name="StoryQuestionArchiveClientError",this.code=r.code||"ARCHIVE_CLIENT_ERROR",this.retryable=r.retryable===!0,this.statusCode=r.statusCode}}const LE={version:1,entries:[]};function kE(){return`story-question-${globalThis.crypto.randomUUID()}`}function Dt(e){return(typeof e=="string"?e.trim():"")||null}function zi(e,t){return e.frameId===t.frameId&&e.speaker===t.speaker&&e.text===t.text}function mr(){return{archive:LE,revision:0}}function oo(e){return!!e&&typeof e=="object"&&ta(e.archive)&&Number.isInteger(e.revision)&&e.revision>=0}function Sd(e){if(!e||typeof e!="object")return!1;const t=e;return t.ok===!0&&(t.status==="appended"||t.status==="duplicate")&&ta(t.archive)&&Number.isInteger(t.revision)&&t.revision>=0&&t.archive.entries.some(r=>JSON.stringify(r)===JSON.stringify(t.entry))}function DE(e){if(e instanceof zt)return e;const t=e,r=typeof(t==null?void 0:t.statusCode)=="number"?t.statusCode:void 0,a=(t==null?void 0:t.retryable)===!0||(t==null?void 0:t.retryable)===void 0&&(r===void 0||r===408||r===429||r>=500);return new zt(typeof(t==null?void 0:t.message)=="string"?t.message:"Failed to save story question.",{code:typeof(t==null?void 0:t.code)=="string"?t.code:void 0,retryable:a,statusCode:r})}function ME(e,t){if(!t||typeof t!="object")return null;const r="entry"in t?t.entry:{operationId:e.operationId,anchor:e.anchor,question:e.question,playerSpeaker:e.playerSpeaker,steps:t.steps},a=Wg(null,r);return!a.ok||a.entry.operationId!==e.operationId||JSON.stringify(a.entry.anchor)!==JSON.stringify(e.anchor)||a.entry.question!==e.question.trim()||a.entry.playerSpeaker!==e.playerSpeaker.trim()?null:a.entry}function UE({fetchImpl:e=st,getToken:t=()=>typeof localStorage>"u"?null:localStorage.getItem("p2g_token")}={}){const r=async(a,n)=>{const i=t(),o=new Headers(n.headers);i&&o.set("Authorization",`Bearer ${i}`);const c=await e(`/api/saves/${encodeURIComponent(a)}/story-questions`,{...n,headers:o});let f=null;try{f=await c.json()}catch{f=null}if(!c.ok){const d=f;
213throw new zt(typeof(d==null?void 0:d.error)=="string"?d.error:"Failed to access story question archive.",{code:typeof(d==null?void 0:d.code)=="string"?d.code:void 0,retryable:(d==null?void 0:d.retryable)===!0,statusCode:c.status})}return f};return{append:async(a,n)=>{const i=await r(a,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({entry:n})});if(!Sd(i))throw new zt("Invalid story question acknowledgement.");return i},read:async a=>{const n=await r(a,{method:"GET"});if(!oo(n))throw new zt("Invalid story question archive response.");return n}}}function BE(e){const t=Math.min(Wu,Math.max(1,Math.floor(e.maxPending??Wu))),r=Math.min($u,Math.max(1,Math.floor(e.maxRetries??$u))),a=new Map,n=new Map,i=new Map,o=new Map,c=new Map,f=new Map,d=new Map,S=new Set;let b=Dt(e.ownerId),w=e.enabled===!0,v=1,j=1,$=!1,V=null;const Y=()=>({ownerId:b,sessionEpoch:v,closed:$,pending:[...a.values()].map(m=>({ownerId:m.handle.ownerId,saveId:m.saveId,generationId:Dt(m.handle.generationId),operationId:m.entry.operationId,attempts:m.attempts,status:m.status})),acknowledged:[...c.values()].map(m=>({...m})),lastFailure:V}),q=()=>{const m=Y();S.forEach(P=>P(m))},K=(m,P,O)=>{V={ownerId:m.handle.ownerId,saveId:m.saveId,operationId:m.entry.operationId,code:P.code,retryable:P.retryable,terminal:O,message:P.message}},Se=m=>!$&&m.handle.sessionEpoch===v&&m.handle.ownerId===b,ee=m=>Se(m)&&m.handle.requestEpoch===j,Z=m=>Ps({version:1,entries:[...a.values(),...m?[{entry:m}]:[]].map(P=>P.entry)}),fe=()=>{const m=()=>[...f.values()].reduce((O,k)=>O+k.archive.entries.length,0),P=()=>[...f.values()].reduce((O,k)=>O+Ps(k.archive),0);for(;f.size>0&&(m()>200||P()>_s);){const O=f.keys().next().value;f.delete(O),o.delete(O);for(const k of c.keys())k.startsWith(`${O}:`)&&c.delete(k)}for(;c.size>200;){const O=c.keys().next().value;c.delete(O);const k=O.slice(0,O.lastIndexOf(":")),A=O.slice(O.lastIndexOf(":")+1),N=o.get(k);N==null||N.delete(A),(N==null?void 0:N.size)===0&&o.delete(k)}},ne=async(m,P,O)=>{if(!m.saveId||!Se(m))return;const k=v,A=b,N=`${m.handle.ownerId}:${m.saveId}`,M=`${N}:${P.entry.operationId}`;if(e.cacheAcknowledgements!==!1&&(await so({ownerId:m.handle.ownerId,saveId:m.saveId,archive:P.archive,revision:P.revision},{shouldCommit:()=>k===v&&A===b,cacheEpoch:O}).catch(()=>{}),k!==v||A!==b))return;const F=f.get(N);(!F||P.revision>=F.revision)&&(f.delete(N),f.set(N,{revision:P.revision,archive:P.archive}));const G=o.get(N)||new Set;G.add(P.entry.operationId),o.set(N,G);const te=c.get(M);(!te||P.revision>=te.revision)&&c.set(M,{saveId:m.saveId,revision:P.revision,entry:P.entry}),fe()},Pe=m=>{const P=`${m.handle.ownerId}:${m.saveId}:${m.entry.operationId}`,O=n.get(P);if(O)return O;const k=async()=>{var te;if(!Se(m))return m.status="stale",q(),{status:"stale",operationId:m.entry.operationId};if(!m.saveId||m.awaitingSnapshot||m.status==="retryable-failure"||m.attempts>=r)return q(),m.status==="retryable-failure"&&m.attempts>=r?{status:"failed",operationId:m.entry.operationId,message:V==null?void 0:V.message}:{status:"pending",operationId:m.entry.operationId,message:V==null?void 0:V.message};if(m.status==="failed")return q(),{status:"failed",operationId:m.entry.operationId,message:V==null?void 0:V.message};m.status="sending",q();const G=m.saveId?wa():void 0;try{for(;m.attempts<r;){if(!Se(m))return m.status="stale",q(),{status:"stale",operationId:m.entry.operationId};try{const ie=await e.transport.append(m.saveId,m.entry);if(!Se(m))return m.status="stale",q(),{status:"stale",operationId:m.entry.operationId};if(!Sd(ie)||JSON.stringify(ie.entry)!==JSON.stringify(m.entry))throw new zt("Invalid story question acknowledgement.");return await ne(m,ie,G),a.delete(m.entry.operationId),ee(m)?((V==null?void 0:V.operationId)===m.entry.operationId&&(V=null),q(),{status:ie.status,operationId:m.entry.operationId,archive:ie.archive,entry:ie.entry,revision:ie.revision}):(m.status="stale",q(),{status:"stale",operationId:m.entry.operationId})}catch(ie){if(!ee(m))return a.delete(m.entry.operationId),m.status="stale",q(),{status:"stale",operationId:m.entry.operationId};const Ie=DE(ie);if(m.attempts+=1,Ie.code==="ANCHOR_NOT_READY")return m.awaitingSnapshot=m.attempts<r,m.status=m.attempts>=r?"retryable-failure":"pending",m.attempts>=r&&K(m,Ie,!1),q(),m.attempts>=r?{status:"failed",operationId:m.entry.operationId,message:Ie.message}:{status:"pending",operationId:m.entry.operationId,message:Ie.message};if(!Ie.retryable||m.attempts>=r)return m.status=Ie.retryable?"retryable-failure":"failed",K(m,Ie,!Ie.retryable),q(),{status:"failed",operationId:m.entry.operationId,message:Ie.message}}}return{status:"failed",operationId:m.entry.operationId,message:V==null?void 0:V.message}}finally{(te=G==null?void 0:G.release)==null||te.call(G)}},A=`${m.handle.sessionEpoch}:${m.handle.ownerId}:${m.saveId}`,M=(i.get(A)||Promise.resolve()).catch(()=>{}).then(k);n.set(P,M);const F=M.then(()=>{},()=>{});return i.set(A,F),M.then(()=>{n.get(P)===M&&n.delete(P),i.get(A)===F&&i.delete(A)},()=>{n.get(P)===M&&n.delete(P),i.get(A)===F&&i.delete(A)}),M},Ee=m=>{const P=`${m.handle.ownerId}:${m.saveId}:${m.entry.operationId}`,O=m.saveId?c.get(P):void 0;if(O){if(JSON.stringify(O.entry)!==JSON.stringify(m.entry)){const N=new zt("Story question operation ID is already in use.",{code:"OPERATION_CONFLICT"});return K(m,N,!0),q(),{status:"invalid",operationId:m.entry.operationId,message:N.message}}const A=f.get(`${m.handle.ownerId}:${m.saveId}`);return A?{status:"duplicate",operationId:m.entry.operationId,archive:A.archive,entry:O.entry,revision:O.revision}:{status:"pending",operationId:m.entry.operationId}}const k=a.get(m.entry.operationId);if(k){if(JSON.stringify(k.entry)!==JSON.stringify(m.entry)){const A=new zt("Story question operation ID is already in use.",{code:"OPERATION_CONFLICT"});return K(m,A,!0),q(),{status:"invalid",operationId:m.entry.operationId,message:A.message}}return k.saveId?Pe(k):{status:"pending",operationId:m.entry.operationId}}
213if(a.size>=t||Z(m.entry)>_s){const A=new zt(a.size>=t?"Too many unsaved story questions.":"Unsaved story questions exceed the size limit.",{code:a.size>=t?"PENDING_CAPACITY":"PENDING_SIZE"});return K(m,A,!0),q(),{status:"invalid",operationId:m.entry.operationId,message:A.message}}return a.set(m.entry.operationId,m),q(),m.saveId?Pe(m):{status:"pending",operationId:m.entry.operationId}},ye=()=>{const m=a.values().next().value;return m?(V={ownerId:m.handle.ownerId,saveId:m.saveId,operationId:m.entry.operationId,code:"PENDING_UNSAVED",retryable:!1,terminal:!1,message:"A successful story question was not saved before leaving this session."},!0):!1},_e=m=>{const P=m===void 0?b:Dt(m),O=ye();return a.clear(),d.clear(),f.clear(),c.clear(),o.clear(),P!==b?(V=null,b=P):O||(V=null),v+=1,j+=1,$=!1,q(),{ownerId:b,sessionEpoch:v}},be=(m="session-invalidated")=>{const P=ye();v+=1,j+=1,a.clear(),d.clear(),f.clear(),c.clear(),o.clear(),P||(V=null),q()},se=(m,P,O)=>{const k=Dt(P);return k?`${v}:${m}:${k}:${O.frameId}:${O.speaker}:${O.text}`:null},me=()=>{j+=1,[...a.values()].filter(m=>m.status!=="sending").forEach(m=>{a.delete(m.entry.operationId),m.status="stale"}),q()},Oe=m=>{const P=e.isEnabled?e.isEnabled():w,O=Dt(m.ownerId)||b||"",k=Dt(m.generationId),A={...m.anchor};return{...m,ownerId:O,saveId:Dt(m.saveId),generationId:k,anchor:A,operationId:Dt(m.operationId)||kE(),sessionEpoch:v,requestEpoch:j,enabledAtStart:P}},B=async(m,P)=>{if(!m.ownerId||!b||m.ownerId!==b||$||m.sessionEpoch!==v||m.requestEpoch!==j)return{status:"stale",operationId:m.operationId};const O=e.isEnabled?e.isEnabled():w;if(!m.enabledAtStart||!O)return{status:"disabled",operationId:m.operationId};const k=ME(m,P);if(!k){const M=new zt("Invalid story question entry.",{code:"INVALID_ENTRY"});return V={ownerId:m.ownerId,saveId:Dt(m.saveId),operationId:m.operationId,code:M.code,retryable:!1,terminal:!0,message:M.message},q(),{status:"invalid",operationId:m.operationId,message:M.message}}const A=Dt(m.saveId)||se(m.ownerId,m.generationId,m.anchor)&&d.get(se(m.ownerId,m.generationId,m.anchor))||null;return await Ee({handle:m,entry:k,saveId:A,attempts:0,status:"pending",awaitingSnapshot:!1})};return{getState:Y,subscribe(m){return S.add(m),()=>S.delete(m)},beginSession:_e,invalidateSession:be,invalidateRequest:me,setOwner:m=>_e(m),setEnabled:m=>{w=m,q()},prepareCapture:Oe,completeCapture:B,capture:async(m,P)=>B(Oe(m),P),assignSave:async({ownerId:m,saveId:P,generationId:O,anchor:k})=>{if($||m!==b)return[];const A=Dt(O);if(!A)return[];const N=se(m,A,k);if(!N)return[];!d.has(N)&&d.size>=t&&d.delete(d.keys().next().value),d.set(N,P);const F=[...a.values()].filter(G=>G.saveId===null&&G.handle.ownerId===m&&G.handle.sessionEpoch===v&&G.handle.generationId===A&&!!(k&&zi(G.handle.anchor,k))).map(G=>(G.saveId=P,Pe(G)));return Promise.all(F)},flush:async m=>{if($||m.ownerId!==b)return[];const P=[...a.values()].filter(O=>O.saveId===m.saveId&&O.handle.ownerId===m.ownerId&&O.handle.sessionEpoch===v&&O.handle.generationId!==null&&O.handle.generationId===Dt(m.generationId)&&!!(m.anchor&&zi(O.handle.anchor,m.anchor))&&!O.awaitingSnapshot).map(O=>Pe(O));return Promise.all(P)},snapshotReady:async m=>{if($||m.ownerId!==b||!m.generationId)return[];const P=[...a.values()].filter(O=>O.saveId===m.saveId&&O.handle.ownerId===m.ownerId&&O.handle.sessionEpoch===v&&O.handle.generationId===m.generationId&&zi(O.handle.anchor,m.anchor)&&O.status==="pending").map(O=>(O.awaitingSnapshot=!1,Pe(O)));return Promise.all(P)},loadOffline:async({saveId:m,ownerId:P,visibility:O="owner",fallback:k})=>{var it;if(O!=="owner"||!P||P!==b||!m)return{...mr(),source:"public"};const A=v,N=()=>b===P&&v===A,M=oo(k)?k:null,F=(Ye,at)=>!at||Ye&&Ye.revision>=at.revision?Ye:at;let G=null;try{G=await On(P,m)}catch{if(!N())return{...mr(),source:"empty"}}if(!N())return{...mr(),source:"empty"};const te=F(G?{archive:G.archive,revision:G.revision}:null,M),ie=e.transport.read;if(!ie)return te?{...te,source:"offline"}:{...mr(),source:"empty"};const Ie=wa(),ve=async Ye=>{!Ye||G&&Ye.revision<=G.revision||!N()||await so({ownerId:P,saveId:m,archive:Ye.archive,revision:Ye.revision},{shouldCommit:N,cacheEpoch:Ie})};try{const Ye=await ie(m);
213if(!oo(Ye))throw new zt("Invalid story question archive response.");if(!N())return{...mr(),source:"empty"};const at=F(te,Ye);return await ve(at),N()?at?{...at,source:at===Ye?"remote":"offline"}:{...mr(),source:"empty"}:{...mr(),source:"empty"}}catch{return N()?(await ve(te).catch(()=>{}),te?{...te,source:"offline"}:{...mr(),source:"empty"}):{...mr(),source:"empty"}}finally{(it=Ie.release)==null||it.call(Ie)}},close:()=>{be("closed"),$=!0,q()}}}const Ad="p2g_story_question_archive_enabled";function FE(){return typeof localStorage<"u"&&localStorage.getItem(Ad)==="1"}function HE(e){const t=l.useRef(FE()),r=l.useRef(null);r.current||(r.current=BE({ownerId:e,enabled:t.current,isEnabled:()=>t.current,transport:UE()}));const a=r.current,[n,i]=l.useState(t.current),[o,c]=l.useState(a.getState);l.useEffect(()=>{const Y=a.subscribe(c);return()=>{Y()}},[a]),l.useEffect(()=>{a.beginSession(e)},[a,e]);const f=l.useCallback(Y=>{t.current=Y,i(Y),a.setEnabled(Y);try{localStorage.setItem(Ad,Y?"1":"0")}catch{}},[a]);l.useEffect(()=>{var q;if(!o.pending.length&&((q=o.lastFailure)==null?void 0:q.code)!=="PENDING_UNSAVED")return;const Y=K=>{K.preventDefault(),K.returnValue=""};return window.addEventListener("beforeunload",Y),()=>window.removeEventListener("beforeunload",Y)},[o.lastFailure,o.pending.length]);const d=l.useCallback((Y=e)=>a.beginSession(Y),[a,e]),S=l.useCallback(Y=>a.invalidateSession(Y),[a]),b=l.useCallback(()=>a.invalidateRequest(),[a]),w=l.useCallback(Y=>a.prepareCapture(Y),[a]),v=l.useCallback((Y,q)=>a.completeCapture(Y,q),[a]),j=l.useCallback(Y=>a.assignSave(Y),[a]),$=l.useCallback(Y=>a.snapshotReady(Y),[a]),V=l.useCallback(Y=>a.loadOffline(Y),[a]);return l.useMemo(()=>({enabled:n,setEnabled:f,state:o,beginSession:d,invalidateSession:S,invalidateRequest:b,prepareCapture:w,completeCapture:v,assignSave:j,snapshotReady:$,loadArchive:V}),[j,d,v,n,b,S,V,f,$,o])}const jE=[25,50,75,100],wr=e=>String(e||"").trim().slice(0,128),qu=e=>Math.max(0,Math.trunc(Number(e)||0)),Qu=e=>{const t=globalThis.crypto;return typeof(t==null?void 0:t.randomUUID)=="function"?`${e}-${t.randomUUID()}`:`${e}-${Date.now()}-${Math.random().toString(36).slice(2,14)}`};function VE(e){const t=e.now||Date.now,r=e.idFactory||(()=>Qu("metric")),a=wr(e.playbackSessionId||Qu("playback")),n=wr(e.jobId),i=wr(e.generationTrace.variantId),o=new Set,c=new Map;let f=!1;const d=b=>{f||e.emit({version:1,eventId:wr(r()),jobId:n,variantId:i,featureSnapshotVersion:2,occurredAtMs:t(),source:"client",playbackSessionId:a,...b})};d({type:"playback_started"});const S=b=>{for(const w of jE)w>b||o.has(w)||(o.add(w),d({type:"playback_progress",milestonePercent:w}))};return{playbackSessionId:a,recordProgress({currentFrameIndex:b,totalFrameCount:w,frameCountFinal:v}){if(f||!v)return;const j=qu(w);if(j===0)return;const $=Math.min(j,qu(b)+1);S(Math.floor($/j*100))},presentQuiz(b){const w=wr(b);!f&&w&&!c.has(w)&&c.set(w,t())},answerQuiz(b,w){const v=wr(b),j=wr(w);if(f||!v||!j)return;const $=c.get(v)??t();d({type:"quiz_answered",quizId:v,selectedOptionId:j,dwellTimeMs:Math.min(864e5,Math.max(0,t()-$))}),c.delete(v)},recordRaisedHand(b){const w=wr(b);w&&d({type:"raised_hand_used",sectionId:w})},finish(b){if(f)return;b==="completed"&&S(100);const w=[...o].reduce((v,j)=>Math.max(v,j),0);d({type:"playback_finished",outcome:b,lastMilestonePercent:w}),f=!0}}}function GE(e={}){const t=e.endpoint||"/api/entertainment/playback-metrics",r=e.fetcher||fetch,a=Math.max(1,Math.min(20,Math.trunc(e.maxBatchSize||10)));let n=[],i=null;const o=(c=!1)=>{if(i||n.length===0)return i||Promise.resolve();const f=n.splice(0,a);let d=!1;return i=r(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({events:f}),keepalive:c}).then(S=>{d=S.ok,S.ok||(n=[...f,...n].slice(0,100))}).catch(()=>{n=[...f,...n].slice(0,100)}).finally(()=>{i=null,d&&!c&&n.length>0&&o(!1)}),i};return{emit(c){n.push(c),(c.type==="playback_finished"||n.length>=a)&&o(c.type==="playback_finished")},flush:o}}function YE(e){const t=String(e),r=[];return{toOffset:n,toPoint:a};function a(i){if(typeof i=="number"&&i>-1&&i<=t.length){let o=0;for(;;){let c=r[o];if(c===void 0){const f=Ku(t,r[o-1]);c=f===-1?t.length+1:f+1,r[o]=c}if(c>i)return{line:o+1,column:i-(o>0?r[o-1]:0)+1,offset:i};o++}}}function n(i){if(i&&typeof i.line=="number"&&typeof i.column=="number"&&!Number.isNaN(i.line)&&!Number.isNaN(i.column)){for(;r.length<i.line;){const c=r[r.length-1],f=Ku(t,c),d=f===-1?t.length+1:f+1;if(c===d)break;r.push(d)}const o=(i.line>1?r[i.line-2]:0)+i.column-1;if(o<r[i.line-1])return o}}}function Ku(e,t){const r=e.indexOf("\r",t),a=e.indexOf(`
214`,t);return a===-1?r:r===-1||r+1===a?a:r<a?r:a}const Id={}.hasOwnProperty,zE=Object.prototype;function WE(e,t){const r=t||{};return Fo({file:r.file||void 0,location:!1,schema:r.space==="svg"?Rl:Nl,verbose:r.verbose||!1},e)}function Fo(e,t){let r;switch(t.nodeName){case"#comment":{const a=t;return r={type:"comment",value:a.data},Ss(e,a,r),r}case"#document":case"#document-fragment":{const a=t,n="mode"in a?a.mode==="quirks"||a.mode==="limited-quirks":!1;if(r={type:"root",children:yd(e,t.childNodes),data:{quirksMode:n}},e.file&&e.location){const i=String(e.file),o=YE(i),c=o.toPoint(0),f=o.toPoint(i.length);r.position={start:c,end:f}}return r}case"#documentType":{const a=t;return r={type:"doctype"},Ss(e,a,r),r}case"#text":{const a=t;return r={type:"text",value:a.value},Ss(e,a,r),r}default:return r=$E(e,t),r}}function yd(e,t){let r=-1;const a=[];for(;++r<t.length;){const n=Fo(e,t[r]);a.push(n)}return a}function $E(e,t){const r=e.schema;e.schema=t.namespaceURI===Fh.svg?Rl:Nl;let a=-1;const n={};for(;++a<t.attrs.length;){const c=t.attrs[a],f=(c.prefix?c.prefix+":":"")+c.name;Id.call(zE,f)||(n[f]=c.value)}
vendor: 9,983 bytes, line 214
214const o=(e.schema.space==="svg"?Hh:jh)(t.tagName,n,yd(e,t.childNodes));if(Ss(e,t,o),o.tagName==="template"){const c=t,f=c.sourceCodeLocation,d=f&&f.startTag&&Ta(f.startTag),S=f&&f.endTag&&Ta(f.endTag),b=Fo(e,c.content);d&&S&&e.file&&(b.position={start:d.end,end:S.start}),o.content=b}return e.schema=r,o}function Ss(e,t,r){if("sourceCodeLocation"in t&&t.sourceCodeLocation&&e.file){const a=qE(e,r,t.sourceCodeLocation);a&&(e.location=!0,r.position=a)}}function qE(e,t,r){const a=Ta(r);if(t.type==="element"){const n=t.children[t.children.length-1];if(a&&!r.endTag&&n&&n.position&&n.position.end&&(a.end=Object.assign({},n.position.end)),e.verbose){const i={};let o;if(r.attrs)for(o in r.attrs)Id.call(r.attrs,o)&&(i[Mh(e.schema,o).property]=Ta(r.attrs[o]));Uh(r.startTag);const c=Ta(r.startTag),f=r.endTag?Ta(r.endTag):void 0,d={opening:c};f&&(d.closing=f),d.properties=i,t.data={position:d}}}return a}function Ta(e){const t=Xu({line:e.startLine,column:e.startCol,offset:e.startOffset}),r=Xu({line:e.endLine,column:e.endCol,offset:e.endOffset});return t||r?{start:t,end:r}:void 0}function Xu(e){return e.line&&e.column?e:void 0}const QE=new Set([65534,65535,131070,131071,196606,196607,262142,262143,327678,327679,393214,393215,458750,458751,524286,524287,589822,589823,655358,655359,720894,720895,786430,786431,851966,851967,917502,917503,983038,983039,1048574,1048575,1114110,1114111]),Qe="�";var h;(function(e){e[e.EOF=-1]="EOF",e[e.NULL=0]="NULL",e[e.TABULATION=9]="TABULATION",e[e.CARRIAGE_RETURN=13]="CARRIAGE_RETURN",e[e.LINE_FEED=10]="LINE_FEED",e[e.FORM_FEED=12]="FORM_FEED",e[e.SPACE=32]="SPACE",e[e.EXCLAMATION_MARK=33]="EXCLAMATION_MARK",e[e.QUOTATION_MARK=34]="QUOTATION_MARK",e[e.AMPERSAND=38]="AMPERSAND",e[e.APOSTROPHE=39]="APOSTROPHE",e[e.HYPHEN_MINUS=45]="HYPHEN_MINUS",e[e.SOLIDUS=47]="SOLIDUS",e[e.DIGIT_0=48]="DIGIT_0",e[e.DIGIT_9=57]="DIGIT_9",e[e.SEMICOLON=59]="SEMICOLON",e[e.LESS_THAN_SIGN=60]="LESS_THAN_SIGN",e[e.EQUALS_SIGN=61]="EQUALS_SIGN",e[e.GREATER_THAN_SIGN=62]="GREATER_THAN_SIGN",e[e.QUESTION_MARK=63]="QUESTION_MARK",e[e.LATIN_CAPITAL_A=65]="LATIN_CAPITAL_A",e[e.LATIN_CAPITAL_Z=90]="LATIN_CAPITAL_Z",e[e.RIGHT_SQUARE_BRACKET=93]="RIGHT_SQUARE_BRACKET",e[e.GRAVE_ACCENT=96]="GRAVE_ACCENT",e[e.LATIN_SMALL_A=97]="LATIN_SMALL_A",e[e.LATIN_SMALL_Z=122]="LATIN_SMALL_Z"})(h||(h={}));const It={DASH_DASH:"--",CDATA_START:"[CDATA[",DOCTYPE:"doctype",SCRIPT:"script",PUBLIC:"public",SYSTEM:"system"};function _d(e){return e>=55296&&e<=57343}function KE(e){return e>=56320&&e<=57343}function XE(e,t){return(e-55296)*1024+9216+t}function Cd(e){return e!==32&&e!==10&&e!==13&&e!==9&&e!==12&&e>=1&&e<=31||e>=127&&e<=159}function wd(e){return e>=64976&&e<=65007||QE.has(e)}var L;(function(e){e.controlCharacterInInputStream="control-character-in-input-stream",e.noncharacterInInputStream="noncharacter-in-input-stream",e.surrogateInInputStream="surrogate-in-input-stream",e.nonVoidHtmlElementStartTagWithTrailingSolidus="non-void-html-element-start-tag-with-trailing-solidus",e.endTagWithAttributes="end-tag-with-attributes",e.endTagWithTrailingSolidus="end-tag-with-trailing-solidus",e.unexpectedSolidusInTag="unexpected-solidus-in-tag",e.unexpectedNullCharacter="unexpected-null-character",e.unexpectedQuestionMarkInsteadOfTagName="unexpected-question-mark-instead-of-tag-name",e.invalidFirstCharacterOfTagName="invalid-first-character-of-tag-name",e.unexpectedEqualsSignBeforeAttributeName="unexpected-equals-sign-before-attribute-name",e.missingEndTagName="missing-end-tag-name",e.unexpectedCharacterInAttributeName="unexpected-character-in-attribute-name",e.unknownNamedCharacterReference="unknown-named-character-reference",e.missingSemicolonAfterCharacterReference="missing-semicolon-after-character-reference",e.unexpectedCharacterAfterDoctypeSystemIdentifier="unexpected-character-after-doctype-system-identifier",e.unexpectedCharacterInUnquotedAttributeValue="unexpected-character-in-unquoted-attribute-value",e.eofBeforeTagName="eof-before-tag-name",e.eofInTag="eof-in-tag",e.missingAttributeValue="missing-attribute-value",e.missingWhitespaceBetweenAttributes="missing-whitespace-between-attributes",e.missingWhitespaceAfterDoctypePublicKeyword="missing-whitespace-after-doctype-public-keyword",e.missingWhitespaceBetweenDoctypePublicAndSystemIdentifiers="missing-whitespace-between-doctype-public-and-system-identifiers",e.missingWhitespaceAfterDoctypeSystemKeyword="missing-whitespace-after-doctype-system-keyword",e.missingQuoteBeforeDoctypePublicIdentifier="missing-quote-before-doctype-public-identifier",e.missingQuoteBeforeDoctypeSystemIdentifier="missing-quote-before-doctype-system-identifier",e.missingDoctypePublicIdentifier="missing-doctype-public-identifier",e.missingDoctypeSystemIdentifier="missing-doctype-system-identifier",e.abruptDoctypePublicIdentifier="abrupt-doctype-public-identifier",e.abruptDoctypeSystemIdentifier="abrupt-doctype-system-identifier",e.cdataInHtmlContent="cdata-in-html-content",e.incorrectlyOpenedComment="incorrectly-opened-comment",e.eofInScriptHtmlCommentLikeText="eof-in-script-html-comment-like-text",e.eofInDoctype="eof-in-doctype",e.nestedComment="nested-comment",e.abruptClosingOfEmptyComment="abrupt-closing-of-empty-comment",e.eofInComment="eof-in-comment",e.incorrectlyClosedComment="incorrectly-closed-comment",e.eofInCdata="eof-in-cdata",e.absenceOfDigitsInNumericCharacterReference="absence-of-digits-in-numeric-character-reference",e.nullCharacterReference="null-character-reference",e.surrogateCharacterReference="surrogate-character-reference",e.characterReferenceOutsideUnicodeRange="character-reference-outside-unicode-range",e.controlCharacterReference="control-character-reference",e.noncharacterCharacterReference="noncharacter-character-reference",e.missingWhitespaceBeforeDoctypeName="missing-whitespace-before-doctype-name",e.missingDoctypeName="missing-doctype-name",e.invalidCharacterSequenceAfterDoctypeName="invalid-character-sequence-after-doctype-name",e.duplicateAttribute="duplicate-attribute",e.nonConformingDoctype="non-conforming-doctype",e.missingDoctype="missing-doctype",e.misplacedDoctype="misplaced-doctype",e.endTagWithoutMatchingOpenElement="end-tag-without-matching-open-element",e.closingOfElementWithOpenChildElements="closing-of-element-with-open-child-elements",e.disallowedContentInNoscriptInHead="disallowed-content-in-noscript-in-head",e.openElementsLeftAfterEof="open-elements-left-after-eof",e.abandonedHeadElementChild="abandoned-head-element-child",e.misplacedStartTagForHeadElement="misplaced-start-tag-for-head-element",e.nestedNoscriptInHead="nested-noscript-in-head",e.eofInElementThatCanContainOnlyText="eof-in-element-that-can-contain-only-text"})(L||(L={}));const JE=65536;class ZE{constructor(t){this.handler=t,this.html="",this.pos=-1,this.lastGapPos=-2,this.gapStack=[],this.skipNextNewLine=!1,this.lastChunkWritten=!1,this.endOfChunkHit=!1,this.bufferWaterline=JE,this.isEol=!1,this.lineStartPos=0,this.droppedBufferSize=0,this.line=1,this.lastErrOffset=-1}get col(){return this.pos-this.lineStartPos+ +(this.lastGapPos!==this.pos)}get offset(){return this.droppedBufferSize+this.pos}getError(t,r){const{line:a,col:n,offset:i}=this,o=n+r,c=i+r;return{code:t,startLine:a,endLine:a,startCol:o,endCol:o,startOffset:c,endOffset:c}}_err(t){this.handler.onParseError&&this.lastErrOffset!==this.offset&&(this.lastErrOffset=this.offset,this.handler.onParseError(this.getError(t,0)))}_addGap(){this.gapStack.push(this.lastGapPos),this.lastGapPos=this.pos}_processSurrogate(t){if(this.pos!==this.html.length-1){const r=this.html.charCodeAt(this.pos+1);if(KE(r))return this.pos++,this._addGap(),XE(t,r)}else if(!this.lastChunkWritten)return this.endOfChunkHit=!0,h.EOF;return this._err(L.surrogateInInputStream),t}willDropParsedChunk(){return this.pos>this.bufferWaterline}dropParsedChunk(){this.willDropParsedChunk()&&(this.html=this.html.substring(this.pos),this.lineStartPos-=this.pos,this.droppedBufferSize+=this.pos,this.pos=0,this.lastGapPos=-2,this.gapStack.length=0)}write(t,r){this.html.length>0?this.html+=t:this.html=t,this.endOfChunkHit=!1,this.lastChunkWritten=r}insertHtmlAtCurrentPos(t){this.html=this.html.substring(0,this.pos+1)+t+this.html.substring(this.pos+1),this.endOfChunkHit=!1}startsWith(t,r){if(this.pos+t.length>this.html.length)return this.endOfChunkHit=!this.lastChunkWritten,!1;if(r)return this.html.startsWith(t,this.pos);for(let a=0;a<t.length;a++)if((this.html.charCodeAt(this.pos+a)|32)!==t.charCodeAt(a))return!1;return!0}peek(t){const r=this.pos+t;if(r>=this.html.length)return this.endOfChunkHit=!this.lastChunkWritten,h.EOF;const a=this.html.charCodeAt(r);return a===h.CARRIAGE_RETURN?h.LINE_FEED:a}advance(){if(this.pos++,this.isEol&&(this.isEol=!1,this.line++,this.lineStartPos=this.pos),this.pos>=this.html.length)return this.endOfChunkHit=!this.lastChunkWritten,h.EOF;let t=this.html.charCodeAt(this.pos);return t===h.CARRIAGE_RETURN?(this.isEol=!0,this.skipNextNewLine=!0,h.LINE_FEED):t===h.LINE_FEED&&(this.isEol=!0,this.skipNextNewLine)?(this.line--,this.skipNextNewLine=!1,this._addGap(),this.advance()):(this.skipNextNewLine=!1,_d(t)&&(t=this._processSurrogate(t)),this.handler.onParseError===null||t>31&&t<127||t===h.LINE_FEED||t===h.CARRIAGE_RETURN||t>159&&t<64976||this._checkForProblematicCharacters(t),t)}_checkForProblematicCharacters(t){Cd(t)?this._err(L.controlCharacterInInputStream):wd(t)&&this._err(L.noncharacterInInputStream)}retreat(t){for(this.pos-=t;this.pos<this.lastGapPos;)this.lastGapPos=this.gapStack.pop(),this.pos--;this.isEol=!1}}var De;(function(e){e[e.CHARACTER=0]="CHARACTER",e[e.NULL_CHARACTER=1]="NULL_CHARACTER",e[e.WHITESPACE_CHARACTER=2]="WHITESPACE_CHARACTER",e[e.START_TAG=3]="START_TAG",e[e.END_TAG=4]="END_TAG",e[e.COMMENT=5]="COMMENT",e[e.DOCTYPE=6]="DOCTYPE",e[e.EOF=7]="EOF",e[e.HIBERNATION=8]="HIBERNATION"})(De||(De={}));function Rd(e,t){for(let r=e.attrs.length-1;r>=0;r--)if(e.attrs[r].name===t)return e.attrs[r].value;return null}const eb=new Uint16Array('
vendor: 16,129 bytes, line 214
214ᵁ<Õıʊҝջאٵ۞ޢߖࠏ੊ઑඡ๭༉༦჊ረዡᐕᒝᓃᓟᔥ\0\0\0\0\0\0ᕫᛍᦍᰒᷝ὾⁠↰⊍⏀⏻⑂⠤⤒ⴈ⹈⿎〖㊺㘹㞬㣾㨨㩱㫠㬮ࠀEMabcfglmnoprstu\\bfms�„‹•˜¦³¹ÈÏlig耻Æ䃆P耻&䀦cute耻Á䃁reve;䄂Āiyx}rc耻Â䃂;䐐r;쀀𝔄rave耻À䃀pha;䎑acr;䄀d;橓Āgp¡on;䄄f;쀀𝔸plyFunction;恡ing耻Å䃅Ācs¾Ãr;쀀𝒜ign;扔ilde耻Ã䃃ml耻Ä䃄ЀaceforsuåûþėĜĢħĪĀcrêòkslash;或Ŷöø;æ«§ed;挆y;䐑ƀcrtąċĔause;戵noullis;愬a;䎒r;쀀𝔅pf;쀀𝔹eve;䋘còēmpeq;扎܀HOacdefhilorsuōőŖƀƞƢƵƷƺǜȕɳɸɾcy;䐧PY耻©䂩ƀcpyŝŢźute;䄆Ā;iŧŨ拒talDifferentialD;慅leys;愭ȀaeioƉƎƔƘron;䄌dil耻Ç䃇rc;䄈nint;戰ot;䄊ĀdnƧƭilla;䂸terDot;䂷òſi;䎧rcleȀDMPTLJNjǑǖot;抙inus;抖lus;投imes;抗oĀcsǢǸkwiseContourIntegral;戲eCurlyĀDQȃȏoubleQuote;思uote;怙ȀlnpuȞȨɇɕonĀ;eȥȦ户;橴ƀgitȯȶȺruent;扡nt;戯ourIntegral;戮ĀfrɌɎ;愂oduct;成nterClockwiseContourIntegral;戳oss;樯cr;쀀𝒞pĀ;Cʄʅ拓ap;才րDJSZacefiosʠʬʰʴʸˋ˗ˡ˦̳ҍĀ;oŹʥtrahd;椑cy;䐂cy;䐅cy;䐏ƀgrsʿ˄ˇger;怡r;憡hv;櫤Āayː˕ron;䄎;䐔lĀ;t˝˞戇a;䎔r;쀀𝔇Āaf˫̧Ācm˰̢riticalȀADGT̖̜̀̆cute;䂴oŴ̋̍;䋙bleAcute;䋝rave;䁠ilde;䋜ond;拄ferentialD;慆Ѱ̽\0\0\0͔͂\0Ѕf;쀀𝔻ƀ;DE͈͉͍䂨ot;惜qual;扐blèCDLRUVͣͲ΂ϏϢϸontourIntegraìȹoɴ͹\0\0ͻ»͉nArrow;懓Āeo·ΤftƀARTΐΖΡrrow;懐ightArrow;懔eåˊngĀLRΫτeftĀARγιrrow;柸ightArrow;柺ightArrow;柹ightĀATϘϞrrow;懒ee;抨pɁϩ\0\0ϯrrow;懑ownArrow;懕erticalBar;戥ǹABLRTaВЪаўѿͼrrowƀ;BUНОТ憓ar;椓pArrow;懵reve;䌑eft˒к\0ц\0ѐightVector;楐eeVector;楞ectorĀ;Bљњ憽ar;楖ightǔѧ\0ѱeeVector;楟ectorĀ;BѺѻ懁ar;楗eeĀ;A҆҇护rrow;憧ĀctҒҗr;쀀𝒟rok;䄐ࠀNTacdfglmopqstuxҽӀӄӋӞӢӧӮӵԡԯԶՒ՝ՠեG;䅊H耻Ð䃐cute耻É䃉ƀaiyӒӗӜron;䄚rc耻Ê䃊;䐭ot;䄖r;쀀𝔈rave耻È䃈ement;戈ĀapÓºÓ¾cr;䄒tyɓԆ\0\0ԒmallSquare;旻erySmallSquare;斫ĀgpÔ¦Ôªon;䄘f;쀀𝔼silon;䎕uĀaiԼՉlĀ;TՂՃ橵ilde;扂librium;懌Āci՗՚r;愰m;橳a;䎗ml耻Ë䃋ĀipÕªÕ¯sts;戃onentialE;慇ʀcfiosօֈ֍ֲ׌y;䐤r;쀀𝔉lledɓ֗\0\0Ö£mallSquare;旼erySmallSquare;斪Ͱֺ\0Ö¿\0\0ׄf;쀀𝔽All;戀riertrf;愱cò׋؀JTabcdfgorstר׬ׯ׺؀ؒؖ؛؝أ٬ٲcy;䐃耻>䀾mmaĀ;d׷׸䎓;䏜reve;䄞ƀeiy؇،ؐdil;䄢rc;䄜;䐓ot;䄠r;쀀𝔊;拙pf;쀀𝔾eater̀EFGLSTصلَٖٛ٦qualĀ;Lؾؿ扥ess;招ullEqual;执reater;檢ess;扷lantEqual;橾ilde;扳cr;쀀𝒢;扫ЀAacfiosuڅڋږڛڞڪھۊRDcy;䐪Āctڐڔek;䋇;䁞irc;䄤r;愌lbertSpace;愋ǰگ\0Ú²f;愍izontalLine;攀Āctۃۅòکrok;䄦mpńېۘownHumðįqual;扏܀EJOacdfgmnostuۺ۾܃܇܎ܚܞܡܨ݄ݸދޏޕcy;䐕lig;䄲cy;䐁cute耻Í䃍Āiyܓܘrc耻Î䃎;䐘ot;䄰r;愑rave耻Ì䃌ƀ;apܠܯܿĀcgÜ´Ü·r;䄪inaryI;慈lieóϝǴ݉\0ݢĀ;eݍݎ戬Āgrݓݘral;戫section;拂isibleĀCTݬݲomma;恣imes;恢ƀgptݿރވon;䄮f;쀀𝕀a;䎙cr;愐ilde;䄨ǫޚ\0ޞcy;䐆l耻Ï䃏ʀcfosuެ޷޼߂ߐĀiyÞ±Þµrc;䄴;䐙r;쀀𝔍pf;쀀𝕁ǣ߇\0ߌr;쀀𝒥rcy;䐈kcy;䐄΀HJacfosߤߨ߽߬߱ࠂࠈcy;䐥cy;䐌ppa;䎚Āeyß¶ß»dil;䄶;䐚r;쀀𝔎pf;쀀𝕂cr;쀀𝒦րJTaceflmostࠥࠩࠬࡐࡣ঳সে্਷ੇcy;䐉耻<䀼ʀcmnpr࠷࠼ࡁࡄࡍute;䄹bda;䎛g;柪lacetrf;愒r;憞ƀaeyࡗ࡜ࡡron;䄽dil;䄻;䐛Āfsࡨ॰tԀACDFRTUVarࡾࢩࢱࣦ࣠ࣼयज़ΐ४Ānrࢃ࢏gleBracket;柨rowƀ;BR࢙࢚࢞憐ar;懤ightArrow;懆eiling;挈oǵࢷ\0ࣃbleBracket;柦nǔࣈ\0࣒eeVector;楡ectorĀ;Bࣛࣜ懃ar;楙loor;挊ightĀAV࣯ࣵrrow;憔ector;楎Āerँगeƀ;AVउऊऐ抣rrow;憤ector;楚iangleƀ;BEतथऩ抲ar;槏qual;抴pƀDTVषूौownVector;楑eeVector;楠ectorĀ;Bॖॗ憿ar;楘ectorĀ;B॥०憼ar;楒ightáΜs̀EFGLSTॾঋকঝঢভqualGreater;拚ullEqual;扦reater;扶ess;檡lantEqual;橽ilde;扲r;쀀𝔏Ā;eঽা拘ftarrow;懚idot;䄿ƀnpw৔ਖਛgȀLRlr৞৷ਂਐeftĀAR০৬rrow;柵ightArrow;柷ightArrow;柶eftĀarγਊightáοightáϊf;쀀𝕃erĀLRਢਬeftArrow;憙ightArrow;憘ƀchtਾੀੂòࡌ;憰rok;䅁;扪Ѐacefiosuਗ਼੝੠੷੼અઋ઎p;椅y;䐜Ādl੥੯iumSpace;恟lintrf;愳r;쀀𝔐nusPlus;戓pf;쀀𝕄cò੶;䎜ҀJacefostuણધભીଔଙඑ඗ඞcy;䐊cute;䅃ƀaey઴હાron;䅇dil;䅅;䐝ƀgswે૰଎ativeƀMTV૓૟૨ediumSpace;怋hiĀcn૦૘ë૙eryThiî૙tedĀGL૸ଆreaterGreateòٳessLesóੈLine;䀊r;쀀𝔑ȀBnptଢନଷ଺reak;恠BreakingSpace;䂠f;愕ڀ;CDEGHLNPRSTV୕ୖ୪୼஡௫ఄ౞಄ದ೘ൡඅ櫬Āou୛୤ngruent;扢pCap;扭oubleVerticalBar;戦ƀlqxஃஊ஛ement;戉ualĀ;Tஒஓ扠ilde;쀀≂̸ists;戄reater΀;EFGLSTஶஷ஽௉௓௘௥扯qual;扱ullEqual;쀀≧̸reater;쀀≫̸ess;批lantEqual;쀀⩾̸ilde;扵umpń௲௽ownHump;쀀≎̸qual;쀀≏̸eĀfsఊధtTriangleƀ;BEచఛడ拪ar;쀀⧏̸qual;括s̀;EGLSTవశ఼ౄోౘ扮qual;扰reater;扸ess;쀀≪̸lantEqual;쀀⩽̸ilde;扴estedĀGL౨౹reaterGreater;쀀⪢̸essLess;쀀⪡̸recedesƀ;ESಒಓಛ技qual;쀀⪯̸lantEqual;拠ĀeiಫಹverseElement;戌ghtTriangleƀ;BEೋೌ೒拫ar;쀀⧐̸qual;拭ĀquೝഌuareSuĀbp೨೹setĀ;E೰ೳ쀀⊏̸qual;拢ersetĀ;Eഃആ쀀⊐̸qual;拣ƀbcpഓതൎsetĀ;Eഛഞ쀀⊂⃒qual;抈ceedsȀ;ESTലള഻െ抁qual;쀀⪰̸lantEqual;拡ilde;쀀≿̸ersetĀ;E൘൛쀀⊃⃒qual;抉ildeȀ;EFT൮൯൵ൿ扁qual;扄ullEqual;扇ilde;扉erticalBar;戤cr;쀀𝒩ilde耻Ñ䃑;䎝܀Eacdfgmoprstuvලෂ෉෕ෛ෠෧෼ขภยา฿ไlig;䅒cute耻Ó䃓Āiy෎ීrc耻Ô䃔;䐞blac;䅐r;쀀𝔒rave耻Ò䃒ƀaei෮ෲ෶cr;䅌ga;䎩cron;䎟pf;쀀𝕆enCurlyĀDQฎบoubleQuote;怜uote;怘;橔Āclวฬr;쀀𝒪ash耻Ø䃘iŬื฼de耻Õ䃕es;樷ml耻Ö䃖erĀBP๋๠Āar๐๓r;怾acĀek๚๜;揞et;掴arenthesis;揜Ҁacfhilors๿ງຊຏຒດຝະ໼rtialD;戂y;䐟r;쀀𝔓i;䎦;䎠usMinus;䂱Āipຢອncareplanåڝf;愙Ȁ;eio຺ູ໠໤檻cedesȀ;EST່້໏໚扺qual;檯lantEqual;扼ilde;找me;怳Ādp໩໮uct;戏ortionĀ;aȥ໹l;戝Āci༁༆r;쀀𝒫;䎨ȀUfos༑༖༛༟OT耻"䀢r;쀀𝔔pf;愚cr;쀀𝒬؀BEacefhiorsu༾གྷཇའཱིྦྷྪྭ႖ႩႴႾarr;椐G耻®䂮ƀcnrཎནབute;䅔g;柫rĀ;tཛྷཝ憠l;椖ƀaeyཧཬཱron;䅘dil;䅖;䐠Ā;vླྀཹ愜erseĀEUྂྙĀlq྇ྎement;戋uilibrium;懋pEquilibrium;楯r»ཹo;䎡ghtЀACDFTUVa࿁࿫࿳ဢဨၛႇϘĀnr࿆࿒gleBracket;柩rowƀ;BL࿜࿝࿡憒ar;懥eftArrow;懄eiling;按oǵ࿹\0စbleBracket;柧nǔည\0နeeVector;楝ectorĀ;Bဝသ懂ar;楕loor;挋Āerိ၃eƀ;AVဵံြ抢rrow;憦ector;楛iangleƀ;BEၐၑၕ抳ar;槐qual;抵pƀDTVၣၮၸownVector;楏eeVector;楜ectorĀ;Bႂႃ憾ar;楔ectorĀ;B႑႒懀ar;楓Āpuႛ႞f;愝ndImplies;楰ightarrow;懛ĀchႹႼr;愛;憱leDelayed;槴ڀHOacfhimoqstuფჱჷჽᄙᄞᅑᅖᅡᅧᆵᆻᆿĀCcჩხHcy;䐩y;䐨FTcy;䐬cute;䅚ʀ;aeiyᄈᄉᄎᄓᄗ檼ron;䅠dil;䅞rc;䅜;䐡r;쀀𝔖ortȀDLRUᄪᄴᄾᅉownArrow»ОeftArrow»࢚ightArrow»࿝pArrow;憑gma;䎣allCircle;战pf;쀀𝕊ɲᅭ\0\0ᅰt;戚areȀ;ISUᅻᅼᆉᆯ斡ntersection;抓uĀbpᆏᆞsetĀ;Eᆗᆘ抏qual;抑ersetĀ;Eᆨᆩ抐qual;抒nion;抔cr;쀀𝒮ar;拆ȀbcmpᇈᇛሉላĀ;sᇍᇎ拐etĀ;Eᇍᇕqual;抆ĀchᇠህeedsȀ;ESTᇭᇮᇴᇿ扻qual;檰lantEqual;扽ilde;承Tháྌ;我ƀ;esሒሓሣ拑rsetĀ;Eሜም抃qual;抇et»ሓրHRSacfhiorsሾቄ቉ቕ቞ቱቶኟዂወዑORN耻Þ䃞ADE;愢ĀHc቎ቒcy;䐋y;䐦Ābuቚቜ;䀉;䎤ƀaeyብቪቯron;䅤dil;䅢;䐢r;쀀𝔗Āeiቻ኉Dzኀ\0ኇefore;戴a;䎘Ācn኎ኘkSpace;쀀  Space;怉ldeȀ;EFTካኬኲኼ戼qual;扃ullEqual;扅ilde;扈pf;쀀𝕋ipleDot;惛Āctዖዛr;쀀𝒯rok;䅦ૡዷጎጚጦ\0ጬጱ\0\0\0\0\0ጸጽ፷ᎅ\0᏿ᐄᐊᐐĀcrዻጁute耻Ú䃚rĀ;oጇገ憟cir;楉rǣጓ\0጖y;䐎ve;䅬Āiyጞጣrc耻Û䃛;䐣blac;䅰r;쀀𝔘rave耻Ù䃙acr;䅪Ādiፁ፩erĀBPፈ፝Āarፍፐr;䁟acĀekፗፙ;揟et;掵arenthesis;揝onĀ;P፰፱拃lus;抎Āgp፻፿on;䅲f;쀀𝕌ЀADETadps᎕ᎮᎸᏄϨᏒᏗᏳrrowƀ;BDᅐᎠᎤar;椒ownArrow;懅ownArrow;憕quilibrium;楮eeĀ;AᏋᏌ报rrow;憥ownáϳerĀLRᏞᏨeftArrow;憖ightArrow;憗iĀ;lᏹᏺ䏒on;䎥ing;䅮cr;쀀𝒰ilde;䅨ml耻Ü䃜ҀDbcdefosvᐧᐬᐰᐳᐾᒅᒊᒐᒖash;披ar;æ««y;䐒ashĀ;lᐻᐼ抩;櫦Āerᑃᑅ;拁ƀbtyᑌᑐᑺar;怖Ā;iᑏᑕcalȀBLSTᑡᑥᑪᑴar;戣ine;䁼eparator;杘ilde;所ThinSpace;怊r;쀀𝔙pf;쀀𝕍cr;쀀𝒱dash;抪ʀcefosᒧᒬᒱᒶᒼirc;䅴dge;拀r;쀀𝔚pf;쀀𝕎cr;쀀𝒲Ȁfiosᓋᓐᓒᓘr;쀀𝔛;䎞pf;쀀𝕏cr;쀀𝒳ҀAIUacfosuᓱᓵᓹᓽᔄᔏᔔᔚᔠcy;䐯cy;䐇cy;䐮cute耻Ý䃝Āiyᔉᔍrc;䅶;䐫r;쀀𝔜pf;쀀𝕐cr;쀀𝒴ml;䅸ЀHacdefosᔵᔹᔿᕋᕏᕝᕠᕤcy;䐖cute;䅹Āayᕄᕉron;䅽;䐗ot;䅻Dzᕔ\0ᕛoWidtè૙a;䎖r;愨pf;愤cr;쀀𝒵௡ᖃᖊᖐ\0ᖰᖶᖿ\0\0\0\0ᗆᗛᗫᙟ᙭\0ᚕ᚛ᚲᚹ\0ᚾcute耻á䃡reve;䄃̀;Ediuyᖜᖝᖡᖣᖨᖭ戾;쀀∾̳;房rc耻â䃢te肻´̆;䐰lig耻æ䃦Ā;r²ᖺ;쀀𝔞rave耻à䃠ĀepᗊᗖĀfpᗏᗔsym;愵èᗓha;䎱ĀapᗟcĀclᗤᗧr;䄁g;樿ɤᗰ\0\0ᘊʀ;adsvᗺᗻᗿᘁᘇ戧nd;橕;橜lope;橘;橚΀;elmrszᘘᘙᘛᘞᘿᙏᙙ戠;榤e»ᘙsdĀ;aᘥᘦ戡ѡᘰᘲᘴᘶᘸᘺᘼᘾ;榨;榩;榪;榫;榬;榭;榮;榯tĀ;vᙅᙆ戟bĀ;dᙌᙍ抾;榝Āptᙔᙗh;戢»¹arr;捼Āgpᙣᙧon;䄅f;쀀𝕒΀;Eaeiop዁ᙻᙽᚂᚄᚇᚊ;æ©°cir;橯;扊d;手s;䀧roxĀ;e዁ᚒñᚃing耻å䃥ƀctyᚡᚦᚨr;쀀𝒶;䀪mpĀ;e዁ᚯñʈilde耻ã䃣ml耻ä䃤Āciᛂᛈoninôɲnt;樑ࠀNabcdefiklnoprsu᛭ᛱᜰ᜼ᝃᝈ᝸᝽០៦ᠹᡐᜍ᤽᥈ᥰot;櫭Ācrᛶ᜞kȀcepsᜀᜅᜍᜓong;扌psilon;䏶rime;怵imĀ;e᜚᜛戽q;拍Ŷᜢᜦee;抽edĀ;gᜬᜭ挅e»ᜭrkĀ;t፜᜷brk;掶Āoyᜁᝁ;䐱quo;怞ʀcmprtᝓ᝛ᝡᝤᝨausĀ;eĊĉptyv;榰séᜌnoõēƀahwᝯ᝱ᝳ;䎲;愶een;扬r;쀀𝔟g΀costuvwឍឝឳេ៕៛៞ƀaiuបពរðݠrc;旯p»፱ƀdptឤឨឭot;樀lus;樁imes;樂ɱឹ\0\0ើcup;樆ar;昅riangleĀdu៍្own;施p;斳plus;樄eåᑄåᒭarow;植ƀako៭ᠦᠵĀcn៲ᠣkƀlst៺֫᠂ozenge;æ§«riangleȀ;dlr᠒᠓᠘᠝斴own;斾eft;旂ight;斸k;搣Ʊᠫ\0ᠳƲᠯ\0á ±;斒;斑4;斓ck;斈ĀeoᠾᡍĀ;qᡃᡆ쀀=⃥uiv;쀀≡⃥t;挐Ȁptwxᡙᡞᡧᡬf;쀀𝕓Ā;tᏋᡣom»Ꮜtie;拈؀DHUVbdhmptuvᢅᢖᢪᢻᣗᣛᣬ᣿ᤅᤊᤐᤡȀLRlrᢎᢐᢒᢔ;敗;敔;敖;敓ʀ;DUduᢡᢢᢤᢦᢨ敐;敦;敩;敤;敧ȀLRlrᢳᢵᢷᢹ;敝;敚;敜;教΀;HLRhlrᣊᣋᣍᣏᣑᣓᣕ救;敬;散;敠;敫;敢;敟ox;槉ȀLRlrᣤᣦᣨᣪ;敕;敒;攐;攌ʀ;DUduڽ᣷᣹᣻᣽;敥;敨;攬;攴inus;抟lus;択imes;抠ȀLRlrᤙᤛᤝ᤟;敛;敘;攘;攔΀;HLRhlrᤰᤱᤳᤵᤷ᤻᤹攂;敪;敡;敞;攼;攤;攜Āevģ᥂bar耻¦䂦Ȁceioᥑᥖᥚᥠr;쀀𝒷mi;恏mĀ;e᜚᜜lƀ;bhᥨᥩᥫ䁜;槅sub;柈Ŭᥴ᥾lĀ;e᥹᥺怢t»᥺pƀ;Eeįᦅᦇ;檮Ā;qۜۛೡᦧ\0᧨ᨑᨕᨲ\0ᨷᩐ\0\0᪴\0\0᫁\0\0ᬡᬮ᭍᭒\0᯽\0ᰌƀcpr᦭ᦲ᧝ute;䄇̀;abcdsᦿᧀᧄ᧊᧕᧙戩nd;橄rcup;橉Āau᧏᧒p;橋p;橇ot;橀;쀀∩︀Āeo᧢᧥t;恁îړȀaeiu᧰᧻ᨁᨅǰ᧵\0᧸s;橍on;䄍dil耻ç䃧rc;䄉psĀ;sᨌᨍ橌m;橐ot;䄋ƀdmnᨛᨠᨦil肻¸ƭptyv;榲t脀¢;eᨭᨮ䂢räƲr;쀀𝔠ƀceiᨽᩀᩍy;䑇ckĀ;mᩇᩈ朓ark»ᩈ;䏇r΀;Ecefms᩟᩠ᩢᩫ᪤᪪᪮旋;槃ƀ;elᩩᩪᩭ䋆q;扗eɡᩴ\0\0᪈rrowĀlr᩼᪁eft;憺ight;憻ʀRSacd᪒᪔᪖᪚᪟»ཇ;擈st;抛irc;抚ash;抝nint;樐id;櫯cir;槂ubsĀ;u᪻᪼晣it»᪼ˬ᫇᫔᫺\0ᬊonĀ;eᫍᫎ䀺Ā;qÇÆɭ᫙\0\0á«¢aĀ;t᫞᫟䀬;䁀ƀ;fl᫨᫩᫫戁îᅠeĀmx᫱᫶ent»᫩eóɍǧ᫾\0ᬇĀ;dኻᬂot;æ©­nôɆƀfryᬐᬔᬗ;쀀𝕔oäɔ脀©;sŕᬝr;愗Āaoᬥᬩrr;憵ss;朗Ācuᬲᬷr;쀀𝒸Ābpᬼ᭄Ā;eᭁᭂ櫏;櫑Ā;eᭉᭊ櫐;櫒dot;拯΀delprvw᭠᭬᭷ᮂᮬᯔ᯹arrĀlr᭨᭪;椸;椵ɰ᭲\0\0á­µr;拞c;拟arrĀ;p᭿ᮀ憶;椽̀;bcdosᮏᮐᮖᮡᮥᮨ截rcap;橈Āauᮛᮞp;橆p;橊ot;抍r;橅;쀀∪︀Ȁalrv᮵ᮿᯞᯣrrĀ;mᮼᮽ憷;椼yƀevwᯇᯔᯘqɰᯎ\0\0ᯒreã᭳uã᭵ee;拎edge;拏en耻¤䂤earrowĀlrᯮ᯳eft»ᮀight»ᮽeäᯝĀciᰁᰇoninôǷnt;戱lcty;挭ঀAHabcdefhijlorstuwz᰸᰻᰿ᱝᱩᱵᲊᲞᲬᲷ᳻᳿ᴍᵻᶑᶫᶻ᷆᷍rò΁ar;楥Ȁglrs᱈ᱍ᱒᱔ger;怠eth;愸òᄳhĀ;vᱚᱛ怐»ऊūᱡᱧarow;椏aã̕Āayᱮᱳron;䄏;䐴ƀ;ao̲ᱼᲄĀgrʿᲁr;懊tseq;橷ƀglmᲑᲔᲘ耻°䂰ta;䎴ptyv;榱ĀirᲣᲨsht;楿;쀀𝔡arĀlrᲳᲵ»ࣜ»သʀaegsv᳂͸᳖᳜᳠mƀ;oș᳊᳔ndĀ;ș᳑uit;晦amma;䏝in;拲ƀ;io᳧᳨᳸䃷de脀÷;oá³§á³°ntimes;拇nø᳷cy;䑒cɯᴆ\0\0ᴊrn;挞op;挍ʀlptuwᴘᴝᴢᵉᵕlar;䀤f;쀀𝕕ʀ;emps̋ᴭᴷᴽᵂqĀ;d͒ᴳot;扑inus;戸lus;戔quare;抡blebarwedgåúnƀadhᄮᵝᵧownarrowóᲃarpoonĀlrᵲᵶefôᲴighôᲶŢᵿᶅkaro÷གɯᶊ\0\0ᶎrn;挟op;挌ƀcotᶘᶣᶦĀryᶝᶡ;쀀𝒹;䑕l;æ§¶rok;䄑Ādrá¶°á¶´ot;拱iĀ;fᶺ᠖斿Āah᷀᷃ròЩaòྦangle;榦Āci᷒ᷕy;䑟grarr;柿ऀDacdefglmnopqrstuxḁḉḙḸոḼṉṡṾấắẽỡἪἷὄ὎὚ĀDoḆᴴoôᲉĀcsḎḔute耻é䃩ter;橮ȀaioyḢḧḱḶron;䄛rĀ;cḭḮ扖耻ê䃪lon;払;䑍ot;䄗ĀDrṁṅot;扒;쀀𝔢ƀ;rsṐṑṗ檚ave耻è䃨Ā;dṜṝ檖ot;檘Ȁ;ilsṪṫṲṴ檙nters;揧;愓Ā;dṹṺ檕ot;檗ƀapsẅẉẗcr;䄓tyƀ;svẒẓẕ戅et»ẓpĀ1;ẝẤijạả;怄;怅怃ĀgsẪẬ;䅋p;怂ĀgpẴẸon;䄙f;쀀𝕖ƀalsỄỎỒrĀ;sỊị拕l;æ§£us;橱iƀ;lvỚớở䎵on»ớ;䏵ȀcsuvỪỳἋἣĀioữḱrc»Ḯɩỹ\0\0ỻíՈantĀglἂἆtr»ṝess»Ṻƀaeiἒ἖Ἒls;䀽st;扟vĀ;DȵἠD;橸parsl;槥ĀDaἯἳot;打rr;楱ƀcdiἾὁỸr;愯oô͒ĀahὉὋ;䎷耻ð䃰Āmrὓὗl耻ë䃫o;悬ƀcipὡὤὧl;䀡sôծĀeoὬὴctatioîՙnentialåչৡᾒ\0ᾞ\0ᾡᾧ\0\0ῆῌ\0ΐ\0ῦῪ \0 ⁚llingdotseñṄy;䑄male;晀ƀilrᾭᾳ῁lig;耀ffiɩᾹ\0\0á¾½g;耀ffig;耀ffl;쀀𝔣lig;耀filig;쀀fjƀaltῙ῜ῡt;晭ig;耀flns;斱of;䆒ǰ΅\0ῳf;쀀𝕗ĀakֿῷĀ;vῼ´拔;櫙artint;樍Āao‌⁕Ācs‑⁒ႉ‸⁅⁈\0⁐β•‥‧‪‬\0‮耻½䂽;慓耻¼䂼;慕;慙;慛Ƴ‴\0‶;慔;慖ʴ‾⁁\0\0⁃耻¾䂾;慗;慜5;慘ƶ⁌\0⁎;慚;慝8;慞l;恄wn;挢cr;쀀𝒻ࢀEabcdefgijlnorstv₂₉₟₥₰₴⃰⃵⃺⃿℃ℒℸ̗ℾ⅒↞Ā;lٍ₇;檌ƀcmpₐₕ₝ute;䇵maĀ;dₜ᳚䎳;檆reve;䄟Āiy₪₮rc;䄝;䐳ot;䄡Ȁ;lqsؾق₽⃉ƀ;qsؾٌ⃄lanô٥Ȁ;cdl٥⃒⃥⃕c;檩otĀ;o⃜⃝檀Ā;l⃢⃣檂;檄Ā;e⃪⃭쀀⋛︀s;檔r;쀀𝔤Ā;gٳ؛mel;愷cy;䑓Ȁ;Eajٚℌℎℐ;檒;檥;檤ȀEaesℛℝ℩ℴ;扩pĀ;p℣ℤ檊rox»ℤĀ;q℮ℯ檈Ā;q℮ℛim;拧pf;쀀𝕘Āci⅃ⅆr;愊mƀ;el٫ⅎ⅐;檎;檐茀>;cdlqr׮ⅠⅪⅮⅳⅹĀciⅥⅧ;檧r;橺ot;拗Par;榕uest;橼ʀadelsↄⅪ←ٖ↛ǰ↉\0↎proø₞r;楸qĀlqؿ↖lesó₈ií٫Āen↣↭rtneqq;쀀≩︀Å↪ԀAabcefkosy⇄⇇⇱⇵⇺∘∝∯≨≽ròΠȀilmr⇐⇔⇗⇛rsðᒄf»․ilôکĀdr⇠⇤cy;䑊ƀ;cwࣴ⇫⇯ir;楈;憭ar;意irc;䄥ƀalr∁∎∓rtsĀ;u∉∊晥it»∊lip;怦con;抹r;쀀𝔥sĀew∣∩arow;椥arow;椦ʀamopr∺∾≃≞≣rr;懿tht;戻kĀlr≉≓eftarrow;憩ightarrow;憪f;쀀𝕙bar;怕ƀclt≯≴≸r;쀀𝒽asè⇴rok;䄧Ābp⊂⊇ull;恃hen»ᱛૡ⊣\0⊪\0⊸⋅⋎\0⋕⋳\0\0⋸⌢⍧⍢⍿\0⎆⎪⎴cute耻í䃭ƀ;iyݱ⊰⊵rc耻î䃮;䐸Ācx⊼⊿y;䐵cl耻¡䂡ĀfrΟ⋉;쀀𝔦rave耻ì䃬Ȁ;inoܾ⋝⋩⋮Āin⋢⋦nt;樌t;戭fin;槜ta;愩lig;䄳ƀaop⋾⌚⌝ƀcgt⌅⌈⌗r;䄫ƀelpܟ⌏⌓inåގarôܠh;䄱f;抷ed;䆵ʀ;cfotӴ⌬⌱⌽⍁are;愅inĀ;t⌸⌹戞ie;槝doô⌙ʀ;celpݗ⍌⍐⍛⍡al;抺Āgr⍕⍙eróᕣã⍍arhk;樗rod;樼Ȁcgpt⍯⍲⍶⍻y;䑑on;䄯f;쀀𝕚a;䎹uest耻¿䂿Āci⎊⎏r;쀀𝒾nʀ;EdsvӴ⎛⎝⎡ӳ;拹ot;拵Ā;v⎦⎧拴;拳Ā;iݷ⎮lde;䄩ǫ⎸\0⎼cy;䑖l耻ï䃯̀cfmosu⏌⏗⏜⏡⏧⏵Āiy⏑⏕rc;䄵;䐹r;쀀𝔧ath;䈷pf;쀀𝕛ǣ⏬\0⏱r;쀀𝒿rcy;䑘kcy;䑔Ѐacfghjos␋␖␢␧␭␱␵␻ppaĀ;v␓␔䎺;䏰Āey␛␠dil;䄷;䐺r;쀀𝔨reen;䄸cy;䑅cy;䑜pf;쀀𝕜cr;쀀𝓀஀ABEHabcdefghjlmnoprstuv⑰⒁⒆⒍⒑┎┽╚▀♎♞♥♹♽⚚⚲⛘❝❨➋⟀⠁⠒ƀart⑷⑺⑼rò৆òΕail;椛arr;椎Ā;gঔ⒋;檋ar;楢ॣ⒥\0⒪\0⒱\0\0\0\0\0⒵Ⓔ\0ⓆⓈⓍ\0⓹ute;䄺mptyv;榴raîࡌbda;䎻gƀ;dlࢎⓁⓃ;榑åࢎ;檅uo耻«䂫rЀ;bfhlpst࢙ⓞⓦⓩ⓫⓮⓱⓵Ā;f࢝ⓣs;椟s;椝ë≒p;憫l;椹im;楳l;憢ƀ;ae⓿─┄檫il;椙Ā;s┉┊檭;쀀⪭︀ƀabr┕┙┝rr;椌rk;杲Āak┢┬cĀek┨┪;䁻;䁛Āes┱┳;榋lĀdu┹┻;榏;榍Ȁaeuy╆╋╖╘ron;䄾Ādi═╔il;䄼ìࢰâ┩;
vendor: 4,294 bytes, line 214
214䐻Ȁcqrs╣╦╭╽a;椶uoĀ;rนᝆĀdu╲╷har;楧shar;楋h;憲ʀ;fgqs▋▌উ◳◿扤tʀahlrt▘▤▷◂◨rrowĀ;t࢙□aé⓶arpoonĀdu▯▴own»њp»०eftarrows;懇ightƀahs◍◖◞rrowĀ;sࣴࢧarpoonó྘quigarro÷⇰hreetimes;拋ƀ;qs▋ও◺lanôবʀ;cdgsব☊☍☝☨c;檨otĀ;o☔☕橿Ā;r☚☛檁;檃Ā;e☢☥쀀⋚︀s;檓ʀadegs☳☹☽♉♋pproøⓆot;拖qĀgq♃♅ôউgtò⒌ôছiíলƀilr♕࣡♚sht;楼;쀀𝔩Ā;Eজ♣;檑š♩♶rĀdu▲♮Ā;l॥♳;楪lk;斄cy;䑙ʀ;achtੈ⚈⚋⚑⚖rò◁orneòᴈard;楫ri;旺Āio⚟⚤dot;䅀ustĀ;a⚬⚭掰che»⚭ȀEaes⚻⚽⛉⛔;扨pĀ;p⛃⛄檉rox»⛄Ā;q⛎⛏檇Ā;q⛎⚻im;拦Ѐabnoptwz⛩⛴⛷✚✯❁❇❐Ānr⛮⛱g;柬r;懽rëࣁgƀlmr⛿✍✔eftĀar০✇ightá৲apsto;柼ightá৽parrowĀlr✥✩efô⓭ight;憬ƀafl✶✹✽r;榅;쀀𝕝us;樭imes;樴š❋❏st;戗áፎƀ;ef❗❘᠀旊nge»❘arĀ;l❤❥䀨t;榓ʀachmt❳❶❼➅➇ròࢨorneòᶌarĀ;d྘➃;業;怎ri;抿̀achiqt➘➝ੀ➢➮➻quo;怹r;쀀𝓁mƀ;egল➪➬;檍;檏Ābu┪➳oĀ;rฟ➹;怚rok;䅂萀<;cdhilqrࠫ⟒☹⟜⟠⟥⟪⟰Āci⟗⟙;檦r;橹reå◲mes;拉arr;楶uest;橻ĀPi⟵⟹ar;榖ƀ;ef⠀भ᠛旃rĀdu⠇⠍shar;楊har;楦Āen⠗⠡rtneqq;쀀≨︀Å⠞܀Dacdefhilnopsu⡀⡅⢂⢎⢓⢠⢥⢨⣚⣢⣤ઃ⣳⤂Dot;戺Ȁclpr⡎⡒⡣⡽r耻¯䂯Āet⡗⡙;時Ā;e⡞⡟朠se»⡟Ā;sျ⡨toȀ;dluျ⡳⡷⡻owîҌefôएðᏑker;斮Āoy⢇⢌mma;権;䐼ash;怔asuredangle»ᘦr;쀀𝔪o;愧ƀcdn⢯⢴⣉ro耻µ䂵Ȁ;acdᑤ⢽⣀⣄sôᚧir;櫰ot肻·Ƶusƀ;bd⣒ᤃ⣓戒Ā;uᴼ⣘;横ţ⣞⣡p;櫛ò−ðઁĀdp⣩⣮els;抧f;쀀𝕞Āct⣸⣽r;쀀𝓂pos»ᖝƀ;lm⤉⤊⤍䎼timap;抸ఀGLRVabcdefghijlmoprstuvw⥂⥓⥾⦉⦘⧚⧩⨕⨚⩘⩝⪃⪕⪤⪨⬄⬇⭄⭿⮮ⰴⱧⱼ⳩Āgt⥇⥋;쀀⋙̸Ā;v⥐௏쀀≫⃒ƀelt⥚⥲⥶ftĀar⥡⥧rrow;懍ightarrow;懎;쀀⋘̸Ā;v⥻ే쀀≪⃒ightarrow;懏ĀDd⦎⦓ash;抯ash;抮ʀbcnpt⦣⦧⦬⦱⧌la»˞ute;䅄g;쀀∠⃒ʀ;Eiop඄⦼⧀⧅⧈;쀀⩰̸d;쀀≋̸s;䅉roø඄urĀ;a⧓⧔普lĀ;s⧓ସdz⧟\0⧣p肻 ଷmpĀ;e௹ఀʀaeouy⧴⧾⨃⨐⨓ǰ⧹\0⧻;橃on;䅈dil;䅆ngĀ;dൾ⨊ot;쀀⩭̸p;橂;䐽ash;怓΀;Aadqsxஒ⨩⨭⨻⩁⩅⩐rr;懗rĀhr⨳⨶k;椤Ā;oᏲᏰot;쀀≐̸uiöୣĀei⩊⩎ar;椨í஘istĀ;s஠டr;쀀𝔫ȀEest௅⩦⩹⩼ƀ;qs஼⩭௡ƀ;qs஼௅⩴lanô௢ií௪Ā;rஶ⪁»ஷƀAap⪊⪍⪑rò⥱rr;憮ar;櫲ƀ;svྍ⪜ྌĀ;d⪡⪢拼;拺cy;䑚΀AEadest⪷⪺⪾⫂⫅⫶⫹rò⥦;쀀≦̸rr;憚r;急Ȁ;fqs఻⫎⫣⫯tĀar⫔⫙rro÷⫁ightarro÷⪐ƀ;qs఻⪺⫪lanôౕĀ;sౕ⫴»శiíౝĀ;rవ⫾iĀ;eచథiäඐĀpt⬌⬑f;쀀𝕟膀¬;in⬙⬚⬶䂬nȀ;Edvஉ⬤⬨⬮;쀀⋹̸ot;쀀⋵̸ǡஉ⬳⬵;拷;拶iĀ;vಸ⬼ǡಸ⭁⭃;拾;拽ƀaor⭋⭣⭩rȀ;ast୻⭕⭚⭟lleì୻l;쀀⫽⃥;쀀∂̸lint;樔ƀ;ceಒ⭰⭳uåಥĀ;cಘ⭸Ā;eಒ⭽ñಘȀAait⮈⮋⮝⮧rò⦈rrƀ;cw⮔⮕⮙憛;쀀⤳̸;쀀↝̸ghtarrow»⮕riĀ;eೋೖ΀chimpqu⮽⯍⯙⬄୸⯤⯯Ȁ;cerല⯆ഷ⯉uå൅;쀀𝓃ortɭ⬅\0\0⯖ará⭖mĀ;e൮⯟Ā;q൴൳suĀbp⯫⯭å೸åഋƀbcp⯶ⰑⰙȀ;Ees⯿ⰀഢⰄ抄;쀀⫅̸etĀ;eഛⰋqĀ;qണⰀcĀ;eലⰗñസȀ;EesⰢⰣൟⰧ抅;쀀⫆̸etĀ;e൘ⰮqĀ;qൠⰣȀgilrⰽⰿⱅⱇìௗlde耻ñ䃱çృiangleĀlrⱒⱜeftĀ;eచⱚñదightĀ;eೋⱥñ೗Ā;mⱬⱭ䎽ƀ;esⱴⱵⱹ䀣ro;愖p;怇ҀDHadgilrsⲏⲔⲙⲞⲣⲰⲶⳓⳣash;抭arr;椄p;쀀≍⃒ash;抬ĀetⲨⲬ;쀀≥⃒;쀀>⃒nfin;槞ƀAetⲽⳁⳅrr;椂;쀀≤⃒Ā;rⳊⳍ쀀<⃒ie;쀀⊴⃒ĀAtⳘⳜrr;椃rie;쀀⊵⃒im;쀀∼⃒ƀAan⳰⳴ⴂrr;懖rĀhr⳺⳽k;椣Ā;oᏧᏥear;椧ቓ᪕\0\0\0\0\0\0\0\0\0\0\0\0\0ⴭ\0ⴸⵈⵠⵥ⵲ⶄᬇ\0\0ⶍⶫ\0ⷈⷎ\0ⷜ⸙⸫⸾⹃Ācsⴱ᪗ute耻ó䃳ĀiyⴼⵅrĀ;c᪞ⵂ耻ô䃴;䐾ʀabios᪠ⵒⵗLjⵚlac;䅑v;樸old;榼lig;䅓Ācr⵩⵭ir;榿;쀀𝔬ͯ⵹\0\0⵼\0ⶂn;䋛ave耻ò䃲;槁Ābmⶈ෴ar;榵Ȁacitⶕ⶘ⶥⶨrò᪀Āir⶝ⶠr;榾oss;榻nå๒;槀ƀaeiⶱⶵⶹcr;䅍ga;䏉ƀcdnⷀⷅǍron;䎿;榶pf;쀀𝕠ƀaelⷔ⷗ǒr;榷rp;榹΀;adiosvⷪⷫⷮ⸈⸍⸐⸖戨rò᪆Ȁ;efmⷷⷸ⸂⸅橝rĀ;oⷾⷿ愴f»ⷿ耻ª䂪耻º䂺gof;抶r;橖lope;橗;橛ƀclo⸟⸡⸧ò⸁ash耻ø䃸l;折iŬⸯ⸴de耻õ䃵esĀ;aǛ⸺s;樶ml耻ö䃶bar;挽ૡ⹞\0⹽\0⺀⺝\0⺢⺹\0\0⻋ຜ\0⼓\0\0⼫⾼\0⿈rȀ;
vendor: 6,210 bytes, line 214
214astЃ⹧⹲຅脀¶;l⹭⹮䂶leìЃɩ⹸\0\0⹻m;櫳;櫽y;䐿rʀcimpt⺋⺏⺓ᡥ⺗nt;䀥od;䀮il;怰enk;怱r;쀀𝔭ƀimo⺨⺰⺴Ā;v⺭⺮䏆;䏕maô੶ne;明ƀ;tv⺿⻀⻈䏀chfork»´;䏖Āau⻏⻟nĀck⻕⻝kĀ;h⇴⻛;愎ö⇴sҀ;abcdemst⻳⻴ᤈ⻹⻽⼄⼆⼊⼎䀫cir;樣ir;樢Āouᵀ⼂;樥;橲n肻±ຝim;樦wo;樧ƀipu⼙⼠⼥ntint;樕f;쀀𝕡nd耻£䂣Ԁ;Eaceinosu່⼿⽁⽄⽇⾁⾉⾒⽾⾶;檳p;檷uå໙Ā;c໎⽌̀;acens່⽙⽟⽦⽨⽾pproø⽃urlyeñ໙ñ໎ƀaes⽯⽶⽺pprox;檹qq;檵im;拨iíໟmeĀ;s⾈ຮ怲ƀEas⽸⾐⽺ð⽵ƀdfp໬⾙⾯ƀals⾠⾥⾪lar;挮ine;挒urf;挓Ā;t໻⾴ï໻rel;抰Āci⿀⿅r;쀀𝓅;䏈ncsp;怈̀fiopsu⿚⋢⿟⿥⿫⿱r;쀀𝔮pf;쀀𝕢rime;恗cr;쀀𝓆ƀaeo⿸〉〓tĀei⿾々rnionóڰnt;樖stĀ;e【】䀿ñἙô༔઀ABHabcdefhilmnoprstux぀けさすムㄎㄫㅇㅢㅲㆎ㈆㈕㈤㈩㉘㉮㉲㊐㊰㊷ƀartぇおがròႳòϝail;検aròᱥar;楤΀cdenqrtとふへみわゔヌĀeuねぱ;쀀∽̱te;䅕iãᅮmptyv;榳gȀ;del࿑らるろ;榒;榥å࿑uo耻»䂻rր;abcfhlpstw࿜ガクシスゼゾダッデナp;極Ā;f࿠ゴs;椠;椳s;椞ë≝ð✮l;楅im;楴l;憣;憝Āaiパフil;椚oĀ;nホボ戶aló༞ƀabrョリヮrò៥rk;杳ĀakンヽcĀekヹ・;䁽;䁝Āes㄂㄄;榌lĀduㄊㄌ;榎;榐Ȁaeuyㄗㄜㄧㄩron;䅙Ādiㄡㄥil;䅗ì࿲âヺ;䑀Ȁclqsㄴㄷㄽㅄa;椷dhar;楩uoĀ;rȎȍh;憳ƀacgㅎㅟངlȀ;ipsླྀㅘㅛႜnåႻarôྩt;断ƀilrㅩဣㅮsht;楽;쀀𝔯ĀaoㅷㆆrĀduㅽㅿ»ѻĀ;l႑ㆄ;楬Ā;vㆋㆌ䏁;䏱ƀgns㆕ㇹㇼht̀ahlrstㆤㆰ㇂㇘㇤㇮rrowĀ;t࿜ㆭaéトarpoonĀduㆻㆿowîㅾp»႒eftĀah㇊㇐rrowó࿪arpoonóՑightarrows;應quigarro÷ニhreetimes;拌g;䋚ingdotseñἲƀahm㈍㈐㈓rò࿪aòՑ;怏oustĀ;a㈞㈟掱che»㈟mid;櫮Ȁabpt㈲㈽㉀㉒Ānr㈷㈺g;柭r;懾rëဃƀafl㉇㉊㉎r;榆;쀀𝕣us;樮imes;樵Āap㉝㉧rĀ;g㉣㉤䀩t;榔olint;樒arò㇣Ȁachq㉻㊀Ⴜ㊅quo;怺r;쀀𝓇Ābu・㊊oĀ;rȔȓƀhir㊗㊛㊠reåㇸmes;拊iȀ;efl㊪ၙᠡ㊫方tri;槎luhar;楨;愞ൡ㋕㋛㋟㌬㌸㍱\0㍺㎤\0\0㏬㏰\0㐨㑈㑚㒭㒱㓊㓱\0㘖\0\0㘳cute;䅛quï➺Ԁ;Eaceinpsyᇭ㋳㋵㋿㌂㌋㌏㌟㌦㌩;檴ǰ㋺\0㋼;檸on;䅡uåᇾĀ;dᇳ㌇il;䅟rc;䅝ƀEas㌖㌘㌛;檶p;檺im;择olint;樓iíሄ;䑁otƀ;be㌴ᵇ㌵担;橦΀Aacmstx㍆㍊㍗㍛㍞㍣㍭rr;懘rĀhr㍐㍒ë∨Ā;oਸ਼਴t耻§䂧i;䀻war;椩mĀin㍩ðnuóñt;朶rĀ;o㍶⁕쀀𝔰Ȁacoy㎂㎆㎑㎠rp;景Āhy㎋㎏cy;䑉;䑈rtɭ㎙\0\0㎜iäᑤaraì⹯耻­䂭Āgm㎨㎴maƀ;fv㎱㎲㎲䏃;䏂Ѐ;deglnprካ㏅㏉㏎㏖㏞㏡㏦ot;橪Ā;q኱ኰĀ;E㏓㏔檞;檠Ā;E㏛㏜檝;檟e;扆lus;樤arr;楲aròᄽȀaeit㏸㐈㐏㐗Āls㏽㐄lsetmé㍪hp;樳parsl;槤Ādlᑣ㐔e;挣Ā;e㐜㐝檪Ā;s㐢㐣檬;쀀⪬︀ƀflp㐮㐳㑂tcy;䑌Ā;b㐸㐹䀯Ā;a㐾㐿槄r;挿f;쀀𝕤aĀdr㑍ЂesĀ;u㑔㑕晠it»㑕ƀcsu㑠㑹㒟Āau㑥㑯pĀ;sᆈ㑫;쀀⊓︀pĀ;sᆴ㑵;쀀⊔︀uĀbp㑿㒏ƀ;esᆗᆜ㒆etĀ;eᆗ㒍ñᆝƀ;esᆨᆭ㒖etĀ;eᆨ㒝ñᆮƀ;afᅻ㒦ְrť㒫ֱ»ᅼaròᅈȀcemt㒹㒾㓂㓅r;쀀𝓈tmîñiì㐕aræᆾĀar㓎㓕rĀ;f㓔ឿ昆Āan㓚㓭ightĀep㓣㓪psiloîỠhé⺯s»⡒ʀbcmnp㓻㕞ሉ㖋㖎Ҁ;Edemnprs㔎㔏㔑㔕㔞㔣㔬㔱㔶抂;櫅ot;檽Ā;dᇚ㔚ot;櫃ult;櫁ĀEe㔨㔪;櫋;把lus;檿arr;楹ƀeiu㔽㕒㕕tƀ;en㔎㕅㕋qĀ;qᇚ㔏eqĀ;q㔫㔨m;櫇Ābp㕚㕜;櫕;櫓c̀;acensᇭ㕬㕲㕹㕻㌦pproø㋺urlyeñᇾñᇳƀaes㖂㖈㌛pproø㌚qñ㌗g;晪ڀ123;Edehlmnps㖩㖬㖯ሜ㖲㖴㗀㗉㗕㗚㗟㗨㗭耻¹䂹耻²䂲耻³䂳;櫆Āos㖹㖼t;檾ub;櫘Ā;dሢ㗅ot;櫄sĀou㗏㗒l;柉b;櫗arr;楻ult;櫂ĀEe㗤㗦;櫌;抋lus;櫀ƀeiu㗴㘉㘌tƀ;enሜ㗼㘂qĀ;qሢ㖲eqĀ;q㗧㗤m;櫈Ābp㘑㘓;櫔;櫖ƀAan㘜㘠㘭rr;懙rĀhr㘦㘨ë∮Ā;oਫ਩war;椪lig耻ß䃟௡㙑㙝㙠ዎ㙳㙹\0㙾㛂\0\0\0\0\0㛛㜃\0㜉㝬\0\0\0㞇ɲ㙖\0\0㙛get;挖;䏄rë๟ƀaey㙦㙫㙰ron;䅥dil;䅣;䑂lrec;挕r;쀀𝔱Ȁeiko㚆㚝㚵㚼Dz㚋\0㚑eĀ4fኄኁaƀ;sv㚘㚙㚛䎸ym;䏑Ācn㚢㚲kĀas㚨㚮pproø዁im»ኬsðኞĀas㚺㚮ð዁rn耻þ䃾Ǭ̟㛆⋧es膀×;bd㛏㛐㛘䃗Ā;aᤏ㛕r;樱;樰ƀeps㛡㛣㜀á⩍Ȁ;bcf҆㛬㛰㛴ot;挶ir;櫱Ā;o㛹㛼쀀𝕥rk;櫚á㍢rime;怴ƀaip㜏㜒㝤dåቈ΀adempst㜡㝍㝀㝑㝗㝜㝟ngleʀ;dlqr㜰㜱㜶㝀㝂斵own»ᶻeftĀ;e⠀㜾ñम;扜ightĀ;e㊪㝋ñၚot;旬inus;樺lus;樹b;槍ime;樻ezium;揢ƀcht㝲㝽㞁Āry㝷㝻;쀀𝓉;䑆cy;䑛rok;䅧Āio㞋㞎xô᝷headĀlr㞗㞠eftarro÷ࡏightarrow»ཝऀAHabcdfghlmoprstuw㟐㟓㟗㟤㟰㟼㠎㠜㠣㠴㡑㡝㡫㢩㣌㣒㣪㣶ròϭar;楣Ācr㟜㟢ute耻ú䃺òᅐrǣ㟪\0㟭y;䑞ve;䅭Āiy㟵㟺rc耻û䃻;䑃ƀabh㠃㠆㠋ròᎭlac;䅱aòᏃĀir㠓㠘sht;楾;쀀𝔲rave耻ù䃹š㠧㠱rĀlr㠬㠮»ॗ»ႃlk;斀Āct㠹㡍ɯ㠿\0\0㡊rnĀ;e㡅㡆挜r»㡆op;挏ri;旸Āal㡖㡚cr;䅫肻¨͉Āgp㡢㡦on;䅳f;쀀𝕦̀adhlsuᅋ㡸㡽፲㢑㢠ownáᎳarpoonĀlr㢈㢌efô㠭ighô㠯iƀ;hl㢙㢚㢜䏅»ᏺon»㢚parrows;懈ƀcit㢰㣄㣈ɯ㢶\0\0㣁rnĀ;e㢼㢽挝r»㢽op;挎ng;䅯ri;旹cr;쀀𝓊ƀdir㣙㣝㣢ot;拰lde;䅩iĀ;f㜰㣨»᠓Āam㣯㣲rò㢨l耻ü䃼angle;榧ހABDacdeflnoprsz㤜㤟㤩㤭㦵㦸㦽㧟㧤㧨㧳㧹㧽㨁㨠ròϷarĀ;v㤦㤧櫨;櫩asèϡĀnr㤲㤷grt;榜΀eknprst㓣㥆㥋㥒㥝㥤㦖appá␕othinçẖƀhir㓫⻈㥙opô⾵Ā;hᎷ㥢ïㆍĀiu㥩㥭gmá㎳Ābp㥲㦄setneqĀ;q㥽㦀쀀⊊︀;쀀⫋︀setneqĀ;q㦏㦒쀀⊋︀;쀀⫌︀Āhr㦛㦟etá㚜iangleĀlr㦪㦯eft»थight»ၑy;䐲ash»ံƀelr㧄㧒㧗ƀ;beⷪ㧋㧏ar;抻q;扚lip;拮Ābt㧜ᑨaòᑩr;쀀𝔳tré㦮suĀbp㧯㧱»ജ»൙pf;쀀𝕧roð໻tré㦴Ācu㨆㨋r;쀀𝓋Ābp㨐㨘nĀEe㦀㨖»㥾nĀEe㦒㨞»㦐igzag;榚΀cefoprs㨶㨻㩖㩛㩔㩡㩪irc;䅵Ādi㩀㩑Ābg㩅㩉ar;機eĀ;qᗺ㩏;扙erp;愘r;쀀𝔴pf;쀀𝕨Ā;eᑹ㩦atèᑹcr;쀀𝓌ૣណ㪇\0㪋\0㪐㪛\0\0㪝㪨㪫㪯\0\0㫃㫎\0㫘ៜ៟tré៑r;쀀𝔵ĀAa㪔㪗ròσrò৶;䎾ĀAa㪡㪤ròθrò৫að✓is;拻ƀdptឤ㪵㪾Āfl㪺ឩ;쀀𝕩imåឲĀAa㫇㫊ròώròਁĀcq㫒ីr;쀀𝓍Āpt៖㫜ré។Ѐacefiosu㫰㫽㬈㬌㬑㬕㬛㬡cĀuy㫶㫻te耻ý䃽;䑏Āiy㬂㬆rc;䅷;䑋n耻¥䂥r;쀀𝔶cy;䑗pf;쀀𝕪cr;쀀𝓎Ācm㬦㬩y;䑎l耻ÿ䃿Ԁacdefhiosw㭂㭈㭔㭘㭤㭩㭭㭴㭺㮀cute;䅺Āay㭍㭒ron;䅾;䐷ot;䅼Āet㭝㭡træᕟa;䎶r;쀀𝔷cy;䐶grarr;懝pf;쀀𝕫cr;쀀𝓏Ājn㮅㮇;怍j;怌
214'.split("").map(e=>e.charCodeAt(0))),tb=new Map([[0,65533],[128,8364],[130,8218],[131,402],[132,8222],[133,8230],[134,8224],[135,8225],[136,710],[137,8240],[138,352],[139,8249],[140,338],[142,381],[145,8216],[146,8217],[147,8220],[148,8221],[149,8226],[150,8211],[151,8212],[152,732],[153,8482],[154,353],[155,8250],[156,339],[158,382],[159,376]]);function rb(e){var t;return e>=55296&&e<=57343||e>1114111?65533:(t=tb.get(e))!==null&&t!==void 0?t:e}var dt;(function(e){e[e.NUM=35]="NUM",e[e.SEMI=59]="SEMI",e[e.EQUALS=61]="EQUALS",e[e.ZERO=48]="ZERO",e[e.NINE=57]="NINE",e[e.LOWER_A=97]="LOWER_A",e[e.LOWER_F=102]="LOWER_F",e[e.LOWER_X=120]="LOWER_X",e[e.LOWER_Z=122]="LOWER_Z",e[e.UPPER_A=65]="UPPER_A",e[e.UPPER_F=70]="UPPER_F",e[e.UPPER_Z=90]="UPPER_Z"})(dt||(dt={}));const ab=32;var Lr;(function(e){e[e.VALUE_LENGTH=49152]="VALUE_LENGTH",e[e.BRANCH_LENGTH=16256]="BRANCH_LENGTH",e[e.JUMP_TABLE=127]="JUMP_TABLE"})(Lr||(Lr={}));function co(e){return e>=dt.ZERO&&e<=dt.NINE}function nb(e){return e>=dt.UPPER_A&&e<=dt.UPPER_F||e>=dt.LOWER_A&&e<=dt.LOWER_F}function sb(e){return e>=dt.UPPER_A&&e<=dt.UPPER_Z||e>=dt.LOWER_A&&e<=dt.LOWER_Z||co(e)}function ib(e){return e===dt.EQUALS||sb(e)}var ut;(function(e){e[e.EntityStart=0]="EntityStart",e[e.NumericStart=1]="NumericStart",e[e.NumericDecimal=2]="NumericDecimal",e[e.NumericHex=3]="NumericHex",e[e.NamedEntity=4]="NamedEntity"})(ut||(ut={}));var hr;(function(e){e[e.Legacy=0]="Legacy",e[e.Strict=1]="Strict",e[e.Attribute=2]="Attribute"})(hr||(hr={}));class ob{constructor(t,r,a){this.decodeTree=t,this.emitCodePoint=r,this.errors=a,this.state=ut.EntityStart,this.consumed=1,this.result=0,this.treeIndex=0,this.excess=1,this.decodeMode=hr.Strict}startEntity(t){this.decodeMode=t,this.state=ut.EntityStart,this.result=0,this.treeIndex=0,this.excess=1,this.consumed=1}write(t,r){switch(this.state){case ut.EntityStart:return t.charCodeAt(r)===dt.NUM?(this.state=ut.NumericStart,this.consumed+=1,this.stateNumericStart(t,r+1)):(this.state=ut.NamedEntity,this.stateNamedEntity(t,r));case ut.NumericStart:return this.stateNumericStart(t,r);case ut.NumericDecimal:return this.stateNumericDecimal(t,r);case ut.NumericHex:return this.stateNumericHex(t,r);case ut.NamedEntity:return this.stateNamedEntity(t,r)}}stateNumericStart(t,r){return r>=t.length?-1:(t.charCodeAt(r)|ab)===dt.LOWER_X?(this.state=ut.NumericHex,this.consumed+=1,this.stateNumericHex(t,r+1)):(this.state=ut.NumericDecimal,this.stateNumericDecimal(t,r))}addToNumericResult(t,r,a,n){if(r!==a){const i=a-r;this.result=this.result*Math.pow(n,i)+Number.parseInt(t.substr(r,i),n),this.consumed+=i}}stateNumericHex(t,r){const a=r;for(;r<t.length;){const n=t.charCodeAt(r);if(co(n)||nb(n))r+=1;else return this.addToNumericResult(t,a,r,16),this.emitNumericEntity(n,3)}return this.addToNumericResult(t,a,r,16),-1}stateNumericDecimal(t,r){const a=r;for(;r<t.length;){const n=t.charCodeAt(r);if(co(n))r+=1;else return this.addToNumericResult(t,a,r,10),this.emitNumericEntity(n,2)}return this.addToNumericResult(t,a,r,10),-1}emitNumericEntity(t,r){var a;if(this.consumed<=r)return(a=this.errors)===null||a===void 0||a.absenceOfDigitsInNumericCharacterReference(this.consumed),0;if(t===dt.SEMI)this.consumed+=1;else if(this.decodeMode===hr.Strict)return 0;return this.emitCodePoint(rb(this.result),this.consumed),this.errors&&(t!==dt.SEMI&&this.errors.missingSemicolonAfterCharacterReference(),this.errors.validateNumericCharacterReference(this.result)),this.consumed}stateNamedEntity(t,r){const{decodeTree:a}=this;let n=a[this.treeIndex],i=(n&Lr.VALUE_LENGTH)>>14;for(;r<t.length;r++,this.excess++){const o=t.charCodeAt(r);if(this.treeIndex=cb(a,n,this.treeIndex+Math.max(1,i),o),this.treeIndex<0)return this.result===0||this.decodeMode===hr.Attribute&&(i===0||ib(o))?0:this.emitNotTerminatedNamedEntity();if(n=a[this.treeIndex],i=(n&Lr.VALUE_LENGTH)>>14,i!==0){if(o===dt.SEMI)return this.emitNamedEntityData(this.treeIndex,i,this.consumed+this.excess);this.decodeMode!==hr.Strict&&(this.result=this.treeIndex,this.consumed+=this.excess,this.excess=0)}}return-1}emitNotTerminatedNamedEntity(){var t;const{result:r,decodeTree:a}=this,n=(a[r]&Lr.VALUE_LENGTH)>>14;return this.emitNamedEntityData(r,n,this.consumed),(t=this.errors)===null||t===void 0||t.missingSemicolonAfterCharacterReference(),this.consumed}emitNamedEntityData(t,r,a){const{decodeTree:n}=this;return this.emitCodePoint(r===1?n[t]&~Lr.VALUE_LENGTH:n[t+1],a),r===3&&this.emitCodePoint(n[t+2],a),a}end(){var t;switch(this.state){case ut.NamedEntity:return this.result!==0&&(this.decodeMode!==hr.Attribute||this.result===this.treeIndex)?this.emitNotTerminatedNamedEntity():0;case ut.NumericDecimal:return this.emitNumericEntity(0,2);case ut.NumericHex:return this.emitNumericEntity(0,3);case ut.NumericStart:return(t=this.errors)===null||t===void 0||t.absenceOfDigitsInNumericCharacterReference(this.consumed),0;case ut.EntityStart:return 0}}}function cb(e,t,r,a){const n=(t&Lr.BRANCH_LENGTH)>>7,i=t&Lr.JUMP_TABLE;if(n===0)return i!==0&&a===i?r:-1;if(i){const f=a-i;return f<0||f>=n?-1:e[r+f]-1}let o=r,c=o+n-1;for(;o<=c;){const f=o+c>>>1,d=e[f];if(d<a)o=f+1;else if(d>a)c=f-1;else return e[f+n]}return-1}var Q;(function(e){e.HTML="http://www.w3.org/1999/xhtml",e.MATHML="http://www.w3.org/1998/Math/MathML",e.SVG="http://www.w3.org/2000/svg",e.XLINK="http://www.w3.org/1999/xlink",e.XML="http://www.w3.org/XML/1998/namespace",e.XMLNS="http://www.w3.org/2000/xmlns/"})(Q||(Q={}));var Zr;(function(e){e.TYPE="type",e.ACTION="action",e.ENCODING="encoding",e.PROMPT="prompt",e.NAME="name",e.COLOR="color",e.FACE="face",e.SIZE="size"})(Zr||(Zr={}));var Mt;(function(e){e.NO_QUIRKS="no-quirks",e.QUIRKS="quirks",e.LIMITED_QUIRKS="limited-quirks"})(Mt||(Mt={}));var R;(function(e){e.A="a",e.ADDRESS="address",e.ANNOTATION_XML="annotation-xml",e.APPLET="applet",e.AREA="area",e.ARTICLE="article",e.ASIDE="aside",e.B="b",e.BASE="base",e.BASEFONT="basefont",e.BGSOUND="bgsound",e.BIG="big",e.BLOCKQUOTE="blockquote",e.BODY="body",e.BR="br",e.BUTTON="button",e.CAPTION="caption",e.CENTER="center",e.CODE="code",e.COL="col",e.COLGROUP="colgroup",e.DD="dd",e.DESC="desc",e.DETAILS="details",e.DIALOG="dialog",e.DIR="dir",e.DIV="div",e.DL="dl",e.DT="dt",e.EM="em",e.EMBED="embed",e.FIELDSET="fieldset",e.FIGCAPTION="figcaption",e.FIGURE="figure",e.FONT="font",e.FOOTER="footer",e.FOREIGN_OBJECT="foreignObject",e.FORM="form",e.FRAME="frame",e.FRAMESET="frameset",e.H1="h1",e.H2="h2",e.H3="h3",e.H4="h4",e.H5="h5",e.H6="h6",e.HEAD="head",e.HEADER="header",e.HGROUP="hgroup",e.HR="hr",e.HTML="html",e.I="i",e.IMG="img",e.IMAGE="image",e.INPUT="input",e.IFRAME="iframe",e.KEYGEN="keygen",e.LABEL="label",e.LI="li",e.LINK="link",e.LISTING="listing",e.MAIN="main",e.MALIGNMARK="malignmark",e.MARQUEE="marquee",e.MATH="math",e.MENU="menu",e.META="meta",e.MGLYPH="mglyph",e.MI="mi",e.MO="mo",e.MN="mn",e.MS="ms",e.MTEXT="mtext",e.NAV="nav",e.NOBR="nobr",e.NOFRAMES="noframes",e.NOEMBED="noembed",e.NOSCRIPT="noscript",e.OBJECT="object",e.OL="ol",e.OPTGROUP="optgroup",e.OPTION="option",e.P="p",e.PARAM="param",e.PLAINTEXT="plaintext",e.PRE="pre",e.RB="rb",e.RP="rp",e.RT="rt",e.RTC="rtc",e.RUBY="ruby",e.S="s",e.SCRIPT="script",e.SEARCH="search",e.SECTION="section",e.SELECT="select",e.SOURCE="source",e.SMALL="small",e.SPAN="span",e.STRIKE="str
214ike",e.STRONG="strong",e.STYLE="style",e.SUB="sub",e.SUMMARY="summary",e.SUP="sup",e.TABLE="table",e.TBODY="tbody",e.TEMPLATE="template",e.TEXTAREA="textarea",e.TFOOT="tfoot",e.TD="td",e.TH="th",e.THEAD="thead",e.TITLE="title",e.TR="tr",e.TRACK="track",e.TT="tt",e.U="u",e.UL="ul",e.SVG="svg",e.VAR="var",e.WBR="wbr",e.XMP="xmp"})(R||(R={}));var s;(function(e){e[e.UNKNOWN=0]="UNKNOWN",e[e.A=1]="A",e[e.ADDRESS=2]="ADDRESS",e[e.ANNOTATION_XML=3]="ANNOTATION_XML",e[e.APPLET=4]="APPLET",e[e.AREA=5]="AREA",e[e.ARTICLE=6]="ARTICLE",e[e.ASIDE=7]="ASIDE",e[e.B=8]="B",e[e.BASE=9]="BASE",e[e.BASEFONT=10]="BASEFONT",e[e.BGSOUND=11]="BGSOUND",e[e.BIG=12]="BIG",e[e.BLOCKQUOTE=13]="BLOCKQUOTE",e[e.BODY=14]="BODY",e[e.BR=15]="BR",e[e.BUTTON=16]="BUTTON",e[e.CAPTION=17]="CAPTION",e[e.CENTER=18]="CENTER",e[e.CODE=19]="CODE",e[e.COL=20]="COL",e[e.COLGROUP=21]="COLGROUP",e[e.DD=22]="DD",e[e.DESC=23]="DESC",e[e.DETAILS=24]="DETAILS",e[e.DIALOG=25]="DIALOG",e[e.DIR=26]="DIR",e[e.DIV=27]="DIV",e[e.DL=28]="DL",e[e.DT=29]="DT",e[e.EM=30]="EM",e[e.EMBED=31]="EMBED",e[e.FIELDSET=32]="FIELDSET",e[e.FIGCAPTION=33]="FIGCAPTION",e[e.FIGURE=34]="FIGURE",e[e.FONT=35]="FONT",e[e.FOOTER=36]="FOOTER",e[e.FOREIGN_OBJECT=37]="FOREIGN_OBJECT",e[e.FORM=38]="FORM",e[e.FRAME=39]="FRAME",e[e.FRAMESET=40]="FRAMESET",e[e.H1=41]="H1",e[e.H2=42]="H2",e[e.H3=43]="H3",e[e.H4=44]="H4",e[e.H5=45]="H5",e[e.H6=46]="H6",e[e.HEAD=47]="HEAD",e[e.HEADER=48]="HEADER",e[e.HGROUP=49]="HGROUP",e[e.HR=50]="HR",e[e.HTML=51]="HTML",e[e.I=52]="I",e[e.IMG=53]="IMG",e[e.IMAGE=54]="IMAGE",e[e.INPUT=55]="INPUT",e[e.IFRAME=56]="IFRAME",e[e.KEYGEN=57]="KEYGEN",e[e.LABEL=58]="LABEL",e[e.LI=59]="LI",e[e.LINK=60]="LINK",e[e.LISTING=61]="LISTING",e[e.MAIN=62]="MAIN",e[e.MALIGNMARK=63]="MALIGNMARK",e[e.MARQUEE=64]="MARQUEE",e[e.MATH=65]="MATH",e[e.MENU=66]="MENU",e[e.META=67]="META",e[e.MGLYPH=68]="MGLYPH",e[e.MI=69]="MI",e[e.MO=70]="MO",e[e.MN=71]="MN",e[e.MS=72]="MS",e[e.MTEXT=73]="MTEXT",e[e.NAV=74]="NAV",e[e.NOBR=75]="NOBR",e[e.NOFRAMES=76]="NOFRAMES",e[e.NOEMBED=77]="NOEMBED",e[e.NOSCRIPT=78]="NOSCRIPT",e[e.OBJECT=79]="OBJECT",e[e.OL=80]="OL",e[e.OPTGROUP=81]="OPTGROUP",e[e.OPTION=82]="OPTION",e[e.P=83]="P",e[e.PARAM=84]="PARAM",e[e.PLAINTEXT=85]="PLAINTEXT",e[e.PRE=86]="PRE",e[e.RB=87]="RB",e[e.RP=88]="RP",e[e.RT=89]="RT",e[e.RTC=90]="RTC",e[e.RUBY=91]="RUBY",e[e.S=92]="S",e[e.SCRIPT=93]="SCRIPT",e[e.SEARCH=94]="SEARCH",e[e.SECTION=95]="SECTION",e[e.SELECT=96]="SELECT",e[e.SOURCE=97]="SOURCE",e[e.SMALL=98]="SMALL",e[e.SPAN=99]="SPAN",e[e.STRIKE=100]="STRIKE",e[e.STRONG=101]="STRONG",e[e.STYLE=102]="STYLE",e[e.SUB=103]="SUB",e[e.SUMMARY=104]="SUMMARY",e[e.SUP=105]="SUP",e[e.TABLE=106]="TABLE",e[e.TBODY=107]="TBODY",e[e.TEMPLATE=108]="TEMPLATE",e[e.TEXTAREA=109]="TEXTAREA",e[e.TFOOT=110]="TFOOT",e[e.TD=111]="TD",e[e.TH=112]="TH",e[e.THEAD=113]="THEAD",e[e.TITLE=114]="TITLE",e[e.TR=115]="TR",e[e.TRACK=116]="TRACK",e[e.TT=117]="TT",e[e.U=118]="U",e[e.UL=119]="UL",e[e.SVG=120]="SVG",e[e.VAR=121]="VAR",e[e.WBR=122]="WBR",e[e.XMP=123]="XMP"})(s||(s={}));const ub=new Map([[R.A,s.A],[R.ADDRESS,s.ADDRESS],[R.ANNOTATION_XML,s.ANNOTATION_XML],[R.APPLET,s.APPLET],[R.AREA,s.AREA],[R.ARTICLE,s.ARTICLE],[R.ASIDE,s.ASIDE],[R.B,s.B],[R.BASE,s.BASE],[R.BASEFONT,s.BASEFONT],[R.BGSOUND,s.BGSOUND],[R.BIG,s.BIG],[R.BLOCKQUOTE,s.BLOCKQUOTE],[R.BODY,s.BODY],[R.BR,s.BR],[R.BUTTON,s.BUTTON],[R.CAPTION,s.CAPTION],[R.CENTER,s.CENTER],[R.CODE,s.CODE],[R.COL,s.COL],[R.COLGROUP,s.COLGROUP],[R.DD,s.DD],[R.DESC,s.DESC],[R.DETAILS,s.DETAILS],[R.DIALOG,s.DIALOG],[R.DIR,s.DIR],[R.DIV,s.DIV],[R.DL,s.DL],[R.DT,s.DT],[R.EM,s.EM],[R.EMBED,s.EMBED],[R.FIELDSET,s.FIELDSET],[R.FIGCAPTION,s.FIGCAPTION],[R.FIGURE,s.FIGURE],[R.FONT,s.FONT],[R.FOOTER,s.FOOTER],[R.FOREIGN_OBJECT,s.FOREIGN_OBJECT],[R.FORM,s.FORM],[R.FRAME,s.FRAME],[R.FRAMESET,s.FRAMESET],[R.H1,s.H1],[R.H2,s.H2],[R.H3,s.H3],[R.H4,s.H4],[R.H5,s.H5],[R.H6,s.H6],[R.HEAD,s.HEAD],[R.HEADER,s.HEADER],[R.HGROUP,s.HGROUP],[R.HR,s.HR],[R.HTML,s.HTML],[R.I,s.I],[R.IMG,s.IMG],[R.IMAGE,s.IMAGE],[R.INPUT,s.INPUT],[R.IFRAME,s.IFRAME],[R.KEYGEN,s.KEYGEN],[R.LABEL,s.LABEL],[R.LI,s.L
vendor: 109,966 bytes, line 214
214I],[R.LINK,s.LINK],[R.LISTING,s.LISTING],[R.MAIN,s.MAIN],[R.MALIGNMARK,s.MALIGNMARK],[R.MARQUEE,s.MARQUEE],[R.MATH,s.MATH],[R.MENU,s.MENU],[R.META,s.META],[R.MGLYPH,s.MGLYPH],[R.MI,s.MI],[R.MO,s.MO],[R.MN,s.MN],[R.MS,s.MS],[R.MTEXT,s.MTEXT],[R.NAV,s.NAV],[R.NOBR,s.NOBR],[R.NOFRAMES,s.NOFRAMES],[R.NOEMBED,s.NOEMBED],[R.NOSCRIPT,s.NOSCRIPT],[R.OBJECT,s.OBJECT],[R.OL,s.OL],[R.OPTGROUP,s.OPTGROUP],[R.OPTION,s.OPTION],[R.P,s.P],[R.PARAM,s.PARAM],[R.PLAINTEXT,s.PLAINTEXT],[R.PRE,s.PRE],[R.RB,s.RB],[R.RP,s.RP],[R.RT,s.RT],[R.RTC,s.RTC],[R.RUBY,s.RUBY],[R.S,s.S],[R.SCRIPT,s.SCRIPT],[R.SEARCH,s.SEARCH],[R.SECTION,s.SECTION],[R.SELECT,s.SELECT],[R.SOURCE,s.SOURCE],[R.SMALL,s.SMALL],[R.SPAN,s.SPAN],[R.STRIKE,s.STRIKE],[R.STRONG,s.STRONG],[R.STYLE,s.STYLE],[R.SUB,s.SUB],[R.SUMMARY,s.SUMMARY],[R.SUP,s.SUP],[R.TABLE,s.TABLE],[R.TBODY,s.TBODY],[R.TEMPLATE,s.TEMPLATE],[R.TEXTAREA,s.TEXTAREA],[R.TFOOT,s.TFOOT],[R.TD,s.TD],[R.TH,s.TH],[R.THEAD,s.THEAD],[R.TITLE,s.TITLE],[R.TR,s.TR],[R.TRACK,s.TRACK],[R.TT,s.TT],[R.U,s.U],[R.UL,s.UL],[R.SVG,s.SVG],[R.VAR,s.VAR],[R.WBR,s.WBR],[R.XMP,s.XMP]]);function qs(e){var t;return(t=ub.get(e))!==null&&t!==void 0?t:s.UNKNOWN}const X=s,lb={[Q.HTML]:new Set([X.ADDRESS,X.APPLET,X.AREA,X.ARTICLE,X.ASIDE,X.BASE,X.BASEFONT,X.BGSOUND,X.BLOCKQUOTE,X.BODY,X.BR,X.BUTTON,X.CAPTION,X.CENTER,X.COL,X.COLGROUP,X.DD,X.DETAILS,X.DIR,X.DIV,X.DL,X.DT,X.EMBED,X.FIELDSET,X.FIGCAPTION,X.FIGURE,X.FOOTER,X.FORM,X.FRAME,X.FRAMESET,X.H1,X.H2,X.H3,X.H4,X.H5,X.H6,X.HEAD,X.HEADER,X.HGROUP,X.HR,X.HTML,X.IFRAME,X.IMG,X.INPUT,X.LI,X.LINK,X.LISTING,X.MAIN,X.MARQUEE,X.MENU,X.META,X.NAV,X.NOEMBED,X.NOFRAMES,X.NOSCRIPT,X.OBJECT,X.OL,X.P,X.PARAM,X.PLAINTEXT,X.PRE,X.SCRIPT,X.SECTION,X.SELECT,X.SOURCE,X.STYLE,X.SUMMARY,X.TABLE,X.TBODY,X.TD,X.TEMPLATE,X.TEXTAREA,X.TFOOT,X.TH,X.THEAD,X.TITLE,X.TR,X.TRACK,X.UL,X.WBR,X.XMP]),[Q.MATHML]:new Set([X.MI,X.MO,X.MN,X.MS,X.MTEXT,X.ANNOTATION_XML]),[Q.SVG]:new Set([X.TITLE,X.FOREIGN_OBJECT,X.DESC]),[Q.XLINK]:new Set,[Q.XML]:new Set,[Q.XMLNS]:new Set},uo=new Set([X.H1,X.H2,X.H3,X.H4,X.H5,X.H6]);R.STYLE,R.SCRIPT,R.XMP,R.IFRAME,R.NOEMBED,R.NOFRAMES,R.PLAINTEXT;var g;(function(e){e[e.DATA=0]="DATA",e[e.RCDATA=1]="RCDATA",e[e.RAWTEXT=2]="RAWTEXT",e[e.SCRIPT_DATA=3]="SCRIPT_DATA",e[e.PLAINTEXT=4]="PLAINTEXT",e[e.TAG_OPEN=5]="TAG_OPEN",e[e.END_TAG_OPEN=6]="END_TAG_OPEN",e[e.TAG_NAME=7]="TAG_NAME",e[e.RCDATA_LESS_THAN_SIGN=8]="RCDATA_LESS_THAN_SIGN",e[e.RCDATA_END_TAG_OPEN=9]="RCDATA_END_TAG_OPEN",e[e.RCDATA_END_TAG_NAME=10]="RCDATA_END_TAG_NAME",e[e.RAWTEXT_LESS_THAN_SIGN=11]="RAWTEXT_LESS_THAN_SIGN",e[e.RAWTEXT_END_TAG_OPEN=12]="RAWTEXT_END_TAG_OPEN",e[e.RAWTEXT_END_TAG_NAME=13]="RAWTEXT_END_TAG_NAME",e[e.SCRIPT_DATA_LESS_THAN_SIGN=14]="SCRIPT_DATA_LESS_THAN_SIGN",e[e.SCRIPT_DATA_END_TAG_OPEN=15]="SCRIPT_DATA_END_TAG_OPEN",e[e.SCRIPT_DATA_END_TAG_NAME=16]="SCRIPT_DATA_END_TAG_NAME",e[e.SCRIPT_DATA_ESCAPE_START=17]="SCRIPT_DATA_ESCAPE_START",e[e.SCRIPT_DATA_ESCAPE_START_DASH=18]="SCRIPT_DATA_ESCAPE_START_DASH",e[e.SCRIPT_DATA_ESCAPED=19]="SCRIPT_DATA_ESCAPED",e[e.SCRIPT_DATA_ESCAPED_DASH=20]="SCRIPT_DATA_ESCAPED_DASH",e[e.SCRIPT_DATA_ESCAPED_DASH_DASH=21]="SCRIPT_DATA_ESCAPED_DASH_DASH",e[e.SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN=22]="SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN",e[e.SCRIPT_DATA_ESCAPED_END_TAG_OPEN=23]="SCRIPT_DATA_ESCAPED_END_TAG_OPEN",e[e.SCRIPT_DATA_ESCAPED_END_TAG_NAME=24]="SCRIPT_DATA_ESCAPED_END_TAG_NAME",e[e.SCRIPT_DATA_DOUBLE_ESCAPE_START=25]="SCRIPT_DATA_DOUBLE_ESCAPE_START",e[e.SCRIPT_DATA_DOUBLE_ESCAPED=26]="SCRIPT_DATA_DOUBLE_ESCAPED",e[e.SCRIPT_DATA_DOUBLE_ESCAPED_DASH=27]="SCRIPT_DATA_DOUBLE_ESCAPED_DASH",e[e.SCRIPT_DATA_DOUBLE_ESCAPED_DASH_DASH=28]="SCRIPT_DATA_DOUBLE_ESCAPED_DASH_DASH",e[e.SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN=29]="SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN",e[e.SCRIPT_DATA_DOUBLE_ESCAPE_END=30]="SCRIPT_DATA_DOUBLE_ESCAPE_END",e[e.BEFORE_ATTRIBUTE_NAME=31]="BEFORE_ATTRIBUTE_NAME",e[e.ATTRIBUTE_NAME=32]="ATTRIBUTE_NAME",e[e.AFTER_ATTRIBUTE_NAME=33]="AFTER_ATTRIBUTE_NAME",e[e.BEFORE_ATTRIBUTE_VALUE=34]="BEFORE_ATTRIBUTE_VALUE",e[e.ATTRIBUTE_VALUE_DOUBLE_QUOTED=35]="ATTRIBUTE_VALUE_DOUBLE_QUOTED",e[e.ATTRIBUTE_VALUE_SINGLE_QUOTED=36]="ATTRIBUTE_VALUE_SINGLE_QUOTED",e[e.ATTRIBUTE_VALUE_UNQUOTED=37]="ATTRIBUTE_VALUE_UNQUOTED",e[e.AFTER_ATTRIBUTE_VALUE_QUOTED=38]="AFTER_ATTRIBUTE_VALUE_QUOTED",e[e.SELF_CLOSING_START_TAG=39]="SELF_CLOSING_START_TAG",e[e.BOGUS_COMMENT=40]="BOGUS_COMMENT",e[e.MARKUP_DECLARATION_OPEN=41]="MARKUP_DECLARATION_OPEN",e[e.COMMENT_START=42]="COMMENT_START",e[e.COMMENT_START_DASH=43]="COMMENT_START_DASH",e[e.COMMENT=44]="COMMENT",e[e.COMMENT_LESS_THAN_SIGN=45]="COMMENT_LESS_THAN_SIGN",e[e.COMMENT_LESS_THAN_SIGN_BANG=46]="COMMENT_LESS_THAN_SIGN_BANG",e[e.COMMENT_LESS_THAN_SIGN_BANG_DASH=47]="COMMENT_LESS_THAN_SIGN_BANG_DASH",e[e.COMMENT_LESS_THAN_SIGN_BANG_DASH_DASH=48]="COMMENT_LESS_THAN_SIGN_BANG_DASH_DASH",e[e.COMMENT_END_DASH=49]="COMMENT_END_DASH",e[e.COMMENT_END=50]="COMMENT_END",e[e.COMMENT_END_BANG=51]="COMMENT_END_BANG",e[e.DOCTYPE=52]="DOCTYPE",e[e.BEFORE_DOCTYPE_NAME=53]="BEFORE_DOCTYPE_NAME",e[e.DOCTYPE_NAME=54]="DOCTYPE_NAME",e[e.AFTER_DOCTYPE_NAME=55]="AFTER_DOCTYPE_NAME",e[e.AFTER_DOCTYPE_PUBLIC_KEYWORD=56]="AFTER_DOCTYPE_PUBLIC_KEYWORD",e[e.BEFORE_DOCTYPE_PUBLIC_IDENTIFIER=57]="BEFORE_DOCTYPE_PUBLIC_IDENTIFIER",e[e.DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED=58]="DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED",e[e.DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED=59]="DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED",e[e.AFTER_DOCTYPE_PUBLIC_IDENTIFIER=60]="AFTER_DOCTYPE_PUBLIC_IDENTIFIER",e[e.BETWEEN_DOCTYPE_PUBLIC_AND_SYSTEM_IDENTIFIERS=61]="BETWEEN_DOCTYPE_PUBLIC_AND_SYSTEM_IDENTIFIERS",e[e.AFTER_DOCTYPE_SYSTEM_KEYWORD=62]="AFTER_DOCTYPE_SYSTEM_KEYWORD",e[e.BEFORE_DOCTYPE_SYSTEM_IDENTIFIER=63]="BEFORE_DOCTYPE_SYSTEM_IDENTIFIER",e[e.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED=64]="DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED",e[e.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED=65]="DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED",e[e.AFTER_DOCTYPE_SYSTEM_IDENTIFIER=66]="AFTER_DOCTYPE_SYSTEM_IDENTIFIER",e[e.BOGUS_DOCTYPE=67]="BOGUS_DOCTYPE",e[e.CDATA_SECTION=68]="CDATA_SECTION",e[e.CDATA_SECTION_BRACKET=69]="CDATA_SECTION_BRACKET",e[e.CDATA_SECTION_END=70]="CDATA_SECTION_END",e[e.CHARACTER_REFERENCE=71]="CHARACTER_REFERENCE",e[e.AMBIGUOUS_AMPERSAND=72]="AMBIGUOUS_AMPERSAND"})(g||(g={}));const yt={DATA:g.DATA,RCDATA:g.RCDATA,RAWTEXT:g.RAWTEXT,SCRIPT_DATA:g.SCRIPT_DATA,PLAINTEXT:g.PLAINTEXT,CDATA_SECTION:g.CDATA_SECTION};function db(e){return e>=h.DIGIT_0&&e<=h.DIGIT_9}function ln(e){return e>=h.LATIN_CAPITAL_A&&e<=h.LATIN_CAPITAL_Z}function fb(e){return e>=h.LATIN_SMALL_A&&e<=h.LATIN_SMALL_Z}function Rr(e){return fb(e)||ln(e)}function Ju(e){return Rr(e)||db(e)}function ps(e){return e+32}function Nd(e){return e===h.SPACE||e===h.LINE_FEED||e===h.TABULATION||e===h.FORM_FEED}function Zu(e){return Nd(e)||e===h.SOLIDUS||e===h.GREATER_THAN_SIGN}function mb(e){return e===h.NULL?L.nullCharacterReference:e>1114111?L.characterReferenceOutsideUnicodeRange:_d(e)?L.surrogateCharacterReference:wd(e)?L.noncharacterCharacterReference:Cd(e)||e===h.CARRIAGE_RETURN?L.controlCharacterReference:null}class hb{constructor(t,r){this.options=t,this.handler=r,this.paused=!1,this.inLoop=!1,this.inForeignNode=!1,this.lastStartTagName="",this.active=!1,this.state=g.DATA,this.returnState=g.DATA,this.entityStartPos=0,this.consumedAfterSnapshot=-1,this.currentCharacterToken=null,this.currentToken=null,this.currentAttr={name:"",value:""},this.preprocessor=new ZE(r),this.currentLocation=this.getCurrentLocation(-1),this.entityDecoder=new ob(eb,(a,n)=>{this.preprocessor.pos=this.entityStartPos+n-1,this._flushCodePointConsumedAsCharacterReference(a)},r.onParseError?{missingSemicolonAfterCharacterReference:()=>{this._err(L.missingSemicolonAfterCharacterReference,1)},absenceOfDigitsInNumericCharacterReference:a=>{this._err(L.absenceOfDigitsInNumericCharacterReference,this.entityStartPos-this.preprocessor.pos+a)},validateNumericCharacterReference:a=>{const n=mb(a);n&&this._err(n,1)}}:void 0)}_err(t,r=0){var a,n;(n=(a=this.handler).onParseError)===null||n===void 0||n.call(a,this.preprocessor.getError(t,r))}getCurrentLocation(t){return this.options.sourceCodeLocationInfo?{startLine:this.preprocessor.line,startCol:this.preprocessor.col-t,startOffset:this.preprocessor.offset-t,endLine:-1,endCol:-1,endOffset:-1}:null}_runParsingLoop(){if(!this.inLoop){for(this.inLoop=!0;this.active&&!this.paused;){this.consumedAfterSnapshot=0;const t=this._consume();this._ensureHibernation()||this._callState(t)}this.inLoop=!1}}pause(){this.paused=!0}resume(t){if(!this.paused)throw new Error("Parser was already resumed");this.paused=!1,!this.inLoop&&(this._runParsingLoop(),this.paused||t==null||t())}write(t,r,a){this.active=!0,this.preprocessor.write(t,r),this._runParsingLoop(),this.paused||a==null||a()}insertHtmlAtCurrentPos(t){this.active=!0,this.preprocessor.insertHtmlAtCurrentPos(t),this._runParsingLoop()}_ensureHibernation(){return this.preprocessor.endOfChunkHit?(this.preprocessor.retreat(this.consumedAfterSnapshot),this.consumedAfterSnapshot=0,this.active=!1,!0):!1}_consume(){return this.consumedAfterSnapshot++,this.preprocessor.advance()}_advanceBy(t){this.consumedAfterSnapshot+=t;for(let r=0;r<t;r++)this.preprocessor.advance()}_consumeSequenceIfMatch(t,r){return this.preprocessor.startsWith(t,r)?(this._advanceBy(t.length-1),!0):!1}_createStartTagToken(){this.currentToken={type:De.START_TAG,tagName:"",tagID:s.UNKNOWN,selfClosing:!1,ackSelfClosing:!1,attrs:[],location:this.getCurrentLocation(1)}}_createEndTagToken(){this.currentToken={type:De.END_TAG,tagName:"",tagID:s.UNKNOWN,selfClosing:!1,ackSelfClosing:!1,attrs:[],location:this.getCurrentLocation(2)}}_createCommentToken(t){this.currentToken={type:De.COMMENT,data:"",location:this.getCurrentLocation(t)}}_createDoctypeToken(t){this.currentToken={type:De.DOCTYPE,name:t,forceQuirks:!1,publicId:null,systemId:null,location:this.currentLocation}}_createCharacterToken(t,r){this.currentCharacterToken={type:t,chars:r,location:this.currentLocation}}_createAttr(t){this.currentAttr={name:t,value:""},this.currentLocation=this.getCurrentLocation(0)}_leaveAttrName(){var t,r;const a=this.currentToken;if(Rd(a,this.currentAttr.name)===null){if(a.attrs.push(this.currentAttr),a.location&&this.currentLocation){const n=(t=(r=a.location).attrs)!==null&&t!==void 0?t:r.attrs=Object.create(null);n[this.currentAttr.name]=this.currentLocation,this._leaveAttrValue()}}else this._err(L.duplicateAttribute)}_leaveAttrValue(){this.currentLocation&&(this.currentLocation.endLine=this.preprocessor.line,this.currentLocation.endCol=this.preprocessor.col,this.currentLocation.endOffset=this.preprocessor.offset)}prepareToken(t){this._emitCurrentCharacterToken(t.location),this.currentToken=null,t.location&&(t.location.endLine=this.preprocessor.line,t.location.endCol=this.preprocessor.col+1,t.location.endOffset=this.preprocessor.offset+1),this.currentLocation=this.getCurrentLocation(-1)}emitCurrentTagToken(){const t=this.currentToken;this.prepareToken(t),t.tagID=qs(t.tagName),t.type===De.START_TAG?(this.lastStartTagName=t.tagName,this.handler.onStartTag(t)):(t.attrs.length>0&&this._err(L.endTagWithAttributes),t.selfClosing&&this._err(L.endTagWithTrailingSolidus),this.handler.onEndTag(t)),this.preprocessor.dropParsedChunk()}emitCurrentComment(t){this.prepareToken(t),this.handler.onComment(t),this.preprocessor.dropParsedChunk()}emitCurrentDoctype(t){this.prepareToken(t),this.handler.onDoctype(t),this.preprocessor.dropParsedChunk()}_emitCurrentCharacterToken(t){if(this.currentCharacterToken){switch(t&&this.currentCharacterToken.location&&(this.currentCharacterToken.location.endLine=t.startLine,this.currentCharacterToken.location.endCol=t.startCol,this.currentCharacterToken.location.endOffset=t.startOffset),this.currentCharacterToken.type){case De.CHARACTER:{this.handler.onCharacter(this.currentCharacterToken);break}case De.NULL_CHARACTER:{this.handler.onNullCharacter(this.currentCharacterToken);break}case De.WHITESPACE_CHARACTER:{this.handler.onWhitespaceCharacter(this.currentCharacterToken);break}}this.currentCharacterToken=null}}_emitEOFToken(){const t=this.getCurrentLocation(0);t&&(t.endLine=t.startLine,t.endCol=t.startCol,t.endOffset=t.startOffset),this._emitCurrentCharacterToken(t),this.handler.onEof({type:De.EOF,location:t}),this.active=!1}_appendCharToCurrentCharacterToken(t,r){if(this.currentCharacterToken)if(this.currentCharacterToken.type===t){this.currentCharacterToken.chars+=r;return}else this.currentLocation=this.getCurrentLocation(0),this._emitCurrentCharacterToken(this.currentLocation),this.preprocessor.dropParsedChunk();this._createCharacterToken(t,r)}_emitCodePoint(t){const r=Nd(t)?De.WHITESPACE_CHARACTER:t===h.NULL?De.NULL_CHARACTER:De.CHARACTER;this._appendCharToCurrentCharacterToken(r,String.fromCodePoint(t))}_emitChars(t){this._appendCharToCurrentCharacterToken(De.CHARACTER,t)}_startCharacterReference(){this.returnState=this.state,this.state=g.CHARACTER_REFERENCE,this.entityStartPos=this.preprocessor.pos,this.entityDecoder.startEntity(this._isCharacterReferenceInAttribute()?hr.Attribute:hr.Legacy)}_isCharacterReferenceInAttribute(){return this.returnState===g.ATTRIBUTE_VALUE_DOUBLE_QUOTED||this.returnState===g.ATTRIBUTE_VALUE_SINGLE_QUOTED||this.returnState===g.ATTRIBUTE_VALUE_UNQUOTED}_flushCodePointConsumedAsCharacterReference(t){this._isCharacterReferenceInAttribute()?this.currentAttr.value+=String.fromCodePoint(t):this._emitCodePoint(t)}_callState(t){switch(this.state){case g.DATA:{this._stateData(t);break}case g.RCDATA:{this._stateRcdata(t);break}case g.RAWTEXT:{this._stateRawtext(t);break}case g.SCRIPT_DATA:{this._stateScriptData(t);break}case g.PLAINTEXT:{this._statePlaintext(t);break}case g.TAG_OPEN:{this._stateTagOpen(t);break}case g.END_TAG_OPEN:{this._stateEndTagOpen(t);break}case g.TAG_NAME:{this._stateTagName(t);break}case g.RCDATA_LESS_THAN_SIGN:{this._stateRcdataLessThanSign(t);break}case g.RCDATA_END_TAG_OPEN:{this._stateRcdataEndTagOpen(t);break}case g.RCDATA_END_TAG_NAME:{this._stateRcdataEndTagName(t);break}case g.RAWTEXT_LESS_THAN_SIGN:{this._stateRawtextLessThanSign(t);break}case g.RAWTEXT_END_TAG_OPEN:{this._stateRawtextEndTagOpen(t);break}case g.RAWTEXT_END_TAG_NAME:{this._stateRawtextEndTagName(t);break}case g.SCRIPT_DATA_LESS_THAN_SIGN:{this._stateScriptDataLessThanSign(t);break}case g.SCRIPT_DATA_END_TAG_OPEN:{this._stateScriptDataEndTagOpen(t);break}case g.SCRIPT_DATA_END_TAG_NAME:{this._stateScriptDataEndTagName(t);break}case g.SCRIPT_DATA_ESCAPE_START:{this._stateScriptDataEscapeStart(t);break}case g.SCRIPT_DATA_ESCAPE_START_DASH:{this._stateScriptDataEscapeStartDash(t);break}case g.SCRIPT_DATA_ESCAPED:{this._stateScriptDataEscaped(t);break}case g.SCRIPT_DATA_ESCAPED_DASH:{this._stateScriptDataEscapedDash(t);break}case g.SCRIPT_DATA_ESCAPED_DASH_DASH:{this._stateScriptDataEscapedDashDash(t);break}case g.SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN:{this._stateScriptDataEscapedLessThanSign(t);break}case g.SCRIPT_DATA_ESCAPED_END_TAG_OPEN:{this._stateScriptDataEscapedEndTagOpen(t);break}case g.SCRIPT_DATA_ESCAPED_END_TAG_NAME:{this._stateScriptDataEscapedEndTagName(t);break}case g.SCRIPT_DATA_DOUBLE_ESCAPE_START:{this._stateScriptDataDoubleEscapeStart(t);break}case g.SCRIPT_DATA_DOUBLE_ESCAPED:{this._stateScriptDataDoubleEscaped(t);break}case g.SCRIPT_DATA_DOUBLE_ESCAPED_DASH:{this._stateScriptDataDoubleEscapedDash(t);break}case g.SCRIPT_DATA_DOUBLE_ESCAPED_DASH_DASH:{this._stateScriptDataDoubleEscapedDashDash(t);break}case g.SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN:{this._stateScriptDataDoubleEscapedLessThanSign(t);break}case g.SCRIPT_DATA_DOUBLE_ESCAPE_END:{this._stateScriptDataDoubleEscapeEnd(t);break}case g.BEFORE_ATTRIBUTE_NAME:{this._stateBeforeAttributeName(t);break}case g.ATTRIBUTE_NAME:{this._stateAttributeName(t);break}case g.AFTER_ATTRIBUTE_NAME:{this._stateAfterAttributeName(t);break}case g.BEFORE_ATTRIBUTE_VALUE:{this._stateBeforeAttributeValue(t);break}case g.ATTRIBUTE_VALUE_DOUBLE_QUOTED:{this._stateAttributeValueDoubleQuoted(t);break}case g.ATTRIBUTE_VALUE_SINGLE_QUOTED:{this._stateAttributeValueSingleQuoted(t);break}case g.ATTRIBUTE_VALUE_UNQUOTED:{this._stateAttributeValueUnquoted(t);break}case g.AFTER_ATTRIBUTE_VALUE_QUOTED:{this._stateAfterAttributeValueQuoted(t);break}case g.SELF_CLOSING_START_TAG:{this._stateSelfClosingStartTag(t);break}case g.BOGUS_COMMENT:{this._stateBogusComment(t);break}case g.MARKUP_DECLARATION_OPEN:{this._stateMarkupDeclarationOpen(t);break}case g.COMMENT_START:{this._stateCommentStart(t);break}case g.COMMENT_START_DASH:{this._stateCommentStartDash(t);break}case g.COMMENT:{this._stateComment(t);break}case g.COMMENT_LESS_THAN_SIGN:{this._stateCommentLessThanSign(t);break}case g.COMMENT_LESS_THAN_SIGN_BANG:{this._stateCommentLessThanSignBang(t);break}case g.COMMENT_LESS_THAN_SIGN_BANG_DASH:{this._stateCommentLessThanSignBangDash(t);break}case g.COMMENT_LESS_THAN_SIGN_BANG_DASH_DASH:{this._stateCommentLessThanSignBangDashDash(t);break}case g.COMMENT_END_DASH:{this._stateCommentEndDash(t);break}case g.COMMENT_END:{this._stateCommentEnd(t);break}case g.COMMENT_END_BANG:{this._stateCommentEndBang(t);break}case g.DOCTYPE:{this._stateDoctype(t);break}case g.BEFORE_DOCTYPE_NAME:{this._stateBeforeDoctypeName(t);break}case g.DOCTYPE_NAME:{this._stateDoctypeName(t);break}case g.AFTER_DOCTYPE_NAME:{this._stateAfterDoctypeName(t);break}case g.AFTER_DOCTYPE_PUBLIC_KEYWORD:{this._stateAfterDoctypePublicKeyword(t);break}case g.BEFORE_DOCTYPE_PUBLIC_IDENTIFIER:{this._stateBeforeDoctypePublicIdentifier(t);break}case g.DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED:{this._stateDoctypePublicIdentifierDoubleQuoted(t);break}case g.DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED:{this._stateDoctypePublicIdentifierSingleQuoted(t);break}case g.AFTER_DOCTYPE_PUBLIC_IDENTIFIER:{this._stateAfterDoctypePublicIdentifier(t);break}case g.BETWEEN_DOCTYPE_PUBLIC_AND_SYSTEM_IDENTIFIERS:{this._stateBetweenDoctypePublicAndSystemIdentifiers(t);break}case g.AFTER_DOCTYPE_SYSTEM_KEYWORD:{this._stateAfterDoctypeSystemKeyword(t);break}case g.BEFORE_DOCTYPE_SYSTEM_IDENTIFIER:{this._stateBeforeDoctypeSystemIdentifier(t);break}case g.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED:{this._stateDoctypeSystemIdentifierDoubleQuoted(t);break}case g.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED:{this._stateDoctypeSystemIdentifierSingleQuoted(t);break}case g.AFTER_DOCTYPE_SYSTEM_IDENTIFIER:{this._stateAfterDoctypeSystemIdentifier(t);break}case g.BOGUS_DOCTYPE:{this._stateBogusDoctype(t);break}case g.CDATA_SECTION:{this._stateCdataSection(t);break}case g.CDATA_SECTION_BRACKET:{this._stateCdataSectionBracket(t);break}case g.CDATA_SECTION_END:{this._stateCdataSectionEnd(t);break}case g.CHARACTER_REFERENCE:{this._stateCharacterReference();break}case g.AMBIGUOUS_AMPERSAND:{this._stateAmbiguousAmpersand(t);break}default:throw new Error("Unknown state")}}_stateData(t){switch(t){case h.LESS_THAN_SIGN:{this.state=g.TAG_OPEN;break}case h.AMPERSAND:{this._startCharacterReference();break}case h.NULL:{this._err(L.unexpectedNullCharacter),this._emitCodePoint(t);break}case h.EOF:{this._emitEOFToken();break}default:this._emitCodePoint(t)}}_stateRcdata(t){switch(t){case h.AMPERSAND:{this._startCharacterReference();break}case h.LESS_THAN_SIGN:{this.state=g.RCDATA_LESS_THAN_SIGN;break}case h.NULL:{this._err(L.unexpectedNullCharacter),this._emitChars(Qe);break}case h.EOF:{this._emitEOFToken();break}default:this._emitCodePoint(t)}}_stateRawtext(t){switch(t){case h.LESS_THAN_SIGN:{this.state=g.RAWTEXT_LESS_THAN_SIGN;break}case h.NULL:{this._err(L.unexpectedNullCharacter),this._emitChars(Qe);break}case h.EOF:{this._emitEOFToken();break}default:this._emitCodePoint(t)}}_stateScriptData(t){switch(t){case h.LESS_THAN_SIGN:{this.state=g.SCRIPT_DATA_LESS_THAN_SIGN;break}case h.NULL:{this._err(L.unexpectedNullCharacter),this._emitChars(Qe);break}case h.EOF:{this._emitEOFToken();break}default:this._emitCodePoint(t)}}_statePlaintext(t){switch(t){case h.NULL:{this._err(L.unexpectedNullCharacter),this._emitChars(Qe);break}case h.EOF:{this._emitEOFToken();break}default:this._emitCodePoint(t)}}_stateTagOpen(t){if(Rr(t))this._createStartTagToken(),this.state=g.TAG_NAME,this._stateTagName(t);else switch(t){case h.EXCLAMATION_MARK:{this.state=g.MARKUP_DECLARATION_OPEN;break}case h.SOLIDUS:{this.state=g.END_TAG_OPEN;break}case h.QUESTION_MARK:{this._err(L.unexpectedQuestionMarkInsteadOfTagName),this._createCommentToken(1),this.state=g.BOGUS_COMMENT,this._stateBogusComment(t);break}case h.EOF:{this._err(L.eofBeforeTagName),this._emitChars("<"),this._emitEOFToken();break}default:this._err(L.invalidFirstCharacterOfTagName),this._emitChars("<"),this.state=g.DATA,this._stateData(t)}}_stateEndTagOpen(t){if(Rr(t))this._createEndTagToken(),this.state=g.TAG_NAME,this._stateTagName(t);else switch(t){case h.GREATER_THAN_SIGN:{this._err(L.missingEndTagName),this.state=g.DATA;break}case h.EOF:{this._err(L.eofBeforeTagName),this._emitChars("</"),this._emitEOFToken();break}default:this._err(L.invalidFirstCharacterOfTagName),this._createCommentToken(2),this.state=g.BOGUS_COMMENT,this._stateBogusComment(t)}}_stateTagName(t){const r=this.currentToken;switch(t){case h.SPACE:case h.LINE_FEED:case h.TABULATION:case h.FORM_FEED:{this.state=g.BEFORE_ATTRIBUTE_NAME;break}case h.SOLIDUS:{this.state=g.SELF_CLOSING_START_TAG;break}case h.GREATER_THAN_SIGN:{this.state=g.DATA,this.emitCurrentTagToken();break}case h.NULL:{this._err(L.unexpectedNullCharacter),r.tagName+=Qe;break}case h.EOF:{this._err(L.eofInTag),this._emitEOFToken();break}default:r.tagName+=String.fromCodePoint(ln(t)?ps(t):t)}}_stateRcdataLessThanSign(t){t===h.SOLIDUS?this.state=g.RCDATA_END_TAG_OPEN:(this._emitChars("<"),this.state=g.RCDATA,this._stateRcdata(t))}_stateRcdataEndTagOpen(t){Rr(t)?(this.state=g.RCDATA_END_TAG_NAME,this._stateRcdataEndTagName(t)):(this._emitChars("</"),this.state=g.RCDATA,this._stateRcdata(t))}handleSpecialEndTag(t){if(!this.preprocessor.startsWith(this.lastStartTagName,!1))return!this._ensureHibernation();this._createEndTagToken();const r=this.currentToken;switch(r.tagName=this.lastStartTagName,this.preprocessor.peek(this.lastStartTagName.length)){case h.SPACE:case h.LINE_FEED:case h.TABULATION:case h.FORM_FEED:return this._advanceBy(this.lastStartTagName.length),this.state=g.BEFORE_ATTRIBUTE_NAME,!1;case h.SOLIDUS:return this._advanceBy(this.lastStartTagName.length),this.state=g.SELF_CLOSING_START_TAG,!1;case h.GREATER_THAN_SIGN:return this._advanceBy(this.lastStartTagName.length),this.emitCurrentTagToken(),this.state=g.DATA,!1;default:return!this._ensureHibernation()}}_stateRcdataEndTagName(t){this.handleSpecialEndTag(t)&&(this._emitChars("</"),this.state=g.RCDATA,this._stateRcdata(t))}_stateRawtextLessThanSign(t){t===h.SOLIDUS?this.state=g.RAWTEXT_END_TAG_OPEN:(this._emitChars("<"),this.state=g.RAWTEXT,this._stateRawtext(t))}_stateRawtextEndTagOpen(t){Rr(t)?(this.state=g.RAWTEXT_END_TAG_NAME,this._stateRawtextEndTagName(t)):(this._emitChars("</"),this.state=g.RAWTEXT,this._stateRawtext(t))}_stateRawtextEndTagName(t){this.handleSpecialEndTag(t)&&(this._emitChars("</"),this.state=g.RAWTEXT,this._stateRawtext(t))}_stateScriptDataLessThanSign(t){switch(t){case h.SOLIDUS:{this.state=g.SCRIPT_DATA_END_TAG_OPEN;break}case h.EXCLAMATION_MARK:{this.state=g.SCRIPT_DATA_ESCAPE_START,this._emitChars("<!");break}default:this._emitChars("<"),this.state=g.SCRIPT_DATA,this._stateScriptData(t)}}_stateScriptDataEndTagOpen(t){Rr(t)?(this.state=g.SCRIPT_DATA_END_TAG_NAME,this._stateScriptDataEndTagName(t)):(this._emitChars("</"),this.state=g.SCRIPT_DATA,this._stateScriptData(t))}_stateScriptDataEndTagName(t){this.handleSpecialEndTag(t)&&(this._emitChars("</"),this.state=g.SCRIPT_DATA,this._stateScriptData(t))}_stateScriptDataEscapeStart(t){t===h.HYPHEN_MINUS?(this.state=g.SCRIPT_DATA_ESCAPE_START_DASH,this._emitChars("-")):(this.state=g.SCRIPT_DATA,this._stateScriptData(t))}_stateScriptDataEscapeStartDash(t){t===h.HYPHEN_MINUS?(this.state=g.SCRIPT_DATA_ESCAPED_DASH_DASH,this._emitChars("-")):(this.state=g.SCRIPT_DATA,this._stateScriptData(t))}_stateScriptDataEscaped(t){switch(t){case h.HYPHEN_MINUS:{this.state=g.SCRIPT_DATA_ESCAPED_DASH,this._emitChars("-");break}case h.LESS_THAN_SIGN:{this.state=g.SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN;break}case h.NULL:{this._err(L.unexpectedNullCharacter),this._emitChars(Qe);break}case h.EOF:{this._err(L.eofInScriptHtmlCommentLikeText),this._emitEOFToken();break}default:this._emitCodePoint(t)}}_stateScriptDataEscapedDash(t){switch(t){case h.HYPHEN_MINUS:{this.state=g.SCRIPT_DATA_ESCAPED_DASH_DASH,this._emitChars("-");break}case h.LESS_THAN_SIGN:{this.state=g.SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN;break}case h.NULL:{this._err(L.unexpectedNullCharacter),this.state=g.SCRIPT_DATA_ESCAPED,this._emitChars(Qe);break}case h.EOF:{this._err(L.eofInScriptHtmlCommentLikeText),this._emitEOFToken();break}default:this.state=g.SCRIPT_DATA_ESCAPED,this._emitCodePoint(t)}}_stateScriptDataEscapedDashDash(t){switch(t){case h.HYPHEN_MINUS:{this._emitChars("-");break}case h.LESS_THAN_SIGN:{this.state=g.SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN;break}case h.GREATER_THAN_SIGN:{this.state=g.SCRIPT_DATA,this._emitChars(">");break}case h.NULL:{this._err(L.unexpectedNullCharacter),this.state=g.SCRIPT_DATA_ESCAPED,this._emitChars(Qe);break}case h.EOF:{this._err(L.eofInScriptHtmlCommentLikeText),this._emitEOFToken();break}default:this.state=g.SCRIPT_DATA_ESCAPED,this._emitCodePoint(t)}}_stateScriptDataEscapedLessThanSign(t){t===h.SOLIDUS?this.state=g.SCRIPT_DATA_ESCAPED_END_TAG_OPEN:Rr(t)?(this._emitChars("<"),this.state=g.SCRIPT_DATA_DOUBLE_ESCAPE_START,this._stateScriptDataDoubleEscapeStart(t)):(this._emitChars("<"),this.state=g.SCRIPT_DATA_ESCAPED,this._stateScriptDataEscaped(t))}_stateScriptDataEscapedEndTagOpen(t){Rr(t)?(this.state=g.SCRIPT_DATA_ESCAPED_END_TAG_NAME,this._stateScriptDataEscapedEndTagName(t)):(this._emitChars("</"),this.state=g.SCRIPT_DATA_ESCAPED,this._stateScriptDataEscaped(t))}_stateScriptDataEscapedEndTagName(t){this.handleSpecialEndTag(t)&&(this._emitChars("</"),this.state=g.SCRIPT_DATA_ESCAPED,this._stateScriptDataEscaped(t))}_stateScriptDataDoubleEscapeStart(t){if(this.preprocessor.startsWith(It.SCRIPT,!1)&&Zu(this.preprocessor.peek(It.SCRIPT.length))){this._emitCodePoint(t);for(let r=0;r<It.SCRIPT.length;r++)this._emitCodePoint(this._consume());this.state=g.SCRIPT_DATA_DOUBLE_ESCAPED}else this._ensureHibernation()||(this.state=g.SCRIPT_DATA_ESCAPED,this._stateScriptDataEscaped(t))}_stateScriptDataDoubleEscaped(t){switch(t){case h.HYPHEN_MINUS:{this.state=g.SCRIPT_DATA_DOUBLE_ESCAPED_DASH,this._emitChars("-");break}case h.LESS_THAN_SIGN:{this.state=g.SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN,this._emitChars("<");break}case h.NULL:{this._err(L.unexpectedNullCharacter),this._emitChars(Qe);break}case h.EOF:{this._err(L.eofInScriptHtmlCommentLikeText),this._emitEOFToken();break}default:this._emitCodePoint(t)}}_stateScriptDataDoubleEscapedDash(t){switch(t){case h.HYPHEN_MINUS:{this.state=g.SCRIPT_DATA_DOUBLE_ESCAPED_DASH_DASH,this._emitChars("-");break}case h.LESS_THAN_SIGN:{this.state=g.SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN,this._emitChars("<");break}case h.NULL:{this._err(L.unexpectedNullCharacter),this.state=g.SCRIPT_DATA_DOUBLE_ESCAPED,this._emitChars(Qe);break}case h.EOF:{this._err(L.eofInScriptHtmlCommentLikeText),this._emitEOFToken();break}default:this.state=g.SCRIPT_DATA_DOUBLE_ESCAPED,this._emitCodePoint(t)}}_stateScriptDataDoubleEscapedDashDash(t){switch(t){case h.HYPHEN_MINUS:{this._emitChars("-");break}case h.LESS_THAN_SIGN:{this.state=g.SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN,this._emitChars("<");break}case h.GREATER_THAN_SIGN:{this.state=g.SCRIPT_DATA,this._emitChars(">");break}case h.NULL:{this._err(L.unexpectedNullCharacter),this.state=g.SCRIPT_DATA_DOUBLE_ESCAPED,this._emitChars(Qe);break}case h.EOF:{this._err(L.eofInScriptHtmlCommentLikeText),this._emitEOFToken();break}default:this.state=g.SCRIPT_DATA_DOUBLE_ESCAPED,this._emitCodePoint(t)}}_stateScriptDataDoubleEscapedLessThanSign(t){t===h.SOLIDUS?(this.state=g.SCRIPT_DATA_DOUBLE_ESCAPE_END,this._emitChars("/")):(this.state=g.SCRIPT_DATA_DOUBLE_ESCAPED,this._stateScriptDataDoubleEscaped(t))}_stateScriptDataDoubleEscapeEnd(t){if(this.preprocessor.startsWith(It.SCRIPT,!1)&&Zu(this.preprocessor.peek(It.SCRIPT.length))){this._emitCodePoint(t);for(let r=0;r<It.SCRIPT.length;r++)this._emitCodePoint(this._consume());this.state=g.SCRIPT_DATA_ESCAPED}else this._ensureHibernation()||(this.state=g.SCRIPT_DATA_DOUBLE_ESCAPED,this._stateScriptDataDoubleEscaped(t))}_stateBeforeAttributeName(t){switch(t){case h.SPACE:case h.LINE_FEED:case h.TABULATION:case h.FORM_FEED:break;case h.SOLIDUS:case h.GREATER_THAN_SIGN:case h.EOF:{this.state=g.AFTER_ATTRIBUTE_NAME,this._stateAfterAttributeName(t);break}case h.EQUALS_SIGN:{this._err(L.unexpectedEqualsSignBeforeAttributeName),this._createAttr("="),this.state=g.ATTRIBUTE_NAME;break}default:this._createAttr(""),this.state=g.ATTRIBUTE_NAME,this._stateAttributeName(t)}}_stateAttributeName(t){switch(t){case h.SPACE:case h.LINE_FEED:case h.TABULATION:case h.FORM_FEED:case h.SOLIDUS:case h.GREATER_THAN_SIGN:case h.EOF:{this._leaveAttrName(),this.state=g.AFTER_ATTRIBUTE_NAME,this._stateAfterAttributeName(t);break}case h.EQUALS_SIGN:{this._leaveAttrName(),this.state=g.BEFORE_ATTRIBUTE_VALUE;break}case h.QUOTATION_MARK:case h.APOSTROPHE:case h.LESS_THAN_SIGN:{this._err(L.unexpectedCharacterInAttributeName),this.currentAttr.name+=String.fromCodePoint(t);break}case h.NULL:{this._err(L.unexpectedNullCharacter),this.currentAttr.name+=Qe;break}default:this.currentAttr.name+=String.fromCodePoint(ln(t)?ps(t):t)}}_stateAfterAttributeName(t){switch(t){case h.SPACE:case h.LINE_FEED:case h.TABULATION:case h.FORM_FEED:break;case h.SOLIDUS:{this.state=g.SELF_CLOSING_START_TAG;break}case h.EQUALS_SIGN:{this.state=g.BEFORE_ATTRIBUTE_VALUE;break}case h.GREATER_THAN_SIGN:{this.state=g.DATA,this.emitCurrentTagToken();break}case h.EOF:{this._err(L.eofInTag),this._emitEOFToken();break}default:this._createAttr(""),this.state=g.ATTRIBUTE_NAME,this._stateAttributeName(t)}}_stateBeforeAttributeValue(t){switch(t){case h.SPACE:case h.LINE_FEED:case h.TABULATION:case h.FORM_FEED:break;case h.QUOTATION_MARK:{this.state=g.ATTRIBUTE_VALUE_DOUBLE_QUOTED;break}case h.APOSTROPHE:{this.state=g.ATTRIBUTE_VALUE_SINGLE_QUOTED;break}case h.GREATER_THAN_SIGN:{this._err(L.missingAttributeValue),this.state=g.DATA,this.emitCurrentTagToken();break}default:this.state=g.ATTRIBUTE_VALUE_UNQUOTED,this._stateAttributeValueUnquoted(t)}}_stateAttributeValueDoubleQuoted(t){switch(t){case h.QUOTATION_MARK:{this.state=g.AFTER_ATTRIBUTE_VALUE_QUOTED;break}case h.AMPERSAND:{this._startCharacterReference();break}case h.NULL:{this._err(L.unexpectedNullCharacter),this.currentAttr.value+=Qe;break}case h.EOF:{this._err(L.eofInTag),this._emitEOFToken();break}default:this.currentAttr.value+=String.fromCodePoint(t)}}_stateAttributeValueSingleQuoted(t){switch(t){case h.APOSTROPHE:{this.state=g.AFTER_ATTRIBUTE_VALUE_QUOTED;break}case h.AMPERSAND:{this._startCharacterReference();break}case h.NULL:{this._err(L.unexpectedNullCharacter),this.currentAttr.value+=Qe;break}case h.EOF:{this._err(L.eofInTag),this._emitEOFToken();break}default:this.currentAttr.value+=String.fromCodePoint(t)}}_stateAttributeValueUnquoted(t){switch(t){case h.SPACE:case h.LINE_FEED:case h.TABULATION:case h.FORM_FEED:{this._leaveAttrValue(),this.state=g.BEFORE_ATTRIBUTE_NAME;break}case h.AMPERSAND:{this._startCharacterReference();break}case h.GREATER_THAN_SIGN:{this._leaveAttrValue(),this.state=g.DATA,this.emitCurrentTagToken();break}case h.NULL:{this._err(L.unexpectedNullCharacter),this.currentAttr.value+=Qe;break}case h.QUOTATION_MARK:case h.APOSTROPHE:case h.LESS_THAN_SIGN:case h.EQUALS_SIGN:case h.GRAVE_ACCENT:{this._err(L.unexpectedCharacterInUnquotedAttributeValue),this.currentAttr.value+=String.fromCodePoint(t);break}case h.EOF:{this._err(L.eofInTag),this._emitEOFToken();break}default:this.currentAttr.value+=String.fromCodePoint(t)}}_stateAfterAttributeValueQuoted(t){switch(t){case h.SPACE:case h.LINE_FEED:case h.TABULATION:case h.FORM_FEED:{this._leaveAttrValue(),this.state=g.BEFORE_ATTRIBUTE_NAME;break}case h.SOLIDUS:{this._leaveAttrValue(),this.state=g.SELF_CLOSING_START_TAG;break}case h.GREATER_THAN_SIGN:{this._leaveAttrValue(),this.state=g.DATA,this.emitCurrentTagToken();break}case h.EOF:{this._err(L.eofInTag),this._emitEOFToken();break}default:this._err(L.missingWhitespaceBetweenAttributes),this.state=g.BEFORE_ATTRIBUTE_NAME,this._stateBeforeAttributeName(t)}}_stateSelfClosingStartTag(t){switch(t){case h.GREATER_THAN_SIGN:{const r=this.currentToken;r.selfClosing=!0,this.state=g.DATA,this.emitCurrentTagToken();break}case h.EOF:{this._err(L.eofInTag),this._emitEOFToken();break}default:this._err(L.unexpectedSolidusInTag),this.state=g.BEFORE_ATTRIBUTE_NAME,this._stateBeforeAttributeName(t)}}_stateBogusComment(t){const r=this.currentToken;switch(t){case h.GREATER_THAN_SIGN:{this.state=g.DATA,this.emitCurrentComment(r);break}case h.EOF:{this.emitCurrentComment(r),this._emitEOFToken();break}case h.NULL:{this._err(L.unexpectedNullCharacter),r.data+=Qe;break}default:r.data+=String.fromCodePoint(t)}}_stateMarkupDeclarationOpen(t){this._consumeSequenceIfMatch(It.DASH_DASH,!0)?(this._createCommentToken(It.DASH_DASH.length+1),this.state=g.COMMENT_START):this._consumeSequenceIfMatch(It.DOCTYPE,!1)?(this.currentLocation=this.getCurrentLocation(It.DOCTYPE.length+1),this.state=g.DOCTYPE):this._consumeSequenceIfMatch(It.CDATA_START,!0)?this.inForeignNode?this.state=g.CDATA_SECTION:(this._err(L.cdataInHtmlContent),this._createCommentToken(It.CDATA_START.length+1),this.currentToken.data="[CDATA[",this.state=g.BOGUS_COMMENT):this._ensureHibernation()||(this._err(L.incorrectlyOpenedComment),this._createCommentToken(2),this.state=g.BOGUS_COMMENT,this._stateBogusComment(t))}_stateCommentStart(t){switch(t){case h.HYPHEN_MINUS:{this.state=g.COMMENT_START_DASH;break}case h.GREATER_THAN_SIGN:{this._err(L.abruptClosingOfEmptyComment),this.state=g.DATA;const r=this.currentToken;this.emitCurrentComment(r);break}default:this.state=g.COMMENT,this._stateComment(t)}}_stateCommentStartDash(t){const r=this.currentToken;switch(t){case h.HYPHEN_MINUS:{this.state=g.COMMENT_END;break}case h.GREATER_THAN_SIGN:{this._err(L.abruptClosingOfEmptyComment),this.state=g.DATA,this.emitCurrentComment(r);break}case h.EOF:{this._err(L.eofInComment),this.emitCurrentComment(r),this._emitEOFToken();break}default:r.data+="-",this.state=g.COMMENT,this._stateComment(t)}}_stateComment(t){const r=this.currentToken;switch(t){case h.HYPHEN_MINUS:{this.state=g.COMMENT_END_DASH;break}case h.LESS_THAN_SIGN:{r.data+="<",this.state=g.COMMENT_LESS_THAN_SIGN;break}case h.NULL:{this._err(L.unexpectedNullCharacter),r.data+=Qe;break}case h.EOF:{this._err(L.eofInComment),this.emitCurrentComment(r),this._emitEOFToken();break}default:r.data+=String.fromCodePoint(t)}}_stateCommentLessThanSign(t){const r=this.currentToken;switch(t){case h.EXCLAMATION_MARK:{r.data+="!",this.state=g.COMMENT_LESS_THAN_SIGN_BANG;break}case h.LESS_THAN_SIGN:{r.data+="<";break}default:this.state=g.COMMENT,this._stateComment(t)}}_stateCommentLessThanSignBang(t){t===h.HYPHEN_MINUS?this.state=g.COMMENT_LESS_THAN_SIGN_BANG_DASH:(this.state=g.COMMENT,this._stateComment(t))}_stateCommentLessThanSignBangDash(t){t===h.HYPHEN_MINUS?this.state=g.COMMENT_LESS_THAN_SIGN_BANG_DASH_DASH:(this.state=g.COMMENT_END_DASH,this._stateCommentEndDash(t))}_stateCommentLessThanSignBangDashDash(t){t!==h.GREATER_THAN_SIGN&&t!==h.EOF&&this._err(L.nestedComment),this.state=g.COMMENT_END,this._stateCommentEnd(t)}_stateCommentEndDash(t){const r=this.currentToken;switch(t){case h.HYPHEN_MINUS:{this.state=g.COMMENT_END;break}case h.EOF:{this._err(L.eofInComment),this.emitCurrentComment(r),this._emitEOFToken();break}default:r.data+="-",this.state=g.COMMENT,this._stateComment(t)}}_stateCommentEnd(t){const r=this.currentToken;switch(t){case h.GREATER_THAN_SIGN:{this.state=g.DATA,this.emitCurrentComment(r);break}case h.EXCLAMATION_MARK:{this.state=g.COMMENT_END_BANG;break}case h.HYPHEN_MINUS:{r.data+="-";break}case h.EOF:{this._err(L.eofInComment),this.emitCurrentComment(r),this._emitEOFToken();break}default:r.data+="--",this.state=g.COMMENT,this._stateComment(t)}}_stateCommentEndBang(t){const r=this.currentToken;switch(t){case h.HYPHEN_MINUS:{r.data+="--!",this.state=g.COMMENT_END_DASH;break}case h.GREATER_THAN_SIGN:{this._err(L.incorrectlyClosedComment),this.state=g.DATA,this.emitCurrentComment(r);break}case h.EOF:{this._err(L.eofInComment),this.emitCurrentComment(r),this._emitEOFToken();break}default:r.data+="--!",this.state=g.COMMENT,this._stateComment(t)}}_stateDoctype(t){switch(t){case h.SPACE:case h.LINE_FEED:case h.TABULATION:case h.FORM_FEED:{this.state=g.BEFORE_DOCTYPE_NAME;break}case h.GREATER_THAN_SIGN:{this.state=g.BEFORE_DOCTYPE_NAME,this._stateBeforeDoctypeName(t);break}case h.EOF:{this._err(L.eofInDoctype),this._createDoctypeToken(null);const r=this.currentToken;r.forceQuirks=!0,this.emitCurrentDoctype(r),this._emitEOFToken();break}default:this._err(L.missingWhitespaceBeforeDoctypeName),this.state=g.BEFORE_DOCTYPE_NAME,this._stateBeforeDoctypeName(t)}}_stateBeforeDoctypeName(t){if(ln(t))this._createDoctypeToken(String.fromCharCode(ps(t))),this.state=g.DOCTYPE_NAME;else switch(t){case h.SPACE:case h.LINE_FEED:case h.TABULATION:case h.FORM_FEED:break;case h.NULL:{this._err(L.unexpectedNullCharacter),this._createDoctypeToken(Qe),this.state=g.DOCTYPE_NAME;break}case h.GREATER_THAN_SIGN:{this._err(L.missingDoctypeName),this._createDoctypeToken(null);const r=this.currentToken;r.forceQuirks=!0,this.emitCurrentDoctype(r),this.state=g.DATA;break}case h.EOF:{this._err(L.eofInDoctype),this._createDoctypeToken(null);const r=this.currentToken;r.forceQuirks=!0,this.emitCurrentDoctype(r),this._emitEOFToken();break}default:this._createDoctypeToken(String.fromCodePoint(t)),this.state=g.DOCTYPE_NAME}}_stateDoctypeName(t){const r=this.currentToken;switch(t){case h.SPACE:case h.LINE_FEED:case h.TABULATION:case h.FORM_FEED:{this.state=g.AFTER_DOCTYPE_NAME;break}case h.GREATER_THAN_SIGN:{this.state=g.DATA,this.emitCurrentDoctype(r);break}case h.NULL:{this._err(L.unexpectedNullCharacter),r.name+=Qe;break}case h.EOF:{this._err(L.eofInDoctype),r.forceQuirks=!0,this.emitCurrentDoctype(r),this._emitEOFToken();break}default:r.name+=String.fromCodePoint(ln(t)?ps(t):t)}}_stateAfterDoctypeName(t){const r=this.currentToken;switch(t){case h.SPACE:case h.LINE_FEED:case h.TABULATION:case h.FORM_FEED:break;case h.GREATER_THAN_SIGN:{this.state=g.DATA,this.emitCurrentDoctype(r);break}case h.EOF:{this._err(L.eofInDoctype),r.forceQuirks=!0,this.emitCurrentDoctype(r),this._emitEOFToken();break}default:this._consumeSequenceIfMatch(It.PUBLIC,!1)?this.state=g.AFTER_DOCTYPE_PUBLIC_KEYWORD:this._consumeSequenceIfMatch(It.SYSTEM,!1)?this.state=g.AFTER_DOCTYPE_SYSTEM_KEYWORD:this._ensureHibernation()||(this._err(L.invalidCharacterSequenceAfterDoctypeName),r.forceQuirks=!0,this.state=g.BOGUS_DOCTYPE,this._stateBogusDoctype(t))}}_stateAfterDoctypePublicKeyword(t){const r=this.currentToken;switch(t){case h.SPACE:case h.LINE_FEED:case h.TABULATION:case h.FORM_FEED:{this.state=g.BEFORE_DOCTYPE_PUBLIC_IDENTIFIER;break}case h.QUOTATION_MARK:{this._err(L.missingWhitespaceAfterDoctypePublicKeyword),r.publicId="",this.state=g.DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED;break}case h.APOSTROPHE:{this._err(L.missingWhitespaceAfterDoctypePublicKeyword),r.publicId="",this.state=g.DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED;break}case h.GREATER_THAN_SIGN:{this._err(L.missingDoctypePublicIdentifier),r.forceQuirks=!0,this.state=g.DATA,this.emitCurrentDoctype(r);break}case h.EOF:{this._err(L.eofInDoctype),r.forceQuirks=!0,this.emitCurrentDoctype(r),this._emitEOFToken();break}default:this._err(L.missingQuoteBeforeDoctypePublicIdentifier),r.forceQuirks=!0,this.state=g.BOGUS_DOCTYPE,this._stateBogusDoctype(t)}}_stateBeforeDoctypePublicIdentifier(t){const r=this.currentToken;switch(t){case h.SPACE:case h.LINE_FEED:case h.TABULATION:case h.FORM_FEED:break;case h.QUOTATION_MARK:{r.publicId="",this.state=g.DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED;break}case h.APOSTROPHE:{r.publicId="",this.state=g.DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED;break}case h.GREATER_THAN_SIGN:{this._err(L.missingDoctypePublicIdentifier),r.forceQuirks=!0,this.state=g.DATA,this.emitCurrentDoctype(r);break}case h.EOF:{this._err(L.eofInDoctype),r.forceQuirks=!0,this.emitCurrentDoctype(r),this._emitEOFToken();break}default:this._err(L.missingQuoteBeforeDoctypePublicIdentifier),r.forceQuirks=!0,this.state=g.BOGUS_DOCTYPE,this._stateBogusDoctype(t)}}_stateDoctypePublicIdentifierDoubleQuoted(t){const r=this.currentToken;switch(t){case h.QUOTATION_MARK:{this.state=g.AFTER_DOCTYPE_PUBLIC_IDENTIFIER;break}case h.NULL:{this._err(L.unexpectedNullCharacter),r.publicId+=Qe;break}case h.GREATER_THAN_SIGN:{this._err(L.abruptDoctypePublicIdentifier),r.forceQuirks=!0,this.emitCurrentDoctype(r),this.state=g.DATA;break}case h.EOF:{this._err(L.eofInDoctype),r.forceQuirks=!0,this.emitCurrentDoctype(r),this._emitEOFToken();break}default:r.publicId+=String.fromCodePoint(t)}}_stateDoctypePublicIdentifierSingleQuoted(t){const r=this.currentToken;switch(t){case h.APOSTROPHE:{this.state=g.AFTER_DOCTYPE_PUBLIC_IDENTIFIER;break}case h.NULL:{this._err(L.unexpectedNullCharacter),r.publicId+=Qe;break}case h.GREATER_THAN_SIGN:{this._err(L.abruptDoctypePublicIdentifier),r.forceQuirks=!0,this.emitCurrentDoctype(r),this.state=g.DATA;break}case h.EOF:{this._err(L.eofInDoctype),r.forceQuirks=!0,this.emitCurrentDoctype(r),this._emitEOFToken();break}default:r.publicId+=String.fromCodePoint(t)}}_stateAfterDoctypePublicIdentifier(t){const r=this.currentToken;switch(t){case h.SPACE:case h.LINE_FEED:case h.TABULATION:case h.FORM_FEED:{this.state=g.BETWEEN_DOCTYPE_PUBLIC_AND_SYSTEM_IDENTIFIERS;break}case h.GREATER_THAN_SIGN:{this.state=g.DATA,this.emitCurrentDoctype(r);break}case h.QUOTATION_MARK:{this._err(L.missingWhitespaceBetweenDoctypePublicAndSystemIdentifiers),r.systemId="",this.state=g.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED;break}case h.APOSTROPHE:{this._err(L.missingWhitespaceBetweenDoctypePublicAndSystemIdentifiers),r.systemId="",this.state=g.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED;break}case h.EOF:{this._err(L.eofInDoctype),r.forceQuirks=!0,this.emitCurrentDoctype(r),this._emitEOFToken();break}default:this._err(L.missingQuoteBeforeDoctypeSystemIdentifier),r.forceQuirks=!0,this.state=g.BOGUS_DOCTYPE,this._stateBogusDoctype(t)}}_stateBetweenDoctypePublicAndSystemIdentifiers(t){const r=this.currentToken;switch(t){case h.SPACE:case h.LINE_FEED:case h.TABULATION:case h.FORM_FEED:break;case h.GREATER_THAN_SIGN:{this.emitCurrentDoctype(r),this.state=g.DATA;break}case h.QUOTATION_MARK:{r.systemId="",this.state=g.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED;break}case h.APOSTROPHE:{r.systemId="",this.state=g.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED;break}case h.EOF:{this._err(L.eofInDoctype),r.forceQuirks=!0,this.emitCurrentDoctype(r),this._emitEOFToken();break}default:this._err(L.missingQuoteBeforeDoctypeSystemIdentifier),r.forceQuirks=!0,this.state=g.BOGUS_DOCTYPE,this._stateBogusDoctype(t)}}_stateAfterDoctypeSystemKeyword(t){const r=this.currentToken;switch(t){case h.SPACE:case h.LINE_FEED:case h.TABULATION:case h.FORM_FEED:{this.state=g.BEFORE_DOCTYPE_SYSTEM_IDENTIFIER;break}case h.QUOTATION_MARK:{this._err(L.missingWhitespaceAfterDoctypeSystemKeyword),r.systemId="",this.state=g.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED;break}case h.APOSTROPHE:{this._err(L.missingWhitespaceAfterDoctypeSystemKeyword),r.systemId="",this.state=g.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED;break}case h.GREATER_THAN_SIGN:{this._err(L.missingDoctypeSystemIdentifier),r.forceQuirks=!0,this.state=g.DATA,this.emitCurrentDoctype(r);break}case h.EOF:{this._err(L.eofInDoctype),r.forceQuirks=!0,this.emitCurrentDoctype(r),this._emitEOFToken();break}default:this._err(L.missingQuoteBeforeDoctypeSystemIdentifier),r.forceQuirks=!0,this.state=g.BOGUS_DOCTYPE,this._stateBogusDoctype(t)}}_stateBeforeDoctypeSystemIdentifier(t){const r=this.currentToken;switch(t){case h.SPACE:case h.LINE_FEED:case h.TABULATION:case h.FORM_FEED:break;case h.QUOTATION_MARK:{r.systemId="",this.state=g.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED;break}case h.APOSTROPHE:{r.systemId="",this.state=g.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED;break}case h.GREATER_THAN_SIGN:{this._err(L.missingDoctypeSystemIdentifier),r.forceQuirks=!0,this.state=g.DATA,this.emitCurrentDoctype(r);break}case h.EOF:{this._err(L.eofInDoctype),r.forceQuirks=!0,this.emitCurrentDoctype(r),this._emitEOFToken();break}default:this._err(L.missingQuoteBeforeDoctypeSystemIdentifier),r.forceQuirks=!0,this.state=g.BOGUS_DOCTYPE,this._stateBogusDoctype(t)}}_stateDoctypeSystemIdentifierDoubleQuoted(t){const r=this.currentToken;switch(t){case h.QUOTATION_MARK:{this.state=g.AFTER_DOCTYPE_SYSTEM_IDENTIFIER;break}case h.NULL:{this._err(L.unexpectedNullCharacter),r.systemId+=Qe;break}case h.GREATER_THAN_SIGN:{this._err(L.abruptDoctypeSystemIdentifier),r.forceQuirks=!0,this.emitCurrentDoctype(r),this.state=g.DATA;break}case h.EOF:{this._err(L.eofInDoctype),r.forceQuirks=!0,this.emitCurrentDoctype(r),this._emitEOFToken();break}default:r.systemId+=String.fromCodePoint(t)}}_stateDoctypeSystemIdentifierSingleQuoted(t){const r=this.currentToken;switch(t){case h.APOSTROPHE:{this.state=g.AFTER_DOCTYPE_SYSTEM_IDENTIFIER;break}case h.NULL:{this._err(L.unexpectedNullCharacter),r.systemId+=Qe;break}case h.GREATER_THAN_SIGN:{this._err(L.abruptDoctypeSystemIdentifier),r.forceQuirks=!0,this.emitCurrentDoctype(r),this.state=g.DATA;break}case h.EOF:{this._err(L.eofInDoctype),r.forceQuirks=!0,this.emitCurrentDoctype(r),this._emitEOFToken();break}default:r.systemId+=String.fromCodePoint(t)}}_stateAfterDoctypeSystemIdentifier(t){const r=this.currentToken;switch(t){case h.SPACE:case h.LINE_FEED:case h.TABULATION:case h.FORM_FEED:break;case h.GREATER_THAN_SIGN:{this.emitCurrentDoctype(r),this.state=g.DATA;break}case h.EOF:{this._err(L.eofInDoctype),r.forceQuirks=!0,this.emitCurrentDoctype(r),this._emitEOFToken();break}default:this._err(L.unexpectedCharacterAfterDoctypeSystemIdentifier),this.state=g.BOGUS_DOCTYPE,this._stateBogusDoctype(t)}}_stateBogusDoctype(t){const r=this.currentToken;switch(t){case h.GREATER_THAN_SIGN:{this.emitCurrentDoctype(r),this.state=g.DATA;break}case h.NULL:{this._err(L.unexpectedNullCharacter);break}case h.EOF:{this.emitCurrentDoctype(r),this._emitEOFToken();break}}}_stateCdataSection(t){switch(t){case h.RIGHT_SQUARE_BRACKET:{this.state=g.CDATA_SECTION_BRACKET;break}case h.EOF:{this._err(L.eofInCdata),this._emitEOFToken();break}default:this._emitCodePoint(t)}}_stateCdataSectionBracket(t){t===h.RIGHT_SQUARE_BRACKET?this.state=g.CDATA_SECTION_END:(this._emitChars("]"),this.state=g.CDATA_SECTION,this._stateCdataSection(t))}_stateCdataSectionEnd(t){switch(t){case h.GREATER_THAN_SIGN:{this.state=g.DATA;break}case h.RIGHT_SQUARE_BRACKET:{this._emitChars("]");break}default:this._emitChars("]]"),this.state=g.CDATA_SECTION,this._stateCdataSection(t)}}_stateCharacterReference(){let t=this.entityDecoder.write(this.preprocessor.html,this.preprocessor.pos);if(t<0)if(this.preprocessor.lastChunkWritten)t=this.entityDecoder.end();else{this.active=!1,this.preprocessor.pos=this.preprocessor.html.length-1,this.consumedAfterSnapshot=0,this.preprocessor.endOfChunkHit=!0;return}t===0?(this.preprocessor.pos=this.entityStartPos,this._flushCodePointConsumedAsCharacterReference(h.AMPERSAND),this.state=!this._isCharacterReferenceInAttribute()&&Ju(this.preprocessor.peek(1))?g.AMBIGUOUS_AMPERSAND:this.returnState):this.state=this.returnState}_stateAmbiguousAmpersand(t){Ju(t)?this._flushCodePointConsumedAsCharacterReference(t):(t===h.SEMICOLON&&this._err(L.unknownNamedCharacterReference),this.state=this.returnState,this._callState(t))}}const Pd=new Set([s.DD,s.DT,s.LI,s.OPTGROUP,s.OPTION,s.P,s.RB,s.RP,s.RT,s.RTC]),el=new Set([...Pd,s.CAPTION,s.COLGROUP,s.TBODY,s.TD,s.TFOOT,s.TH,s.THEAD,s.TR]),ks=new Set([s.APPLET,s.CAPTION,s.HTML,s.MARQUEE,s.OBJECT,s.TABLE,s.TD,s.TEMPLATE,s.TH]),pb=new Set([...ks,s.OL,s.UL]),gb=new Set([...ks,s.BUTTON]),tl=new Set([s.ANNOTATION_XML,s.MI,s.MN,s.MO,s.MS,s.MTEXT]),rl=new Set([s.DESC,s.FOREIGN_OBJECT,s.TITLE]),Eb=new Set([s.TR,s.TEMPLATE,s.HTML]),bb=new Set([s.TBODY,s.TFOOT,s.THEAD,s.TEMPLATE,s.HTML]),Tb=new Set([s.TABLE,s.TEMPLATE,s.HTML]),Sb=new Set([s.TD,s.TH]);class Ab{get currentTmplContentOrNode(){return this._isInTemplate()?this.treeAdapter.getTemplateContent(this.current):this.current}constructor(t,r,a){this.treeAdapter=r,this.handler=a,this.items=[],this.tagIDs=[],this.stackTop=-1,this.tmplCount=0,this.currentTagId=s.UNKNOWN,this.current=t}_indexOf(t){return this.items.lastIndexOf(t,this.stackTop)}_isInTemplate(){return this.currentTagId===s.TEMPLATE&&this.treeAdapter.getNamespaceURI(this.current)===Q.HTML}_updateCurrentElement(){this.current=this.items[this.stackTop],this.currentTagId=this.tagIDs[this.stackTop]}push(t,r){this.stackTop++,this.items[this.stackTop]=t,this.current=t,this.tagIDs[this.stackTop]=r,this.currentTagId=r,this._isInTemplate()&&this.tmplCount++,this.handler.onItemPush(t,r,!0)}pop(){const t=this.current;this.tmplCount>0&&this._isInTemplate()&&this.tmplCount--,this.stackTop--,this._updateCurrentElement(),this.handler.onItemPop(t,!0)}replace(t,r){const a=this._indexOf(t);this.items[a]=r,a===this.stackTop&&(this.current=r)}insertAfter(t,r,a){const n=this._indexOf(t)+1;this.items.splice(n,0,r),this.tagIDs.splice(n,0,a),this.stackTop++,n===this.stackTop&&this._updateCurrentElement(),this.current&&this.currentTagId!==void 0&&this.handler.onItemPush(this.current,this.currentTagId,n===this.stackTop)}popUntilTagNamePopped(t){let r=this.stackTop+1;do r=this.tagIDs.lastIndexOf(t,r-1);while(r>0&&this.treeAdapter.getNamespaceURI(this.items[r])!==Q.HTML);this.shortenToLength(Math.max(r,0))}shortenToLength(t){for(;this.stackTop>=t;){const r=this.current;this.tmplCount>0&&this._isInTemplate()&&(this.tmplCount-=1),this.stackTop--,this._updateCurrentElement(),this.handler.onItemPop(r,this.stackTop<t)}}popUntilElementPopped(t){const r=this._indexOf(t);this.shortenToLength(Math.max(r,0))}popUntilPopped(t,r){const a=this._indexOfTagNames(t,r);this.shortenToLength(Math.max(a,0))}popUntilNumberedHeaderPopped(){this.popUntilPopped(uo,Q.HTML)}popUntilTableCellPopped(){this.popUntilPopped(Sb,Q.HTML)}popAllUpToHtmlElement(){this.tmplCount=0,this.shortenToLength(1)}_indexOfTagNames(t,r){for(let a=this.stackTop;a>=0;a--)if(t.has(this.tagIDs[a])&&this.treeAdapter.getNamespaceURI(this.items[a])===r)return a;return-1}clearBackTo(t,r){const a=this._indexOfTagNames(t,r);this.shortenToLength(a+1)}clearBackToTableContext(){this.clearBackTo(Tb,Q.HTML)}clearBackToTableBodyContext(){this.clearBackTo(bb,Q.HTML)}clearBackToTableRowContext(){this.clearBackTo(Eb,Q.HTML)}remove(t){const r=this._indexOf(t);r>=0&&(r===this.stackTop?this.pop():(this.items.splice(r,1),this.tagIDs.splice(r,1),this.stackTop--,this._updateCurrentElement(),this.handler.onItemPop(t,!1)))}tryPeekProperlyNestedBodyElement(){return this.stackTop>=1&&this.tagIDs[1]===s.BODY?this.items[1]:null}contains(t){return this._indexOf(t)>-1}getCommonAncestor(t){const r=this._indexOf(t)-1;return r>=0?this.items[r]:null}isRootHtmlElementCurrent(){return this.stackTop===0&&this.tagIDs[0]===s.HTML}hasInDynamicScope(t,r){for(let a=this.stackTop;a>=0;a--){const n=this.tagIDs[a];switch(this.treeAdapter.getNamespaceURI(this.items[a])){case Q.HTML:{if(n===t)return!0;if(r.has(n))return!1;break}case Q.SVG:{if(rl.has(n))return!1;break}case Q.MATHML:{if(tl.has(n))return!1;break}}}return!0}hasInScope(t){return this.hasInDynamicScope(t,ks)}hasInListItemScope(t){return this.hasInDynamicScope(t,pb)}hasInButtonScope(t){return this.hasInDynamicScope(t,gb)}hasNumberedHeaderInScope(){for(let t=this.stackTop;t>=0;t--){const r=this.tagIDs[t];switch(this.treeAdapter.getNamespaceURI(this.items[t])){case Q.HTML:{if(uo.has(r))return!0;if(ks.has(r))return!1;break}case Q.SVG:{if(rl.has(r))return!1;break}case Q.MATHML:{if(tl.has(r))return!1;break}}}return!0}hasInTableScope(t){for(let r=this.stackTop;r>=0;r--)if(this.treeAdapter.getNamespaceURI(this.items[r])===Q.HTML)switch(this.tagIDs[r]){case t:return!0;case s.TABLE:case s.HTML:return!1}return!0}hasTableBodyContextInTableScope(){for(let t=this.stackTop;t>=0;t--)if(this.treeAdapter.getNamespaceURI(this.items[t])===Q.HTML)switch(this.tagIDs[t]){case s.TBODY:case s.THEAD:case s.TFOOT:return!0;case s.TABLE:case s.HTML:return!1}return!0}hasInSelectScope(t){for(let r=this.stackTop;r>=0;r--)if(this.treeAdapter.getNamespaceURI(this.items[r])===Q.HTML)switch(this.tagIDs[r]){case t:return!0;case s.OPTION:case s.OPTGROUP:break;default:return!1}return!0}generateImpliedEndTags(){for(;this.currentTagId!==void 0&&Pd.has(this.currentTagId);)this.pop()}generateImpliedEndTagsThoroughly(){for(;this.currentTagId!==void 0&&el.has(this.currentTagId);)this.pop()}generateImpliedEndTagsWithExclusion(t){for(;this.currentTagId!==void 0&&this.currentTagId!==t&&el.has(this.currentTagId);)this.pop()}}const Wi=3;var tr;(function(e){e[e.Marker=0]="Marker",e[e.Element=1]="Element"})(tr||(tr={}));const al={type:tr.Marker};class Ib{constructor(t){this.treeAdapter=t,this.entries=[],this.bookmark=null}_getNoahArkConditionCandidates(t,r){const a=[],n=r.length,i=this.treeAdapter.getTagName(t),o=this.treeAdapter.getNamespaceURI(t);for(let c=0;c<this.entries.length;c++){const f=this.entries[c];if(f.type===tr.Marker)break;const{element:d}=f;if(this.treeAdapter.getTagName(d)===i&&this.treeAdapter.getNamespaceURI(d)===o){const S=this.treeAdapter.getAttrList(d);S.length===n&&a.push({idx:c,attrs:S})}}return a}_ensureNoahArkCondition(t){if(this.entries.length<Wi)return;const r=this.treeAdapter.getAttrList(t),a=this._getNoahArkConditionCandidates(t,r);if(a.length<Wi)return;const n=new Map(r.map(o=>[o.name,o.value]));let i=0;for(let o=0;o<a.length;o++){const c=a[o];c.attrs.every(f=>n.get(f.name)===f.value)&&(i+=1,i>=Wi&&this.entries.splice(c.idx,1))}}insertMarker(){this.entries.unshift(al)}pushElement(t,r){this._ensureNoahArkCondition(t),this.entries.unshift({type:tr.Element,element:t,token:r})}insertElementAfterBookmark(t,r){const a=this.entries.indexOf(this.bookmark);this.entries.splice(a,0,{type:tr.Element,element:t,token:r})}removeEntry(t){const r=this.entries.indexOf(t);r!==-1&&this.entries.splice(r,1)}clearToLastMarker(){const t=this.entries.indexOf(al);t===-1?this.entries.length=0:this.entries.splice(0,t+1)}getElementEntryInScopeWithTagName(t){const r=this.entries.find(a=>a.type===tr.Marker||this.treeAdapter.getTagName(a.element)===t);return r&&r.type===tr.Element?r:null}getElementEntry(t){return this.entries.find(r=>r.type===tr.Element&&r.element===t)}}const Nr={createDocument(){return{nodeName:"#document",mode:Mt.NO_QUIRKS,childNodes:[]}},createDocumentFragment(){return{nodeName:"#document-fragment",childNodes:[]}},createElement(e,t,r){return{nodeName:e,tagName:e,attrs:r,namespaceURI:t,childNodes:[],parentNode:null}},createCommentNode(e){return{nodeName:"#comment",data:e,parentNode:null}},createTextNode(e){return{nodeName:"#text",value:e,parentNode:null}},appendChild(e,t){e.childNodes.push(t),t.parentNode=e},insertBefore(e,t,r){const a=e.childNodes.indexOf(r);e.childNodes.splice(a,0,t),t.parentNode=e},setTemplateContent(e,t){e.content=t},getTemplateContent(e){return e.content},setDocumentType(e,t,r,a){const n=e.childNodes.find(i=>i.nodeName==="#documentType");if(n)n.name=t,n.publicId=r,n.systemId=a;else{const i={nodeName:"#documentType",name:t,publicId:r,systemId:a,parentNode:null};Nr.appendChild(e,i)}},setDocumentMode(e,t){e.mode=t},getDocumentMode(e){return e.mode},detachNode(e){if(e.parentNode){const t=e.parentNode.childNodes.indexOf(e);e.parentNode.childNodes.splice(t,1),e.parentNode=null}},insertText(e,t){if(e.childNodes.length>0){const r=e.childNodes[e.childNodes.length-1];if(Nr.isTextNode(r)){r.value+=t;return}}Nr.appendChild(e,Nr.createTextNode(t))},insertTextBefore(e,t,r){const a=e.childNodes[e.childNodes.indexOf(r)-1];a&&Nr.isTextNode(a)?a.value+=t:Nr.insertBefore(e,Nr.createTextNode(t),r)},adoptAttributes(e,t){const r=new Set(e.attrs.map(a=>a.name));for(let a=0;a<t.length;a++)r.has(t[a].name)||e.attrs.push(t[a])},getFirstChild(e){return e.childNodes[0]},getChildNodes(e){return e.childNodes},getParentNode(e){return e.parentNode},getAttrList(e){return e.attrs},getTagName(e){return e.tagName},getNamespaceURI(e){return e.namespaceURI},getTextNodeContent(e){return e.value},getCommentNodeContent(e){return e.data},getDocumentTypeNodeName(e){return e.name},getDocumentTypeNodePublicId(e){return e.publicId},getDocumentTypeNodeSystemId(e){return e.systemId},isTextNode(e){return e.nodeName==="#text"},isCommentNode(e){return e.nodeName==="#comment"},isDocumentTypeNode(e){return e.nodeName==="#documentType"},isElementNode(e){return Object.prototype.hasOwnProperty.call(e,"tagName")},setNodeSourceCodeLocation(e,t){e.sourceCodeLocation=t},getNodeSourceCodeLocation(e){return e.sourceCodeLocation},updateNodeSourceCodeLocation(e,t){e.sourceCodeLocation={...e.sourceCodeLocation,...t}}},xd="html",yb="about:legacy-compat",_b="http://www.ibm.com/data/dtd/v11/ibmxhtml1-transitional.dtd",Od=["+//silmaril//dtd html pro v0r11 19970101//","-//as//dtd html 3.0 aswedit + extensions//","-//advasoft ltd//dtd html 3.0 aswedit + extensions//","-//ietf//dtd html 2.0 level 1//","-//ietf//dtd html 2.0 level 2//","-//ietf//dtd html 2.0 strict level 1//","-//ietf//dtd html 2.0 strict level 2//","-//ietf//dtd html 2.0 strict//","-//ietf//dtd html 2.0//","-//ietf//dtd html 2.1e//","-//ietf//dtd html 3.0//","-//ietf//dtd html 3.2 final//","-//ietf//dtd html 3.2//","-//ietf//dtd html 3//","-//ietf//dtd html level 0//","-//ietf//dtd html level 1//","-//ietf//dtd html level 2//","-//ietf//dtd html level 3//","-//ietf//dtd html strict level 0//","-//ietf//dtd html strict level 1//","-//ietf//dtd html strict level 2//","-//ietf//dtd html strict level 3//","-//ietf//dtd html strict//","-//ietf//dtd html//","-//metrius//dtd metrius presentational//","-//microsoft//dtd internet explorer 2.0 html strict//","-//microsoft//dtd internet explorer 2.0 html//","-//microsoft//dtd internet explorer 2.0 tables//","-//microsoft//dtd internet explorer 3.0 html strict//","-//microsoft//dtd internet explorer 3.0 html//","-//microsoft//dtd internet explorer 3.0 tables//","-//netscape comm. corp.//dtd html//","-//netscape comm. corp.//dtd strict html//","-//o'reilly and associates//dtd html 2.0//","-//o'reilly and associates//dtd html extended 1.0//","-//o'reilly and associates//dtd html extended relaxed 1.0//","-//sq//dtd html 2.0 hotmetal + extensions//","-//softquad software//dtd hotmetal pro 6.0::19990601::extensions to html 4.0//","-//softquad//dtd hotmetal pro 4.0::19971010::extensions to html 4.0//","-//spyglass//dtd html 2.0 extended//","-//sun microsystems corp.//dtd hotjava html//","-//sun microsystems corp.//dtd hotjava strict html//","-//w3c//dtd html 3 1995-03-24//","-//w3c//dtd html 3.2 draft//","-//w3c//dtd html 3.2 final//","-//w3c//dtd html 3.2//","-//w3c//dtd html 3.2s draft//","-//w3c//dtd html 4.0 frameset//","-//w3c//dtd html 4.0 transitional//","-//w3c//dtd html experimental 19960712//","-//w3c//dtd html experimental 970421//","-//w3c//dtd w3 html//","-//w3o//dtd w3 html 3.0//","-//webtechs//dtd mozilla html 2.0//","-//webtechs//dtd mozilla html//"],Cb=[...Od,"-//w3c//dtd html 4.01 frameset//","-//w3c//dtd html 4.01 transitional//"],wb=new Set(["-//w3o//dtd w3 html strict 3.0//en//","-/w3c/dtd html 4.0 transitional/en","html"]),vd=["-//w3c//dtd xhtml 1.0 frameset//","-//w3c//dtd xhtml 1.0 transitional//"],Rb=[...vd,"-//w3c//dtd html 4.01 frameset//","-//w3c//dtd html 4.01 transitional//"];function nl(e,t){return t.some(r=>e.startsWith(r))}function Nb(e){return e.name===xd&&e.publicId===null&&(e.systemId===null||e.systemId===yb)}function Pb(e){if(e.name!==xd)return Mt.QUIRKS;const{systemId:t}=e;if(t&&t.toLowerCase()===_b)return Mt.QUIRKS;let{publicId:r}=e;if(r!==null){if(r=r.toLowerCase(),wb.has(r))return Mt.QUIRKS;let a=t===null?Cb:Od;if(nl(r,a))return Mt.QUIRKS;if(a=t===null?vd:Rb,nl(r,a))return Mt.LIMITED_QUIRKS}return Mt.NO_QUIRKS}const sl={TEXT_HTML:"text/html",APPLICATION_XML:"application/xhtml+xml"},xb="definitionurl",Ob="definitionURL",vb=new Map(["attributeName","attributeType","baseFrequency","baseProfile","calcMode","clipPathUnits","diffuseConstant","edgeMode","filterUnits","glyphRef","gradientTransform","gradientUnits","kernelMatrix","kernelUnitLength","keyPoints","keySplines","keyTimes","lengthAdjust","limitingConeAngle","markerHeight","markerUnits","markerWidth","maskContentUnits","maskUnits","numOctaves","pathLength","patternContentUnits","patternTransform","patternUnits","pointsAtX","pointsAtY","pointsAtZ","preserveAlpha","preserveAspectRatio","primitiveUnits","refX","refY","repeatCount","repeatDur","requiredExtensions","requiredFeatures","specularConstant","specularExponent","spreadMethod","startOffset","stdDeviation","stitchTiles","surfaceScale","systemLanguage","tableValues","targetX","targetY","textLength","viewBox","viewTarget","xChannelSelector","yChannelSelector","zoomAndPan"].map(e=>[e.toLowerCase(),e])),Lb=new Map([["xlink:actuate",{prefix:"xlink",name:"actuate",namespace:Q.XLINK}],["xlink:arcrole",{prefix:"xlink",name:"arcrole",namespace:Q.XLINK}],["xlink:href",{prefix:"xlink",name:"href",namespace:Q.XLINK}],["xlink:role",{prefix:"xlink",name:"role",namespace:Q.XLINK}],["xlink:show",{prefix:"xlink",name:"show",namespace:Q.XLINK}],["xlink:title",{prefix:"xlink",name:"title",namespace:Q.XLINK}],["xlink:type",{prefix:"xlink",name:"type",namespace:Q.XLINK}],["xml:lang",{prefix:"xml",name:"lang",namespace:Q.XML}],["xml:space",{prefix:"xml",name:"space",namespace:Q.XML}],["xmlns",{prefix:"",name:"xmlns",namespace:Q.XMLNS}],["xmlns:xlink",{prefix:"xmlns",name:"xlink",namespace:Q.XMLNS}]]),kb=new Map(["altGlyph","altGlyphDef","altGlyphItem","animateColor","animateMotion","animateTransform","clipPath","feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence","foreignObject","glyphRef","linearGradient","radialGradient","textPath"].map(e=>[e.toLowerCase(),e])),Db=new Set([s.B,s.BIG,s.BLOCKQUOTE,s.BODY,s.BR,s.CENTER,s.CODE,s.DD,s.DIV,s.DL,s.DT,s.EM,s.EMBED,s.H1,s.H2,s.H3,s.H4,s.H5,s.H6,s.HEAD,s.HR,s.I,s.IMG,s.LI,s.LISTING,s.MENU,s.META,s.NOBR,s.OL,s.P,s.PRE,s.RUBY,s.S,s.SMALL,s.SPAN,s.STRONG,s.STRIKE,s.SUB,s.SUP,s.TABLE,s.TT,s.U,s.UL,s.VAR]);function Mb(e){const t=e.tagID;return t===s.FONT&&e.attrs.some(({name:a})=>a===Zr.COLOR||a===Zr.SIZE||a===Zr.FACE)||Db.has(t)}function Ld(e){for(let t=0;t<e.attrs.length;t++)if(e.attrs[t].name===xb){e.attrs[t].name=Ob;break}}function kd(e){for(let t=0;t<e.attrs.length;t++){const r=vb.get(e.attrs[t].name);r!=null&&(e.attrs[t].name=r)}}function Ho(e){for(let t=0;t<e.attrs.length;t++){const r=Lb.get(e.attrs[t].name);r&&(e.attrs[t].prefix=r.prefix,e.attrs[t].name=r.name,e.attrs[t].namespace=r.namespace)}}function Ub(e){const t=kb.get(e.tagName);t!=null&&(e.tagName=t,e.tagID=qs(e.tagName))}function Bb(e,t){return t===Q.MATHML&&(e===s.MI||e===s.MO||e===s.MN||e===s.MS||e===s.MTEXT)}function Fb(e,t,r){if(t===Q.MATHML&&e===s.ANNOTATION_XML){for(let a=0;a<r.length;a++)if(r[a].name===Zr.ENCODING){const n=r[a].value.toLowerCase();return n===sl.TEXT_HTML||n===sl.APPLICATION_XML}}return t===Q.SVG&&(e===s.FOREIGN_OBJECT||e===s.DESC||e===s.TITLE)}function Hb(e,t,r,a){return(!a||a===Q.HTML)&&Fb(e,t,r)||(!a||a===Q.MATHML)&&Bb(e,t)}const jb="hidden",Vb=8,Gb=3;var T;(function(e){e[e.INITIAL=0]="INITIAL",e[e.BEFORE_HTML=1]="BEFORE_HTML",e[e.BEFORE_HEAD=2]="BEFORE_HEAD",e[e.IN_HEAD=3]="IN_HEAD",e[e.IN_HEAD_NO_SCRIPT=4]="IN_HEAD_NO_SCRIPT",e[e.AFTER_HEAD=5]="AFTER_HEAD",e[e.IN_BODY=6]="IN_BODY",e[e.TEXT=7]="TEXT",e[e.IN_TABLE=8]="IN_TABLE",e[e.IN_TABLE_TEXT=9]="IN_TABLE_TEXT",e[e.IN_CAPTION=10]="IN_CAPTION",e[e.IN_COLUMN_GROUP=11]="IN_COLUMN_GROUP",e[e.IN_TABLE_BODY=12]="IN_TABLE_BODY",e[e.IN_ROW=13]="IN_ROW",e[e.IN_CELL=14]="IN_CELL",e[e.IN_SELECT=15]="IN_SELECT",e[e.IN_SELECT_IN_TABLE=16]="IN_SELECT_IN_TABLE",e[e.IN_TEMPLATE=17]="IN_TEMPLATE",e[e.AFTER_BODY=18]="AFTER_BODY",e[e.IN_FRAMESET=19]="IN_FRAMESET",e[e.AFTER_FRAMESET=20]="AFTER_FRAMESET",e[e.AFTER_AFTER_BODY=21]="AFTER_AFTER_BODY",e[e.AFTER_AFTER_FRAMESET=22]="AFTER_AFTER_FRAMESET"})(T||(T={}));const Yb={startLine:-1,startCol:-1,startOffset:-1,endLine:-1,endCol:-1,endOffset:-1},Dd=new Set([s.TABLE,s.TBODY,s.TFOOT,s.THEAD,s.TR]),il={scriptingEnabled:!0,sourceCodeLocationInfo:!1,treeAdapter:Nr,onParseError:null};class Md{constructor(t,r,a=null,n=null){this.fragmentContext=a,this.scriptHandler=n,this.currentToken=null,this.stopped=!1,this.insertionMode=T.INITIAL,this.originalInsertionMode=T.INITIAL,this.headElement=null,this.formElement=null,this.currentNotInHTML=!1,this.tmplInsertionModeStack=[],this.pendingCharacterTokens=[],this.hasNonWhitespacePendingCharacterToken=!1,this.framesetOk=!0,this.skipNextNewLine=!1,this.fosterParentingEnabled=!1,this.options={...il,...t},this.treeAdapter=this.options.treeAdapter,this.onParseError=this.options.onParseError,this.onParseError&&(this.options.sourceCodeLocationInfo=!0),this.document=r??this.treeAdapter.createDocument(),this.tokenizer=new hb(this.options,this),this.activeFormattingElements=new Ib(this.treeAdapter),this.fragmentContextID=a?qs(this.treeAdapter.getTagName(a)):s.UNKNOWN,this._setContextModes(a??this.document,this.fragmentContextID),this.openElements=new Ab(this.document,this.treeAdapter,this)}static parse(t,r){const a=new this(r);return a.tokenizer.write(t,!0),a.document}static getFragmentParser(t,r){const a={...il,...r};t??(t=a.treeAdapter.createElement(R.TEMPLATE,Q.HTML,[]));const n=a.treeAdapter.createElement("documentmock",Q.HTML,[]),i=new this(a,n,t);return i.fragmentContextID===s.TEMPLATE&&i.tmplInsertionModeStack.unshift(T.IN_TEMPLATE),i._initTokenizerForFragmentParsing(),i._insertFakeRootElement(),i._resetInsertionMode(),i._findFormInFragmentContext(),i}getFragment(){const t=this.treeAdapter.getFirstChild(this.document),r=this.treeAdapter.createDocumentFragment();return this._adoptNodes(t,r),r}_err(t,r,a){var n;if(!this.onParseError)return;const i=(n=t.location)!==null&&n!==void 0?n:Yb,o={code:r,startLine:i.startLine,startCol:i.startCol,startOffset:i.startOffset,endLine:a?i.startLine:i.endLine,endCol:a?i.startCol:i.endCol,endOffset:a?i.startOffset:i.endOffset};this.onParseError(o)}onItemPush(t,r,a){var n,i;(i=(n=this.treeAdapter).onItemPush)===null||i===void 0||i.call(n,t),a&&this.openElements.stackTop>0&&this._setContextModes(t,r)}onItemPop(t,r){var a,n;if(this.options.sourceCodeLocationInfo&&this._setEndLocation(t,this.currentToken),(n=(a=this.treeAdapter).onItemPop)===null||n===void 0||n.call(a,t,this.openElements.current),r){let i,o;this.openElements.stackTop===0&&this.fragmentContext?(i=this.fragmentContext,o=this.fragmentContextID):{current:i,currentTagId:o}=this.openElements,this._setContextModes(i,o)}}_setContextModes(t,r){const a=t===this.document||t&&this.treeAdapter.getNamespaceURI(t)===Q.HTML;this.currentNotInHTML=!a,this.tokenizer.inForeignNode=!a&&t!==void 0&&r!==void 0&&!this._isIntegrationPoint(r,t)}_switchToTextParsing(t,r){this._insertElement(t,Q.HTML),this.tokenizer.state=r,this.originalInsertionMode=this.insertionMode,this.insertionMode=T.TEXT}switchToPlaintextParsing(){this.insertionMode=T.TEXT,this.originalInsertionMode=T.IN_BODY,this.tokenizer.state=yt.PLAINTEXT}_getAdjustedCurrentElement(){return this.openElements.stackTop===0&&this.fragmentContext?this.fragmentContext:this.openElements.current}_findFormInFragmentContext(){let t=this.fragmentContext;for(;t;){if(this.treeAdapter.getTagName(t)===R.FORM){this.formElement=t;break}t=this.treeAdapter.getParentNode(t)}}_initTokenizerForFragmentParsing(){if(!(!this.fragmentContext||this.treeAdapter.getNamespaceURI(this.fragmentContext)!==Q.HTML))switch(this.fragmentContextID){case s.TITLE:case s.TEXTAREA:{this.tokenizer.state=yt.RCDATA;break}case s.STYLE:case s.XMP:case s.IFRAME:case s.NOEMBED:case s.NOFRAMES:case s.NOSCRIPT:{this.tokenizer.state=yt.RAWTEXT;break}case s.SCRIPT:{this.tokenizer.state=yt.SCRIPT_DATA;break}case s.PLAINTEXT:{this.tokenizer.state=yt.PLAINTEXT;break}}}_setDocumentType(t){const r=t.name||"",a=t.publicId||"",n=t.systemId||"";if(this.treeAdapter.setDocumentType(this.document,r,a,n),t.location){const o=this.treeAdapter.getChildNodes(this.document).find(c=>this.treeAdapter.isDocumentTypeNode(c));o&&this.treeAdapter.setNodeSourceCodeLocation(o,t.location)}}_attachElementToTree(t,r){if(this.options.sourceCodeLocationInfo){const a=r&&{...r,startTag:r};this.treeAdapter.setNodeSourceCodeLocation(t,a)}if(this._shouldFosterParentOnInsertion())this._fosterParentElement(t);else{const a=this.openElements.currentTmplContentOrNode;this.treeAdapter.appendChild(a??this.document,t)}}_appendElement(t,r){const a=this.treeAdapter.createElement(t.tagName,r,t.attrs);this._attachElementToTree(a,t.location)}_insertElement(t,r){const a=this.treeAdapter.createElement(t.tagName,r,t.attrs);this._attachElementToTree(a,t.location),this.openElements.push(a,t.tagID)}_insertFakeElement(t,r){const a=this.treeAdapter.createElement(t,Q.HTML,[]);this._attachElementToTree(a,null),this.openElements.push(a,r)}_insertTemplate(t){const r=this.treeAdapter.createElement(t.tagName,Q.HTML,t.attrs),a=this.treeAdapter.createDocumentFragment();this.treeAdapter.setTemplateContent(r,a),this._attachElementToTree(r,t.location),this.openElements.push(r,t.tagID),this.options.sourceCodeLocationInfo&&this.treeAdapter.setNodeSourceCodeLocation(a,null)}_insertFakeRootElement(){const t=this.treeAdapter.createElement(R.HTML,Q.HTML,[]);this.options.sourceCodeLocationInfo&&this.treeAdapter.setNodeSourceCodeLocation(t,null),this.treeAdapter.appendChild(this.openElements.current,t),this.openElements.push(t,s.HTML)}_appendCommentNode(t,r){const a=this.treeAdapter.createCommentNode(t.data);this.treeAdapter.appendChild(r,a),this.options.sourceCodeLocationInfo&&this.treeAdapter.setNodeSourceCodeLocation(a,t.location)}_insertCharacters(t){let r,a;if(this._shouldFosterParentOnInsertion()?({parent:r,beforeElement:a}=this._findFosterParentingLocation(),a?this.treeAdapter.insertTextBefore(r,t.chars,a):this.treeAdapter.insertText(r,t.chars)):(r=this.openElements.currentTmplContentOrNode,this.treeAdapter.insertText(r,t.chars)),!t.location)return;const n=this.treeAdapter.getChildNodes(r),i=a?n.lastIndexOf(a):n.length,o=n[i-1];if(this.treeAdapter.getNodeSourceCodeLocation(o)){const{endLine:f,endCol:d,endOffset:S}=t.location;this.treeAdapter.updateNodeSourceCodeLocation(o,{endLine:f,endCol:d,endOffset:S})}else this.options.sourceCodeLocationInfo&&this.treeAdapter.setNodeSourceCodeLocation(o,t.location)}_adoptNodes(t,r){for(let a=this.treeAdapter.getFirstChild(t);a;a=this.treeAdapter.getFirstChild(t))this.treeAdapter.detachNode(a),this.treeAdapter.appendChild(r,a)}_setEndLocation(t,r){if(this.treeAdapter.getNodeSourceCodeLocation(t)&&r.location){const a=r.location,n=this.treeAdapter.getTagName(t),i=r.type===De.END_TAG&&n===r.tagName?{endTag:{...a},endLine:a.endLine,endCol:a.endCol,endOffset:a.endOffset}:{endLine:a.startLine,endCol:a.startCol,endOffset:a.startOffset};this.treeAdapter.updateNodeSourceCodeLocation(t,i)}}shouldProcessStartTagTokenInForeignContent(t){if(!this.currentNotInHTML)return!1;let r,a;return this.openElements.stackTop===0&&this.fragmentContext?(r=this.fragmentContext,a=this.fragmentContextID):{current:r,currentTagId:a}=this.openElements,t.tagID===s.SVG&&this.treeAdapter.getTagName(r)===R.ANNOTATION_XML&&this.treeAdapter.getNamespaceURI(r)===Q.MATHML?!1:this.tokenizer.inForeignNode||(t.tagID===s.MGLYPH||t.tagID===s.MALIGNMARK)&&a!==void 0&&!this._isIntegrationPoint(a,r,Q.HTML)}_processToken(t){switch(t.type){case De.CHARACTER:{this.onCharacter(t);break}case De.NULL_CHARACTER:{this.onNullCharacter(t);break}case De.COMMENT:{this.onComment(t);break}case De.DOCTYPE:{this.onDoctype(t);break}case De.START_TAG:{this._processStartTag(t);break}case De.END_TAG:{this.onEndTag(t);break}case De.EOF:{this.onEof(t);break}case De.WHITESPACE_CHARACTER:{this.onWhitespaceCharacter(t);break}}}_isIntegrationPoint(t,r,a){const n=this.treeAdapter.getNamespaceURI(r),i=this.treeAdapter.getAttrList(r);return Hb(t,n,i,a)}_reconstructActiveFormattingElements(){const t=this.activeFormattingElements.entries.length;if(t){const r=this.activeFormattingElements.entries.findIndex(n=>n.type===tr.Marker||this.openElements.contains(n.element)),a=r===-1?t-1:r-1;for(let n=a;n>=0;n--){const i=this.activeFormattingElements.entries[n];this._insertElement(i.token,this.treeAdapter.getNamespaceURI(i.element)),i.element=this.openElements.current}}}_closeTableCell(){this.openElements.generateImpliedEndTags(),this.openElements.popUntilTableCellPopped(),this.activeFormattingElements.clearToLastMarker(),this.insertionMode=T.IN_ROW}_closePElement(){this.openElements.generateImpliedEndTagsWithExclusion(s.P),this.openElements.popUntilTagNamePopped(s.P)}_resetInsertionMode(){for(let t=this.openElements.stackTop;t>=0;t--)switch(t===0&&this.fragmentContext?this.fragmentContextID:this.openElements.tagIDs[t]){case s.TR:{this.insertionMode=T.IN_ROW;return}case s.TBODY:case s.THEAD:case s.TFOOT:{this.insertionMode=T.IN_TABLE_BODY;return}case s.CAPTION:{this.insertionMode=T.IN_CAPTION;return}case s.COLGROUP:{this.insertionMode=T.IN_COLUMN_GROUP;return}case s.TABLE:{this.insertionMode=T.IN_TABLE;return}case s.BODY:{this.insertionMode=T.IN_BODY;return}case s.FRAMESET:{this.insertionMode=T.IN_FRAMESET;return}case s.SELECT:{this._resetInsertionModeForSelect(t);return}case s.TEMPLATE:{this.insertionMode=this.tmplInsertionModeStack[0];return}case s.HTML:{this.insertionMode=this.headElement?T.AFTER_HEAD:T.BEFORE_HEAD;return}case s.TD:case s.TH:{if(t>0){this.insertionMode=T.IN_CELL;return}break}case s.HEAD:{if(t>0){this.insertionMode=T.IN_HEAD;return}break}}this.insertionMode=T.IN_BODY}_resetInsertionModeForSelect(t){if(t>0)for(let r=t-1;r>0;r--){const a=this.openElements.tagIDs[r];if(a===s.TEMPLATE)break;if(a===s.TABLE){this.insertionMode=T.IN_SELECT_IN_TABLE;return}}this.insertionMode=T.IN_SELECT}_isElementCausesFosterParenting(t){return Dd.has(t)}_shouldFosterParentOnInsertion(){return this.fosterParentingEnabled&&this.openElements.currentTagId!==void 0&&this._isElementCausesFosterParenting(this.openElements.currentTagId)}_findFosterParentingLocation(){for(let t=this.openElements.stackTop;t>=0;t--){const r=this.openElements.items[t];switch(this.openElements.tagIDs[t]){case s.TEMPLATE:{if(this.treeAdapter.getNamespaceURI(r)===Q.HTML)return{parent:this.treeAdapter.getTemplateContent(r),beforeElement:null};break}case s.TABLE:{const a=this.treeAdapter.getParentNode(r);return a?{parent:a,beforeElement:r}:{parent:this.openElements.items[t-1],beforeElement:null}}}}return{parent:this.openElements.items[0],beforeElement:null}}_fosterParentElement(t){const r=this._findFosterParentingLocation();r.beforeElement?this.treeAdapter.insertBefore(r.parent,t,r.beforeElement):this.treeAdapter.appendChild(r.parent,t)}_isSpecialElement(t,r){const a=this.treeAdapter.getNamespaceURI(t);return lb[a].has(r)}onCharacter(t){if(this.skipNextNewLine=!1,this.tokenizer.inForeignNode){SS(this,t);return}switch(this.insertionMode){case T.INITIAL:{on(this,t);break}case T.BEFORE_HTML:{mn(this,t);break}case T.BEFORE_HEAD:{hn(this,t);break}case T.IN_HEAD:{pn(this,t);break}case T.IN_HEAD_NO_SCRIPT:{gn(this,t);break}case T.AFTER_HEAD:{En(this,t);break}case T.IN_BODY:case T.IN_CAPTION:case T.IN_CELL:case T.IN_TEMPLATE:{Bd(this,t);break}case T.TEXT:case T.IN_SELECT:case T.IN_SELECT_IN_TABLE:{this._insertCharacters(t);break}case T.IN_TABLE:case T.IN_TABLE_BODY:case T.IN_ROW:{$i(this,t);break}case T.IN_TABLE_TEXT:{Yd(this,t);break}case T.IN_COLUMN_GROUP:{Ds(this,t);break}case T.AFTER_BODY:{Ms(this,t);break}case T.AFTER_AFTER_BODY:{As(this,t);break}}}onNullCharacter(t){if(this.skipNextNewLine=!1,this.tokenizer.inForeignNode){TS(this,t);return}switch(this.insertionMode){case T.INITIAL:{on(this,t);break}case T.BEFORE_HTML:{mn(this,t);break}case T.BEFORE_HEAD:{hn(this,t);break}case T.IN_HEAD:{pn(this,t);break}case T.IN_HEAD_NO_SCRIPT:{gn(this,t);break}case T.AFTER_HEAD:{En(this,t);break}case T.TEXT:{this._insertCharacters(t);break}case T.IN_TABLE:case T.IN_TABLE_BODY:case T.IN_ROW:{$i(this,t);break}case T.IN_COLUMN_GROUP:{Ds(this,t);break}case T.AFTER_BODY:{Ms(this,t);break}case T.AFTER_AFTER_BODY:{As(this,t);break}}}onComment(t){if(this.skipNextNewLine=!1,this.currentNotInHTML){lo(this,t);return}switch(this.insertionMode){case T.INITIAL:case T.BEFORE_HTML:case T.BEFORE_HEAD:case T.IN_HEAD:case T.IN_HEAD_NO_SCRIPT:case T.AFTER_HEAD:case T.IN_BODY:case T.IN_TABLE:case T.IN_CAPTION:case T.IN_COLUMN_GROUP:case T.IN_TABLE_BODY:case T.IN_ROW:case T.IN_CELL:case T.IN_SELECT:case T.IN_SELECT_IN_TABLE:case T.IN_TEMPLATE:case T.IN_FRAMESET:case T.AFTER_FRAMESET:{lo(this,t);break}case T.IN_TABLE_TEXT:{cn(this,t);break}case T.AFTER_BODY:{Xb(this,t);break}case T.AFTER_AFTER_BODY:case T.AFTER_AFTER_FRAMESET:{Jb(this,t);break}}}onDoctype(t){switch(this.skipNextNewLine=!1,this.insertionMode){case T.INITIAL:{Zb(this,t);break}case T.BEFORE_HEAD:case T.IN_HEAD:case T.IN_HEAD_NO_SCRIPT:case T.AFTER_HEAD:{this._err(t,L.misplacedDoctype);break}case T.IN_TABLE_TEXT:{cn(this,t);break}}}onStartTag(t){this.skipNextNewLine=!1,this.currentToken=t,this._processStartTag(t),t.selfClosing&&!t.ackSelfClosing&&this._err(t,L.nonVoidHtmlElementStartTagWithTrailingSolidus)}_processStartTag(t){this.shouldProcessStartTagTokenInForeignContent(t)?AS(this,t):this._startTagOutsideForeignContent(t)}_startTagOutsideForeignContent(t){switch(this.insertionMode){case T.INITIAL:{on(this,t);break}case T.BEFORE_HTML:{eT(this,t);break}case T.BEFORE_HEAD:{rT(this,t);break}case T.IN_HEAD:{$t(this,t);break}case T.IN_HEAD_NO_SCRIPT:{sT(this,t);break}case T.AFTER_HEAD:{oT(this,t);break}case T.IN_BODY:{Et(this,t);break}case T.IN_TABLE:{Na(this,t);break}case T.IN_TABLE_TEXT:{cn(this,t);break}case T.IN_CAPTION:{aS(this,t);break}case T.IN_COLUMN_GROUP:{Go(this,t);break}case T.IN_TABLE_BODY:{Xs(this,t);break}case T.IN_ROW:{Js(this,t);break}case T.IN_CELL:{iS(this,t);break}case T.IN_SELECT:{$d(this,t);break}case T.IN_SELECT_IN_TABLE:{cS(this,t);break}case T.IN_TEMPLATE:{lS(this,t);break}case T.AFTER_BODY:{fS(this,t);break}case T.IN_FRAMESET:{mS(this,t);break}case T.AFTER_FRAMESET:{pS(this,t);break}case T.AFTER_AFTER_BODY:{ES(this,t);break}case T.AFTER_AFTER_FRAMESET:{bS(this,t);break}}}onEndTag(t){this.skipNextNewLine=!1,this.currentToken=t,this.currentNotInHTML?IS(this,t):this._endTagOutsideForeignContent(t)}_endTagOutsideForeignContent(t){switch(this.insertionMode){case T.INITIAL:{on(this,t);break}case T.BEFORE_HTML:{tT(this,t);break}case T.BEFORE_HEAD:{aT(this,t);break}case T.IN_HEAD:{nT(this,t);break}case T.IN_HEAD_NO_SCRIPT:{iT(this,t);break}case T.AFTER_HEAD:{cT(this,t);break}case T.IN_BODY:{Ks(this,t);break}case T.TEXT:{$T(this,t);break}case T.IN_TABLE:{yn(this,t);break}case T.IN_TABLE_TEXT:{cn(this,t);break}case T.IN_CAPTION:{nS(this,t);break}case T.IN_COLUMN_GROUP:{sS(this,t);break}case T.IN_TABLE_BODY:{fo(this,t);break}case T.IN_ROW:{Wd(this,t);break}case T.IN_CELL:{oS(this,t);break}case T.IN_SELECT:{qd(this,t);break}case T.IN_SELECT_IN_TABLE:{uS(this,t);break}case T.IN_TEMPLATE:{dS(this,t);break}case T.AFTER_BODY:{Kd(this,t);break}case T.IN_FRAMESET:{hS(this,t);break}case T.AFTER_FRAMESET:{gS(this,t);break}case T.AFTER_AFTER_BODY:{As(this,t);break}}}onEof(t){switch(this.insertionMode){case T.INITIAL:{on(this,t);break}case T.BEFORE_HTML:{mn(this,t);break}case T.BEFORE_HEAD:{hn(this,t);break}case T.IN_HEAD:{pn(this,t);break}case T.IN_HEAD_NO_SCRIPT:{gn(this,t);break}case T.AFTER_HEAD:{En(this,t);break}case T.IN_BODY:case T.IN_TABLE:case T.IN_CAPTION:case T.IN_COLUMN_GROUP:case T.IN_TABLE_BODY:case T.IN_ROW:case T.IN_CELL:case T.IN_SELECT:case T.IN_SELECT_IN_TABLE:{Vd(this,t);break}case T.TEXT:{qT(this,t);break}case T.IN_TABLE_TEXT:{cn(this,t);break}case T.IN_TEMPLATE:{Qd(this,t);break}case T.AFTER_BODY:case T.IN_FRAMESET:case T.AFTER_FRAMESET:case T.AFTER_AFTER_BODY:case T.AFTER_AFTER_FRAMESET:{Vo(this,t);break}}}onWhitespaceCharacter(t){if(this.skipNextNewLine&&(this.skipNextNewLine=!1,t.chars.charCodeAt(0)===h.LINE_FEED)){if(t.chars.length===1)return;t.chars=t.chars.substr(1)}if(this.tokenizer.inForeignNode){this._insertCharacters(t);return}switch(this.insertionMode){case T.IN_HEAD:case T.IN_HEAD_NO_SCRIPT:case T.AFTER_HEAD:case T.TEXT:case T.IN_COLUMN_GROUP:case T.IN_SELECT:case T.IN_SELECT_IN_TABLE:case T.IN_FRAMESET:case T.AFTER_FRAMESET:{this._insertCharacters(t);break}case T.IN_BODY:case T.IN_CAPTION:case T.IN_CELL:case T.IN_TEMPLATE:case T.AFTER_BODY:case T.AFTER_AFTER_BODY:case T.AFTER_AFTER_FRAMESET:{Ud(this,t);break}case T.IN_TABLE:case T.IN_TABLE_BODY:case T.IN_ROW:{$i(this,t);break}case T.IN_TABLE_TEXT:{Gd(this,t);break}}}}function zb(e,t){let r=e.activeFormattingElements.getElementEntryInScopeWithTagName(t.tagName);return r?e.openElements.contains(r.element)?e.openElements.hasInScope(t.tagID)||(r=null):(e.activeFormattingElements.removeEntry(r),r=null):jd(e,t),r}function Wb(e,t){let r=null,a=e.openElements.stackTop;for(;a>=0;a--){const n=e.openElements.items[a];if(n===t.element)break;e._isSpecialElement(n,e.openElements.tagIDs[a])&&(r=n)}return r||(e.openElements.shortenToLength(Math.max(a,0)),e.activeFormattingElements.removeEntry(t)),r}function $b(e,t,r){let a=t,n=e.openElements.getCommonAncestor(t);for(let i=0,o=n;o!==r;i++,o=n){n=e.openElements.getCommonAncestor(o);const c=e.activeFormattingElements.getElementEntry(o),f=c&&i>=Gb;!c||f?(f&&e.activeFormattingElements.removeEntry(c),e.openElements.remove(o)):(o=qb(e,c),a===t&&(e.activeFormattingElements.bookmark=c),e.treeAdapter.detachNode(a),e.treeAdapter.appendChild(o,a),a=o)}return a}function qb(e,t){const r=e.treeAdapter.getNamespaceURI(t.element),a=e.treeAdapter.createElement(t.token.tagName,r,t.token.attrs);return e.openElements.replace(t.element,a),t.element=a,a}function Qb(e,t,r){const a=e.treeAdapter.getTagName(t),n=qs(a);if(e._isElementCausesFosterParenting(n))e._fosterParentElement(r);else{const i=e.treeAdapter.getNamespaceURI(t);n===s.TEMPLATE&&i===Q.HTML&&(t=e.treeAdapter.getTemplateContent(t)),e.treeAdapter.appendChild(t,r)}}function Kb(e,t,r){const a=e.treeAdapter.getNamespaceURI(r.element),{token:n}=r,i=e.treeAdapter.createElement(n.tagName,a,n.attrs);e._adoptNodes(t,i),e.treeAdapter.appendChild(t,i),e.activeFormattingElements.insertElementAfterBookmark(i,n),e.activeFormattingElements.removeEntry(r),e.openElements.remove(r.element),e.openElements.insertAfter(t,i,n.tagID)}function jo(e,t){for(let r=0;r<Vb;r++){const a=zb(e,t);if(!a)break;const n=Wb(e,a);if(!n)break;e.activeFormattingElements.bookmark=a;const i=$b(e,n,a.element),o=e.openElements.getCommonAncestor(a.element);e.treeAdapter.detachNode(i),o&&Qb(e,o,i),Kb(e,n,a)}}function lo(e,t){e._appendCommentNode(t,e.openElements.currentTmplContentOrNode)}function Xb(e,t){e._appendCommentNode(t,e.openElements.items[0])}function Jb(e,t){e._appendCommentNode(t,e.document)}function Vo(e,t){if(e.stopped=!0,t.location){const r=e.fragmentContext?0:2;for(let a=e.openElements.stackTop;a>=r;a--)e._setEndLocation(e.openElements.items[a],t);if(!e.fragmentContext&&e.openElements.stackTop>=0){const a=e.openElements.items[0],n=e.treeAdapter.getNodeSourceCodeLocation(a);if(n&&!n.endTag&&(e._setEndLocation(a,t),e.openElements.stackTop>=1)){const i=e.openElements.items[1],o=e.treeAdapter.getNodeSourceCodeLocation(i);o&&!o.endTag&&e._setEndLocation(i,t)}}}}function Zb(e,t){e._setDocumentType(t);const r=t.forceQuirks?Mt.QUIRKS:Pb(t);Nb(t)||e._err(t,L.nonConformingDoctype),e.treeAdapter.setDocumentMode(e.document,r),e.insertionMode=T.BEFORE_HTML}function on(e,t){e._err(t,L.missingDoctype,!0),e.treeAdapter.setDocumentMode(e.document,Mt.QUIRKS),e.insertionMode=T.BEFORE_HTML,e._processToken(t)}function eT(e,t){t.tagID===s.HTML?(e._insertElement(t,Q.HTML),e.insertionMode=T.BEFORE_HEAD):mn(e,t)}function tT(e,t){const r=t.tagID;(r===s.HTML||r===s.HEAD||r===s.BODY||r===s.BR)&&mn(e,t)}function mn(e,t){e._insertFakeRootElement(),e.insertionMode=T.BEFORE_HEAD,e._processToken(t)}function rT(e,t){switch(t.tagID){case s.HTML:{Et(e,t);break}case s.HEAD:{e._insertElement(t,Q.HTML),e.headElement=e.openElements.current,e.insertionMode=T.IN_HEAD;break}default:hn(e,t)}}function aT(e,t){const r=t.tagID;r===s.HEAD||r===s.BODY||r===s.HTML||r===s.BR?hn(e,t):e._err(t,L.endTagWithoutMatchingOpenElement)}function hn(e,t){e._insertFakeElement(R.HEAD,s.HEAD),e.headElement=e.openElements.current,e.insertionMode=T.IN_HEAD,e._processToken(t)}function $t(e,t){switch(t.tagID){case s.HTML:{Et(e,t);break}case s.BASE:case s.BASEFONT:case s.BGSOUND:case s.LINK:case s.META:{e._appendElement(t,Q.HTML),t.ackSelfClosing=!0;break}case s.TITLE:{e._switchToTextParsing(t,yt.RCDATA);break}case s.NOSCRIPT:{e.options.scriptingEnabled?e._switchToTextParsing(t,yt.RAWTEXT):(e._insertElement(t,Q.HTML),e.insertionMode=T.IN_HEAD_NO_SCRIPT);break}case s.NOFRAMES:case s.STYLE:{e._switchToTextParsing(t,yt.RAWTEXT);break}case s.SCRIPT:{e._switchToTextParsing(t,yt.SCRIPT_DATA);break}case s.TEMPLATE:{e._insertTemplate(t),e.activeFormattingElements.insertMarker(),e.framesetOk=!1,e.insertionMode=T.IN_TEMPLATE,e.tmplInsertionModeStack.unshift(T.IN_TEMPLATE);break}case s.HEAD:{e._err(t,L.misplacedStartTagForHeadElement);break}default:pn(e,t)}}function nT(e,t){switch(t.tagID){case s.HEAD:{e.openElements.pop(),e.insertionMode=T.AFTER_HEAD;break}case s.BODY:case s.BR:case s.HTML:{pn(e,t);break}case s.TEMPLATE:{na(e,t);break}default:e._err(t,L.endTagWithoutMatchingOpenElement)}}function na(e,t){e.openElements.tmplCount>0?(e.openElements.generateImpliedEndTagsThoroughly(),e.openElements.currentTagId!==s.TEMPLATE&&e._err(t,L.closingOfElementWithOpenChildElements),e.openElements.popUntilTagNamePopped(s.TEMPLATE),e.activeFormattingElements.clearToLastMarker(),e.tmplInsertionModeStack.shift(),e._resetInsertionMode()):e._err(t,L.endTagWithoutMatchingOpenElement)}function pn(e,t){e.openElements.pop(),e.insertionMode=T.AFTER_HEAD,e._processToken(t)}function sT(e,t){switch(t.tagID){case s.HTML:{Et(e,t);break}case s.BASEFONT:case s.BGSOUND:case s.HEAD:case s.LINK:case s.META:case s.NOFRAMES:case s.STYLE:{$t(e,t);break}case s.NOSCRIPT:{e._err(t,L.nestedNoscriptInHead);break}default:gn(e,t)}}function iT(e,t){switch(t.tagID){case s.NOSCRIPT:{e.openElements.pop(),e.insertionMode=T.IN_HEAD;break}case s.BR:{gn(e,t);break}default:e._err(t,L.endTagWithoutMatchingOpenElement)}}function gn(e,t){const r=t.type===De.EOF?L.openElementsLeftAfterEof:L.disallowedContentInNoscriptInHead;e._err(t,r),e.openElements.pop(),e.insertionMode=T.IN_HEAD,e._processToken(t)}function oT(e,t){switch(t.tagID){case s.HTML:{Et(e,t);break}case s.BODY:{e._insertElement(t,Q.HTML),e.framesetOk=!1,e.insertionMode=T.IN_BODY;break}case s.FRAMESET:{e._insertElement(t,Q.HTML),e.insertionMode=T.IN_FRAMESET;break}case s.BASE:case s.BASEFONT:case s.BGSOUND:case s.LINK:case s.META:case s.NOFRAMES:case s.SCRIPT:case s.STYLE:case s.TEMPLATE:case s.TITLE:{e._err(t,L.abandonedHeadElementChild),e.openElements.push(e.headElement,s.HEAD),$t(e,t),e.openElements.remove(e.headElement);break}case s.HEAD:{e._err(t,L.misplacedStartTagForHeadElement);break}default:En(e,t)}}function cT(e,t){switch(t.tagID){case s.BODY:case s.HTML:case s.BR:{En(e,t);break}case s.TEMPLATE:{na(e,t);break}default:e._err(t,L.endTagWithoutMatchingOpenElement)}}function En(e,t){e._insertFakeElement(R.BODY,s.BODY),e.insertionMode=T.IN_BODY,Qs(e,t)}function Qs(e,t){switch(t.type){case De.CHARACTER:{Bd(e,t);break}case De.WHITESPACE_CHARACTER:{Ud(e,t);break}case De.COMMENT:{lo(e,t);break}case De.START_TAG:{Et(e,t);break}case De.END_TAG:{Ks(e,t);break}case De.EOF:{Vd(e,t);break}}}function Ud(e,t){e._reconstructActiveFormattingElements(),e._insertCharacters(t)}function Bd(e,t){e._reconstructActiveFormattingElements(),e._insertCharacters(t),e.framesetOk=!1}function uT(e,t){e.openElements.tmplCount===0&&e.treeAdapter.adoptAttributes(e.openElements.items[0],t.attrs)}function lT(e,t){const r=e.openElements.tryPeekProperlyNestedBodyElement();r&&e.openElements.tmplCount===0&&(e.framesetOk=!1,e.treeAdapter.adoptAttributes(r,t.attrs))}function dT(e,t){const r=e.openElements.tryPeekProperlyNestedBodyElement();e.framesetOk&&r&&(e.treeAdapter.detachNode(r),e.openElements.popAllUpToHtmlElement(),e._insertElement(t,Q.HTML),e.insertionMode=T.IN_FRAMESET)}function fT(e,t){e.openElements.hasInButtonScope(s.P)&&e._closePElement(),e._insertElement(t,Q.HTML)}function mT(e,t){e.openElements.hasInButtonScope(s.P)&&e._closePElement(),e.openElements.currentTagId!==void 0&&uo.has(e.openElements.currentTagId)&&e.openElements.pop(),e._insertElement(t,Q.HTML)}function hT(e,t){e.openElements.hasInButtonScope(s.P)&&e._closePElement(),e._insertElement(t,Q.HTML),e.skipNextNewLine=!0,e.framesetOk=!1}function pT(e,t){const r=e.openElements.tmplCount>0;(!e.formElement||r)&&(e.openElements.hasInButtonScope(s.P)&&e._closePElement(),e._insertElement(t,Q.HTML),r||(e.formElement=e.openElements.current))}function gT(e,t){e.framesetOk=!1;const r=t.tagID;for(let a=e.openElements.stackTop;a>=0;a--){const n=e.openElements.tagIDs[a];if(r===s.LI&&n===s.LI||(r===s.DD||r===s.DT)&&(n===s.DD||n===s.DT)){e.openElements.generateImpliedEndTagsWithExclusion(n),e.openElements.popUntilTagNamePopped(n);break}if(n!==s.ADDRESS&&n!==s.DIV&&n!==s.P&&e._isSpecialElement(e.openElements.items[a],n))break}e.openElements.hasInButtonScope(s.P)&&e._closePElement(),e._insertElement(t,Q.HTML)}function ET(e,t){e.openElements.hasInButtonScope(s.P)&&e._closePElement(),e._insertElement(t,Q.HTML),e.tokenizer.state=yt.PLAINTEXT}function bT(e,t){e.openElements.hasInScope(s.BUTTON)&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilTagNamePopped(s.BUTTON)),e._reconstructActiveFormattingElements(),e._insertElement(t,Q.HTML),e.framesetOk=!1}function TT(e,t){const r=e.activeFormattingElements.getElementEntryInScopeWithTagName(R.A);r&&(jo(e,t),e.openElements.remove(r.element),e.activeFormattingElements.removeEntry(r)),e._reconstructActiveFormattingElements(),e._insertElement(t,Q.HTML),e.activeFormattingElements.pushElement(e.openElements.current,t)}function ST(e,t){e._reconstructActiveFormattingElements(),e._insertElement(t,Q.HTML),e.activeFormattingElements.pushElement(e.openElements.current,t)}function AT(e,t){e._reconstructActiveFormattingElements(),e.openElements.hasInScope(s.NOBR)&&(jo(e,t),e._reconstructActiveFormattingElements()),e._insertElement(t,Q.HTML),e.activeFormattingElements.pushElement(e.openElements.current,t)}function IT(e,t){e._reconstructActiveFormattingElements(),e._insertElement(t,Q.HTML),e.activeFormattingElements.insertMarker(),e.framesetOk=!1}function yT(e,t){e.treeAdapter.getDocumentMode(e.document)!==Mt.QUIRKS&&e.openElements.hasInButtonScope(s.P)&&e._closePElement(),e._insertElement(t,Q.HTML),e.framesetOk=!1,e.insertionMode=T.IN_TABLE}function Fd(e,t){e._reconstructActiveFormattingElements(),e._appendElement(t,Q.HTML),e.framesetOk=!1,t.ackSelfClosing=!0}function Hd(e){const t=Rd(e,Zr.TYPE);return t!=null&&t.toLowerCase()===jb}function _T(e,t){e._reconstructActiveFormattingElements(),e._appendElement(t,Q.HTML),Hd(t)||(e.framesetOk=!1),t.ackSelfClosing=!0}function CT(e,t){e._appendElement(t,Q.HTML),t.ackSelfClosing=!0}function wT(e,t){e.openElements.hasInButtonScope(s.P)&&e._closePElement(),e._appendElement(t,Q.HTML),e.framesetOk=!1,t.ackSelfClosing=!0}function RT(e,t){t.tagName=R.IMG,t.tagID=s.IMG,Fd(e,t)}function NT(e,t){e._insertElement(t,Q.HTML),e.skipNextNewLine=!0,e.tokenizer.state=yt.RCDATA,e.originalInsertionMode=e.insertionMode,e.framesetOk=!1,e.insertionMode=T.TEXT}function PT(e,t){e.openElements.hasInButtonScope(s.P)&&e._closePElement(),e._reconstructActiveFormattingElements(),e.framesetOk=!1,e._switchToTextParsing(t,yt.RAWTEXT)}function xT(e,t){e.framesetOk=!1,e._switchToTextParsing(t,yt.RAWTEXT)}function ol(e,t){e._switchToTextParsing(t,yt.RAWTEXT)}function OT(e,t){e._reconstructActiveFormattingElements(),e._insertElement(t,Q.HTML),e.framesetOk=!1,e.insertionMode=e.insertionMode===T.IN_TABLE||e.insertionMode===T.IN_CAPTION||e.insertionMode===T.IN_TABLE_BODY||e.insertionMode===T.IN_ROW||e.insertionMode===T.IN_CELL?T.IN_SELECT_IN_TABLE:T.IN_SELECT}function vT(e,t){e.openElements.currentTagId===s.OPTION&&e.openElements.pop(),e._reconstructActiveFormattingElements(),e._insertElement(t,Q.HTML)}function LT(e,t){e.openElements.hasInScope(s.RUBY)&&e.openElements.generateImpliedEndTags(),e._insertElement(t,Q.HTML)}function kT(e,t){e.openElements.hasInScope(s.RUBY)&&e.openElements.generateImpliedEndTagsWithExclusion(s.RTC),e._insertElement(t,Q.HTML)}function DT(e,t){e._reconstructActiveFormattingElements(),Ld(t),Ho(t),t.selfClosing?e._appendElement(t,Q.MATHML):e._insertElement(t,Q.MATHML),t.ackSelfClosing=!0}function MT(e,t){e._reconstructActiveFormattingElements(),kd(t),Ho(t),t.selfClosing?e._appendElement(t,Q.SVG):e._insertElement(t,Q.SVG),t.ackSelfClosing=!0}function cl(e,t){e._reconstructActiveFormattingElements(),e._insertElement(t,Q.HTML)}function Et(e,t){switch(t.tagID){case s.I:case s.S:case s.B:case s.U:case s.EM:case s.TT:case s.BIG:case s.CODE:case s.FONT:case s.SMALL:case s.STRIKE:case s.STRONG:{ST(e,t);break}case s.A:{TT(e,t);break}case s.H1:case s.H2:case s.H3:case s.H4:case s.H5:case s.H6:{mT(e,t);break}case s.P:case s.DL:case s.OL:case s.UL:case s.DIV:case s.DIR:case s.NAV:case s.MAIN:case s.MENU:case s.ASIDE:case s.CENTER:case s.FIGURE:case s.FOOTER:case s.HEADER:case s.HGROUP:case s.DIALOG:case s.DETAILS:case s.ADDRESS:case s.ARTICLE:case s.SEARCH:case s.SECTION:case s.SUMMARY:case s.FIELDSET:case s.BLOCKQUOTE:case s.FIGCAPTION:{fT(e,t);break}case s.LI:case s.DD:case s.DT:{gT(e,t);break}case s.BR:case s.IMG:case s.WBR:case s.AREA:case s.EMBED:case s.KEYGEN:{Fd(e,t);break}case s.HR:{wT(e,t);break}case s.RB:case s.RTC:{LT(e,t);break}case s.RT:case s.RP:{kT(e,t);break}case s.PRE:case s.LISTING:{hT(e,t);break}case s.XMP:{PT(e,t);break}case s.SVG:{MT(e,t);break}case s.HTML:{uT(e,t);break}case s.BASE:case s.LINK:case s.META:case s.STYLE:case s.TITLE:case s.SCRIPT:case s.BGSOUND:case s.BASEFONT:case s.TEMPLATE:{$t(e,t);break}case s.BODY:{lT(e,t);break}case s.FORM:{pT(e,t);break}case s.NOBR:{AT(e,t);break}case s.MATH:{DT(e,t);break}case s.TABLE:{yT(e,t);break}case s.INPUT:{_T(e,t);break}case s.PARAM:case s.TRACK:case s.SOURCE:{CT(e,t);break}case s.IMAGE:{RT(e,t);break}case s.BUTTON:{bT(e,t);break}case s.APPLET:case s.OBJECT:case s.MARQUEE:{IT(e,t);break}case s.IFRAME:{xT(e,t);break}case s.SELECT:{OT(e,t);break}case s.OPTION:case s.OPTGROUP:{vT(e,t);break}case s.NOEMBED:case s.NOFRAMES:{ol(e,t);break}case s.FRAMESET:{dT(e,t);break}case s.TEXTAREA:{NT(e,t);break}case s.NOSCRIPT:{e.options.scriptingEnabled?ol(e,t):cl(e,t);break}case s.PLAINTEXT:{ET(e,t);break}case s.COL:case s.TH:case s.TD:case s.TR:case s.HEAD:case s.FRAME:case s.TBODY:case s.TFOOT:case s.THEAD:case s.CAPTION:case s.COLGROUP:break;default:cl(e,t)}}function UT(e,t){if(e.openElements.hasInScope(s.BODY)&&(e.insertionMode=T.AFTER_BODY,e.options.sourceCodeLocationInfo)){const r=e.openElements.tryPeekProperlyNestedBodyElement();r&&e._setEndLocation(r,t)}}function BT(e,t){e.openElements.hasInScope(s.BODY)&&(e.insertionMode=T.AFTER_BODY,Kd(e,t))}function FT(e,t){const r=t.tagID;e.openElements.hasInScope(r)&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilTagNamePopped(r))}function HT(e){const t=e.openElements.tmplCount>0,{formElement:r}=e;t||(e.formElement=null),(r||t)&&e.openElements.hasInScope(s.FORM)&&(e.openElements.generateImpliedEndTags(),t?e.openElements.popUntilTagNamePopped(s.FORM):r&&e.openElements.remove(r))}function jT(e){e.openElements.hasInButtonScope(s.P)||e._insertFakeElement(R.P,s.P),e._closePElement()}function VT(e){e.openElements.hasInListItemScope(s.LI)&&(e.openElements.generateImpliedEndTagsWithExclusion(s.LI),e.openElements.popUntilTagNamePopped(s.LI))}function GT(e,t){const r=t.tagID;e.openElements.hasInScope(r)&&(e.openElements.generateImpliedEndTagsWithExclusion(r),e.openElements.popUntilTagNamePopped(r))}function YT(e){e.openElements.hasNumberedHeaderInScope()&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilNumberedHeaderPopped())}function zT(e,t){const r=t.tagID;e.openElements.hasInScope(r)&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilTagNamePopped(r),e.activeFormattingElements.clearToLastMarker())}function WT(e){e._reconstructActiveFormattingElements(),e._insertFakeElement(R.BR,s.BR),e.openElements.pop(),e.framesetOk=!1}function jd(e,t){const r=t.tagName,a=t.tagID;for(let n=e.openElements.stackTop;n>0;n--){const i=e.openElements.items[n],o=e.openElements.tagIDs[n];if(a===o&&(a!==s.UNKNOWN||e.treeAdapter.getTagName(i)===r)){e.openElements.generateImpliedEndTagsWithExclusion(a),e.openElements.stackTop>=n&&e.openElements.shortenToLength(n);break}if(e._isSpecialElement(i,o))break}}function Ks(e,t){switch(t.tagID){case s.A:case s.B:case s.I:case s.S:case s.U:case s.EM:case s.TT:case s.BIG:case s.CODE:case s.FONT:case s.NOBR:case s.SMALL:case s.STRIKE:case s.STRONG:{jo(e,t);break}case s.P:{jT(e);break}case s.DL:case s.UL:case s.OL:case s.DIR:case s.DIV:case s.NAV:case s.PRE:case s.MAIN:case s.MENU:case s.ASIDE:case s.BUTTON:case s.CENTER:case s.FIGURE:case s.FOOTER:case s.HEADER:case s.HGROUP:case s.DIALOG:case s.ADDRESS:case s.ARTICLE:case s.DETAILS:case s.SEARCH:case s.SECTION:case s.SUMMARY:case s.LISTING:case s.FIELDSET:case s.BLOCKQUOTE:case s.FIGCAPTION:{FT(e,t);break}case s.LI:{VT(e);break}case s.DD:case s.DT:{GT(e,t);break}case s.H1:case s.H2:case s.H3:case s.H4:case s.H5:case s.H6:{YT(e);break}case s.BR:{WT(e);break}case s.BODY:{UT(e,t);break}case s.HTML:{BT(e,t);break}case s.FORM:{HT(e);break}case s.APPLET:case s.OBJECT:case s.MARQUEE:{zT(e,t);break}case s.TEMPLATE:{na(e,t);break}default:jd(e,t)}}function Vd(e,t){e.tmplInsertionModeStack.length>0?Qd(e,t):Vo(e,t)}function $T(e,t){var r;t.tagID===s.SCRIPT&&((r=e.scriptHandler)===null||r===void 0||r.call(e,e.openElements.current)),e.openElements.pop(),e.insertionMode=e.originalInsertionMode}function qT(e,t){e._err(t,L.eofInElementThatCanContainOnlyText),e.openElements.pop(),e.insertionMode=e.originalInsertionMode,e.onEof(t)}function $i(e,t){if(e.openElements.currentTagId!==void 0&&Dd.has(e.openElements.currentTagId))switch(e.pendingCharacterTokens.length=0,e.hasNonWhitespacePendingCharacterToken=!1,e.originalInsertionMode=e.insertionMode,e.insertionMode=T.IN_TABLE_TEXT,t.type){case De.CHARACTER:{Yd(e,t);break}case De.WHITESPACE_CHARACTER:{Gd(e,t);break}}else vn(e,t)}function QT(e,t){e.openElements.clearBackToTableContext(),e.activeFormattingElements.insertMarker(),e._insertElement(t,Q.HTML),e.insertionMode=T.IN_CAPTION}function KT(e,t){e.openElements.clearBackToTableContext(),e._insertElement(t,Q.HTML),e.insertionMode=T.IN_COLUMN_GROUP}function XT(e,t){e.openElements.clearBackToTableContext(),e._insertFakeElement(R.COLGROUP,s.COLGROUP),e.insertionMode=T.IN_COLUMN_GROUP,Go(e,t)}function JT(e,t){e.openElements.clearBackToTableContext(),e._insertElement(t,Q.HTML),e.insertionMode=T.IN_TABLE_BODY}function ZT(e,t){e.openElements.clearBackToTableContext(),e._insertFakeElement(R.TBODY,s.TBODY),e.insertionMode=T.IN_TABLE_BODY,Xs(e,t)}function eS(e,t){e.openElements.hasInTableScope(s.TABLE)&&(e.openElements.popUntilTagNamePopped(s.TABLE),e._resetInsertionMode(),e._processStartTag(t))}function tS(e,t){Hd(t)?e._appendElement(t,Q.HTML):vn(e,t),t.ackSelfClosing=!0}function rS(e,t){!e.formElement&&e.openElements.tmplCount===0&&(e._insertElement(t,Q.HTML),e.formElement=e.openElements.current,e.openElements.pop())}function Na(e,t){switch(t.tagID){case s.TD:case s.TH:case s.TR:{ZT(e,t);break}case s.STYLE:case s.SCRIPT:case s.TEMPLATE:{$t(e,t);break}case s.COL:{XT(e,t);break}case s.FORM:{rS(e,t);break}case s.TABLE:{eS(e,t);break}case s.TBODY:case s.TFOOT:case s.THEAD:{JT(e,t);break}case s.INPUT:{tS(e,t);break}case s.CAPTION:{QT(e,t);break}case s.COLGROUP:{KT(e,t);break}default:vn(e,t)}}function yn(e,t){switch(t.tagID){case s.TABLE:{e.openElements.hasInTableScope(s.TABLE)&&(e.openElements.popUntilTagNamePopped(s.TABLE),e._resetInsertionMode());break}case s.TEMPLATE:{na(e,t);break}case s.BODY:case s.CAPTION:case s.COL:case s.COLGROUP:case s.HTML:case s.TBODY:case s.TD:case s.TFOOT:case s.TH:case s.THEAD:case s.TR:break;default:vn(e,t)}}function vn(e,t){const r=e.fosterParentingEnabled;e.fosterParentingEnabled=!0,Qs(e,t),e.fosterParentingEnabled=r}function Gd(e,t){e.pendingCharacterTokens.push(t)}function Yd(e,t){e.pendingCharacterTokens.push(t),e.hasNonWhitespacePendingCharacterToken=!0}function cn(e,t){let r=0;if(e.hasNonWhitespacePendingCharacterToken)for(;r<e.pendingCharacterTokens.length;r++)vn(e,e.pendingCharacterTokens[r]);else for(;r<e.pendingCharacterTokens.length;r++)e._insertCharacters(e.pendingCharacterTokens[r]);e.insertionMode=e.originalInsertionMode,e._processToken(t)}const zd=new Set([s.CAPTION,s.COL,s.COLGROUP,s.TBODY,s.TD,s.TFOOT,s.TH,s.THEAD,s.TR]);function aS(e,t){const r=t.tagID;zd.has(r)?e.openElements.hasInTableScope(s.CAPTION)&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilTagNamePopped(s.CAPTION),e.activeFormattingElements.clearToLastMarker(),e.insertionMode=T.IN_TABLE,Na(e,t)):Et(e,t)}function nS(e,t){const r=t.tagID;switch(r){case s.CAPTION:case s.TABLE:{e.openElements.hasInTableScope(s.CAPTION)&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilTagNamePopped(s.CAPTION),e.activeFormattingElements.clearToLastMarker(),e.insertionMode=T.IN_TABLE,r===s.TABLE&&yn(e,t));break}case s.BODY:case s.COL:case s.COLGROUP:case s.HTML:case s.TBODY:case s.TD:case s.TFOOT:case s.TH:case s.THEAD:case s.TR:break;default:Ks(e,t)}}function Go(e,t){switch(t.tagID){case s.HTML:{Et(e,t);break}case s.COL:{e._appendElement(t,Q.HTML),t.ackSelfClosing=!0;break}case s.TEMPLATE:{$t(e,t);break}default:Ds(e,t)}}function sS(e,t){switch(t.tagID){case s.COLGROUP:{e.openElements.currentTagId===s.COLGROUP&&(e.openElements.pop(),e.insertionMode=T.IN_TABLE);break}case s.TEMPLATE:{na(e,t);break}case s.COL:break;default:Ds(e,t)}}function Ds(e,t){e.openElements.currentTagId===s.COLGROUP&&(e.openElements.pop(),e.insertionMode=T.IN_TABLE,e._processToken(t))}function Xs(e,t){switch(t.tagID){case s.TR:{e.openElements.clearBackToTableBodyContext(),e._insertElement(t,Q.HTML),e.insertionMode=T.IN_ROW;break}case s.TH:case s.TD:{e.openElements.clearBackToTableBodyContext(),e._insertFakeElement(R.TR,s.TR),e.insertionMode=T.IN_ROW,Js(e,t);break}case s.CAPTION:case s.COL:case s.COLGROUP:case s.TBODY:case s.TFOOT:case s.THEAD:{e.openElements.hasTableBodyContextInTableScope()&&(e.openElements.clearBackToTableBodyContext(),e.openElements.pop(),e.insertionMode=T.IN_TABLE,Na(e,t));break}default:Na(e,t)}}function fo(e,t){const r=t.tagID;switch(t.tagID){case s.TBODY:case s.TFOOT:case s.THEAD:{e.openElements.hasInTableScope(r)&&(e.openElements.clearBackToTableBodyContext(),e.openElements.pop(),e.insertionMode=T.IN_TABLE);break}case s.TABLE:{e.openElements.hasTableBodyContextInTableScope()&&(e.openElements.clearBackToTableBodyContext(),e.openElements.pop(),e.insertionMode=T.IN_TABLE,yn(e,t));break}case s.BODY:case s.CAPTION:case s.COL:case s.COLGROUP:case s.HTML:case s.TD:case s.TH:case s.TR:break;default:yn(e,t)}}function Js(e,t){switch(t.tagID){case s.TH:case s.TD:{e.openElements.clearBackToTableRowContext(),e._insertElement(t,Q.HTML),e.insertionMode=T.IN_CELL,e.activeFormattingElements.insertMarker();break}case s.CAPTION:case s.COL:case s.COLGROUP:case s.TBODY:case s.TFOOT:case s.THEAD:case s.TR:{e.openElements.hasInTableScope(s.TR)&&(e.openElements.clearBackToTableRowContext(),e.openElements.pop(),e.insertionMode=T.IN_TABLE_BODY,Xs(e,t));break}default:Na(e,t)}}function Wd(e,t){switch(t.tagID){case s.TR:{e.openElements.hasInTableScope(s.TR)&&(e.openElements.clearBackToTableRowContext(),e.openElements.pop(),e.insertionMode=T.IN_TABLE_BODY);break}case s.TABLE:{e.openElements.hasInTableScope(s.TR)&&(e.openElements.clearBackToTableRowContext(),e.openElements.pop(),e.insertionMode=T.IN_TABLE_BODY,fo(e,t));break}case s.TBODY:case s.TFOOT:case s.THEAD:{(e.openElements.hasInTableScope(t.tagID)||e.openElements.hasInTableScope(s.TR))&&(e.openElements.clearBackToTableRowContext(),e.openElements.pop(),e.insertionMode=T.IN_TABLE_BODY,fo(e,t));break}case s.BODY:case s.CAPTION:case s.COL:case s.COLGROUP:case s.HTML:case s.TD:case s.TH:break;default:yn(e,t)}}function iS(e,t){const r=t.tagID;zd.has(r)?(e.openElements.hasInTableScope(s.TD)||e.openElements.hasInTableScope(s.TH))&&(e._closeTableCell(),Js(e,t)):Et(e,t)}function oS(e,t){const r=t.tagID;switch(r){case s.TD:case s.TH:{e.openElements.hasInTableScope(r)&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilTagNamePopped(r),e.activeFormattingElements.clearToLastMarker(),e.insertionMode=T.IN_ROW);break}case s.TABLE:case s.TBODY:case s.TFOOT:case s.THEAD:case s.TR:{e.openElements.hasInTableScope(r)&&(e._closeTableCell(),Wd(e,t));break}case s.BODY:case s.CAPTION:case s.COL:case s.COLGROUP:case s.HTML:break;default:Ks(e,t)}}function $d(e,t){switch(t.tagID){case s.HTML:{Et(e,t);break}case s.OPTION:{e.openElements.currentTagId===s.OPTION&&e.openElements.pop(),e._insertElement(t,Q.HTML);break}case s.OPTGROUP:{e.openElements.currentTagId===s.OPTION&&e.openElements.pop(),e.openElements.currentTagId===s.OPTGROUP&&e.openElements.pop(),e._insertElement(t,Q.HTML);break}case s.HR:{e.openElements.currentTagId===s.OPTION&&e.openElements.pop(),e.openElements.currentTagId===s.OPTGROUP&&e.openElements.pop(),e._appendElement(t,Q.HTML),t.ackSelfClosing=!0;break}case s.INPUT:case s.KEYGEN:case s.TEXTAREA:case s.SELECT:{e.openElements.hasInSelectScope(s.SELECT)&&(e.openElements.popUntilTagNamePopped(s.SELECT),e._resetInsertionMode(),t.tagID!==s.SELECT&&e._processStartTag(t));break}case s.SCRIPT:case s.TEMPLATE:{$t(e,t);break}}}function qd(e,t){switch(t.tagID){case s.OPTGROUP:{e.openElements.stackTop>0&&e.openElements.currentTagId===s.OPTION&&e.openElements.tagIDs[e.openElements.stackTop-1]===s.OPTGROUP&&e.openElements.pop(),e.openElements.currentTagId===s.OPTGROUP&&e.openElements.pop();break}case s.OPTION:{e.openElements.currentTagId===s.OPTION&&e.openElements.pop();break}case s.SELECT:{e.openElements.hasInSelectScope(s.SELECT)&&(e.openElements.popUntilTagNamePopped(s.SELECT),e._resetInsertionMode());break}case s.TEMPLATE:{na(e,t);break}}}function cS(e,t){const r=t.tagID;r===s.CAPTION||r===s.TABLE||r===s.TBODY||r===s.TFOOT||r===s.THEAD||r===s.TR||r===s.TD||r===s.TH?(e.openElements.popUntilTagNamePopped(s.SELECT),e._resetInsertionMode(),e._processStartTag(t)):$d(e,t)}function uS(e,t){const r=t.tagID;r===s.CAPTION||r===s.TABLE||r===s.TBODY||r===s.TFOOT||r===s.THEAD||r===s.TR||r===s.TD||r===s.TH?e.openElements.hasInTableScope(r)&&(e.openElements.popUntilTagNamePopped(s.SELECT),e._resetInsertionMode(),e.onEndTag(t)):qd(e,t)}function lS(e,t){switch(t.tagID){case s.BASE:case s.BASEFONT:case s.BGSOUND:case s.LINK:case s.META:case s.NOFRAMES:case s.SCRIPT:case s.STYLE:case s.TEMPLATE:case s.TITLE:{$t(e,t);break}case s.CAPTION:case s.COLGROUP:case s.TBODY:case s.TFOOT:case s.THEAD:{e.tmplInsertionModeStack[0]=T.IN_TABLE,e.insertionMode=T.IN_TABLE,Na(e,t);break}case s.COL:{e.tmplInsertionModeStack[0]=T.IN_COLUMN_GROUP,e.insertionMode=T.IN_COLUMN_GROUP,Go(e,t);break}case s.TR:{e.tmplInsertionModeStack[0]=T.IN_TABLE_BODY,e.insertionMode=T.IN_TABLE_BODY,Xs(e,t);break}case s.TD:case s.TH:{e.tmplInsertionModeStack[0]=T.IN_ROW,e.insertionMode=T.IN_ROW,Js(e,t);break}default:e.tmplInsertionModeStack[0]=T.IN_BODY,e.insertionMode=T.IN_BODY,Et(e,t)}}function dS(e,t){t.tagID===s.TEMPLATE&&na(e,t)}function Qd(e,t){e.openElements.tmplCount>0?(e.openElements.popUntilTagNamePopped(s.TEMPLATE),e.activeFormattingElements.clearToLastMarker(),e.tmplInsertionModeStack.shift(),e._resetInsertionMode(),e.onEof(t)):Vo(e,t)}function fS(e,t){t.tagID===s.HTML?Et(e,t):Ms(e,t)}function Kd(e,t){var r;if(t.tagID===s.HTML){if(e.fragmentContext||(e.insertionMode=T.AFTER_AFTER_BODY),e.options.sourceCodeLocationInfo&&e.openElements.tagIDs[0]===s.HTML){e._setEndLocation(e.openElements.items[0],t);const a=e.openElements.items[1];a&&!(!((r=e.treeAdapter.getNodeSourceCodeLocation(a))===null||r===void 0)&&r.endTag)&&e._setEndLocation(a,t)}}else Ms(e,t)}function Ms(e,t){e.insertionMode=T.IN_BODY,Qs(e,t)}function mS(e,t){switch(t.tagID){case s.HTML:{Et(e,t);break}case s.FRAMESET:{e._insertElement(t,Q.HTML);break}case s.FRAME:{e._appendElement(t,Q.HTML),t.ackSelfClosing=!0;break}case s.NOFRAMES:{$t(e,t);break}}}function hS(e,t){t.tagID===s.FRAMESET&&!e.openElements.isRootHtmlElementCurrent()&&(e.openElements.pop(),!e.fragmentContext&&e.openElements.currentTagId!==s.FRAMESET&&(e.insertionMode=T.AFTER_FRAMESET))}function pS(e,t){switch(t.tagID){case s.HTML:{Et(e,t);break}case s.NOFRAMES:{$t(e,t);break}}}function gS(e,t){t.tagID===s.HTML&&(e.insertionMode=T.AFTER_AFTER_FRAMESET)}function ES(e,t){t.tagID===s.HTML?Et(e,t):As(e,t)}function As(e,t){e.insertionMode=T.IN_BODY,Qs(e,t)}function bS(e,t){switch(t.tagID){case s.HTML:{Et(e,t);break}case s.NOFRAMES:{$t(e,t);break}}}function TS(e,t){t.chars=Qe,e._insertCharacters(t)}function SS(e,t){e._insertCharacters(t),e.framesetOk=!1}function Xd(e){for(;e.treeAdapter.getNamespaceURI(e.openElements.current)!==Q.HTML&&e.openElements.currentTagId!==void 0&&!e._isIntegrationPoint(e.openElements.currentTagId,e.o
214penElements.current);)e.openElements.pop()}function AS(e,t){if(Mb(t))Xd(e),e._startTagOutsideForeignContent(t);else{const r=e._getAdjustedCurrentElement(),a=e.treeAdapter.getNamespaceURI(r);a===Q.MATHML?Ld(t):a===Q.SVG&&(Ub(t),kd(t)),Ho(t),t.selfClosing?e._appendElement(t,a):e._insertElement(t,a),t.ackSelfClosing=!0}}function IS(e,t){if(t.tagID===s.P||t.tagID===s.BR){Xd(e),e._endTagOutsideForeignContent(t);return}for(let r=e.openElements.stackTop;r>0;r--){const a=e.openElements.items[r];if(e.treeAdapter.getNamespaceURI(a)===Q.HTML){e._endTagOutsideForeignContent(t);break}const n=e.treeAdapter.getTagName(a);if(n.toLowerCase()===t.tagName){t.tagName=n,e.openElements.shortenToLength(r);break}}}R.AREA,R.BASE,R.BASEFONT,R.BGSOUND,R.BR,R.COL,R.EMBED,R.FRAME,R.HR,R.IMG,R.INPUT,R.KEYGEN,R.LINK,R.META,R.PARAM,R.SOURCE,R.TRACK,R.WBR;function yS(e,t){return Md.parse(e,t)}function _S(e,t,r){typeof e=="string"&&(r=t,t=e,e=null);const a=Md.getFragmentParser(e,r);return a.tokenizer.write(t,!0),a.getFragment()}const CS={abandonedHeadElementChild:{reason:"Unexpected metadata element after head",description:"Unexpected element after head. Expected the element before `</head>`",url:!1},abruptClosingOfEmptyComment:{reason:"Unexpected abruptly closed empty comment",description:"Unexpected `>` or `->`. Expected `-->` to close comments"},abruptDoctypePublicIdentifier:{reason:"Unexpected abruptly closed public identifier",description:"Unexpected `>`. Expected a closing `\"` or `'` after the public identifier"},abruptDoctypeSystemIdentifier:{reason:"Unexpected abruptly closed system identifier",description:"Unexpected `>`. Expected a closing `\"` or `'` after the identifier identifier"},absenceOfDigitsInNumericCharacterReference:{reason:"Unexpected non-digit at start of numeric character reference",description:"Unexpected `%c`. Expected `[0-9]` for decimal references or `[0-9a-fA-F]` for hexadecimal references"},cdataInHtmlContent:{reason:"Unexpected CDATA section in HTML",description:"Unexpected `<![CDATA[` in HTML. Remove it, use a comment, or encode special characters instead"},characterReferenceOutsideUnicodeRange:{reason:"Unexpected too big numeric character reference",description:"Unexpectedly high character reference. Expected character references to be at most hexadecimal 10ffff (or decimal 1114111)"},closingOfElementWithOpenChildElements:{reason:"Unexpected closing tag with open child elements",description:"Unexpectedly closing tag. Expected other tags to be closed first",url:!1},controlCharacterInInputStream:{reason:"Unexpected control character",description:"Unexpected control character `%x`. Expected a non-control code point, 0x00, or ASCII whitespace"},controlCharacterReference:{reason:"Unexpected control character reference",description:"Unexpectedly control character in reference. Expected a non-control code point, 0x00, or ASCII whitespace"},disallowedContentInNoscriptInHead:{reason:"Disallowed content inside `<noscript>` in `<head>`",description:"Unexpected text character `%c`. Only use text in `<noscript>`s in `<body>`",url:!1},duplicateAttribute:{reason:"Unexpected duplicate attribute",description:"Unexpectedly double attribute. Expected attributes to occur only once"},endTagWithAttributes:{reason:"Unexpected attribute on closing tag",description:"Unexpected attribute. Expected `>` instead"},endTagWithTrailingSolidus:{reason:"Unexpected slash at end of closing tag",description:"Unexpected `%c-1`. Expected `>` instead"},endTagWithoutMatchingOpenElement:{reason:"Unexpected unopened end tag",description:"Unexpected end tag. Expected no end tag or another end tag",url:!1},eofBeforeTagName:{reason:"Unexpected end of file",description:"Unexpected end of file. Expected tag name instead"},eofInCdata:{reason:"Unexpected end of file in CDATA",description:"Unexpected end of file. Expected `]]>` to close the CDATA"},eofInComment:{reason:"Unexpected end of file in comment",description:"Unexpected end of file. Expected `-->` to close the comment"},eofInDoctype:{reason:"Unexpected end of file in doctype",description:"Unexpected end of file. Expected a valid doctype (such as `<!doctype html>`)"},eofInElementThatCanContainOnlyText:{reason:"Unexpected end of file in element that can only contain text",description:"Unexpected end of file. Expected text or a closing tag",url:!1},eofInScriptHtmlCommentLikeText:{reason:"Unexpected end of file in comment inside script",description:"Unexpected end of file. Expected `-->` to close the comment"},eofInTag:{reason:"Unexpected end of file in tag",description:"Unexpected end of file. Expected `>` to close the tag"},incorrectlyClosedComment:{reason:"Incorrectly closed comment",description:"Unexpected `%c-1`. Expected `-->` to close the comment"},incorrectlyOpenedComment:{reason:"Incorrectly opened comment",description:"Unexpected `%c`. Expected `<!--` to open the comment"},invalidCharacterSequenceAfterDoctypeName:{reason:"Invalid sequence after doctype name",description:"Unexpected sequence at `%c`. Expected `public` or `system`"},invalidFirstCharacterOfTagName:{reason:"Invalid first character in tag name",description:"Unexpected `%c`. Expected an ASCII letter instead"},misplacedDoctype:{reason:"Misplaced doctype",description:"Unexpected doctype. Expected doctype before head",url:!1},misplacedStartTagForHeadElement:{reason:"Misplaced `<head>` start tag",description:"Unexpected start tag `<head>`. Expected `<head>` directly after doctype",url:!1},missingAttributeValue:{reason:"Missing attribute value",description:"Unexpected `%c-1`. Expected an attribute value or no `%c-1` instead"},missingDoctype:{reason:"Missing doctype before other content",description:"Expected a `<!doctype html>` before anything else",url:!1},missingDoctypeName:{reason:"Missing doctype name",description:"Unexpected doctype end at `%c`. Expected `html` instead"},missingDoctypePublicIdentifier:{reason:"Missing public identifier in doctype",description:"Unexpected `%c`. Expected identifier for `public` instead"}
214,missingDoctypeSystemIdentifier:{reason:"Missing system identifier in doctype",description:'Unexpected `%c`. Expected identifier for `system` instead (suggested: `"about:legacy-compat"`)'},missingEndTagName:{reason:"Missing name in end tag",description:"Unexpected `%c`. Expected an ASCII letter instead"},missingQuoteBeforeDoctypePublicIdentifier:{reason:"Missing quote before public identifier in doctype",description:"Unexpected `%c`. Expected `\"` or `'` instead"},missingQuoteBeforeDoctypeSystemIdentifier:{reason:"Missing quote before system identifier in doctype",description:"Unexpected `%c`. Expected `\"` or `'` instead"},missingSemicolonAfterCharacterReference:{reason:"Missing semicolon after character reference",description:"Unexpected `%c`. Expected `;` instead"},missingWhitespaceAfterDoctypePublicKeyword:{reason:"Missing whitespace after public identifier in doctype",description:"Unexpected `%c`. Expected ASCII whitespace instead"},missingWhitespaceAfterDoctypeSystemKeyword:{reason:"Missing whitespace after system identifier in doctype",description:"Unexpected `%c`. Expected ASCII whitespace instead"},missingWhitespaceBeforeDoctypeName:{reason:"Missing whitespace before doctype name",description:"Unexpected `%c`. Expected ASCII whitespace instead"},missingWhitespaceBetweenAttributes:{reason:"Missing whitespace between attributes",description:"Unexpected `%c`. Expected ASCII whitespace instead"},missingWhitespaceBetweenDoctypePublicAndSystemIdentifiers:{reason:"Missing whitespace between public and system identifiers in doctype",description:"Unexpected `%c`. Expected ASCII whitespace instead"},nestedComment:{reason:"Unexpected nested comment",description:"Unexpected `<!--`. Expected `-->`"},nestedNoscriptInHead:{reason:"Unexpected nested `<noscript>` in `<head>`",description:"Unexpected `<noscript>`. Expected a closing tag or a meta element",url:!1},nonConformingDoctype:{reason:"Unexpected non-conforming doctype declaration",description:'Expected `<!doctype html>` or `<!doctype html system "about:legacy-compat">`',url:!1},nonVoidHtmlElementStartTagWithTrailingSolidus:{reason:"Unexpected trailing slash on start tag of non-void element",description:"Unexpected `/`. Expected `>` instead"},noncharacterCharacterReference:{reason:"Unexpected noncharacter code point referenced by character reference",description:"Unexpected code point. Do not use noncharacters in HTML"},noncharacterInInputStream:{reason:"Unexpected noncharacter character",description:"Unexpected code point `%x`. Do not use noncharacters in HTML"},nullCharacterReference:{reason:"Unexpected NULL character referenced by character reference",description:"Unexpected code point. Do not use NULL characters in HTML"},openElementsLeftAfterEof:{reason:"Unexpected end of file",description:"Unexpected end of file. Expected closing tag instead",url:!1},surrogateCharacterReference:{reason:"Unexpected surrogate character referenced by character reference",description:"Unexpected code point. Do not use lone surrogate characters in HTML"},surrogateInInputStream:{reason:"Unexpected surrogate character",description:"Unexpected code point `%x`. Do not use lone surrogate characters in HTML"},unexpectedCharacterAfterDoctypeSystemIdentifier:{reason:"Invalid character after system identifier in doctype",description:"Unexpected character at `%c`. Expected `>`"},unexpectedCharacterInAttributeName:{reason:"Unexpected character in attribute name",description:"Unexpected `%c`. Expected whitespace, `/`, `>`, `=`, or probably an ASCII letter"},unexpectedCharacterInUnquotedAttributeValue:{reason:"Unexpected character in unquoted attribute value",description:"Unexpected `%c`. Quote the attribute value to include it"},unexpectedEqualsSignBeforeAttributeName:{reason:"Unexpected equals sign before attribute name",description:"Unexpected `%c`. Add an attribute name before it"},unexpectedNullCharacter:{reason:"Unexpected NULL character",description:"Unexpected code point `%x`. Do not use NULL characters in HTML"},unexpectedQuestionMarkInsteadOfTagName:{reason:"Unexpected question mark instead of tag name",description:"Unexpected `%c`. Expected an ASCII letter instead"},unexpectedSolidusInTag:{reason:"Unexpected slash in tag",description:"Unexpected `%c-1`. Expected it followed by `>` or in a quoted attribute value"},unknownNamedCharacterReference:{reason:"Unexpected unknown named character reference",description:"Unexpected character reference. Expected known named character references"}},wS="https://html.spec.whatwg.org/multipage/parsing.html#parse-error-",RS=/-[a-z]/g,NS=/%c(?:([-+])(\d+))?/g,PS=/%x/g,xS={2:!0,1:!1,
2140:null},OS={};function vS(e,t){const r=t||OS,a=r.onerror,n=e instanceof su?e:new su(e),i=r.fragment?_S:yS,o=String(n),c=i(o,{sourceCodeLocationInfo:!0,onParseError:r.onerror?f:null,scriptingEnabled:!1});return WE(c,{file:n,space:r.space,verbose:r.verbose});function f(d){const S=d.code,b=LS(S),w=r[b],v=w??!0,j=typeof v=="number"?v:v?1:0;if(j){const V=CS[b],Y=new Bh($(V.reason),{place:{start:{line:d.startLine,column:d.startCol,offset:d.startOffset},end:{line:d.endLine,column:d.endCol,offset:d.endOffset}},ruleId:S,source:"hast-util-from-html"});n.path&&(Y.file=n.path,Y.name=n.path+":"+Y.name),Y.fatal=xS[j],Y.note=$(V.description),Y.url=V.url===!1?void 0:wS+S,a(Y)}function $(V){return V.replace(NS,Y).replace(PS,q);function Y(K,Se,ee){const Z=(ee?Number.parseInt(ee,10):0)*(Se==="-"?-1:1),fe=o.charAt(d.startOffset+Z);return DS(fe)}function q(){return MS(o.charCodeAt(d.startOffset))}}}}function LS(e){return e.replace(RS,kS)}function kS(e){return e.charAt(1).toUpperCase()}function DS(e){return e==="`"?"` ` `":e}function MS(e){return"0x"+e.toString(16).toUpperCase()}const qi={maxMessages:200,maxMessageChars:2e4,maxMessageReferenceBytes:4*1024*1024},US=e=>typeof TextEncoder<"u"?new TextEncoder().encode(e).byteLength:Buffer.byteLength(e,"utf8"),mo=e=>!!e&&typeof e=="object"&&!Array.isArray(e),Jd=(e,t)=>Object.keys(e).every(r=>t.includes(r)),ul=e=>mo(e)&&Jd(e,["id","materialId","fileOrdinal","sectionId","sectionTitle","quote","startOffset","endOffset"])&&typeof e.id=="string"&&e.id.trim().length>0&&typeof e.materialId=="string"&&e.materialId.trim().length>0&&Number.isSafeInteger(e.fileOrdinal)&&e.fileOrdinal>=0&&typeof e.sectionId=="string"&&e.sectionId.trim().length>0&&typeof e.sectionTitle=="string"&&e.sectionTitle.trim().length>0&&typeof e.quote=="string"&&e.quote.length>0&&Number.isSafeInteger(e.startOffset)&&Number.isSafeInteger(e.endOffset)&&e.startOffset>=0&&e.endOffset>e.startOffset&&e.endOffset-e.startOffset===e.quote.length,ll=(e=Number.NaN,t=Number.POSITIVE_INFINITY,r=Number.NaN)=>({ok:!1,messageCount:e,maxMessageChars:t,jsonBytes:r,reason:"invalid_payload",code:"RESEARCH_CAPACITY_INVALID_PAYLOAD"});function BS(e,t=[]){try{const r=JSON.stringify({messages:e,references:t});return typeof r=="string"?US(r):Number.NaN}catch{return Number.NaN}}function FS(e,t=[]){try{const r=Array.isArray(e)&&Array.isArray(t),a=Array.isArray(e)?e.length:Number.NaN,n=Array.isArray(e)?e.reduce((S,b)=>Math.max(S,mo(b)&&typeof b.text=="string"?b.text.length:Number.POSITIVE_INFINITY),0):Number.POSITIVE_INFINITY,i=r?BS(e,t):Number.NaN,o=new Set,c=e.every(S=>!mo(S)||!Jd(S,["id","role","text","citations","createdAt"])||typeof S.id!="string"||S.id.trim().length===0||o.has(S.id)||S.role!=="user"&&S.role!=="assistant"||typeof S.text!="string"||S.text.trim().length===0||S.citations!==void 0&&(!Array.isArray(S.citations)||!S.citations.every(ul))||S.createdAt!==void 0&&typeof S.createdAt!="string"?!1:(o.add(S.id),!0));if(!r||!Number.isFinite(i)||!c||!t.every(ul))return ll(a,n,i);const d={ok:!0,messageCount:a,maxMessageChars:n,jsonBytes:i};return!Number.isSafeInteger(a)||a>qi.maxMessages?{...d,ok:!1,reason:"message_count",code:"RESEARCH_CAPACITY_EXCEEDED"}:n>qi.maxMessageChars?{...d,ok:!1,reason:"message_chars",code:"RESEARCH_CAPACITY_EXCEEDED"}:i>qi.maxMessageReferenceBytes?{...d,ok:!1,reason:"message_reference_bytes",code:"RESEARCH_CAPACITY_EXCEEDED"}:d}catch{return ll()}}const HS=2e4,jS=/^(?:abstract|summary|introduction|background|related work|literature review|method(?:ology)?|approach|model|experiment(?:s|al setup)?|evaluation|result(?:s)?|discussion|limitation(?:s)?|conclusion|references|appendix|摘要|概述|引言|背景|相关工作|文献综述|方法|模型|实验|评估|结果|讨论|局限|结论|参考文献|附录)$/iu,VS=/^(?:references|bibliography|acknowledg(?:e)?ments?|declarations?|参考文献|声明|作者贡献|利益冲突|致谢)$/iu,Pt=e=>!!e&&typeof e=="object"&&!Array.isArray(e),Nt=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),_n=(e,t)=>Object.keys(e).every(r=>t.includes(r)),Zd=e=>e.replace(/\r\n?/gu,`
215`),ho=e=>e.normalize("NFKC").replace(/<[^>]*>/gu,"").replace(/^#+\s*/u,"").replace(/\s+#+\s*$/u,"").replace(/[*_`~]/gu,"").replace(/\s+/gu," ").trim().slice(0,160),ef=e=>e.replace(/^(?:(?:\d+(?:[..]\d+)*)|(?:[IVXLCDM]+))[.)]?\s+/iu,"").trim(),GS=e=>jS.test(ef(e)),YS=e=>{var n;const t=e.trim();if(!t||t.length>180)return null;const r=/^(#{1,6})\s+(.+?)\s*#*$/u.exec(t);if(r){const i=ho(r[2]);return i?{title:i,level:r[1].length}:null}const a=/^(\d{1,2}(?:[.]\d{1,2}
215)*)[.)]?\s+(.+)$/u.exec(t);if(a){const i=ho(t);return i?{title:i,level:Math.min(6,(((n=a[1].match(/[.]/gu))==null?void 0:n.length)??0)+1)}:null}return null},zS=(e,t)=>{var d,S;const r=[],a=t.text.split(`
216`);let n=t.startOffset,i=0,o=null;for(;i<a.length;){const b=a[i],w=n,v=/^\s{0,3}(`{3,}|~{3,})/u.exec(b);if(o){const q=v&&v[1][0]===o.marker&&v[1].length>=o.length;n+=b.length+1,i+=1,q&&(o=null);continue}if(v){o={marker:v[1][0],length:v[1].length},n+=b.length+1,i+=1;continue}let j=YS(b),$=b.length+1,V=Math.min(t.endOffset,n+$);const Y=(d=a[i+1])==null?void 0:d.trim();if(!j&&Y&&/^(?:=+|-+)$/u.test(Y)&&b.trim()){const q=ho(b);q&&(j={title:q,level:Y[0]==="="?1:2},$+=(((S=a[i+1])==null?void 0:S.length)??0)+1,V=Math.min(t.endOffset,n+$),i+=1)}j&&r.push({...j,headingOffset:w,contentOffset:V,endOffset:t.endOffset}),n+=$,i+=1}r.length>0&&r[0].level===1&&!GS(r[0].title)&&r.shift(),r.forEach((b,w)=>{var v;b.endOffset=((v=r[w+1])==null?void 0:v.headingOffset)??t.endOffset});const c=r.filter(b=>b.contentOffset<b.endOffset&&t.text.slice(b.contentOffset-t.startOffset,b.endOffset-t.startOffset).trim().length>0&&!VS.test(ef(b.title)));return(c.length>0?c:[{title:"全文",level:1,headingOffset:t.startOffset,contentOffset:t.startOffset,endOffset:t.endOffset}]).map((b,w)=>({id:`research:${e}:file:${t.fileOrdinal}:section:${w+1}`,materialId:e,fileOrdinal:t.fileOrdinal,title:b.title,level:b.level,startOffset:b.contentOffset,endOffset:b.endOffset}))},WS=e=>{if(typeof e.materialId!="string"||!e.materialId.trim())throw new Error("Research material requires a non-empty materialId");if(!Array.isArray(e.files)||e.files.length===0)throw new Error("Research material requires at least one file");const t=new Set;e.files.forEach((r,a)=>{if(!r||typeof r.name!="string"||!r.name.trim())throw new Error(`Research material file ${a} has no name`);if(typeof r.text!="string"||Zd(r.text).trim().length===0)throw new Error(`Research material file ${a} has no text`);const n=r.fileOrdinal??a;if(!Number.isSafeInteger(n)||n<0||t.has(n))throw new Error(`Research material file ${a} has an invalid or duplicate fileOrdinal`);t.add(n)})},$S=e=>Object.freeze({...e,files:Object.freeze(e.files.map(t=>Object.freeze({...t}))),outline:Object.freeze(e.outline.map(t=>Object.freeze({...t})))});function qS(e){WS(e);let t=0;const r=e.files.map((i,o)=>{const c=Zd(i.text),f=t,d=f+c.length;return t=d+(o<e.files.length-1?1:0),{name:i.name,text:c,fileOrdinal:i.fileOrdinal??o,startOffset:f,endOffset:d}}),a=r.map(i=>i.text).join(`
217`),n=r.flatMap(i=>zS(e.materialId,i));return $S({materialId:e.materialId,files:r,fullText:a,outline:n})}const QS=(e,t)=>Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((r,a)=>{const n=t[a];return Pt(r)&&r.id===n.id&&r.materialId===n.materialId&&r.fileOrdinal===n.fileOrdinal&&r.title===n.title&&r.level===n.level&&r.startOffset===n.startOffset&&r.endOffset===n.endOffset}),KS=e=>{if(!Pt(e)||typeof e.materialId!="string"||!Array.isArray(e.files))return null;const t=[];for(const r of e.files){const a=Pt(r)?r.fileOrdinal:void 0;if(!Pt(r)||!_n(r,["name","text","fileOrdinal","startOffset","endOffset"])||typeof r.name!="string"||typeof r.text!="string"||!Number.isSafeInteger(a)||Nt(r,"startOffset")!==Nt(r,"endOffset"))return null;t.push({name:r.name,text:r.text,fileOrdinal:a})}return t};function Ln(e){var i,o;if(!Pt(e)||Nt(e,"version")&&e.version!==1)return null;const t=Nt(e,"version")?["version","materialId","files"]:["materialId","files","fullText","outline"];if(Nt(e,"version")&&(e.version!==1||!Nt(e,"materialId")||!Nt(e,"files"))||!_n(e,t))return null;const r=KS(e);if(!r)return null;let a;try{a=qS({materialId:e.materialId,files:r})}catch{return null}if(Nt(e,"fullText")&&(typeof e.fullText!="string"||e.fullText!==a.fullText)||Nt(e,"outline")&&(!Array.isArray(e.outline)||!e.outline.every(c=>Pt(c)&&_n(c,["id","materialId","fileOrdinal","title","level","startOffset","endOffset"]))||!QS(e.outline,a.outline)))return null;const n=e.files;for(let c=0;c<n.length;c+=1){const f=n[c];if(Pt(f)&&Nt(f,"startOffset")&&(f.startOffset!==((i=a.files[c])==null?void 0:i.startOffset)||f.endOffset!==((o=a.files[c])==null?void 0:o.endOffset)))return null}return a}const XS=e=>!Pt(e)||Nt(e,"version")||typeof e.fullText!="string"||!Array.isArray(e.outline)||!Array.isArray(e.files)||!e.files.every(t=>Pt(t)&&Nt(t,"startOffset")&&Nt(t,"endOffset")&&Number.isSafeInteger(t.startOffset)&&Number.isSafeInteger(t.endOffset))?!1:Ln(e)!==null,Zs=e=>XS(e)?Ln(e):null;function eI(e,t){const r=Zs(e);if(!r)return null;const a=t?r.outline.find(n=>n.id===t):r.outline[0];return a?{materialId:r.materialId,section:{...a},text:r.fullText.slice(a.startOffset,a.endOffset)}:null}function JS(e){const t=Zs(e);if(!t)throw new Error("Research material is not canonical");return{version:1,materialId:t.materialId,files:t.files.map(({name:r,text:a,fileOrdinal:n})=>({name:r,text:a,fileOrdinal:n}))}}const ZS=(e,t)=>e.files.find(r=>r.fileOrdinal===t),tf=e=>typeof e=="string"&&/^C\d{1,4}$/u.test(e)?e:"";function Yo(e,t){const r=Zs(t);if(!Pt(e)||!r||!_n(e,["id","materialId","fileOrdinal","sectionId","sectionTitle","quote","startOffset","endOffset"]))return null;const a=tf(e.id),n=e.materialId,i=e.fileOrdinal,o=e.sectionId,c=e.sectionTitle,f=e.quote,d=e.startOffset,S=e.endOffset;if(!a||n!==r.materialId||typeof o!="string"||typeof c!="string"||typeof f!="string"||f.length===0||f.length>HS||typeof i!="number"||typeof d!="number"||typeof S!="number"||!Number.isSafeInteger(i)||!Number.isSafeInteger(d)||!Number.isSafeInteger(S)||d<0||S<=d||S-d!==f.length)return null;const b=ZS(r,i),w=r.outline.find(v=>v.id===o);return!b||!w||w.materialId!==r.materialId||w.fileOrdinal!==i||w.title!==c||d<b.startOffset||S>b.endOffset||d<w.startOffset||S>w.endOffset||r.fullText.slice(d,S)!==f?null:{id:a,materialId:r.materialId,fileOrdinal:i,sectionId:o,sectionTitle:c,quote:f,startOffset:d,endOffset:S}}const e1=e=>Pt(e)&&_n(e,["id","materialId","fileOrdinal","sectionId","sectionTitle","quote","startOffset","endOffset"])&&!!tf(e.id)&&typeof e.materialId=="string"&&Number.isSafeInteger(e.fileOrdinal)&&typeof e.sectionId=="string"&&typeof e.sectionTitle=="string"&&typeof e.quote=="string"&&Number.isSafeInteger(e.startOffset)&&Number.isSafeInteger(e.endOffset)&&e.startOffset<e.endOffset&&e.endOffset-e.startOffset===e.quote.length;function rf(e,t,r){if(typeof e!="string"||!Array.isArray(t)||t.length===0||!Zs(r))return[];const a=new Map;for(const o of t){if(!Pt(o)||typeof o.id!="string")continue;const c=o.id;if(a.has(c))return[];const f=c.trim();if(t.some(S=>Pt(S)&&typeof S.id=="string"&&S.id.trim()===f&&S!==o))return[];if(!e1(o))continue;const d=Yo(o,r);d&&a.set(d.id,d)}const n=[],i=new Set;for(const o of e.matchAll(/[\[【]([^\]】]{1,80})[\]】]/gu))for(const c of o[1].matchAll(/\bC\d{1,4}\b/gu)){const f=c[0],d=a.get(f);!d||i.has(f)||(i.add(f),n.push(d))}return n}const t1=e=>e.replace(/[ \t]*(?:\[C\d{1,4}\]|【C\d{1,4}】)/gu,"").replace(/\n{3,}/gu,`
218
219`).trim(),tI=t1,zo=(e,t=0)=>{var n,i,o,c;const r=(i=(n=e.position)==null?void 0:n.start)==null?void 0:i.offset,a=(c=(o=e.position)==null?void 0:o.end)==null?void 0:c.offset;return Number.isSafeInteger(r)&&Number.isSafeInteger(a)&&a>=r?{startOffset:t+r,endOffset:t+a}:null},bn=(e,t)=>({alt:"",url:"",title:null,html:!0,startOffset:e,endOffset:t}),af=e=>/<\s*img(?=[\s/>]|$)/iu.test(e),Wo=(e,t,r)=>e>=0&&e<t&&t<=r,r1=e=>{const t=[];let r=!1;try{const a=Pl().use(xl).use(Ol).parse(e);To(a,"html",n=>{const i=n;
219if(typeof i.value!="string")return;const o=zo(i);if(!o||!Wo(o.startOffset,o.endOffset,e.length)||e.slice(o.startOffset,o.endOffset)!==i.value){af(i.value)&&(r=!0);return}t.push({value:i.value,...o})})}catch{return null}return r?null:t},a1=e=>{const t=[];let r=!1,a=!1;const n=af(e.value);try{const i=vS(e.value,{fragment:!0,onerror:()=>{a=!0}});To(i,"element",o=>{var d,S,b;const c=o;if(String(c.tagName??"").toLowerCase()!=="img")return;const f=zo(c);if(!f||!Wo(f.startOffset,f.endOffset,e.value.length)){r=!0;return}t.push({alt:typeof((d=c.properties)==null?void 0:d.alt)=="string"?c.properties.alt:"",url:typeof((S=c.properties)==null?void 0:S.src)=="string"?c.properties.src:"",title:typeof((b=c.properties)==null?void 0:b.title)=="string"?c.properties.title:null,html:!0,startOffset:e.startOffset+f.startOffset,endOffset:e.startOffset+f.endOffset})})}catch{return n?[bn(e.startOffset,e.endOffset)]:[]}return(a||r)&&n?[bn(e.startOffset,e.endOffset)]:t};function rI(e){if(typeof e!="string")return[];const t=[];let r=!1;try{const n=Pl().use(xl).use(Ol).parse(e);if(To(n,"image",o=>{const c=o,f=zo(c);if(!f||!Wo(f.startOffset,f.endOffset,e.length)||typeof c.url!="string"){r=!0;return}t.push({alt:c.alt??"",url:c.url,title:c.title,html:!1,...f})}),r)return[bn(0,e.length)];const i=r1(e);if(i===null)return[bn(0,e.length)];for(const o of i)t.push(...a1(o))}catch{return[bn(0,e.length)]}const a=new Set;return t.sort((n,i)=>n.startOffset-i.startOffset||n.endOffset-i.endOffset).filter(n=>{const i=`${n.startOffset}:${n.endOffset}`;return a.has(i)?!1:(a.add(i),!0)})}const n1=48,dl=/[\r\n\u2028\u2029\u0000-\u001f\u007f`<>\[\]{}]|(?:system|developer|assistant|user)\s*[::]|(?:系统|开发者|助手|用户)\s*[::]|ignore\s+(?:all\s+)?(?:previous|prior|above)\s+(?:instructions?|rules?)|忽略(?:以上|之前|所有)?(?:指令|规则|提示)/iu;function s1(e){if(typeof e!="string"||dl.test(e))return"";const t=e.normalize("NFKC").replace(/\s+/gu," ").trim();return!t||dl.test(t)?"":Array.from(t).slice(0,n1).join("")}const i1=1,o1=16*1024,Us=120,nf=80,$o=240,qo=80,sf=80,c1=["version","title","category","preview","character","background","outputLanguage","narrativeStyle","playerAddress"],u1=["kind","id","skinId","name","reference"],l1=["kind","id"],d1=["kind","dbId"],f1=["kind","id","name"],m1=new Set(["title","category","preview","character","background","outputLanguage","narrativeStyle","playerAddress"]),h1=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u,p1=/[\u0000-\u001f\u007f\u2028\u2029]/u,g1=e=>!!e&&typeof e=="object"&&!Array.isArray(e),Tn=(e,t)=>Object.keys(e).every(r=>t.includes(r)),Br=(e,t,r,a=!1)=>{if(typeof e!="string")throw gt(`研究${r}无效。`);const n=e.normalize("NFKC").replace(/[ \t\r\n]+/gu," ").trim();if(a&&!n||n.length>t||p1.test(n))throw gt(`研究${r}无效。`);return n},Bs=(e,t,r)=>e==null||e===""?null:Br(e,t,r),Sa=(e,t)=>{const r=Br(e,128,t,!0);if(!h1.test(r))throw gt(`研究${t}无效。`);return r},gt=e=>Object.assign(new Error(e),{code:"RESEARCH_METADATA_INVALID",httpStatus:400}),Cn=(e,t="研究元数据无效。")=>{if(!g1(e))throw gt(t);return e},of=e=>{const t=Cn(e,"研究角色无效。");if(!Tn(t,u1)||t.kind!=="default"&&t.kind!=="cloud")throw gt("研究角色无效。");const r=t.kind==="default"?Sa(t.id,"角色标识").toUpperCase():Sa(t.id,"角色标识"),a=t.skinId==null||t.skinId===""?"base":Sa(t.skinId,"皮肤标识"),n=Br(t.name,qo,"角色名称",!0),i=Cn(t.reference,"研究角色引用无效。");if(t.kind==="default"){if(!Tn(i,l1)||i.kind!=="default"||String(i.id||"").trim().toUpperCase()!==r)throw gt("研究角色引用无效。")}else if(!Tn(i,d1)||i.kind!=="cloud"||i.dbId!==t.id)throw gt("研究角色引用无效。");return{kind:t.kind,id:r,skinId:a,name:n,reference:t.kind==="default"?{kind:"default",id:r}:{kind:"cloud",dbId:Sa(i.dbId,"角色引用")}}},cf=e=>{const t=Cn(e,"研究背景无效。");if(!Tn(t,f1)||t.kind!=="preset"&&t.kind!=="custom")throw gt("研究背景无效。");return{kind:t.kind,id:t.kind==="preset"?Sa(t.id,"背景标识").toLowerCase():Sa(t.id,"背景标识"),name:Br(t.name,qo,"背景名称",!0)}},E1=e=>{const t=JSON.stringify(e);if((typeof TextEncoder=="function"?new TextEncoder().encode(t).byteLength:unescape(encodeURIComponent(t)).length)>o1)throw gt("研究元数据过大。");return e};
219function Dr(e,t={}){const r=Cn(e);if(!Tn(r,c1)||r.version!==i1)throw gt("研究元数据版本或字段无效。");const a=ad(r.outputLanguage);if(!a)throw gt("研究输出语言无效。");const n=Bs(r.playerAddress,sf,"称呼"),i=n==null?null:s1(n);if(n!=null&&!i)throw gt("研究称呼无效。");const o={version:1,title:Br(r.title,Us,"标题",!0),category:Bs(r.category,nf,"分类"),preview:Br(r.preview,$o,"摘要"),character:of(r.character),background:cf(r.background),outputLanguage:a,narrativeStyle:r.narrativeStyle==="lighthearted"?"lighthearted":r.narrativeStyle==="classic"?"classic":(()=>{throw gt("研究叙事风格无效。")})(),playerAddress:i};return E1(o)}function b1(e){const t=Cn(e,"研究元数据更新载荷无效。");if(Object.keys(t).length===0||Object.keys(t).some(a=>!m1.has(a)))throw gt("研究元数据更新字段无效。");const r={};if(Object.prototype.hasOwnProperty.call(t,"title")&&(r.title=Br(t.title,Us,"标题",!0)),Object.prototype.hasOwnProperty.call(t,"category")&&(r.category=Bs(t.category,nf,"分类")),Object.prototype.hasOwnProperty.call(t,"preview")&&(r.preview=Br(t.preview,$o,"摘要")),Object.prototype.hasOwnProperty.call(t,"character")&&(r.character=of(t.character)),Object.prototype.hasOwnProperty.call(t,"background")&&(r.background=cf(t.background)),Object.prototype.hasOwnProperty.call(t,"outputLanguage")){const a=ad(t.outputLanguage);if(!a)throw gt("研究输出语言无效。");r.outputLanguage=a}if(Object.prototype.hasOwnProperty.call(t,"narrativeStyle")){if(t.narrativeStyle!=="classic"&&t.narrativeStyle!=="lighthearted")throw gt("研究叙事风格无效。");r.narrativeStyle=t.narrativeStyle}return Object.prototype.hasOwnProperty.call(t,"playerAddress")&&(r.playerAddress=Bs(t.playerAddress,sf,"称呼")),r}const uf=e=>(String((e==null?void 0:e.fullText)||"").split(/\r?\n/u).map(r=>r.replace(/^\s*#+\s*/u,"").trim()).find(Boolean)||"").slice(0,$o).trim(),T1=e=>{var a,n;return(String(((n=(a=e==null?void 0:e.files)==null?void 0:a[0])==null?void 0:n.name)||"").split(/[\\/]/u).pop()||"").replace(/\.[A-Za-z0-9]{1,12}$/u,"").trim().slice(0,Us).trim()||uf(e).slice(0,Us)||"Research notes"},S1=()=>({kind:"default",id:"UNKNOWN",skinId:"base",name:"Unknown character",reference:{kind:"default",id:"UNKNOWN"}}),A1=()=>{const e=Pr.find(t=>t.id==="library")||Pr[0];return{kind:"preset",id:String((e==null?void 0:e.id)||"library"),name:String((e==null?void 0:e.name)||"Library").slice(0,qo)}};function Qo(e={},t={}){return Dr({version:1,title:t.title||T1(e),category:t.category??null,preview:t.preview??uf(e),character:t.character||S1(),background:t.background||A1(),outputLanguage:t.outputLanguage||"en",narrativeStyle:t.narrativeStyle||"classic",playerAddress:t.playerAddress??null})}const I1=128,po=2e4,y1=2*1024*1024,_1=/^[A-Za-z0-9][A-Za-z0-9._:-]*$/u,wn=/^p2g-document-image:\/\/([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\/(\d+)$/iu,Fs=/^research-session-[0-9a-f-]{36}$/iu,go=/^research-task-[0-9a-f-]{36}$/iu,C1=/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$/u,w1=new Set(["message_count","message_chars","message_reference_bytes","invalid_payload"]),R1=new Set(["actual_image","data_chart","architecture_diagram"]),N1=e=>e instanceof ae&&e.status===0&&e.code==="RESEARCH_NETWORK_ERROR";class ae extends Error{constructor(t,r,a,n="研究请求失败。"){super(n),this.name="ResearchHttpError",this.code=t,this.status=r,this.kind=a}}const Xe=e=>!!e&&typeof e=="object"&&!Array.isArray(e),rr=e=>typeof e=="string"?e.trim():"",P1=e=>`${e.ownerId}\0${e.sessionId}\0${e.epoch}`,lf=e=>{if(!e||!rr(e.ownerId)||!Number.isSafeInteger(e.epoch)||e.epoch<0)throw new ae("RESEARCH_REQUEST_INVALID",400,"request","研究账户身份无效。")},df=e=>{if(lf(e),!rr(e.sessionId)||!Fs.test(e.sessionId))throw new ae("RESEARCH_REQUEST_INVALID",400,"request","研究会话身份无效。")},dn=e=>{const t=rr(e);if(!t||t.length>I1||!_1.test(t))throw new ae("RESEARCH_OPERATION_INVALID",400,"request","研究操作身份无效。");return t},er=e=>encodeURIComponent(e),ff=(e,t,r)=>`/api/research/sessions/${er(e)}/assets/${er(t)}/${r}`,x1=(e,t)=>Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((r,a)=>{const n=t[a];return r.id===n.id&&r.materialId===n.materialId&&r.fileOrdinal===n.fileOrdinal&&r.title===n.title&&r.level===n.level&&r.startOffset===n.startOffset&&r.endOffset===n.endOffset}),Eo=(e,t,r)=>{if(!Xe(e)||e.role!=="user"&&e.role!=="assistant"||!rr(e.id)||r.has(String(e.id))||typeof e.text!="string"||!e.text.trim())throw new ae("RESEARCH_RESPONSE_INVALID",502,"invali
219d_response","研究响应格式无效。");const a=String(e.id);if(r.add(a),e.createdAt!==void 0&&typeof e.createdAt!="string")throw new ae("RESEARCH_RESPONSE_INVALID",502,"invalid_response","研究响应格式无效。");const n=Object.prototype.hasOwnProperty.call(e,"citations");if(e.role==="user"&&n)throw new ae("RESEARCH_RESPONSE_INVALID",502,"invalid_response","研究响应格式无效。");const i=e.role==="assistant"?(()=>{if(!n)return[];if(!Array.isArray(e.citations))throw new ae("RESEARCH_RESPONSE_INVALID",502,"invalid_response","研究响应格式无效。");const o=new Set,c=e.citations.map(f=>Yo(f,t));if(c.some(f=>!f||o.has(f.id)))throw new ae("RESEARCH_RESPONSE_INVALID",502,"invalid_response","研究响应格式无效。");return c.forEach(f=>o.add(f.id)),rf(e.text,c,t)})():[];return{id:a,role:e.role,text:e.text,...i.length>0?{citations:i}:n?{citations:[]}:{},...typeof e.createdAt=="string"?{createdAt:e.createdAt}:{}}},O1=(e,t,r)=>{if(!Xe(e)||e.materialId!==t.materialId||!rr(e.runId)||!Number.isSafeInteger(e.index)||Number(e.index)<1||!Number.isSafeInteger(e.fileOrdinal)||!t.files.some(n=>n.fileOrdinal===e.fileOrdinal)||typeof e.reference!="string"||!wn.test(e.reference)||!R1.has(String(e.type))||typeof e.description!="string"||e.description.length>300)throw new ae("RESEARCH_RESPONSE_INVALID",502,"invalid_response","研究图片响应格式无效。");const a=wn.exec(e.reference);if(!a||a[1].toLowerCase()!==String(e.runId).toLowerCase()||Number(a[2])!==e.index)throw new ae("RESEARCH_RESPONSE_INVALID",502,"invalid_response","研究图片响应格式无效。");if(e.url!==void 0&&e.url!==ff(r,String(e.runId),e.index))throw new ae("RESEARCH_RESPONSE_INVALID",502,"invalid_response","研究图片响应格式无效。");return{materialId:t.materialId,fileOrdinal:e.fileOrdinal,runId:String(e.runId),index:e.index,reference:e.reference,type:e.type,description:e.description}},Ko=(e,t)=>{try{return e==null?Qo(t):Dr(e,{material:t})}catch{throw new ae("RESEARCH_RESPONSE_INVALID",502,"invalid_response","研究元数据响应格式无效。")}},v1=(e,t,r)=>{if(!Xe(e))throw new ae("RESEARCH_RESPONSE_INVALID",502,"invalid_response","研究会话响应格式无效。");const a=["id","sessionId","materialId","revision","presentation"];if(Object.keys(e).some(i=>!a.includes(i)))throw new ae("RESEARCH_RESPONSE_INVALID",502,"invalid_response","研究会话响应格式无效。");const n=e.id??e.sessionId;if(n!==void 0&&n!==r||e.sessionId!==void 0&&e.sessionId!==r)throw new ae("RESEARCH_RESPONSE_INVALID",502,"invalid_response","研究会话响应身份校验失败。");if(e.materialId!==void 0&&e.materialId!==t.materialId)throw new ae("RESEARCH_RESPONSE_INVALID",502,"invalid_response","研究会话响应身份校验失败。");if(e.revision!==void 0&&(!Number.isSafeInteger(e.revision)||Number(e.revision)<0))throw new ae("RESEARCH_RESPONSE_INVALID",502,"invalid_response","研究版本响应格式无效。");return{...typeof n=="string"?{id:n}:{},...typeof e.sessionId=="string"?{sessionId:e.sessionId}:{},...typeof e.materialId=="string"?{materialId:e.materialId}:{},...Number.isSafeInteger(e.revision)?{revision:e.revision}:{},...e.presentation!==void 0?{presentation:Ko(e.presentation,t)}:{}}},L1=(e,t)=>{if(df(t),!Xe(e)||e.sessionId!==t.sessionId||typeof e.materialId!="string"||!Number.isSafeInteger(e.revision)||Number(e.revision)<0||!Array.isArray(e.messages)||e.metadataMissing!==void 0&&typeof e.metadataMissing!="boolean")throw new ae("RESEARCH_RESPONSE_INVALID",502,"invalid_response","研究会话响应格式无效。");const r=e.material,a=Ln(r);if(!a||a.materialId!==e.materialId||e.fullText!==a.fullText||!x1(e.outline,a.outline))throw new ae("RESEARCH_RESPONSE_INVALID",502,"invalid_response","研究材料响应校验失败。");if(e.selectedSectionId!==void 0&&e.selectedSectionId!==null&&(typeof e.selectedSectionId!="string"||!a.outline.some(b=>b.id===e.selectedSectionId)))throw new ae("RESEARCH_RESPONSE_INVALID",502,"invalid_response","研究章节响应校验失败。");const n=new Set,i=e.messages.map(b=>Eo(b,a,n));if(typeof e.boardContent<"u"&&(typeof e.boardContent!="string"||e.boardContent.length>
219po))throw new ae("RESEARCH_RESPONSE_INVALID",502,"invalid_response","研究黑板响应格式无效。");const o=e.images===void 0?[]:e.images;if(!Array.isArray(o))throw new ae("RESEARCH_RESPONSE_INVALID",502,"invalid_response","研究图片响应格式无效。");let c;if(e.latestTurn!==void 0)if(e.latestTurn===null)c=null;else{if(!Xe(e.latestTurn)||typeof e.latestTurn.operationId!="string"||!Array.isArray(e.latestTurn.imageReferences)||e.latestTurn.imageReferences.some(b=>typeof b!="string"||!wn.test(b))||typeof e.latestTurn.boardContent!="string"||e.latestTurn.boardContent.length>po)throw new ae("RESEARCH_RESPONSE_INVALID",502,"invalid_response","研究当前回答投影格式无效。");c={operationId:e.latestTurn.operationId,boardContent:e.latestTurn.boardContent,imageReferences:[...new Set(e.latestTurn.imageReferences)]}}const f=o.map(b=>O1(b,a,t.sessionId)),d=new Set;if(f.some(b=>d.has(b.reference))||f.some(b=>(d.add(b.reference),!1)))throw new ae("RESEARCH_RESPONSE_INVALID",502,"invalid_response","研究图片响应格式无效。");const S=e.metadataMissing===!0||e.presentation==null;return{ownerId:t.ownerId,sessionId:t.sessionId,revision:e.revision,metadataMissing:S,presentation:Ko(e.presentation,a),...c===void 0?{}:{latestTurn:c},material:a,...typeof e.selectedSectionId=="string"?{selectedSectionId:e.selectedSectionId}:{},messages:i,boardContent:typeof e.boardContent=="string"?e.boardContent:"",images:f.map(b=>({...b,url:""}))}},gs=(e,t)=>{if(!Xe(e)||typeof e.taskId!="string"||!go.test(e.taskId)||typeof e.operationId!="string"||!rr(e.operationId)||!Number.isSafeInteger(e.revision)||Number(e.revision)<0||e.state!=="preparing"&&e.state!=="ready"&&e.state!=="failed"&&e.state!=="cancelled")throw new ae("RESEARCH_RESPONSE_INVALID",502,"invalid_response","研究准备响应格式无效。");const r=dn(e.operationId);if(t&&r!==t)throw new ae("RESEARCH_RESPONSE_INVALID",502,"invalid_response","研究操作身份校验失败。");if(e.state==="ready"&&(typeof e.sessionId!="string"||!Fs.test(e.sessionId)))throw new ae("RESEARCH_RESPONSE_INVALID",502,"invalid_response","研究准备响应格式无效。");if(e.sessionId!==void 0&&(typeof e.sessionId!="string"||!Fs.test(e.sessionId)))throw new ae("RESEARCH_RESPONSE_INVALID",502,"invalid_response","研究准备响应格式无效。");if(e.terminalCode!==void 0&&(typeof e.terminalCode!="string"||!rr(e.terminalCode)))throw new ae("RESEARCH_RESPONSE_INVALID",502,"invalid_response","研究准备响应格式无效。");if(e.presentation!==void 0&&e.presentation!==null&&(()=>{try{return Dr(e.presentation),!1}catch{return!0}})())throw new ae("RESEARCH_RESPONSE_INVALID",502,"invalid_response","研究准备响应格式无效。");if(e.pollAfterMs!==void 0&&(!Number.isSafeInteger(e.pollAfterMs)||e.pollAfterMs<0))throw new ae("RESEARCH_RESPONSE_INVALID",502,"invalid_response","研究准备响应格式无效。");return{taskId:e.taskId,operationId:r,revision:e.revision,state:e.state,...typeof e.sessionId=="string"?{sessionId:e.sessionId}:{},...typeof e.terminalCode=="string"?{terminalCode:e.terminalCode}:{},...typeof e.pollAfterMs=="number"?{pollAfterMs:e.pollAfterMs}:{},...e.presentation!==void 0?{presentation:e.presentation===null?null:Dr(e.presentation)}:{}}},fl=e=>`${e.ownerId}\0${e.epoch}`,ml=(e,t)=>e===401||t==="AUTH_REQUIRED"?"auth":e===404?"not_found":e===409&&t==="RESEARCH_SESSION_STALE_REVISION"?"stale_revision":t==="RESEARCH_CAPACITY_EXCEEDED"?"capacity":e===429||t==="STORY_QUESTION_LIMIT_REACHED"?"quota":e===202||t==="RESEARCH_ASK_PENDING"||t==="RESEARCH_ASK_SAVE_PENDING"?"pending":"request",hl=(e,t)=>typeof e=="string"&&C1.test(e)?e:t,pl=(e,t)=>e==="RESEARCH_METADATA_REFERENCE_NOT_FOUND"?"研究角色或背景已不可用。":e==="RESEARCH_METADATA_UNAVAILABLE"?"研究元数据暂不可用。":t==="auth"?"需要登录。":t==="not_found"?"研究会话不存在。":t==="quota"?"研究问答次数已达上限。":t==="capacity"?"研究会话容量已达上限。":t==="pending"?"研究操作仍在服务端处理中。":e==="RESEARCH_SESSION_STALE_REVISION"?"研究会话版本已变化。":e==="RESEARCH_METADATA_INVALID"?"研究元数据无效。":e==="RESEARCH_OFFLINE_MUTATION_DISABLED"?"离线研究会话为只读。":e==="RESEARCH_SESSION_MATERIAL_INVALID"?"材料校验失败,请联系管理员。":e==="RESEARCH_PRIVATE_STORAGE_NOT_CONFIGURED"?"服务器未配置私有研究存储,请联系管理员。":e==="RESEARCH_PRIVATE_STORAGE_CONFIG_INVALID"?"服务器私有研究存储配置无效,请联系管理员。":e==="RESEARCH_PRIVATE_STORAGE_PUBLIC_CONFIG"?"服务器私有研究存储配置不安全,请联系管理员。":e==="RESEARCH_PRIVATE_STORAGE_BUCKET_COLLISION"?"服务器私有研究存储与公共存储冲突,请联系管理员。":e==="RESEARCH_SOURCE_STORAGE_FAILED"?"研究私有å­
219˜å‚¨æš‚时不可用,请稍后重试或联系管理员。":e==="RESEARCH_PRIVATE_OBJECT_TOO_LARGE"?"研究资产超出服务器存储限制,请联系管理员。":e==="RESEARCH_PRIVATE_OBJECT_TRUNCATED"?"研究资产数据不完整,请联系管理员。":e==="RESEARCH_PRIVATE_OBJECT_NOT_STREAMABLE"?"研究资产数据无法读取,请联系管理员。":e==="RESEARCH_SCHEMA_NOT_READY"?"研究服务尚未完成数据库结构部署,请联系管理员。":"研究请求失败。",k1=async e=>{try{return await e.json()}catch{return null}};function D1({tokenReader:e,fetcher:t,offlineStore:r}){if(typeof e!="function")throw new Error("research HTTP gateway requires a token reader");const a=t??((_,m)=>st(_,m));let n="",i="",o=0,c=0,f=!1;const d=new Set,S=new Map,b=new Map,w=new Map,v=new Map,j=new Map,$=new Map,V=()=>{for(const _ of d)try{URL.revokeObjectURL(_)}catch{}d.clear(),S.clear(),b.clear()},Y=_=>{if(lf(_),f)throw new ae("RESEARCH_GATEWAY_DISPOSED",410,"request","研究会话已关闭。");const m=fl(_);return i!==m&&(V(),w.clear(),v.clear(),j.clear(),$.clear(),n="",i=m,o+=1),{scope:m,generation:o}},q=_=>{if(df(_),f)throw new ae("RESEARCH_GATEWAY_DISPOSED",410,"request","研究会话已关闭。");const m=P1(_),P=fl(_);return(i!==P||n!==m)&&(V(),w.clear(),v.clear(),j.clear(),$.clear(),i=P,n=m,o+=1),{scope:m,generation:o}},K=(_,m)=>{if(f||n!==_||o!==m)throw new ae("RESEARCH_SCOPE_CHANGED",409,"request","研究会话上下文已变化。")},Se=(_,m)=>{if(f||i!==_||o!==m)throw new ae("RESEARCH_SCOPE_CHANGED",409,"request","研究会话上下文已变化。")},ee=_=>{const m=e();if(typeof m!="string"||!m.trim())throw new ae("AUTH_REQUIRED",401,"auth","需要登录。");return{..._?{"Content-Type":_}:{},Authorization:`Bearer ${m.trim()}`}},Z=async(_,m,P,O=!0)=>{if(!P||typeof P.aborted!="boolean")throw new ae("RESEARCH_REQUEST_INVALID",400,"request","研究请求信号无效。");let k;try{k=await a(_,{...m,signal:P})}catch(N){throw P.aborted?N:new ae("RESEARCH_NETWORK_ERROR",0,"request","研究网络请求失败。")}const A=O?await k1(k):null;return{response:k,body:A}},fe=(_,m)=>{if(_.ok)return;const P=hl(Xe(m)?m.code:void 0,_.status===401?"AUTH_REQUIRED":"RESEARCH_REQUEST_FAILED"),O=ml(_.status,P);throw new ae(P,_.status,O,pl(P,O))},ne=async(_,m,P,O,k,A)=>{var te;const{response:N,body:M}=await Z(ff(_.sessionId,m.runId,m.index),{method:"GET",headers:ee()},P,!1);if(O!==void 0&&k!==void 0&&K(O,k),!N.ok){if(N.status===404)return null;fe(N,M)}const F=await N.blob();if(O!==void 0&&k!==void 0&&K(O,k),!F||F.size<=0||F.size>y1||!String(F.type||"").toLowerCase().startsWith("image/")||typeof URL>"u"||typeof URL.createObjectURL!="function")return null;const G=URL.createObjectURL(F);if(d.add(G),b.set(`${_.ownerId}\0${_.sessionId}\0${m.reference}`,F),A!==void 0&&(!O||!k||n===O)&&((te=S.get(A))==null||te.add(G)),O!==void 0&&k!==void 0&&(n!==O||o!==k)||A!==void 0&&c!==A){try{URL.revokeObjectURL(G)}catch{}throw d.delete(G),new ae("RESEARCH_SCOPE_CHANGED",409,"request","研究会话上下文已变化。")}return{...m,url:G}},Pe=async(_,m,P,O,k,A)=>(await Promise.all(m.map(async M=>{try{return await ne(_,M,P,O,k,A)}catch(F){if(F instanceof ae&&F.code==="RESEARCH_SCOPE_CHANGED"||F instanceof DOMException&&F.name==="AbortError")throw F;return null}}))).filter(M=>M!==null),Ee=async _=>{if(!(!r||_.offline||!await r.acknowledge(_)))for(const P of _.images??[]){const O=b.get(`${_.ownerId}\0${_.sessionId}\0${P.reference}`);O&&await r.putAsset({ownerId:_.ownerId,sessionId:_.sessionId,reference:P.reference,blob:O})}},ye=async _=>{if(!r)return;if(!await r.clearSession({ownerId:_.ownerId,sessionId:_.sessionId}))throw new ae("RESEARCH_OFFLINE_DELETE_FAILED",503,"request","研究会话已从服务端删除,但本机缓存删除失败,无法保证重启后不会恢复。")},_e=async(_,m,P,O)=>{if(!r)return null;const k=await r.read(_);if(K(m,P),!k)return null;const A=await Promise.all(k.images.map(async M=>{var te;const F=await r.readAsset({..._,reference:M.reference});if(!F||typeof URL>"u"||typeof URL.createObjectURL!="function")return null;const G=URL.createObjectURL(F);return d.add(G),(te=S.get(O))==null||te.add(G),{...M,url:G}}));K(m,P);const N={ownerId:k.ownerId,sessionId:k.sessionId,revision:k.revision,material:k.material,selectedSectionId:k.selectedSectionId,presentation:k.presentation,metadataMissing:k.metadataMissing,messages:k.messages,boardContent:k.boardContent,images:A.filter(M=>M!==null),offline:!0};return v.set(m,N),N},be=async _=>{var Ie;const m=q(_),P=++c;S.set(P,new Set);const O=`/api/research/sessions/${er(_.sessionId)}`;let k;try{k=await Z(O,{method:"GET",headers:ee()},_.signal)}catch(ve){if(!N1(ve)||_.signal.aborted)throw ve;const it=await _e(_,m.scope,m.generation,P);if(S.delete(P),it)return it;throw ve}const{response:A,body:N}=k;if(K(m.scope,m.generation),A.status===404)return V(),w.clear(),v.delete(m.scope),j.delete(m.scope),$.delete(m.scope),S.delete(P),await ye(_),null;fe(A,N);const M=L1(N,_);K(m.scope,m.generation);const F=v.get(m.scope);if(F&&F.revision>M.revision)return S.delete(P),F;V(),w.clear();const G=((Ie=M.images)==null?void 0:Ie.map(({url:ve,...it})=>it))??[];G.forEach(ve=>w.set(ve.reference,ve));let te;try{te=await Pe(_,G,_.signal,m.scope,m.generation,P)}catch(ve){throw V(),S.delete(P),ve}if(c!==P)throw V(),S.delete(P),new ae("RESEARCH_SCOPE_CHANGED",409,"request","研究会话上下文已变化。");S.delete(P);const ie={...M,images:te};return v.set(m.scope,ie),j.set(m.scope,M.revision),$.set(m.scope,M.revision),Ee(ie),ie},se=async _=>{const m=q(_);if(!Number.isSafeInteger(_.expectedRevision)||_.expectedRevision<0||typeof _.selectedSectionId!="string"||!_.selectedSectionId.trim())throw new ae("RESEARCH_POSITION_INVA
219LID",400,"request","研究章节位置无效。");const{response:P,body:O}=await Z(`/api/research/sessions/${er(_.sessionId)}/position`,{method:"PATCH",headers:ee("application/json"),body:JSON.stringify({expectedRevision:_.expectedRevision,selectedSectionId:_.selectedSectionId})},_.signal);if(K(m.scope,m.generation),fe(P,O),!Xe(O)||!Number.isSafeInteger(O.revision)||Number(O.revision)<0||O.revision!==_.expectedRevision+1)throw new ae("RESEARCH_RESPONSE_INVALID",502,"invalid_response","研究版本响应格式无效。");const k=v.get(m.scope),A=$.get(m.scope)??-1;if(k&&!k.offline&&A<=_.expectedRevision){const N={...k,revision:Math.max(k.revision,O.revision),selectedSectionId:_.selectedSectionId};$.set(m.scope,O.revision),v.set(m.scope,N),Ee(N)}return{revision:O.revision}},me=async _=>{const m=q(_);if(!Number.isSafeInteger(_.expectedRevision)||_.expectedRevision<0)throw new ae("RESEARCH_METADATA_INVALID",400,"request","研究元数据更新载荷无效。");const P=v.get(m.scope);if(P!=null&&P.offline)throw new ae("RESEARCH_OFFLINE_MUTATION_DISABLED",409,"request","离线研究会话为只读。");let O;try{O=b1(_.patch)}catch{throw new ae("RESEARCH_METADATA_INVALID",400,"request","研究元数据更新载荷无效。")}const{response:k,body:A}=await Z(`/api/research/sessions/${er(_.sessionId)}/metadata`,{method:"PATCH",headers:ee("application/json"),body:JSON.stringify({expectedRevision:_.expectedRevision,patch:O})},_.signal);K(m.scope,m.generation);try{fe(k,A)}catch(te){throw te instanceof ae&&te.kind==="stale_revision"&&await be(_).catch(()=>null),te}if(!Xe(A)||!Number.isSafeInteger(A.revision)||Number(A.revision)<0||A.revision!==_.expectedRevision+1||A.metadataMissing!==!1||!Object.prototype.hasOwnProperty.call(A,"presentation"))throw new ae("RESEARCH_RESPONSE_INVALID",502,"invalid_response","研究元数据响应格式无效。");const N=v.get(m.scope),M=N?Ko(A.presentation,N.material):(()=>{try{return Dr(A.presentation)}catch{throw new ae("RESEARCH_RESPONSE_INVALID",502,"invalid_response","研究元数据响应格式无效。")}})(),F=A.revision,G=j.get(m.scope)??-1;if(N&&!N.offline&&G<=_.expectedRevision){const te={...N,revision:Math.max(N.revision,F),presentation:M,metadataMissing:!1};j.set(m.scope,F),v.set(m.scope,te),Ee(te)}return{revision:F,presentation:M}},Oe=(_,m,P)=>{var F,G,te;const O=v.get(P);if(!O||O.offline)return;const k=Number.isSafeInteger(_.revision)?_.revision:(F=_.session)==null?void 0:F.revision;if(k!==void 0&&k<O.revision)return;k!==void 0&&((G=_.session)==null?void 0:G.presentation)!==void 0&&j.set(P,Math.max(j.get(P)??0,k));const A=new Map(O.messages.map(ie=>[ie.id,ie]));for(const ie of[_.userMessage,_.assistantMessage])A.set(ie.id,ie);const N=((te=_.session)==null?void 0:te.presentation)===void 0?O.presentation:_.session.presentation;v.set(P,{...O,...k!==void 0?{revision:k}:{},...N!==void 0?{presentation:N}:{},messages:[...A.values()],...typeof _.boardContent=="string"?{boardContent:_.boardContent}:{}});const M=v.get(P);M&&Ee(M)};return{loadSession:be,updatePosition:se,updateMetadata:me,ask:async _=>{const m=q(_),P=dn(_.operationId),O=v.get(n);if(!O)throw new ae("RESEARCH_SESSION_CONTEXT_REQUIRED",409,"request","研究会话尚未加载。");const k={operationId:P,question:_.question};_.selectedSection!==void 0&&(k.selectedSection=_.selectedSection),_.characterConfiguration!==void 0&&(k.characterConfiguration=_.characterConfiguration);const{response:A,body:N}=await Z(`/api/research/sessions/${er(_.sessionId)}/ask`,{method:"POST",headers:ee("application/json"),body:JSON.stringify(k)},_.signal);if(K(m.scope,m.generation),A.status===202){if((Xe(N)?rr(N.operationId):"")!==P)throw new ae("RESEARCH_RESPONSE_INVALID",502,"invalid_response","研究操作身份校验失败。");return{status:"pending",operationId:P,pendingReason:"ask"}}if(Xe(N)&&N.code==="RESEARCH_ASK_SAVE_PENDING"){if(N.operationId!==void 0&&N.operationId!==P)throw new ae("RESEARCH_RESPONSE_INVALID",502,"invalid_response","研究操作身份校验失败。");return{status:"pending",operationId:P,pendingReason:"save"}}if(!A.ok){const F=hl(Xe(N)?N.code:void 0,A.status===429?"STORY_QUESTION_LIMIT_REACHED":A.status===4
21913?"RESEARCH_CAPACITY_EXCEEDED":"RESEARCH_REQUEST_FAILED"),G=ml(A.status,F);if(G==="quota")return{status:"quota",operationId:P,code:F,count:Xe(N)&&Number.isSafeInteger(N.count)&&N.count>=0?N.count:void 0,limit:Xe(N)&&Number.isSafeInteger(N.limit)&&N.limit>=0?N.limit:void 0};if(G==="capacity")return{status:"capacity",operationId:P,code:F,reason:Xe(N)&&typeof N.reason=="string"&&w1.has(N.reason)?N.reason:void 0};throw new ae(F,A.status,G,pl(F,G))}const M=gl(N,P,O.material,_.sessionId);return Oe(M,_,m.scope),M},saveTurn:async _=>{const m=q(_),P=dn(_.operationId),O=v.get(n);if(!O)throw new ae("RESEARCH_SESSION_CONTEXT_REQUIRED",409,"request","研究会话尚未加载。");const{response:k,body:A}=await Z(`/api/research/sessions/${er(_.sessionId)}/ask/confirm`,{method:"POST",headers:ee("application/json"),body:JSON.stringify({operationId:P})},_.signal);if(K(m.scope,m.generation),k.status===202||Xe(A)&&A.code==="RESEARCH_ASK_SAVE_PENDING"){if(!Xe(A)||A.operationId!==void 0&&A.operationId!==P)throw new ae("RESEARCH_RESPONSE_INVALID",502,"invalid_response","研究操作身份校验失败。");return{status:"pending",operationId:P,pendingReason:"save"}}fe(k,A);const N=gl(A,P,O.material,_.sessionId);return Oe(N,_,m.scope),N},resolveImage:async _=>{var N,M;const m=q(_);if(typeof _.reference!="string"||!wn.test(_.reference))return null;const P=w.get(_.reference);if(!P)return null;const O=v.get(n),k=(N=O==null?void 0:O.images)==null?void 0:N.find(F=>F.reference===_.reference);if((M=k==null?void 0:k.url)!=null&&M.startsWith("blob:"))return k;const A=await ne(_,P,_.signal,m.scope,m.generation,c);if(K(m.scope,m.generation),A){const F=v.get(m.scope);if(F&&!F.offline){const G=new Map((F.images??[]).map(ie=>[ie.reference,ie]));G.set(A.reference,A);const te={...F,images:[...G.values()]};v.set(m.scope,te),Ee(te)}}return A},prepare:async _=>{const m=Y(_),P=dn(_.operationId);let O;if(_.presentation!==void 0)if(_.presentation===null)O=null;else try{O=Dr(_.presentation)}catch{throw new ae("RESEARCH_METADATA_INVALID",400,"request","研究元数据无效。")}const k=_.files??[];if(!Array.isArray(k)||k.length===0&&(typeof _.text!="string"||!_.text.trim()))throw new ae("RESEARCH_DOCUMENTS_REQUIRED",400,"request","请至少提交一个研究文档。");const A=k.length>0&&k.every(G=>typeof Blob<"u"&&G instanceof Blob);let N;if(A){const G=new FormData;G.set("operationId",P),O!==void 0&&G.set("presentation",O===null?"null":JSON.stringify(O)),k.forEach(te=>G.append("file",te,typeof File<"u"&&te instanceof File?te.name:"research.txt")),N={method:"POST",headers:{...ee(),"Idempotency-Key":P},body:G}}else{if(k.some(ie=>!Xe(ie)||typeof ie.name!="string"||typeof ie.text!="string"))throw new ae("RESEARCH_DOCUMENTS_REQUIRED",400,"request","研究文档载荷无效。");const G=k,te={operationId:P};O!==void 0&&(te.presentation=O),G.length>0?te.files=G.map(ie=>({name:ie.name,text:ie.text})):te.text=_.text,N={method:"POST",headers:ee("application/json"),body:JSON.stringify(te)}}const{response:M,body:F}=await Z("/api/research/sessions/prepare",N,_.signal);return Se(m.scope,m.generation),fe(M,F),gs(F,P)},pollPreparation:async _=>{const m=Y(_);if(typeof _.taskId!="string"||!go.test(_.taskId))throw new ae("RESEARCH_REQUEST_INVALID",400,"request","研究准备任务身份无效。");const{response:P,body:O}=await Z(`/api/research/preparations/${er(_.taskId)}`,{method:"GET",headers:ee()},_.signal);return Se(m.scope,m.generation),!P.ok&&P.status===409&&Xe(O)&&(O.state==="failed"||O.state==="cancelled")||fe(P,O),gs(O)},cancelPreparation:async _=>{const m=Y(_);if(typeof _.taskId!="string"||!go.test(_.taskId))throw new ae("RESEARCH_REQUEST_INVALID",400,"request","研究准备任务身份无效。");const{response:P,body:O}=await Z(`/api/research/preparations/${er(_.taskId)}/cancel`,{method:"POST",headers:ee()},_.signal);return Se(m.scope,m.generation),fe(P,O),gs(O)},listSessions:async _=>{const m=Y(_),{response:P,body:O}=await Z("/api/research/sessions",{method:"GET",headers:ee()},_.signal);if(Se(m.scope,m.generation),fe(P,O),!Array.isArray(O))throw new ae("RESEARCH_RESPONSE_INVALID",502,"invali
219d_response","研究会话列表格式无效。");return O.map(k=>{if(!Xe(k)||typeof k.sessionId!="string"||!Fs.test(k.sessionId)||typeof k.operationId!="string"||!rr(k.operationId)||typeof k.materialId!="string"||!rr(k.materialId)||!Number.isSafeInteger(k.revision)||Number(k.revision)<0||k.selectedSectionId!==null&&k.selectedSectionId!==void 0&&typeof k.selectedSectionId!="string"||k.metadataMissing!==void 0&&typeof k.metadataMissing!="boolean"||k.metadataMissing===!1&&k.presentation==null)throw new ae("RESEARCH_RESPONSE_INVALID",502,"invalid_response","研究会话列表格式无效。");let A=null;if(k.presentation!==void 0&&k.presentation!==null)try{A=Dr(k.presentation)}catch{throw new ae("RESEARCH_RESPONSE_INVALID",502,"invalid_response","研究会话列表格式无效。")}return{ownerId:_.ownerId,sessionId:k.sessionId,operationId:dn(k.operationId),materialId:k.materialId,...typeof k.selectedSectionId=="string"?{selectedSectionId:k.selectedSectionId}:{},presentation:A,metadataMissing:k.metadataMissing===!0||k.presentation==null,revision:k.revision,...typeof k.updatedAt=="string"?{updatedAt:k.updatedAt}:{}}})},deleteSession:async _=>{const m=q(_),{response:P,body:O}=await Z(`/api/research/sessions/${er(_.sessionId)}`,{method:"DELETE",headers:ee()},_.signal);if(K(m.scope,m.generation),!P.ok&&P.status===404)return await ye(_),v.delete(n),j.delete(n),$.delete(n),w.clear(),V(),o+=1,c+=1,{deleted:!1};if(fe(P,O),!Xe(O)||typeof O.deleted!="boolean")throw new ae("RESEARCH_RESPONSE_INVALID",502,"invalid_response","研究删除响应格式无效。");return v.delete(n),j.delete(n),$.delete(n),w.clear(),V(),o+=1,c+=1,await ye(_),{deleted:O.deleted}},logout:()=>{V(),w.clear(),v.clear(),j.clear(),$.clear(),n="",i="",o+=1,c+=1},dispose:()=>{f=!0,V(),w.clear(),v.clear(),j.clear(),$.clear(),n="",i="",o+=1,c+=1}}}function gl(e,t,r,a){if(!Xe(e)||e.operationId!==t)throw new ae("RESEARCH_RESPONSE_INVALID",502,"invalid_response","研究操作身份校验失败。");const n=new Set,i=Eo(e.userMessage,r,n),o=Eo(e.assistantMessage,r,n);if(i.role!=="user"||o.role!=="assistant")throw new ae("RESEARCH_RESPONSE_INVALID",502,"invalid_response","研究回答角色校验失败。");if(typeof e.boardContent<"u"&&(typeof e.boardContent!="string"||e.boardContent.length>po))throw new ae("RESEARCH_RESPONSE_INVALID",502,"invalid_response","研究黑板响应格式无效。");if(e.imageReferences!==void 0&&(!Array.isArray(e.imageReferences)||e.imageReferences.some(f=>typeof f!="string"||!wn.test(f))))throw new ae("RESEARCH_RESPONSE_INVALID",502,"invalid_response","研究图片引用响应格式无效。");if(e.revision!==void 0&&(!Number.isSafeInteger(e.revision)||Number(e.revision)<0))throw new ae("RESEARCH_RESPONSE_INVALID",502,"invalid_response","研究版本响应格式无效。");const c=e.session===void 0?void 0:v1(e.session,r,a);return{operationId:t,userMessage:i,assistantMessage:o,...typeof e.boardContent=="string"?{boardContent:e.boardContent}:{},...Array.isArray(e.imageReferences)?{imageReferences:[...new Set(e.imageReferences)]}:{},...Number.isSafeInteger(e.revision)?{revision:e.revision}:{},...c?{session:c}:{}}}const M1=4*1024*1024,U1=3e5,B1=20,mf=2*1024*1024,F1="p2g_research_private_offline",H1=1,hf="p2g-research-offline:v1:record:",j1="p2g-research-offline:v1:registry:",pf="p2g-research-offline:v1:asset:",V1="p2g-research-offline:v1:asset-registry:",bo=/^[^\u0000]{1,256}$/u,Hs=/^research-session-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/iu,Mr=/^p2g-document-image:\/\/([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\/(\d+)$/iu,G1=new Set(["actual_image","data_chart","architecture_diagram"]),Y1=["version","kind","ownerId","sessionId","revision","material","presentation","metadataMissing","latestTurn","selectedSectionId","messages","boardContent","images"],z1=["version","kind","ownerId","sessionId","revision"],kn=e=>!!e&&typeof e=="object"&&!Array.isArray(e),Dn=(e,t)=>Object.keys(e).every(r=>t.includes(r)),W1=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),$1=e=>JSON.parse(JSON.stringify(e)),Yt=e=>
219{if(!e||typeof e.ownerId!="string"||typeof e.sessionId!="string")return null;const t=e.ownerId.trim(),r=e.sessionId.trim();return!bo.test(t)||!Hs.test(r)?null:{ownerId:t,sessionId:r}},Wt=e=>encodeURIComponent(e),ft=e=>`${hf}${Wt(e.ownerId)}:${Wt(e.sessionId)}`,El=e=>`${j1}${Wt(e)}`,Qi=(e,t)=>`${pf}${Wt(e.ownerId)}:${Wt(e.sessionId)}:${Wt(t)}`,gf=e=>`${hf}${Wt(e)}:`,Ef=e=>`${pf}${Wt(e)}:`,Is=e=>`${Ef(e.ownerId)}${Wt(e.sessionId)}:`,bl=e=>`${V1}${Wt(e.ownerId)}:${Wt(e.sessionId)}`,q1=(e,t)=>{const r=gf(e);if(!t.startsWith(r))return null;try{const a=decodeURIComponent(t.slice(r.length));return Hs.test(a)?a:null}catch{return null}},Q1=(e,t)=>{const r=Is(e);if(!t.startsWith(r))return null;try{const a=decodeURIComponent(t.slice(r.length));return Mr.test(a)?a:null}catch{return null}},K1=e=>typeof TextEncoder<"u"?new TextEncoder().encode(e).byteLength:Buffer.byteLength(e,"utf8"),X1=(e,t)=>{if(!Array.isArray(e))return null;const r=new Set,a=[];for(const n of e){if(!kn(n)||!Dn(n,["id","role","text","citations","createdAt"])||n.role!=="user"&&n.role!=="assistant"||typeof n.id!="string"||!n.id.trim()||n.id.length>256||r.has(n.id)||typeof n.text!="string"||!n.text.trim()||n.createdAt!==void 0&&typeof n.createdAt!="string")return null;const i=W1(n,"citations");if(n.role==="user"&&i)return null;let o;if(n.role==="assistant"&&i){if(!Array.isArray(n.citations))return null;const c=new Set,f=n.citations.map(d=>Yo(d,t));if(f.some(d=>!d||c.has(d.id)))return null;f.forEach(d=>c.add(d.id)),o=rf(n.text,f,t)}r.add(n.id),a.push({id:n.id,role:n.role,text:n.text,...o?{citations:o}:{},...typeof n.createdAt=="string"?{createdAt:n.createdAt}:{}})}return a},J1=(e,t)=>{if(!Array.isArray(e))return null;const r=new Set,a=[];for(const n of e){if(!kn(n)||!Dn(n,["materialId","fileOrdinal","runId","index","reference","type","description"])||n.materialId!==t.materialId||typeof n.runId!="string"||!Mr.test(`p2g-document-image://${n.runId}/1`)||!Number.isSafeInteger(n.index)||n.index<1||!Number.isSafeInteger(n.fileOrdinal)||!t.files.some(o=>o.fileOrdinal===n.fileOrdinal)||typeof n.reference!="string"||!Mr.test(n.reference)||r.has(n.reference.toLowerCase())||!G1.has(n.type)||typeof n.description!="string"||n.description.length>300)return null;const i=Mr.exec(n.reference);if(!i||i[1].toLowerCase()!==n.runId.toLowerCase()||Number(i[2])!==n.index)return null;r.add(n.reference.toLowerCase()),a.push({materialId:t.materialId,fileOrdinal:n.fileOrdinal,runId:n.runId,index:n.index,reference:n.reference,type:n.type,description:n.description})}return a},Tl=e=>{if(!kn(e)||!Dn(e,Y1)||e.kind!=="snapshot"||e.version!==1||typeof e.ownerId!="string"||typeof e.sessionId!="string"||!Number.isSafeInteger(e.revision)||e.revision<0||typeof e.boardContent!="string"||e.boardContent.length>2e4||e.metadataMissing!==void 0&&typeof e.metadataMissing!="boolean"||!Array.isArray(e.messages)||!Array.isArray(e.images))return null;const t=Yt({ownerId:e.ownerId,sessionId:e.sessionId});if(!t||t.ownerId!==e.ownerId||t.sessionId!==e.sessionId)return null;const r=Ln(e.material);if(!r||r.fullText.length>U1||r.files.length>B1)return null;const a=X1(e.messages,r),n=J1(e.images,r);if(!a||!n||e.selectedSectionId!==void 0&&e.selectedSectionId!==null&&(typeof e.selectedSectionId!="string"||!r.outline.some(d=>d.id===e.selectedSectionId))||!FS(a,a.flatMap(d=>d.citations??[])).ok)return null;let o;const c=e.metadataMissing===!0||e.presentation==null;try{o=c?Qo(r):Dr(e.presentation,{material:r})}catch{return null}const f={version:1,kind:"snapshot",ownerId:t.ownerId,sessionId:t.sessionId,revision:e.revision,presentation:o,metadataMissing:c,...e.latestTurn===void 0?{}:{latestTurn:e.latestTurn},material:JS(r),...typeof e.selectedSectionId=="string"?{selectedSectionId:e.selectedSectionId}:{},messages:a,boardContent:e.boardContent,images:n};try{if(K1(JSON.stringify(f))>M1)return null}catch{return null}return $1(f)},Z1=e=>{if(!kn(e)||!Dn(e,z1)||e.kind!=="tombstone"||e.version!==1||typeof e.ownerId!="string"||typeof e.sessionId!="string"||!Number.isSafeInteger(e.revision)||e.revision<0)return null;const t=Yt({ownerId:e.ownerId,sessionId:e.sessionId});return t&&t.ownerId===e.ownerId&&t.sessionId===e.sessionId?{version:1,kind:"tombstone",...t,revision:e.revision}:null},eA=e=>{if(!kn(e)||!Dn(e,["version","kind","ownerId","sessionId","reference","blob"])||e.version!==1||e.kind!=="asset"||typeof e.ownerId!="str
219ing"||typeof e.sessionId!="string"||typeof e.reference!="string"||!Mr.test(e.reference)||typeof Blob>"u"||!(e.blob instanceof Blob)||e.blob.size<=0||e.blob.size>mf||!String(e.blob.type||"").toLowerCase().startsWith("image/"))return null;const t=Yt({ownerId:e.ownerId,sessionId:e.sessionId});return t&&t.ownerId===e.ownerId&&t.sessionId===e.sessionId?{version:1,kind:"asset",...t,reference:e.reference,blob:e.blob}:null},Sl=e=>!!e&&typeof e.put=="function"&&typeof e.get=="function"&&typeof e.delete=="function",un=e=>new Promise(t=>{try{const r=e.open(F1,H1);r.onupgradeneeded=()=>{const a=r.result;a.objectStoreNames.contains("records")||a.createObjectStore("records"),a.objectStoreNames.contains("assets")||a.createObjectStore("assets")},r.onsuccess=()=>t(r.result),r.onerror=()=>t(null),r.onblocked=()=>t(null)}catch{t(null)}}),Al=e=>new Promise(t=>{e.onsuccess=()=>t(e.result??null),e.onerror=()=>t(null)});function tA(e={}){const t=e.indexedDB,r=t===void 0?typeof indexedDB>"u"?null:indexedDB:t&&!Sl(t)?t:null,a=Sl(t)?t:null,n=e.localStorage===void 0?typeof localStorage>"u"?null:localStorage:e.localStorage,i=!!(a||r);let o=null,c=0,f=!1;const d=new Map;let S=Promise.resolve();const b=B=>{const U=S.then(B,B);return S=U.then(()=>{},()=>{}),U},w=B=>!f&&c===B,v=async(B,U="records")=>{if(a)try{return{available:!0,value:await a.get(B)}}catch{return{available:!1,value:null}}if(r){o??(o=un(r));const z=await o;if(z)try{return{available:!0,value:await Al(z.transaction(U,"readonly").objectStore(U).get(B))}}catch{return{available:!1,value:null}}return{available:!1,value:null}}if(U==="assets"||!n)return{available:!1,value:null};try{const z=n.getItem(B);return{available:!0,value:z==null?null:JSON.parse(z)}}catch{return{available:!1,value:null}}},j=async(B,U,z="records")=>{if(a)try{return await a.put(B,U),!0}catch{return!1}if(r){o??(o=un(r));const re=await o;if(re)try{return await new Promise((le,ue)=>{const he=re.transaction(z,"readwrite");he.objectStore(z).put(U,B),he.oncomplete=()=>le(),he.onerror=()=>ue(he.error),he.onabort=()=>ue(he.error)}),!0}catch{return!1}}if(z==="assets"||!n)return!1;try{return n.setItem(B,JSON.stringify(U)),!0}catch{return!1}},$=async(B,U="records")=>{if(a)try{return await a.delete(B),!0}catch{return!1}if(r){o??(o=un(r));const z=await o;if(z)try{return await new Promise((re,le)=>{const ue=z.transaction(U,"readwrite");ue.objectStore(U).delete(B),ue.oncomplete=()=>re(),ue.onerror=()=>le(ue.error),ue.onabort=()=>le(ue.error)}),!0}catch{return!1}}if(U==="assets")return!r;if(!n)return!0;try{return n.removeItem(B),!0}catch{return!1}},V=async(B,U="records")=>{if(a!=null&&a.list)try{return(await a.list(B)).filter(z=>z.startsWith(B))}catch{throw new Error("research offline key enumeration unavailable")}if(r){o??(o=un(r));const z=await o;if(z)try{const re=await Al(z.transaction(U,"readonly").objectStore(U).getAllKeys());return(Array.isArray(re)?re:[]).filter(le=>typeof le=="string"&&le.startsWith(B))}catch{throw new Error("research offline key enumeration unavailable")}}if(U==="assets"||!n)return[];try{const z=[];for(let re=0;re<n.length;re+=1){const le=n.key(re);le!=null&&le.startsWith(B)&&z.push(le)}return z}catch{throw new Error("research offline key enumeration unavailable")}},Y=async B=>{const U=Yt(B);if(!U)return null;const z=await v(ft(U));if(!z.available)throw new Error("research offline record storage unavailable");return Tl(z.value)??Z1(z.value)},q=async B=>{const U=await v(El(B));if(!U.available)throw new Error("research offline registry storage unavailable");return Array.isArray(U.value)?[...new Set(U.value.filter(z=>typeof z=="string"&&Hs.test(z)))]:[]},K=(B,U)=>j(El(B),[...new Set(U.filter(z=>Hs.test(z)))]),Se=async B=>{const U=await q(B.ownerId);return U.includes(B.sessionId)?!0:K(B.ownerId,[...U,B.sessionId])},ee=async B=>{const U=await v(bl(B));if(!U.available)throw new Error("research offline asset registry unavailable");return Array.isArray(U.value)?[...new Set(U.value.filter(z=>typeof z=="string"&&z.startsWith(Is(B))))]:[]},Z=(B,U)=>j(bl(B),[...new Set(U.filter(z=>z.startsWith(Is(B))))]),fe=async(B,U=new Set)=>{if(!i)return!0;
219if(r&&(o??(o=un(r)),!await o))return!1;const z=await ee(B),re=await V(Is(B),"assets"),le=[...new Set([...z,...re])];let ue=!0;const he=[];for(const Me of le){const _=Q1(B,Me);if(_&&U.has(_.toLowerCase())){he.push(Me);continue}ue=await $(Me,"assets")&&ue}return ue=await Z(B,he)&&ue,ue};return{acknowledge:async B=>{var le;if(!B||typeof B!="object"||B.offline===!0)return!1;const U=Yt({ownerId:B.ownerId,sessionId:B.sessionId});if(!U)return!1;const z=Tl({version:1,kind:"snapshot",...U,revision:B.revision,presentation:B.presentation??null,...B.metadataMissing===!0?{metadataMissing:!0}:{},...B.latestTurn===void 0?{}:{latestTurn:B.latestTurn},material:B.material,selectedSectionId:B.selectedSectionId??null,messages:B.messages,boardContent:B.boardContent??"",images:((le=B.images)==null?void 0:le.map(({url:ue,...he})=>he))??[]});if(!z)return!1;const re=c;return b(async()=>{if(!w(re))return!1;let ue;try{ue=await Y(U)}catch{return!1}if(!w(re)||d.has(ft(U))||ue&&ue.revision>=z.revision||!await j(ft(U),z)||!w(re))return!1;const he=new Set(z.images.map(Me=>Me.reference.toLowerCase()));return!await Se(U)||!w(re)?(await $(ft(U)),!1):fe(U,he)})},read:async B=>{const U=Yt(B);if(!U||d.has(ft(U)))return null;const z=c;return b(async()=>{if(!w(z)||d.has(ft(U)))return null;let re;try{re=await Y(U)}catch{return null}return w(z)&&!d.has(ft(U))&&(re==null?void 0:re.kind)==="snapshot"?Il(re):null})},list:async B=>{const U=typeof B=="string"?B.trim():"";if(!bo.test(U))return[];const z=c;return b(async()=>{if(!w(z))return[];let re;try{re=await q(U)}catch{return[]}const le=await Promise.all(re.map(async ue=>{let he;const Me={ownerId:U,sessionId:ue};if(d.has(ft(Me)))return null;try{he=await Y(Me)}catch{return null}return!d.has(ft(Me))&&(he==null?void 0:he.kind)==="snapshot"?Il(he):null}));return w(z)?le.filter(ue=>ue!==null).sort((ue,he)=>he.revision-ue.revision):[]})},tombstone:async(B,U)=>{const z=Yt(B);if(!z||!Number.isSafeInteger(U)||U<0)return!1;const re=ft(z),le=d.get(re);if(le!==void 0&&le>=U)return!1;d.set(re,U);const ue=c;return b(async()=>{if(!w(ue))return!1;let he;try{he=await Y(z)}catch{return!1}if(!w(ue)||he&&he.revision>=U)return!1;const Me={version:1,kind:"tombstone",...z,revision:U};return!await j(ft(z),Me)||!w(ue)||!await Se(z)?!1:await fe(z)})},clearSession:async B=>{const U=Yt(B);if(!U)return!1;const z=c;return b(async()=>{if(!w(z))return!1;let re;try{re=await Y(U)}catch{return d.set(ft(U),0),!1}const le=(re==null?void 0:re.revision)??0;if(d.set(ft(U),le),!re||re.kind==="snapshot"){const ue={version:1,kind:"tombstone",...U,revision:le};if(!await j(ft(U),ue))return!1}return await Se(U)?fe(U):!1})},clearOwner:async B=>{const U=typeof B=="string"?B.trim():"";if(!bo.test(U))return!1;const z=c;return b(async()=>{if(!w(z))return!1;let re,le;try{re=await q(U),le=await V(gf(U),"records")}catch{return!1}const ue=[...new Set([...re,...le.map(_=>q1(U,_)).filter(_=>_!==null)])];let he=!0;for(const _ of ue){const m={ownerId:U,sessionId:_};let P;try{P=await Y(m)}catch{d.set(ft(m),0),he=!1;continue}const O=(P==null?void 0:P.revision)??0;d.set(ft(m),O),(!P||P.kind==="snapshot")&&(he=await j(ft(m),{version:1,kind:"tombstone",ownerId:U,sessionId:_,revision:O})&&he),he=await fe({ownerId:U,sessionId:_})&&he}const Me=await V(Ef(U),"assets");for(const _ of Me)he=await $(_,"assets")&&he;return he})},putAsset:async B=>{if(!B||typeof B.reference!="string"||!Mr.test(B.reference)||typeof Blob>"u"||!(B.blob instanceof Blob)||B.blob.size<=0||B.blob.size>mf||!String(B.blob.type||"").toLowerCase().startsWith("image/"))return!1;const U=Yt(B);if(!U||!i)return!1;const z=c;return b(async()=>{if(!w(z))return!1;let re;try{re=await Y(U)}catch{return!1}if(!re||re.kind!=="snapshot"||!re.images.some(he=>he.reference.toLowerCase()===B.reference.toLowerCase()))return!1;const le=Qi(U,B.reference);if(!await j(le,{version:1,kind:"asset",...U,reference:B.reference,blob:B.blob},"assets")||!w(z))return!1;const ue=await ee(U);return ue.includes(le)||await Z(U,[...ue,le])?!0:(await $(le,"assets"),!1)})},readAsset:async B=>{if(f||typeof B.reference!="string"||!Mr.test(B.reference))return null;const U=Yt(B);if(!U||!i||typeof Blob>"u")return null;const z=c;return b(async()=>
219{if(!w(z))return null;let re;try{re=await Y(U)}catch{return null}if(!re||re.kind!=="snapshot"||!re.images.some(he=>he.reference.toLowerCase()===B.reference.toLowerCase()))return null;const le=await v(Qi(U,B.reference),"assets");if(!le.available)return null;const ue=eA(le.value);return w(z)&&ue&&ue.ownerId===U.ownerId&&ue.sessionId===U.sessionId?ue.blob:null})},removeAsset:async B=>{if(f||typeof B.reference!="string"||!Mr.test(B.reference))return!1;const U=Yt(B);if(!U||!i)return!1;const z=c;return b(async()=>{if(!w(z))return!1;const re=Qi(U,B.reference),le=await $(re,"assets"),ue=await ee(U);return await Z(U,ue.filter(he=>he!==re)),le})},logout:()=>{f=!0,c+=1,d.clear()}}}const Il=e=>{const t=Ln(e.material);return t?Object.freeze({ownerId:e.ownerId,sessionId:e.sessionId,revision:e.revision,presentation:e.presentation,metadataMissing:e.metadataMissing,...e.latestTurn===void 0?{}:{latestTurn:e.latestTurn},material:t,...e.selectedSectionId?{selectedSectionId:e.selectedSectionId}:{},messages:Object.freeze(e.messages.map(r=>Object.freeze({...r,...r.citations?{citations:Object.freeze(r.citations.map(a=>Object.freeze({...a})))}:{}}))),boardContent:e.boardContent,images:Object.freeze(e.images.map(r=>Object.freeze({...r})))}):null},rA=e=>{var t,r;return((r=(t=e.presentation)==null?void 0:t.title)==null?void 0:r.trim())||"Research session"},aA=e=>({sessionId:e.sessionId,materialId:e.materialId,revision:e.revision,presentation:e.presentation,metadataMissing:e.metadataMissing===!0||e.presentation==null,updatedAt:e.updatedAt,label:rA(e)}),yl=e=>{var t,r;return{sessionId:e.sessionId,materialId:e.material.materialId,revision:e.revision,offline:!0,presentation:e.presentation,metadataMissing:e.metadataMissing===!0||e.presentation==null,label:((r=(t=e.presentation)==null?void 0:t.title)==null?void 0:r.trim())||e.material.files.map(a=>a.name).join(", ")||"Research session"}};function nA({user:e,language:t,appState:r,gateway:a,offlineStore:n,navigate:i}){const[o,c]=l.useState(null),[f,d]=l.useState(null),[S,b]=l.useState(null),[w,v]=l.useState(null),[j,$]=l.useState(!1),[V,Y]=l.useState(!1),[q,K]=l.useState(!1),[Se,ee]=l.useState(null),[Z,fe]=l.useState(!1),[ne,Pe]=l.useState([]),[Ee,ye]=l.useState(!1),[_e,be]=l.useState(null),se=l.useRef(0),me=l.useRef(null),Oe=l.useRef(null),B=l.useRef(null),U=l.useRef(!1),z=l.useRef(!1),re=l.useRef((e==null?void 0:e.id)??null),le=l.useRef(e);le.current=e;const ue=l.useCallback(()=>{var M;(M=me.current)==null||M.abort(),me.current=null,se.current+=1,c(null),d(null),b(null),v(null),Oe.current=null,B.current=null,U.current=!1,z.current=!1,$(!1),Y(!1),K(!1),ee(null),fe(!1),Pe([]),ye(!1),be(null),a.logout()},[a]);l.useEffect(()=>{const M=(e==null?void 0:e.id)??null;re.current!==M&&(ue(),re.current=M)},[ue,e==null?void 0:e.id]);const he=l.useCallback((M,F)=>({ownerId:M,epoch:se.current,signal:F}),[]),Me=l.useCallback(async()=>{var te,ie;const M=(te=le.current)==null?void 0:te.id;if(!M)return;const F=new AbortController;(ie=me.current)==null||ie.abort(),me.current=F;const G=se.current;ye(!0),be(null);try{const Ie=await a.listSessions(he(M,F.signal));if(G!==se.current||F.signal.aborted)return;const ve=await n.list(M);if(G!==se.current||F.signal.aborted)return;const it=Ie.map(aA),Ye=new Set(it.map(at=>at.sessionId));Pe([...it,...ve.filter(at=>!Ye.has(at.sessionId)).map(yl)])}catch(Ie){if(G!==se.current||F.signal.aborted)return;if(!(Ie instanceof ae)||Ie.code!=="RESEARCH_NETWORK_ERROR"){be(Ie instanceof Error?Ie.message:"研究历史加载失败。");return}try{const ve=await n.list(M);if(G!==se.current||F.signal.aborted)return;Pe(ve.map(yl))}catch{G===se.current&&!F.signal.aborted&&be("研究历史加载失败。")}}finally{me.current===F&&(me.current=null,G===se.current&&ye(!1))}},[a,n,he]),_=l.useCallback(M=>{var te,ie;const F=(te=le.current)==null?void 0:te.id;if(!F||!M.trim())return;(ie=me.current)==null||ie.abort(),me.current=null;const G=ne.find(Ie=>Ie.sessionId===M);v((G==null?void 0:G.presentation)??null),c({ownerId:F,sessionId:M,epoch:se.current}),i(D.RESEARCH_ROOM)},[i,ne]),m=l.useCallback(async(M,F)=>{var Ie,ve,it;const G=(Ie=le.current)==null?void 0:Ie.id;if(!G||M.offline||typeof a.updateMetadata!="function")return!1;const te=se.current,ie=new AbortController;try{const Ye=await a.updateMetadata({ownerId:G,sessionId:M.sessionId,epoch:te,signal:ie.signal,expectedRevision:M.revision,patch:F});return te!==se.current||((ve=le.current)==null?void 0:ve.id)!==G?!1:(Pe(at=>at.map(ot=>ot.sessionId===M.sessionId?{...ot,revision:Ye.revision,presentation:Ye.presentation,metadataMissing:!1,label:Ye.presentation.title}:ot)),!0)}catch(Ye){return te===se.current&&((it=le.current)==null?void 0:it.id)===G&&be(Ye instanceof Error?Ye.message:"研究元数据保存失败。"),!1}},[a]),P=l.useCallback((M,F)=>{!M||F.character.id==="UNKNOWN"||(v(F),Pe(G=>G.map(te=>te.sessionId===M?{...te,presentation:F,metadataMissing:!1,label:F.title}:te)))},[]),O=l.useCallback(async M=>{var ie,Ie;const F=(ie=le.current)==null?void 0:ie.id;if(!F||((Ie=le.current)==null?void 0:Ie.id)!==F)return;
219const G=se.current,te=new AbortController;try{if(M.offline){if(!await n.clearSession({ownerId:F,sessionId:M.sessionId}))throw new Error(t==="zh"?"研究会话本机缓存删除失败,无法保证重启后不会恢复。":"The local research cache could not be deleted; it cannot be guaranteed not to return after restart.")}else if(await a.deleteSession({ownerId:F,sessionId:M.sessionId,epoch:G,signal:te.signal}),!await n.tombstone({ownerId:F,sessionId:M.sessionId},M.revision+1))throw new Error(t==="zh"?"研究会话已删除,但本机缓存删除失败,无法保证重启后不会恢复。":"The research session was deleted, but its local cache could not be deleted and may return after restart.");G===se.current&&await Me()}catch(ve){G===se.current&&be(ve instanceof Error?ve.message:"研究会话删除失败。")}},[a,t,Me,n]),k=l.useCallback(async({text:M,documentFiles:F,presentation:G})=>{var Ye,at;const te=(Ye=le.current)==null?void 0:Ye.id;if(!te){await ke(t==="zh"?"请先登录后使用研究室。":"Please sign in before using Research Room.",{variant:"info"}),i(D.LOGIN);return}const ie=M.trim();if(F.length>0&&ie){await ke(t==="zh"?"请只提交文字或文档文件之一。":"Submit text or document files, not both.",{variant:"warning"});return}if(!F.length&&!ie){await ke(t==="zh"?"请先提交研究材料。":"Please provide research material first.",{variant:"warning"});return}(at=me.current)==null||at.abort(),se.current+=1;const Ie=new AbortController;me.current=Ie;const ve=se.current,it=G==null?null:JSON.parse(JSON.stringify(G));b(it),v(it),c(null),ee(null),Y(!1),K(!1),fe(!1),d(null),Oe.current=null,U.current=!1,z.current=!1,$(!0),i(D.RESEARCH_ROOM);try{const ot=`research-prepare-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`;B.current=ot;let Ve=await a.prepare({...he(te,Ie.signal),operationId:ot,text:ie||void 0,files:F,...G!==void 0?{presentation:G}:{}});if(U.current){Oe.current=Ve,d(Ve);const Ct=new AbortController;await a.cancelPreparation({...he(te,Ct.signal),taskId:Ve.taskId}),d(null),b(null),v(null),Oe.current=null,B.current=null,U.current=!1,$(!1),Y(!1),K(!1),fe(!1),z.current=!1,i(D.MENU);return}if(ve!==se.current||Ie.signal.aborted)return;for(d(Ve),Oe.current=Ve,Ve.presentation&&(b(Ve.presentation),v(Ve.presentation)),K(!1);Ve.state==="preparing";){if(await new Promise((Ct,ei)=>{const Bt=window.setTimeout(Ct,Math.max(250,Math.min(5e3,Ve.pollAfterMs??1e3)));Ie.signal.addEventListener("abort",()=>{window.clearTimeout(Bt),ei(new DOMException("The operation was aborted.","AbortError"))},{once:!0})}),ve!==se.current||Ie.signal.aborted||(Ve=await a.pollPreparation({...he(te,Ie.signal),taskId:Ve.taskId}),ve!==se.current||Ie.signal.aborted))return;d(Ve),Oe.current=Ve,K(!1)}if(Ve.state!=="ready"||!Ve.sessionId)throw new Error(Ve.terminalCode||(t==="zh"?"研究材料准备失败。":"Research preparation failed."));d(null),Oe.current=null,B.current=null,$(!1),Y(!1),K(!1),c({ownerId:te,sessionId:Ve.sessionId,epoch:ve}),v(Ve.presentation??it)}catch(ot){if(Ie.signal.aborted||ve!==se.current)return;if(U.current&&Oe.current){ee(ot instanceof Error?ot.message:"取消研究准备失败。"),Y(!1),K(!0),$(!0),fe(!1),z.current=!1;return}if(U.current){d(null),b(null),v(null),Oe.current=null,B.current=null,U.current=!1,$(!1),Y(!1),K(!1),fe(!1),z.current=!1,i(D.MENU);return}const Ve=!!Oe.current,Ct=ot instanceof ae&&ot.code==="RESEARCH_NETWORK_ERROR";B.current=null,ee(ot instanceof Error?ot.message:t==="zh"?"研究材料准备失败。":"Research preparation failed."),Y(!Ve||!Ct),K(Ve&&Ct),$(Ve&&Ct)}finally{me.current===Ie&&(me.current=null)}},[a,t,i,he]),A=l.useCallback(async()=>{var ie,Ie;const M=Oe.current??f,F=(ie=le.current)==null?void 0:ie.id;if(!F||z.current)return;if(!M){U.current=!0,z.current=!0,d(null),$(!0),Y(!1),K(!1),ee(null),fe(!0),B.current=null;return}z.current=!0,(Ie=me.current)==null||Ie.abort();const G=new AbortController;me.current=G;const te=++se.current;fe(!0);try{if(await a.cancelPreparation({...he(F,G.signal),taskId:M.taskId}),te!==se.current||G.signal.aborted)return;d(null),b(null),v(null),Oe.current=null,B.current=null,U.current=!1,$(!1),Y(!1),K(!1),i(D.MENU)}catch(ve){!G.signal.aborted&&te===se.current&&ee(ve instanceof Error?ve.message:"取消研究准备å¤
219±è´¥ã€‚")}finally{z.current=!1,te===se.current&&fe(!1),me.current===G&&(me.current=null)}},[a,i,f,he,ue]);l.useEffect(()=>{if(r===D.RESEARCH_ROOM&&!(e!=null&&e.id)){i(D.LOGIN,"replace");return}r===D.RESEARCH_ROOM&&(e!=null&&e.id)&&!o&&!j&&!V&&!Se&&i(D.MENU,"replace")},[r,o,i,j,Se,V,e==null?void 0:e.id]);const N=l.useCallback(()=>{var M,F;if(V){(M=me.current)==null||M.abort(),me.current=null,se.current+=1,d(null),b(null),v(null),Oe.current=null,B.current=null,U.current=!1,$(!1),Y(!1),K(!1),ee(null),fe(!1),i(D.MENU);return}if(j){A();return}(F=me.current)==null||F.abort(),me.current=null,se.current+=1,c(null),v(null),b(null),i(D.MENU)},[A,i,j,V]);return l.useEffect(()=>()=>{var M;(M=me.current)==null||M.abort(),a.logout()},[a]),{identity:o,preparation:f,preparationPresentation:S,activePresentation:w,preparationActive:j,preparationTerminal:V,preparationUncertain:q,preparationError:Se,preparationCancelling:Z,sessions:ne,sessionsLoading:Ee,sessionsError:_e,resetMemory:ue,loadSessions:Me,loadSession:_,deleteSession:O,updateSessionMetadata:m,resolveSessionPresentation:P,startResearch:k,cancelPreparation:A,exitRoom:N}}const sA=(e,t)=>({fullText:t.length>0?"":e,files:t.map(r=>({name:r.name}))}),iA=()=>new Promise(e=>{if(typeof window>"u"||typeof window.requestAnimationFrame!="function"){setTimeout(e,0);return}window.requestAnimationFrame(()=>{window.requestAnimationFrame(()=>e())})}),oA=e=>e==="sakura"||e==="gothic"||e==="fullwidth",cA={floral:{image:"/assets/ui/dialogue/floral-control-button.png",slice:"30 42 30 42 fill",borderWidth:"8px",mobileBorderWidth:"5px",className:"text-[#7a4b2f] hover:text-[#a7653a]"},sakura:{image:"/assets/ui/dialogue/sakura-control-button.png",slice:"34 46 32 52 fill",borderWidth:"8px",mobileBorderWidth:"5px",className:"text-[#8f5261] hover:text-[#c45f78]"},gothic:{image:"/assets/ui/dialogue/gothic-control-button.png",slice:"26 44 26 44 fill",borderWidth:"8px",mobileBorderWidth:"5px",className:"text-[#d9cbe3] hover:text-[#f4d8ff]"}},uA=(e,t)=>({borderImageSource:`url("${e.image}")`,borderImageSlice:e.slice,borderImageRepeat:"stretch",borderStyle:"solid",borderColor:"transparent",borderWidth:t?e.mobileBorderWidth:e.borderWidth,borderRadius:0,backgroundColor:"transparent",boxShadow:"none"}),lA=e=>["1","true","yes","on"].includes("".trim().toLowerCase()),Ki=lA(),_l=()=>{if(typeof window>"u")return"";const t=fn(window.location.pathname).match(/^\/share\/([^/?#]+)$/);if(t!=null&&t[1])return decodeURIComponent(t[1]);const r=new URLSearchParams(window.location.search);return r.get("save")||r.get("sharedSave")||""},dA=()=>typeof window>"u"?"":new URLSearchParams(window.location.search).get("openSave")||"",fA=(e,t)=>!!(e&&t)&&e.frameId===t.frameId&&e.speaker===t.speaker&&e.text===t.text,mA=()=>{var Gc,Yc,zc,Wc,$c,qc,Qc;const e=Io(),{chars:t,loading:r}=I0(),[a,n]=l.useState(D.MENU),[i,o]=l.useState(null),[c,f]=l.useState(0),[d,S]=l.useState(null),[b,w]=l.useState(ga),v=l.useRef(b),j=l.useRef(Promise.resolve(null)),$=u=>{v.current=u,w(u)},[V,Y]=l.useState(null),[q,K]=l.useState(null),[Se,ee]=l.useState(!1),[Z,fe]=l.useState(()=>{const u=localStorage.getItem("p2g_characterId");return u!=null&&u.trim()?u.trim():"RUKA"}),[ne,Pe]=l.useState(()=>{try{const u=localStorage.getItem("p2g_default_character_skins");return u?JSON.parse(u):{}}catch{return{}}}),[Ee,ye]=l.useState(null),[_e,be]=l.useState(null),[se,me]=l.useState(null),[Oe,B]=l.useState(null),[U,z]=l.useState(null),[re,le]=l.useState([]),ue=l.useRef(0),[he,Me]=l.useState(""),[_,m]=l.useState(null),[P,O]=l.useState(!1),[,k]=l.useState(!1),[A,N]=l.useState(null),M=_a.useRef(!1),[F,G]=l.useState(!1),[te,ie]=l.useState(!1),[Ie,ve]=l.useState(null),[it,Ye]=l.useState(!1),[at,ot]=l.useState(void 0),[Ve,Ct]=l.useState(null),[ei,Bt]=l.useState(0),Ft=l.useRef(!1),xt=l.useRef(!1),ze=l.useRef([]),pr=l.useRef(new Set),Ot=l.useRef(!1),bt=l.useRef(null),Je=l.useRef(0),sa=l.useRef(null),sr=l.useRef(null);l.useRef(new Map);const va=l.useRef(null),qt=l.useRef(null),Mn=l.useRef(""),[Un,La]=l.useState(null),[Tf,Bn]=l.useState(null),[Xo,Jo]=l.useState(!1),[Zo,gA]=l.useState(!1),[Sf,Tt]=l.useState(!1),[EA,ec]=l.useState(!1),[Af,Fn]=l.useState(null),[If,ti]=l.useState(!1),[Hn,Fr]=l.useState([]),[tc,Hr]=l.useState([]),jr=Hn[Hn.length-1]||null,[rc,ri]=l.useState(""),[ai,yf]=l.useState("browser"),[_f,Cf]=l.useState(()=>Xi()==="native-app"),[wf,ac]=l.useState(!1),[Rf,nc]=l.useState(!1),[sc,ic]=l.useState(null),Nf=()=>{window.dispatchEvent(new CustomEvent("p2g-open-steam-wishlist-modal"))},[W,Pf]=l.useState(()=>{const u=localStorage.getItem("p2g_language");if(u&&(u==="en"||u==="zh"||u==="ja"||u==="ru"))return u;try{const E=navigator.language.toLowerCase();return E.startsWith("zh")?"zh":E.startsWith("ja")?"ja":E.startsWith("ru")?"ru":"en"}catch{return"en"}});l.useEffect(()=>{const u=Xi();yf(u),u!=="browser"&&ac(!1)},[]),l.useEffect(()=>{let u=!0;return eg().then(E=>{u&&E&&ic(E)}),()=>{u=!1}},[]);const[Te,ia]=l.useState(()=>{try{const u=localStorage.getItem("p2g_user");return u?JSON.parse(u):null}catch{return null}}),St=HE(Te==null?void 0:Te.id),[xf,oc]=l.useState({version:1,entries:[]}),[oa,ka]=l.useState("ready"),[Of,vf]=l.useState("owner"),Vr=l.useRef(null),ca=l.useRef("owner"),ct=l.useRef((Te==null?void 0:Te.id)||null),Da=l.useRef(0),ir=l.useRef(0),Ma=l.useRef(new Set);ct.current=(Te==null?void 0:Te.id)||null;const Gr=(u,E="owner",I=ct.current)=>{Vr.current=u,ca.current=E,S(u),vf(E)},cc=()=>{oc({version:1,entries:[]}
219),ka("ready"),Ma.current=new Set},Ua=(u,E=!0)=>{Da.current+=1,ir.current+=1,St.invalidateSession(u),cc(),E&&Gr(null,"owner",null)},Lf=()=>{Da.current+=1,ir.current+=1,St.invalidateRequest(),Fr([]),Hr([])},ni=u=>{Da.current+=1,ir.current+=1,St.beginSession(u),cc(),Fr([]),Hr([]),Gr(null,"owner",null)},si=l.useMemo(()=>tA(),[]),uc=l.useMemo(()=>D1({tokenReader:()=>localStorage.getItem("p2g_token"),offlineStore:si}),[si]),Ue=l.useCallback((u,E="push")=>{if(n(u),E==="none")return;const I=fp[u];!I||fn(window.location.pathname)===I&&E==="push"||(E==="replace"?window.history.replaceState({},"",I):window.history.pushState({},"",I))},[]),lc=nA({user:Te,language:W,appState:a,gateway:uc,offlineStore:si,navigate:Ue}),{identity:gr,preparation:kf,preparationActive:Df,preparationTerminal:Mf,preparationUncertain:Uf,preparationError:Bf,preparationCancelling:Ff,sessions:jn,sessionsLoading:Hf,sessionsError:jf,resetMemory:Vf,loadSessions:Gf,loadSession:dc,deleteSession:Yf,startResearch:fc,exitRoom:mc,activePresentation:ua,resolveSessionPresentation:zf}=lc,Ht=()=>{Ua("logout"),Vf(),localStorage.removeItem("p2g_token"),localStorage.removeItem("p2g_user"),ia(null)},Wf=u=>{ct.current=(u==null?void 0:u.id)||null,ni((u==null?void 0:u.id)||null),ia(u),localStorage.setItem("p2g_user",JSON.stringify(u)),Ue(D.MENU,"replace")},hc=u=>{(u==null?void 0:u.id)!==ct.current&&(ct.current=(u==null?void 0:u.id)||null,ni((u==null?void 0:u.id)||null)),ia(u),localStorage.setItem("p2g_user",JSON.stringify(u))},$f=(u,E)=>{const I=(u||"").trim();if(!I||I.length<=E)return I;const y=Math.floor(E*.6),C=Math.max(0,E-y-18);return`${I.slice(0,y)}
220
221[中间内容已截断]
222
223${I.slice(-C)}`},ii=(u,E)=>{const I=t.find(y=>y.id===String(u||"").toUpperCase());return I?{kind:"default",id:I.id}:E!=null&&E.dbId?{kind:"cloud",dbId:E.dbId}:E?{kind:"local",name:E.name,...E.prompt?{guide:E.prompt}:{},...E.performanceProfile?{performanceProfile:E.performanceProfile}:{}}:{kind:"local",name:(jt==null?void 0:jt.name)||(pe==null?void 0:pe.speaker)||String(u||"Character")}},pc=()=>{var E;const u=We.find(I=>I.id===Z);return((E=i==null?void 0:i.characterReference)==null?void 0:E.kind)==="local"&&u&&!u.dbId?ii(Z,u):(i==null?void 0:i.characterReference)||ii(Z,u)},qf=()=>{if(!i||!pe)return"";const u=Array.from(new Set([...vt,pe.id])).map(I=>i.frames.find(y=>y.id===I)).filter(I=>!!I).slice(-10).map(I=>{const y=I.blackboard?`
224板书:${I.blackboard}`:"";return`${I.speaker||"旁白"}:${I.text}${y}`}).join(`
225
226`),E=pe.choices&&pe.choices.length>0?`
227当前可选项:
228${pe.choices.map((I,y)=>`${y+1}. ${I.text}`).join(`
229`)}`:"";return[`标题:${i.title||"未命名剧情"}`,`摘要:${i.summary||"暂无摘要"}`,`当前背景:${(Ee==null?void 0:Ee.name)||pe.background||"未指定"}`,`当前帧角色:${pe.speaker||"旁白"}`,`最近剧情:
230${u||"暂无"}`,E?E.trim():""].filter(Boolean).join(`
231
232`)},gc=l.useRef(!1);l.useEffect(()=>()=>{var u;(u=sr.current)==null||u.abort()},[]);const[Qf,Ec]=l.useState(!1);l.useEffect(()=>{K0(),J0();try{window.self!==window.top&&Ec(!0)}catch{Ec(!0)}const u=new URLSearchParams(window.location.search),E=fn(window.location.pathname);if(u.get("page")==="admin")n(D.ADMIN);else if(E==="/terms")$r(W==="zh"?"/docs/Terms_Of_Service_CN.md":"/docs/Terms_Of_Service_EN.md",He[W].termsOfService||"Terms of Service","none");else if(E==="/privacy")$r(W==="zh"?"/docs/Privacy_Policy_CN.md":"/docs/Privacy_Policy_EN.md",He[W].privacyPolicy||"Privacy Policy","none");else if(u.get("page")==="terms")$r(W==="zh"?"/docs/Terms_Of_Service_CN.md":"/docs/Terms_Of_Service_EN.md",He[W].termsOfService||"Terms of Service","replace");else if(u.get("page")==="privacy")$r(W==="zh"?"/docs/Privacy_Policy_CN.md":"/docs/Privacy_Policy_EN.md",He[W].privacyPolicy||"Privacy Policy","replace");else{const x=Au(E);x&&n(x)}const I=u.get("code"),y=u.get("error"),C=u.get("state")||"";if(I)(async()=>{const H=`${C}:${I}`,J=sessionStorage.getItem("p2g_oauth_callback_key");if(gc.current||J===H)return;gc.current=!0,sessionStorage.setItem("p2g_oauth_callback_key",H),(()=>{const de=new URLSearchParams(window.location.search);de.delete("code"),de.delete("state");const we=window.location.pathname+(de.toString()?`?${de.toString()}`:"");window.history.replaceState({},"",we)}
232)();const Re=C.startsWith("watcha_")?"watcha":"discord",Ae=Re==="watcha"?"/api/auth/watcha":"/api/auth/discord",ce=Re==="watcha"?"Watcha OAuth failed":"Discord OAuth failed";try{const de=localStorage.getItem("p2g_token"),we={"Content-Type":"application/json"};de&&(we.Authorization=`Bearer ${de}`);const je=await fetch(Ae,{method:"POST",headers:we,body:JSON.stringify(Z0({code:I,state:C}))}),Ze=await je.json();if(!je.ok)throw new Error(Ze.error||ce);if(Ze.token){localStorage.setItem("p2g_token",Ze.token),localStorage.setItem("p2g_user",JSON.stringify(Ze.user)),ia(Ze.user);const nt=He[W];await ke(nt.updateSuccess||"Success",{variant:"success"})}}catch(de){console.error("OAuth Error:",de),await ke(de.message||ce,{variant:"error"})}})();else if(y){ke(y||"OAuth canceled",{variant:"error"});const x=new URLSearchParams(window.location.search);x.delete("error"),x.delete("error_description");const H=window.location.pathname+(x.toString()?`?${x.toString()}`:"");window.history.replaceState({},"",H)}},[]),l.useEffect(()=>{const u=()=>{const E=new URLSearchParams(window.location.search),I=fn(window.location.pathname);if(E.get("page")==="admin"){n(D.ADMIN);return}if(I==="/terms"){$r(W==="zh"?"/docs/Terms_Of_Service_CN.md":"/docs/Terms_Of_Service_EN.md",He[W].termsOfService||"Terms of Service","none");return}if(I==="/privacy"){$r(W==="zh"?"/docs/Privacy_Policy_CN.md":"/docs/Privacy_Policy_EN.md",He[W].privacyPolicy||"Privacy Policy","none");return}const y=Au(I);y&&n(y)};return window.addEventListener("popstate",u),()=>window.removeEventListener("popstate",u)},[W]),h0({setExtensionAutoStart:O,setExtensionBlackboard:k,setExtensionFile:m});const Ba=_a.useRef(!1);l.useEffect(()=>{if(!(Ba.current||!Te))try{const u=new URLSearchParams(window.location.search),E=u.get("p2g_doc_url");if(!E)return;Ba.current=!0;const I=u.get("p2g_doc_name")||"document.pdf",y=u.get("p2g_doc_type")||"pdf",C=u.get("p2g_auto_start")==="1",x=localStorage.getItem("p2g_token");if(!x){Ba.current=!1;return}fetch("/api/document-from-url",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${x}`},body:JSON.stringify({url:E,name:I})}).then(async H=>{const J=new URL(window.location.href);if(J.searchParams.delete("p2g_doc_url"),J.searchParams.delete("p2g_doc_name"),J.searchParams.delete("p2g_doc_type"),J.searchParams.delete("p2g_auto_start"),J.searchParams.delete("p2g_blackboard"),window.history.replaceState({},"",J.pathname+(J.search||"")+(J.hash||"")),!H.ok){const ce=await H.json().catch(()=>({}));throw new Error(ce.error||`获取失败: ${H.status}`)}const oe=await H.blob(),Re=H.headers.get("Content-Type")||(y==="pdf"?"application/pdf":"application/vnd.openxmlformats-officedocument.wordprocessingml.document"),Ae=new File([oe],I,{type:Re});O(C),m(Ae)}).catch(H=>{console.error("document-from-url failed",H),Ba.current=!1})}catch{Ba.current=!1}},[Te]);const Kf=()=>{try{window.top?window.top.location.href="https://paper2gal.com":window.location.href="https://paper2gal.com"}catch{window.location.href="https://paper2gal.com"}},[We,Vn]=l.useState([]),[bc,Gn]=l.useState(!1);l.useEffect(()=>{localStorage.removeItem("p2g_custom_chars")},[]),l.useEffect(()=>{let u=!1;if(Gn(!1),Te){const E=localStorage.getItem("p2g_token");E?st("/api/user/characters",{headers:{Authorization:`Bearer ${E}`}}).then(I=>{if(I.status===401)throw Ht(),new Error("Unauthorized");return I.json()}).then(I=>{if(!u&&Array.isArray(I)){const y=x=>{if(Array.isArray(x))return x.filter(H=>typeof H=="string"&&H);if(typeof x=="string"&&x.trim())try{const H=JSON.parse(x);return Array.isArray(H)?H.filter(J=>typeof J=="string"&&J):[]}catch{return[]}return[]},C=I.map(x=>({dbId:x.id,id:x.characterId,name:x.name,prompt:x.prompt,performanceProfile:x.performanceProfile??void 0,avatarUrl:x.avatarUrl,renderMode:x.renderMode,live2d:x.live2d,cgImages:y(x.cgImages),isShared:x.isShared,isBorrowed:x.isBorrowed,borrowId:x.borrowId,borrowCount:x.borrowCount,communityStatus:x.communityStatus,voiceRefAudioUrl:x.voiceRefAudioUrl??void 0,voiceRefText:x.voiceRefText??void 0,synthesisVersion:x.synthesisVersion??void 0,layout:x.layout??void 0,expressions:hu(x)}
232));Vn(x=>{const H=[...C];return x.forEach(J=>{H.some(oe=>oe.id===J.id)||H.push(J)}),H})}}).catch(I=>{!u&&I.message!=="Unauthorized"&&console.error("Failed to fetch custom characters",I)}).finally(()=>{u||Gn(!0)}):(Gn(!0),Ht())}else Vn([]),Gn(!0);return()=>{u=!0}},[Te]),l.useEffect(()=>{if(!bc||r)return;const u=tp(String(Z||""),t.map(E=>E.id),We.map(E=>E.id));u!==Z&&fe(u)},[Z,We,bc,t,r]);const[Qt,Yr]=l.useState(!1),[Kt,oi]=l.useState(!1),or=l.useRef(null),[Er,Xf]=l.useState(!1),[Tc,Jf]=l.useState({audio:null,emotion:lt.NEUTRAL}),[zr,Zf]=l.useState(()=>{const u=localStorage.getItem("p2g_bgmVolume");if(u!=null)return parseFloat(u);const E=localStorage.getItem("p2g_volume");return E?parseFloat(E):.3}),[la,em]=l.useState(()=>{const u=localStorage.getItem("p2g_voiceVolume");if(u!=null)return parseFloat(u);const E=localStorage.getItem("p2g_volume");return E?parseFloat(E):.9}),ci=l.useRef(null),Fa=l.useRef(null),Ha=l.useRef(null),ui=l.useRef(new Map),li=l.useRef(new Set),[ja,tm]=l.useState(()=>{var u;return typeof navigator<"u"&&((u=navigator.userActivation)==null?void 0:u.hasBeenActive)===!0}),[di]=l.useState(()=>Iu[Math.floor(Math.random()*Iu.length)]),[br,rm]=l.useState(()=>{const u=localStorage.getItem("p2g_bgmUrl");return up(u)}),[Yn,fi]=l.useState([]),Sc=l.useRef(!1),mi=a===D.LOADING||a===D.PLAYING||a===D.FINISHED||a===D.ERROR;l.useEffect(()=>{(async()=>{try{const E=await xi.loadBgms();if(E&&E.length>0)fi(E);else{const I=localStorage.getItem("p2g_customBgms");if(I){const y=JSON.parse(I);fi(y),xi.saveBgms(y),localStorage.removeItem("p2g_customBgms")}}}catch(E){console.error("Failed to load custom BGMs from DB",E)}})()},[]),l.useEffect(()=>{a===D.MENU&&(Sc.current||(Sc.current=!0,R0({imageUrls:op},{delayMs:500})))},[a,br]),l.useEffect(()=>{if(ja)return;const u=()=>tm(!0);return window.addEventListener("pointerdown",u,{once:!0}),window.addEventListener("keydown",u,{once:!0}),()=>{window.removeEventListener("pointerdown",u),window.removeEventListener("keydown",u)}},[ja]);const am=u=>{if(!u.startsWith("/assets/"))return Promise.resolve(u);const E=ui.current.get(u);if(E)return E;const I=fetch(u,{cache:"force-cache"}).then(y=>{if(!y.ok)throw new Error(`BGM load failed: ${y.status}`);return y.blob()}).then(y=>{const C=URL.createObjectURL(y);return li.current.add(C),C}).catch(()=>u);return ui.current.set(u,I),I},[jt,Va]=l.useState(null),hi=t.find(u=>u.id===String(Z||"").toUpperCase())?ne[String(Z||"").toUpperCase()]:null,pi=u=>{var x,H;const E=t.find(J=>J.id===String(u||"").toUpperCase());if(!E)return null;const I=ne[E.id],y=pa(E,I),C=E.name||((x=E.names)==null?void 0:x[W])||((H=He[W])==null?void 0:H[E.nameKey])||E.id;return{name:String(C||E.id),avatarUrl:(y==null?void 0:y.avatarUrl)||E.avatarUrl,renderMode:E.renderMode,live2d:vi(E,!0),expressions:(y==null?void 0:y.expressions)||E.expressions,cgImages:(y==null?void 0:y.cgImages)||E.cgImages||[],defaultSkinId:I||null}},[zn,Wn]=l.useState(!1),[$n,nm]=l.useState(()=>{const u=localStorage.getItem("p2g_textSpeed");return u?parseInt(u):30}),[qn,sm]=l.useState(()=>{const u=localStorage.getItem("p2g_dialogueFontScale"),E=u?parseFloat(u):1;return Number.isFinite(E)?Math.min(1.4,Math.max(.8,E)):1}),[Ga,im]=l.useState(()=>{const u=localStorage.getItem("p2g_gameUiPreset");return u==="floral"||u==="sakura"||u==="gothic"||u==="fullwidth"?u:"classic"}),[Ac,Qn]=l.useState(Te?null:!1),[om,Ya]=l.useState(!!Te),gi=l.useRef(0),Ic=l.useRef({userId:void 0,showSettings:!1}),[Kn,cm]=l.useState(()=>{const u=localStorage.getItem("p2g_autoAdvanceDelayMs"),E=u?parseInt(u,10):2e3;return Number.isFinite(E)?Math.min(3e4,Math.max(2e3,E)):2e3}),[Xn,um]=l.useState(()=>localStorage.getItem("p2g_autoAdvanceByVoice")==="1"),[mt,lm]=l.useState(()=>localStorage.getItem("p2g_outputLanguage")||""),[Jn,dm]=l.useState(()=>localStorage.getItem("p2g_voiceLanguage")||"auto"),[wt,fm]=l.useState(()=>localStorage.getItem("p2g_narrativeStyle")==="lighthearted"?"lighthearted":"classic"),[ht,yc]=l.useState(()=>localStorage.getItem("p2g_playerNickname")||""),[Zn,mm]=l.useState(()=>OE()),hm=l.useCallback(async({text:u,documentFiles:E})=>{var C;if(!Te){await ke(He[W].loginRequired||"请先登录后使用研究室。",{variant:"info"}),n(D.LOGIN);return}if(!u.trim()&&E.length===0)return;const I=t.find(x=>x.id===String(Z||"").toUpperCase()),y=We.find(x=>x.id===Z);me({text:u,documentFiles:E,characterId:Z,skinId:((C=pa(I,I?ne[I.id]:null))==null?void 0:C.id)||"base",outputLanguage:sn(mt,W),narrativeStyle:wt,playerAddress:ht.trim()||null}),z(!I&&!y?W==="zh"?"当前角色视觉暂不可用,将使用安全占位图。":"The selected character visual is unavailable; a safe placeholder will be used.":null),B(null),Me(""),n(D.BACKGROUND_SELECT)},[Z,We,t,W,wt,mt,ht,ne,Te]),pm=l.useCallback(()=>{ue.current+=1,B(null),z(null),ye(null),me(null),mc()},[mc]),gm=l.useCallback(async(u,E,I)=>{var Re,Ae;const y=se;if(!y)return;const C=t.find(ce=>ce.id===String(y.characterId||"").toUpperCase()),x=We.find(ce=>ce.id===y.characterId),H=C?{kind:"default",id:C.id,skinId:((Re=pa(C,y.skinId))==null?void 0:Re.id)||"base",name:C.name||((Ae=C.names)==null?void 0:Ae[W])||C.id,reference:{kind:"default",id:C.id}}
232:x!=null&&x.dbId?{kind:"cloud",id:x.dbId,skinId:"base",name:x.name,reference:{kind:"cloud",dbId:x.dbId}}:null;if(!H){await ke(W==="zh"?"当前角色无法用于研究室,请先选择可用角色。":"This character cannot be used in Research Room. Choose an available character first.",{variant:"warning"});return}const J=I||(()=>{const ce=Pr.find(de=>de.url===u);return ce?{kind:"preset",id:ce.id}:void 0})();if(!J){await ke(W==="zh"?"请选择有效的图片背景。":"Choose a valid image background.",{variant:"warning"});return}const oe=Qo(sA(y.text,y.documentFiles),{character:H,background:{kind:J.kind,id:J.id,name:E||"Background"},outputLanguage:y.outputLanguage,narrativeStyle:y.narrativeStyle,playerAddress:y.playerAddress});ye({url:u,name:E}),B(oe),z(null),me(null),await fc({text:y.text,documentFiles:y.documentFiles,presentation:oe})},[We,t,W,se,fc]),Em=l.useCallback(u=>{const E=jn.find(I=>I.sessionId===u);B((E==null?void 0:E.presentation)??null),z(null),ye(null),dc(u)},[dc,jn]),bm=l.useCallback(async()=>{var H,J;if(!await du(W==="zh"?"将把当前菜单角色与背景保存到此旧会话,并用于后续提问。是否继续?":"Save the current menu character and background to this legacy session for future questions?",{title:W==="zh"?"确认研究角色":"Confirm research persona",variant:"warning"}))return null;const E=t.find(oe=>oe.id===String(Z||"").toUpperCase()),I=We.find(oe=>oe.id===Z),y=E?{kind:"default",id:E.id,skinId:((H=pa(E,ne[E.id]))==null?void 0:H.id)||"base",name:E.name||((J=E.names)==null?void 0:J[W])||E.id,reference:{kind:"default",id:E.id}}:I!=null&&I.dbId?{kind:"cloud",id:I.dbId,skinId:"base",name:I.name,reference:{kind:"cloud",dbId:I.dbId}}:null,C=Ee&&Pr.find(oe=>oe.url===Ee.url),x=Ee&&re.find(oe=>oe.url===Ee.url);return!y||!Ee||!C&&!x?null:{character:y,background:C?{kind:"preset",id:C.id,name:C.name}:{kind:"custom",id:x.id,name:x.name||"Background"},outputLanguage:sn(mt,W),narrativeStyle:wt,playerAddress:ht.trim()||null}},[Z,We,t,W,wt,mt,ht,re,Ee,ne]),Tm=l.useCallback(u=>{const E=++ue.current;B(u);const I=u.character.kind==="default"?t.some(C=>C.id===u.character.id):We.some(C=>C.dbId===u.character.id||C.id===u.character.id);if(z(I?null:W==="zh"?"保存的研究角色已不可用,无法继续提问。":"The saved research character is unavailable; questions are disabled."),u.background.kind==="preset"){const C=Pr.find(x=>x.id===u.background.id);C?ye({url:C.url,name:C.name}):(ye({url:Vt[0],name:"Default"}),z(W==="zh"?"保存的研究背景已不可用,已使用安全背景。":"The saved research background is unavailable; a safe fallback is shown."));return}const y=re.find(C=>C.id===u.background.id);if(y){ye({url:y.url,name:y.name||u.background.name});return}st("/api/user/backgrounds",{headers:{Authorization:`Bearer ${localStorage.getItem("p2g_token")||""}`}}).then(C=>C.ok?C.json():[]).then(C=>{if(E!==ue.current)return;const x=Array.isArray(C)&&C.find(H=>(H==null?void 0:H.id)===u.background.id&&typeof(H==null?void 0:H.url)=="string");x?(le(H=>H.some(J=>J.id===x.id)?H:[...H,x]),ye({url:x.url,name:x.name||u.background.name})):(ye({url:Vt[0],name:"Default"}),z(W==="zh"?"保存的研究背景已不可用,已使用安全背景。":"The saved research background is unavailable; a safe fallback is shown."))}).catch(()=>{E===ue.current&&(ye({url:Vt[0],name:"Default"}),z(W==="zh"?"保存的研究背景暂时不可用,已使用安全背景。":"The saved research background is temporarily unavailable; a safe fallback is shown."))})},[We,t,W,re]);l.useEffect(()=>{localStorage.setItem("p2g_bgmVolume",zr.toString())},[zr]),l.useEffect(()=>{localStorage.setItem("p2g_voiceVolume",la.toString())},[la]),l.useEffect(()=>{localStorage.setItem("p2g_textSpeed",$n.toString())},[$n]),l.useEffect(()=>{localStorage.setItem("p2g_dialogueFontScale",qn.toString())},[qn]),l.useEffect(()=>{localStorage.setItem("p2g_gameUiPreset",Ga)},[Ga]),l.useEffect(()=>{const u=(Te==null?void 0:Te.id)??null,E=Ic.current,I=E.userId!==u,y=zn&&!E.showSettings;if(Ic.current={userId:u,showSettings:zn},!I&&!y)return;const C=++gi.current;if(!Te){Qn(!1),Ya(!1);return}const x=localStorage.getItem("p2g_token");if(!x){Qn(!1),Ya(!1);return}I&&Qn(null),Ya(!0),st("/api/membership/status",{headers:{Authorization:`Bearer ${x}`}}).then(async H=>{if(H.status===401||H.status===403)return{membership:{active:!1}};if(!H.ok)throw new Error("membership status failed");return H.json()}).then(H=>{var J;C===gi.current&&(Qn(((J=H==null?void 0:H.membership)==null?void 0:J.active)===!0),Ya(!1))}).catch(()=>{C===gi.current&&Ya(!1)})},[zn,Te==null?void 0:Te.id]);const Tr=oA(Ga)&&Ac!==!0?"classic":Ga,es=cA[Tr],za=es?uA(es,e):void 0,Wa=Tr==="fullwidth"?`${e?"p-2":"p-2.5"} border-0 bg-transparent text-white/85 shadow-none transition-all hover:scale-110 hover:text-white`:es?`${e?"h-9 w-9":"h-12 w-12"} ${es.className} flex shrink-0 items-center justify-center border-solid border-transparent bg-transparent roun
232ded-none shadow-none transition-all hover:scale-[1.04] active:scale-95`:`${e?"min-h-11 min-w-11 p-2":"p-3"} bg-black/20 backdrop-blur-md border border-white/30 rounded-full text-white hover:bg-white hover:text-brand-blue shadow-lg transition-all`,da=e?17:20;l.useEffect(()=>{localStorage.setItem("p2g_autoAdvanceDelayMs",Kn.toString())},[Kn]),l.useEffect(()=>{localStorage.setItem("p2g_autoAdvanceByVoice",Xn?"1":"0")},[Xn]),l.useEffect(()=>{localStorage.setItem("p2g_default_character_skins",JSON.stringify(ne))},[ne]),l.useEffect(()=>{localStorage.setItem("p2g_characterId",String(Z))},[Z]),l.useEffect(()=>{localStorage.setItem("p2g_language",W)},[W]),l.useEffect(()=>{localStorage.setItem("p2g_outputLanguage",mt)},[mt]),l.useEffect(()=>{localStorage.setItem("p2g_voiceLanguage",Jn)},[Jn]),l.useEffect(()=>{vE(Zn)},[Zn]),l.useEffect(()=>{localStorage.setItem("p2g_narrativeStyle",wt)},[wt]),l.useEffect(()=>{br.length<1e3&&localStorage.setItem("p2g_bgmUrl",br)},[br]),l.useEffect(()=>{Yn.length>0&&xi.saveBgms(Yn).catch(u=>{console.error("Failed to persist custom BGMs",u)})},[Yn]),l.useEffect(()=>{if(localStorage.setItem("p2g_playerNickname",ht),Te&&typeof ht=="string"){const u=localStorage.getItem("p2g_token");u?st("/api/user/profile",{method:"PUT",headers:{"Content-Type":"application/json",Authorization:`Bearer ${u}`},body:JSON.stringify({playerNickname:ht})}).then(E=>{E.status===401&&Ht()}).catch(E=>console.error("Auto-sync nickname failed:",E)):Ht()}},[ht,Te==null?void 0:Te.id]);const[_c,ts]=l.useState(!1),[$a,Wr]=l.useState(!1),[Cc,qa]=l.useState([]),[Sm,Ei]=l.useState(0),[Am,bi]=l.useState(1),[Im,ym]=l.useState(()=>ku(window.innerWidth*.38,window.innerWidth));l.useEffect(()=>{const u=ct.current;if(!u||ca.current!=="owner"||!Vr.current||!i)return;const E=String(Je.current),I=i.frames[c];if(!I)return;const y={frameId:I.id,speaker:I.speaker,text:I.text},C=Vr.current;C&&St.assignSave({ownerId:u,saveId:C,generationId:E,anchor:y}).then(()=>St.snapshotReady({ownerId:u,saveId:C,generationId:E,anchor:y}))},[c,d,Of,i,St,Te==null?void 0:Te.id]);const[_m,Cm]=l.useState(""),[wm,Rm]=l.useState(""),$r=(u,E,I="push")=>{if(Cm(u),Rm(E),n(D.DOCS),I!=="none"){const y=u.toLowerCase().includes("terms")?"/terms":"/privacy";I==="replace"?window.history.replaceState({},"",y):window.history.pushState({},"",y)}},[Nm,rs]=l.useState(!1),[wc,Rc]=l.useState(!1),[Pm,xm]=l.useState(Zi);l.useEffect(()=>{if(_l().trim())return;let u=!1,E=null;return(async()=>{var x;let y=Zi;try{const H=await st("/api/announcements");if(H.ok){const J=await H.json().catch(()=>[]);Array.isArray(J)&&((x=J[0])!=null&&x.id)&&(y=String(J[0].id))}}catch(H){console.warn("Announcement check failed:",H)}if(u)return;xm(y),localStorage.getItem("p2g_last_seen_announcement")!==y&&(Rc(!0),E=setTimeout(()=>{u||rs(!0)},1500))})(),()=>{u=!0,E&&clearTimeout(E)}},[]);const Om=()=>{rs(!1),Rc(!1),localStorage.setItem("p2g_last_seen_announcement",Pm)},Sr=l.useRef(0),Ti=l.useRef(!1),Si=l.useRef(0),Nc=async u=>{if(u<=0||!Te)return;const E=localStorage.getItem("p2g_token");if(!E||Ti.current)return;const I=Math.max(0,u-Si.current);if(I>0){Si.current+=I;const y=(Te.totalPlayTime??0)+I;ia(x=>x?{...x,totalPlayTime:y}:null);const C=localStorage.getItem("p2g_user");if(C){const x=JSON.parse(C);x.totalPlayTime=y,localStorage.setItem("p2g_user",JSON.stringify(x))}}Ti.current=!0;try{const y=await fetch("/api/user/play-time",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${E}`},body:JSON.stringify({increment:u}),keepalive:!0});if(y.ok){const C=await y.json();Sr.current=0,Si.current=0,ia(H=>H?{...H,totalPlayTime:C.totalPlayTime}:null);const x=localStorage.getItem("p2g_user");if(x){const H=JSON.parse(x);H.totalPlayTime=C.totalPlayTime,localStorage.setItem("p2g_user",JSON.stringify(H))}}}catch(y){console.error("Failed to sync play time, keep optimistic value",y)}finally{Ti.current=!1}};l.useEffect(()=>{let u;return a===D.PLAYING?u=window.setInterval(()=>{document.visibilityState!=="visible"||!document.hasFocus()||(Sr.current+=1,Sr.current>=60&&Nc(Sr.current))},1e3):Sr.current>0&&Nc(Sr.current),()=>{u&&clearInterval(u)}},[a,Te]),l.useEffect(()=>{const u=()=>{var E,I;if((E=qt.current)==null||E.finish("page_closed"),qt.current=null,Mn.current="",(I=va.current)==null||I.flush(!0),Sr.current>0&&Te){const y=localStorage.getItem("p2g_token");y&&fetch("/api/user/play-time",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${y}`},body:JSON.stringify({increment:Sr.current}),keepalive:!0})}};return window.addEventListener("beforeunload",u),()=>window.removeEventListener("beforeunload",u)},[Te]);const Vt=["/assets/local/backgrounds/default-scene.png"];l.useEffect(()=>{const u=y=>{const C=new Audio;return C.loop=!0,C.volume=zr,C.preload="none",C.dataset.sourceUrl=y,C},E=u(di),I=u(br);return Fa.current=E,Ha.current=I,ci.current=E,()=>{E.pause(),I.pause(),Fa.current=null,Ha.current=null,ci.current=null,li.current.forEach(y=>URL.revokeObjectURL(y)),li.current.clear(),ui.current.clear()}},[]),l.useEffect(()=>{Fa.current&&(Fa.current.volume=zr),Ha.current&&(Ha.current.volume=zr)},[zr]),l.useEffect(()=>{const u=Fa.current,E=Ha.current;if(!u||!E)return;let I=!1;const y=async(H,J)=>{H.dataset.sourceUrl=J;const oe=await am(J);I||H.dataset.sourceUrl!==J||(H.src!==oe&&(H.src=oe),W0(H,()=>{}))},C=ja&&a===D.MENU&&!Er,x=ja&&mi&&!Er;return ci.current=mi?E:u,C?y(u,di):u.pause(),x?y(E,br):E.pause(),()=>{I=!0}},[a,Er,mi,br,ja,di]);const Ai={[ha.LIBRARY]:"/assets/local/backgrounds/5.jpg",[ha.CLASSROOM]:"/assets/local/backgrounds/7.jpg",[ha.LAB]:"/assets/local/backgrounds/default-scene.png",[ha.ROOFTOP]:"/assets/local/backgrounds/2.jpg",[ha.CAFE]:"/assets/local/backgrounds/3.jpg",[ha.ABSTRACT]:"/assets/local/backgrounds/4.jpg"},Pc=u=>{let E=[];const I=t.find(C=>C.id===u);if(I){const C=pa(I,ne[I.id]);E=[C==null?void 0:C.avatarUrl,...Object.values((C==null?void 0:C.expressions)||{}
232),...(C==null?void 0:C.cgImages)||[]].filter(Boolean)}else{const C=We.find(x=>x.id===u);C&&(E=[C.avatarUrl,...Object.values(C.expressions||{})].filter(Boolean))}[...Vt,...E].forEach(C=>{const x=new Image;x.src=C})},vm=u=>{const y=ce=>(ce||"").replace(/\s+\n/g,`
233`).trim(),C=y(u);if(!C)return[];let x=C.split(/\n{2,}/g).map(ce=>y(ce)).filter(Boolean);x.length<=1&&(x=C.split(/\n+/g).map(ce=>y(ce)).filter(Boolean));const H=[];let J=[],oe=0;const Re=()=>{const ce=y(J.join(`
234
235`));ce&&H.push(ce),J=[],oe=0},Ae=ce=>{const de=y(ce);if(de){if(de.length>4500*1.6){oe>0&&Re();for(let we=0;we<de.length;we+=4500){const je=y(de.slice(we,we+4500));je&&H.push(je)}return}if(oe===0){J=[de],oe=de.length;return}if(oe+2+de.length<=4500){J.push(de),oe+=2+de.length;return}if(oe>=3e3){Re(),J=[de],oe=de.length;return}Re(),J=[de],oe=de.length}};for(const ce of x)Ae(ce);if(oe>0&&Re(),H.length>10){const ce=H.slice(0,9),de=H.slice(9).join(`
236
237`);return[...ce,y(de)].filter(Boolean)}return H},Lm=(u,E)=>{const I=u.frames.map(y=>{var H;const C=typeof y.nextFrameId=="number"?y.nextFrameId+E:void 0,x=(H=y.choices)==null?void 0:H.map(J=>({...J,nextFrameId:J.nextFrameId+E}));return{...y,id:y.id+E,...typeof C=="number"?{nextFrameId:C}:{},...x?{choices:x}:{}}});return{...u,frames:I}},km=(u,E)=>{var Re,Ae,ce;const I=E==="zh"?"旁白":E==="ja"?"ナレーター":E==="ru"?"рассказчик":"Narrator",y=((Ae=(Re=u[0])==null?void 0:Re.title)==null?void 0:Ae.trim())||(E==="zh"?"精读":"Intensive Reading"),C=u.map(de=>(de.summary||"").trim()).filter(Boolean).slice(0,6).join(" / ");let x=[],H=0,J=1;const oe=de=>de.reduce((we,je)=>Math.max(we,je.id),0);for(let de=0;de<u.length;de++){const we=Lm(u[de],H),je=oe(we.frames);if(de>0){const Ze=je+1+J;J++,x.push({id:Ze,speaker:I,text:E==="zh"?`进入下一小节(第 ${de+1}/${u.length} 章),我们把上一章结论接着往下推。`:E==="ja"?`次の小節(第 ${de+1}/${u.length} 章)へ進み、前章の内容を踏まえて続きを見ていきます。`:E==="ru"?`Переходим к следующему фрагменту (глава ${de+1}/${u.length}), продолжая мысль предыдущей части.`:`Moving to the next section (Chapter ${de+1}/${u.length}), continuing from the previous part.`,emotion:"NEUTRAL",background:((ce=we.frames[0])==null?void 0:ce.background)||"CLASSROOM"})}x=x.concat(we.frames),H=Math.max(oe(x),je),H=H+1e3}return{...u[0],title:E==="zh"?`精读:${y}`:`Intensive Reading: ${y}`,summary:C||(E==="zh"?"分段精读已合并为一章。":"Merged intensive reading into one chapter."),frames:x}},Dm=async(u,E,I,y,C,x,H,J,oe)=>{const Re=He[W];if(!Te){await ke(Re.loginRequired||"请先登录后使用该功能。",{variant:"info"}),n(D.LOGIN);return}Ua("new-generation"),Je.current+=1,Xh(),Fi({blackboard:!0}),M.current=!!y,Me(""),qa(Lu(J||[])),Ei(0),bi(1),Wr(!1);const Ae=!!C&&!x;typeof C=="boolean"?ie(Ae):x&&ie(!1);const ce=I!==!1;Ye(ce),Ki&&(sa.current={startedAtMs:Date.now(),voiceEnabled:Ae,intensiveReadingEnabled:!!x}),be({text:u,fingerprint:E,intensiveReadingEnabled:!!x,voiceEnabled:Ae,blackboardEnabled:ce,videoUrl:(H==null?void 0:H.trim())||void 0,documentFiles:J&&J.length>0?J:void 0,imageParsingEnabled:oe===!0,narrativeStyle:wt}),n(D.BACKGROUND_SELECT)};l.useEffect(()=>{if(a!==D.LOADING||Ve!=="script"||Un)return;const u=setInterval(()=>{Bt(E=>E>=98?E:Math.min(E+1,98))},1500);return()=>clearInterval(u)},[a,Ve,Un]),l.useEffect(()=>{if(!Xo||a!==D.LOADING)return;const u=E=>{E.preventDefault()};return window.addEventListener("beforeunload",u),()=>window.removeEventListener("beforeunload",u)},[a,Xo]),l.useEffect(()=>{if(Zo){const u=requestAnimationFrame(()=>ec(!0));return()=>cancelAnimationFrame(u)}else ec(!1)},[Zo]),l.useEffect(()=>{if(bt.current=i,!i)return;const u=new Set(i.frames.map(E=>E.id));i.frames.forEach(E=>pr.current.add(E.id)),ze.current=ze.current.filter(E=>!u.has(E.id))},[i]),l.useEffect(()=>{a!==D.PLAYING&&a!==D.FINISHED&&ve(null)},[a]),l.useEffect(()=>{a!==D.BACKGROUND_SELECT||!M.current||!_e||(M.current=!1,xc(Pr[0].url,Pr[0].name))},[a,_e]);const xc=async(u,E)=>{var Kc,Xc,Jc,Zc;if(!_e)return;const I=_e.blackboardEnabled!==!1;Ua("new-generation"),Je.current+=1;const{text:y,fingerprint:C,intensiveReadingEnabled:x,voiceEnabled:H,videoUrl:J,documentFiles:oe,imageParsingEnabled:Re,narrativeStyle:Ae="
237classic",entertainmentQuality:ce=Ae==="lighthearted"?"on":"off"}=_e,de=Array.isArray(oe)&&oe.length>0,we=!!H&&!x,je=!0,Ze=He[W];if(we){const Ce=t.find(xe=>xe.id===String(Z||"").toUpperCase()),qe=We.find(xe=>xe.id===Z);if(!(!!(Ce!=null&&Ce.voiceRefAudioUrl)||!!(qe!=null&&qe.voiceRefAudioUrl))){await ke(Ze.voiceModeCharNoVoiceHint||"当前角色不支持语音,请关闭语音模式或选择带语音的角色后再开始。",{variant:"info"});return}}ye({url:u,name:E}),Ki&&sa.current&&(sa.current.confirmedAtMs=Date.now()),n(D.LOADING),Ct("script"),Bt(0),Fi({blackboard:I}),Y(null),K(null),ee(!1),Bn(null),Ft.current=!1,xt.current=!1,ze.current=[],pr.current=new Set,Ot.current=!0,bt.current=null,La(null),o(null),f(0),Xt([]),$(ga()),Pc(Z);const nt=We.find(Ce=>Ce.id===Z),Jt=ii(Z,nt),os=Jt.kind==="local"?{kind:"local",name:Jt.name}:Jt,Qr=sn(mt,W),Ja=gg(Jn,Qr,W);let Ar=y;const Zt=(Ce,qe)=>{const Le=new Map;for(const xe of Ce)Le.set(xe.id,xe);for(const xe of qe){const lr=Le.get(xe.id);lr?Le.set(xe.id,{...lr,...xe}):Le.set(xe.id,xe)}return Array.from(Le.values())},Lt=(Ce,qe=[])=>{const Le=ze.current,xe=Zt(Ce.frames,[...Le,...qe]);return{...Ce,frames:xe}},Za=(Ce,qe)=>{if(!Ce||qe.length===0)return Ce;const Le=new Map;for(const yr of qe)Le.set(yr.frameId,yr);let xe=!1;const lr=Ce.frames.map(yr=>{const _r=Le.get(yr.id);return _r?(xe=!0,{...yr,voiceStatus:_r.voiceStatus,..._r.audioUrl?{audioUrl:_r.audioUrl}:{audioUrl:void 0}}):yr});return xe?{...Ce,frames:lr}:Ce},Ir=Ce=>{Ce.length===0||Je.current!==At||(ze.current=ze.current.map(qe=>{const Le=Ce.find(xe=>xe.frameId===qe.id);return Le?{...qe,voiceStatus:Le.voiceStatus,...Le.audioUrl?{audioUrl:Le.audioUrl}:{audioUrl:void 0}}:qe}),l.startTransition(()=>{o(qe=>{const Le=Za(qe,Ce);return Le&&(bt.current=Le),Le})}))};Je.current+=1;const At=Je.current;(Kc=sr.current)==null||Kc.abort(),sr.current=new AbortController,we&&(async()=>{try{const Ce=localStorage.getItem("p2g_token");if(!Ce)return;const qe=await st("/api/tts/queue-info",{headers:{Authorization:`Bearer ${Ce}`},cache:"no-store"});if(!qe.ok||Je.current!==At)return;const Le=await qe.json().catch(()=>null),xe=Ql(Le==null?void 0:Le.analysisVoice);xe&&Je.current===At&&Bn(lr=>lr??xe)}catch(Ce){console.warn("[voice-queue] failed to fetch initial queue info:",Ce)}})();try{Me(Ar);let Ce=null,qe=Promise.resolve();const Le=ge=>{const et=Ce;et&&(qe=qe.then(()=>Ii(ge,Z,et,{syncCurrentSaveId:!1,generationRunId:At})).catch(dr=>console.warn("[GenerationSave] Failed to persist incremental snapshot:",dr)))};let xe;const lr=ge=>{if(ge){if(La(ge),Bt(et=>np(ge,et)),we&&ge.textComplete===!0&&(Ot.current=!0,ze.current.length===0&&(xt.current=!1,Tt(!1))),typeof ge.voiceTotal=="number"&&ot({current:ge.voiceTerminal??0,total:ge.voiceTotal}),we&&(typeof ge.voiceQueueAhead=="number"||typeof ge.voiceQueueJobsAhead=="number")){const et=typeof ge.voiceQueueAhead=="number"?ge.voiceQueueAhead:ge.voiceQueueFramesAhead??ge.voiceQueueJobsAhead??0;Bn({queueAhead:Math.max(0,et),etaMinutes:Math.max(0,ge.voiceQueueEtaMinutes??et*ql),jobsAhead:typeof ge.voiceQueueJobsAhead=="number"?Math.max(0,ge.voiceQueueJobsAhead):void 0,framesAhead:typeof ge.voiceQueueFramesAhead=="number"?Math.max(0,ge.voiceQueueFramesAhead):void 0,state:ge.voiceQueueState,workerConcurrency:ge.voiceWorkerConcurrency})}ge.phase==="voice_wait"||we&&ge.textComplete===!0&&(ge.voicePending??0)>0?Ct("voice"):(ge.phase==="streaming"||ge.phase==="done")&&Ct("script")}};if(x&&!de){const ge=vm(Ar);if(ge.length===0)throw new Error(W==="zh"?"精读模式:未能从文档中切分出有效段落。":"Intensive reading: failed to split document into sections.");const et=[];let dr="";Fn({current:0,total:ge.length});for(let pt=0;pt<ge.length;pt++){Fn({current:pt,total:ge.length}),Bt(Math.min(98,Math.floor(pt/ge.length*98)));const en=["[[P2G_INTENSIVE_READING_MODE]]",`SECTION_INDEX: ${pt+1}`,`SECTION_TOTAL: ${ge.length}`,pt===0?"CONTINUITY: This is the first section.":`CONTINUITY: This is a direct continuation. Previous section summary (for context, do NOT re-introduce the story):
238${dr||"(empty)"}`,"","INSTRUCTIONS (CRITICAL):","- This is an intensive, chapter-by-chapter explanation.",'- For section 2+, DO NOT restart with a fresh intro like "今天我们来..." or self-introduction. Start as if we are already in the middle of the lesson.',"- Keep the same speaking style and continue smoothly from the previous section.","- If you need a recap, limit it to 1-2 short frames max, then immediately continue into the new content.","- Focus on details: assumptions, notation, derivations, and concrete examples.",""].join(`
239`),tn=await Jh(`${en}${ge[pt]}`,Z,W,C,nt,Qr,Ja,E,je,ht,t,I,(Xc=sr.current)==null?void 0:Xc.signal,Ae,ce),tt=await an(tn);et.push(tt),dr=(tt.summary||"").trim(),Fn({current:pt+1,total:ge.length})}xe=km(et,W),I&&(xe=ki(xe)),Bt(100)}
239else{Ft.current=!0,Ot.current=!1,ze.current=[],pr.current=new Set;const ge=We.find(tt=>tt.id===Z),et=ge?{name:ge.name,avatarUrl:ge.avatarUrl,renderMode:ge.renderMode,live2d:vi(ge),expressions:ge.expressions,cgImages:ge.cgImages||[],defaultSkinId:null,layout:ge.layout}:pi(Z),dr={customBackgroundUrl:u,characterReference:os,...et?{charMetadata:et,defaultCharacterSkinId:et.defaultSkinId||null}:{}},pt={onNewFrames:(tt,Cr,Kr,Ri)=>{if(Je.current!==At)return;Ri&&Ri.length>0&&Ir(Ri);const Ni=tt.filter(Ge=>pr.current.has(Ge.id)?!1:(pr.current.add(Ge.id),!0));if(Ni.length>0&&(ze.current=Zt(ze.current,Ni),xt.current=!1,Tt(!1),l.startTransition(()=>{o(Ge=>{if(!Ge)return Ge;const Rt=Lt(Ge,Ni);bt.current=Rt;const Xr=new Set(Rt.frames.map(fr=>fr.id));return ze.current=ze.current.filter(fr=>!Xr.has(fr.id)),Ot.current&&ze.current.length===0&&(Ft.current=!1),Le(Rt),Rt}),n(Ge=>Ge===D.FINISHED?D.PLAYING:Ge)})),Kr&&lr(Kr),Cr){Bt(100),Ot.current=!0,Ft.current=ze.current.length>0,La(null);{const Ge=Kr,Rt=typeof(Ge==null?void 0:Ge.title)=="string"&&Ge.title.trim()?Ge.title.trim():null,Xr=typeof(Ge==null?void 0:Ge.summary)=="string"&&Ge.summary.trim()?Ge.summary.trim():null,fr=Array.isArray(Ge==null?void 0:Ge.documentAssets)?Ge.documentAssets:null;if(Rt||Xr||fr){const rn=bt.current;if(rn){const tu=Rt!=null&&rn.title!==Rt,ru=Xr!=null&&rn.summary!==Xr,au=fr!=null&&JSON.stringify(rn.documentAssets??[])!==JSON.stringify(fr);if(tu||ru||au){const Pi={...rn,...Rt&&tu?{title:Rt}:{},...Xr&&ru?{summary:Xr}:{},...fr&&au?{documentAssets:fr}:{}};bt.current=Pi,o(Pi),Le(Pi)}}}}xt.current&&ze.current.length===0&&(xt.current=!1,f(Ge=>{const Rt=bt.current;return Rt&&Ge>=Rt.frames.length-1&&(fa("completed"),vc()),Ge}))}},onVoiceUpdates:tt=>{Ir(tt)},onProgress:tt=>{lr(tt)}},en=de?(async()=>{var Cr;const{generateDocumentBatchIncremental:tt}=await Be(async()=>{const{generateDocumentBatchIncremental:Kr}=await import("./aiService-9EzGVred.js");return{generateDocumentBatchIncremental:Kr}},__vite__mapDeps([0,1,2,3,4,5,6,7]),import.meta.url);return tt({files:oe,characterId:Z,language:W,fingerprint:C||"",customCharacter:nt,outputLanguage:Qr,voiceLanguage:Ja,backgroundName:E,fixedBackground:je,playerNickname:ht,blackboardModeEnabled:I,imageParsingEnabled:Re===!0,voiceEnabled:we,narrativeStyle:Ae,entertainmentQuality:ce,callbacks:pt,signal:(Cr=sr.current)==null?void 0:Cr.signal})})():Zh(Ar,Z,W,C||"",nt,Qr,Ja,E,je,ht,I,we,pt,t,(Jc=sr.current)==null?void 0:Jc.signal,dr,J,Ae,ce),tn=await ap({generation:en,videoUrl:de?void 0:J,abortController:sr.current});xe=await an(Lt(tn)),I&&(xe=ki(xe)),bt.current=xe,xe.frames.forEach(tt=>pr.current.add(tt.id)),ze.current=ze.current.filter(tt=>!xe.frames.some(Cr=>Cr.id===tt.id)),Bt(50)}const yr=Ft.current||!Ot.current,_r=ge=>yr?Lt(ge):ge;xe={...xe,characterReference:os};let cs={...xe,customBackgroundUrl:u},eu=!1;(ge=>{if(!(eu||Je.current!==At)){if(eu=!0,Ki&&sa.current){const et=Date.now(),{startedAtMs:dr,confirmedAtMs:pt,voiceEnabled:en,intensiveReadingEnabled:tn}=sa.current,tt=et-dr,Cr=pt?pt-dr:0,Kr=pt?et-pt:tt;console.log(["[StartToGameTiming]",`totalMs=${tt}`,`totalSec=${(tt/1e3).toFixed(2)}`,`backgroundSelectMs=${Cr}`,`generationMs=${Kr}`,`frames=${Array.isArray(ge.frames)?ge.frames.length:0}`,`voice=${en===!0}`,`intensive=${tn===!0}`].join(" ")),sa.current=null}bt.current=_r(ge),ot(void 0),Ct(null),Bt(0),o(bt.current),f(0),n(D.PLAYING),Yr(!0)}})(cs),await iA();const wi=await Ii(cs,Z,void 0,{generationRunId:At});if(Je.current!==At)return;Ce=(wi==null?void 0:wi.id)??null;const sh=Ce;if(l.startTransition(()=>{o(ge=>{const et=_r(ge||cs);return bt.current=et,et})}),sh){const ge=_r(bt.current||cs);Le(ge)}}catch(Ce){if(Je.current!==At)return;if(Ce.message==="AUTH_REQUIRED"){await ke(Ze.loginRequired||"请先登录后使用该功能。",{variant:"info"}),n(D.LOGIN);return}if(Ce.message==="BORROWED_CHARACTER_UNAVAILABLE"){await ke("借阅角色暂时不可用,请重试。",{variant:"warning"}),n(D.MENU);return}if(Ce.message==="CHARACTER_UNAVAILABLE"){await ke("角色暂时不可用,请重试。",{variant:"warning"}),n(D.MENU);return}if(typeof Ce.message=="string"&&Ce.message.startsWith("SAVE_LIMIT_REACHED")){const[,Le,xe]=Ce.message.split(":");await ke(W==="zh"?`存档数量已达到上限(${Le||"当前数量"}/${xe||"上限"}
239)。请先删除不需要的存档,数量降到上限以下后再生成新的游戏剧情。`:`Save limit reached (${Le||"current"}/${xe||"limit"}). Delete unused saves below the limit before generating a new story.`,{variant:"warning"}),n(D.MENU);return}if(Ce.message==="DAILY_LIMIT_EXCEEDED"||Ce.message&&(Ce.message.includes("Limit")||Ce.message.includes("429"))){await ke(Ze.dailyLimitExceeded||"今日使用次数已达上限,请明日再来或使用兑换码获取永久次数。",{variant:"warning"}),n(D.MENU);return}const qe={appState:a,language:W,characterId:Z,pdfParseMode:"none",errorLayerHint:(Ce==null?void 0:Ce.errorLayerHint)||"ai_api",outputLanguage:((Zc=mt==null?void 0:mt.trim)==null?void 0:Zc.call(mt))||"",isVoiceEnabled:we,blackboardModeEnabled:I,selectedBackground:Ee?{name:Ee.name,url:Ee.url}:null,pdfFiles:null,fingerprint:C||null};Cs(Ce,qe,{category:"llm",source:"generation"}).then(Le=>{Je.current===At&&Le&&K(Le)}).catch(()=>{}),Y(Ui(Ce==null?void 0:Ce.message,W)),n(D.ERROR)}finally{if(Je.current!==At)return;be(null),ot(void 0),Ct(null),Bt(0),Jo(!1),Fn(null),La(null)}},Mm=async(u,E,I=!1)=>{var J,oe;Ua("local-script"),Je.current+=1,Ft.current=!1,xt.current=!1,ze.current=[],pr.current=new Set,Ot.current=!0,Tt(!1);const y=E||Z;E&&fe(E);const C=ki(await an(u));await Fi({blackboard:C.frames.some(Re=>{var Ae;return!!((Ae=Re.blackboard)!=null&&Ae.trim())})});const x=((J=C.charMetadata)==null?void 0:J.defaultSkinId)||null;x&&Pe(Re=>({...Re,[String(y).toUpperCase()]:x}));const H=C.customBackgroundUrl||Ai[(oe=C.frames[0])==null?void 0:oe.background]||Vt[0];ye({url:H}),C.charMetadata?Va(C.charMetadata):Va(null),Pc(y),Me(""),qa([]),Wr(!1),o(C),f(0),Xt([]),$(ga()),n(D.PLAYING),Yr(!0)};l.useEffect(()=>{let u;return Qt&&(u=window.setTimeout(()=>{Yr(!1)},8e3)),()=>clearTimeout(u)},[Qt]),l.useEffect(()=>()=>{or.current&&window.clearTimeout(or.current)},[]);const Oc=()=>{or.current&&(window.clearTimeout(or.current),or.current=null),oi(!1)},vc=()=>{Kt||(or.current&&window.clearTimeout(or.current),xt.current=!1,Tt(!1),ts(!1),Fr([]),ti(!1),oi(!0),or.current=window.setTimeout(()=>{or.current=null,oi(!1),n(D.FINISHED)},dp))},[vt,Xt]=l.useState([]),as=(u,E=v.current)=>{const I=localStorage.getItem("p2g_token");if(!I||!u)return Promise.resolve(null);const y=j.current.catch(()=>null).then(async()=>{const C=await fetch(`/api/saves/${encodeURIComponent(u)}/choice-state`,{method:"PATCH",headers:{"Content-Type":"application/json",Authorization:`Bearer ${I}`},body:JSON.stringify({storyChoiceState:E})});if(!C.ok)throw new Error("Failed to sync story choice state");return C.json()});return j.current=y,y},Ii=async(u,E,I,y)=>{var ce,de;const C=ct.current,x=String((y==null?void 0:y.generationRunId)??Je.current),H=Da.current,J=()=>!!C&&ct.current===C&&Da.current===H&&((y==null?void 0:y.generationRunId)==null||Je.current===y.generationRunId);if(!J())return null;const oe=u||i,Re=E||Z;if(!oe||!C)return;const Ae=localStorage.getItem("p2g_token");if(Ae){try{const we=We.find(Lt=>Lt.id===Re),je=pi(Re),Ze=we?{name:we.name,avatarUrl:we.avatarUrl,renderMode:we.renderMode,live2d:vi(we),expressions:we.expressions,cgImages:we.cgImages||[],layout:we.layout}:je,nt=(je==null?void 0:je.defaultSkinId)||null,Jt=await an(oe),os=JSON.stringify({script:Jt,characterId:Re,defaultCharacterSkinId:nt,charMetadata:Ze,storyChoiceState:In(v.current,Jt.frames)}),Qr=(Jt.title||"").trim()||"未命名讲解",Ja=(Jt.summary||"").trim()||(((de=(ce=Jt.frames)==null?void 0:ce[0])==null?void 0:de.text)||"").trim().slice(0,200)||Qr,Ar=await fetch("/api/saves",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Ae}`},body:JSON.stringify({chapterTitle:Qr,previewText:Ja,gameState:os,type:"auto",id:I??Vr.current})});if(Ar.status===401)return Ht(),null;if(Ar.ok){const Lt=await Ar.json();if(!J())return Lt;Ea(Lt,C),(y==null?void 0:y.syncCurrentSaveId)!==!1&&Gr(Lt.id,"owner",C),ca.current==="owner"&&Promise.all(Jt.frames.map(async Ir=>{if(!J()||ca.current!=="owner")return;const At={ownerId:C,saveId:Lt.id,generationId:x,anchor:{frameId:Ir.id,speaker:Ir.speaker,text:Ir.text}};await St.assignSave(At),J()&&await St.snapshotReady(At)}));const Za=await as(Lt.id,v.current).catch(Ir=>(console.warn("[StoryChoiceState] Failed to sync after save:",Ir),null));return Za&&J()&&Ea(Za,C),Za||Lt}const Zt=await Ar.json().catch(()=>null);if((Zt==null?void 0:Zt.code)==="SAVE_LIMIT_REACHED")throw new Error(`SAVE_LIMIT_REACHED:${typeof Zt.count=="number"?Zt.count:""}:${typeof Zt.limit=="number"?Zt.limit:""}`)}catch(we){if(console.error("Cloud save failed",we),we instanceof Error&&we.message.startsWith("SAVE_LIMIT_REACHED"))throw we}return null}},ns=async(u,E={})=>{var Re,Ae;const I=E.visibility||"owner",y=ct.current;if(I==="owner"&&(!y||u.userId!==y))return!1;const C=y,x=()=>H===ir.current&&ct.current===C;ni(C);const H=ir.current,J=u,oe=I==="owner"&&C===u.userId?Object.prototype.hasOwnProperty.call(E,"archiveFallback")?E.archiveFallback:ta(J.storyQuestionArchive)&&Number.isInteger(J.storyQuestionRevision)&&J.storyQuestionRevision>=0?{archive:J.storyQuestionArchive,revision:J.storyQuestionRevision}:null:null;Gr(null,I,C),qa([]),Wr(!1),ka("loading"),o(null),f(0);try{if(!Rg(u)){const nt=sd(u);return x()&&(await ke(xg(u),{variant:nt.kind==="failed"||nt.kind==="cancelled"?"error":"info"}),x()&&ka("ready")),!1}const ce=JSON.parse(u.gameState);Tt(!1),Me("");const de=await an(Sg(ce.script,u)),we=I==="owner"&&C&&C===u.userId?await St.loadArchive({saveId:u.id,ownerId:C,visibility:I,fallback:oe}):{archive:{version:1,entries:[]},revision:0,source:"public"};if(!x())return!1;oc(we.archive),ka("ready"),Gr(I==="owner"?u.id:null,I,I==="owner"?C:null),o(de),f(0),Xt([]),$(In(ce.storyChoiceState,de.frames)),fe(ce.characterId);const je=ce.defaultCharacterSkinId||((Re=ce.charMetadata)==null?void 0:Re.defaultSkinId);je&&Pe(nt=>({...nt,[String(ce.characterId).toUpperCase()]:je})),ce.charMetadata?Va(ce.charMetadata):Va(null);
239const Ze=de.customBackgroundUrl||Ai[(Ae=de.frames[0])==null?void 0:Ae.background]||Vt[0];return ye({url:Ze}),n(D.PLAYING),Yr(!0),!0}catch(ce){return x()&&(ka("ready"),console.error("Failed to load save",ce),await ke("Failed to load save",{variant:"error"})),!1}},ss=l.useRef(null);l.useEffect(()=>{const u=_l().trim();if(!u||ss.current===u)return;ss.current=u;const E=ir.current,I=ct.current,y=()=>ss.current===u&&ir.current===E&&ct.current===I;(async()=>{try{const x=await fetch(`/api/public/saves/${encodeURIComponent(u)}`);if(!x.ok)throw x.status===404?new Error(He[W].saveNotFound||"Save not found"):x.status===403?new Error(He[W].saveNotShared||"Save not shared"):new Error("Load failed");const H=await x.json();if(!y())return;await ns(H,{visibility:"public"})}catch(x){if(!y())return;ss.current=null,await ke(Ui((x==null?void 0:x.message)||"Load failed",W),{variant:"error"})}})()},[W]);const Qa=l.useRef(null);l.useEffect(()=>{const u=dA().trim();if(!u||!Te||Qa.current===u)return;Qa.current=u;const E=ir.current,I=ct.current,y=()=>Qa.current===u&&ir.current===E&&ct.current===I;(async()=>{try{const x=localStorage.getItem("p2g_token");if(!x)throw new Error(He[W].loginRequired||"Please log in first");const H=await fetch("/api/saves",{headers:{Authorization:`Bearer ${x}`},cache:"no-store"}),J=await H.json().catch(()=>[]);if(!H.ok)throw new Error((J==null?void 0:J.error)||"Failed to load saves");const oe=Array.isArray(J)?J.find(Ae=>(Ae==null?void 0:Ae.id)===u):null;if(!oe)throw new Error(He[W].saveNotFound||"Save not found");if(await ns(oe)&&Qa.current===u&&ct.current===I){const Ae=new URLSearchParams(window.location.search);Ae.delete("openSave");const ce=`${window.location.pathname}${Ae.toString()?`?${Ae}`:""}${window.location.hash}`;window.history.replaceState({},"",ce)}}catch(x){if(!y())return;Qa.current=null,await ke(Ui((x==null?void 0:x.message)||"Load failed",W),{variant:"error"})}})()},[Te==null?void 0:Te.id,W]);const Um=async()=>{const u=He[W];if(!Te)throw await ke(u.loginRequired||"请先登录后使用该功能。",{variant:"info"}),new Error(u.loginRequired||"Login required");const E=localStorage.getItem("p2g_token");if(!E)throw await ke(u.loginRequired||"请先登录后使用该功能。",{variant:"info"}),new Error(u.loginRequired||"Login required");let I=d;if(i){const H=await Ii(i,Z,I||void 0);I=(H==null?void 0:H.id)||I}if(!I)throw new Error(u.shareSaveMissing||"Unable to create a cloud save for sharing.");const y=await fetch(`/api/saves/${encodeURIComponent(I)}/share`,{method:"PATCH",headers:{"Content-Type":"application/json",Authorization:`Bearer ${E}`},body:JSON.stringify({isShared:!0})});if(y.status===401)throw Ht(),new Error(u.loginRequired||"Login required");const C=await y.json().catch(()=>null);if(!y.ok)throw new Error((C==null?void 0:C.error)||u.shareSaveFailed||"Failed to share save");Gr(C.id||I,"owner",ct.current);const x=`${window.location.origin}/?save=${encodeURIComponent(C.id||I)}`;return{saveId:C.id||I,shareUrl:x}},fa=u=>{var E;(E=qt.current)==null||E.finish(u),qt.current=null,Mn.current=""},yi=()=>H0({renderedScript:i,latestScript:bt.current,pendingFrames:ze.current}),Ka=u=>{i!==u&&(bt.current=u,o(E=>E===u?E:u))},Bm=()=>{if(Kt||oa==="loading")return;const u=yi();if(!u)return;const E=pu({renderedScript:i,navigableScript:u,currentFrameIndex:c});if(E===-1)return;const I=Ot.current&&ze.current.length===0,y=gu({script:u,currentFrameIndex:E,isStreaming:Ft.current&&!I,hasPendingFrames:ze.current.length>0});if(y.action==="goto"){xt.current=!1,Tt(!1),Ka(u),Xt(C=>[...C,y.historyFrameId]),f(y.nextIndex);return}if(y.action==="wait"){xt.current=!0,Tt(!0);return}y.action==="finish"&&(xt.current=!1,Tt(!1),Ka(u),Xt(C=>[...C,y.historyFrameId]),fa("completed"),vc())},Fm=u=>{var H;if(oa==="loading")return;const E=yi();if(!E)return;const I=pu({renderedScript:i,navigableScript:E,currentFrameIndex:c}),y=E.frames[I];if(!y)return;if(y.quizId&&u.optionId&&((H=qt.current)==null||H.answerQuiz(y.quizId,u.optionId)),u.choiceId&&u.optionId){const J=new Set(Li({script:E,historyFrameIds:vt,currentFrameId:y.id}).map(Re=>Re.socialChoiceId).filter(Re=>!!Re));J.add(u.choiceId);const oe=TE({state:v.current,frames:E.frames,choiceId:u.choiceId,optionId:u.optionId,activeChoiceIds:J});$(oe),d&&as(d,oe).then(Re=>Re&&Ea(Re)).catch(Re=>console.warn("[StoryChoiceState] Failed to sync choice:",Re))}Xt(J=>[...J,y.id]);const C=u.nextFrameId,x=E.frames.findIndex(J=>J.id===C);if(x!==-1)Ka(E),Tt(!1),f(x);else{console.warn(`[handleChoice] nextFrameId ${C} not found in navigable script. Falling back to linear advance.`);const J=gu({script:E,currentFrameIndex:I,isStreaming:Ft.current&&!(Ot.current&&ze.current.length===0),hasPendingFrames:ze.current.length>0});J.action==="goto"?(Ka(E),Tt(!1),f(J.nextIndex)):J.action==="wait"&&(xt.current=!0,Tt(!0))}},Hm=()=>{const u=yi();if(u)if(Tt(!1),vt.length>0){const E=vt.slice(0,-1),I=vt[vt.length-1],y=u.frames.findIndex(H=>H.id===I);y!==-1&&(Ka(u),f(y)),Xt(E);const C=new Set(Li({script:u,historyFrameIds:E,currentFrameId:I}).map(H=>H.socialChoiceId).filter(H=>!!H)),x=gd(v.current,u.frames,C);$(x),d&&as(d,x).then(H=>H&&Ea(H)).catch(H=>console.warn("[StoryChoiceState] Failed to sync back navigation:",H))}else c>0&&f(E=>E-1)},Lc=()=>{var u;(a===D.PLAYING||Kt)&&fa("active_exit"),Je.current+=1,Ua("reset"),(u=sr.current)==null||u.abort(),sr.current=null,Oc(),n(D.MENU),Me(""),ti(!1),Fr([]),Hr([]),o(null),f(0),Gr(null,"owner",null),Xt([]),$(ga()),Yr(!1),ts(!1),Wr(!1),qa([]),Va(null),ye(null),ri(""),bt.current=null,Ft.current=!1,xt.current=!1,ze.current=[],pr.current=ne
239w Set,Ot.current=!0,La(null),Tt(!1),ot(void 0),Bn(null),Jo(!1)},kc=async()=>{const u=Ft.current||ze.current.length>0;if((a===D.PLAYING||a===D.FINISHED)&&u){const E=He[W];if(!await du(E.exitWhileGeneratingMessage,{title:E.exitWhileGeneratingTitle,variant:"warning",confirmText:E.exitWhileGeneratingConfirm,cancelText:E.exitWhileGeneratingCancel}))return}Lc()},Dc=u=>u?`p2g_bookmark_${u}`:null,jm=async()=>{if(!i)return;const u=Dc(d);if(!u)return;const E=i.frames[c];try{localStorage.setItem(u,JSON.stringify({frameId:E.id,savedAt:Date.now()})),await ke(He[W].bookmarkSaved||"书签已保存",{variant:"success"})}catch(I){console.error("Failed to save bookmark",I),await ke(He[W].bookmarkSaveFailed||"书签保存失败",{variant:"error"})}},Vm=async()=>{if(!i)return;const u=Dc(d);if(u)try{const E=localStorage.getItem(u);if(!E){await ke(He[W].bookmarkNotFound||"当前存档还没有书签",{variant:"info"});return}const I=JSON.parse(E);if(typeof I.frameId!="number")throw new Error("Invalid bookmark data");const y=i.frames.findIndex(C=>C.id===I.frameId);if(y===-1){await ke(He[W].bookmarkInvalid||"书签已失效,无法跳转",{variant:"warning"});return}Tt(!1),f(y),Xt([]),await ke(He[W].bookmarkLoaded||"已跳转到书签位置",{variant:"success"})}catch(E){console.error("Failed to load bookmark",E),await ke(He[W].bookmarkLoadFailed||"读取书签失败",{variant:"error"})}},Gm=async u=>{var Re;const E=He[W];if((Re=qt.current)==null||Re.recordRaisedHand((pe==null?void 0:pe.sectionId)||`frame-${(pe==null?void 0:pe.id)||c+1}`),!i||!pe)throw new Error(E.questionUnavailable||"当前剧情暂时无法提问。");const I=sn(mt,W),y=ct.current,C=Vr.current,x=String(Je.current),H=ca.current,oe=!!(y&&H==="owner"&&pe)?St.prepareCapture({ownerId:y,saveId:C,generationId:x,anchor:{frameId:pe.id,speaker:pe.speaker,text:pe.text},question:u.trim(),playerSpeaker:"You"}):null;try{const Ae=await e0(u.trim(),pc(),NE({referenceText:he,documentAssets:i.documentAssets,question:u,maxLength:14e3}),$f(qf(),7e3),I,void 0,wt,ht,Gu({frames:i.frames,currentFrameIndex:c,historyFrameIds:vt,narrativeStyle:wt}));if(oe){const ce=Mc.current,de=ce.ownerId===oe.ownerId,we=ce.visibility==="owner",je=fA(ce.anchor,oe.anchor),Ze=oe.saveId?ce.saveId===oe.saveId&&ce.generationId===oe.generationId:ce.generationId===oe.generationId;de&&we&&je&&Ze&&St.completeCapture(oe,Ae).then(nt=>{(nt.status==="appended"||nt.status==="duplicate")&&Ma.current.add(oe.operationId),(nt.status==="failed"||nt.status==="invalid")&&console.warn("[StoryQuestionArchive] Answer remains live but was not saved:",nt.message)})}return Ae}catch(Ae){if((Ae==null?void 0:Ae.message)==="AUTH_REQUIRED")throw await ke(E.loginRequired||"请先登录后使用该功能。",{variant:"info"}),n(D.LOGIN),new Error(E.loginRequired||"请先登录后使用该功能。");if(typeof(Ae==null?void 0:Ae.message)=="string"&&Ae.message.startsWith("STORY_QUESTION_LIMIT_REACHED")){const[,ce,de]=Ae.message.split(":"),we=Number(ce),je=Number(de),Ze=Number.isFinite(we)&&Number.isFinite(je)&&je>0?`今日举手问答次数已达上限(${we}/${je})。免费用户每天 20 次,会员每天 100 次。`:"今日举手问答次数已达上限。免费用户每天 20 次,会员每天 100 次。";throw await ke(Ze,{variant:"info"}),new Error(Ze)}throw Ae}},Ym=()=>{i&&(fa("completed"),Oc(),Tt(!1),f(0),Xt([]),$(ga()),d&&as(d,ga()).then(u=>u&&Ea(u)).catch(u=>console.warn("[StoryChoiceState] Failed to reset replay state:",u)),Fr([]),Hr([]),Ma.current=new Set,n(D.PLAYING),Yr(!0))},pe=i==null?void 0:i.frames[c],Mc=l.useRef({ownerId:null,saveId:null,generationId:null,visibility:"owner",anchor:null});Mc.current={ownerId:ct.current,saveId:Vr.current,generationId:String(Je.current),visibility:ca.current,anchor:pe?{frameId:pe.id,speaker:pe.speaker,text:pe.text}:null};const zm=$g(xf,pe?{id:pe.id,speaker:pe.speaker,text:pe.text}:void 0,{alreadySeenOperationIds:Ma.current}),Wm=qg(zm.entries),Ne=Oe||ua,Xa=(Ne==null?void 0:Ne.character.kind)==="cloud"?We.find(u=>u.dbId===Ne.character.id||u.id===Ne.character.id):null,Uc=(Ne==null?void 0:Ne.character.kind)==="cloud"?(Xa==null?void 0:Xa.id)||"__research_character_unavailable__":(Ne==null?void 0:Ne.character.id)||Z,_i=t.find(u=>u.id===Uc),ma=_i?pa(_i,(Ne==null?void 0:Ne.character.skinId)||"base"):null,cr=Xa||_i,Bc=!!(gr&&!Oe&&!ua||(ua==null?void 0:ua.character.id)==="UNKNOWN"||(Gc=jn.find(u=>u.sessionId===(gr==null?void 0:gr.sessionId)))!=null&&Gc.metadataMissing),Ci=!!(!Bc&&((Ne==null?void 0:Ne.character.kind)==="default"?t.some(u=>u.id===Ne.character.id):Xa)),$m=(Ne==null?void 0:Ne.background.kind)==="preset"?
239((Yc=Pr.find(u=>u.id===Ne.background.id))==null?void 0:Yc.url)||Vt[0]:((Ne==null?void 0:Ne.background.kind)==="custom",(Ee==null?void 0:Ee.url)||Vt[0]),qm=l.useMemo(()=>({characterReference:(Ne==null?void 0:Ne.character.reference)||pc(),outputLanguage:(Ne==null?void 0:Ne.outputLanguage)||sn(mt,W),narrativeStyle:(Ne==null?void 0:Ne.narrativeStyle)||wt,playerAddressOverride:(Ne==null?void 0:Ne.playerAddress)||ht.trim()||void 0,runtimeContext:Gu({frames:(i==null?void 0:i.frames)??[],currentFrameIndex:c,historyFrameIds:vt,narrativeStyle:wt})}),[Z,We,c,vt,W,wt,mt,ht,i==null?void 0:i.frames,ua,Ne]);l.useEffect(()=>{a!==D.PLAYING&&a!==D.FINISHED&&fa("active_exit")},[a]),l.useEffect(()=>{var y;const u=i==null?void 0:i.generationTrace,E=(i==null?void 0:i.analysisJobId)||Vr.current;if(!i||!u||!E||a!==D.PLAYING)return;const I=`${E}:${((y=i.frames[0])==null?void 0:y.id)||0}`;(Mn.current!==I||!qt.current)&&(fa("active_exit"),va.current||(va.current=GE()),qt.current=VE({jobId:E,generationTrace:u,emit:C=>{var x;return(x=va.current)==null?void 0:x.emit(C)}}),Mn.current=I),qt.current.recordProgress({currentFrameIndex:c,totalFrameCount:i.frames.length,frameCountFinal:Ot.current}),!Qt&&(pe!=null&&pe.quizId)&&qt.current.presentQuiz(pe.quizId)},[a,pe==null?void 0:pe.id,pe==null?void 0:pe.quizId,c,d,i==null?void 0:i.analysisJobId,i==null?void 0:i.frames.length,i==null?void 0:i.generationTrace,Qt]);const Qm=(jr==null?void 0:jr.speaker)||(pe==null?void 0:pe.speaker)||"",Km=(jr==null?void 0:jr.emotion)||(pe==null?void 0:pe.emotion)||lt.NEUTRAL;l.useEffect(()=>{if(!i){ri("");return}ri(V0({frames:i.frames,currentFrameIndex:c,historyFrameIds:vt,activeQuestionSteps:[...Hn,...tc]}))},[Hn,c,vt,tc,i]);let qr=!1;const ur=Qm.toLowerCase(),Xm=sp.some(u=>ur.includes(u)),Jm=ip.some(u=>ur.includes(u));if(Xm)qr=!0;else if(Jm)qr=!0;else{const u=t.find(E=>E.id===Z);if(u){const E=Array.isArray(u.keywords)&&u.keywords.some(C=>ur.includes(String(C).toLowerCase())),y=[u.name,(zc=u.names)==null?void 0:zc[W],(Wc=u.names)==null?void 0:Wc.zh,u.id].filter(Boolean).map(C=>String(C).toLowerCase()).some(C=>ur.includes(C));qr=E||y||ur.length>0}else{const E=We.find(I=>I.id===Z);E?qr=ur.includes(E.name.toLowerCase())||ur.length>0:jt&&(qr=ur.includes(jt.name.toLowerCase())||ur.length>0)}}If&&(qr=!1);const Zm=Km,Fc=Ee?Ee.url:pe&&Ai[pe.background]||Vt[0],Hc=Li({script:i,historyFrameIds:vt,currentFrameId:pe==null?void 0:pe.id});jr||i==null||i.frames[c+1];const eh=Ft.current&&!!i&&c>=i.frames.length-1&&!(Ot.current&&ze.current.length===0),jc=!!rc.trim(),th=a===D.PLAYING||a===D.FINISHED||a===D.LOADING||a===D.ERROR||a===D.RESEARCH_ROOM,is=a===D.SUPPORT,Fe=He[W],rh=(()=>{const u=St.state.lastFailure;return(u==null?void 0:u.code)==="ARCHIVE_CAPACITY"||(u==null?void 0:u.code)==="PENDING_CAPACITY"||(u==null?void 0:u.code)==="PENDING_SIZE"?Fe.storyQuestionArchiveCapacity:(u==null?void 0:u.code)==="ANCHOR_NOT_READY"?Fe.storyQuestionArchiveAnchorPending:(u==null?void 0:u.code)==="PENDING_UNSAVED"?Fe.storyQuestionArchivePending:u?Fe.storyQuestionArchiveSaveFailed:St.state.pending.length>0?Fe.storyQuestionArchivePending:null})(),ah=(()=>{var I,y,C;if((I=jt==null?void 0:jt.name)!=null&&I.trim())return jt.name.trim();const u=pi(Z);if((y=u==null?void 0:u.name)!=null&&y.trim())return u.name.trim();const E=We.find(x=>x.id===Z);return(C=E==null?void 0:E.name)!=null&&C.trim()?E.name.trim():String(Z||"")})(),Vc=SE(b,W),nh=[String(Fe.endingFarewell||"本次论文阅读已完成。").replace(/\{\{\s*name\s*\}\}/g,ah),Vc].filter(Boolean).join(" ");return Qf?p.jsx("div",{className:"fixed inset-0 z-[99999] bg-red-900 flex flex-col items-center justify-center p-6 text-white text-center font-sans",children:p.jsxs("div",{className:"bg-red-800 p-8 rounded-3xl shadow-2xl max-w-lg w-full border-[6px] border-red-400 animate-pulse",children:[p.jsx(wl,{size:80,className:"mx-auto mb-6 text-red-200"}),p.jsx("h1",{className:"text-2xl md:text-3xl font-black mb-4 uppercase tracking-tighter",children:"警告 / WARNING"}),p.jsxs("div",{className:"space-y-4 mb-8",children:[p.jsxs("div",{className:"bg-red-950/30 p-4 rounded-xl",children:[p.jsx("p",{className:"text-lg font-bold text-red-100 mb-2",children:"此网站可能是伪冒网站或镜像站。"}),p.jsx("p",{className:"text-sm text-red-200 opacity-90",children:"检测到非法嵌套。为保障您的数据安全和体验,请前往官方网站。"})]}),p.jsxs("div",{className:"bg-red-950/30 p-4 rounded-xl text-left",children:[p.jsx("p",{className:"text-lg font-bold text-red-100 mb-2",children:"This might be a fake website."}),p.jsx("p",{className:"text-sm text-red-200 opacity-90",children:"Illegal framing detected. For your safety and best experience, please visit the official website."})]})]}),p.jsxs("div",{className:"flex flex-col gap-3",children:[p.jsx("p",{className:"text-sm text-red-300 font-bold uppercase tracking-widest",children:"Official Website"}),p.jsxs("button",{onClick:Kf,className:"w-full py-4 bg-white text-red-900 rounded-xl font-black text-xl hover:bg-red-50 hover:scale-105 transition-all shadow-xl flex items-center justify-center gap-2",children:[p.jsx(Ah,{size:24})," paper2gal.com"]})]})]})}):p.jsxs(p.Fragment,{children:[p.jsx("style",{children:`
240        .app-container {
241          position: fixed;
242          inset: 0;
243          width: 100vw;
244          height: 100vh;
245          height: 100dvh;
246          overflow: hidden;
247          --app-vw: 100vw;
248          --app-vh: 100dvh;
249        }
250
251        .source-pdf-reader { width: min(720px, 88vw); }
252        .source-pdf-scroll { scrollbar-color: #d7b7b8 #eee9e4; scrollbar-width: thin; }
253        .source-pdf-scroll::-webkit-scrollbar { width: 8px; height: 8px; }
254        .source-pdf-scroll::-webkit-scrollbar-thumb { background: #d7b7b8; border-radius: 8px; }
255        .source-pdf-scroll::-webkit-scrollbar-track { background: #eee9e4; }
256        .source-pdf-resize { display: none; }
257        @media (min-width: 1200px) {
258          .app-game-source-split { right: var(--source-reader-width) !important; width: auto !important; }
259          .source-pdf-reader { width: var(--source-reader-width); }
260          .source-pdf-resize { display: block; }
261          .source-pdf-backdrop { display: none; }
262        }
263
264        .app-container.force-landscape-mobile {
265          inset: auto;
266          top: 50%;
267          left: 50%;
268          width: max(100vw, 100dvh);
269          height: min(100vw, 100dvh);
270          --app-vw: max(100vw, 100dvh);
271          --app-vh: min(100vw, 100dvh);
272          transform-origin: center center;
273          background-color: #fff0f5;
274          z-index: 0;
275          border-radius: 0;
276          box-shadow: none;
277        }
278
279        /* A square cover display has no portrait axis to correct. Using the
280           orientation media feature there is inconsistent across engines and
281           could rotate an already-valid 360×360 canvas. */
282        @media screen and (max-aspect-ratio: 999/1000) {
283          .app-container.force-landscape-mobile {
284            transform: translate(-50%, -50%) rotate(90deg);
285          }
286        }
287
288        @media screen and (min-aspect-ratio: 1/1) {
289          .app-container.force-landscape-mobile {
290            transform: translate(-50%, -50%) rotate(0deg);
291          }
292        }
293
294        .main-menu-quick-actions > button:hover,
295        .main-menu-quick-actions > button:focus-visible,
296        .main-menu-quick-actions > button:active {
297          z-index: 20;
298        }
299
300        .main-menu-quick-actions:has(details) > button { display: none; }
301        .main-menu-quick-actions:has(details[open]) > button { display: flex; }
302
303        .main-menu-quick-actions .quick-action-hint {
304          top: 50%;
305          right: 100%;
306          left: auto;
307          margin: 0 0.75rem 0 0;
308          transform: translateY(-50%);
309          z-index: 50;
310        }
311
312        .main-menu-quick-actions .quick-action-hint-arrow {
313          top: 50%;
314          left: 100%;
315          width: 7px;
316          height: 14px;
317          transform: translateY(-50%);
318          border: 0;
319          background: var(--quick-action-hint-color);
320          clip-path: polygon(0 0, 100% 50%, 0 100%);
321        }
322
323        .main-menu-quick-actions .quick-action-hint-arrow-pink { --quick-action-hint-color: #f472b6; }
324        .main-menu-quick-actions .quick-action-hint-arrow-amber { --quick-action-hint-color: #fbbf24; }
325        .main-menu-quick-actions .quick-action-hint-arrow-live { --quick-action-hint-color: #fb7299; }
326        .main-menu-quick-actions .quick-action-hint-arrow-sky { --quick-action-hint-color: #38bdf8; }
327      `}),p.jsxs("div",{className:`app-container font-sans bg-blue-50 relative selection:bg-brand-blue selection:text-white ${e&&!is?"force-landscape-mobile":""}`,style:{"--source-reader-width":`${Im}px`},children:[p.jsx("div",{"data-testid":"story-question-archive-state","data-state":oa,role:"status","aria-live":"polite",className:"sr-only",children:oa==="loading"?"Loading saved questions…":"Saved questions ready"}),p.jsxs(b0,{language:W,children:[_f&&!is&&p.jsx("button",{type:"button",className:"fixed inset-0 z-[100000] flex h-full w-full cursor-pointer items-center justify-center overflow-hidden border-0 bg-[#f8f5f2] p-0",onClick:()=>Cf(!1),"aria-label":W==="zh"?"点击开始":W==="ja"?"タップしてスタート":W==="ru"?"Нажмите, чтобы начать":"Tap to start",children:p.jsx("img",{src:"/assets/mobile/paper2gal-title-screen.png",alt:"Paper2Gal",className:"h-full w-full select-none object-contain",draggable:!1})}),sc&&!is&&p.jsx(ag,{update:sc,language:W,onClose:()=>ic(null)}),!is&&(e&&wf||Rf)&&p.jsx(Sp,{isOpen:!0,onClose:()=>{ac(!1),nc(!1)},language:W,shell:ai}
327),(a===D.MENU||a===D.LOGIN)&&p.jsx(mp,{onStart:Dm,onLoadScript:Mm,isLoading:a===D.LOADING,onOpenSettings:()=>Wn(!0),characterId:Z,setCharacterId:fe,selectedDefaultSkinId:hi,onSelectDefaultSkin:(u,E)=>{Pe(I=>({...I,[String(u).toUpperCase()]:E}))},gameUiPreset:Tr,language:W,customCharacters:We,setCustomCharacters:Vn,user:Te,onLogin:()=>n(D.LOGIN),onLogout:Ht,onRefreshUser:hc,onOpenSaves:async()=>{if(!Te){await ke(He[W].loginRequired||"请先登录后使用该功能。",{variant:"info"}),n(D.LOGIN);return}Ue(D.SAVES)},onLoadSave:ns,onStartResearch:hm,onOpenStudyRoom:()=>Ue(D.STUDY_ROOM),playerNickname:ht,setPlayerNickname:yc,onOpenCommunity:()=>Ue(D.COMMUNITY),voiceModeEnabled:F,setVoiceModeEnabled:G,onOpenArxiv:()=>Ue(D.ARXIV),onOpenMembership:()=>Ue(D.MEMBERSHIP),onOpenProfile:async()=>{if(!Te){await ke(He[W].loginRequired||"请先登录后使用该功能。",{variant:"info"}),n(D.LOGIN);return}Ue(D.PROFILE)},onOpenStudyDashboard:async()=>{if(!Te){await ke(He[W].loginRequired||"请先登录后使用该功能。",{variant:"info"}),n(D.LOGIN);return}Ue(D.STUDY_DASHBOARD)},onOpenDocs:$r,arxivPrefill:A,onConsumeArxivPrefill:()=>N(null),extensionFile:_,onClearExtensionFile:()=>m(null),extensionAutoStart:P,narrativeStyle:wt,setNarrativeStyle:fm}),a===D.LOGIN&&p.jsx(l.Suspense,{fallback:p.jsx(kt,{}),children:p.jsx(Ip,{onBack:()=>Ue(D.MENU,"replace"),onLoginSuccess:Wf,language:W,onRegister:()=>{}})}),a===D.ADMIN&&p.jsx(l.Suspense,{fallback:p.jsx(kt,{}),children:p.jsx(yp,{onBack:()=>{Ue(D.MENU,"replace")},language:W})}),a===D.SAVES&&Te&&p.jsx(l.Suspense,{fallback:p.jsx(kt,{}),children:p.jsx(Cp,{userId:Te.id,onBack:()=>Ue(D.MENU),onLoadSave:ns,language:W,customCharacters:We,onLogout:()=>{Ht(),Ue(D.LOGIN,"replace")},researchSessions:jn,researchSessionsLoading:Hf,researchSessionsError:jf,onLoadResearchSessions:Gf,onLoadResearchSession:Em,onUpdateResearchSessionMetadata:lc.updateSessionMetadata,onDeleteResearchSession:Yf})}),a===D.ARXIV&&p.jsx(l.Suspense,{fallback:p.jsx(kt,{}),children:p.jsx(wp,{onBack:()=>Ue(D.MENU),language:W,interests:Zn,onUsePaper:u=>{N(u),Ue(D.MENU,"replace")}})}),a===D.MEMBERSHIP&&p.jsx(l.Suspense,{fallback:p.jsx(kt,{}),children:p.jsx(Rp,{onBack:()=>Ue(D.MENU),onLogin:()=>n(D.LOGIN),language:W,user:Te})}),a===D.SUPPORT&&p.jsx(l.Suspense,{fallback:p.jsx(kt,{}),children:p.jsx(vp,{language:W,onBack:()=>Ue(D.MENU)})}),a===D.PROFILE&&p.jsx(l.Suspense,{fallback:p.jsx(kt,{}),children:p.jsx(Np,{onBack:()=>Ue(D.MENU),onLogin:()=>n(D.LOGIN),onLogout:()=>{Ht(),Ue(D.MENU,"replace")},onRefreshUser:hc,onOpenMembership:()=>Ue(D.MEMBERSHIP),onOpenStudyDashboard:()=>Ue(D.STUDY_DASHBOARD),language:W,user:Te})}),a===D.STUDY_DASHBOARD&&p.jsx(l.Suspense,{fallback:p.jsx(kt,{}),children:p.jsx(Pp,{onBack:()=>Ue(D.MENU),onLogin:()=>n(D.LOGIN),onLogout:Ht,onOpenSaves:()=>Ue(D.SAVES),onOpenMembership:()=>Ue(D.MEMBERSHIP),language:W,user:Te})}),a===D.RESEARCH_ROOM&&p.jsxs(p.Fragment,{children:[p.jsx("div",{"data-testid":"research-scene-background","aria-hidden":"true",className:"pointer-events-none absolute inset-0 z-0 bg-cover bg-center",style:{backgroundImage:`url('${$m}')`}}),p.jsx("div",{className:"pointer-events-none absolute inset-0 z-20 flex items-end justify-center","data-research-character-available":Ci?"true":"false",children:p.jsx(yu,{emotion:Tc.emotion,voiceAudio:Tc.audio,visible:Ci,characterId:Uc,customCharacters:We,defaultSkinId:(Ne==null?void 0:Ne.character.skinId)||"base"})}),U&&p.jsx("div",{role:"status",className:"absolute left-1/2 top-4 z-50 -translate-x-1/2 rounded-xl bg-amber-950/80 px-4 py-2 text-center text-xs font-bold text-amber-100 shadow-lg",children:U}),p.jsx(l.Suspense,{fallback:p.jsx(kt,{}),children:p.jsx(Op,{identity:gr,gateway:uc,characterConfiguration:qm,language:W,preparation:kf,preparationActive:Df,preparationTerminal:Mf,preparationUncertain:Uf,preparationError:Bf,preparationCancelling:Ff,characterAvailable:Ci,voiceAvailable:!!(cr!=null&&cr.voiceRefAudioUrl),characterExpressions:(ma==null?void 0:ma.expressions)||(cr==null?void 0:cr.expressions),characterAvatarUrl:(ma==null?void 0:ma.avatarUrl)||(cr==null?void 0:cr.avatarUrl),voiceVolume:la,muted:Er,onVoiceStateChange:Jf,metadataMissing:Bc,onResolveMissingMetadata:bm,onMetadataResolved:u=>zf((gr==null?void 0:gr.sessionId)||"",u),onPresentationResolved:Tm,onExit:pm})})]}),a===D.STUDY_ROOM&&p.jsx(l.Suspense,{fallback:p.jsx(kt,{}),children:p.jsx(xp,{onBack:()=>Ue(D.MENU),language:W})}),a===D.BACKGROUND_SELECT&&p.jsx(Ap,{language:W,onSelect:se?gm:xc,onCancel:()=>{se&&(me(null),z(null)),Ue(D.MENU,"replace")}}),th&&p.jsxs("div",{className:`absolute inset-0 z-0 w-full h-full ${$a&&a===D.PLAYING?"app-game-source-split":""} ${Tr==="fullwidth"?"overflow-clip":"overflow-hidden"}`,children:[a===D.LOADING&&p.jsx(pp,{language:W,loadingPhase:Ve,scriptProgress:ei,intensiveProgress:Af,isVoiceEnabled:te,ttsProgress:at,ttsQueueInfo:Tf,streamingProgress:Un,dinoRunImageUrl:"/assets/local/loading/runner-run-1.png",dinoRunImageUrlAlt:"/assets/local/loading/runner-run-2.png",dinoRunImageUrlThird:"/assets/local/loading/runner-run-3.png",dinoJumpImageUrl:"/assets/local/loading/runner-jump.png"}),a===D.ERROR&&p.jsx("div",{className:"absolute inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-md animate-fade-in",style:e?{padding:"max(0.75rem, env(safe-area-inset-top)) max(0.75rem, env(safe-area-inset-left)) max(0.75rem, env(safe-area-inset-bottom)) max(0.75rem, env(safe-area-inset-right))"}:void 0,children:p.jsxs("div",{className:`relative w-full bg-white/95 backdrop-blur-xl shadow-[0_20px_60px_rgba(0,0,0,0.3)] flex flex-col items-center text-center border-white ring-4 ring-red-100 overflow-hidden overflow-y-auto ${e?"max-w-[92vw] rounded-2xl border-2 p-5 max-h-[85dvh]":"max-w-lg rounded-3xl border-[6px] p-8 md:p-12"}`,children:[p.jsx("div",{className:"absolute top-0 left-0 w-full h-2 bg-gradient-to-r from-red-300 via-pink-400 to-red-300 shrink-0"}),p.jsx("div",{className:"absolute -top-10 -right-10 w-32 h-32 bg-red-100 rounded-full blur-2xl opacity-50 pointer-events-none"}),p.jsx("div",{className:`${e?"mb-4 p-3":"mb-6 p-5"} bg-red-50 rounded-[20px] shadow-inner transform rotate-3 animate-bounce-gentle shrink-0`,children:p.jsx(Cl,{size:e?32:48,className:"text-red-400 drop-shadow-sm"})}),p.jsx("h2",{className:`font-black text-slate-800 tracking-tight shrink-0 ${e?"text-lg mb-2":"text-2xl md:text-3xl mb-3"}`,children:Fe.errorTitle||Fe.systemError}),p.jsx("p",{className:`text-slate-500 font-medium leading-relaxed shrink-0 ${e?"text-xs mb-4":"mb-4 text-sm md:text-base"}`,children:Fe.errorHint}),V&&p.jsxs("div",{className:`w-full text-left bg-red-50/70 border border-red-100 rounded-xl ${e?"p-3 mb-3":"p-4 mb-4"}`,children:[p.jsxs("div",{className:"flex items-center gap-2 text-red-600 font-black text-xs mb-2",children:[p.jsx(Ih,{size:14}),p.jsx("span",{children:"报错原因"})]}),p.jsx("div",{className:"text-sm font-bold leading-relaxed text-slate-700 whitespace-pre-wrap break-words",children:V}),p.jsxs("div",{className:"mt-3 rounded-lg border border-red-100 bg-white/80 p-3",children:[p.jsx("div",{className:"text-[11px] font-black text-slate-500 mb-1",children:"错误编号"}),p.jsxs("div",{className:"flex items-center justify-between gap-2",children:[p.jsx("code",{className:"text-xs font-black text-slate-800 break-all",children:q||"记录中..."}),p.jsxs("button",{disabled:!q,onClick:async()=>
327{if(q)try{await navigator.clipboard.writeText(q),ee(!0),window.setTimeout(()=>ee(!1),1500)}catch{}},className:`shrink-0 inline-flex items-center gap-2 rounded-lg font-black transition-all min-h-[32px] px-3 py-1.5 text-xs ${Se?"bg-green-600 text-white":"bg-slate-200 hover:bg-slate-300 text-slate-700 disabled:opacity-50 disabled:cursor-not-allowed"}`,children:[Se?p.jsx(yh,{size:14}):p.jsx(_h,{size:14}),Se?"已复制":"复制编号"]})]})]})]}),p.jsxs("div",{className:"flex flex-col w-full gap-2 sm:gap-3 shrink-0",children:[p.jsxs("button",{onClick:Lc,className:`w-full bg-gradient-to-r from-red-400 to-pink-500 hover:from-red-500 hover:to-pink-600 text-white rounded-2xl font-black shadow-xl hover:shadow-2xl hover:-translate-y-1 transition-all duration-300 flex items-center justify-center gap-2 group min-h-[44px] ${e?"py-3 text-sm":"py-4 text-lg"}`,children:[p.jsx(Ch,{size:e?18:20,className:"group-hover:-rotate-180 transition-transform duration-500"}),Fe.retry]}),p.jsxs("a",{href:"https://space.bilibili.com/472900263",target:"_blank",rel:"noopener noreferrer",className:`w-full bg-slate-100 hover:bg-blue-50 text-slate-600 hover:text-blue-500 rounded-xl font-bold transition-all flex items-center justify-center gap-2 min-h-[44px] ${e?"py-3 text-sm":"py-3 text-sm md:text-base"}`,children:[p.jsx(nu,{size:e?16:18})," ",Fe.contactAdmin]})]})]})}),(a===D.PLAYING||a===D.FINISHED)&&i&&pe&&p.jsxs(p.Fragment,{children:[p.jsx("div",{className:`absolute inset-0 z-0 bg-cover bg-center transition-all duration-1000 ease-in-out transform scale-105 ${Qt?"blur-sm brightness-50":"blur-0 brightness-100"} ${Kt?"scale-110 blur-sm brightness-[0.35]":""}`,style:{backgroundImage:`url('${Fc}')`}}),p.jsx("div",{className:`absolute inset-0 z-[60] flex flex-col items-center justify-center bg-black/40 backdrop-blur-md transition-all duration-1000 ease-in-out ${Qt?"opacity-100 visible":"opacity-0 invisible pointer-events-none"}`,onClick:()=>Yr(!1),children:p.jsx("div",{className:`w-full text-center cursor-pointer group select-none ${e?"max-w-[78vw] p-4":"max-w-4xl p-12"}`,children:p.jsxs("div",{className:`${e?"space-y-3":"space-y-8"} animate-fade-in-up`,children:[p.jsxs("div",{className:`flex items-center justify-center ${e?"gap-2 text-[10px]":"gap-4 text-sm"} text-pink-300 tracking-[0.5em] uppercase font-bold`,children:[p.jsx("div",{className:"h-[1px] w-12 bg-pink-300"}),p.jsx("span",{children:"New Chapter"}),p.jsx("div",{className:"h-[1px] w-12 bg-pink-300"})]}),p.jsx("h1",{className:`${e?"text-2xl":"text-5xl md:text-7xl"} font-serif font-black text-white drop-shadow-[0_5px_5px_rgba(0,0,0,0.5)]`,children:i.title}),(($c=i.summary)==null?void 0:$c.trim())&&p.jsxs("p",{className:`${e?"text-sm":"text-xl md:text-2xl"} font-serif text-gray-100 max-w-2xl mx-auto italic opacity-90`,children:['"',i.summary,'"']})]})})}),p.jsx("div",{className:`absolute inset-0 z-20 pointer-events-none flex justify-center items-end transition-all duration-1000 ${Qt?"opacity-0 translate-y-10":"opacity-100"} ${Kt?"opacity-0 translate-y-12 scale-[1.03]":""}`,children:p.jsx(yu,{emotion:Zm,visible:qr,characterId:Z,customCharacters:We,charMetadata:jt,defaultSkinId:hi,shiftLeft:jc,voiceAudio:Ie,action:Qt?"none":pe.action,actionKey:pe.id})}),p.jsx("div",{className:`absolute z-30 rounded-l-xl border-8 border-amber-400 bg-black shadow-lg pointer-events-auto overflow-y-auto overflow-x-hidden p-4 text-amber-50 text-sm md:text-base [&_.katex]:text-amber-50 [&_.katex-display]:text-amber-50 transition-all duration-500 ease-out ${jc?"opacity-100 translate-x-0":"opacity-0 translate-x-8 pointer-events-none"} ${Kt?"opacity-0 translate-x-12 pointer-events-none":""}`,style:e?{top:"max(0.5rem, env(safe-area-inset-top, 12px))",right:"max(0.5rem, env(safe-area-inset-right, 12px))",width:"min(78vw, 420px)",height:"50vh",minHeight:"200px"}:{top:"max(5rem, calc(env(safe-area-inset-top, 24px) + 4rem))",right:"max(0.75rem, env(safe-area-inset-right, 12px))",width:$a?"min(46%, 840px)":"min(46vw, 840px)",height:"min(46vh, 640px)",minWidth:$a?void 0:"400px",minHeight:"360px"},children:p.jsx(l.Suspense,{fallback:p.jsxs("div",{className:"font-medium h-full leading-relaxed text-amber-50 animate-pulse",children:[p.jsx("div",{className:"h-4 bg-amber-100/20 rounded w-3/4 mb-3"}),p.jsx("div",{className:"h-4 bg-amber-100/20 rounded w-1/2 mb-3"}),p.jsx("div",{className:"h-4 bg-amber-100/20 rounded w-5/6"})]}),children:p.jsx(kp,{content:rc})})}),p.jsx("div",{className:`absolute inset-0 z-50 pointer-events-none flex flex-col justify-end transition-all duration-700 transform ${Qt?"opacity-0 translate-y-10":"opacity-100 translate-y-0"} ${Kt?"opacity-0 translate-y-16 scale-[0.98]":""}`,children:p.jsx(hp,{currentFrame:pe,history:Hc,onNext:Bm,onBack:Hm,canBack:c>0,textSpeed:$n,fontScale:qn,uiPreset:Tr,autoAdvanceDelayMs:Kn,autoAdvanceByVoice:Xn,onOpenLog:()=>ts(!0),isLogOpen:_c,onOpenSource:()=>Wr(u=>!u),isSourceReaderOpen:$a,language:W,onChoice:Fm,scriptFrames:i==null?void 0:i.frames,selectedChoiceOptionId:pe.socialChoiceId?b.selectedChoices[pe.socialChoiceId]:void 0,onTts:void 0,onAskQuestion:Gm,
327storyQuestionArchiveLoading:oa==="loading",onQuestionStepsChange:u=>{Fr(u),Hr([])},onQuestionInputStateChange:ti,replayItems:Wm,onReplayComplete:u=>{u.forEach(E=>Ma.current.add(E)),Hr([])},onReplayStepsChange:u=>{Hr(u),u.length>0&&Fr([])},onQuestionPanelClose:Lf,storyQuestionArchiveNotice:rh,voiceVolume:la,onVoiceAudioChange:ve,isTitleCardShowing:Qt,characterThemeColor:(qc=t.find(u=>u.id===String(Z||"").toUpperCase()))==null?void 0:qc.themeColor,isWaitingForMore:eh,streamingProgress:Un??void 0,isUserWaitingForStream:Sf,isInteractionLocked:Kt||oa==="loading"})}),Kt&&p.jsx("div",{className:"absolute inset-0 z-[120] flex items-center justify-center bg-black/45 backdrop-blur-md pointer-events-auto",children:p.jsxs("div",{className:`text-center text-white select-none ${e?"px-6":"px-10"} animate-fade-in-up`,children:[p.jsx("div",{className:`font-semibold uppercase tracking-[0.45em] text-white/55 ${e?"text-[10px]":"text-xs"}`,children:"FIN"}),p.jsx("div",{className:`mt-3 font-serif font-black text-white drop-shadow-[0_8px_24px_rgba(0,0,0,0.45)] ${e?"text-2xl":"text-4xl md:text-5xl"}`,children:Fe.researchCompleted}),p.jsx("div",{className:`mx-auto mt-4 max-w-[min(82vw,42rem)] font-serif leading-relaxed text-white/92 ${e?"text-sm":"text-lg md:text-xl"}`,children:nh}),p.jsx("div",{className:`mt-3 text-white/65 ${e?"text-[11px]":"text-sm md:text-base"}`,children:Fe.endingTransitionHint||"故事落幕中..."})]})}),a===D.FINISHED&&p.jsx(bp,{script:i,onRestart:kc,onReplay:Ym,onShareSave:Um,characterId:Z,language:W,customCharacters:We,storyBackgroundUrl:Fc,charMetadata:jt,defaultSkinId:hi,choiceState:b,relationshipEndingLine:Vc}),a!==D.FINISHED&&!Kt&&p.jsxs("div",{"data-testid":"game-tools",className:Tr==="fullwidth"?"fullwidth-game-tools absolute z-[70] flex gap-0.5 md:gap-1":`absolute top-6 z-50 flex ${e?"gap-1.5 left-6":"gap-2 right-6"}`,style:Tr==="fullwidth"?{bottom:"env(safe-area-inset-bottom, 0px)",right:"env(safe-area-inset-right, 0px)"}:e?{top:"max(1.5rem, env(safe-area-inset-top, 24px))",left:"max(1.5rem, env(safe-area-inset-left, 24px))"}:{top:"max(1.5rem, env(safe-area-inset-top, 24px))",right:"max(1.5rem, env(safe-area-inset-right, 24px))"},children:[p.jsx("button",{onClick:jm,className:Wa,style:za,title:Fe.saveBookmark||"保存书签",children:p.jsx(wh,{size:da})}),p.jsx("button",{onClick:Vm,className:Wa,style:za,title:Fe.loadBookmark||"读取书签",children:p.jsx(Rh,{size:da})}),p.jsx("button",{"aria-label":Fe.settings||"Settings",onClick:()=>Wn(!0),className:Wa,style:za,children:p.jsx(Nh,{size:da})}),p.jsx("button",{"aria-label":Er?Fe.studyRoomUnmute||"Unmute":Fe.studyRoomMute||"Mute",onClick:()=>Xf(!Er),className:Wa,style:za,children:Er?p.jsx(Ph,{size:da}):p.jsx(xh,{size:da})}),p.jsx("button",{"data-testid":"game-reset-button","aria-label":Fe.retry||"Reset",onClick:kc,className:Wa,style:za,children:p.jsx(Oh,{size:da})})]}),p.jsx(Ep,{isOpen:_c,onClose:()=>ts(!1),history:Hc,language:W,characterThemeColor:(Qc=t.find(u=>u.id===String(Z||"").toUpperCase()))==null?void 0:Qc.themeColor,voiceVolume:la,muted:Er,onVoiceAudioChange:ve})]})]}),a===D.PLAYING&&$a&&p.jsxs(p.Fragment,{children:[p.jsx("button",{type:"button","aria-label":W==="zh"?"关闭原文阅读器":"Close source reader",className:"source-pdf-backdrop absolute inset-0 z-[90] bg-black/40",onClick:()=>Wr(!1)}),p.jsx(dg,{files:Cc,selectedFileIndex:Sm,pageNumber:Am,language:W,onSelectFileIndex:Ei,onPageChange:bi,onChooseFile:u=>{Lu([u]).length&&(qa(E=>[...E,u]),Ei(Cc.length),bi(1))},onClose:()=>Wr(!1),onResize:u=>ym(ku(u,window.innerWidth))})]}),a===D.COMMUNITY&&p.jsx(l.Suspense,{fallback:p.jsx(kt,{}),children:p.jsx(_p,{onClose:()=>Ue(D.MENU),user:Te,customCharacters:We,language:W,gameUiPreset:Tr,onLogout:Ht,onBorrowSuccess:u=>{const E={dbId:u.dbId,id:u.characterId,name:u.name,prompt:u.prompt,performanceProfile:u.performanceProfile??void 0,avatarUrl:u.avatarUrl,renderMode:u.renderMode,live2d:u.live2d,cgImages:Array.isArray(u.cgImages)?u.cgImages:[],isShared:u.isShared,isBorrowed:!0,borrowId:u.borrowId,borrowCount:u.borrowCount,voiceRefAudioUrl:u.voiceRefAudioUrl??void 0,voiceRefText:u.voiceRefText??void 0,synthesisVersion:u.synthesisVersion??void 0,layout:u.layout??void 0,expressions:hu(u)};Vn(I=>I.some(y=>y.id===E.id)?I:[...I,E])}})}),a===D.DOCS&&p.jsx(l.Suspense,{fallback:p.jsx(kt,{}
327),children:p.jsx(Lp,{url:_m,title:wm,onBack:()=>{Ue(D.MENU,"replace")},language:W})}),a===D.MENU&&!e&&p.jsx("div",{className:"absolute left-6 top-6 z-40",children:p.jsx(_u,{onClick:()=>rs(!0),hasUnread:wc,label:Fe.announcementTitle||"Announcements",variant:"steam"})}),a===D.MENU&&p.jsxs("div",{"data-testid":"main-menu-quick-actions",className:`main-menu-quick-actions absolute right-3 z-40 flex flex-col items-end transition-all ${e?"top-[76px] gap-1":"top-24 gap-2 md:right-6"}`,children:[e&&p.jsx(_u,{onClick:()=>rs(!0),hasUnread:wc,label:Fe.announcementTitle||"Announcements"}),!e&&p.jsx("details",{className:"group relative",children:p.jsx("summary",{className:"flex h-11 w-11 cursor-pointer list-none items-center justify-center rounded-xl border border-white/70 bg-white/80 text-[#40586a] shadow-sm","aria-label":W==="zh"?"更多快捷入口":"More shortcuts",children:p.jsx(vh,{size:20})})}),p.jsxs("button",{type:"button",onClick:()=>Ue(D.MEMBERSHIP),className:"group relative flex items-center justify-center w-11 h-11 md:w-12 md:h-12 bg-white/70 backdrop-blur-md rounded-full shadow-sm border border-pink-200 hover:bg-white/90 hover:border-amber-300 transition-all hover:scale-110 active:scale-95","aria-label":W==="zh"?"会员":"Membership",children:[p.jsx(Lh,{className:"text-amber-500 group-hover:text-amber-600 transition-colors",size:20,strokeWidth:2.8}),p.jsxs("div",{className:"quick-action-hint absolute top-full left-1/2 mt-3 -translate-x-1/2 px-2 py-1 bg-white border-2 border-amber-400 text-slate-900 text-[13px] font-extrabold rounded-xl opacity-0 group-hover:opacity-100 pointer-events-none transition-all whitespace-nowrap hidden md:block shadow-lg",children:[p.jsx("div",{className:"quick-action-hint-arrow quick-action-hint-arrow-amber absolute top-0 left-1/2 -translate-x-1/2 -translate-y-full w-0 h-0 border-l-[7px] border-r-[7px] border-b-[7px] border-l-transparent border-r-transparent border-b-amber-400"}),"VIP"]})]}),p.jsxs("button",{type:"button",onClick:()=>nc(!0),className:"group relative flex items-center justify-center w-11 h-11 md:w-12 md:h-12 bg-white/70 backdrop-blur-md rounded-full shadow-sm border border-pink-200 hover:bg-white/90 hover:border-pink-300 transition-all hover:scale-110 active:scale-95","aria-label":Fe.downloads||Fe.mobileApkDownload||"Downloads",children:[p.jsx(kh,{className:"text-pink-400 group-hover:text-pink-500 transition-colors",size:20}),p.jsxs("div",{className:"quick-action-hint absolute top-full left-1/2 mt-3 translate-x-[-75%] px-2 py-1 bg-white border-2 border-amber-400 text-slate-900 text-[13px] font-extrabold rounded-xl opacity-0 group-hover:opacity-100 pointer-events-none transition-all whitespace-nowrap hidden md:block shadow-lg",children:[p.jsx("div",{className:"quick-action-hint-arrow quick-action-hint-arrow-amber absolute top-0 left-[75%] -translate-y-full w-0 h-0 border-l-[7px] border-r-[7px] border-b-[7px] border-l-transparent border-r-transparent border-b-amber-400"}),ai==="native-app"?Fe.mobileNativeAppTitle||"App":ai==="pwa"?Fe.mobilePwaAppTitle||"App":Fe.downloads||Fe.mobileApkDownload||"Downloads"]})]}),p.jsxs("button",{type:"button",onClick:()=>Ue(D.STUDY_ROOM),className:"group relative flex items-center justify-center w-11 h-11 md:w-12 md:h-12 bg-white/70 backdrop-blur-md rounded-full shadow-sm border border-pink-200 hover:bg-white/90 hover:border-[#FB7299] transition-all hover:scale-110 active:scale-95","aria-label":Fe.studyRoom||"自习室",children:[p.jsx(nu,{className:"text-[#FB7299] group-hover:text-[#e85f88] transition-colors",size:20}),p.jsxs("div",{className:"quick-action-hint absolute top-full left-1/2 mt-3 translate-x-[-25%] px-2 py-1 bg-white border-2 border-[#FB7299] text-slate-900 text-[13px] font-extrabold rounded-xl opacity-0 group-hover:opacity-100 pointer-events-none transition-all whitespace-nowrap hidden md:block shadow-lg",children:[p.jsx("div",{className:"quick-action-hint-arrow quick-action-hint-arrow-live absolute top-0 left-[25%] -translate-y-full w-0 h-0 border-l-[7px] border-r-[7px] border-b-[7px] border-l-transparent border-r-transparent border-b-[#FB7299]"}),Fe.studyRoom||"自习室"]})]}),p.jsxs("button",{type:"button",onClick:Nf,className:"group relative flex items-center justify-center w-11 h-11 md:w-12 md:h-12 bg-white/70 backdrop-blur-md rounded-full shadow-sm border border-pink-200 hover:bg-white/90 hover:border-pink-300 transition-all hover:scale-110 active:scale-95","aria-label":"Steam",children:[p.jsx("div",{className:"w-6 h-6 rounded-full bg-[#1b2838] group-hover:bg-[#2a475e] flex items-center justify-center shadow-sm transition-colors",children:p.jsx("img",{src:lp,alt:"Steam",className:"w-3 h-3 object-contain"})}),p.jsxs("div",{className:"quick-action-hint absolute top-full left-1/2 mt-3 -translate-x-1/2 px-2 py-1 bg-white border-2 border-sky-400 text-slate-900 text-[13px] font-extrabold rounded-xl opacity-0 group-hover:opacity-100 pointer-events-none transition-all whitespace-nowrap hidden md:block shadow-lg",children:[p.jsx("div",{className:"quick-action-hint-arrow quick-action-hint-arrow-sky absolute top-0 left-1/2 -translate-x-1/2 -translate-y-full w-0 h-0 border-l-[7px] border-r-[7px] border-b-[7px] border-l-transparent border-r-transparent border-b-sky-400"}),"Steam"]})]})]}),p.jsx(Tp,{isOpen:Nm,onClose:Om,language:W}),p.jsx(gp,{isOpen:zn,onClose:()=>Wn(!1),bgmVolume:zr,setBgmVolume:Zf,voiceVolume:la,setVoiceVolume:em,textSpeed:$n,setTextSpeed:nm,dialogueFontScale:qn,setDialogueFontScale:sm,gameUiPreset:Ga,setGameUiPreset:im,isMembershipActive:Ac===!0,isMembershipStatusLoading:om,onOpenMembership:()=>{Wn(!1),Ue(D.MEMBERSHIP)},autoAdvanceDelayMs:Kn,setAutoAdvanceDelayMs:cm,autoAdvanceByVoice:Xn,setAutoAdvanceByVoice:um,language:W,setLanguage:Pf,outputLanguage:mt,setOutputLanguage:lm,voiceLanguage:Jn,setVoiceLanguage:dm,playerNickname:ht,setPlayerNickname:yc,paperPreferences:Zn,setPaperPreferences:mm,storyQuestionArchiveEnabled:St.enabled,setStoryQuestionArchiveEnabled:St.setEnabled,bgmUrl:br,setBgmUrl:rm,customBgms:Yn,setCustomBgms:fi})]})]})]})};class hA extends _a.Component{constructor(){super(...arguments),this.state={hasError:!1,error:null,errorInfo:null,copied:!1,errorId:null}}static getDerivedStateFromError(t){return{hasError:!0,error:t}}componentDidCatch(t,r){console.error("Uncaught error:",t,r),this.setState({errorInfo:r}),Cs(t,{boundary:"ErrorBoundary",componentStack:(r==null?void 0:r.componentStack)||""},{category:"frontend",source:"error_boundary"}).then(a=>{this.setState({errorId:a})})}
327render(){if(this.state.hasError){const{errorId:t,copied:r}=this.state;return p.jsx("div",{style:{position:"fixed",top:0,left:0,right:0,bottom:0,display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",backgroundColor:"rgba(0, 0, 0, 0.9)",backdropFilter:"blur(10px)",color:"#ffffff",fontFamily:'"Quicksand", "LXGW WenKai", "Noto Sans SC", -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", "Microsoft YaHei", sans-serif',zIndex:9999,padding:"20px",textAlign:"center"},children:p.jsxs("div",{style:{background:"rgba(255, 255, 255, 0.05)",padding:"40px",borderRadius:"20px",border:"1px solid rgba(255, 255, 255, 0.1)",boxShadow:"0 8px 32px 0 rgba(0, 0, 0, 0.37)",maxWidth:"500px",width:"100%"},children:[p.jsx("h2",{style:{fontSize:"1.8rem",marginBottom:"1rem",color:"#ff6b6b",fontWeight:600},children:"哎呀,出错了"}),p.jsx("p",{style:{fontSize:"1.1rem",color:"#cccccc",marginBottom:"2rem",lineHeight:"1.5"},children:"我们遇到了一些意料之外的错误。你可以尝试刷新页面;如果问题持续存在,请复制错误编号发给作者排查。"}),p.jsx("div",{style:{textAlign:"left",background:"rgba(255, 255, 255, 0.06)",border:"1px solid rgba(255, 255, 255, 0.12)",borderRadius:"14px",padding:"12px 14px",marginBottom:"16px"},children:p.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",gap:"10px"},children:[p.jsxs("div",{children:[p.jsx("div",{style:{fontSize:"0.78rem",color:"#bbbbbb",marginBottom:"4px"},children:"错误编号"}),p.jsx("div",{style:{fontFamily:"ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace",color:"#ffffff",fontWeight:700},children:t||"记录中..."})]}),p.jsx("button",{disabled:!t,onClick:async()=>{if(t)try{await navigator.clipboard.writeText(t),this.setState({copied:!0}),window.setTimeout(()=>this.setState({copied:!1}),1500)}catch{}},style:{padding:"8px 12px",fontSize:"0.85rem",backgroundColor:r?"#16a34a":"rgba(255, 255, 255, 0.15)",color:"#ffffff",border:"1px solid rgba(255, 255, 255, 0.18)",borderRadius:"10px",cursor:t?"pointer":"not-allowed",fontWeight:700,opacity:t?1:.6},children:r?"已复制":"复制编号"})]})}),p.jsx("button",{onClick:()=>window.location.reload(),style:{padding:"12px 30px",fontSize:"1rem",backgroundColor:"#ffffff",color:"#000000",border:"none",borderRadius:"50px",cursor:"pointer",fontWeight:"600",transition:"transform 0.2s",boxShadow:"0 4px 15px rgba(255, 255, 255, 0.1)"},onMouseOver:a=>a.currentTarget.style.transform="scale(1.05)",onMouseOut:a=>a.currentTarget.style.transform="scale(1)",children:"刷新页面"})]})})}return this.props.children}}typeof window<"u"&&(window.addEventListener("error",e=>{Cs(e.error||e.message,{filename:e.filename,lineno:e.lineno,colno:e.colno},{category:"frontend",source:"window_error"})}),window.addEventListener("unhandledrejection",e=>{Cs(e.reason||"Unhandled promise rejection",{},{category:"frontend",source:"unhandled_rejection"})}));const bf=document.getElementById("root");if(!bf)throw new Error("Could not find root element to mount to");const pA=ih.createRoot(bf);pA.render(p.jsx(_a.StrictMode,{children:p.jsx(hA,{children:p.jsx(A0,{children:p.jsx(mA,{})})})}));export{ta as $,RA as A,nr as B,v0 as C,_A as D,lt as E,Rn as F,vA as G,$A as H,XA as I,wa as J,qA as K,QA as L,YA as M,sd as N,Rg as O,GA as P,WA as Q,Bi as R,UA as S,He as T,ZA as U,ql as V,Ea as W,xg as X,JA as Y,KA as Z,Be as _,gg as a,zA as a0,ke as a1,BA as a2,ed as a3,FA as a4,jA as a5,VA as a6,HA as a7,eI as a8,Qo as a9,Ln as aa,Dr as ab,Yo as ac,rf as ad,tI as ae,rI as af,_o as ag,Vp as ah,Ns as ai,V0 as aj,wA as b,OA as c,PA as d,NA as e,I0 as f,xA as g,pa as h,CA as i,vi as j,M0 as k,st as l,Ui as m,kA as n,DA as o,LA as p,MA as q,sn as r,W0 as s,hu as t,Io as u,bs as v,Td as w,Pr as x,_t as y,Z0 as z};

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.