@heybox/hb-sdk 0.9.9-alpha.4 → 0.9.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/CHANGELOG.md +32 -0
  2. package/dist/cli-chunks/{build-BJ3OdlOf.cjs → build-CqtqZ23J.cjs} +4 -4
  3. package/dist/cli-chunks/{create-Nnriz1g8.cjs → create-DgWmJwpT.cjs} +1 -1
  4. package/dist/cli-chunks/{dev-fCGFdByu.cjs → dev-puM5fyUz.cjs} +16785 -15512
  5. package/dist/cli-chunks/{doctor-Dka35I4J.cjs → doctor-uvy4wUfq.cjs} +1 -1
  6. package/dist/cli-chunks/{game-binding-guide-74xdBeSz.cjs → game-binding-guide-C7MKLid5.cjs} +2 -2
  7. package/dist/cli-chunks/{game-bindings-Bn9K3b-V.cjs → game-bindings-ECpuE1hY.cjs} +3 -3
  8. package/dist/cli-chunks/{games-CJd7dnrn.cjs → games-CGMhM4Ls.cjs} +1 -1
  9. package/dist/cli-chunks/{index-C0e35S9F.cjs → index-DysLYcsL.cjs} +479 -21
  10. package/dist/cli-chunks/{index-BXVwHHJK.cjs → index-Oyj4VUom.cjs} +1 -1
  11. package/dist/cli-chunks/{index.esm-BXwlM8dI.cjs → index.esm-BcS7pyg5.cjs} +11 -11
  12. package/dist/cli-chunks/{login-BnQ61BTt.cjs → login-CgHgJ9Pq.cjs} +1 -1
  13. package/dist/cli-chunks/{project-vite-o_omhA5m.cjs → project-vite-Y9KUipBC.cjs} +1 -1
  14. package/dist/cli-chunks/{remote-IrbvALD1.cjs → remote-Ctx8U3BD.cjs} +942 -837
  15. package/dist/cli-chunks/{runtime-permission-env-B8cFtlhN.cjs → runtime-permission-env-Q4zSDBpm.cjs} +3 -2
  16. package/dist/cli-chunks/{skill-BgrvLAJa.cjs → skill-q-rmEGex.cjs} +2 -2
  17. package/dist/cli-chunks/{version-BDrKYZTU.cjs → version-BlcBgXzK.cjs} +1 -1
  18. package/dist/cli.cjs +1 -1
  19. package/dist/devtools/browser-dev-host/assets/browser-dev-host-dcCcXSgR.js +224 -0
  20. package/dist/devtools/browser-dev-host/assets/desktop-app-launch-BkP-ubPn.js +6 -0
  21. package/dist/devtools/browser-dev-host/assets/index-870cPYsT.css +1 -0
  22. package/dist/devtools/browser-dev-host/assets/index-CulhbtOT.js +574 -0
  23. package/dist/devtools/browser-dev-host/assets/pc-onboarding-example-BS3sevnG.webp +0 -0
  24. package/dist/devtools/browser-dev-host/index.html +3 -3
  25. package/dist/index.cjs.js +1 -1
  26. package/dist/index.esm.js +1 -1
  27. package/dist/vite.cjs.js +16 -8
  28. package/dist/vite.esm.js +16 -8
  29. package/package.json +6 -5
  30. package/skill/SKILL.md +7 -0
  31. package/skill/skill.json +5 -5
  32. package/types/vite/index.d.ts +2 -0
  33. package/dist/devtools/browser-dev-host/assets/browser-dev-host-CRAx6EPL.js +0 -224
  34. package/dist/devtools/browser-dev-host/assets/desktop-app-launch-hnNxdeA6.js +0 -13
  35. package/dist/devtools/browser-dev-host/assets/index-C5kOabQa.js +0 -567
  36. package/dist/devtools/browser-dev-host/assets/index-D0XGMYIr.css +0 -1
@@ -0,0 +1,224 @@
1
+ import{m as Im,H as Hc,a_ as bm,bA as ym,a3 as Nm,bh as wm,bi as Dm,n as wt,bK as ee,ba as cl,l as ul,aM as Sm,e as Fc,aR as Om,aD as Mm,k as Cm,aN as Rm,bE as mn,aY as Vn,aX as io,aZ as ki,b2 as dl,b4 as Lm,f as Wi,v as Pm,ap as $i,Z as Jo,aQ as vm,j as so,at as ao,h as km,be as ll,aI as xm,G as Um,b0 as fl,U as Bm,z as Hm,aF as Fm,y as zm,bb as jm,bC as hl,bB as ml,b6 as Vm,g as oo,aH as Gm,b as Er,c as Ym}from"./desktop-app-launch-BkP-ubPn.js";function Qm(){return{targetId:"ui-preview-target",ownerId:"ui-preview-owner",adapterId:"browser-dev-host",kind:"browser",capabilities:{storage:!0,presentation:!0,sandboxList:!0,sandboxRead:!0},state:"attached",currentInstanceId:"ui-preview-instance",cdpTargetId:"ui-preview-browser-target",metadata:{displayName:"UI 预览(模拟)",browser:"Chrome",os:"macOS"},updatedAt:Date.now(),stale:!1}}function qm(){return[{key:"network",label:"网络请求",state:"approved",facts:{platformApproval:!0,temporary:!1,effective:!0,online:"enabled"}},{key:"companion",label:"桌面辅助应用",state:"temporary",facts:{platformApproval:!1,temporary:!0,effective:!0,online:"disabled"},releaseDifference:"发布前需要获得平台批准。"},{key:"network.useOfficialDomain",label:"官方域名",state:"unavailable",facts:{platformApproval:!1,temporary:!1,effective:!1,online:"disabled"},reason:"不支持本地临时授权,获得平台批准后才能使用。"}]}const Ti={device:'[data-preview-target="device"]',screen:'[data-preview-target="screen"]',app:"#device iframe",workbench:'[data-testid="workbench-root"]'},zc=15e3,Wm=32*1024*1024,jc="data-hb-preview-capture-device",wa="data-hb-preview-capture-ancestor",Vc="data-hb-preview-capture-surface",Gc=64,$m=1024;function Km(e={}){const t=e.document??globalThis.document,r=t.defaultView,n=e.leaseMs??zc;if(!Number.isFinite(n)||n<=0||n>zc)throw tt("INVALID_CAPTURE_LEASE","截图租约无效");let i;function s(d,l,h){d.attributes.push({element:l,name:h,previous:l.getAttribute(h)}),l.setAttribute(h,d.token)}function a(d){const l=i;if(!l||l.token!==d)return!1;const h=c(l),f=!!l.style?.isConnected;i=void 0,clearTimeout(l.timer),l.removeAbort?.(),l.removeResize?.(),l.observer?.disconnect(),l.style?.remove(),l.bounds?.remove();for(const{element:p,name:g,previous:b}of l.attributes)p.getAttribute(g)===d&&(b===null?p.removeAttribute(g):p.setAttribute(g,b));return l.overlay.remove(),f&&(r.scrollX!==l.scroll.x||r.scrollY!==l.scroll.y)&&r.scrollTo(l.scroll.x,l.scroll.y),h}function c(d){const{viewport:l,target:h,rect:f}=d;if(!h?.isConnected||!f||Date.now()>=d.expiresAt||r.innerWidth!==l.width||r.innerHeight!==l.height||r.devicePixelRatio!==l.devicePixelRatio)return!1;const p=h.getBoundingClientRect();return["left","top","width","height"].every(g=>Math.abs(p[g]-f[g])<.01)}async function u(d,l){if(l?.throwIfAborted(),!Number.isFinite(d.deadlineAt)||Date.now()>=d.deadlineAt)throw tt("PREVIEW_TIMEOUT","截图操作已超时");if(d.scope==="workbench"||!Object.hasOwn(Ti,d.scope))throw tt("INVALID_CAPTURE_SCOPE","设备像素截图仅支持 device、screen 或 app");if(!d.operationId||d.operationId.length>128)throw tt("INVALID_OPERATION","截图操作标识无效");if(!d.previewImage.startsWith("data:image/png;base64,")||d.previewImage.length>Wm)throw tt("INVALID_CAPTURE_IMAGE","共享窗口冻结图无效或过大");if(i)throw tt("PREVIEW_BUSY","已有设备截图正在执行");const h=t.querySelectorAll(Ti.device);if(h.length!==1)throw tt("DEVICE_NOT_UNIQUE","设备画面不唯一或尚未创建");const f=h[0],p=d.scope==="device"?f:t.querySelector(Ti[d.scope]);if(!p||p!==f&&!f.contains(p))throw tt("CAPTURE_TARGET_UNAVAILABLE","截图内容尚未创建");const g=f.getBoundingClientRect();if(!(g.width>0&&g.height>0))throw tt("CAPTURE_TARGET_UNAVAILABLE","设备画面当前不可见");const b=t.createElement("img");b.alt="",b.setAttribute("aria-hidden","true"),b.setAttribute("data-hb-preview-capture-freeze",""),b.style.cssText=`position:fixed;left:0;top:0;width:${r.innerWidth}px;height:${r.innerHeight}px;max-width:none;max-height:none;margin:0;border:0;padding:0;z-index:2147483647;pointer-events:auto;user-select:none;`,b.addEventListener("wheel",Y=>Y.preventDefault(),{passive:!1}),b.addEventListener("touchmove",Y=>Y.preventDefault(),{passive:!1});const y=Math.min(Date.now()+n,d.deadlineAt),N={operationId:d.operationId,token:r.crypto.randomUUID(),overlay:b,attributes:[],scroll:{x:r.scrollX,y:r.scrollY},viewport:{width:r.innerWidth,height:r.innerHeight,devicePixelRatio:r.devicePixelRatio},expiresAt:y};i=N,N.timer=setTimeout(()=>a(N.token),Math.max(0,y-Date.now()));const C=()=>a(N.token);l?.addEventListener("abort",C,{once:!0}),N.removeAbort=()=>l?.removeEventListener("abort",C);const I=()=>{const{viewport:Y}=N;(r.innerWidth!==Y.width||r.innerHeight!==Y.height||r.devicePixelRatio!==Y.devicePixelRatio)&&a(N.token)};r.addEventListener("resize",I),N.removeResize=()=>r.removeEventListener("resize",I);const U=()=>{if(l?.throwIfAborted(),i!==N||Date.now()>=y)throw tt("CAPTURE_EXPIRED","截图布局租约已结束,请重新截图")};try{b.src=d.previewImage,await b.decode(),U();const Y=N.token,R=`[${jc}="${Y}"]`,P=r.getComputedStyle(f),M=new r.DOMMatrixReadOnly(P.transform==="none"?void 0:P.transform),V=Math.atan2(M.b,M.a),z=f.querySelector(".desktop-window__surface"),te=z?z.offsetWidth:Number.parseFloat(P.width),x=z?z.offsetHeight:Number.parseFloat(P.height),Q=P.backgroundColor,j=r.getComputedStyle(t.body).backgroundColor,H=ye=>!ye||ye==="transparent"||ye==="rgba(0, 0, 0, 0)",F=H(Q)?H(j)?"#fff":j:Q;if(!(te>0&&x>0))throw tt("CAPTURE_TARGET_UNAVAILABLE","设备布局尺寸无效");U(),t.body.append(b),s(N,f,jc),z&&s(N,z,Vc);for(let ye=f.parentElement;ye;ye=ye.parentElement)s(N,ye,wa);const v=t.createElement("style");N.style=v;const L=`
2
+ [${wa}="${Y}"] {overflow:visible!important;scrollbar-width:none!important;}
3
+ [${wa}="${Y}"]::-webkit-scrollbar {display:none!important;}
4
+ [${Vc}="${Y}"] {transform:none!important;transition:none!important;}
5
+ `,q=(ye,ve,Pe=0,He=0)=>`${R} {position:absolute!important;left:${ye}px!important;top:${ve}px!important;width:${te}px!important;height:${x}px!important;transform:translate(${Pe}px,${He}px) rotate(${V}rad)!important;transition:none!important;z-index:2147483646!important;background-color:${F}!important;}`;v.textContent=L+q(0,0),U(),t.head.append(v);const D=f.getBoundingClientRect(),W=t.querySelector(Ti.app),$=W&&f.contains(W)?W.getBoundingClientRect():void 0,m=$&&$.width>0&&$.height>0?$:void 0,w=m?Math.floor(r.innerWidth-1-(m.left-D.left)):r.innerWidth+64,B=m?Math.floor(r.innerHeight-1-(m.top-D.top)):32,K=w-D.left,ce=B-D.top;U(),v.textContent=L+q(K,ce);const pe=f.getBoundingClientRect();v.textContent=L+q(K,ce,w-pe.left,B-pe.top),U();const ue=p.getBoundingClientRect(),Te=Math.floor(Lr(ue.left+r.scrollX)),we=Math.floor(Lr(ue.top+r.scrollY)),Ae={x:Te,y:we,width:Math.ceil(Lr(ue.right+r.scrollX))-Te,height:Math.ceil(Lr(ue.bottom+r.scrollY))-we};if(!(Ae.width>0&&Ae.height>0)||Ae.x<0||Ae.y<0)throw tt("CAPTURE_LAYOUT_INVALID","无法建立完整设备截图布局");if(m&&W){const ye=W.getBoundingClientRect();if(!(ye.left<r.innerWidth&&ye.top<r.innerHeight&&ye.right>0&&ye.bottom>0))throw tt("CAPTURE_LAYOUT_INVALID","无法保持 iframe 的最小绘制区域");const ve=f.getBoundingClientRect(),Pe=Math.floor(Lr(ve.left))-1,He=Math.floor(Lr(ve.top))-1,Ve=r.innerWidth-Pe,cr=r.innerHeight-He;if(Pe<0||He<0||Ve<=0||cr<=0||Ve>Gc||cr>Gc||Ve*cr>$m)throw tt("CAPTURE_LAYOUT_INVALID","无法在有界角部保持完整设备绘制,请改用 --scale css");b.style.clipPath=`polygon(0 0,100% 0,100% ${He}px,${Pe}px ${He}px,${Pe}px 100%,0 100%)`,b.setAttribute("data-hb-preview-capture-corner",JSON.stringify({x:Pe,y:He,width:Ve,height:cr}))}const Ie=t.createElement("div");if(Ie.setAttribute("aria-hidden","true"),Ie.style.cssText=`position:absolute;left:${Ae.x+Ae.width+2}px;top:${Ae.y+Ae.height+2}px;width:1px;height:1px;pointer-events:none;opacity:0;`,N.bounds=Ie,U(),t.body.append(Ie),N.target=p,N.rect=ue,await Zm(r,l),U(),!c(N))throw tt("CAPTURE_LAYOUT_INVALID","截图准备期间布局发生变化,请重新截图");N.observer=new r.ResizeObserver(()=>{i===N&&!c(N)&&a(N.token)});for(const{element:ye}of N.attributes)N.observer.observe(ye);return{token:Y,clip:Ae,devicePixelRatio:r.devicePixelRatio,expiresAt:y}}catch(Y){throw a(N.token),Y}}return{prepare:u,restore:a,cancel:d=>i?.operationId!==d?!1:(a(i.token),!0),dispose:()=>{i&&a(i.token)}}}function Zm(e,t){return new Promise((r,n)=>{let i=e.requestAnimationFrame(()=>{i=e.requestAnimationFrame(a)});const s=()=>{e.cancelAnimationFrame(i),t?.removeEventListener("abort",s),n(t?.reason)};function a(){t?.removeEventListener("abort",s),r()}t?.addEventListener("abort",s,{once:!0}),t?.aborted&&s()})}function tt(e,t){return Object.assign(new Error(t),{name:"PreviewError",code:e})}function Lr(e){const t=Math.round(e);return Math.abs(e-t)<.001?t:e}const Zs=["post.get","post.comments.list","post.watch"],Gn=["post.setLiked","post.setFavorited","post.comments.openEditor","post.comments.delete","post.comments.setLiked"],ec="user.games.getOverview",Ki="user.data.query",Rn="user.data.sync",Zi="user.data.file",tc="user.dataPermission.request",rc="user.dataPermission.get",nc="user.dataPermission.set",ic="user.dataPermission.openSettings",sc="user.dataPermission.revokeSession",El=[ec,Ki,Rn,Zi,tc,rc,nc,ic,sc],Xi="workspaceCards.requestRefresh",Ji="auth.getAccountState",es="auth.login",ts="user.getFollowStatus",rs="user.requestFollowAuthor",Xm="gameSaves.list",Jm="gameSaves.sync",e0="gameSaves.getFile",t0="gameSaves.readParsedData",ns="user.getInfo",is="user.revokeAuthorization",ss="user.getSteamGameList",Yn="user.showAppreciation",as="share.copyLink",os="share.showShareMenu",cs="share.screenshot",us="share.screenshotLong",wr="viewport.setDisplay",ds="viewport.getWindowInfo",ls="viewport.setNavigationBarStyle",Qn="storage.getStorage",qn="storage.setStorage",fs="network.request",hs="network.download",ms="network.upload",Es="files.pickFiles",gs="files.pickDirectory",ps="files.saveFile",Wn="file.create",$n="file.remove",Ts="file.exists",Kn="file.readText",_s="file.writeText",Zn="file.readBytes",As="file.writeBytes",Xn="file.stat",Is="directory.create",Jn="directory.remove",bs="directory.exists",ys="directory.list",ei="media.pick",Ns="ui.showToast",ws="ui.showLoading",Ds="ui.hideLoading",Ss="device.vibrate",Os="device.setClipboard",Ms="device.executeProtocol",Cs="navigation.close",Rs="navigation.reload",Ls="navigation.openAppPage",Yt="cloud.leaderboard.submit",Nt="cloud.leaderboard.getList",nr="cloud.leaderboard.getCurrentUserEntry",Dr="cloud.leaderboard.deleteCurrentUserEntry",xt="cloud.leaderboard.getInfo",$r="cloud.storage.getStorage",Kr="cloud.storage.setStorage",Zr="cloud.storage.removeItem",Sr="cloud.storage.getKeys",Xs="companion.getInfo",Js="companion.getPreparationStatus",ea="companion.prepare",ta="companion.cancelPreparation",ra="companion.getActiveSession",na="companion.launch",ia="companion.session.write",sa="companion.session.closeStdin",aa="companion.session.terminate",oa="companion.session.ackOutput",ca="companion.openAttachment",ua="companion.showNotification",ir=[...Zs.map(e=>({method:e,module:"post",capability:e,requirement:{kind:"all",permissions:["post"]},risk:"medium"})),...Gn.map(e=>({method:e,module:"post",capability:e,requirement:{kind:"all",permissions:["post"]},risk:"high"})),...[Xm,Jm,e0,t0].map(e=>({method:e,module:"gameSaves",capability:e,requirement:{kind:"all",permissions:["gameSaves"]},risk:"high"})),...El.map(e=>({method:e,module:"userGameData",capability:e,requirement:{kind:"all",permissions:["user_game_data"]},risk:"high"})),{method:Xi,module:"workspaceCards",capability:Xi,requirement:{kind:"all",permissions:["workspaceCards"]},risk:"high"},{method:Ji,module:"auth",capability:Ji,requirement:{kind:"none"},risk:"low"},{method:es,module:"auth",capability:es,requirement:{kind:"all",permissions:["userInfo"]},risk:"medium"},{method:ts,module:"user",capability:ts,requirement:{kind:"none"},risk:"low"},{method:rs,module:"user",capability:rs,requirement:{kind:"none"},risk:"high"},{method:ns,module:"user",capability:ns,requirement:{kind:"all",permissions:["userInfo"]},risk:"medium"},{method:is,module:"user",capability:is,requirement:{kind:"none"},risk:"high"},{method:ss,module:"user",capability:ss,requirement:{kind:"all",permissions:["steamLibrary"]},risk:"high"},{method:Yn,module:"user",capability:Yn,requirement:{kind:"none"},risk:"medium"},{method:as,module:"share",capability:as,requirement:{kind:"all",permissions:["share"]},risk:"medium"},{method:os,module:"share",capability:os,requirement:{kind:"all",permissions:["share"]},risk:"low"},{method:cs,module:"share",capability:cs,requirement:{kind:"all",permissions:["share"]},risk:"medium"},{method:us,module:"share",capability:us,requirement:{kind:"all",permissions:["share"]},risk:"medium"},{method:ds,module:"viewport",capability:ds,requirement:{kind:"none"},risk:"low"},{method:ls,module:"viewport",capability:ls,requirement:{kind:"none"},risk:"low"},{method:wr,module:"viewport",capability:wr,requirement:{kind:"none"},risk:"low"},{method:Qn,module:"storage",capability:Qn,requirement:{kind:"all",permissions:["storage"]},risk:"low"},{method:qn,module:"storage",capability:qn,requirement:{kind:"all",permissions:["storage"]},risk:"medium"},{method:fs,module:"network",capability:fs,requirement:{kind:"all",permissions:["network"]},risk:"high"},{method:hs,module:"network",capability:hs,requirement:{kind:"all",permissions:["network","filesystem"]},risk:"high"},{method:ms,module:"network",capability:ms,requirement:{kind:"all",permissions:["network","filesystem"]},risk:"high"},{method:Es,module:"files",capability:Es,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:gs,module:"files",capability:gs,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:ps,module:"files",capability:ps,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Wn,module:"file",capability:Wn,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:$n,module:"file",capability:$n,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Ts,module:"file",capability:Ts,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Kn,module:"file",capability:Kn,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:_s,module:"file",capability:_s,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Zn,module:"file",capability:Zn,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:As,module:"file",capability:As,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Xn,module:"file",capability:Xn,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Is,module:"directory",capability:Is,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Jn,module:"directory",capability:Jn,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:bs,module:"directory",capability:bs,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:ys,module:"directory",capability:ys,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:ei,module:"media",capability:ei,requirement:{kind:"all",permissions:["media"]},risk:"high"},{method:Ns,module:"ui",capability:Ns,requirement:{kind:"none"},risk:"low"},{method:ws,module:"ui",capability:ws,requirement:{kind:"none"},risk:"low"},{method:Ds,module:"ui",capability:Ds,requirement:{kind:"none"},risk:"low"},{method:Ss,module:"device",capability:Ss,requirement:{kind:"none"},risk:"low"},{method:Os,module:"device",capability:Os,requirement:{kind:"all",permissions:["clipboard"]},risk:"medium"},{method:Ms,module:"device",capability:Ms,requirement:{kind:"all",permissions:["appProtocol"]},risk:"high"},{method:Cs,module:"navigation",capability:Cs,requirement:{kind:"none"},risk:"medium"},{method:Rs,module:"navigation",capability:Rs,requirement:{kind:"none"},risk:"medium"},{method:Ls,module:"navigation",capability:Ls,requirement:{kind:"none"},risk:"medium"},{method:Yt,module:"cloud",capability:Yt,requirement:{kind:"all",permissions:["leaderboard"]},risk:"medium"},{method:Nt,module:"cloud",capability:Nt,requirement:{kind:"all",permissions:["leaderboard"]},risk:"low"},{method:nr,module:"cloud",capability:nr,requirement:{kind:"all",permissions:["leaderboard"]},risk:"medium"},{method:Dr,module:"cloud",capability:Dr,requirement:{kind:"all",permissions:["leaderboard"]},risk:"medium"},{method:xt,module:"cloud",capability:xt,requirement:{kind:"all",permissions:["leaderboard"]},risk:"low"},{method:$r,module:"cloud",capability:$r,requirement:{kind:"all",permissions:["cloud_storage"]},risk:"low"},{method:Kr,module:"cloud",capability:Kr,requirement:{kind:"all",permissions:["cloud_storage"]},risk:"medium"},{method:Zr,module:"cloud",capability:Zr,requirement:{kind:"all",permissions:["cloud_storage"]},risk:"medium"},{method:Sr,module:"cloud",capability:Sr,requirement:{kind:"all",permissions:["cloud_storage"]},risk:"low"},...[Xs,Js,ea,ta,ra,na,ia,sa,aa,oa,ca,ua].map(e=>({method:e,module:"companion",capability:e,requirement:{kind:"all",permissions:["companion"]},risk:"high"}))],lr="heybox:miniprogram",gl=2,pl="hb_mini_bridge_nonce",Tl="sdk.handshake",_i="runtime.location.probe",r0="sdk.location.report",n0="sdk.csp.violation",_l="operation.progress",i0="companion.session.output",s0="companion.session.exit",a0="companion.session.ownershipLost";function o0(e){return!It(e)||e.namespace!==lr||e.version!==1&&e.version!==2||!je(e.nonce)?!1:e.type==="handshake"?je(e.id)&&e.method===Tl&&e.error===void 0&&E0(e.payload):e.type==="request"?je(e.id)&&je(e.method)&&e.error===void 0:e.type==="response"?je(e.id)&&(e.method===void 0||je(e.method))&&(e.error===void 0||g0(e.error)):e.type==="event"?!je(e.method)||e.error!==void 0?!1:e.method===_l?e.version===2&&je(e.id)&&m0(e.payload):e.id===void 0||je(e.id):e.type==="cancel"?e.version===2&&je(e.id)&&e.method===void 0&&e.payload===void 0&&e.error===void 0:!1}function ac(e){return typeof e!="string"||!e||e.startsWith("/")||e.endsWith("/")||/[\\\u0000-\u001f\u007f]/.test(e)?!1:e.split("/").every(t=>!!t&&t!=="."&&t!=="..")}function Al(e){return It(e)?e.kind==="sandbox"?ht(e,["kind"]):e.kind==="directory"&&je(e.handleId)&&ht(e,["kind","handleId"]):!1}function Ir(e){return!It(e)||e.kind!=="file"?!1:je(e.handleId)?ht(e,["kind","handleId"]):Al(e.root)&&ac(e.relativePath)&&ht(e,["kind","root","relativePath"])}function Il(e){return!It(e)||e.kind!=="directory"?!1:je(e.handleId)?ht(e,["kind","handleId"]):Al(e.root)&&(e.relativePath==="."||ac(e.relativePath))&&ht(e,["kind","root","relativePath"])}function c0(e){return It(e)&&e.kind==="file"&&je(e.name)&&p0(e.mode)&&Ir(e.ref)&&ht(e,["kind","name","mode","ref"])}const bl=20,Yc=["type","mimeType","size","width","height","previewUrl","file"];function u0(e){return e===void 0?!0:!(!It(e)||!ht(e,["source","mediaType","maxCount"])||e.source!==void 0&&e.source!=="album"&&e.source!=="camera"||e.mediaType!==void 0&&e.mediaType!=="image"&&e.mediaType!=="video"&&e.mediaType!=="all"||e.maxCount!==void 0&&(!T0(e.maxCount,1,bl)||e.source==="camera"&&e.maxCount!==1))}function yl(e){if(!It(e)||e.type!=="image"&&e.type!=="video")return!1;const t=e.type==="video";return!ht(e,t?[...Yc,"durationMs"]:Yc)||!je(e.mimeType)||!Jt(e.size)||!Qc(e.width)||!Qc(e.height)||!je(e.previewUrl)||!l0(e.file)?!1:t?Jt(e.durationMs):!0}function d0(e){if(!Array.isArray(e)||e.length<1||e.length>bl)return!1;for(let t=0;t<e.length;t+=1)if(!Object.prototype.hasOwnProperty.call(e,t)||!yl(e[t]))return!1;return!0}function l0(e){return!c0(e)||e.mode!=="read"?!1:e.ref.kind==="file"&&"handleId"in e.ref&&je(e.ref.handleId)}function Nl(e){return e instanceof Uint8Array&&e.buffer instanceof ArrayBuffer}function f0(e){return!It(e)||!Jt(e.loaded)||typeof e.lengthComputable!="boolean"||!ht(e,["loaded","total","lengthComputable"])?!1:e.lengthComputable?Jt(e.total)&&e.loaded<=e.total:e.total===void 0}function h0(e){return It(e)?e.phase==="downloading"?Jt(e.loaded)&&(e.total===void 0||Jt(e.total)&&e.loaded<=e.total)&&ht(e,["phase","loaded","total"]):e.phase!=="verifying"&&e.phase!=="extracting"?!1:Jt(e.processed)&&Jt(e.total)&&e.processed<=e.total&&ht(e,["phase","processed","total"]):!1}function m0(e){return f0(e)||h0(e)||It(e)&&ht(e,["watching"])&&e.watching===!0}function E0(e){return It(e)&&je(e.href)&&typeof e.userAgent=="string"&&je(e.sdkVersion)}function g0(e){return It(e)&&je(e.code)&&typeof e.message=="string"}function p0(e){return e==="read"||e==="readwrite"}function Jt(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function Qc(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>0}function T0(e,t,r){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=t&&e<=r}function je(e){return typeof e=="string"&&e.length>0}function ht(e,t){const r=new Set(t);return Object.keys(e).every(n=>r.has(n))}function It(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const wl={ark:"明日方舟",black_myth_wukong:"黑神话悟空",task_bar_hero:"任务栏英雄",phantom_blade_zero:"影之刃零"},Dl=Object.keys(wl),br=[{key:"game.ark.profile",game:"ark",family:"profile",name:"明日方舟角色与养成资料",disclosureRevision:1,queries:{get:{schema:"ark.profile",version:1}},sync:!1,file:!1},{key:"game.ark.gacha",game:"ark",family:"gacha",name:"明日方舟抽卡记录与分析",disclosureRevision:1,queries:{get:{schema:"ark.gacha-analysis",version:1},list:{schema:"ark.gacha-record-page",version:1,page:{defaultSize:50,maxSize:100}}},sync:!1,file:!1},{key:"game.black_myth_wukong.save_analysis",game:"black_myth_wukong",family:"save_analysis",name:"黑神话悟空存档解析结果",disclosureRevision:1,queries:{get:{schema:"black_myth_wukong.save",version:1}},sync:!0,file:!1},{key:"game.black_myth_wukong.save_files",game:"black_myth_wukong",family:"save_files",name:"黑神话悟空云存档文件",disclosureRevision:1,queries:{list:{schema:"save-file-page",version:1}},sync:!0,file:!0},{key:"game.task_bar_hero.save_analysis",game:"task_bar_hero",family:"save_analysis",name:"任务栏英雄存档解析结果",disclosureRevision:1,queries:{get:{schema:"task_bar_hero.save",version:1}},sync:!0,file:!1},{key:"game.task_bar_hero.save_files",game:"task_bar_hero",family:"save_files",name:"任务栏英雄云存档文件",disclosureRevision:1,queries:{list:{schema:"save-file-page",version:1}},sync:!0,file:!0},{key:"game.phantom_blade_zero.save_analysis",game:"phantom_blade_zero",family:"save_analysis",name:"影之刃零存档解析结果",disclosureRevision:1,queries:{get:{schema:"phantom_blade_zero.save",version:1}},sync:!0,file:!1},{key:"game.phantom_blade_zero.save_files",game:"phantom_blade_zero",family:"save_files",name:"影之刃零云存档文件",disclosureRevision:1,queries:{list:{schema:"save-file-page",version:1}},sync:!0,file:!0}],gr=br.map(e=>e.key),_0=new Set(gr),A0=new Set(Dl);function Zt(e){return _0.has(e)}function qc(e){return A0.has(e)}function oc(e){const t=br.find(i=>i.key===e);if(!t)return;const r=t.queries,n=Object.keys(r);return t.sync&&n.push("sync"),t.file&&n.push("file"),{key:t.key,game:t.game,name:t.name,family:t.family,disclosureRevision:t.disclosureRevision,queries:r,operations:n}}const I0="同步时,原始存档将上传至小黑盒;向小程序提供原始文件仍需单独许可。",Or=["userInfo","steamLibrary","share","storage","cloud_storage","gameSaves","filesystem","media","clipboard","leaderboard","network","companion","appProtocol","workspaceCards","user_game_data","post"],cc=[{key:"gameSaves",name:"游戏存档",description:"已废弃,将在 SDK 0.10.0 移除;新接入使用 user.games。",access:"declaration",risk:"high",config:{},methods:["gameSaves.list","gameSaves.sync","gameSaves.getFile","gameSaves.readParsedData"],conditions:["SDK < 0.10.0-0 保留兼容入口,保留原合同,不增加本版逐资源确认;需要有效 Steam 登录和宿主支持。"]},{key:"userInfo",name:"用户信息",description:"登录小程序并读取当前用户的授权信息。",access:"declaration",risk:"medium",config:{},methods:["auth.login","user.getInfo"],conditions:["继续执行黑盒登录、用户授权和可信手势规则。"]},{key:"steamLibrary",name:"Steam 游戏库",description:"读取当前用户授权的 Steam 游戏库。",access:"declaration",risk:"high",config:{},methods:["user.getSteamGameList"],conditions:["继续执行账号绑定和数据可用性规则。"]},{key:"share",name:"分享",description:"使用小程序分享、分享菜单和截图能力。",access:"declaration",risk:"medium",config:{},methods:["share.copyLink","share.showShareMenu","share.screenshot","share.screenshotLong"],conditions:["继续执行分享参数校验和 Host 支持检查。"]},{key:"storage",name:"键值存储",description:"读写按小程序隔离的简单键值数据。",access:"declaration",risk:"medium",config:{},methods:["storage.getStorage","storage.setStorage"],conditions:["仅用于简单键值存储,不包含文件系统。"]},{key:"cloud_storage",name:"云端存储",description:"读写按小程序和当前登录用户隔离的云端键值数据。",access:"declaration",risk:"medium",config:{},methods:["cloud.storage.getStorage","cloud.storage.setStorage","cloud.storage.removeItem","cloud.storage.getKeys"],conditions:["云端存储按登录用户隔离并受容量配额限制。"]},{key:"filesystem",name:"文件系统",description:"访问小程序沙盒文件和用户选择的外部文件。",access:"declaration",risk:"high",config:{},methods:["network.download","network.upload","files.pickFiles","files.pickDirectory","files.saveFile","file.create","file.remove","file.exists","file.readText","file.writeText","file.readBytes","file.writeBytes","file.stat","directory.create","directory.remove","directory.exists","directory.list"],conditions:["外部文件继续要求有效的用户选择、会话句柄和匹配的读写模式。"]},{key:"media",name:"媒体",description:"通过系统图库或相机选择图片、视频。",access:"declaration",risk:"high",config:{},methods:["media.pick"],conditions:["图库授权范围仅限本次用户选择的媒体,不包含任意文件或沙盒访问权;继续执行可信手势、Host 能力与会话资源规则。"]},{key:"clipboard",name:"剪贴板",description:"向系统剪贴板写入文本。",access:"declaration",risk:"medium",config:{},methods:["device.setClipboard"],conditions:["继续执行文本长度和 Host 支持限制。"]},{key:"leaderboard",name:"排行榜",description:"读写小程序云排行榜。",access:"declaration",risk:"medium",config:{},methods:["cloud.leaderboard.submit","cloud.leaderboard.getList","cloud.leaderboard.getCurrentUserEntry","cloud.leaderboard.deleteCurrentUserEntry","cloud.leaderboard.getInfo"],conditions:["排行榜必须已创建,用户和资源规则保持不变。"]},{key:"network",name:"网络",description:"通过 network 模块请求或下载外部资源。",access:"platform-approval",risk:"high",config:{useOfficialDomain:{type:"boolean",required:!1,default:!1,description:"是否申请访问小黑盒官方域名。"}},methods:["network.request","network.download","network.upload"],conditions:["声明后仍需平台批准,并继续执行网络安全策略。"]},{key:"companion",name:"桌面辅助应用",description:"下载、准备并运行随当前小程序版本发布的受管桌面程序。",access:"platform-approval",risk:"high",config:{},methods:["companion.getInfo","companion.getPreparationStatus","companion.prepare","companion.cancelPreparation","companion.getActiveSession","companion.launch","companion.session.write","companion.session.closeStdin","companion.session.terminate","companion.session.ackOutput","companion.openAttachment","companion.showNotification"],conditions:["声明后仍需平台批准,并继续执行可信用户手势、Host 能力和当前版本 Manifest 校验。"]},{key:"appProtocol",name:"应用协议执行",description:"执行任意小黑盒客户端协议。",access:"platform-approval",risk:"high",config:{},methods:["device.executeProtocol"],conditions:["最高危险权限:批准后该入口可执行任意协议,并绕过其他 SDK 能力权限及专用授权流程。"]},{key:"workspaceCards",name:"工作区卡片",description:"在已绑定游戏的桌面工作区展示受审核卡片。",access:"platform-approval",risk:"high",config:{},methods:["workspaceCards.requestRefresh"],conditions:["需平台批准、Host 支持与有效执行租约;不隐式授予网络或存储权限。"]},{key:"user_game_data",name:"游戏资料",description:"在精确资源声明范围内读取当前用户的游戏资料:明日方舟角色/养成与抽卡,以及黑神话悟空、任务栏英雄、影之刃零的云存档解析结果与文件。",access:"declaration",risk:"high",config:{resources:{type:"resource-map",required:!0,items:gr,description:"精确资源声明对象;每项必须填写 1~30 个 Unicode 码点的 purpose,不接受通配符或未开放资源。"}},methods:El,conditions:["逐项声明资源与用途,读取前需用户许可;未取得许可不查询个人来源。","文件与解析结果分别许可;本次许可仅当前实例有效,持久许可保存在本机。","同步会将原存档上传至小黑盒,向小程序交付原文件仍需 `save_files` 许可。","平台取数不授予小程序 `network` 权限;已交付的数据副本无法撤回。"]},{key:"post",name:"关联帖子",description:"读取关联帖子与评论,或以当前用户身份互动并打开社区原生编辑器。",access:"declaration",risk:"high",config:{read:{type:"boolean",required:!1,default:!1,description:"读取帖子、评论和订阅变化。"},write:{type:"boolean",required:!1,default:!1,description:"点赞、收藏、删除评论及打开社区原生编辑器。"}},methods:[...Zs,...Gn],conditions:["显式声明 read / write,省略时为 false;写操作须由用户明确触发,继续执行社区审核和权限校验。"]}];new Set(Or);const b0=30;function y0(e){if(typeof e!="string")throw new Error("purpose 必须是字符串");const t=e.trim(),r=Array.from(t);if(r.length<1||r.length>b0)throw new Error("purpose 去除首尾空白后必须为 1~30 个 Unicode 码点");if(r.some(n=>{const i=n.codePointAt(0);return i>=55296&&i<=57343}))throw new Error("purpose 包含非法 Unicode 字符");return t}function ti(e){return Sl(e,!1)}function N0(e){return Sl(e,!0)}function Sl(e,t){if(!Wc(e))throw new Error("resources 必须是资源声明对象;每项资源必须填写 purpose");const r={};for(const n of Object.keys(e).sort()){const i=e[n];if(!Wc(i)||Object.keys(i).length!==1||!Object.prototype.hasOwnProperty.call(i,"purpose"))throw new Error(`resources.${n} 必须且只能包含 purpose`);let s;try{s=y0(i.purpose)}catch(a){throw new Error(`resources.${n}: ${a.message}`)}if(!Zt(n)){if(t&&/^game\.[a-z0-9_]+\.[a-z0-9_.]+$/.test(n))continue;throw new Error(`resources 包含未开放资源:${n}`)}r[n]={purpose:s}}return r}function w0(e){return gr.filter(t=>Object.prototype.hasOwnProperty.call(e,t))}function Wc(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ol(e,t,r,n){return JSON.stringify(["user-game-data-purpose-v1",e,t,r,n])}const D0=new Set(Or);function S0(e){return D0.has(e)}function it(e){if(!Pr(e)||e.schema_version!==1||!Array.isArray(e.entries))return{valid:!1,permissions:{}};if(e.revision!==void 0&&(typeof e.revision!="number"||!Number.isInteger(e.revision)||e.revision<0))return{valid:!1,permissions:{}};const t=new Set,r={};for(const n of e.entries){if(!Pr(n)||typeof n.key!="string"||!n.key.trim())return{valid:!1,permissions:{}};const i=n.key.trim(),s=i==="network.request"?"network":i;if(t.has(s)||n.status!=="enabled"&&n.status!=="disabled")return{valid:!1,permissions:{}};if(t.add(s),!!S0(s)){if(s==="network"){const a=n.config;if(!Pr(a)||typeof a.useOfficialDomain!="boolean")return{valid:!1,permissions:{}};r[s]={key:s,status:n.status,config:{useOfficialDomain:a.useOfficialDomain}};continue}if(s==="post"){const a=n.config;if(!Pr(a)||typeof a.read!="boolean"||typeof a.write!="boolean")return{valid:!1,permissions:{}};r[s]={key:s,status:n.status,config:{read:a.read,write:a.write}};continue}if(s==="user_game_data"){const a=n.config;if(!Pr(a))return{valid:!1,permissions:{}};try{const c=N0(a.resources);r[s]={key:s,status:n.status,config:{resources:c}}}catch{return{valid:!1,permissions:{}}}continue}if(n.config!==null&&n.config!==void 0&&(!Pr(n.config)||Object.keys(n.config).length>0))return{valid:!1,permissions:{}};r[s]={key:s,status:n.status,config:{}}}}return{valid:!0,permissions:r}}function Pr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const xi=["network","companion","appProtocol"];function Ml(e){if(!En(e,["schema_version","revision","entries"])||e.schema_version!==1||typeof e.revision!="number"||!Number.isSafeInteger(e.revision)||e.revision<0||!Array.isArray(e.entries)||e.entries.length>xi.length)return{valid:!1};const t=[],r=new Set;for(const n of e.entries){if(!En(n,["key","status","config"])||n.status!=="enabled")return{valid:!1};if(typeof n.key!="string"||r.has(n.key))return{valid:!1};if(r.add(n.key),n.key==="network"){if(!En(n.config,["useOfficialDomain"])||n.config.useOfficialDomain!==!1)return{valid:!1};t.push({key:"network",status:"enabled",config:{useOfficialDomain:!1}})}else if(n.key==="companion"){if(!En(n.config,[]))return{valid:!1};t.push({key:"companion",status:"enabled",config:{}})}else if(n.key==="appProtocol"){if(!En(n.config,[]))return{valid:!1};t.push({key:"appProtocol",status:"enabled",config:{}})}else return{valid:!1}}return t.sort((n,i)=>xi.indexOf(n.key)-xi.indexOf(i.key)),{valid:!0,grant:{schema_version:1,revision:e.revision,entries:t}}}function O0(e){if(!Number.isSafeInteger(e.revision)||e.revision<0)throw new Error("本地调试权限 revision 必须是非负安全整数");const t=it(e.runtimePermissions),r=new Set(e.eligiblePermissionKeys??["network","appProtocol"]),n=[];for(const i of xi)!r.has(i)||e.declaredPermissions[i]?.enabled!==!0||t.valid&&t.permissions[i]?.status==="enabled"||n.push(i==="network"?{key:i,status:"enabled",config:{useOfficialDomain:!1}}:{key:i,status:"enabled",config:{}});return{schema_version:1,revision:e.revision,entries:n}}function uc(e){const t=it(e.runtimePermissions),r=Ml(e.localDevGrant),n=t.valid?t.permissions:{};for(const a of Or)e.declaredPermissions[a]?.enabled!==!0?delete n[a]:cc.some(c=>c.key===a&&c.access==="declaration")?n[a]={key:a,status:"enabled",config:M0(a,e.declaredPermissions)}:a==="network"&&n.network&&(n.network.config.useOfficialDomain=n.network.status==="enabled"&&n.network.config.useOfficialDomain===!0&&e.declaredPermissions.network?.useOfficialDomain===!0);const i=[];if(r.valid)for(const a of r.grant.entries)e.declaredPermissions[a.key]?.enabled!==!0||n[a.key]?.status==="enabled"||(n[a.key]=a,i.push(a.key));const s=Cl(e.runtimePermissions)&&typeof e.runtimePermissions.revision=="number"&&Number.isSafeInteger(e.runtimePermissions.revision)&&e.runtimePermissions.revision>=0?e.runtimePermissions.revision:void 0;return{runtimePermissions:{schema_version:1,...s===void 0?{}:{revision:s},entries:Or.flatMap(a=>n[a]?[n[a]]:[])},temporaryPermissionKeys:i,grantValid:r.valid}}function M0(e,t){const r=cc.find(i=>i.key===e);if(!r)return{};const n={};for(const[i,s]of Object.entries(r.config)){if(e==="post"&&s.type==="boolean"){n[i]=t.post?.[i]===!0;continue}s.type==="resource-map"&&(n[i]=i==="resources"?ti(t[e]?.resources):{})}return n}function Cl(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function En(e,t){return Cl(e)&&Object.keys(e).length===t.length&&t.every(r=>Object.prototype.hasOwnProperty.call(e,r))}const Xr=["identity","profile","steam_account"],C0=/^[a-z][a-z0-9-]{0,31}$/,Rl=["COMPANION_UNSUPPORTED","COMPANION_PREVIEW_UNSUPPORTED","COMPANION_NOT_DECLARED","COMPANION_TARGET_UNSUPPORTED","COMPANION_NOT_PREPARED","COMPANION_PREPARATION_CANCELLED","COMPANION_DOWNLOAD_FAILED","COMPANION_DESCRIPTOR_UNAVAILABLE","COMPANION_ARCHIVE_INVALID","COMPANION_INTEGRITY_FAILED","COMPANION_ENTRYPOINT_INVALID","COMPANION_USER_CANCELLED","COMPANION_ELEVATION_DENIED","COMPANION_OS_BLOCKED","COMPANION_LAUNCH_FAILED","COMPANION_SESSION_VERSION_MISMATCH","COMPANION_SESSION_OWNERSHIP_LOST","COMPANION_SESSION_EXITED","COMPANION_PIPE_CLOSED","COMPANION_OUTPUT_LIMIT","COMPANION_PROCESS_CRASHED","COMPANION_ATTACHMENT_NOT_FOUND","COMPANION_NOTIFICATION_UNAVAILABLE","COMPANION_TERMINATE_FAILED"];var $c;function Le(e,t,r){function n(c,u){if(c._zod||Object.defineProperty(c,"_zod",{value:{def:u,constr:a,traits:new Set},enumerable:!1}),c._zod.traits.has(e))return;c._zod.traits.add(e),t(c,u);const d=a.prototype,l=Object.keys(d);for(let h=0;h<l.length;h++){const f=l[h];f in c||(c[f]=d[f].bind(c))}}const i=r?.Parent??Object;class s extends i{}Object.defineProperty(s,"name",{value:e});function a(c){var u;const d=r?.Parent?new s:this;n(d,c),(u=d._zod).deferred??(u.deferred=[]);for(const l of d._zod.deferred)l();return d}return Object.defineProperty(a,"init",{value:n}),Object.defineProperty(a,Symbol.hasInstance,{value:c=>r?.Parent&&c instanceof r.Parent?!0:c?._zod?.traits?.has(e)}),Object.defineProperty(a,"name",{value:e}),a}class Ln extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}($c=globalThis).__zod_globalConfig??($c.__zod_globalConfig={});const Kc=globalThis.__zod_globalConfig;function ln(e){return e&&Object.assign(Kc,e),Kc}function R0(e,t){return typeof t=="bigint"?t.toString():t}function L0(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function Ll(e){const t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}const Zc=Symbol("evaluating");function ot(e,t,r){let n;Object.defineProperty(e,t,{get(){if(n!==Zc)return n===void 0&&(n=Zc,n=r()),n},set(i){Object.defineProperty(e,t,{value:i})},configurable:!0})}const Pl="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function P0(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Xc(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function v0(e,t,r){const n=new e._zod.constr(t??e._zod.def);return(!t||r?.parent)&&(n._zod.parent=e),n}function bt(e){return{}}function k0(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}const x0={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function Dn(e,t=0){if(e.aborted===!0)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue!==!0)return!0;return!1}function U0(e,t=0){if(e.aborted===!0)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue===!1)return!0;return!1}function vl(e,t){return t.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(e),r})}function Ai(e){return typeof e=="string"?e:e?.message}function ui(e,t,r){const n=e.message?e.message:Ai(e.inst?._zod.def?.error?.(e))??Ai(t?.error?.(e))??Ai(r.customError?.(e))??Ai(r.localeError?.(e))??"Invalid input",{inst:i,continue:s,input:a,...c}=e;return c.path??(c.path=[]),c.message=n,t?.reportInput&&(c.input=a),c}const kl=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,R0,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},B0=Le("$ZodError",kl),da=Le("$ZodError",kl,{Parent:Error}),H0=e=>(t,r,n,i)=>{const s=n?{...n,async:!1}:{async:!1},a=t._zod.run({value:r,issues:[]},s);if(a instanceof Promise)throw new Ln;if(a.issues.length){const c=new(i?.Err??e)(a.issues.map(u=>ui(u,s,ln())));throw Pl(c,i?.callee),c}return a.value},F0=H0(da),z0=e=>async(t,r,n,i)=>{const s=n?{...n,async:!0}:{async:!0};let a=t._zod.run({value:r,issues:[]},s);if(a instanceof Promise&&(a=await a),a.issues.length){const c=new(i?.Err??e)(a.issues.map(u=>ui(u,s,ln())));throw Pl(c,i?.callee),c}return a.value},j0=z0(da),V0=e=>(t,r,n)=>{const i=n?{...n,async:!1}:{async:!1},s=t._zod.run({value:r,issues:[]},i);if(s instanceof Promise)throw new Ln;return s.issues.length?{success:!1,error:new(e??B0)(s.issues.map(a=>ui(a,i,ln())))}:{success:!0,data:s.value}},xl=V0(da),G0=e=>async(t,r,n)=>{const i=n?{...n,async:!0}:{async:!0};let s=t._zod.run({value:r,issues:[]},i);return s instanceof Promise&&(s=await s),s.issues.length?{success:!1,error:new e(s.issues.map(a=>ui(a,i,ln())))}:{success:!0,data:s.value}},Ul=G0(da),Y0=e=>{const t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},Q0=/^-?\d+$/,q0=/^-?\d+(?:\.\d+)?$/,W0=/^null$/i,la=Le("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),Bl={number:"number",bigint:"bigint",object:"date"},$0=Le("$ZodCheckLessThan",(e,t)=>{la.init(e,t);const r=Bl[typeof t.value];e._zod.onattach.push(n=>{const i=n._zod.bag,s=(t.inclusive?i.maximum:i.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<s&&(t.inclusive?i.maximum=t.value:i.exclusiveMaximum=t.value)}),e._zod.check=n=>{(t.inclusive?n.value<=t.value:n.value<t.value)||n.issues.push({origin:r,code:"too_big",maximum:typeof t.value=="object"?t.value.getTime():t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),K0=Le("$ZodCheckGreaterThan",(e,t)=>{la.init(e,t);const r=Bl[typeof t.value];e._zod.onattach.push(n=>{const i=n._zod.bag,s=(t.inclusive?i.minimum:i.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>s&&(t.inclusive?i.minimum=t.value:i.exclusiveMinimum=t.value)}),e._zod.check=n=>{(t.inclusive?n.value>=t.value:n.value>t.value)||n.issues.push({origin:r,code:"too_small",minimum:typeof t.value=="object"?t.value.getTime():t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Z0=Le("$ZodCheckNumberFormat",(e,t)=>{la.init(e,t),t.format=t.format||"float64";const r=t.format?.includes("int"),n=r?"int":"number",[i,s]=x0[t.format];e._zod.onattach.push(a=>{const c=a._zod.bag;c.format=t.format,c.minimum=i,c.maximum=s,r&&(c.pattern=Q0)}),e._zod.check=a=>{const c=a.value;if(r){if(!Number.isInteger(c)){a.issues.push({expected:n,format:t.format,code:"invalid_type",continue:!1,input:c,inst:e});return}if(!Number.isSafeInteger(c)){c>0?a.issues.push({input:c,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,inclusive:!0,continue:!t.abort}):a.issues.push({input:c,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,inclusive:!0,continue:!t.abort});return}}c<i&&a.issues.push({origin:"number",input:c,code:"too_small",minimum:i,inclusive:!0,inst:e,continue:!t.abort}),c>s&&a.issues.push({origin:"number",input:c,code:"too_big",maximum:s,inclusive:!0,inst:e,continue:!t.abort})}}),X0=Le("$ZodCheckStringFormat",(e,t)=>{var r,n;la.init(e,t),e._zod.onattach.push(i=>{const s=i._zod.bag;s.format=t.format,t.pattern&&(s.patterns??(s.patterns=new Set),s.patterns.add(t.pattern))}),t.pattern?(r=e._zod).check??(r.check=i=>{t.pattern.lastIndex=0,!t.pattern.test(i.value)&&i.issues.push({origin:"string",code:"invalid_format",format:t.format,input:i.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(n=e._zod).check??(n.check=()=>{})}),J0=Le("$ZodCheckRegex",(e,t)=>{X0.init(e,t),e._zod.check=r=>{t.pattern.lastIndex=0,!t.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),eE={major:4,minor:4,patch:3},St=Le("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=eE;const n=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&n.unshift(e);for(const i of n)for(const s of i._zod.onattach)s(e);if(n.length===0)(r=e._zod).deferred??(r.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{const i=(a,c,u)=>{let d=Dn(a),l;for(const h of c){if(h._zod.def.when){if(U0(a)||!h._zod.def.when(a))continue}else if(d)continue;const f=a.issues.length,p=h._zod.check(a);if(p instanceof Promise&&u?.async===!1)throw new Ln;if(l||p instanceof Promise)l=(l??Promise.resolve()).then(async()=>{await p,a.issues.length!==f&&(d||(d=Dn(a,f)))});else{if(a.issues.length===f)continue;d||(d=Dn(a,f))}}return l?l.then(()=>a):a},s=(a,c,u)=>{if(Dn(a))return a.aborted=!0,a;const d=i(c,n,u);if(d instanceof Promise){if(u.async===!1)throw new Ln;return d.then(l=>e._zod.parse(l,u))}return e._zod.parse(d,u)};e._zod.run=(a,c)=>{if(c.skipChecks)return e._zod.parse(a,c);if(c.direction==="backward"){const d=e._zod.parse({value:a.value,issues:[]},{...c,skipChecks:!0});return d instanceof Promise?d.then(l=>s(l,a,c)):s(d,a,c)}const u=e._zod.parse(a,c);if(u instanceof Promise){if(c.async===!1)throw new Ln;return u.then(d=>i(d,n,c))}return i(u,n,c)}}ot(e,"~standard",()=>({validate:i=>{try{const s=xl(e,i);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return Ul(e,i).then(a=>a.success?{value:a.data}:{issues:a.error?.issues})}},vendor:"zod",version:1}))}),tE=Le("$ZodString",(e,t)=>{St.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??Y0(e._zod.bag),e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=String(r.value)}catch{}return typeof r.value=="string"||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:e}),r}}),Hl=Le("$ZodNumber",(e,t)=>{St.init(e,t),e._zod.pattern=e._zod.bag.pattern??q0,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=Number(r.value)}catch{}const i=r.value;if(typeof i=="number"&&!Number.isNaN(i)&&Number.isFinite(i))return r;const s=typeof i=="number"?Number.isNaN(i)?"NaN":Number.isFinite(i)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:i,inst:e,...s?{received:s}:{}}),r}}),rE=Le("$ZodNumberFormat",(e,t)=>{Z0.init(e,t),Hl.init(e,t)}),nE=Le("$ZodNull",(e,t)=>{St.init(e,t),e._zod.pattern=W0,e._zod.values=new Set([null]),e._zod.parse=(r,n)=>{const i=r.value;return i===null||r.issues.push({expected:"null",code:"invalid_type",input:i,inst:e}),r}}),iE=Le("$ZodNever",(e,t)=>{St.init(e,t),e._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:e}),r)});function Jc(e,t,r){e.issues.length&&t.issues.push(...vl(r,e.issues)),t.value[r]=e.value}const sE=Le("$ZodArray",(e,t)=>{St.init(e,t),e._zod.parse=(r,n)=>{const i=r.value;if(!Array.isArray(i))return r.issues.push({expected:"array",code:"invalid_type",input:i,inst:e}),r;r.value=Array(i.length);const s=[];for(let a=0;a<i.length;a++){const c=i[a],u=t.element._zod.run({value:c,issues:[]},n);u instanceof Promise?s.push(u.then(d=>Jc(d,r,a))):Jc(u,r,a)}return s.length?Promise.all(s).then(()=>r):r}});function Ps(e,t,r,n,i,s){const a=r in n;if(e.issues.length){if(i&&s&&!a)return;t.issues.push(...vl(r,e.issues))}if(!a&&!i){e.issues.length||t.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[r]});return}e.value===void 0?a&&(t.value[r]=void 0):t.value[r]=e.value}function aE(e){const t=Object.keys(e.shape);for(const n of t)if(!e.shape?.[n]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${n}": expected a Zod schema`);const r=k0(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(r)}}function oE(e,t,r,n,i,s){const a=[],c=i.keySet,u=i.catchall._zod,d=u.def.type,l=u.optin==="optional",h=u.optout==="optional";for(const f in t){if(f==="__proto__"||c.has(f))continue;if(d==="never"){a.push(f);continue}const p=u.run({value:t[f],issues:[]},n);p instanceof Promise?e.push(p.then(g=>Ps(g,r,f,t,l,h))):Ps(p,r,f,t,l,h)}return a.length&&r.issues.push({code:"unrecognized_keys",keys:a,input:t,inst:s}),e.length?Promise.all(e).then(()=>r):r}const cE=Le("$ZodObject",(e,t)=>{if(St.init(e,t),!Object.getOwnPropertyDescriptor(t,"shape")?.get){const c=t.shape;Object.defineProperty(t,"shape",{get:()=>{const u={...c};return Object.defineProperty(t,"shape",{value:u}),u}})}const n=L0(()=>aE(t));ot(e._zod,"propValues",()=>{const c=t.shape,u={};for(const d in c){const l=c[d]._zod;if(l.values){u[d]??(u[d]=new Set);for(const h of l.values)u[d].add(h)}}return u});const i=P0,s=t.catchall;let a;e._zod.parse=(c,u)=>{a??(a=n.value);const d=c.value;if(!i(d))return c.issues.push({expected:"object",code:"invalid_type",input:d,inst:e}),c;c.value={};const l=[],h=a.shape;for(const f of a.keys){const p=h[f],g=p._zod.optin==="optional",b=p._zod.optout==="optional",y=p._zod.run({value:d[f],issues:[]},u);y instanceof Promise?l.push(y.then(N=>Ps(N,c,f,d,g,b))):Ps(y,c,f,d,g,b)}return s?oE(l,d,c,u,n.value,e):l.length?Promise.all(l).then(()=>c):c}});function eu(e,t,r,n){for(const s of e)if(s.issues.length===0)return t.value=s.value,t;const i=e.filter(s=>!Dn(s));return i.length===1?(t.value=i[0].value,i[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:e.map(s=>s.issues.map(a=>ui(a,n,ln())))}),t)}const uE=Le("$ZodUnion",(e,t)=>{St.init(e,t),ot(e._zod,"optin",()=>t.options.some(n=>n._zod.optin==="optional")?"optional":void 0),ot(e._zod,"optout",()=>t.options.some(n=>n._zod.optout==="optional")?"optional":void 0),ot(e._zod,"values",()=>{if(t.options.every(n=>n._zod.values))return new Set(t.options.flatMap(n=>Array.from(n._zod.values)))}),ot(e._zod,"pattern",()=>{if(t.options.every(n=>n._zod.pattern)){const n=t.options.map(i=>i._zod.pattern);return new RegExp(`^(${n.map(i=>Ll(i.source)).join("|")})$`)}});const r=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(n,i)=>{if(r)return r(n,i);let s=!1;const a=[];for(const c of t.options){const u=c._zod.run({value:n.value,issues:[]},i);if(u instanceof Promise)a.push(u),s=!0;else{if(u.issues.length===0)return u;a.push(u)}}return s?Promise.all(a).then(c=>eu(c,n,e,i)):eu(a,n,e,i)}}),dE=Le("$ZodLiteral",(e,t)=>{if(St.init(e,t),t.values.length===0)throw new Error("Cannot create literal schema with no valid values");const r=new Set(t.values);e._zod.values=r,e._zod.pattern=new RegExp(`^(${t.values.map(n=>typeof n=="string"?Xc(n):n?Xc(n.toString()):String(n)).join("|")})$`),e._zod.parse=(n,i)=>{const s=n.value;return r.has(s)||n.issues.push({code:"invalid_value",values:t.values,input:s,inst:e}),n}});function tu(e,t){return t===void 0&&(e.issues.length||e.fallback)?{issues:[],value:void 0}:e}const lE=Le("$ZodOptional",(e,t)=>{St.init(e,t),e._zod.optin="optional",e._zod.optout="optional",ot(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),ot(e._zod,"pattern",()=>{const r=t.innerType._zod.pattern;return r?new RegExp(`^(${Ll(r.source)})?$`):void 0}),e._zod.parse=(r,n)=>{if(t.innerType._zod.optin==="optional"){const i=r.value,s=t.innerType._zod.run(r,n);return s instanceof Promise?s.then(a=>tu(a,i)):tu(s,i)}return r.value===void 0?r:t.innerType._zod.run(r,n)}}),fE=Le("$ZodLazy",(e,t)=>{St.init(e,t),ot(e._zod,"innerType",()=>{const r=t;return r._cachedInner||(r._cachedInner=t.getter()),r._cachedInner}),ot(e._zod,"pattern",()=>e._zod.innerType?._zod?.pattern),ot(e._zod,"propValues",()=>e._zod.innerType?._zod?.propValues),ot(e._zod,"optin",()=>e._zod.innerType?._zod?.optin??void 0),ot(e._zod,"optout",()=>e._zod.innerType?._zod?.optout??void 0),e._zod.parse=(r,n)=>e._zod.innerType._zod.run(r,n)});function hE(e,t){return new e({type:"string",...bt()})}function mE(e,t){return new e({type:"number",checks:[],...bt()})}function EE(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...bt()})}function gE(e,t){return new e({type:"null",...bt()})}function pE(e,t){return new e({type:"never",...bt()})}function he(e,t){return new $0({check:"less_than",...bt(),value:e,inclusive:!0})}function me(e,t){return new K0({check:"greater_than",...bt(),value:e,inclusive:!0})}function Ee(e,t){return new J0({check:"string_format",format:"regex",...bt(),pattern:e})}ln({jitless:!0});function Fl(e){if(e.schema_version!==1||!/^[a-f0-9]{32}$/.test(e.session_id)||!Number.isSafeInteger(e.revision)||e.revision<1||!/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/.test(e.sdk_version)||!e.declared_permissions||typeof e.declared_permissions!="object"||Array.isArray(e.declared_permissions)||!Array.isArray(e.platforms)||e.platforms.some(r=>!["android","ios","ohos","windows","macos","linux"].includes(r))||new Set(e.platforms).size!==e.platforms.length)throw new Error("开发快照无效");const t={};for(const r of Or){const n=e.declared_permissions[r];if(n){if(typeof n.enabled!="boolean")throw new Error("开发权限声明无效");if(r==="network"){t[r]={enabled:n.enabled,useOfficialDomain:n.useOfficialDomain===!0};continue}if(r==="post"){for(const i of["read","write"])if(n[i]!==void 0&&typeof n[i]!="boolean")throw new Error("开发权限声明无效");t.post={enabled:n.enabled,read:n.read===!0,write:n.write===!0};continue}if(r==="user_game_data"){t[r]={enabled:n.enabled,resources:ti(n.resources)};continue}t[r]={enabled:n.enabled}}}if(Object.keys(e.declared_permissions).some(r=>!Or.includes(r)))throw new Error("开发权限声明无效");if(e.companion_manifest_sha256!==void 0&&!/^[a-f0-9]{64}$/.test(e.companion_manifest_sha256))throw new Error("开发产物摘要无效");return JSON.stringify({schema_version:1,session_id:e.session_id,revision:e.revision,sdk_version:e.sdk_version,declared_permissions:t,platforms:[...e.platforms].sort(),...e.companion_manifest_sha256?{companion_manifest_sha256:e.companion_manifest_sha256}:{}})}function TE(e){if(!(typeof e!="string"||e.length>16384))try{const t=JSON.parse(e);return Fl(t)===e?t:void 0}catch{return}}const zt=Le("ZodMiniType",(e,t)=>{if(!e._zod)throw new Error("Uninitialized schema in ZodMiniType.");St.init(e,t),e.def=t,e.type=t.type,e.parse=(r,n)=>F0(e,r,n,{callee:e.parse}),e.safeParse=(r,n)=>xl(e,r,n),e.parseAsync=async(r,n)=>j0(e,r,n,{callee:e.parseAsync}),e.safeParseAsync=async(r,n)=>Ul(e,r,n),e.check=(...r)=>e.clone({...t,checks:[...t.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]},{parent:!0}),e.with=e.check,e.clone=(r,n)=>v0(e,r,n),e.brand=()=>e,e.register=((r,n)=>(r.add(e,n),e)),e.apply=r=>r(e)}),_E=Le("ZodMiniString",(e,t)=>{tE.init(e,t),zt.init(e,t)});function O(e){return hE(_E)}const zl=Le("ZodMiniNumber",(e,t)=>{Hl.init(e,t),zt.init(e,t)});function Z(e){return mE(zl)}const AE=Le("ZodMiniNumberFormat",(e,t)=>{rE.init(e,t),zl.init(e,t)});function ge(e){return EE(AE)}const IE=Le("ZodMiniNull",(e,t)=>{nE.init(e,t),zt.init(e,t)});function de(e){return gE(IE)}const bE=Le("ZodMiniNever",(e,t)=>{iE.init(e,t),zt.init(e,t)});function yE(e){return pE(bE)}const NE=Le("ZodMiniArray",(e,t)=>{sE.init(e,t),zt.init(e,t)});function oe(e,t){return new NE({type:"array",element:e,...bt()})}const wE=Le("ZodMiniObject",(e,t)=>{cE.init(e,t),zt.init(e,t),ot(e,"shape",()=>t.shape)});function fe(e,t){return new wE({type:"object",shape:e,catchall:yE(),...bt()})}const DE=Le("ZodMiniUnion",(e,t)=>{uE.init(e,t),zt.init(e,t)});function S(e,t){return new DE({type:"union",options:e,...bt()})}const SE=Le("ZodMiniLiteral",(e,t)=>{dE.init(e,t),zt.init(e,t)});function _e(e,t){return new SE({type:"literal",values:Array.isArray(e)?e:[e],...bt()})}const OE=Le("ZodMiniOptional",(e,t)=>{lE.init(e,t),zt.init(e,t)});function X(e){return new OE({type:"optional",innerType:e})}const ME=Le("ZodMiniLazy",(e,t)=>{fE.init(e,t),zt.init(e,t)});function ie(e){return new ME({type:"lazy",getter:e})}const se={ArkProfile:fe({uid:O(),name:O(),level:Z(),avatar:X(ie(()=>se.ArkPlayerAvatar)),characterCount:Z(),totalCharacterCount:Z(),mainStageProgress:O(),rogueLevel:Z(),campaignFullKillCount:Z(),tag:O(),observedAt:X(S([O(),Z()])),lastOnlineTs:X(S([O(),Z()])),registerTs:X(S([O(),Z()])),changeTime:X(S([O(),Z()])),operators:X(oe(ie(()=>se.ArkOperator)))}),ArkPlayerAvatar:fe({url:O(),type:O(),id:O()}),ArkOperator:fe({characterId:O(),name:O(),profession:O(),evolvePhase:Z(),potentialRank:Z()}),ArkGachaAnalysis:fe({uid:O(),year:Z(),total:Z(),srCount:Z(),upCount:Z(),missCount:Z(),careerEvaluation:O(),careerIsLucky:S([_e(!1),_e(!0)]),pools:oe(ie(()=>se.ArkGachaPoolStat)),records:oe(ie(()=>se.ArkGachaAnalysisRecord)),luckyLottery:oe(Z())}),ArkGachaPoolStat:fe({poolId:O(),totalCost:Z(),ssrCount:Z(),ssrCost:Z(),records:oe(ie(()=>se.ArkGachaAnalysisRecord))}),ArkGachaAnalysisRecord:fe({name:O(),timestamp:S([ge().check(me(-9007199254740991),he(9007199254740991)),O().check(Ee(new RegExp("^-?(0|[1-9][0-9]*)$")))]),diff:Z(),negativeDiff:Z(),tag:O(),missUp:S([_e(!1),_e(!0)])}),GachaRecord:fe({id:O(),name:O(),pool:O(),rarity:Z(),timestamp:S([ge().check(me(-9007199254740991),he(9007199254740991)),O().check(Ee(new RegExp("^-?(0|[1-9][0-9]*)$")))])}),BlackMythWukongSave:fe({level:X(Z()),newGamePlusCount:X(Z()),gameTotalTime:X(Z()),playerDeathCount:X(Z()),totalMoney:X(O()),meditationList:X(S([de(),oe(Z())])),monsterCollectionList:X(S([de(),oe(Z())])),returnPointList:X(S([de(),oe(Z())])),activatedWeaponIdList:X(S([de(),oe(O())])),activatedEquipIdList:X(S([de(),oe(Z())])),magicArtifactList:X(S([de(),oe(Z())])),soulSkillIdList:X(S([de(),oe(Z())])),huluIdLits:X(S([de(),oe(Z())])),wineIdList:X(S([de(),oe(Z())])),wineIdPartnerList:X(S([de(),oe(Z())])),cropIdList:X(S([de(),oe(Z())])),recipeIdList:X(S([de(),oe(Z())])),wearedWaeponId:X(O()),wearedMagicArtifact:X(Z()),wearedSoulSkill:X(Z()),wearedHead:X(Z()),wearedUpware:X(Z()),wearedArm:X(Z()),wearedFoot:X(Z()),wearedHulu:X(Z()),wearedAccessoryList:X(S([de(),oe(Z())])),spellQishu:X(S([de(),oe(Z())])),spellShenfa:X(S([de(),oe(Z())])),spellHaomao:X(S([de(),oe(Z())])),spellBianshen:X(S([de(),oe(Z())])),bossRushBossgroup:X(ie(()=>se.BlackMythWukongBossRushData)),bossRushRefight:X(ie(()=>se.BlackMythWukongBossRefightData))}),BlackMythWukongBossRushData:fe({bossGroups:X(S([de(),oe(ie(()=>se.BlackMythWukongBossRushRecord))]))}),BlackMythWukongBossRushRecord:fe({bossGroupId:X(Z()),isPassed:X(S([_e(!1),_e(!0)])),bestRecords:X(S([de(),oe(ie(()=>se.BlackMythWukongBattleRecord))])),encounterBossIndex:X(Z()),battleCount:X(Z())}),BlackMythWukongBattleRecord:fe({battleId:X(O()),battleData:X(ie(()=>se.BlackMythWukongBattleData))}),BlackMythWukongBattleData:fe({totalTime:X(Z()),score:X(Z()),debuffList:X(S([de(),oe(Z())])),targetId:X(Z()),archiveTime:X(O()),roleBase:X(ie(()=>se.BlackMythWukongRoleBase)),battleStyleInfo:X(ie(()=>se.BlackMythWukongBattleStyleInfo)),damageInfo:X(ie(()=>se.BlackMythWukongDamageInfo))}),BlackMythWukongRoleBase:fe({level:X(Z()),atk:X(Z()),hpMax:X(Z()),staminaMax:X(Z()),mpMax:X(Z())}),BlackMythWukongBattleStyleInfo:fe({spellList:X(S([de(),oe(ie(()=>se.BlackMythWukongCast))])),fabaoInfo:X(ie(()=>se.BlackMythWukongCast)),soulInfo:X(ie(()=>se.BlackMythWukongCast)),itemCount:X(Z()),wineCount:X(Z()),rollCount:X(Z()),defuseCount:X(Z()),fourPeCount:X(Z())}),BlackMythWukongCast:fe({castId:X(Z()),castCount:X(Z())}),BlackMythWukongDamageInfo:fe({totalDamage:X(S([O(),Z()])),hightestDamage:X(S([O(),Z()])),criticalDmgRate:X(Z()),totalBeDamaged:X(S([O(),Z()])),criticalDmgTotal:X(S([O(),Z()])),elemDotDmgTotal:X(S([O(),Z()])),elemDotDmgRate:X(Z())}),BlackMythWukongBossRefightData:fe({bossList:X(S([de(),oe(ie(()=>se.BlackMythWukongBossRefightRecord))]))}),BlackMythWukongBossRefightRecord:fe({bossId:X(Z()),passedMaxLevel:X(Z()),lastChallengeLevel:X(Z()),bestRecords:X(S([de(),oe(ie(()=>se.BlackMythWukongBattleRecord))])),refightStatisticsList:X(S([de(),oe(ie(()=>se.BlackMythWukongRefightStatistic))]))}),BlackMythWukongRefightStatistic:fe({challengeLevel:X(Z()),battleCount:X(Z())}),TaskBarHeroSave:fe({update_time:S([ge().check(me(-9007199254740991),he(9007199254740991)),O().check(Ee(new RegExp("^-?(0|[1-9][0-9]*)$")))]),game_version:O(),account_version:O(),play_time:Z(),last_saved_time:O(),common:ie(()=>se.TaskBarHeroCommon),summary:ie(()=>se.TaskBarHeroSummary),heroes:S([de(),oe(ie(()=>se.TaskBarHeroHero))]),rune_save_data:S([de(),oe(ie(()=>se.TaskBarHeroRune))]),pets:S([de(),oe(ie(()=>se.TaskBarHeroPet))]),attributes:S([de(),oe(ie(()=>se.TaskBarHeroAttribute))]),inventory_slots:S([de(),oe(ie(()=>se.TaskBarHeroItemSlot))]),stash_slots:S([de(),oe(ie(()=>se.TaskBarHeroItemSlot))]),item_instances:S([de(),oe(ie(()=>se.TaskBarHeroItemInstance))]),values:ie(()=>se.TaskBarHeroValueSummary)}),TaskBarHeroCommon:fe({max_completed_stage:S([ge().check(me(-9007199254740991),he(9007199254740991)),O().check(Ee(new RegExp("^-?(0|[1-9][0-9]*)$")))]),current_stage_key:S([ge().check(me(-9007199254740991),he(9007199254740991)),O().check(Ee(new RegExp("^-?(0|[1-9][0-9]*)$")))]),current_stage_wave:S([ge().check(me(-9007199254740991),he(9007199254740991)),O().check(Ee(new RegExp("^-?(0|[1-9][0-9]*)$")))]),arranged_hero_keys:S([de(),oe(S([ge().check(me(-9007199254740991),he(9007199254740991)),O().check(Ee(new RegExp("^-?(0|[1-9][0-9]*)$")))]))]),arranged_pet_key:S([ge().check(me(-9007199254740991),he(9007199254740991)),O().check(Ee(new RegExp("^-?(0|[1-9][0-9]*)$")))])}),TaskBarHeroSummary:fe({max_hero_level:S([ge().check(me(-9007199254740991),he(9007199254740991)),O().check(Ee(new RegExp("^-?(0|[1-9][0-9]*)$")))]),learned_rune_count:S([ge().check(me(-9007199254740991),he(9007199254740991)),O().check(Ee(new RegExp("^-?(0|[1-9][0-9]*)$")))]),unlocked_hero:S([ge().check(me(-9007199254740991),he(9007199254740991)),O().check(Ee(new RegExp("^-?(0|[1-9][0-9]*)$")))]),total_hero:S([ge().check(me(-9007199254740991),he(9007199254740991)),O().check(Ee(new RegExp("^-?(0|[1-9][0-9]*)$")))]),item_count:S([ge().check(me(-9007199254740991),he(9007199254740991)),O().check(Ee(new RegExp("^-?(0|[1-9][0-9]*)$")))]),inventory_slots:S([ge().check(me(-9007199254740991),he(9007199254740991)),O().check(Ee(new RegExp("^-?(0|[1-9][0-9]*)$")))]),stash_slots:S([ge().check(me(-9007199254740991),he(9007199254740991)),O().check(Ee(new RegExp("^-?(0|[1-9][0-9]*)$")))])}),TaskBarHeroHero:fe({hero_key:S([ge().check(me(-9007199254740991),he(9007199254740991)),O().check(Ee(new RegExp("^-?(0|[1-9][0-9]*)$")))]),hero_level:S([ge().check(me(-9007199254740991),he(9007199254740991)),O().check(Ee(new RegExp("^-?(0|[1-9][0-9]*)$")))]),is_unlock:S([_e(!1),_e(!0)]),hero_exp:Z(),ability_point:S([ge().check(me(-9007199254740991),he(9007199254740991)),O().check(Ee(new RegExp("^-?(0|[1-9][0-9]*)$")))]),allocated_hero_ability_point:S([ge().check(me(-9007199254740991),he(9007199254740991)),O().check(Ee(new RegExp("^-?(0|[1-9][0-9]*)$")))]),equipped_item_ids:S([de(),oe(O())]),equipped_skill_keys:S([de(),oe(S([ge().check(me(-9007199254740991),he(9007199254740991)),O().check(Ee(new RegExp("^-?(0|[1-9][0-9]*)$")))]))]),unlocked_attribute_group_keys:S([de(),oe(S([ge().check(me(-9007199254740991),he(9007199254740991)),O().check(Ee(new RegExp("^-?(0|[1-9][0-9]*)$")))]))])}),TaskBarHeroRune:fe({rune_key:S([ge().check(me(-9007199254740991),he(9007199254740991)),O().check(Ee(new RegExp("^-?(0|[1-9][0-9]*)$")))]),level:S([ge().check(me(-9007199254740991),he(9007199254740991)),O().check(Ee(new RegExp("^-?(0|[1-9][0-9]*)$")))])}),TaskBarHeroPet:fe({pet_key:S([ge().check(me(-9007199254740991),he(9007199254740991)),O().check(Ee(new RegExp("^-?(0|[1-9][0-9]*)$")))]),is_unlock:S([_e(!1),_e(!0)])}),TaskBarHeroAttribute:fe({key:S([ge().check(me(-9007199254740991),he(9007199254740991)),O().check(Ee(new RegExp("^-?(0|[1-9][0-9]*)$")))]),level:S([ge().check(me(-9007199254740991),he(9007199254740991)),O().check(Ee(new RegExp("^-?(0|[1-9][0-9]*)$")))])}),TaskBarHeroItemSlot:fe({index:S([ge().check(me(-9007199254740991),he(9007199254740991)),O().check(Ee(new RegExp("^-?(0|[1-9][0-9]*)$")))]),item_unique_id:O(),is_unlock:S([_e(!1),_e(!0)]),is_unlocked_by_rune:S([_e(!1),_e(!0)])}),TaskBarHeroItemInstance:fe({item_key:S([ge().check(me(-9007199254740991),he(9007199254740991)),O().check(Ee(new RegExp("^-?(0|[1-9][0-9]*)$")))]),unique_id:O(),is_chaotic:S([_e(!1),_e(!0)]),is_blocked:S([_e(!1),_e(!0)]),is_server_pending_item:S([_e(!1),_e(!0)]),enchant_count:S([de(),oe(S([ge().check(me(-9007199254740991),he(9007199254740991)),O().check(Ee(new RegExp("^-?(0|[1-9][0-9]*)$")))]))]),enchant_data:S([de(),oe(ie(()=>se.TaskBarHeroEnchantData))]),item_get_source_type:S([ge().check(me(-9007199254740991),he(9007199254740991)),O().check(Ee(new RegExp("^-?(0|[1-9][0-9]*)$")))]),decoration_applied_total_count:S([ge().check(me(-9007199254740991),he(9007199254740991)),O().check(Ee(new RegExp("^-?(0|[1-9][0-9]*)$")))]),engraving_applied_total_count:S([ge().check(me(-9007199254740991),he(9007199254740991)),O().check(Ee(new RegExp("^-?(0|[1-9][0-9]*)$")))]),inscription_applied_total_count:S([ge().check(me(-9007199254740991),he(9007199254740991)),O().check(Ee(new RegExp("^-?(0|[1-9][0-9]*)$")))])}),TaskBarHeroEnchantData:fe({stat_mod_key:S([ge().check(me(-9007199254740991),he(9007199254740991)),O().check(Ee(new RegExp("^-?(0|[1-9][0-9]*)$")))]),tier:S([ge().check(me(-9007199254740991),he(9007199254740991)),O().check(Ee(new RegExp("^-?(0|[1-9][0-9]*)$")))]),value:Z(),recipe_type:S([ge().check(me(-9007199254740991),he(9007199254740991)),O().check(Ee(new RegExp("^-?(0|[1-9][0-9]*)$")))]),mod_type:S([ge().check(me(-9007199254740991),he(9007199254740991)),O().check(Ee(new RegExp("^-?(0|[1-9][0-9]*)$")))]),material_key:S([ge().check(me(-9007199254740991),he(9007199254740991)),O().check(Ee(new RegExp("^-?(0|[1-9][0-9]*)$")))]),stat_type:S([ge().check(me(-9007199254740991),he(9007199254740991)),O().check(Ee(new RegExp("^-?(0|[1-9][0-9]*)$")))])}),TaskBarHeroValueSummary:fe({market_value:S([ge().check(me(-9007199254740991),he(9007199254740991)),O().check(Ee(new RegExp("^-?(0|[1-9][0-9]*)$")))]),price_state:O(),currency:O()}),PhantomBladeZeroSave:fe({defaultSlot:O(),slots:oe(ie(()=>se.PhantomBladeZeroSaveSlot))}),PhantomBladeZeroSaveSlot:fe({slot:O(),head:ie(()=>se.PhantomBladeZeroSlotHead),firstClear:ie(()=>se.PhantomBladeZeroSlotFirstClear),progress:ie(()=>se.PhantomBladeZeroSlotProgress),combat:ie(()=>se.PhantomBladeZeroSlotCombat),achievements:ie(()=>se.PhantomBladeZeroSlotAchievementSummary),bosses:ie(()=>se.PhantomBladeZeroSlotBossSummary),collectibles:ie(()=>se.PhantomBladeZeroSlotCollectibles),quest_details:S([de(),ie(()=>se.PhantomBladeZeroQuestDetails)]),inventory_details:S([de(),oe(ie(()=>se.PhantomBladeZeroInventoryItem))]),detail:ie(()=>se.PhantomBladeZeroSlotDetail)}),PhantomBladeZeroSlotHead:fe({saveTime:O(),currentLevel:O(),cycle:O(),difficulty:ie(()=>se.PhantomBladeZeroSlotDifficulty)}),PhantomBladeZeroSlotDifficulty:fe({raw:Z(),name:O()}),PhantomBladeZeroSlotFirstClear:fe({clearDate:ie(()=>se.PhantomBladeZeroUnavailableValue),cycles:S([de(),oe(ie(()=>se.PhantomBladeZeroClearanceRecord))])}),PhantomBladeZeroUnavailableValue:fe({value:de(),reason:O()}),PhantomBladeZeroClearanceRecord:fe({Cycle:X(S([de(),Z()])),Ending:Z(),Difficulty:Z(),GameTime:S([ge().check(me(-9007199254740991),he(9007199254740991)),O().check(Ee(new RegExp("^-?(0|[1-9][0-9]*)$")))]),Completion:Z(),DiedTimes:S([ge().check(me(-9007199254740991),he(9007199254740991)),O().check(Ee(new RegExp("^-?(0|[1-9][0-9]*)$")))])}),PhantomBladeZeroSlotProgress:fe({playTimeSeconds:S([ge().check(me(-9007199254740991),he(9007199254740991)),O().check(Ee(new RegExp("^-?(0|[1-9][0-9]*)$")))]),playTime:O(),lastLaunch:ie(()=>se.PhantomBladeZeroUnavailableValue),narrativePercentage:Z(),chapter:O(),remainingDays:S([ge().check(me(-9007199254740991),he(9007199254740991)),O().check(Ee(new RegExp("^-?(0|[1-9][0-9]*)$")))])}),PhantomBladeZeroSlotCombat:fe({loadout:X(ie(()=>se.PhantomBladeZeroSlotLoadout)),totalDeaths:S([ge().check(me(-9007199254740991),he(9007199254740991)),O().check(Ee(new RegExp("^-?(0|[1-9][0-9]*)$")))]),cycleDeaths:S([ge().check(me(-9007199254740991),he(9007199254740991)),O().check(Ee(new RegExp("^-?(0|[1-9][0-9]*)$")))]),bossKillTotal:S([ge().check(me(-9007199254740991),he(9007199254740991)),O().check(Ee(new RegExp("^-?(0|[1-9][0-9]*)$")))]),currentMainWeapon:X(S([de(),ie(()=>se.PhantomBladeZeroNamedItem)])),mainWeapon:ie(()=>se.PhantomBladeZeroCollectionCount),currentShaqi:X(S([de(),ie(()=>se.PhantomBladeZeroNamedItem)])),shaqi:ie(()=>se.PhantomBladeZeroCollectionCount)}),PhantomBladeZeroSlotLoadout:fe({states:X(S([de(),oe(ie(()=>se.PhantomBladeZeroLoadoutState))])),main_weapons:S([de(),oe(O())]),shaqi_weapons:S([de(),oe(O())]),accessory_ids:S([de(),oe(O())]),top_medicine:O(),bottom_medicine:O(),current_weapon_index:Z(),current_shaqi_weapon_index:Z()}),PhantomBladeZeroLoadoutState:fe({category:O(),id:O(),level:X(Z()),soul_forged:X(S([_e(!1),_e(!0)])),reincarnation_count:X(Z())}),PhantomBladeZeroNamedItem:fe({id:O(),name:O()}),PhantomBladeZeroCollectionCount:fe({unknown:X(S([O(),Z()])),done:S([ge().check(me(-9007199254740991),he(9007199254740991)),O().check(Ee(new RegExp("^-?(0|[1-9][0-9]*)$")))]),total:S([ge().check(me(-9007199254740991),he(9007199254740991)),O().check(Ee(new RegExp("^-?(0|[1-9][0-9]*)$")))])}),PhantomBladeZeroSlotAchievementSummary:fe({unlocked:S([ge().check(me(-9007199254740991),he(9007199254740991)),O().check(Ee(new RegExp("^-?(0|[1-9][0-9]*)$")))]),total:S([ge().check(me(-9007199254740991),he(9007199254740991)),O().check(Ee(new RegExp("^-?(0|[1-9][0-9]*)$")))]),reason:O()}),PhantomBladeZeroSlotBossSummary:fe({groups:S([de(),oe(ie(()=>se.PhantomBladeZeroBossGroup))])}),PhantomBladeZeroBossGroup:fe({map:O(),mapName:O(),count:S([ge().check(me(-9007199254740991),he(9007199254740991)),O().check(Ee(new RegExp("^-?(0|[1-9][0-9]*)$")))]),bosses:S([de(),oe(ie(()=>se.PhantomBladeZeroBoss))])}),PhantomBladeZeroBoss:fe({id:O(),classPath:O(),map:O(),mapName:O(),encountered:S([_e(!1),_e(!0)]),killed:S([_e(!1),_e(!0)]),kill:S([ge().check(me(-9007199254740991),he(9007199254740991)),O().check(Ee(new RegExp("^-?(0|[1-9][0-9]*)$")))]),attempt:S([ge().check(me(-9007199254740991),he(9007199254740991)),O().check(Ee(new RegExp("^-?(0|[1-9][0-9]*)$")))]),bestTimeMs:S([ge().check(me(-9007199254740991),he(9007199254740991)),O().check(Ee(new RegExp("^-?(0|[1-9][0-9]*)$")))]),records:S([de(),oe(ie(()=>se.PhantomBladeZeroBossRecord))])}),PhantomBladeZeroBossRecord:fe({cycle:O(),diff:O(),diffName:O(),kill:S([ge().check(me(-9007199254740991),he(9007199254740991)),O().check(Ee(new RegExp("^-?(0|[1-9][0-9]*)$")))]),attempt:S([ge().check(me(-9007199254740991),he(9007199254740991)),O().check(Ee(new RegExp("^-?(0|[1-9][0-9]*)$")))]),bestTimeMs:S([ge().check(me(-9007199254740991),he(9007199254740991)),O().check(Ee(new RegExp("^-?(0|[1-9][0-9]*)$")))])}),PhantomBladeZeroSlotCollectibles:fe({overall:ie(()=>se.PhantomBladeZeroCollectionSummary),craneBellCount:S([ge().check(me(-9007199254740991),he(9007199254740991)),O().check(Ee(new RegExp("^-?(0|[1-9][0-9]*)$")))]),byBigMap:S([de(),oe(ie(()=>se.PhantomBladeZeroBigMapProgress))]),currentChapter:ie(()=>se.PhantomBladeZeroChapterProgress)}),PhantomBladeZeroCollectionSummary:fe({bell:ie(()=>se.PhantomBladeZeroCollectionCount),weapon:ie(()=>se.PhantomBladeZeroCollectionCount),shaqi:ie(()=>se.PhantomBladeZeroCollectionCount),accessory:ie(()=>se.PhantomBladeZeroCollectionCount),medicine:ie(()=>se.PhantomBladeZeroCollectionCount),challenge:ie(()=>se.PhantomBladeZeroCollectionCount),hupo:ie(()=>se.PhantomBladeZeroCollectionCount),heishi:ie(()=>se.PhantomBladeZeroCollectionCount),flower:ie(()=>se.PhantomBladeZeroCollectionCount)}),PhantomBladeZeroBigMapProgress:fe({unknown:X(S([O(),Z()])),mapID:O(),name:O(),pct:Z(),done:S([ge().check(me(-9007199254740991),he(9007199254740991)),O().check(Ee(new RegExp("^-?(0|[1-9][0-9]*)$")))]),total:S([ge().check(me(-9007199254740991),he(9007199254740991)),O().check(Ee(new RegExp("^-?(0|[1-9][0-9]*)$")))]),subMaps:S([de(),oe(O())])}),PhantomBladeZeroChapterProgress:fe({unknown:X(S([O(),Z()])),mapID:O(),pct:Z(),done:S([ge().check(me(-9007199254740991),he(9007199254740991)),O().check(Ee(new RegExp("^-?(0|[1-9][0-9]*)$")))]),total:S([ge().check(me(-9007199254740991),he(9007199254740991)),O().check(Ee(new RegExp("^-?(0|[1-9][0-9]*)$")))]),reason:O()}),PhantomBladeZeroQuestDetails:fe({CurrentMainQuestPath:O(),CurrentTutorialQuestPath:O(),TrackedQuestPath:O(),TrackedBranchID:O(),TrackedTaskPointID:O(),ManualTrackingOptOut:S([_e(!1),_e(!0)]),NarrativeSavedQuests:S([de(),oe(ie(()=>se.PhantomBladeZeroQuest))])}),PhantomBladeZeroQuest:fe({QuestClass:O(),QuestCompletion:O(),QuestBranches:S([de(),oe(ie(()=>se.PhantomBladeZeroQuestBranch))]),CompletedBranches:S([de(),oe(O())]),ReachedStateNames:S([de(),oe(O())])}),PhantomBladeZeroQuestBranch:fe({BranchID:O(),TasksProgress:S([de(),oe(S([ge().check(me(-9007199254740991),he(9007199254740991)),O().check(Ee(new RegExp("^-?(0|[1-9][0-9]*)$")))]))]),BranchType:O()}),PhantomBladeZeroInventoryItem:fe({id:O(),amount:S([ge().check(me(-9007199254740991),he(9007199254740991)),O().check(Ee(new RegExp("^-?(0|[1-9][0-9]*)$")))])}),PhantomBladeZeroSlotDetail:fe({bell:S([de(),oe(ie(()=>se.PhantomBladeZeroBellDetail))]),weapon:S([de(),oe(ie(()=>se.PhantomBladeZeroItemDetail))]),shaqi:S([de(),oe(ie(()=>se.PhantomBladeZeroItemDetail))]),accessory:S([de(),oe(ie(()=>se.PhantomBladeZeroItemDetail))]),medicine:S([de(),oe(ie(()=>se.PhantomBladeZeroItemDetail))]),challenge:S([de(),oe(ie(()=>se.PhantomBladeZeroChallengeDetail))]),hupo:S([de(),oe(ie(()=>se.PhantomBladeZeroWorldItemDetail))]),heishi:S([de(),oe(ie(()=>se.PhantomBladeZeroWorldItemDetail))]),flower:S([de(),oe(ie(()=>se.PhantomBladeZeroItemDetail))]),achievements:S([de(),oe(ie(()=>se.PhantomBladeZeroAchievementDetail))])}),PhantomBladeZeroBellDetail:fe({unknown:X(S([_e(!1),_e(!0)])),id:O(),done:S([_e(!1),_e(!0)]),equip:S([_e(!1),_e(!0)])}),PhantomBladeZeroItemDetail:fe({level:X(Z()),soul_forged:X(S([_e(!1),_e(!0)])),reincarnation_count:X(Z()),unknown:X(S([_e(!1),_e(!0)])),id:O(),name:O(),done:S([_e(!1),_e(!0)]),equip:S([_e(!1),_e(!0)]),locs:S([de(),oe(ie(()=>se.PhantomBladeZeroLocation))])}),PhantomBladeZeroLocation:fe({map:O(),mapName:O(),x:Z(),y:Z(),z:Z()}),PhantomBladeZeroChallengeDetail:fe({key:X(O()),unknown:X(S([_e(!1),_e(!0)])),index:S([ge().check(me(-9007199254740991),he(9007199254740991)),O().check(Ee(new RegExp("^-?(0|[1-9][0-9]*)$")))]),guids:S([de(),oe(O())]),done:S([_e(!1),_e(!0)]),locs:S([de(),oe(ie(()=>se.PhantomBladeZeroLocation))])}),PhantomBladeZeroWorldItemDetail:fe({key:X(O()),unknown:X(S([_e(!1),_e(!0)])),id:O(),saveGuid:O(),mobDomain:O(),done:S([_e(!1),_e(!0)]),locs:S([de(),oe(ie(()=>se.PhantomBladeZeroLocation))])}),PhantomBladeZeroAchievementDetail:fe({id:O(),name:O(),desc:O(),grade:O(),hidden:S([_e(!1),_e(!0)]),done:S([_e(!1),_e(!0)])}),UserGameDataSaveFilePage:fe({items:oe(ie(()=>se.UserGameDataSaveInfo)),hasMore:_e(!1)}),UserGameDataSaveInfo:fe({saveId:O(),createdAt:O(),files:oe(ie(()=>se.UserGameDataSaveFileInfo))}),UserGameDataSaveFileInfo:fe({fileId:O(),name:O(),sizeBytes:Z(),modifiedAt:O()})},CE=new Map([["ark.profile",ie(()=>se.ArkProfile)],["ark.gacha-analysis",ie(()=>se.ArkGachaAnalysis)],["ark.gacha-record-page",fe({items:oe(ie(()=>se.GachaRecord)),nextCursor:X(O()),hasMore:S([_e(!1),_e(!0)]),total:X(Z())})],["black_myth_wukong.save",ie(()=>se.BlackMythWukongSave)],["task_bar_hero.save",ie(()=>se.TaskBarHeroSave)],["phantom_blade_zero.save",ie(()=>se.PhantomBladeZeroSave)],["save-file-page",ie(()=>se.UserGameDataSaveFilePage)]]);function RE(e,t){return CE.get(e)?.safeParse(t).success??!1}ir.map(e=>e.method);function Ui(){const e=new Error("The operation was aborted");return e.name="AbortError",e}function Oe(e,t={}){if(e.aborted)throw t.preserveReason?e.reason===void 0?new DOMException("存储操作已取消","AbortError"):e.reason:Ui()}function jl(e){if(e.source!=="runtime-private"||e.credentials!=="omit"||e.route!=="game-save"||e.target.kind!=="absolute-url"||e.method!=="GET"||e.redirectPolicy!=="error"||e.data!==void 0||e.params!==void 0||e.headers!==void 0)return!1;try{const t=new URL(e.target.url);return t.protocol==="https:"&&t.hostname==="heybox-beijing-1251007209.cos.ap-beijing.myqcloud.com"&&!t.port&&!t.username&&!t.password&&!t.hash&&/^\/cloud_archive\/[0-9]{1,20}\.zip$/.test(t.pathname)&&t.searchParams.has("q-signature")}catch{return!1}}const Vl="METHOD_FORBIDDEN";function _t(e){const t=new Error(`小程序能力已禁用: ${e}`);return t.name="MethodForbiddenError",t.code=Vl,t}class Qe extends Error{code="HOST_REQUEST_UNSUPPORTED";constructor(t="当前 Host 不支持该请求形状",r){super(t),this.name="HostRequestUnsupportedError",r&&"cause"in r&&Object.defineProperty(this,"cause",{configurable:!0,enumerable:!1,value:r.cause}),Object.setPrototypeOf(this,new.target.prototype)}}const LE=/^[A-Za-z0-9_-]{1,64}$/,ru=1e3;function Gl(e){return LE.test(e)?e:xE(e)}function PE(e){return`id_${Gl(e.trim())}`}function vr(e,t){return`hb_miniprogram_${e}_${t}`}function Ii(e){return`hb_miniprogram_keys_${e}`}const vE="hb_user_game_data_consent_";function kE(e){return`${vE}${e}`}function xE(e){let t=2166136261;for(let r=0;r<e.length;r+=1)t^=e.charCodeAt(r),t=Math.imul(t,16777619);return(t>>>0).toString(36)}const UE=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]);function dc(e){const t=new TextEncoder().encode(e),r=Math.ceil((t.length+9)/64)*64,n=new Uint8Array(r);n.set(t),n[t.length]=128,new DataView(n.buffer).setUint32(r-4,t.length*8,!1);const i=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),s=new Uint32Array(64),a=new DataView(n.buffer);for(let c=0;c<r;c+=64){for(let y=0;y<16;y+=1)s[y]=a.getUint32(c+y*4,!1);for(let y=16;y<64;y+=1){const N=s[y-15],C=s[y-2],I=Mt(N,7)^Mt(N,18)^N>>>3,U=Mt(C,17)^Mt(C,19)^C>>>10;s[y]=s[y-16]+I+s[y-7]+U>>>0}let[u,d,l,h,f,p,g,b]=i;for(let y=0;y<64;y+=1){const N=b+(Mt(f,6)^Mt(f,11)^Mt(f,25))+(f&p^~f&g)+UE[y]+s[y]>>>0,C=(Mt(u,2)^Mt(u,13)^Mt(u,22))+(u&d^u&l^d&l);b=g,g=p,p=f,f=h+N>>>0,h=l,l=d,d=u,u=N+C>>>0}[u,d,l,h,f,p,g,b].forEach((y,N)=>{i[N]=i[N]+y>>>0})}return Array.from(i,c=>c.toString(16).padStart(8,"0")).join("")}function Mt(e,t){return e>>>t|e<<32-t}const BE=Object.freeze({upload:"你允许读取的数据可能会被上传至开发者服务器。",no_network:"此小程序未获准将你允许读取的数据上传至开发者服务器。"});function HE(e){if(e===void 0||e==="")return;let t;try{t=JSON.parse(e)}catch{return}if(typeof t!="object"||t===null||Array.isArray(t))return;const r=t;if(r.schema_version!==1||typeof r.records!="object"||r.records===null||Array.isArray(r.records))return;const n={};for(const[i,s]of Object.entries(r.records)){if(typeof s!="object"||s===null||Array.isArray(s))return;const a=s;if(a.decision!=="ask"&&a.decision!=="allow"&&a.decision!=="deny"||typeof a.revision!="number"||!Number.isSafeInteger(a.revision)||a.revision<1||a.consentFingerprint!==void 0&&!jE(a.consentFingerprint))return;n[i]={decision:a.decision,revision:a.revision,...a.decision==="allow"&&a.consentFingerprint!==void 0?{consentFingerprint:a.consentFingerprint}:{}}}return{schema_version:1,records:n}}function FE(e){return dc(`${e.miniProgramId}\0${e.userId}\0${e.environment}`).slice(0,32)}function zE(e){const t=e.miniProgramId?.trim(),r=e.userId?.trim(),n=e.environment?.trim();if(!t||!r||!n)throw Object.assign(new Error("无法确定用户数据许可作用域"),{code:"INVALID_STATE"});return Object.freeze({miniProgramId:t,userId:r,environment:n})}function jE(e){return typeof e=="string"&&/^[0-9a-f]{64}$/.test(e)}function Me(e,t,r){return{code:e,message:t,data:r}}function vs(e){return VE(e)?{code:e.code,message:e.message,data:e.data}:e instanceof Error?Me("RUNTIME_ERROR",e.message):Me("UNKNOWN_ERROR","小程序运行时异常",e)}function VE(e){return!!e&&typeof e=="object"&&typeof e.code=="string"&&typeof e.message=="string"}const fr=["account.getCurrentUserId","account.onChange","storage.getRaw","storage.setRaw"],Da=[...fr,"network.request"],nu={"post.get":["account.getCurrentUserId","account.onChange","network.request"],"post.comments.list":["account.getCurrentUserId","account.onChange","network.request"],"post.comments.delete":["account.getCurrentUserId","account.onChange","network.request"],"post.comments.setLiked":["account.getCurrentUserId","account.onChange","network.request"],"post.comments.openEditor":["account.getCurrentUserId","account.onChange","network.request","presentation.openPostCommentEditor"],"post.watch":["account.getCurrentUserId","account.onChange","network.request"],"post.setLiked":["account.getCurrentUserId","account.onChange","network.request"],"post.setFavorited":["account.getCurrentUserId","account.onChange","network.request"],"gameSaves.list":["account.getCurrentUserId","account.onChange","network.request"],"gameSaves.sync":["account.getCurrentUserId","account.onChange","network.request"],"gameSaves.readParsedData":["account.getCurrentUserId","account.onChange","network.request"],"gameSaves.getFile":["account.getCurrentUserId","account.onChange","network.request","network.stream","files.transfer","files.access"],[Xi]:["workspaceCards.requestRefresh"],[Ji]:["account.getCurrentUserId","account.getAccountKey","account.onChange"],[es]:["account.getCurrentUserId","account.ensureAuthenticated","account.onChange","network.request"],[ts]:["account.getCurrentUserId","account.onChange","network.request"],[rs]:["account.getCurrentUserId","account.ensureAuthenticated","account.onChange","network.request"],[ns]:["account.getCurrentUserId","account.onChange","network.request"],[is]:["account.getCurrentUserId","account.onChange","network.request"],[ss]:["account.getCurrentUserId","account.onChange","network.request"],[as]:["presentation.setClipboard"],[os]:["presentation.showShareMenu"],[cs]:["presentation.getViewportMetrics","presentation.captureAndShare"],[us]:["presentation.getViewportMetrics","presentation.captureAndShare"],[wr]:["presentation.applyOrientation"],[ds]:["presentation.getViewportMetrics","presentation.getNavigationBarHeight"],[ls]:["presentation.setNavigationBarStyle"],[Qn]:["storage.getRaw"],[qn]:["storage.setRaw"],[fs]:["network.request"],[hs]:["network.stream","files.transfer","files.access"],[ms]:["network.upload","files.access"],[Es]:["files.external"],[gs]:["files.external"],[ps]:["files.save"],[Wn]:["files.access"],[$n]:["files.removeFile"],[Ts]:["files.access"],[Kn]:["files.access"],[_s]:["files.access"],[Zn]:["files.access"],[As]:["files.access"],[Xn]:["files.access"],[Is]:["files.access"],[Jn]:["files.removeDirectory"],[bs]:["files.access"],[ys]:["files.access"],[ei]:["media.pick"],[Yn]:["presentation.showAppreciation"],[Ns]:["presentation.showToast"],[ws]:["presentation.showLoading"],[Ds]:["presentation.hideLoading"],[Ss]:["presentation.vibrate"],[Os]:["presentation.setClipboard"],[Ms]:["protocol.invoke"],[Cs]:["presentation.close"],[Rs]:["presentation.reload"],[Ls]:["presentation.openAppPage"],[Yt]:["account.getCurrentUserId","account.onChange","network.request"],[Nt]:["account.onChange","network.request"],[nr]:["account.getCurrentUserId","account.onChange","network.request"],[Dr]:["account.getCurrentUserId","account.onChange","network.request"],[xt]:["account.onChange","network.request"],[$r]:["account.getCurrentUserId","account.onChange","network.request"],[Kr]:["account.getCurrentUserId","account.onChange","network.request"],[Zr]:["account.getCurrentUserId","account.onChange","network.request"],[Sr]:["account.getCurrentUserId","account.onChange","network.request"],[Xs]:["companion.getInfo"],[Js]:["companion.getPreparationStatus"],[ea]:["companion.getInfo","companion.getPreparationStatus","companion.prepare"],[ta]:["companion.cancelPreparation"],[ra]:["companion.getActiveSession"],[na]:["companion.getInfo","companion.launch"],[ia]:["companion.session.write"],[sa]:["companion.session.closeStdin"],[aa]:["companion.session.terminate"],[oa]:["companion.session.ackOutput"],[ca]:["companion.openAttachment"],[ua]:["companion.showNotification"],[ec]:fr,[Ki]:Da,[Rn]:Da,[Zi]:[...Da,"files.sandbox","files.removeFile","network.stream","files.transfer"],[tc]:[...fr,"presentation.confirmDataPermission"],[rc]:fr,[nc]:fr,[ic]:[...fr,"presentation.openDataPermissions"],[sc]:fr},GE=new Set([Yn]);function Yl(e,t){if(t[e]!==!0)throw GE.has(e)?Me("REQUEST_UNSUPPORTED","当前宿主不支持该能力"):_t(e)}const YE=32*1024*1024,QE=/^application\/(?:[a-z0-9!#$&^_.+-]+\+)?json(?:\s*;|$)/i;function qE(e){if(e.mode==="request-only")return{network:{request:(n,i)=>e.request(n,i)}};if(e.mode==="override-request")return{network:{request:(n,i)=>e.request(n,i)},...e.stream===void 0?{}:{stream:e.stream}};const{consume:t,stream:r}=e;return{stream:r,network:{async request(n,i){const s=await r.open(n,i);let a;try{const c=await t(s.body,{maxBytes:YE},i);return WE(s,c)}catch(c){throw a=c,c}finally{try{await r.release(s.body)}catch(c){if(a===void 0)throw c}}}}}}function WE(e,t){const r=Object.fromEntries(Object.entries(e.headers).map(([n,i])=>[n,i.join(", ")]));return{status:e.status,...e.statusText===void 0?{}:{statusText:e.statusText},headers:r,data:$E(t,ZE(e,"content-type"))}}function $E(e,t){KE(t);let r;try{r=new TextDecoder("utf-8",{fatal:!0}).decode(e)}catch(n){throw new Qe("Host network response 不是合法 UTF-8 文本",{cause:n})}if(r.charCodeAt(0)===65279&&(r=r.slice(1)),!t||!QE.test(t)||r==="")return r;try{return JSON.parse(r)}catch{return r}}function KE(e){if(!e)return;const t=/(?:^|;)\s*charset\s*=\s*["']?([^;"'\s]+)/i.exec(e)?.[1];if(t&&!/^utf-?8$/i.test(t))throw new Qe(`Host network response 不支持 charset=${t}`)}function ZE(e,t){return Object.entries(e.headers).find(([r])=>r.toLowerCase()===t)?.[1]?.[0]}function ae(e){return typeof e=="function"}function iu(e){return(...t)=>{throw _t(e)}}function Ge(e){return async(...t)=>{throw _t(e)}}const XE=(e,t)=>{},JE=()=>()=>{};function eg(e){const t={request:ae(e.network?.request)?e.network.request.bind(e.network):Ge("network.request")},r={...ae(e.account?.getAccountKey)?{getAccountKey:e.account.getAccountKey.bind(e.account)}:{},getCurrentUserId:ae(e.account?.getCurrentUserId)?e.account.getCurrentUserId.bind(e.account):Ge("account.getCurrentUserId"),ensureAuthenticated:ae(e.account?.ensureAuthenticated)?e.account.ensureAuthenticated.bind(e.account):Ge("account.ensureAuthenticated"),onChange:ae(e.account?.onChange)?e.account.onChange.bind(e.account):JE},n={...e.storage?.withLock?{withLock:e.storage.withLock.bind(e.storage)}:{},getRaw:ae(e.storage?.getRaw)?e.storage.getRaw.bind(e.storage):Ge("storage.getRaw"),setRaw:ae(e.storage?.setRaw)?e.storage.setRaw.bind(e.storage):Ge("storage.setRaw")},i={...ae(e.presentation?.showSteamLoginRequired)?{showSteamLoginRequired:e.presentation.showSteamLoginRequired.bind(e.presentation)}:{},...ae(e.presentation?.applyOrientation)?{applyOrientation:e.presentation.applyOrientation.bind(e.presentation)}:{},...ae(e.presentation?.onViewportChange)?{onViewportChange:e.presentation.onViewportChange.bind(e.presentation)}:{},close:ae(e.presentation?.close)?e.presentation.close.bind(e.presentation):Ge("presentation.close"),reload:ae(e.presentation?.reload)?e.presentation.reload.bind(e.presentation):Ge("presentation.reload"),openAppPage:ae(e.presentation?.openAppPage)?e.presentation.openAppPage.bind(e.presentation):Ge("presentation.openAppPage"),openWindow:ae(e.presentation?.openWindow)?e.presentation.openWindow.bind(e.presentation):Ge("presentation.openWindow"),getViewportMetrics:ae(e.presentation?.getViewportMetrics)?e.presentation.getViewportMetrics.bind(e.presentation):iu("presentation.getViewportMetrics"),getNavigationBarHeight:ae(e.presentation?.getNavigationBarHeight)?e.presentation.getNavigationBarHeight.bind(e.presentation):iu("presentation.getNavigationBarHeight"),setNavigationBarStyle:ae(e.presentation?.setNavigationBarStyle)?e.presentation.setNavigationBarStyle.bind(e.presentation):Ge("presentation.setNavigationBarStyle"),showShareMenu:ae(e.presentation?.showShareMenu)?e.presentation.showShareMenu.bind(e.presentation):Ge("presentation.showShareMenu"),setScreenshotChromeHidden:ae(e.presentation?.setScreenshotChromeHidden)?e.presentation.setScreenshotChromeHidden.bind(e.presentation):XE,supportsLongScreenshot:e.presentation?.supportsLongScreenshot===!0,captureAndShare:ae(e.presentation?.captureAndShare)?e.presentation.captureAndShare.bind(e.presentation):Ge("presentation.captureAndShare"),openPostCommentEditor:ae(e.presentation?.openPostCommentEditor)?e.presentation.openPostCommentEditor.bind(e.presentation):void 0,showAppreciation:ae(e.presentation?.showAppreciation)?e.presentation.showAppreciation.bind(e.presentation):async()=>{throw Me("REQUEST_UNSUPPORTED","当前宿主不支持赞赏码")},showToast:ae(e.presentation?.showToast)?e.presentation.showToast.bind(e.presentation):Ge("presentation.showToast"),showLoading:ae(e.presentation?.showLoading)?e.presentation.showLoading.bind(e.presentation):Ge("presentation.showLoading"),hideLoading:ae(e.presentation?.hideLoading)?e.presentation.hideLoading.bind(e.presentation):Ge("presentation.hideLoading"),vibrate:ae(e.presentation?.vibrate)?e.presentation.vibrate.bind(e.presentation):Ge("presentation.vibrate"),setClipboard:ae(e.presentation?.setClipboard)?e.presentation.setClipboard.bind(e.presentation):Ge("presentation.setClipboard")},s=ae(e.storageDiagnostics?.listRaw)?{listRaw:e.storageDiagnostics.listRaw.bind(e.storageDiagnostics)}:void 0,a=Object.fromEntries(["getInfo","getPreparationStatus","prepare","cancelPreparation","getActiveSession","launch","write","closeStdin","terminate","ackOutput","openAttachment","showNotification"].map(u=>[u,ae(e.companion?.[u])?e.companion[u].bind(e.companion):Ge(`companion.${u}`)]));ae(e.companion?.onSessionEvent)&&(a.onSessionEvent=e.companion.onSessionEvent.bind(e.companion));const c={invoke:ae(e.protocol?.invoke)?e.protocol.invoke.bind(e.protocol):Ge("protocol.invoke")};return{network:t,...e.workspaceCards?{workspaceCards:e.workspaceCards}:{},account:r,storage:n,presentation:i,companion:a,protocol:c,...e.files===void 0?{}:{files:e.files},...e.picker===void 0?{}:{picker:e.picker},...e.media===void 0?{}:{media:e.media},...e.transfer===void 0?{}:{transfer:e.transfer},...e.scopedStorage?{scopedStorage:e.scopedStorage}:{},...s?{storageDiagnostics:s}:{}}}function tg(e,t={}){const r=rg(e.files?.sandbox),n=ae(e.picker?.pickFiles)&&ae(e.picker?.pickDirectory),i=ae(e.picker?.saveFile),s=r||n||i||ae(e.companion?.openAttachment),a=r?e.files?.sandbox.file(".hb-remove-capability"):void 0;return{"account.getAccountKey":ae(e.account?.getAccountKey),"account.getCurrentUserId":ae(e.account?.getCurrentUserId),"account.ensureAuthenticated":ae(e.account?.ensureAuthenticated),"account.onChange":ae(e.account?.onChange),"network.request":ae(e.network?.request),"network.stream":ae(e.transfer?.network.open)&&ae(e.transfer?.network.release),"network.upload":ae(e.transfer?.upload?.upload),"files.sandbox":r,"files.external":n,"files.save":i,"files.access":s,"files.removeFile":ae(a?.remove),"files.removeDirectory":ae(e.files?.sandbox.remove),"files.transfer":ae(e.transfer?.files.writeResource),"media.pick":ae(e.media?.pick),"storage.getRaw":ae(e.scopedStorage?.get)||ae(e.storage?.getRaw),"storage.setRaw":ae(e.scopedStorage?.set)||ae(e.storage?.setRaw),"presentation.close":ae(e.presentation?.close),"presentation.reload":ae(e.presentation?.reload),"presentation.openAppPage":ae(e.presentation?.openAppPage),"presentation.applyOrientation":ae(e.presentation?.applyOrientation),"presentation.openWindow":ae(e.presentation?.openWindow),"presentation.getViewportMetrics":ae(e.presentation?.getViewportMetrics),"presentation.getNavigationBarHeight":ae(e.presentation?.getNavigationBarHeight),"presentation.setNavigationBarStyle":ae(e.presentation?.setNavigationBarStyle),"presentation.showShareMenu":ae(e.presentation?.showShareMenu),"presentation.setScreenshotChromeHidden":!0,"presentation.captureAndShare":ae(e.presentation?.captureAndShare),"presentation.openPostCommentEditor":ae(e.presentation?.openPostCommentEditor),"presentation.showAppreciation":ae(e.presentation?.showAppreciation),"presentation.showToast":ae(e.presentation?.showToast),"presentation.showLoading":ae(e.presentation?.showLoading),"presentation.hideLoading":ae(e.presentation?.hideLoading),"presentation.vibrate":ae(e.presentation?.vibrate),"presentation.setClipboard":ae(e.presentation?.setClipboard),"workspaceCards.requestRefresh":ae(e.workspaceCards?.requestRefresh),"companion.getInfo":ae(e.companion?.getInfo),"companion.getPreparationStatus":ae(e.companion?.getPreparationStatus),"companion.prepare":ae(e.companion?.prepare),"companion.cancelPreparation":ae(e.companion?.cancelPreparation),"companion.getActiveSession":ae(e.companion?.getActiveSession),"companion.launch":ae(e.companion?.launch),"companion.session.write":ae(e.companion?.write),"companion.session.closeStdin":ae(e.companion?.closeStdin),"companion.session.terminate":ae(e.companion?.terminate),"companion.session.ackOutput":ae(e.companion?.ackOutput),"companion.openAttachment":ae(e.companion?.openAttachment),"companion.showNotification":ae(e.companion?.showNotification),"protocol.invoke":ae(e.protocol?.invoke),"presentation.confirmDataPermission":t.hasUserDataPresentation===!0,"presentation.openDataPermissions":t.hasUserDataSettings===!0}}function rg(e){if(!e||typeof e!="object")return!1;const t=e;return t.kind==="directory"&&(t.mode==="read"||t.mode==="readwrite")&&ae(t.file)&&ae(t.directory)&&ae(t.create)&&ae(t.stat)&&ae(t.list)}function su(e,t){return t?.[e]!==!1}function ng(e){return e==="network.download"||e.startsWith("files.")||e.startsWith("file.")||e.startsWith("directory.")||e.startsWith("media.")||e.startsWith("companion.")}function Ql(e,t={}){const r={};for(const n of Object.keys(nu)){const s=nu[n].every(c=>e[c]),a=!ng(n)||!!t.miniProgramDetail?.miniProgramId.trim();r[n]=su(n,t.callerCapabilities)&&su(n,t.hostCapabilities)&&s&&a}return r}function ql(e={},t={}){const r=tg(e,t),n=Ql(r,t);return{ports:eg(e),primitiveAvailability:r,availablePrimitives:r,effectiveCapabilities:n}}function Re(e,t,r){if(!t||t===e.signal)return r===void 0?e:{...e,requestId:r};const n=typeof AbortSignal.any=="function"?AbortSignal.any([e.signal,t]):ig(e.signal,t);return{...e,signal:n,...r===void 0?{}:{requestId:r}}}function ig(e,t){const r=new AbortController,n=()=>{e.removeEventListener("abort",s),t.removeEventListener("abort",a)},i=c=>{r.signal.aborted||(n(),r.abort(c.reason))},s=()=>i(e),a=()=>i(t);return e.aborted?i(e):t.aborted?i(t):(e.addEventListener("abort",s,{once:!0}),t.addEventListener("abort",a,{once:!0})),r.signal}function sg(e){if(!e||typeof e!="object"||e.lifecycle!=="cleanup")return!1;const t=e.signal;return!!t&&typeof t=="object"&&typeof t.aborted=="boolean"&&typeof t.addEventListener=="function"&&typeof t.removeEventListener=="function"}const ag=4,og=["xiaoheihe.cn","max-c.com","debugmode.cn","maxjia.com"],cg=new Set(["connection","content-length","host","origin","referer","keep-alive","proxy-connection","te","trailer","transfer-encoding","upgrade","x-heybox-runtime-auth-context-token"]),ug=["/user_miniprogram/runtime/auth","/user_miniprogram/openapi/v1"],dg=["/account/restore_login","/account/check_login","/account/login","/account/get_login_code","/account/login_code","/account/get_qrcode_url","/account/qr_state","/account/google_2fa_verify","/account/open/login","/account/captcha","/account/get_verify_code","/account/send_verify_code","/account/verify_code"];function lg(e,t){const r=mg(e);return r===null||au(r,ug)?!0:t&&au(r,dg)}function fg(e){const t=e.hostname.toLowerCase().replace(/\.$/,"");return og.some(r=>t===r||t.endsWith(`.${r}`))}function hg(e){const t=e.trim().toLowerCase();return t.startsWith("x-hb-sdk-")||t.startsWith("sec-")||cg.has(t)||/^(?:x-heybox|x-xhh)-(?:access-token|auth|authorization|pkey|session|token)$/.test(t)}function mg(e){let t=e;for(let r=0;r<ag;r+=1){let n;try{n=decodeURIComponent(t)}catch{return null}if(n===t)return ou(t);t=n}try{if(decodeURIComponent(t)!==t)return null}catch{return null}return ou(t)}function au(e,t){return t.some(r=>e===r||e.startsWith(`${r}/`))}function ou(e){const t=[];for(const r of e.replace(/\\/g,"/").split("/"))!r||r==="."||(r===".."?t.pop():t.push(r));return`/${t.join("/")}`}function Eg(e){if(typeof e!="string"||e!==e.trim()||e.length>253)return;const t=e.toLowerCase();if(!(!t.includes(".")||/^\d+(?:\.\d+)*$/.test(t))&&t.split(".").every(r=>/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/.test(r))&&!(t==="localhost"||t.endsWith(".localhost")||t.endsWith(".local")||t.endsWith(".internal")))return t}function Wl(e){if(e==null)return;if(typeof e!="object"||Array.isArray(e))throw Sa("网络策略格式无效");const t=e,r=t.entries===void 0?[]:t.entries;if(!Number.isSafeInteger(t.revision)||t.revision<1||t.enforcement!=="approved_domains"&&t.enforcement!=="restricted"||!Array.isArray(r)||r.length>20)throw Sa("网络策略格式无效");const n=new Set;for(const i of r){const s=Eg(i&&typeof i=="object"?i.domain:void 0);if(!s)throw Sa("网络策略包含无效域名");n.add(s)}return Object.freeze({revision:t.revision,enforcement:t.enforcement,entries:Object.freeze([...n].sort().map(i=>Object.freeze({domain:i})))})}function Sa(e){return Object.assign(new TypeError(e),{code:"NETWORK_POLICY_INVALID"})}function cu(e){return e instanceof Qe?{code:"REQUEST_UNSUPPORTED",message:e.message}:e}function be(e,t,r={}){if(t.aborted&&!r.invokeWhenAborted)return Promise.reject(Ui());let n;try{n=e()}catch(i){return Promise.reject(cu(i))}return t.aborted?(Promise.resolve(n).catch(()=>{}),Promise.reject(Ui())):new Promise((i,s)=>{let a=!1;const c=d=>{a||(a=!0,t.removeEventListener("abort",u),d())},u=()=>c(()=>s(Ui()));t.addEventListener("abort",u,{once:!0}),Promise.resolve(n).then(d=>c(()=>i(d)),d=>c(()=>s(cu(d))))})}async function gg(e,t,r){Oe(r);const i=e.ownerDocument.defaultView;if(!i||!e.isConnected)throw new Error("长图容器不可用");const s=e.getAttribute("style"),a=i.scrollX,c=i.scrollY,u=e.getBoundingClientRect().width,d=()=>{s===null?e.removeAttribute("style"):e.setAttribute("style",s),i.scrollTo(a,c)};try{e.style.setProperty("width",`${u}px`,"important"),e.style.setProperty("height",`${t.top+t.height}px`,"important"),e.style.setProperty("min-height","0","important"),e.style.setProperty("max-height","none","important"),i.scrollTo(0,0),await be(()=>new Promise(h=>i.requestAnimationFrame(()=>i.requestAnimationFrame(()=>h()))),r);const l=e.getBoundingClientRect();if(l.height+1<t.top+t.height||l.width+1<t.left+t.width||l.left<0||l.top<0)throw new Error("宿主布局无法容纳长图");for(let h=e.parentElement;h;h=h.parentElement){const f=i.getComputedStyle(h),p=h.getBoundingClientRect();if(["hidden","clip","scroll","auto"].includes(f.overflowY)&&(l.top+t.top<p.top-1||l.top+t.top+t.height>p.bottom+1))throw new Error("宿主布局无法容纳长图:祖先容器存在纵向裁剪")}return{rect:{...t,left:t.left+l.left,top:t.top+l.top},restore:d}}catch(l){throw d(),l}}function pg(e,t,r,n=1e4){const i=new AbortController;return new Promise((s,a)=>{let c=!1;const u=h=>{c||(c=!0,clearTimeout(l),r.signal.removeEventListener("abort",d),i.abort(h),a(h))},d=()=>{i.abort(),u({code:"NETWORK_POLICY_CHANGED",message:"网络策略初始化已取消"})},l=setTimeout(()=>u({code:"NETWORK_POLICY_UNSUPPORTED",message:"Host 网络策略初始化超时"}),n);if(r.signal.addEventListener("abort",d,{once:!0}),r.signal.aborted){d();return}Promise.resolve().then(()=>e.activate(t,{signal:i.signal})).then(h=>{if(typeof h!="function"){u({code:"NETWORK_POLICY_UNSUPPORTED",message:"Host 未完成严格网络策略初始化"});return}if(c){try{h()}catch{}return}c=!0,clearTimeout(l),s(()=>{r.signal.removeEventListener("abort",d),i.abort(),h()})},u)})}function $l(e,t){return Tg(t)??_g(e.pathname)}function Tg(e){if(!e)return;const t=new URL(e,"https://mini-program.invalid").pathname;return t.endsWith("/")?t:`${t}/`}function _g(e){const t=/^(\/u\/[^/]+\/[^/]+\/)/.exec(e)?.[1];if(t)return t;const r=e.lastIndexOf("/");return r>=0?e.slice(0,r+1):"/"}const Ag=2,Kl="allow-scripts allow-same-origin allow-pointer-lock",Ig="",bg="no-referrer";function yg(e=Kl){return!e.split(/\s+/).includes("allow-same-origin")}function uu(){return window.crypto?.randomUUID?window.crypto.randomUUID():`${Date.now().toString(36)}_${Math.random().toString(36).slice(2)}`}const Ng=new Set(["javascript:","data:","blob:","file:"]),du="xiaoheihe.cn";function wg(e,t=window.location.href,r={}){const n=e.trim();if(!n)throw new Error("缺少 mini_url 参数");let i;try{i=new URL(n)}catch{throw new Error("小程序链接必须是绝对 URL")}if(Ng.has(i.protocol)||!["http:","https:"].includes(i.protocol))throw new Error("不支持的小程序链接协议");if(!Sg(i,t,r))throw new Error("小程序链接必须属于 https://*.xiaoheihe.cn 或本地调试地址");return i.toString()}function Dg(e,t){const r=new URL(e);return r.searchParams.set(pl,t),r.toString()}function Zl(e,t,r){try{const n=new URL(e),i=new URL(t);if(n.origin!==i.origin)return!1;const s=$l(n,r);return i.pathname.startsWith(s)}catch{return!1}}function lu(e){const t=new URL(e);return lc(t)?"loopback":fc(t)?"lan":"production"}function Sg(e,t,r){return Og(e)||lc(e)||fc(e)&&Cg(t,r)}function Og(e){return e.protocol==="https:"&&Pg(e.hostname)}function lc(e){return e.protocol==="http:"&&Mg(e.hostname)}function Mg(e){return e==="localhost"||e==="127.0.0.1"||e==="[::1]"}function fc(e){return e.protocol==="http:"&&Rg(e.hostname)}function Cg(e,t){if(t.allowPrivateNetwork)return!0;try{const r=new URL(e);return lc(r)||fc(r)}catch{return!1}}function Rg(e){const t=Lg(e);return t?t[0]===10||t[0]===172&&t[1]>=16&&t[1]<=31||t[0]===192&&t[1]===168:!1}function Lg(e){const t=e.split(".");if(t.length!==4)return;const r=t.map(n=>{if(!/^\d+$/.test(n))return;const i=Number(n);return Number.isInteger(i)&&i>=0&&i<=255?i:void 0});return r.every(n=>n!==void 0)?r:void 0}function Pg(e){return e===du||e.endsWith(`.${du}`)}function vg(e){let t,r=!1,n=!1;const i=new URL(e.launchUrl).origin,s=a=>{const c=a.data;if(n||!e.iframe.contentWindow||a.source!==e.iframe.contentWindow||a.origin!==i||c?.type!=="hb-sdk:dev-document"||c.nonce!==e.nonce||typeof c.documentId!="string"||!/^[a-f0-9]{32}$/.test(c.documentId)||typeof c.href!="string"||c.href.length>8192||!Zl(e.launchUrl,c.href,e.locationBasePath))return;const u=new URL(c.href);if(!(u.username||u.password||u.searchParams.get(pl)!==e.nonce)){if(c.phase==="leaving"){c.documentId===t&&!r&&(r=!0,e.onLeaving());return}if(c.phase==="boot"){if(t!==void 0&&t!==c.documentId&&c.navigationType==="reload"){n=!0,e.onReload(u.href);return}r&&t===c.documentId&&e.onResume(),t=c.documentId,r=!1}}};return window.addEventListener("message",s),()=>{window.removeEventListener("message",s)}}function Xl(e){const t=it(e);return(r,n)=>{if(r.kind==="none")return{allowed:!0};for(const i of r.permissions){const s=t.valid?t.permissions[i]:void 0;if(!s)return{allowed:!1,code:"PERMISSION_NOT_IN_SNAPSHOT",message:`当前运行快照不包含权限: ${i};正式入口需发布包含该声明的新版本,开发入口请重新打开调试`,data:{permission:i,method:n}};if(s.status!=="enabled")return{allowed:!1,code:"PERMISSION_DENIED",message:`小程序权限未启用: ${i}`,data:{permission:i,method:n}};if(i==="post"){const a=Zs.includes(n)?"read":Gn.includes(n)?"write":void 0;if(!a||s.config[a]!==!0)return{allowed:!1,code:"PERMISSION_DENIED",message:`关联帖子未声明 ${a??n} 权限`,data:{permission:i,method:n}}}}return{allowed:!0}}}function kg(e){const t=it(e),r=Object.values(t.permissions).map(i=>Object.freeze({...i,config:Object.freeze({...i.config})})),n=e&&typeof e=="object"&&"revision"in e?e.revision:void 0;return Object.freeze({schema_version:1,...typeof n=="number"?{revision:n}:{},entries:Object.freeze(r)})}function xg(){try{return{activeElement:globalThis.document?.activeElement??null,userActivation:globalThis.navigator?.userActivation}}catch{return{activeElement:null}}}const Ug=1e3;function Bg(e,t=xg()){if(t.userActivation)return t.userActivation.isActive===!0;const r=t.lastUserInteractionAt,n=t.now??Date.now();return t.activeElement===e&&r!==void 0&&n>=r&&n-r<=Ug}const Hg="runtime.gate.probe",Jl=new Set(ir.map(e=>e.method));class Fg{iframe;nonce;onReady;getWorkspaceCardLaunchContext;onHandshake;onDuplicateHandshake;onInternalEvent;onResponsePosted;onDevUploadSession;handleMessage;handleUserInteraction;dispatcher;environmentInfo;started=!1;destroyed=!1;handshaken=!1;bridgeVersion=gl;targetOrigin;lastUserInteractionAt;operations=new Map;constructor(t){this.iframe=t.iframe,this.nonce=t.nonce,this.onReady=t.onReady,this.getWorkspaceCardLaunchContext=t.getWorkspaceCardLaunchContext,this.onHandshake=t.onHandshake,this.onDuplicateHandshake=t.onDuplicateHandshake,this.onInternalEvent=t.onInternalEvent,this.onResponsePosted=t.onResponsePosted,this.onDevUploadSession=t.onDevUploadSession,this.handleMessage=this.onMessage.bind(this),this.handleUserInteraction=this.onUserInteraction.bind(this),this.dispatcher=t.dispatcher,this.environmentInfo=t.environmentInfo,this.targetOrigin=t.targetOrigin||"*"}get protocolVersion(){return this.handshaken?this.bridgeVersion:void 0}start(){if(!(this.started||this.destroyed)){this.started=!0,window.addEventListener("message",this.handleMessage);for(const t of["pointerdown","touchend","mousedown","keydown"])window.addEventListener(t,this.handleUserInteraction,!0)}}setTargetOrigin(t){this.targetOrigin=t||"*"}destroy(){if(this.destroyed)return;const t=this.started;this.destroyed=!0,this.started=!1,this.handshaken=!1;try{t&&this.postMessage({namespace:lr,version:this.bridgeVersion,nonce:this.nonce,type:"event",method:"unload",payload:{timestamp:Date.now()}})}catch{}finally{window.removeEventListener("message",this.handleMessage);for(const r of["pointerdown","touchend","mousedown","keydown"])window.removeEventListener(r,this.handleUserInteraction,!0);this.lastUserInteractionAt=void 0;for(const r of this.operations.values())r.abort("bridge destroyed");this.operations.clear()}}postEvent(t,r){this.destroyed||this.postMessage({namespace:lr,version:this.bridgeVersion,nonce:this.nonce,type:"event",method:t,payload:r})}postInternalRequest(t,r,n){this.destroyed||this.postMessage({namespace:lr,version:this.bridgeVersion,nonce:this.nonce,type:"request",id:r,method:t,payload:n})}postProgress(t,r){this.bridgeVersion===2&&this.postMessage({namespace:lr,version:2,nonce:this.nonce,type:"event",id:t,method:_l,payload:r})}onMessage(t){if(!this.started||this.destroyed)return;if(this.onDevUploadSession&&this.iframe.contentWindow&&t.source===this.iframe.contentWindow&&t.data?.type==="hb-sdk:dev-upload-session"){const n=t.data.deviceSessionId;if(typeof n=="string"&&/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i.test(n))try{this.onDevUploadSession(n)}catch{}return}if(!this.isTrustedMiniProgramMessage(t))return;const r=t.data;if(r.type==="handshake"){this.handleHandshake(r,t.origin);return}if(r.type==="request"){let n=!1;try{const i=navigator.userActivation;if(i==null){this.handleRequest(r,this.iframe.isConnected&&document.visibilityState==="visible");return}n=Bg(this.iframe,{activeElement:document.activeElement,userActivation:i,lastUserInteractionAt:this.lastUserInteractionAt,now:Date.now()})}catch{n=!1}this.handleRequest(r,n);return}if(r.type==="cancel"&&this.handshaken&&r.id){this.operations.get(r.id)?.abort();return}r.type==="event"&&this.handshaken&&this.onInternalEvent?.(r)}onUserInteraction(t){const r=typeof t.composedPath=="function"?t.composedPath():[];(t.target===this.iframe||r.includes(this.iframe))&&(this.lastUserInteractionAt=Date.now())}isTrustedMiniProgramMessage(t){return t.source===this.iframe.contentWindow&&o0(t.data)&&(!this.handshaken||t.data.version===this.bridgeVersion)&&((this.handshaken?this.bridgeVersion:t.data.version)===1||this.targetOrigin==="*"||t.origin===this.targetOrigin)&&t.data.nonce===this.nonce}handleHandshake(t,r){const n=t.payload,i=t.version,s=!this.handshaken;if(s){if(this.onHandshake?.(n)===!1)return;this.bridgeVersion=i,i===1&&this.targetOrigin!=="*"&&r&&r!=="null"&&(this.targetOrigin=r),this.handshaken=!0,this.postEvent("launch",{timestamp:Date.now(),url:this.iframe.src})}this.environmentInfo&&t.id&&this.postMessage({namespace:lr,version:this.bridgeVersion,nonce:this.nonce,type:"response",id:t.id,method:Tl,payload:{environment:this.environmentInfo,...this.getWorkspaceCardLaunchContext?{workspaceCardLaunchContext:this.getWorkspaceCardLaunchContext()}:{}}}),this.postEvent("ready",{timestamp:Date.now()}),s?this.onReady?.(n):this.onDuplicateHandshake?.()}async handleRequest(t,r){if(!t.id||!t.method)return;if(!this.handshaken&&t.method===Hg){this.postResponse(t,{ready:!0});return}if(!this.handshaken){this.postResponse(t,void 0,Me("BRIDGE_NOT_READY","小程序 SDK 尚未完成握手"));return}if(!Jl.has(t.method)){this.postResponse(t,void 0,Me("METHOD_NOT_FOUND",`未开放小程序能力: ${t.method}`));return}if(this.operations.has(t.id)){this.postResponse(t,void 0,Me("INVALID_PARAMS","bridge request id 重复"));return}const n=new AbortController;this.operations.set(t.id,n);try{const i=await this.dispatcher.dispatch(t.method,t.payload,{requestId:t.id,postEvent:this.postEvent.bind(this),postProgress:s=>{this.operations.get(t.id)===n&&this.postProgress(t.id,s)},signal:n.signal,trustedUserGesture:r});if(i.status==="dropped"||!this.started||this.operations.get(t.id)!==n)return;this.postResponse(t,i.value)}catch(i){if(!this.started||this.operations.get(t.id)!==n)return;const s=vs(i);this.postResponse(t,void 0,s),this.postEvent("error",s)}finally{this.operations.get(t.id)===n&&(this.operations.delete(t.id),n.signal.aborted||n.abort("operation terminal"))}}postResponse(t,r,n){if(!(!this.postMessage({namespace:lr,version:t.version,nonce:this.nonce,type:"response",id:t.id,method:t.method,payload:r,error:n})||!zg(t.method)))try{this.onResponsePosted?.({method:t.method,outcome:n?"error":"success",...n?{errorCode:n.code}:{}})}catch{}}postMessage(t){const r=this.iframe.contentWindow;return r?(r.postMessage(t,this.targetOrigin),!0):!1}}function zg(e){return typeof e=="string"&&Jl.has(e)}function T(e,t,r){return r===void 0?{code:e,message:t}:{code:e,message:t,data:r}}function le(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function hc(){const e=globalThis.crypto;if(!e||typeof e.getRandomValues!="function")throw T("FILE_IO_FAILED","当前环境缺少安全随机数能力");try{const t=e.getRandomValues(new Uint8Array(16));return Array.from(t,r=>r.toString(16).padStart(2,"0")).join("")}catch{throw T("FILE_IO_FAILED","无法生成安全文件标识")}}function ef(e,t,r={}){const n=t==="readwrite"&&e.mode==="readwrite"?"readwrite":"read",i=n==="readwrite",s=r.allowRemove!==!1&&typeof e.remove=="function";return Object.freeze({kind:"file",name:e.name,mode:n,create:i?(a,c)=>e.create(a,c):co,remove:s?a=>e.remove(a):rf,read:a=>e.read(a),...typeof e.readPrefix=="function"?{readPrefix:(a,c)=>e.readPrefix(a,c)}:{},write:i?(a,c)=>e.write(a,c):co,stat:a=>e.stat(a)})}function tf(e,t,r={}){const n=t==="readwrite"&&e.mode==="readwrite"?"readwrite":"read",i=n==="readwrite",s=r.allowRemove!==!1,a=s&&typeof e.remove=="function";return Object.freeze({kind:"directory",name:e.name,mode:n,file:c=>ef(e.file(c),n,{allowRemove:s}),directory:c=>tf(e.directory(c),n,{allowRemove:s}),create:i?(c,u)=>e.create(c,u):co,remove:a?(c,u)=>e.remove(c,u):rf,stat:c=>e.stat(c),list:(c,u)=>e.list(c,u)})}function co(){return Promise.reject(T("FILE_ACCESS_DENIED","当前文件授权只允许读取"))}function rf(){return Promise.reject(T("FILE_ACCESS_DENIED","外部文件授权不允许删除"))}const jg=new Set(["REQUEST_CANCELLED","REQUEST_TIMEOUT","RUNTIME_DESTROYED","USER_DATA_PERMISSION_STORAGE_UNAVAILABLE","USER_DATA_PERMISSION_STATE_INVALID","USER_DATA_SOURCE_NOT_LINKED","USER_DATA_SOURCE_LOGIN_REQUIRED","USER_GAME_DATA_UNAVAILABLE","USER_GAME_DATA_INVALID_RESPONSE","METHOD_FORBIDDEN","FILE_PICKER_CANCELLED","FILE_ACCESS_REVOKED","FILE_ACCESS_DENIED","FILE_NOT_FOUND","DIRECTORY_NOT_FOUND","FILE_ALREADY_EXISTS","DIRECTORY_ALREADY_EXISTS","FILE_TYPE_MISMATCH","FILE_TOO_LARGE","FILE_QUOTA_EXCEEDED","FILE_ENCODING_INVALID","DIRECTORY_LIST_LIMIT_EXCEEDED","DIRECTORY_NOT_EMPTY","FILE_IO_FAILED"]),Vg={REQUEST_CANCELLED:"文件操作已取消",REQUEST_TIMEOUT:"文件操作超时",RUNTIME_DESTROYED:"小程序已关闭",USER_DATA_PERMISSION_STORAGE_UNAVAILABLE:"无法读取本地用户数据许可",USER_DATA_PERMISSION_STATE_INVALID:"本地用户数据许可状态异常,已停止访问",USER_DATA_SOURCE_NOT_LINKED:"请先在小黑盒关联对应游戏账号",USER_DATA_SOURCE_LOGIN_REQUIRED:"请先在小黑盒更新游戏来源登录",USER_GAME_DATA_UNAVAILABLE:"游戏资料暂不可用,请稍后重试",USER_GAME_DATA_INVALID_RESPONSE:"游戏资料响应异常,请稍后重试",METHOD_FORBIDDEN:"当前 Host 未开放该文件能力",FILE_PICKER_CANCELLED:"已取消文件选择",FILE_ACCESS_REVOKED:"文件授权已失效",FILE_ACCESS_DENIED:"当前文件授权不允许此操作",FILE_NOT_FOUND:"文件不存在",DIRECTORY_NOT_FOUND:"目录不存在",FILE_ALREADY_EXISTS:"文件已存在",DIRECTORY_ALREADY_EXISTS:"目录已存在",FILE_TYPE_MISMATCH:"文件类型不匹配",FILE_TOO_LARGE:"文件超过大小限制",FILE_QUOTA_EXCEEDED:"文件配额已用尽",FILE_ENCODING_INVALID:"文件编码不合法",DIRECTORY_LIST_LIMIT_EXCEEDED:"目录项数量超过限制",DIRECTORY_NOT_EMPTY:"目录不为空",FILE_IO_FAILED:"文件操作失败"};function Jr(e){const t=mc(e),r=t&&jg.has(t)?T(t,Vg[t]??"文件操作失败"):T("FILE_IO_FAILED","文件操作失败");return Object.defineProperty(r,"cause",{value:e,enumerable:!1}),r}function jt(e){try{return e()}catch(t){throw Jr(t)}}function mc(e){try{if(!le(e))return;const t=Object.getOwnPropertyDescriptor(e,"code");return t&&"value"in t&&typeof t.value=="string"?t.value:void 0}catch{return}}const fu=1024;class Ec{constructor(t,r){this.files=t,this.miniProgramDetail=r}handles=new Map;disposed=!1;createTransferScope(){return this.assertCanonicalDetail(),new Ec(void 0,this.miniProgramDetail)}dispose(){this.disposed||(this.disposed=!0,this.handles.clear())}registerFile(t,r="external",n){this.assertCanonicalDetail();const i=this.prepareFile(t,r,n),[s]=this.registerMany([i]);return bi(i.handle,{kind:"file",handleId:s})}registerFiles(t,r="external",n,i){this.assertCanonicalDetail();const s=jt(()=>{if(!Array.isArray(t))throw T("FILE_IO_FAILED","Host 返回了无效文件选择结果");const c=t.length;if(i!==void 0&&c>i)throw T("FILE_IO_FAILED","Host 返回了过多文件选择结果");if(this.handles.size+c>fu)throw T("FILE_QUOTA_EXCEEDED","当前会话的文件授权句柄已达上限");const u=[];for(let d=0;d<c;d+=1){if(!Object.prototype.hasOwnProperty.call(t,d))throw T("FILE_IO_FAILED","Host 返回了稀疏文件选择结果");u.push(this.prepareFile(t[d],r,n))}return u}),a=this.registerMany(s);return s.map((c,u)=>bi(c.handle,{kind:"file",handleId:a[u]}))}revokeFiles(t){for(const r of t)this.handles.get(r)?.handle.kind==="file"&&this.handles.delete(r)}registerDirectory(t,r="external",n){this.assertCanonicalDetail();const i=this.prepareDirectory(t,r,n),[s]=this.registerMany([i]);return mu(i.handle,{kind:"directory",handleId:s})}resolveFile(t){return this.resolveFileEntry(t).handle}resolveDirectory(t){return this.resolveDirectoryEntry(t).handle}isCompanionAttachmentRef(t){return!Ir(t)||!("handleId"in t)?!1:this.handles.get(t.handleId)?.origin==="companion-attachment"}isGameSaveRef(t){return!Ir(t)||!("handleId"in t)?!1:this.handles.get(t.handleId)?.origin==="game-save"}isUserDataDownloadRef(t){return!Ir(t)||!("handleId"in t)?!1:this.handles.get(t.handleId)?.origin==="download"}resolveFileEntry(t){this.assertCanonicalDetail();const r=Yg(t);if("handleId"in r){const a=this.readDirect(r.handleId,"file");return{ref:r,...a}}const n=this.resolveRoot(r.root),i=ri(r.relativePath);Oa(n.origin,i);const s=this.prepareFile(jt(()=>n.hostHandle.file(i)),n.origin,n.handle.mode);return{ref:r,...s}}resolveDirectoryEntry(t){this.assertCanonicalDetail();const r=Qg(t);if("handleId"in r){const a=this.readDirect(r.handleId,"directory");return{ref:r,...a}}const n=this.resolveRoot(r.root),i=r.relativePath==="."?".":ri(r.relativePath);Oa(n.origin,i);const s=this.prepareDirectory(i==="."?n.hostHandle:jt(()=>n.hostHandle.directory(i)),n.origin,n.handle.mode,!0);return{ref:r,...s}}describeFile(t,r){return gu(t),bi(t,r)}describeListedEntries(t,r,n){return this.assertCanonicalDetail(),jt(()=>{if(!Array.isArray(r))throw T("FILE_IO_FAILED","Host 返回了无效目录列表");const i=r.length;if(i>n)throw T("DIRECTORY_LIST_LIMIT_EXCEEDED","目录项数量超过限制");const s=[];for(let a=0;a<i;a+=1){if(!Object.prototype.hasOwnProperty.call(r,a))throw T("FILE_IO_FAILED","Host 返回了稀疏目录列表");const c=r[a];t.origin==="sandbox"&&le(c)&&typeof c.name=="string"&&nf(c.name)||s.push(this.describeListedEntry(t,c))}return this.assertCanonicalDetail(),s})}describeListedEntry(t,r){return jt(()=>{if(le(r)&&r.kind==="file"){const n=this.prepareFile(r,t.origin,t.handle.mode);return bi(n.handle,hu(t.ref,n.handle.name))}if(le(r)&&r.kind==="directory"){const n=this.prepareDirectory(r,t.origin,t.handle.mode);return mu(n.handle,Gg(t.ref,n.handle.name))}throw T("FILE_IO_FAILED","Host 返回了无效目录项")})}deriveFile(t,r){this.assertCanonicalDetail();const n=di(r);Oa(t.origin,n);const i=this.prepareFile(jt(()=>t.hostHandle.file(n)),t.origin,t.handle.mode);return{ref:hu(t.ref,n),...i}}assertSandboxOrigin(t){if(t.origin!=="sandbox")throw T("FILE_ACCESS_DENIED","外部文件授权不允许删除")}prepareFile(t,r,n){return jt(()=>{gu(t);const i=n??t.mode;return Eu(t.mode,i),{handle:ef(t,i,{allowRemove:r==="sandbox"}),hostHandle:t,origin:r}})}prepareDirectory(t,r,n,i=!1){return jt(()=>{$g(t,i);const s=n??t.mode;return Eu(t.mode,s),{handle:tf(t,s,{allowRemove:r==="sandbox"}),hostHandle:t,origin:r}})}registerMany(t){if(this.assertCanonicalDetail(),this.handles.size+t.length>fu)throw T("FILE_QUOTA_EXCEEDED","当前会话的文件授权句柄已达上限");const r=new Set,n=t.map(()=>{for(let i=0;i<8;i+=1){const s=hc();if(!this.handles.has(s)&&!r.has(s))return r.add(s),s}throw T("FILE_IO_FAILED","无法创建文件授权句柄")});return t.forEach((i,s)=>this.handles.set(n[s],i)),n}readDirect(t,r){if(!qg(t))throw T("FILE_ACCESS_REVOKED","文件授权句柄无效");const n=this.handles.get(t);if(!n)throw T("FILE_ACCESS_REVOKED","文件授权已失效");if(n.handle.kind!==r||n.hostHandle.kind!==r)throw T("FILE_TYPE_MISMATCH","文件句柄类型不匹配");return n}resolveRoot(t){if(this.assertCanonicalDetail(),t.kind==="sandbox"){if(!this.files)throw _t("files.sandbox");return this.prepareDirectory(jt(()=>this.files.sandbox),"sandbox",void 0,!0)}return this.readDirect(t.handleId,"directory")}assertCanonicalDetail(){if(this.disposed)throw T("FILE_ACCESS_REVOKED","文件授权已失效");if(!this.miniProgramDetail?.miniProgramId.trim())throw _t("files")}}function ri(e){if(!ac(e))throw T("INVALID_PARAMS","relativePath 不是规范逻辑路径");return e}function Oa(e,t){if(e==="sandbox"&&nf(t))throw T("FILE_ACCESS_DENIED","Runtime 私有缓存不能通过沙箱路径访问")}function nf(e){return e.split("/").some(t=>t.replace(/[. ]+$/,"").toLowerCase()===".hb-game-saves")}function di(e,t="文件名"){const r=ri(e);if(r.includes("/"))throw T("INVALID_PARAMS",`${t} 只能是 basename`);return r}function hu(e,t){return"handleId"in e?{kind:"file",root:{kind:"directory",handleId:e.handleId},relativePath:t}:{kind:"file",root:e.root,relativePath:ri(e.relativePath==="."?t:`${e.relativePath}/${t}`)}}function Gg(e,t){return"handleId"in e?{kind:"directory",root:{kind:"directory",handleId:e.handleId},relativePath:t}:{kind:"directory",root:e.root,relativePath:ri(e.relativePath==="."?t:`${e.relativePath}/${t}`)}}function bi(e,t){return{kind:"file",name:e.name,mode:e.mode,ref:t}}function mu(e,t){return{kind:"directory",name:e.name,mode:e.mode,ref:t}}function Eu(e,t){if(t==="readwrite"&&e!=="readwrite")throw T("FILE_ACCESS_DENIED","Host 未授予请求的文件写权限")}function Yg(e){return Ir(e)||sf(),e}function Qg(e){return Il(e)||sf(),e}function sf(){throw T("INVALID_PARAMS","文件引用不合法")}function qg(e){return/^[0-9a-f]{32}$/.test(e)}function Wg(e){return le(e)&&e.kind==="file"&&typeof e.name=="string"&&(e.mode==="read"||e.mode==="readwrite")&&typeof e.create=="function"&&typeof e.read=="function"&&typeof e.write=="function"&&typeof e.stat=="function"}function gu(e){if(!Wg(e))throw T("FILE_IO_FAILED","Host 返回了无效 File handle");di(e.name,"Host File name")}function $g(e,t=!1){if(!le(e)||e.kind!=="directory"||typeof e.name!="string"||e.mode!=="read"&&e.mode!=="readwrite"||typeof e.file!="function"||typeof e.directory!="function"||typeof e.create!="function"||typeof e.stat!="function"||typeof e.list!="function")throw T("FILE_IO_FAILED","Host 返回了无效 Directory handle");if(!t&&e.name.length===0)throw T("FILE_IO_FAILED","Host Directory name 不能为空");e.name&&di(e.name,"Host Directory name")}const Kg=new Set(["content-length","content-encoding","transfer-encoding","content-disposition","content-range","content-type"]),Zg=new Set(["content-length","content-encoding","content-disposition","content-range","content-type"]),Xg=new Set(["range","if-range","a-im"]),Jg=new Set(["METHOD_FORBIDDEN","DOWNLOAD_HTTP_STATUS","DOWNLOAD_NETWORK_FAILED","DOWNLOAD_TIMEOUT","DOWNLOAD_CANCELLED","FILE_ACCESS_REVOKED","FILE_ACCESS_DENIED","FILE_NOT_FOUND","DIRECTORY_NOT_FOUND","FILE_ALREADY_EXISTS","DIRECTORY_ALREADY_EXISTS","FILE_TYPE_MISMATCH","FILE_TOO_LARGE","FILE_QUOTA_EXCEEDED","FILE_IO_FAILED"]),ep=/^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\..*)?$/i,yi={initial:0,target:1,open:2,validate:3,transfer:4,committed:5,completed:6};class tp{constructor(t){this.signal=t}phase="initial";transition(t){if(yi[t]<=yi[this.phase])throw T("FILE_IO_FAILED","下载状态转换不合法");this.phase=t}throwIfCancelled(){if(yi[this.phase]<yi.committed&&this.signal.aborted)throw cf()}normalizeHostError(t,r){return this.throwIfCancelled(),pc(t,r,this.signal)}}async function af(e,t,r){const n=r.transfer,i=r.fileRegistry;if(!n||!i)throw _t("network.download");const s=Re(r.operationContext,t.signal),a=new tp(s.signal);a.transition("target"),a.throwIfCancelled();let c;try{c=await sp(e,i,s)}catch(l){throw a.normalizeHostError(l,"file")}a.throwIfCancelled();let u;a.transition("open");try{u=await n.network.open(e.request,s)}catch(l){throw a.normalizeHostError(l,"network")}let d=!1;try{a.throwIfCancelled(),a.transition("validate");const l=op(u);cp(u,l);const h=up(u.status,l);if(e.maxBytes!==void 0&&h.expectedBytes!==void 0&&h.expectedBytes>e.maxBytes)throw T("FILE_TOO_LARGE","下载响应超过 maxBytes");a.throwIfCancelled();const f=ap(e,c,l,i);let p=0;const g=np(h.expectedBytes,e.maxBytes);Ca(t,Ma(0,h));const b={...s,onProgress(C){!Number.isSafeInteger(C)||C<p||g!==void 0&&C>g||(p=C,Ca(t,Ma(p,h)))}};a.transition("transfer"),d=!0;let y;try{y=await n.files.writeResource(f.hostHandle,u.body,{mode:f.mode,...e.maxBytes===void 0?{}:{maxBytes:e.maxBytes},...h.expectedBytes===void 0?{}:{expectedBytes:h.expectedBytes}},b)}catch(C){throw a.normalizeHostError(C,"transfer")}a.transition("committed"),p=rp(y,h,p,e.maxBytes),Ca(t,Ma(p,h));const N=i.describeFile(f.handle,f.ref);return a.transition("completed"),N}finally{d||ip(n.network,u.body)}}function rp(e,t,r,n){if(t.expectedBytes!==void 0)return t.expectedBytes;const i=n===void 0?r:Math.min(r,n);try{const s=e?.committedBytes;if(typeof s=="number"&&Number.isSafeInteger(s)&&s>=i&&(n===void 0||s<=n))return s}catch{}return i}function np(e,t){return e===void 0?t:t===void 0?e:Math.min(e,t)}function ip(e,t){try{Promise.resolve(e.release(t)).catch(()=>{})}catch{}}async function sp(e,t,r){if(e.targetKind==="file"){const i=t.resolveFileEntry(e.to);return uo(i.handle.mode),await gp(i.handle,r),{kind:"file",...i}}const n=t.resolveDirectoryEntry(e.to);return uo(n.handle.mode),await pp(n.handle,r),{kind:"directory",...n}}function ap(e,t,r,n){if(t.kind==="file")return{ref:t.ref,handle:t.handle,hostHandle:t.hostHandle,mode:"replace-existing"};const i=lp(e,r),s=n.deriveFile(t,i);return uo(s.handle.mode),{...s,mode:e.overwrite===!0?"upsert":"create-exclusive"}}function op(e){if(!e||typeof e!="object"||!Number.isInteger(e.status)||e.status<100||e.status>599||e.statusText!==void 0&&typeof e.statusText!="string"||!e.body||typeof e.body!="object")throw T("DOWNLOAD_NETWORK_FAILED","Host 返回了无效 stream response");if(!le(e.headers))throw T("DOWNLOAD_NETWORK_FAILED","Host 返回了无效 stream headers");const t={};for(const[r,n]of Object.entries(e.headers)){if(r!==r.toLowerCase()||!Kg.has(r)||!Array.isArray(n)||n.length===0)throw T("DOWNLOAD_NETWORK_FAILED","Host 返回了不安全 stream header");if(n.some(i=>typeof i!="string"||/[\r\n]/.test(i)))throw T("DOWNLOAD_NETWORK_FAILED","Host 返回了无效 stream header value");t[r]=[...n]}return t}function cp(e,t){if(e.status<200||e.status>=300||e.status===206||e.status===226)throw T("DOWNLOAD_HTTP_STATUS",`下载请求失败: HTTP ${e.status}`,{status:e.status,...e.statusText===void 0?{}:{statusText:e.statusText},headers:Ep(t,Zg)});if((t["content-range"]?.length??0)>0)throw T("DOWNLOAD_NETWORK_FAILED","下载响应包含 Content-Range")}function up(e,t){const r=t["content-length"]??[],n=t["transfer-encoding"]??[];if(r.length>0&&n.length>0)throw T("DOWNLOAD_NETWORK_FAILED","下载响应同时包含 Transfer-Encoding 与 Content-Length");if((e===204||e===205)&&r.some(d=>d!=="0"))throw T("DOWNLOAD_NETWORK_FAILED","无内容响应声明了非零 Content-Length");if((e===204||e===205)&&n.length>0)throw T("DOWNLOAD_NETWORK_FAILED","无内容响应不允许 Transfer-Encoding");const i=r.length===1&&/^(?:0|[1-9]\d*)$/.test(r[0])?Number(r[0]):void 0,s=i!==void 0&&Number.isSafeInteger(i)?i:void 0,a=dp(t["content-encoding"]),c=e===204||e===205?0:n.length===0&&a?s:void 0,u=c!==void 0;return{...c===void 0?{}:{expectedBytes:c},...u?{total:c}:{},lengthComputable:u}}function dp(e){return!e||e.length===0?!0:e.length===1&&e[0].trim().toLowerCase()==="identity"}function Ma(e,t){return{loaded:e,...t.total===void 0?{}:{total:t.total},lengthComputable:t.lengthComputable}}function Ca(e,t){try{e.postProgress(t)}catch{}}function lp(e,t){const r=t["content-disposition"]??[];for(const i of r){const s=fp(i);if(s&&Bi(s))return s}for(const i of r){const s=hp(i);if(s&&Bi(s))return s}if(e.suggestedName!==void 0)return gc(e.suggestedName);const n=mp(e.url);return n&&Bi(n)?n:"download.bin"}function fp(e){const t=/(?:^|;)\s*filename\*\s*=\s*([^;]+)/i.exec(e);if(!t)return;const r=t[1].trim().replace(/^"|"$/g,""),n=/^utf-8'[^']*'(.*)$/i.exec(r);if(n)try{return decodeURIComponent(n[1])}catch{return}}function hp(e){const t=/(?:^|;)\s*filename\s*=\s*"((?:\\.|[^"\\])*)"/i.exec(e)?.[1];return t!==void 0?t.replace(/\\(["\\])/g,"$1"):/(?:^|;)\s*filename\s*=\s*([^;]+)/i.exec(e)?.[1]?.trim()}function mp(e){const t=e.pathname.split("/").pop();if(t)try{return decodeURIComponent(t)}catch{return}}function gc(e){try{di(e,"suggestedName")}catch{throw T("INVALID_PARAMS","suggestedName 不是安全 basename")}if(!Bi(e))throw T("INVALID_PARAMS","suggestedName 不是安全 basename");return e}function Bi(e){return!(!e||e==="."||e===".."||Array.from(e).length>255||/[\\/<>:"|?*\u0000-\u001f\u007f]/.test(e)||/[. ]$/.test(e)||ep.test(e))}function Ep(e,t){return Object.fromEntries(Object.entries(e).filter(([r])=>t.has(r)).map(([r,n])=>[r,n.join(", ")]))}async function gp(e,t){try{const r=await e.stat(t);if(!r||r.kind!=="file")throw of()}catch(r){throw pc(r,"file",t.signal)}}async function pp(e,t){try{const r=await e.stat(t);if(!r||r.kind!=="directory")throw of()}catch(r){throw pc(r,"file",t.signal)}}function uo(e){if(e!=="readwrite")throw T("FILE_ACCESS_DENIED","下载目标只允许读取")}const Tp={METHOD_FORBIDDEN:"当前 Host 未开放下载能力",DOWNLOAD_HTTP_STATUS:"下载请求返回了失败状态",DOWNLOAD_NETWORK_FAILED:"下载网络请求失败",DOWNLOAD_TIMEOUT:"下载网络请求超时",DOWNLOAD_CANCELLED:"下载已取消",FILE_ACCESS_REVOKED:"下载目标授权已失效",FILE_ACCESS_DENIED:"下载目标不允许写入",FILE_NOT_FOUND:"下载目标文件不存在",DIRECTORY_NOT_FOUND:"下载目标目录不存在",FILE_ALREADY_EXISTS:"下载目标文件已存在",DIRECTORY_ALREADY_EXISTS:"下载目标目录已存在",FILE_TYPE_MISMATCH:"下载目标类型不匹配",FILE_TOO_LARGE:"下载响应超过大小限制",FILE_QUOTA_EXCEEDED:"下载目标配额已用尽",FILE_IO_FAILED:"下载文件写入失败"};function pc(e,t,r){if(r.aborted)return cf();const n=_p(e);if(n&&Jg.has(n)){const s=T(n,Tp[n]??"下载失败");return Object.defineProperty(s,"cause",{value:e,enumerable:!1}),s}if(e instanceof Error&&e.name==="AbortError")return t==="network"||t==="transfer"?T("DOWNLOAD_TIMEOUT","下载网络请求超时"):T("FILE_IO_FAILED","下载文件写入失败");const i=t==="network"?T("DOWNLOAD_NETWORK_FAILED","下载网络请求失败"):T("FILE_IO_FAILED","下载文件写入失败");return Object.defineProperty(i,"cause",{value:e,enumerable:!1}),i}function _p(e){return le(e)&&typeof e.code=="string"?e.code:void 0}function of(){return T("FILE_TYPE_MISMATCH","下载目标类型不匹配")}function cf(){return T("DOWNLOAD_CANCELLED","下载已取消")}function Ap(e){if(!e)return;const t=Object.keys(e).find(r=>Xg.has(r.trim().toLowerCase()));if(t)throw T("INVALID_PARAMS",`network.download 不允许设置请求头: ${t}`)}const pu=8*1024*1024,Ip=32*1024*1024;function Tc(e){const t=new Map;let r=0;const n={signal:new AbortController().signal,lifecycle:"cleanup"},i=c=>c.remove(n).catch(()=>{}),s=async c=>{const u=t.get(c);u&&(t.delete(c),r-=u.size,await i(u.target))};e.signal.addEventListener("abort",()=>{for(const c of t.keys())s(c)},{once:!0});const a=c=>{if(e.signal.aborted||c.signal.aborted)throw T("DOWNLOAD_CANCELLED","存档下载已取消")};return{release:s,sizeOf:c=>t.get(c)?.size,async download(c,u,d){const l=c.file;if(!l||typeof l.file_id!="string"||typeof l.name!="string"||typeof l.size_bytes!="number"||!Number.isSafeInteger(l.size_bytes)||l.size_bytes<0||typeof c.download_url!="string"||typeof c.expires_at!="number"||!Number.isSafeInteger(c.expires_at))throw T("INVALID_RESPONSE","存档下载描述无效");if(l.size_bytes>pu)throw T("FILE_TOO_LARGE","存档文件超过 8 MiB");const h={source:"runtime-private",credentials:"omit",route:"game-save",redirectPolicy:"error",method:"GET",target:{kind:"absolute-url",url:c.download_url},timeout:6e4};if(!jl(h)||new URL(c.download_url).pathname!==`/cloud_archive/${l.file_id}.zip`||c.expires_at<=Date.now())throw T("INVALID_RESPONSE","存档下载地址无效");a(d);const f=Math.min(pu,Ip-r);if(f<=0)throw T("FILE_QUOTA_EXCEEDED","当前会话存档缓存已达上限");const p=e.files.sandbox.file(`.hb-game-saves/${hc()}.zip`);if(!p.remove)throw T("REQUEST_UNSUPPORTED","宿主不支持私有存档清理");r+=f;let g=!1;try{await e.files.sandbox.directory(".hb-game-saves").create({recursive:!0,exclusive:!1},d),await p.create({recursive:!0,exclusive:!0},d);const b=e.registry.createTransferScope();try{const I=b.registerFile(p,"game-save","readwrite");await af({request:h,url:new URL(c.download_url),to:I.ref,targetKind:"file",maxBytes:f},{...d,trustedUserGesture:!1,postEvent:()=>{},postProgress:()=>{}},{transfer:e.transfer,fileRegistry:b,operationContext:d})}finally{b.dispose()}a(d);const y=(await p.stat(d)).size;if(!Number.isSafeInteger(y)||y<0||y>f)throw T("FILE_TOO_LARGE","存档实际大小超过限额");await u(d),a(d);const N=async()=>{throw T("FILE_ACCESS_DENIED","存档文件只读")},C={kind:"file",mode:"read",name:l.name,create:N,write:N,async read(I){a(I),await u(I);const U=await p.read(I);try{if(a(I),await u(I),U.byteLength!==y)throw T("INVALID_RESPONSE","私有存档副本长度不匹配");return U}catch(Y){throw U.fill(0),Y}},async stat(I){return a(I),await u(I),await p.stat(I),a(I),await u(I),{kind:"file",size:y,...typeof l.modified_at=="number"&&Number.isSafeInteger(l.modified_at)?{modifiedAt:l.modified_at}:{}}}};return r-=f-y,t.set(C,{target:p,size:y}),g=!0,C}finally{g||(r-=f,await i(p))}}}}const bp=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*)(?:\.(?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*))*))?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/;function yp(e){if(!e?.minimumSdkVersion)throw Me("MINIMUM_SDK_VERSION_UNAVAILABLE","平台最低 SDK 版本配置不可用");const t=pr(e.minimumSdkVersion),r=e.sdkVersion?pr(e.sdkVersion):void 0;if(!t)throw Me("MINIMUM_SDK_VERSION_UNAVAILABLE","平台最低 SDK 版本配置不合法");if(e.sdkVersion&&!r)throw Me("SDK_VERSION_INVALID","小程序 SDK 版本不合法");const n=pr("0.6.0");if(!r){if(Hi(t,n)<0)return{heartbeatEnabled:!1,sdkVersion:void 0};throw Me("SDK_VERSION_INVALID","小程序 SDK 版本缺失")}if((e.releaseChannel??"public")==="public"&&r.prerelease.length>0&&e.allowPublicPrerelease!==!0)throw Me("SDK_VERSION_INVALID","正式小程序不能使用预发布 SDK");if(Hi(r,t)<0)throw Me("SDK_VERSION_TOO_LOW","小程序 SDK 版本低于平台最低要求");return{heartbeatEnabled:Hi(r,pr("0.6.0-0"))>=0,sdkVersion:e.sdkVersion}}function Np(e,t){if(typeof t!="string"||!pr(t))throw Me("SDK_VERSION_INVALID","SDK handshake 版本不合法");if(t!==e)throw Me("SDK_VERSION_MISMATCH","SDK handshake 版本与 Version record 不一致")}function _c(e,t){const r=pr(e),n=pr(t);if(!(!r||!n))return Hi(r,n)}function pr(e){const t=bp.exec(e);if(t)return{major:Number(t[1]),minor:Number(t[2]),patch:Number(t[3]),prerelease:t[4]?.split(".").map(r=>/^\d+$/.test(r)?Number(r):r)??[]}}function Hi(e,t){for(const n of["major","minor","patch"])if(e[n]!==t[n])return e[n]<t[n]?-1:1;if(e.prerelease.length===0||t.prerelease.length===0)return e.prerelease.length===t.prerelease.length?0:e.prerelease.length===0?1:-1;const r=Math.max(e.prerelease.length,t.prerelease.length);for(let n=0;n<r;n+=1){const i=e.prerelease[n],s=t.prerelease[n];if(i===void 0||s===void 0)return i===s?0:i===void 0?-1:1;if(i!==s)return typeof i=="number"&&typeof s=="string"?-1:typeof i=="string"&&typeof s=="number"?1:i<s?-1:1}return 0}function wp(e){return{[Yn]:async(t,r)=>{const n=Re(e.operationContext,r.signal);if(Oe(n.signal),t!==void 0)throw T("INVALID_PARAMS","user.showAppreciation 不支持参数");if(!r.trustedUserGesture)throw T("USER_GESTURE_REQUIRED","请通过点击打开赞赏码");const i=e.miniProgramPresentation;if(!i?.name||!i.author)throw T("INVALID_STATE","缺少小程序名称或开发者信息,无法展示赞赏码");const s=e.presentation.showAppreciation;if(!s)throw T("REQUEST_UNSUPPORTED","当前宿主不支持赞赏码");await be(()=>s({name:i.name,author:i.author},n),n.signal)}}}function kr(){const e=new Error("Runtime cache read cancelled");return e.name="AbortError",e}function Tu(e,t){return e.length===t.length&&e.every((r,n)=>r===t[n])}function uf(e={}){const t=e.now??Date.now,r=new WeakMap,n=new Map,i=new Set,s=new Map,a=new Set,c=new Set;let u=!1;function d(b,y){try{e.onEvent&&Promise.resolve(e.onEvent({namespace:b,type:y})).catch(()=>{})}catch{}}function l(b){const y=r.get(b);if(!y)throw new Error("Unknown runtime cache scope");return y}function h(b,y){return b.flatMap((N,C)=>{const I=JSON.stringify(b.slice(0,C+1));return[JSON.stringify([I]),JSON.stringify([I,y])]})}function f(b,y){return JSON.stringify(h(b,y).map(N=>n.get(N)??0))}async function p(b,y){const N=l(b),C=JSON.stringify([JSON.stringify(N),...y?[y]:[]]),I=(n.get(C)??0)+1;n.set(C,I),i.add(C);for(const U of c)U(N,y);if(!e.store){i.delete(C),d(y??"*","invalidation");return}try{await e.store.invalidate(N,y)}catch(U){throw d(y??"*","storage_error"),U}n.get(C)===I&&i.delete(C),d(y??"*","invalidation")}function g(b){if(u)throw new Error("Runtime cache manager disposed");const y=s.get(b.namespace);if(y){if(y.sourceCodec!==b.codec||y.definition.codec.version!==b.codec.version||JSON.stringify(y.definition.policy)!==JSON.stringify(b.policy))throw new Error("Conflicting runtime cache namespace");return y.cache}if(!b.namespace||!b.codec.version)throw new Error("Invalid runtime cache definition");const N=Object.freeze({...b.policy}),C=Object.freeze({version:b.codec.version,encode:b.codec.encode.bind(b.codec),decode:b.codec.decode.bind(b.codec),validate:b.codec.validate.bind(b.codec),clone:b.codec.clone.bind(b.codec)}),I=b.namespace;for(const v of[N.ttlMs,N.memoryMaxEntries,N.diskMaxEntries,N.diskMaxBytes,N.maxEntryBytes])if(!Number.isFinite(v)||v<0)throw new Error("Invalid runtime cache policy");const U=new Map,Y=new Map,R=new Map;let P=!1;function M(v,L,q){if(u||P||v.aborted||f(L,I)!==q)throw kr()}function V(v){return N.ttlMs>0&&N.persistence==="memory-and-disk"&&!!e.store&&!h(v,I).some(L=>i.has(L))}function z(v,L,q){const D=t();return v.envelopeVersion===1&&JSON.stringify(v.address)===JSON.stringify(L)&&Tu(v.revisions,q)&&v.payload.byteLength<=N.maxEntryBytes&&Number.isFinite(v.cachedAt)&&Number.isFinite(v.expiresAt)&&v.cachedAt<=D&&v.cachedAt>=0&&v.expiresAt>v.cachedAt&&Math.min(v.expiresAt,v.cachedAt+N.ttlMs)>D}function te(v,L,q,D,W){if(!(N.ttlMs<=0||N.memoryMaxEntries<1)){for(const[$,m]of U)Math.min(m.entry.expiresAt,m.entry.cachedAt+N.ttlMs)<=t()&&U.delete($);for(U.delete(v);U.size>=Math.floor(N.memoryMaxEntries);){const $=U.keys().next();if($.done)break;U.delete($.value)}U.set(v,{entry:L,value:q,epoch:D,persistent:W})}}async function x(v,L,q,D){const W={namespace:I,codecVersion:C.version,scopeIds:L,key:v.key},$=JSON.stringify(W);let m=[],w=V(L);if(w)try{m=await e.store.readRevisions(L,I)}catch{w=!1,d(I,"storage_error")}M(D.signal,L,q);async function B(){if(!w)return!0;try{return Tu(m,await e.store.readRevisions(L,I))}catch{return w=!1,d(I,"storage_error"),!1}}const K=U.get($);if(N.ttlMs>0&&K&&K.epoch===q&&z(K.entry,W,m)&&K.persistent===w&&await B())return M(D.signal,L,q),d(I,"memory_hit"),K.value;if(U.delete($),w){let ue,Te;try{ue=await e.store.read(W,N.maxEntryBytes),ue&&z(ue,W,m)?Te=C.decode(ue.payload):ue=void 0}catch{ue=void 0,d(I,"storage_error")}if(M(D.signal,L,q),ue&&await B())return M(D.signal,L,q),te($,ue,Te,q,!0),d(I,"disk_hit"),Te}d(I,"miss");const ce=C.validate(await v.load(D.signal));M(D.signal,L,q);const pe=C.clone(ce);if(!await B()&&w)throw kr();if(M(D.signal,L,q),N.ttlMs>0){const ue=t();let Te;try{Te=C.encode(pe)}catch{return pe}const we={envelopeVersion:1,address:W,revisions:w?m:[],cachedAt:ue,expiresAt:ue+N.ttlMs,payload:Te};if(w&&Te.byteLength<=N.maxEntryBytes){let Ae=!0,Ie=!1;try{Ae=await e.store.publish(we,N),Ie=Ae}catch{d(I,"storage_error")}if(M(D.signal,L,q),!Ae)throw kr();Ie&&d(I,"published")}M(D.signal,L,q),te($,we,pe,q,w)}return pe}async function Q(v){if(u||P||v.signal?.aborted)return Promise.reject(kr());const L=l(v.scope),q=f(L,I);let D;if(V(L)){const w=new AbortController;R.set(w,L);const B=()=>w.abort();v.signal?.addEventListener("abort",B,{once:!0});let K=()=>{};try{D=await Promise.race([e.store.readRevisions(L,I),new Promise((ce,pe)=>{const ue=()=>pe(kr());w.signal.addEventListener("abort",ue,{once:!0}),K=()=>w.signal.removeEventListener("abort",ue)})])}catch{w.signal.aborted||d(I,"storage_error")}finally{K(),R.delete(w),v.signal?.removeEventListener("abort",B)}}M(v.signal??new AbortController().signal,L,q);const W=JSON.stringify([L,v.key,q,D]);let $=Y.get(W);if($?.controller.signal.aborted&&($=void 0),!$){const w=new AbortController;$={ids:L,controller:w,waiters:0,promise:Promise.resolve(void 0)};const B=$;B.promise=x(v,L,q,w).finally(()=>{Y.get(W)===B&&Y.delete(W)}),Y.set(W,B)}const m=$;return m.waiters+=1,new Promise((w,B)=>{let K=!1;function ce(ue){K||(K=!0,v.signal?.removeEventListener("abort",pe),m.controller.signal.removeEventListener("abort",pe),m.waiters-=1,m.waiters===0&&m.controller.abort(),ue())}function pe(){ce(()=>B(kr()))}v.signal?.addEventListener("abort",pe,{once:!0}),m.controller.signal.addEventListener("abort",pe,{once:!0}),m.promise.then(ue=>ce(()=>{try{M(v.signal??new AbortController().signal,L,q),w(C.clone(ue))}catch(Te){B(Te)}}),ue=>ce(()=>B(ue)))})}function j(v,L){if(L&&L!==I)return;const q=D=>v.every((W,$)=>D[$]===W);for(const[D,W]of U)q(W.entry.address.scopeIds)&&U.delete(D);for(const[D,W]of Y)q(W.ids)&&(W.controller.abort(),Y.delete(D));for(const[D,W]of R)q(W)&&D.abort()}function H(){if(!P){P=!0,U.clear();for(const v of R.keys())v.abort();R.clear();for(const v of Y.values())v.controller.abort();Y.clear(),a.delete(H),c.delete(j),s.get(I)?.cache===F&&s.delete(I)}}const F={read:Q,invalidateScope:v=>p(v,I),dispose:H};return a.add(H),c.add(j),s.set(I,{definition:{namespace:I,codec:C,policy:N},sourceCodec:b.codec,cache:F}),F}return{createScope(b,y){if(u||!b)throw new Error("Invalid runtime cache scope");const N=Object.freeze({});return r.set(N,[...y?l(y):[],b]),N},register:g,invalidateScope:b=>p(b),dispose(){if(!u){u=!0;for(const b of[...a])b();s.clear(),n.clear(),i.clear()}}}}function Dp(e){const t=new TextEncoder,r=new TextDecoder("utf-8",{fatal:!0});return{version:e.version,validate:e.validate,encode:n=>t.encode(JSON.stringify(n)),decode:n=>e.validate(JSON.parse(r.decode(n))),clone:n=>e.validate(JSON.parse(JSON.stringify(n)))}}const Sp=".hb-runtime-cache-v1",Op=1e3,Ra=64*1024,xr=1e3,Mp=2048,gn=32*1024*1024,Cp=1024,Fi=new TextEncoder,_u=new TextDecoder("utf-8",{fatal:!0});function pn(){return Object.assign(new Error("缓存文件操作已取消"),{name:"AbortError"})}async function Ni(e){const t=await globalThis.crypto.subtle.digest("SHA-256",Fi.encode(JSON.stringify(e)));return Array.from(new Uint8Array(t),r=>r.toString(16).padStart(2,"0")).join("")}function Ct(e,t){return JSON.stringify(e)===JSON.stringify(t)}function Au(){return Array.from(globalThis.crypto.getRandomValues(new Uint8Array(16)),e=>e.toString(16).padStart(2,"0")).join("")}function Rp(e){return!!e&&typeof e=="object"&&["METHOD_FORBIDDEN","NOT_SUPPORTED","UNSUPPORTED_OPERATION","ENOSYS","ENOTSUP","EOPNOTSUPP"].includes(String(e.code))}function Iu(e,t){if(t.some(r=>typeof e[r]!="function"))throw Object.assign(new Error("Host 文件原语不完整,关闭磁盘缓存"),{code:"METHOD_FORBIDDEN"})}function Lp(e,t){const r=e.sandbox.directory(Sp),n=r.directory("revisions"),i=r.directory("entries");for(const x of[r,n,i,i.directory("capability-check")])Iu(x,["directory","file","create","stat","list","remove"]),Iu(x.file("capability-check"),["create","stat","read","write","remove"]);const s=new AbortController,a=()=>s.abort();t.signal.aborted?a():t.signal.addEventListener("abort",a,{once:!0});const c={...t,signal:s.signal};let u=Promise.resolve(),d;function l(x){d=x,s.abort(),t.signal.removeEventListener("abort",a)}function h(x){if(Rp(x))throw l(x),x}function f(){if(d)throw d;if(c.signal.aborted)throw pn()}function p(x,Q=c.signal){const j=u.then(()=>{if(Q.aborted)throw d??pn();return f(),x()},()=>{if(Q.aborted)throw d??pn();return f(),x()}).catch(L=>{throw h(L),L});if(u=j.catch(()=>{}),Q.aborted)return Promise.reject(d??pn());let H=()=>{};const F=new Promise((L,q)=>{const D=()=>q(d??pn());Q.addEventListener("abort",D,{once:!0}),H=()=>Q.removeEventListener("abort",D)}),v=setTimeout(()=>{l(Object.assign(new Error("缓存文件操作超时,已降级为内存缓存"),{code:"CACHE_STORAGE_TIMEOUT"}))},Op);return Promise.race([j,F]).finally(()=>{clearTimeout(v),H()})}async function g(){f(),await n.create({recursive:!0,exclusive:!1},c),f(),await i.create({recursive:!0,exclusive:!1},c),f()}async function b(x,Q){const j=n.file(`${await Ni([x,Q??null])}.revision`);await N(j);let H=!1;try{await j.create({recursive:!1,exclusive:!0},c),H=!0}catch(L){h(L),f()}if(H){const L=Au();return await j.write(Fi.encode(L),c),f(),L}const F=await j.stat(c);if(F.size<1||F.size>128)throw new Error("缓存 revision 文件损坏");const v=_u.decode(await j.read(c));if(!/^(?:[0-9a-f]{32}|[0-9a-f-]{36})$/.test(v))throw new Error("缓存 revision 文件损坏");return f(),v}async function y(x){const Q=await x.list({limit:xr},c);if(Q.length>=xr)throw new Error("缓存目录超过治理上限");return Q}async function N(x){try{await x.stat(c);return}catch(j){if(!wi(j))throw j}if((await y(n)).length>=xr-1)throw new Error("缓存 metadata 超过治理上限")}async function C(x,Q){await g();const j=[];for(let H=0;H<x.length;H+=1){const F=x.slice(0,H+1);j.push(await b(F),await b(F,Q))}return j}async function I(x){return r.directory(`entries/${await Ni([x.namespace,x.codecVersion,x.scopeIds])}`)}async function U(x){return(await I(x)).file(`${await Ni(x.key)}.cache`)}async function Y(x,Q){const j=await x.stat(c);if(j.size<5||j.size>Q+Ra+4)throw new Error("缓存条目超过大小限制");const H=await x.read(c);if(f(),H.length!==j.size)throw new Error("缓存条目读取不完整");const F=new DataView(H.buffer,H.byteOffset,H.byteLength).getUint32(0);if(F<1||F>Ra||F+4>H.length)throw new Error("缓存信封损坏");const v=JSON.parse(_u.decode(H.subarray(4,F+4))),L=H.slice(F+4);if(v.envelopeVersion!==1||!v.address||!Array.isArray(v.address.scopeIds)||!v.address.scopeIds.every(q=>typeof q=="string")||typeof v.address.namespace!="string"||typeof v.address.codecVersion!="string"||typeof v.address.key!="string"||!Array.isArray(v.revisions)||v.revisions.length!==v.address.scopeIds.length*2||!v.revisions.every(q=>typeof q=="string"&&q.length>0)||!Number.isSafeInteger(v.cachedAt)||!Number.isSafeInteger(v.expiresAt)||v.cachedAt<0||v.expiresAt<=v.cachedAt||v.payloadBytes!==L.length||L.length>Q)throw new Error("缓存信封损坏");return{envelopeVersion:1,address:v.address,revisions:v.revisions,cachedAt:v.cachedAt,expiresAt:v.expiresAt,payload:L}}async function R(x){if(!x.remove)throw new Error("Host 不支持缓存文件删除");await x.remove(c)}async function P(x){try{if((await x.file.stat(c)).size!==x.size)return!1;const Q=await Y(x.file,gn);return!Ct(Q.address,x.entry.address)||!Ct(Q.revisions,x.entry.revisions)||Q.cachedAt!==x.entry.cachedAt||Q.expiresAt!==x.entry.expiresAt||!Ct(await M(Q.payload),await M(x.entry.payload))?!1:(await R(x.file),!0)}catch(Q){if(wi(Q))return!0;throw Q}}async function M(x){const Q=await globalThis.crypto.subtle.digest("SHA-256",x);return Array.from(new Uint8Array(Q),j=>j.toString(16).padStart(2,"0")).join("")}async function V(){const x=await y(n);let Q=0;for(const v of x)if(v.kind==="file"&&(Q+=(await v.stat(c)).size,Q>gn))throw new Error("缓存扫描超过字节上限");const j=[];let H=0,F=Q;for(const v of await y(i)){if(v.kind!=="directory")throw new Error("缓存目录结构损坏");for(const L of await y(v)){if(L.kind!=="file"||++H>Mp)throw new Error("缓存文件超过治理上限");const q=(await L.stat(c)).size;if(F+=q,F>gn)throw new Error("缓存扫描超过字节上限");try{const D=await Y(L,gn);j.push({file:L,entry:D,size:(await L.stat(c)).size,bucketName:v.name})}catch(D){h(D),f(),wi(D)||await R(L)}}}return{entries:j,metadataBytes:Q}}async function z(){for(const x of await y(i))if(x.kind==="directory"&&x.remove&&(await y(x)).length===0)try{await x.remove({recursive:!1},c)}catch(Q){h(Q),f()}}function te(x){const{payload:Q,...j}=x,H=Fi.encode(JSON.stringify({...j,payloadBytes:Q.length}));if(H.length>Ra)throw new Error("缓存信封过大");const F=new Uint8Array(4+H.length+Q.length);return new DataView(F.buffer).setUint32(0,H.length),F.set(H,4),F.set(Q,H.length+4),F}return{readRevisions:(x,Q)=>p(()=>C(x,Q)),read:(x,Q)=>p(async()=>{f();const j=await U(x);let H;try{H=await Y(j,Q)}catch(F){if(f(),wi(F))return;throw F}if(!(!Ct(H.address,x)||H.expiresAt<=Date.now())&&Ct(H.revisions,await C(x.scopeIds,x.namespace)))return H}),publish:(x,Q)=>p(async()=>{f();const{address:j}=x;if(!Ct(x.revisions,await C(j.scopeIds,j.namespace)))return!1;const H=te(x);if(x.payload.length>Q.maxEntryBytes||H.length>Q.diskMaxBytes||Q.diskMaxEntries<1)throw new Error("缓存条目超出容量预算");await g();const F=await I(j),v=await U(j),L=await V(),q=[],D=new Map;for(const m of L.entries){if(m.bucketName===F.name&&m.file.name===v.name)continue;const w=JSON.stringify([m.entry.address.scopeIds,m.entry.address.namespace]);let B=D.get(w);if(B||(B=await C(m.entry.address.scopeIds,m.entry.address.namespace),D.set(w,B)),m.entry.expiresAt<=Date.now()||!Ct(m.entry.revisions,B)){if(!await P(m))throw new Error("缓存治理期间条目已变化")}else q.push(m)}q.sort((m,w)=>m.entry.cachedAt-w.entry.cachedAt);function W(){const m=q.filter(w=>w.bucketName===F.name);return q.length+1>Cp||H.length+L.metadataBytes+q.reduce((w,B)=>w+B.size,0)>gn||m.length+1>Math.min(Q.diskMaxEntries,xr-1)||H.length+m.reduce((w,B)=>w+B.size,0)>Q.diskMaxBytes}for(;W();){const m=q.filter(K=>K.bucketName===F.name),B=m.length+1>Math.min(Q.diskMaxEntries,xr-1)||H.length+m.reduce((K,ce)=>K+ce.size,0)>Q.diskMaxBytes?m[0]:q[0];if(!B||!await P(B))throw new Error("缓存容量不足或条目已变化");q.splice(q.indexOf(B),1)}await z();const $=await y(i);if(!$.some(m=>m.name===F.name)&&$.length>=xr-1)throw new Error("缓存目录超过治理上限");if(await F.create({recursive:!0,exclusive:!1},c),!Ct(x.revisions,await C(j.scopeIds,j.namespace)))return!1;try{await v.create({recursive:!1,exclusive:!0},c)}catch(m){h(m),await v.stat(c)}return await v.write(H,c),f(),Ct(x.revisions,await C(j.scopeIds,j.namespace))}),invalidate:(x,Q)=>p(async()=>{await g();const j=n.file(`${await Ni([x,Q??null])}.revision`);await N(j);try{await j.create({recursive:!1,exclusive:!0},c)}catch(H){h(H),await j.stat(c)}await j.write(Fi.encode(Au()),c),f();try{const{entries:H}=await V();for(const F of H){if(Q!==void 0&&F.entry.address.namespace!==Q||!x.every((L,q)=>F.entry.address.scopeIds[q]===L))continue;const v=await C(F.entry.address.scopeIds,F.entry.address.namespace);Ct(F.entry.revisions,v)||await P(F)}await z()}catch(H){h(H),f()}})}}function wi(e){return!!e&&typeof e=="object"&&["FILE_NOT_FOUND","ENOENT","NOT_FOUND"].includes(String(e.code))}const Pp="RATE_LIMITED_BY_RUNTIME",vp="RATE_LIMITED",df=20,lf=40,ff=150,hf=20,mf=1e4,Ef=45e3,gf=1,kp=300*1e3,xp=64;function Ur(e,t){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:t}function Up(e,t){return typeof e=="number"&&Number.isFinite(e)&&e>=0?Math.floor(e):t}function Bp(e={}){const t=e.now??Date.now,r=Up(e.coalesceWindowMs,ff),n=e.budget===!1?void 0:{ratePerSecond:Math.max(.001,Ur(e.budget?.ratePerSecond,df)),burst:Math.max(1,Math.floor(Ur(e.budget?.burst,lf)))},i=e.loopDetection===!1?void 0:{maxCalls:Math.max(1,Math.floor(Ur(e.loopDetection?.maxCalls,hf))),windowMs:Math.max(1,Math.floor(Ur(e.loopDetection?.windowMs,mf)))},s=e.circuitBreaker===!1?void 0:{failureThreshold:Math.max(1,Math.floor(Ur(e.circuitBreaker?.failureThreshold,gf))),openMs:Math.max(1,Math.floor(Ur(e.circuitBreaker?.openMs,Ef)))},a=new Map,c=new Map,u=new Set,d=new Map,l=n?{tokens:n.burst,updatedAt:t()}:{tokens:0,updatedAt:0},h={coalesced:0,budgetRejected:0,loopRejected:0,circuitOpened:0,circuitRejected:0};let f=!1;function p(P){try{e.onReport?.(P)}catch{}}function g(P,M){if(!i)return{exceeded:!1,count:0};const V=c.get(P)??[],z=M-i.windowMs;let te=0;for(;te<V.length&&V[te]<=z;)te+=1;te>0&&V.splice(0,te);const x=V.length>=i.maxCalls;return x||(V.push(M),V.length>i.maxCalls+1&&V.splice(0,V.length-(i.maxCalls+1))),c.set(P,V),{exceeded:x,count:V.length}}function b(P){if(!n)return!0;const M=Math.max(0,P-l.updatedAt)/1e3;return l.tokens=Math.min(n.burst,l.tokens+M*n.ratePerSecond),l.updatedAt=P,l.tokens<1?!1:(l.tokens-=1,!0)}function y(P){if(!n)return 0;const M=Math.max(0,P-l.updatedAt)/1e3,V=Math.min(n.burst,l.tokens+M*n.ratePerSecond);return Math.max(0,Math.ceil((1-V)/n.ratePerSecond*1e3))}function N(P,M,V,z,te){if(!s)return;const x=d.get(M),Q=(x?.open?0:x?.failures??0)+1;if(Q<s.failureThreshold){d.set(M,{open:!1,openedAt:0,openMs:0,failures:Q});return}const j=Math.min(Math.max(s.openMs,z),kp);d.set(M,{open:!0,openedAt:te,openMs:j,failures:Q}),h.circuitOpened+=1,p({type:"circuit_opened",capability:P,endpointId:M,status:V,openMs:j,timestamp:te})}function C(P){const M=d.get(P);M&&!M.open&&d.delete(P)}function I(P){for(const[M,V]of a)!V.pending&&V.expiresAt<=P&&a.delete(M);for(;a.size>=xp;){const M=[...a].find(([,V])=>!V.pending);if(!M)break;a.delete(M[0])}}function U(P,M){if(P===void 0)return;const V=a.get(P);V?.promise===M&&(V.pending=!1)}function Y(P,M){if(P===void 0)return;a.get(P)?.promise===M&&a.delete(P)}async function R(P){if(f)return P.load();const M=t();if(s){const x=d.get(P.endpointId);if(x?.open){const Q=x.openedAt+x.openMs-M;if(Q>0)throw h.circuitRejected+=1,p({type:"circuit_rejected",capability:P.capability,endpointId:P.endpointId,retryAfterMs:Q,timestamp:M}),zp("上游已被网关限流,Runtime 熔断中,请稍后重试",{origin:"circuit",reason:"circuit_open",endpointId:P.endpointId,retryAfterMs:Q});d.delete(P.endpointId)}}const V=g(P.endpointId,M);V.exceeded&&i?u.has(P.endpointId)||(u.add(P.endpointId),p({type:"loop_detected",capability:P.capability,endpointId:P.endpointId,count:V.count,windowMs:i.windowMs,timestamp:M})):u.delete(P.endpointId);const z=r>0?P.coalesceKey:void 0;if(z!==void 0){const x=a.get(z);if(x&&(x.pending||x.expiresAt>M))return h.coalesced+=1,p({type:"coalesced",capability:P.capability,endpointId:P.endpointId,timestamp:M}),x.promise;x&&a.delete(z)}if(V.exceeded&&i)throw h.loopRejected+=1,bu("检测到同一 endpoint 的高频循环调用,本次请求已在 Runtime 本地拒绝",{origin:"loop",reason:"loop",capability:P.capability,endpointId:P.endpointId,count:V.count,windowMs:i.windowMs});if(!b(M)){h.budgetRejected+=1;const x=y(M);throw p({type:"budget_exhausted",capability:P.capability,endpointId:P.endpointId,retryAfterMs:x,timestamp:M}),bu("请求过于频繁,已触发 Runtime 本地配额限制",{origin:"budget",reason:"budget",capability:P.capability,endpointId:P.endpointId,retryAfterMs:x})}z!==void 0&&I(M);const te=P.load().then(x=>(U(z,te),C(P.endpointId),x),x=>{Y(z,te);const Q=Hp(x);throw Q!==void 0&&N(P.capability,P.endpointId,Q,Fp(x),M),x});return z!==void 0&&a.set(z,{endpointId:P.endpointId,promise:te,expiresAt:M+r,pending:!0}),te}return{execute:R,invalidateCoalescing(P){if(P===void 0){a.clear();return}for(const[M,V]of a)P.includes(V.endpointId)&&a.delete(M)},snapshot(){return{...h,openCircuits:[...d.entries()].filter(([,P])=>P.open).map(([P])=>P)}},dispose(){f||(f=!0,a.clear(),c.clear(),u.clear(),d.clear())}}}function Hp(e){if(typeof e!="object"||e===null)return;const t=e.status;if(!(typeof t!="number"||!Number.isInteger(t)))return t===403||t===429?t:void 0}function Fp(e){if(typeof e!="object"||e===null)return 0;const t=e.retryAfterMs;return typeof t=="number"&&Number.isFinite(t)&&t>0?t:0}function bu(e,t){return{code:Pp,message:e,data:t}}function zp(e,t){return{code:vp,message:e,data:t}}const pf=3e4,Tf=6e4,lo=1440*60*1e3;function jp(e){const t=e!==!1&&(e?.enabled??!0),r=e===!1?void 0:e;return{enabled:t,debugReport:t&&r?.debugReport===!0,identityTtlMs:t?Math.max(0,Math.floor(r?.identityTtlMs??pf)):0,profileTtlMs:t?Math.max(0,Math.floor(r?.profileTtlMs??Tf)):0,steamGameListTtlMs:t?Vp(r?.steamGameListTtlMs):0,gateOptions:{budget:r?.budget??{ratePerSecond:df,burst:lf},coalesceWindowMs:r?.coalesceWindowMs??ff,loopDetection:r?.loopDetection??{maxCalls:hf,windowMs:mf},circuitBreaker:r?.circuitBreaker??{failureThreshold:gf,openMs:Ef}}}}function Vp(e){return e===void 0||!Number.isFinite(e)?lo:Math.max(0,Math.floor(e))}function _f(e){return typeof e=="object"&&e!==null}function Af(e,t){const r=e.data;if(!_f(r))throw new Error(t);if(r.status!=="ok")throw new Error(typeof r.msg=="string"&&r.msg?r.msg:t);return r.result}function xe(e,t){const r=e.data;if(!_f(r)||typeof r.status!="string")throw new Error(t);return r}const If={auth:"optional",channel:"api",id:"heybox.account.user_base_info.envelope.get",method:"GET",path:"/account/get_user_base_info"},Gp={auth:"optional",channel:"api",failurePresentation:"none",id:"heybox.user_miniprogram.public.detail.get",method:"GET",path:"/user_miniprogram/public/detail",query(e){return{mini_program_id:e.mini_program_id,...e.miniprogram_version?{miniprogram_version:e.miniprogram_version}:{},...e.preview_token?{preview_token:e.preview_token}:{},...e.local_dev_launch_token?{local_dev_launch_token:e.local_dev_launch_token}:{},...e.entry?{entry:e.entry}:{},...e.h_src_parent?{h_src_parent:e.h_src_parent}:{},...e.extra!==void 0?{extra:e.extra}:{}}},parse(e,t){return xe(e,"工坊小程序详情加载失败")}};function li(e){const t=e.runtimeAuthContextToken?.trim();return{mini_program_id:e.miniProgramId,...t?{runtime_auth_context_token:t}:{}}}function Yp(e){return{challenge:e.challenge,expiresIn:e.expires_in,requestedScopes:e.requested_scopes||[],displayedScopes:e.displayed_scopes||[],consentUiVersion:e.consent_ui_version}}function Qp(e){const t=xe(e,"小程序登录授权接口响应异常"),r=t.result,n={};if(r.login_code&&typeof r.login_code=="object"){const i=r.login_code;n.loginCode={code:i.code,expiresIn:i.expires_in,scopes:i.scopes||[]}}return r.consent_challenge&&typeof r.consent_challenge=="object"&&(n.consentChallenge=Yp(r.consent_challenge)),{...t,result:n}}const qp={auth:"none",bodyEncoding:"form",channel:"api",failurePresentation:"none",id:"heybox.user_miniprogram.runtime.auth.authorization.cancel.post",method:"POST",path:"/user_miniprogram/runtime/auth/authorization/cancel",body:e=>({...li(e.runtimeContext),challenge:e.challenge}),parse:e=>xe(e,"小程序授权取消接口响应异常")},Wp={auth:"none",bodyEncoding:"form",channel:"api",failurePresentation:"none",id:"heybox.user_miniprogram.runtime.auth.authorization.revoke.post",method:"POST",path:"/user_miniprogram/runtime/auth/authorization/revoke",body:e=>li(e.runtimeContext),parse:e=>xe(e,"小程序授权撤销接口响应异常")},$p={auth:"none",bodyEncoding:"form",channel:"api",failurePresentation:"none",id:"heybox.user_miniprogram.runtime.local_identity.post",method:"POST",path:"/user_miniprogram/runtime/local_identity",body:e=>li(e.runtimeContext),parse(e){const t=xe(e,"小程序隔离身份接口响应异常"),r=typeof t.result.steam_id=="string"&&t.result.steam_id.trim()?t.result.steam_id.trim():void 0;return{...t,result:{appUserId:t.result.app_user_id,...r?{steamId:r}:{}}}}},Kp={auth:"none",bodyEncoding:"form",channel:"api",failurePresentation:"none",id:"heybox.user_miniprogram.runtime.auth.login.begin.post",method:"POST",path:"/user_miniprogram/runtime/auth/login/begin",body:e=>({...li(e.runtimeContext),...e.scopes?.length?{scopes:e.scopes.join(",")}:{}}),parse:e=>Qp(e)},Zp={auth:"none",bodyEncoding:"form",channel:"api",failurePresentation:"none",id:"heybox.user_miniprogram.runtime.auth.login.confirm.post",method:"POST",path:"/user_miniprogram/runtime/auth/login/confirm",body:e=>({...li(e.runtimeContext),challenge:e.challenge,...e.selectedScopes.length?{selected_scopes:e.selectedScopes.join(",")}:{}}),parse(e){const t=xe(e,"小程序登录确认接口响应异常");return{...t,result:{code:t.result.code,expiresIn:t.result.expires_in,scopes:t.result.scopes}}}},Xp=64;function bf(e){const t=e.ttlMs,r=Math.max(1,Math.floor(e.maxEntries??Xp)),n=e.now??Date.now,i=new Map,s=new Map;let a=0,c=!1;function u(h){for(const[f,p]of i)p.expiresAt<=h&&i.delete(f)}function d(h,f,p){if(c||t<=0||p!==a)return;const g=n();for(u(g),i.delete(h);i.size>=r;){const b=i.keys().next();if(b.done)break;i.delete(b.value)}i.set(h,{expiresAt:g+t,value:f})}function l(h,f){if(c)return f();if(t>0){const y=i.get(h);if(y&&y.expiresAt>n())return Promise.resolve(y.value);y&&i.delete(h)}const p=s.get(h);if(p)return p;const g=a,b=f().then(y=>(d(h,y,g),y)).finally(()=>{s.get(h)===b&&s.delete(h)});return s.set(h,b),b}return{read:l,invalidate(){a+=1,i.clear(),s.clear()},dispose(){c||(c=!0,a+=1,i.clear(),s.clear())},get size(){return i.size}}}function Jp(e,t){return t?e?"server":"local":"legacy"}function eT(e,t){if(e==="local")throw T("SERVER_API_REQUIRED",`${t} 需要 effective network 启用后才能使用`)}const tT=["baseURL","errorMode","jsonParseMode","observability","queryEncoding","responseType","security"],rT=new Set(["auth","body","bodyEncoding","channel","failurePresentation","headers","id","method","parse","path","query","timeout"]),nT=/authorization|cookie|pkey|password|secret|token/i,yf=/authorization|cookie|pkey|token|password|secret/i;function Rt(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function iT(e){for(const t of Object.keys(e))if(!rT.has(t))throw new Qe(`endpoint 字段不受 hb-sdk-runtime private mapper 支持: ${t}`);for(const t of tT)if(Object.prototype.hasOwnProperty.call(e,t)&&Rt(e,t)!==void 0)throw new Qe(`endpoint 字段不受 hb-sdk-runtime private mapper 支持: ${t}`);if(Rt(e,"bodyEncoding")!==void 0&&Rt(e,"bodyEncoding")!=="json"&&Rt(e,"bodyEncoding")!=="form")throw new Qe("endpoint bodyEncoding 不受 HostNetworkPort 支持");if(Rt(e,"failurePresentation")!==void 0&&Rt(e,"failurePresentation")!=="none")throw new Qe("endpoint failurePresentation 必须为 none");if(Rt(e,"auth")!==void 0&&Rt(e,"auth")!=="none"&&Rt(e,"auth")!=="optional"&&Rt(e,"auth")!=="required")throw new Qe("endpoint auth 必须为 none、optional 或 required")}function ks(e){if(Array.isArray(e))return e.map(ks);if(!e||typeof e!="object")return e;const t=e,r={};for(const[n,i]of Object.entries(t))nT.test(n)||(r[n]=ks(i));return r}function yu(e){if(!e)return;const t={};for(const[r,n]of Object.entries(e))yf.test(r)||(t[r]=n);return t}function sT(e){if(!e)return;const t=Object.keys(e).find(r=>yf.test(r));if(t)throw new Qe(`endpoint 禁止声明 credential-bearing header: ${t}`)}class fi extends Error{code="INTERNAL_ENDPOINT_HTTP_STATUS";endpointId;status;retryAfterMs;constructor(t){super(`内部 endpoint 请求失败: HTTP ${t.status}`),this.name="InternalEndpointHttpStatusError",this.endpointId=t.endpointId,this.status=t.status,Object.defineProperty(this,"responseData",{value:t.responseData,enumerable:!1}),t.retryAfterMs!==void 0&&(this.retryAfterMs=t.retryAfterMs),Object.setPrototypeOf(this,new.target.prototype)}}const Nu=1440*60*1e3,aT=/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun)\b/i;function oT(e,t=Date.now){if(!e)return;const r=Object.entries(e).find(([a])=>a.trim().toLowerCase()==="retry-after")?.[1];if(typeof r!="string"||!r.trim())return;const n=r.trim();if(/^\d+$/.test(n)){const a=Number(n)*1e3;return a>0?Math.min(a,Nu):void 0}if(!aT.test(n))return;const i=Date.parse(n);if(!Number.isFinite(i))return;const s=i-t();return s>0?Math.min(s,Nu):void 0}function cT(e,t,r,n){if(e.method!=="GET")return;let i;try{i=JSON.stringify([t??null,r??null])??"undefined"}catch{return}return`${e.id}\0${n}\0${i}`}function Nf(e,t){Object.defineProperty(e,"cause",{configurable:!1,enumerable:!1,value:t,writable:!1})}class en extends Error{code="INTERNAL_ENDPOINT_REQUEST_FAILED";endpointId;constructor(t){super(`内部 endpoint 请求执行失败: ${t.endpointId}`),this.name="InternalEndpointRequestError",this.endpointId=t.endpointId,Nf(this,t.cause),Object.setPrototypeOf(this,new.target.prototype)}}class hi extends Error{code="INTERNAL_ENDPOINT_PARSE_FAILED";endpointId;constructor(t){super(`内部 endpoint 响应解析失败: ${t.endpointId}`),this.name="InternalEndpointParseError",this.endpointId=t.endpointId,Nf(this,t.cause),Object.setPrototypeOf(this,new.target.prototype)}}function uT(e,t,r,n,i,s,a,c){return{config:{auth:e.auth,body:ks(i),bodyEncoding:e.bodyEncoding,channel:e.channel,credentials:a.credentials,headers:yu(s),method:e.method,metadata:{endpointId:e.id},query:ks(n),timeout:e.timeout,url:r},data:c.data,headers:yu(c.headers)||{},status:c.status,statusText:c.statusText}}async function fa(e,t,r,n){if(!n||!n.signal)throw new TypeError("requestEndpoint requires an AbortSignal");if(n.credentials!=="heybox-session"&&n.credentials!=="omit")throw new TypeError("requestEndpoint requires explicit credentials");if(iT(t),typeof t.id!="string"||!t.id)throw new Qe("endpoint id 必须为非空字符串");if(!["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"].includes(t.method))throw new Qe("endpoint method 不受 HostNetworkPort 支持");const i=typeof t.path=="function"?await t.path(r):t.path;if(typeof i!="string"||!i)throw new Qe("endpoint path 必须为非空字符串");const s=t.query?await t.query(r):void 0,a=t.body?await t.body(r):void 0,c=t.headers?await t.headers(r):void 0;sT(c);const u=async()=>{let h;try{h=await e.request({source:"runtime-private",redirectPolicy:"error",target:{kind:"heybox-api",endpointId:t.id,...t.channel?{channel:t.channel}:{},path:i},method:t.method,...s===void 0?{}:{params:s},...a===void 0?{}:{data:a},...c===void 0?{}:{headers:c},credentials:n.credentials,...t.bodyEncoding===void 0?{}:{bodyEncoding:t.bodyEncoding},...t.timeout===void 0?{}:{timeout:t.timeout}},{signal:n.signal,...n.miniProgramDetail===void 0?{}:{miniProgramDetail:n.miniProgramDetail}})}catch(p){throw p instanceof Qe?p:new en({endpointId:t.id,cause:p})}if(h.status<200||h.status>=300)throw new fi({endpointId:t.id,status:h.status,responseData:h.data,retryAfterMs:oT(h.headers)});const f=uT(t,r,i,s,a,c,n,h);if(t.parse)try{return await t.parse(f,r)}catch(p){throw new hi({endpointId:t.id,cause:p})}return f.data},d=n.gate;if(!d)return u();const l=cT(t,s,a,n.credentials);return d.gate.execute({capability:d.capability,endpointId:t.id,...l===void 0?{}:{coalesceKey:l},load:u})}const dT=new Set(["MINIPROGRAM_UNAVAILABLE","RUNTIME_CONTEXT_INVALID","CAPABILITY_NOT_GRANTED","AUTHORIZATION_CONTEXT_CHANGED","SERVER_API_REQUIRED","AUTHORIZATION_CANCELLED"]),lT=new Set(Xr),Ac="steam_account",wf=new Set(Xr.filter(e=>e!==Ac)),fT=1e3;function hT(e){const t=new Set,r=bf({ttlMs:Math.max(0,Math.floor(e.identityTtlMs??pf))}),n=new Set;let i=0,s=!1,a=Promise.resolve(),c;const u=e.steamAccount===!0,d=e.userDataMode??Jp(e.networkEnabled===!0,u),l=e.requestPolicyEnabled!==!1,h=e.requestGate?{capability:"auth",gate:e.requestGate}:void 0;async function f(){if(!u&&!e.authorizationContext)return{};if(!e.authorizationContext)throw T("METHOD_FORBIDDEN","新能力版本缺少 Runtime auth context Port");let L;try{L=await e.authorizationContext.get(e.operationContext)}catch(D){throw ho(D)?La(D.code,D.message,D):La("REQUEST_FAILED","读取 Runtime auth context 失败",D)}if(L.steamAccount!==u||L.userDataMode!==d)throw T("AUTHORIZATION_CONTEXT_CHANGED","Runtime auth context 已变化,请重新打开小程序");const q=L.token.trim();if(!q)throw T("REQUEST_FAILED","Runtime auth context 为空");return{runtimeAuthContextToken:q}}const p=e.account.onChange(L=>{if(g(),b("heybox_app_login_change",L?{isHeyboxAppLoggedIn:!0}:{isHeyboxAppLoggedIn:!1,accountKey:null}),L&&e.account.getAccountKey){const q=i;Y().then(D=>{!s&&i===q&&b("heybox_app_login_change",D)}).catch(()=>{})}});function g(){i+=1,c?.abort(),r.invalidate(),e.requestGate?.invalidateCoalescing(),n.clear()}function b(L,q){L==="user_info_authorization_change"&&_T(q)&&r.invalidate();for(const D of t)try{D(L,q)}catch{}}function y(){const L=e.identity.get()?.miniProgramId?.trim();if(!L)throw T("INVALID_STATE","当前能力缺少 canonical 小程序身份");return L}function N(){if(s||e.operationContext.signal.aborted)throw T("RUNTIME_DESTROYED","小程序 Runtime 已终止")}async function C(){N();let L;try{L=await e.account.getCurrentUserId(e.operationContext)}catch(q){throw Ou(q,e.operationContext.signal,"读取小黑盒账号失败")}return typeof L=="string"&&L.trim()?L.trim():void 0}async function I(L,q){const D=await C();if(i!==q||D!==L)throw T("AUTHORIZATION_CONTEXT_CHANGED","授权期间账号上下文已变化,请重新操作")}async function U(L,q,D=y()){if(!e.account.getAccountKey)throw T("METHOD_FORBIDDEN","Host 不支持持久化账号比较");let W;try{W=await e.account.getAccountKey(D,L,e.operationContext)}catch{throw N(),T("REQUEST_FAILED","读取本地账号标识失败")}if(await I(L,q),y()!==D)throw T("AUTHORIZATION_CONTEXT_CHANGED","读取期间小程序上下文已变化");if(typeof W!="string"||!W.trim())throw T("INVALID_RESPONSE","Host 返回了无效的账号标识");return W}async function Y(){const L=y(),q=i,D=await C();if(N(),i!==q)throw T("AUTHORIZATION_CONTEXT_CHANGED","读取期间账号上下文已变化");return D?{isHeyboxAppLoggedIn:!0,accountKey:await U(D,q,L)}:{isHeyboxAppLoggedIn:!1,accountKey:null}}async function R(L){N();try{await e.account.ensureAuthenticated({trustedUserGesture:L,reason:"runtime_auth",signal:e.operationContext.signal})}catch(D){throw Ou(D,e.operationContext.signal,"小黑盒登录失败")}const q=await C();if(!q)throw T("HEYBOX_APP_LOGIN_REQUIRED","请先登录小黑盒");return q}async function P(L,q,D=e.operationContext.signal){try{if(D.aborted)throw fo();return await TT(fa(e.network,L,q,{...e.operationContext,credentials:"heybox-session",signal:D,...h?{gate:h}:{}}),D)}catch(W){throw e.operationContext.signal.aborted?T("RUNTIME_DESTROYED","小程序 Runtime 已终止"):W instanceof Qe?T("REQUEST_UNSUPPORTED",W.message):W instanceof hi?T("INVALID_RESPONSE","授权接口响应不合法"):W instanceof en?T("REQUEST_FAILED","授权请求失败"):W instanceof fi?l&&(W.status===403||W.status===429)?T("RATE_LIMITED","授权请求已被网关限流,请稍后重试",{status:W.status,...W.retryAfterMs===void 0?{}:{retryAfterMs:W.retryAfterMs}}):T("REQUEST_FAILED",W.message):ho(W)?W:T("REQUEST_FAILED","授权请求失败")}}async function M(L,q){await P(qp,{runtimeContext:{miniProgramId:L,...await f()},challenge:q}).catch(()=>{})}function V(L){const q=async()=>{const W=Du(e.operationContext.signal);c=W;try{return await L(W.signal)}finally{c===W&&(c=void 0),W.abort()}},D=a.then(q,q);return a=D.then(()=>{},()=>{}),D}async function z(L,q,D,W,$){if(!D)throw await M(L,q.challenge),T("USER_GESTURE_REQUIRED","展示授权确认需要用户手势");if(!e.authPresentation)throw await M(L,q.challenge),T("AUTHORIZATION_PRESENTATION_UNAVAILABLE","授权确认界面不可用");return V(async m=>{await I(W,$);const w=await te(L,q.displayedScopes,m);await I(W,$);let B;try{B=await e.authPresentation.confirmAuthorization({miniProgramId:L,scopes:q.displayedScopes,...w,signal:m})}catch(ce){throw e.operationContext.signal.aborted?T("RUNTIME_DESTROYED","小程序 Runtime 已终止"):(await I(W,$),await M(L,q.challenge),La("REQUEST_FAILED","授权确认界面执行失败",ce))}if(await I(W,$),B.status!=="granted")throw await M(L,q.challenge),T("AUTHORIZATION_CANCELLED","用户取消授权");const K=gT(B.grantedScopes,q.displayedScopes,u);if(!K.includes("identity"))throw await M(L,q.challenge),T("AUTHORIZATION_CANCELLED","用户拒绝授权");return K})}async function te(L,q,D){const W=Du(D),$=setTimeout(()=>W.abort(),fT);try{const m=pT(e.miniProgramPresentation),[w,B]=await Promise.all([m?Promise.resolve(m):x(L,W.signal),q.includes("profile")?Q(W.signal):Promise.resolve(void 0)]);return{...w?{miniProgram:w}:{},...B?{userProfile:B}:{}}}finally{clearTimeout($),W.abort()}}async function x(L,q){try{const D=e.identity.get()?.version?.trim(),W=await P(Gp,{mini_program_id:L,...D?{miniprogram_version:D}:{}},q),$=Br(W,"小程序公开资料"),m=Gr($.name),w=Gr($.icon_url);return m||w?{...m?{name:m}:{},...w?{avatarUrl:w}:{}}:void 0}catch{return}}async function Q(L){try{const q=await P(If,void 0,L),D=Br(q,"账号基础信息"),W=Gr(D.display_username),$=Gr(D.display_avatar);return W||$?{...W?{nickname:W}:{},...$?{avatar:$}:{}}:void 0}catch{return}}async function j(L,q){if(eT(d,"auth.login"),!u&&L.includes(Ac))throw T("INVALID_PARAMS","auth.login 参数不合法");const D=y(),W=await R(q),$=i,m=await P(Kp,{runtimeContext:{miniProgramId:D,...await f()},scopes:L});await I(W,$);const w=Br(m,"小程序登录"),B=Su(w,"loginCode"),K=Su(w,"consentChallenge");if(B===K)throw T("INVALID_RESPONSE","小程序登录 begin 必须返回 exact oneof");let ce;if(B)ce=wu(w.loginCode,u);else{const ue=mT(w.consentChallenge,u),Te=await z(D,ue,q,W,$);await I(W,$);const we=await P(Zp,{runtimeContext:{miniProgramId:D,...await f()},challenge:ue.challenge,selectedScopes:Te});if(await I(W,$),ce=wu(Br(we,"小程序登录确认"),u),ce.scopes.some(Ae=>!Te.includes(Ae)))throw T("INVALID_RESPONSE","小程序登录确认返回了未选择的 scope")}n.clear();for(const ue of ce.scopes)n.add(ue);r.invalidate();const pe=e.account.getAccountKey?await U(W,$,D):void 0;return b("heybox_app_login_change",{isHeyboxAppLoggedIn:!0,...pe===void 0?{}:{accountKey:pe}}),b("user_info_authorization_change",Pa(n,u)),{...ce,...pe===void 0?{}:{accountKey:pe}}}async function H(L,q){const D=i,W=await P($p,{runtimeContext:{miniProgramId:q,...await f()}});await I(L,D);const $=ET(Br(W,"用户本地身份"),u);for(const m of u?Xr:wf)n.add(m);return b("user_info_authorization_change",Pa(n,u)),$}function F(L){N();const q=y(),D=`${L}\0${q}\0${i}\0${u}`;return r.read(D,()=>H(L,q))}async function v(L){if(!L)throw T("USER_GESTURE_REQUIRED","撤销授权需要用户手势");const q=y(),D=i,W=await C();if(!W)throw T("HEYBOX_APP_LOGIN_REQUIRED","请先登录小黑盒");const $=await P(Wp,{runtimeContext:{miniProgramId:q,...await f()}});await I(W,D),Br($,"用户授权撤销"),g(),b("user_info_authorization_change",{identity:"denied",profile:"denied",...u?{steam_account:"denied"}:{}})}return{getAccountState:Y,login:j,async confirmGameSaves(L){if(!L)throw T("USER_GESTURE_REQUIRED","读取游戏存档需要点击按钮授权");if(!e.authPresentation)throw T("AUTHORIZATION_PRESENTATION_UNAVAILABLE","授权确认界面不可用");const q=y(),D=await R(L),W=i;await V(async $=>{await I(D,W);const m=await te(q,["identity"],$),w=await e.authPresentation.confirmAuthorization({miniProgramId:q,scopes:["identity","game_saves"],...m,signal:$});if(await I(D,W),w.status!=="granted"||!w.grantedScopes.includes("game_saves")||!w.grantedScopes.includes("identity"))throw T("AUTHORIZATION_CANCELLED","用户取消存档授权")})},getOrCreateLocalIdentity:F,invalidateLocalIdentity(){r.invalidate()},getAuthorization:()=>Pa(n,u),revoke:v,onEvent(L){return t.add(L),()=>t.delete(L)},dispose(){s||(s=!0,g(),r.dispose(),p(),t.clear())}}}function La(e,t,r){const n=T(e,t);return Object.defineProperty(n,"cause",{configurable:!0,enumerable:!1,value:r}),n}function Br(e,t){if(!le(e))throw T("INVALID_RESPONSE",`${t}响应必须是对象`);if(e.status!=="ok"){const r=typeof e.msg=="string"&&e.msg.trim()?e.msg.trim():`${t}请求失败`,n=["login","relogin","lack_token"].includes(String(e.status))?"HEYBOX_APP_LOGIN_REQUIRED":dT.has(r)?r:"REQUEST_FAILED";throw T(n,r)}if(!le(e.result))throw T("INVALID_RESPONSE",`${t} result 必须是对象`);return e.result}function wu(e,t){if(!le(e))throw T("INVALID_RESPONSE","login code 必须是对象");const r=xs(e.scopes,"login code scopes",t);if(typeof e.code!="string"||!e.code.trim()||!Number.isInteger(e.expiresIn)||Number(e.expiresIn)<=0||!r.includes("identity"))throw T("INVALID_RESPONSE","login code 响应不合法");return{code:e.code,expiresIn:Number(e.expiresIn),scopes:r}}function mT(e,t){if(!le(e))throw T("INVALID_RESPONSE","授权 challenge 必须是对象");const r=xs(e.requestedScopes,"challenge requestedScopes",t),n=xs(e.displayedScopes,"challenge displayedScopes",t);if(typeof e.challenge!="string"||!e.challenge.trim()||!Number.isInteger(e.expiresIn)||Number(e.expiresIn)<=0||!Number.isInteger(e.consentUiVersion)||Number(e.consentUiVersion)<0||!r.length||!r.includes("identity")||!n.length||!n.includes("identity")||r.some(i=>!n.includes(i)))throw T("INVALID_RESPONSE","授权 challenge 响应不合法");return{challenge:e.challenge.trim(),requestedScopes:r,displayedScopes:n}}function ET(e,t){if(!le(e)||typeof e.appUserId!="string"||!e.appUserId.trim())throw T("INVALID_RESPONSE","本地身份 appUserId 必须是非空字符串");const r=e.appUserId.trim();if(!t)return{appUserId:r};if(e.steamId!==void 0&&typeof e.steamId!="string")throw T("INVALID_RESPONSE","本地身份 steamId 必须是字符串");const n=typeof e.steamId=="string"&&e.steamId.trim()?e.steamId.trim():void 0;return n?{appUserId:r,steamId:n}:{appUserId:r}}function gT(e,t,r){const n=xs(e,"授权选择 scopes",r);if(n.some(i=>!t.includes(i)))throw T("INVALID_RESPONSE","授权选择包含未展示的 scope");return n}function Gr(e){return typeof e=="string"&&e.trim()?e.trim():void 0}function pT(e){const t=Gr(e?.name),r=Gr(e?.avatarUrl);return t||r?{...t?{name:t}:{},...r?{avatarUrl:r}:{}}:void 0}function Du(e){const t=new AbortController;return e.aborted?t.abort(e.reason):e.addEventListener("abort",()=>t.abort(e.reason),{once:!0,signal:t.signal}),t}function TT(e,t){return t.aborted?Promise.reject(fo()):new Promise((r,n)=>{let i=!1;const s=c=>{i||(i=!0,t.removeEventListener("abort",a),c())},a=()=>s(()=>n(fo()));t.addEventListener("abort",a,{once:!0}),e.then(c=>s(()=>r(c)),c=>s(()=>n(c)))})}function fo(){const e=new Error("The operation was aborted");return e.name="AbortError",e}function xs(e,t,r){const n=r?lT:wf;if(!Array.isArray(e)||e.some(i=>typeof i!="string"||!n.has(i))||new Set(e).size!==e.length)throw T("INVALID_RESPONSE",`${t} 不合法`);return[...e]}function Pa(e,t){const r=t?Xr:Xr.filter(n=>n!==Ac);return Object.fromEntries(r.map(n=>[n,e.has(n)?"granted":"not_requested"]))}function Su(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function _T(e){return le(e)?Object.values(e).some(t=>t==="denied"):!1}function ho(e){return le(e)&&typeof e.code=="string"&&typeof e.message=="string"}function Ou(e,t,r){return t.aborted?T("RUNTIME_DESTROYED","小程序 Runtime 已终止"):ho(e)?e:T("REQUEST_FAILED",r)}const AT=new Set(Xr);function IT(e){return{[Ji]:async t=>{if(t!==void 0)throw T("INVALID_PARAMS","auth.getAccountState 不接受参数");return e.authorization.getAccountState()},[es]:async(t,r)=>e.authorization.login(bT(t),r.trustedUserGesture)}}function bT(e){if(e===void 0)return["identity"];if(!le(e)||Object.keys(e).some(t=>t!=="scopes"))throw Mu();if(e.scopes===void 0)return["identity"];if(!Array.isArray(e.scopes)||e.scopes.some(t=>typeof t!="string"||!AT.has(t))||new Set(e.scopes).size!==e.scopes.length)throw Mu();return[...e.scopes]}function Mu(){return T("INVALID_PARAMS","auth.login 参数不合法")}const yT={auth:"optional",channel:"api",failurePresentation:"none",id:"heybox.user_miniprogram.cloud.leaderboard.current.delete.post",method:"POST",path:"/user_miniprogram/cloud/leaderboard/current/delete",body(e){return{mini_program_id:e.miniProgramId,...e.key?{key:e.key}:{}}},parse(e,t){return xe(e,"排行榜记录删除接口响应异常")}},NT={auth:"optional",channel:"api",failurePresentation:"none",id:"heybox.user_miniprogram.cloud.leaderboard.current.get",method:"GET",path:"/user_miniprogram/cloud/leaderboard/current",query(e){return{mini_program_id:e.miniProgramId,...e.key?{key:e.key}:{}}},parse(e,t){return xe(e,"当前排行榜记录接口响应异常")}},wT={auth:"optional",channel:"api",failurePresentation:"none",id:"heybox.user_miniprogram.cloud.leaderboard.info.get",method:"GET",path:"/user_miniprogram/cloud/leaderboard/info",query(e){return{mini_program_id:e.miniProgramId,...e.key?{key:e.key}:{}}},parse(e,t){return xe(e,"排行榜信息接口响应异常")}},DT={auth:"optional",channel:"api",failurePresentation:"none",id:"heybox.user_miniprogram.cloud.leaderboard.list.get",method:"GET",path:"/user_miniprogram/cloud/leaderboard/list",query(e){return{mini_program_id:e.miniProgramId,...e.key?{key:e.key}:{},limit:e.limit,...e.cursor?{cursor:e.cursor}:{}}},parse(e,t){return xe(e,"排行榜列表接口响应异常")}},ST={auth:"optional",channel:"api",failurePresentation:"none",id:"heybox.user_miniprogram.cloud.leaderboard.submit.post",method:"POST",path:"/user_miniprogram/cloud/leaderboard/submit",body(e){return{mini_program_id:e.miniProgramId,...e.key?{key:e.key}:{},score:e.score,...e.extra===void 0?{}:{extra:JSON.stringify(e.extra)}}},parse(e,t){return xe(e,"排行榜提交接口响应异常")}},OT={1:"Canceled",2:"Unknown",3:"InvalidArgument",4:"DeadlineExceeded",5:"NotFound",6:"AlreadyExists",7:"PermissionDenied",8:"ResourceExhausted",9:"FailedPrecondition",10:"Aborted",11:"OutOfRange",12:"Unimplemented",13:"Internal",14:"Unavailable",15:"DataLoss",16:"Unauthenticated"};async function mi(e,t,r){e.assertUsable();const n={request:async(i,s)=>(e.assertUsable(),e.network.request(i,s))};try{return await be(()=>fa(n,t,r,{...e.operationContext,credentials:"heybox-session",...e.gate?{gate:e.gate}:{}}),e.operationContext.signal)}catch(i){if(Hs(i)||Sn(i,"REQUEST_UNSUPPORTED")||Sn(i,"RATE_LIMITED")||Sn(i,"RATE_LIMITED_BY_RUNTIME"))throw i;if(i instanceof Qe)throw ne("REQUEST_UNSUPPORTED",`当前 Host 不支持该${e.subject}请求`);if(i instanceof en&&Sn(i.cause,"INVALID_STATE"))throw i.cause;if(i instanceof fi){if(e.requestPolicyEnabled!==!1&&(i.status===403||i.status===429))throw ne("RATE_LIMITED",`${e.subject}请求已被网关限流,请稍后重试`,{status:i.status,...i.retryAfterMs===void 0?{}:{retryAfterMs:i.retryAfterMs}});if(i.status===401||i.status===403)throw ne("UNAUTHORIZED","当前用户未登录");const s=MT(i.responseData);if(Se(s)&&typeof s.status=="string"&&s.status!=="ok"){const a=Se(s.result)?Vt(s.result.error_code):void 0;if(s.status==="login"||s.status==="relogin"||Us(s.result)||Us(s)||a&&/^[A-Z][A-Z0-9_]+$/.test(a))throw Df(s,e.subject)}throw ne("HTTP_ERROR",`${e.subject}请求失败(HTTP ${i.status})`,{status:i.status})}throw i instanceof en?Bs(e.subject):i instanceof hi?Ne(i.cause instanceof Error?i.cause.message:`${e.subject}响应不合法`):Ne(i instanceof Error?i.message:`${e.subject}响应不合法`)}}function Je(e,t,r){if(!Se(e)||typeof e.status!="string")throw Ne(`${t} 响应必须是标准信封`);if(e.status!=="ok")throw Df(e,r);if(!Object.prototype.hasOwnProperty.call(e,"result")||e.result===void 0||e.result===null)throw Ne(`${t} 响应缺少 result`);return e.result}function Ei(e,t){try{return e.onChange(t)}catch(r){if(Sn(r,Vl))return()=>{};throw r}}function Df(e,t){if(e.status==="login"||e.status==="relogin")throw ne("UNAUTHORIZED",Vt(e.msg)||"当前用户未登录");if(Se(e.result)){const i=Vt(e.result.error_code);if(i&&/^[A-Z][A-Z0-9_]+$/.test(i))throw ne(i,Vt(e.result.message)||Vt(e.msg)||`${t}请求失败`)}const r=Us(e.result)??Us(e),n=Vt(r?.user_message)||Vt(e.msg)||Vt(r?.developer_message)||`${t}请求失败`;throw r?ne(CT(r),n,{status:e.status,sbe:r}):ne("HEYBOX_API_ERROR",n,{status:e.status})}function MT(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return}}function Us(e){return Se(e)&&Se(e.sbe)?e.sbe:void 0}function CT(e){const t=Vt(e.developer_message);if(t==="CLOUD_STORAGE_KEY_LIMIT_EXCEEDED")return"STORAGE_QUOTA_EXCEEDED";if(t&&/^[A-Z][A-Z0-9_]+$/.test(t))return t;const r=e.code;if(typeof r=="number"&&Number.isInteger(r))return OT[r]||t||"HEYBOX_API_ERROR";if(typeof r=="string"){const n=/^([A-Za-z][A-Za-z0-9_]*)(?:\(\d+\))?$/.exec(r.trim());if(n?.[1])return n[1]}return t||"HEYBOX_API_ERROR"}function Se(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Vt(e){return typeof e=="string"&&e.trim()?e.trim():void 0}function Sn(e,t){return Se(e)&&e.code===t}function ne(e,t,r){return r===void 0?{code:e,message:t}:{code:e,message:t,data:r}}function Ne(e){return ne("INVALID_RESPONSE",e)}function Bs(e){return ne("REQUEST_FAILED",`${e}请求失败`)}function Hs(e){return e instanceof Error&&e.name==="AbortError"}const RT="default",ur="排行榜",LT=/^[A-Za-z0-9_-]{1,64}$/,PT=300*1e3,vT=250,kT=3;class xT{constructor(t){this.options=t,this.requestGateContext=t.requestGate?{capability:"cloud",gate:t.requestGate}:void 0,this.unsubscribeAccountChange=Ei(t.account,()=>this.invalidateForAccountChange()),t.operationContext.signal.aborted?this.dispose():t.operationContext.signal.addEventListener("abort",this.handleTerminalAbort,{once:!0})}accountGeneration=0;buckets=new Map;inflight=new Map;unsubscribeAccountChange;requestGateContext;disposed=!1;handleTerminalAbort=()=>this.dispose();async submit(t){this.assertUsable();const r=this.accountGeneration,n=this.readMiniProgramId();await this.requireCurrentUser(r);const i=await this.request(ST,{miniProgramId:n,...t});this.assertAccountGeneration(r);const s=Je(i,Yt,ur);return this.invalidateMutableReads(this.createBucketKey(n,t.key)),va(s,Yt)}getList(t){this.assertUsable();const r=this.readMiniProgramId(),n=this.createBucketKey(r,t.key),i=Tn("list",t.limit,t.cursor??null);return this.read(n,"list",i,async()=>{const s=await this.request(DT,{miniProgramId:r,...t}),a=Je(s,Nt,ur);if(!Se(a)||!Array.isArray(a.entries)||typeof a.has_more!="boolean")throw Ne(`${Nt} 返回值不合法`);if(a.cursor!==void 0&&a.cursor!==null&&typeof a.cursor!="string")throw Ne(`${Nt} 返回的 cursor 必须是字符串`);return{entries:a.entries.map(c=>va(c,Nt)),...typeof a.cursor=="string"&&a.cursor?{cursor:a.cursor}:{},hasMore:a.has_more}})}async getCurrentUserEntry(t){this.assertUsable();const r=this.accountGeneration,n=this.readMiniProgramId(),i=await this.requireCurrentUser(r),s=this.createBucketKey(n,t.key),a=Tn("current",i);return this.read(s,"current",a,async()=>{const c=await this.request(NT,{miniProgramId:n,...t}),u=Je(c,nr,ur);if(!Se(u))throw Ne(`${nr} 返回值必须是对象`);return u.entry===void 0||u.entry===null?void 0:va(u.entry,nr)})}async deleteCurrentUserEntry(t){this.assertUsable();const r=this.accountGeneration,n=this.readMiniProgramId();await this.requireCurrentUser(r);const i=await this.request(yT,{miniProgramId:n,...t});this.assertAccountGeneration(r);const s=Je(i,Dr,ur);if(this.invalidateMutableReads(this.createBucketKey(n,t.key)),!Se(s)||typeof s.deleted!="boolean")throw Ne(`${Dr} 返回的 deleted 必须是布尔值`);return{deleted:s.deleted}}getInfo(t){this.assertUsable();const r=this.readMiniProgramId(),n=this.createBucketKey(r,t.key);return this.read(n,"info",Tn("info"),async()=>{const i=await this.request(wT,{miniProgramId:r,...t}),s=Je(i,xt,ur);if(!Se(s)||typeof s.key!="string"||!LT.test(s.key))throw Ne(`${xt} 返回的 key 不合法`);if(t.key!==void 0&&s.key!==t.key)throw Ne(`${xt} 返回的 key 与请求不一致`);if(s.order!=="asc"&&s.order!=="desc")throw Ne(`${xt} 返回的 order 必须是 asc 或 desc`);if(typeof s.rank_limit!="number"||!Number.isInteger(s.rank_limit)||s.rank_limit<0)throw Ne(`${xt} 返回的 rankLimit 必须是非负整数`);return{key:s.key,order:s.order,rankLimit:s.rank_limit}})}read(t,r,n,i){this.assertUsable();const s=this.getOrCreateBucket(t),a=s?.caches[r],c=a?.get(n);if(c&&c.expiresAt>Date.now())return Promise.resolve(c.value);a?.delete(n);const u=Tn(t,n),d=this.inflight.get(u);if(d)return d.promise;const l=this.accountGeneration,h=s?.generation,f=i().then(p=>(this.assertAccountGeneration(l),s&&a&&s.generation===h&&(r==="list"?a.size>=vT&&a.delete(a.keys().next().value):a.clear(),a.set(n,{expiresAt:Date.now()+PT,value:p})),p)).finally(()=>{this.inflight.get(u)?.promise===f&&this.inflight.delete(u),s&&this.removeEmptyBucket(t,s)});return this.inflight.set(u,{bucketKey:t,promise:f}),f}getOrCreateBucket(t){const r=this.buckets.get(t);if(r)return r;if(this.pruneExpiredBuckets(),this.buckets.size>=kT)return;const n={generation:0,caches:{list:new Map,current:new Map,info:new Map}};return this.buckets.set(t,n),n}invalidateMutableReads(t){this.invalidateInflight(t);const r=this.buckets.get(t);r&&(r.generation+=1,r.caches.list.clear(),r.caches.current.clear())}invalidateForAccountChange(){this.accountGeneration+=1,this.buckets.clear(),this.inflight.clear()}invalidateInflight(t){for(const[r,n]of this.inflight)n.bucketKey===t&&this.inflight.delete(r)}pruneExpiredBuckets(){const t=Date.now();for(const[r,n]of this.buckets)Cu(n,t),this.isBucketEmpty(r,n)&&this.buckets.delete(r)}removeEmptyBucket(t,r){Cu(r,Date.now()),this.buckets.get(t)===r&&this.isBucketEmpty(t,r)&&this.buckets.delete(t)}isBucketEmpty(t,r){return![...this.inflight.values()].some(n=>n.bucketKey===t)&&Object.values(r.caches).every(n=>n.size===0)}async requireCurrentUser(t){this.assertUsable();let r;try{r=await be(()=>this.options.account.getCurrentUserId(this.options.operationContext),this.options.operationContext.signal)}catch(n){throw Hs(n)?n:Bs(ur)}if(this.assertAccountGeneration(t),typeof r!="string"||!r.trim())throw ne("UNAUTHORIZED","当前用户未登录");return r.trim()}readMiniProgramId(){const t=this.options.identity.get()?.miniProgramId.trim();if(!t)throw ne("INVALID_STATE","canonical mini-program identity 尚未绑定");return t}createBucketKey(t,r){return Tn(t,r??RT)}assertAccountGeneration(t){if(this.assertUsable(),t!==this.accountGeneration)throw ne("UNAUTHORIZED","登录状态已变化,请重试")}request(t,r){return mi({network:this.options.network,operationContext:this.options.operationContext,...this.requestGateContext?{gate:this.requestGateContext}:{},...this.options.requestPolicyEnabled===void 0?{}:{requestPolicyEnabled:this.options.requestPolicyEnabled},subject:ur,assertUsable:()=>this.assertUsable()},t,r)}dispose(){this.disposed||(this.disposed=!0,this.accountGeneration+=1,this.options.operationContext.signal.removeEventListener("abort",this.handleTerminalAbort),this.unsubscribeAccountChange(),this.buckets.clear(),this.inflight.clear())}assertUsable(){if(Oe(this.options.operationContext.signal),this.disposed)throw ne("INVALID_STATE","Cloud capability 已释放")}}function UT(e){return new xT(e)}function va(e,t){if(!Se(e))throw Ne(`${t} 返回的 entry 必须是对象`);if(typeof e.ranked!="boolean")throw Ne(`${t} 返回的 ranked 必须是布尔值`);if(typeof e.rank!="number"||!Number.isInteger(e.rank)||(e.ranked?e.rank<=0:e.rank!==0))throw Ne(`${t} 返回的 rank/ranked 不合法`);if(typeof e.app_user_id!="string"||!e.app_user_id.trim())throw Ne(`${t} 返回的 appUserId 必须是非空字符串`);if(typeof e.score!="number"||!Number.isFinite(e.score))throw Ne(`${t} 返回的 score 必须是有限数字`);if(!Se(e.extra))throw Ne(`${t} 返回的 extra 必须是对象`);if(typeof e.created_at!="number"||!Number.isFinite(e.created_at)||typeof e.updated_at!="number"||!Number.isFinite(e.updated_at))throw Ne(`${t} 返回的时间字段必须是有限数字`);return{appUserId:e.app_user_id,createdAt:e.created_at,extra:e.extra,rank:e.rank,ranked:e.ranked,score:e.score,updatedAt:e.updated_at}}function Cu(e,t){for(const r of Object.values(e.caches))for(const[n,i]of r)i.expiresAt<=t&&r.delete(n)}function Tn(...e){return JSON.stringify(e)}const BT={auth:"optional",channel:"api",failurePresentation:"none",id:"heybox.user_miniprogram.cloud.storage.delete.post",method:"POST",path:"/user_miniprogram/cloud/storage/delete",body(e){return{runtime_auth_context_token:e.runtimeAuthContextToken,key:e.key}},parse(e,t){return xe(e,"云端存储删除接口响应异常")}},Ru={auth:"optional",channel:"api",failurePresentation:"none",id:"heybox.user_miniprogram.cloud.storage.get.post",method:"POST",path:"/user_miniprogram/cloud/storage/get",body(e){return{key:e.key,runtime_auth_context_token:e.runtimeAuthContextToken}},parse(e,t){return xe(e,"云端存储读取接口响应异常")}},Lu={auth:"optional",channel:"api",failurePresentation:"none",id:"heybox.user_miniprogram.cloud.storage.keys.post",method:"POST",path:"/user_miniprogram/cloud/storage/keys",body(e){return{runtime_auth_context_token:e.runtimeAuthContextToken}},parse(e,t){return xe(e,"云端存储 key 列表接口响应异常")}},HT={auth:"optional",channel:"api",failurePresentation:"none",id:"heybox.user_miniprogram.cloud.storage.set.post",method:"POST",path:"/user_miniprogram/cloud/storage/set",body(e){return{runtime_auth_context_token:e.runtimeAuthContextToken,key:e.key,value:e.value,expected_version:String(e.expectedVersion),expected_revision:e.expectedRevision}},parse(e,t){return xe(e,"云端存储写入接口响应异常")}},dr="云端存储",FT=3e4,zT=128,jT=500;class VT{constructor(t){this.options=t,this.requestGateContext=t.requestGate?{capability:"cloud.storage",gate:t.requestGate}:void 0,this.unsubscribeAccountChange=Ei(t.account,r=>{this.observedUserId=r?.trim()||void 0,this.hasAccountObservation=!0,!(this.boundUserId===void 0||this.boundUserId===this.observedUserId)&&this.invalidateForAccountChange()}),t.operationContext.signal.aborted?this.dispose():t.operationContext.signal.addEventListener("abort",this.handleTerminalAbort,{once:!0})}accountGeneration=0;cache=new Map;inflight=new Map;keyGenerations=new Map;queues=new Map;activeKeys=new Set;timers=new Map;blockedKeys=new Map;unfinished=new Set;disposed=!1;boundScope;boundUserId;observedUserId;hasAccountObservation=!1;unsubscribeAccountChange;requestGateContext;handleTerminalAbort=()=>this.dispose();async getItem(t){const r=this.accountGeneration;await this.requireCurrentUser(r),this.assertAccountGeneration(r);const n=[...this.unfinished].filter(a=>a.key===t).at(-1);if(n)return n.kind==="set"?n.value:void 0;const i=this.keyGenerations.get(t)??0,s=await this.readStored(t,r,!1);return this.assertAccountGeneration(r),(this.keyGenerations.get(t)??0)!==i?this.getItem(t):(this.blockedKeys.delete(t),s.found?s.value:void 0)}setItem(t,r){return this.enqueue("set",t,r)}removeItem(t){return this.enqueue("remove",t,"")}async getKeys(){const t=this.accountGeneration;await this.requireCurrentUser(t),this.assertAccountGeneration(t);const r=Je(await this.request(Lu,{}),Sr,dr);if(this.assertAccountGeneration(t),!Se(r)||r.keys!==void 0&&(!Array.isArray(r.keys)||!r.keys.every(i=>typeof i=="string")))throw Ne("cloud.storage.getKeys 返回的 keys 必须是字符串数组");const n=new Set(r.keys??[]);for(const i of this.unfinished)i.kind==="set"?n.add(i.key):n.delete(i.key);return[...n]}async enqueue(t,r,n){this.assertUsable(),this.readMiniProgramId();const i=this.accountGeneration;return await this.requireCurrentUser(i),this.assertAccountGeneration(i),t==="set"&&this.blockedKeys.has(r)?Promise.reject(this.blockedKeys.get(r)):new Promise((s,a)=>{const c=this.queues.get(r)??[],u=c.at(-1);if(t==="set"&&u?.kind==="set"&&u.generation===this.accountGeneration&&u.readyAt>Date.now())u.value=n,u.waiters.push({resolve:s,reject:a});else{const d={kind:t,key:r,value:n,generation:this.accountGeneration,readyAt:Date.now()+(t==="set"?jT:0),waiters:[{resolve:s,reject:a}]};c.push(d),this.unfinished.add(d)}this.queues.set(r,c),this.invalidateRead(r),this.drainKey(r)})}async drainKey(t){if(!this.activeKeys.has(t)){this.activeKeys.add(t);try{let r;for(;r=this.queues.get(t)?.[0];){const n=r.readyAt-Date.now();if(n>0){this.timers.has(t)||this.timers.set(t,setTimeout(()=>{this.timers.delete(t),this.drainKey(t)},n));break}this.queues.get(t).shift();try{if(await this.requireCurrentUser(r.generation),this.assertAccountGeneration(r.generation),r.kind==="remove"){const i=Je(await this.request(BT,{key:t}),Zr,dr);if(this.assertAccountGeneration(r.generation),!Se(i)||i.deleted!==void 0&&typeof i.deleted!="boolean")throw Ne("删除结果不合法");this.writeCache(t,{value:"",found:!1,version:0,revision:""}),this.blockedKeys.delete(t)}else{const i=await this.readStored(t,r.generation,!0);if(this.assertAccountGeneration(r.generation),!Number.isSafeInteger(i.version+1))throw Ne("云存储版本超出安全整数范围");const s=Je(await this.request(HT,{key:t,value:r.value,expectedVersion:i.version,expectedRevision:i.revision}),Kr,dr);if(this.assertAccountGeneration(r.generation),!Se(s)||s.success!==!0)throw Ne("云存储写入结果不合法");const a=Pu({...s,found:!0,value:r.value});if(a.version!==i.version+1||i.found&&a.revision!==i.revision)throw Ne("写入版本凭证不匹配");this.writeCache(t,a)}this.finish(r)}catch(i){if(this.finish(r,i),r.generation===this.accountGeneration){this.cache.delete(t),this.blockedKeys.set(t,i);for(const s of this.queues.get(t)??[])this.finish(s,i);this.queues.delete(t)}}}}finally{this.activeKeys.delete(t),this.queues.get(t)?.length||this.queues.delete(t)}}}async readStored(t,r,n){this.assertAccountGeneration(r);const i=this.cache.get(t);if(i&&(n||i.expiresAt>Date.now()))return i.value;const s=this.inflight.get(t);if(s)return s;const a=this.keyGenerations.get(t)??0,c=this.request(Ru,{key:t}).then(u=>{this.assertAccountGeneration(r);const d=Pu(Je(u,$r,dr));return(this.keyGenerations.get(t)??0)===a&&this.writeCache(t,d),d}).finally(()=>{this.inflight.get(t)===c&&this.inflight.delete(t)});return this.inflight.set(t,c),c}writeCache(t,r){this.cache.delete(t),this.cache.size>=zT&&this.cache.delete(this.cache.keys().next().value),this.cache.set(t,{expiresAt:Date.now()+FT,value:r})}invalidateRead(t){this.keyGenerations.set(t,(this.keyGenerations.get(t)??0)+1),this.inflight.delete(t),this.options.requestGate?.invalidateCoalescing([Ru.id,Lu.id])}finish(t,r){if(this.unfinished.delete(t)){t.generation===this.accountGeneration&&this.invalidateRead(t.key);for(const n of t.waiters)r===void 0?n.resolve():n.reject(r)}}dispose(){this.disposed||(this.disposed=!0,this.options.operationContext.signal.removeEventListener("abort",this.handleTerminalAbort),this.unsubscribeAccountChange(),this.purge(ne("INVALID_STATE","Cloud capability 已释放")))}invalidateForAccountChange(){this.purge(ne("UNAUTHORIZED","登录状态已变化,请重试")),this.options.requestGate?.invalidateCoalescing()}purge(t){this.accountGeneration+=1;for(const r of this.timers.values())clearTimeout(r);this.timers.clear();for(const r of[...this.unfinished])this.finish(r,t);this.queues.clear(),this.blockedKeys.clear(),this.cache.clear(),this.inflight.clear(),this.keyGenerations.clear(),this.boundScope=void 0,this.boundUserId=void 0}async requireCurrentUser(t){this.assertAccountGeneration(t);const r=this.readMiniProgramId();let n;try{n=await be(()=>this.options.account.getCurrentUserId(this.options.operationContext),this.options.operationContext.signal)}catch(s){throw Hs(s)?s:Bs(dr)}if(this.assertAccountGeneration(t),this.hasAccountObservation&&(n?.trim()||void 0)!==this.observedUserId)throw this.invalidateForAccountChange(),ne("UNAUTHORIZED","登录状态已变化,请重试");const i=JSON.stringify([r,n]);if(this.boundScope!==void 0&&this.boundScope!==i)throw this.invalidateForAccountChange(),ne("UNAUTHORIZED","登录状态已变化,请重试");if(typeof n!="string"||!n.trim())throw ne("UNAUTHORIZED","当前用户未登录");return this.boundScope=i,this.boundUserId=n.trim(),n}readMiniProgramId(){const t=this.options.identity.get()?.miniProgramId.trim();if(!t)throw ne("INVALID_STATE","canonical mini-program identity 尚未绑定");return t}assertAccountGeneration(t){if(this.assertUsable(),t!==this.accountGeneration)throw ne("UNAUTHORIZED","登录状态已变化,请重试")}async request(t,r){const n=this.accountGeneration;if(this.assertUsable(),!this.options.authorizationContext)throw ne("METHOD_FORBIDDEN","云端存储缺少受信运行上下文");let i;try{i=await be(()=>this.options.authorizationContext.get(this.options.operationContext),this.options.operationContext.signal)}catch(a){throw Hs(a)?a:Bs(dr)}this.assertAccountGeneration(n);const s=i.token.trim();if(!s||i.expiresAt<=Date.now())throw ne("UNAUTHORIZED","小程序运行上下文无效,请重新打开");return mi({network:this.options.network,operationContext:this.options.operationContext,...this.requestGateContext?{gate:this.requestGateContext}:{},...this.options.requestPolicyEnabled===void 0?{}:{requestPolicyEnabled:this.options.requestPolicyEnabled},subject:dr,assertUsable:()=>this.assertAccountGeneration(n)},t,{...r,runtimeAuthContextToken:s})}assertUsable(){if(Oe(this.options.operationContext.signal),this.disposed)throw ne("INVALID_STATE","Cloud capability 已释放")}}function GT(e){return new VT(e)}function Pu(e){if(!Se(e))throw Ne("云存储读取结果必须是对象");const t=e.found??!1,r=e.value??"",n=e.version??0,i=e.revision??"";if(typeof t!="boolean"||typeof r!="string"||typeof n!="number"||!Number.isSafeInteger(n)||n<0||typeof i!="string")throw Ne("云存储读取结果不合法");if(t&&(n===0||!/^[0-9a-f]{24}$/.test(i)||/^0+$/.test(i)))throw Ne("云存储版本凭证不合法");return t?{value:r,found:t,version:n,revision:i}:{value:"",found:!1,version:0,revision:""}}const YT=/^[A-Za-z0-9_-]{1,64}$/,vu=20,QT=100,ku=2048,qT=/^[A-Za-z0-9_-]{1,128}$/,xu=16*1024;function WT(e){const t=UT(e),r=GT(e);return{handlers:{[Yt]:async i=>t.submit($T(i)),[Nt]:async i=>t.getList(KT(i)),[nr]:async i=>t.getCurrentUserEntry(ka(i,nr)),[Dr]:async i=>t.deleteCurrentUserEntry(ka(i,Dr)),[xt]:async i=>t.getInfo(ka(i,xt)),[$r]:async i=>r.getItem(Uu(i,$r)),[Kr]:async i=>{const{key:s,value:a}=ZT(i);return r.setItem(s,a)},[Zr]:async i=>r.removeItem(Uu(i,Zr)),[Sr]:async i=>(JT(i),r.getKeys())},dispose:()=>{t.dispose(),r.dispose()}}}function $T(e){const t=fn(e,Yt,!1);if(hn(t,["key","score","extra"],Yt),typeof t.score!="number"||!Number.isFinite(t.score)||Math.abs(t.score)>Number.MAX_SAFE_INTEGER)throw ut("INVALID_PARAMS","cloud.leaderboard.submit score 必须是有限安全数字");return{...Ic(t.key,Yt),score:t.score,...t.extra===void 0?{}:{extra:e_(t.extra)}}}function KT(e){if(e===void 0)return{limit:vu};const t=fn(e,Nt,!0);hn(t,["key","limit","cursor"],Nt);const r=t.limit===void 0?vu:t.limit;if(typeof r!="number"||!Number.isInteger(r)||r<=0||r>QT)throw ut("INVALID_PARAMS","cloud.leaderboard.getList limit 必须是 1-100 的整数");if(t.cursor!==void 0&&typeof t.cursor!="string")throw ut("INVALID_PARAMS","cloud.leaderboard.getList cursor 必须是字符串");return{...Ic(t.key,Nt),limit:r,...t.cursor===void 0?{}:{cursor:t.cursor}}}function ka(e,t){if(e===void 0)return{};const r=fn(e,t,!0);return hn(r,["key"],t),Ic(r.key,t)}function Uu(e,t){const r=fn(e,t,!1);return hn(r,["key"],t),Sf(r.key,t)}function ZT(e){const t=Kr,r=fn(e,t,!1);hn(r,["key","value"],t);const n=Sf(r.key,t);if(typeof r.value!="string")throw ut("INVALID_PARAMS",`${t} value 必须是字符串`);if(XT(r.value))throw ut("INVALID_PARAMS",`${t} value 不能包含不成对的代理字符`);if(new TextEncoder().encode(r.value).length>xu)throw ut("INVALID_PARAMS",`${t} value 不能超过 ${xu} 字节`);return{key:n,value:r.value}}function XT(e){for(let t=0;t<e.length;t++){const r=e.charCodeAt(t);if(r>=55296&&r<=56319){const n=e.charCodeAt(t+1);if(!(n>=56320&&n<=57343))return!0;t++}else if(r>=56320&&r<=57343)return!0}return!1}function JT(e){const t=fn(e,Sr,!0);hn(t,[],Sr)}function Sf(e,t){if(typeof e!="string"||!qT.test(e))throw ut("INVALID_PARAMS",`${t} key 仅支持 1–128 位英文字母、数字、下划线和连字符`);return e}function fn(e,t,r){if(e===void 0&&r)return{};if(!Of(e))throw ut("INVALID_PARAMS",`${t} 参数必须是对象`);return e}function hn(e,t,r){const n=Object.keys(e).find(i=>!t.includes(i));if(n)throw ut("INVALID_PARAMS",`${r} 不支持参数 ${n}`)}function Ic(e,t){if(e===void 0)return{};if(typeof e!="string"||!YT.test(e))throw ut("INVALID_PARAMS",`${t} key 仅支持 1-64 位字母、数字、下划线和连字符`);return{key:e}}function e_(e){if(!Of(e))throw ut("INVALID_PARAMS","cloud.leaderboard.submit extra 必须是对象");let t;try{t=JSON.stringify(e)}catch{throw ut("INVALID_PARAMS","cloud.leaderboard.submit extra 必须可序列化")}if(typeof t!="string")throw ut("INVALID_PARAMS","cloud.leaderboard.submit extra 必须可序列化");if(new TextEncoder().encode(t).length>ku)throw ut("INVALID_PARAMS",`cloud.leaderboard.submit extra 不能超过 ${ku} 字节`);return e}function Of(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ut(e,t){return{code:e,message:t}}const t_={auth:"optional",channel:"api",id:"heybox.user_miniprogram.runtime.game_saves.post",method:"POST",path:"/user_miniprogram/runtime/game_saves",bodyEncoding:"form",failurePresentation:"none",body(e){return{...e}},parse(e,t){return xe(e,"游戏存档接口响应异常")}},r_=new Map([["2358720","blackMythWukong"],["3678970","taskbarHero"],["4115450","phantomBladeZero"],["1245620","eldenRing"],["413150","stardewValley"],["2246340","monsterHunterWilds"],["3167020","duckov"],["3489700","stellarBlade"],["2001120","splitFiction"]]);function mo(e,t=0){return t>64?!1:e===null||typeof e=="string"||typeof e=="boolean"?!0:typeof e=="number"?Number.isFinite(e)&&(!Number.isInteger(e)||Number.isSafeInteger(e)):Array.isArray(e)?e.every(r=>mo(r,t+1)):Se(e)&&Object.values(e).every(r=>mo(r,t+1))}function n_(e,t){const r=r_.get(t);if(!r||Se(e)&&e.status==="unsupported")return{status:"unsupported"};if(Se(e)&&e.game===r){if(e.status==="empty")return{status:"empty"};if(e.status==="failed"&&["UNAUTHORIZED","STEAM_ACCOUNT_CHANGED","GAME_SAVES_AUTHORIZATION_REQUIRED"].includes(String(e.error_code)))throw ne(String(e.error_code),"账号或授权已变化");if(e.status==="ready"&&Se(e.data)&&mo(e.data))return{status:"ready",data:e.data}}return{status:"failed",error:{code:"STRUCTURED_DATA_UNAVAILABLE",message:"结构化数据暂时无法读取,请稍后重试"}}}function Mf(e){const t=new Map,r=new Map,n=u=>u.resource?`hb_runtime_game_save_resource_sync_v1_${[u.miniProgramId,u.userId,u.resource].map(encodeURIComponent).join(":")}`:`hb_runtime_game_save_sync_v1_${[u.miniProgramId,u.userId,u.gameId].map(encodeURIComponent).join(":")}`;async function i(u,d,l){const h=n(u),f=r.get(h)??Promise.resolve();let p;const g=new Promise(y=>{p=y}),b=f.then(()=>g);r.set(h,b);try{return await be(()=>f,d.signal),Oe(d.signal),e?.withLock?await e.withLock(h,l):await l()}finally{p(),r.get(h)===b&&b.then(()=>{r.get(h)===b&&r.delete(h)})}}async function s(u,d,l=!1){const h=n(u);if(!l&&t.has(h)||!e)return t.get(h);try{const f=await be(()=>e.getRaw(h,d),d.signal);if(!f)return;const p=JSON.parse(f);if(!p||typeof p!="object")return;const g=p;return g.version!==1||g.miniProgramId!==u.miniProgramId||g.userId!==u.userId||g.gameId!==u.gameId||(u.resource?g.resource!==u.resource:typeof g.accountId!="string"||!/^[1-9][0-9]{0,19}$/.test(g.accountId))||typeof g.taskId!="string"||(u.resource?g.taskId.length<1||g.taskId.length>128:!/^[1-9][0-9]{0,19}$/.test(g.taskId))?void 0:(l||t.set(h,g),g)}catch(f){if(Oe(d.signal),l)throw f;return t.get(h)}}async function a(u,d,l){Oe(l.signal);const h=n(u),f=d?{...u,version:1,taskId:d}:void 0;if(t.set(h,f),!!e)try{await be(()=>e.setRaw(h,f?JSON.stringify(f):"",l),l.signal)}catch{Oe(l.signal)}}async function c(u,d,l){await i(u,l,async()=>{const h=n(u),f=t.get(h),p=f?.taskId===d&&f.accountId===u.accountId;let g;try{g=await s(u,l,!0)}catch{Oe(l.signal),p&&t.set(h,void 0);return}g?.taskId===d&&g.accountId===u.accountId?(await a(u,void 0,l),f&&!p&&t.set(h,f)):p&&t.set(h,g)})}return{run:i,async get(u,d){const l=await s(u,d);if(l&&l.accountId!==u.accountId){t.delete(n(u));return}return l?.taskId},set:a,remove:c,clear(u){for(const d of t.values())d&&c(d,d.taskId,u).catch(()=>{})}}}const i_=2e3,s_=5*6e4;function a_(e){const t=Mf(e.storage);let r=0,n=!1,i;const s=e.fileDownloads??(e.files&&e.transfer?Tc({files:e.files,transfer:e.transfer,registry:e.fileRegistry,signal:e.operationContext.signal}):void 0),a=new Set,c=new Map,u={...e.operationContext,lifecycle:"cleanup",signal:new AbortController().signal},d=M=>s?.release(M)??Promise.resolve(),l=new Set;let h=new AbortController,f;const p=()=>{h.abort(),h=new AbortController,f=void 0},g=(M=!0)=>{M&&t.clear(u),r++,p();for(const V of l)V.abort();for(const V of a)d(V).catch(()=>{});a.clear(),c.clear()},b=Ei(e.account,M=>{i&&M!==i&&(g(),i=void 0)}),y=e.authorization.onEvent(()=>g());function N(M,V,z,te){if(C(z),te.signal.aborted||!M.account_id||!e.presentation?.showSteamLoginRequired)return;const x=`${M.account_id}:${M.game_id}:${M.task_id??"sync"}`;if(f!==x){f=x;try{e.presentation.showSteamLoginRequired({userId:V,accountId:M.account_id},Re(e.operationContext,h.signal))}catch{}}}function C(M){if(n||e.operationContext.signal.aborted)throw ne("RUNTIME_DESTROYED","小程序已关闭");if(M!==r)throw ne("AUTHORIZATION_CONTEXT_CHANGED","账号或授权已变化")}async function I(M,V,z){if(C(V),await e.account.getCurrentUserId(z)!==M)throw g(),ne("AUTHORIZATION_CONTEXT_CHANGED","账号已变化");C(V)}async function U(M,V,z,te){if(await I(V,z,te),!e.authorizationContext)throw ne("METHOD_FORBIDDEN","宿主不支持存档授权上下文");const x=await e.authorizationContext.get(te);if(!x.token||x.expiresAt<=Date.now())throw ne("UNAUTHORIZED","小程序运行上下文已过期");const Q=await mi({network:e.network,operationContext:te,subject:"游戏存档",assertUsable:()=>C(z),...e.requestGate?{gate:{capability:"gameSaves",gate:e.requestGate}}:{},requestPolicyEnabled:e.requestPolicyEnabled},t_,{...M,runtime_auth_context_token:x.token});if(await I(V,z,te),Q.status==="failed"&&Se(Q.result)&&Q.result.error_code==="RECENT_SAVE_AVAILABLE")throw ne("RECENT_SAVE_AVAILABLE",typeof Q.msg=="string"&&Q.msg?Q.msg:"已有近期存档,请直接查询使用");const j=Je(Q,M.action,"游戏存档");if(!Se(j))throw ne("INVALID_RESPONSE","存档响应不合法");return j}async function Y(M,V,z){const te=o_(M,V),x=r;if(C(x),M==="file"&&(!e.transfer||!e.files))throw ne("METHOD_FORBIDDEN","宿主不支持存档文件读取");const Q=new AbortController;l.add(Q);let j=!1;const H=M==="sync"?setTimeout(()=>{j=!0,Q.abort()},s_):void 0,F=Re(Re(e.operationContext,z.signal),Q.signal);try{const v=await e.account.getCurrentUserId(F);if(!v)throw ne("UNAUTHORIZED","请先登录小黑盒");if(i&&i!==v)throw g(),ne("AUTHORIZATION_CONTEXT_CHANGED","账号已变化");if(i=v,M==="sync"||M==="parsed"){if(M==="sync"&&p(),!te.account_id){const $=await U({action:"check",game_id:te.game_id},v,x,F);te.account_id=ni($.account_id)}if(M==="sync")return await R(te,v,x,F)}const L=await U({action:M,...te},v,x,F);if(M==="list")return c_(L);if(M==="parsed")return n_(L.parsed_data,te.game_id);if(Cf(L.file).fileId!==te.file_id)throw ne("INVALID_RESPONSE","文件标识不匹配");if(!s)throw ne("REQUEST_UNSUPPORTED","宿主不支持存档下载");const D=await s.download(L,async $=>{try{C(x),await U({action:"check",game_id:te.game_id,account_id:te.account_id},v,x,$)}catch(m){const w=Se(m)?String(m.code):"";throw["RUNTIME_DESTROYED","AUTHORIZATION_CONTEXT_CHANGED","STEAM_ACCOUNT_CHANGED","GAME_SAVES_AUTHORIZATION_REQUIRED","UNAUTHORIZED"].includes(w)?(g(),ne("FILE_ACCESS_REVOKED","游戏存档授权已失效")):m}},F);let W=!1;try{if(await I(v,x,F),C(x),F.signal.aborted)throw ne("DOWNLOAD_CANCELLED","存档下载已取消");const $=e.fileRegistry.registerFile(D,"game-save","read");return a.add(D),c.set(hc(),{file:D,sizeBytes:s.sizeOf(D)}),W=!0,$}finally{W||await s.release(D)}}catch(v){throw j?ne("REQUEST_TIMEOUT","等待同步超时,任务可能仍在执行,请稍后查询存档列表"):v}finally{H!==void 0&&clearTimeout(H),l.delete(Q)}}async function R(M,V,z,te){const x=e.identity.get()?.miniProgramId;if(!x)throw ne("INVALID_STATE","小程序身份尚未确认");const Q={miniProgramId:x,userId:V,gameId:M.game_id,accountId:M.account_id},j=F=>U({action:"status",...M,task_id:F},V,z,te);let H;try{const F=await t.run(Q,te,async()=>{await I(V,z,te);const L=await t.get(Q,te);if(L){H=L;try{return{taskId:L,status:await j(L)}}catch(D){if(!Se(D)||!["SYNC_TASK_NOT_FOUND","SYNC_TASK_CHANGED"].includes(String(D.code)))throw D;await t.set(Q,void 0,te),H=void 0}}const q=await U({action:"sync",...M},V,z,te);return H=ni(q.task_id),await t.set(Q,H,te),await I(V,z,te),{taskId:H,status:void 0}});H=F.taskId;let v=F.status;for(;;){if(C(z),te.signal.aborted)throw ne("REQUEST_CANCELLED","已停止等待存档同步");if(v??=await j(H),v.state==="succeeded"||v.state==="failed"){if(await t.remove(Q,H,te),await I(V,z,te),v.state==="succeeded")return{state:"succeeded"};throw ne(v.error_code?Fs(v.error_code):"SYNC_FAILED",v.message?Fs(v.message):"存档同步失败")}if(v.state!=="syncing"&&v.state!=="uploading")throw ne("INVALID_RESPONSE","同步状态不合法");v=void 0,await u_(i_,te.signal)}}catch(F){if(Se(F)){const v=String(F.code);v==="STEAM_LOGIN_REQUIRED"&&N({...M,task_id:H},V,z,te),H&&["SYNC_TASK_NOT_FOUND","SYNC_TASK_CHANGED","STEAM_ACCOUNT_CHANGED","STEAM_ACCOUNT_REQUIRED","GAME_SAVES_AUTHORIZATION_REQUIRED","AUTHORIZATION_CONTEXT_CHANGED","UNAUTHORIZED"].includes(v)&&await t.remove(Q,H,u)}throw F}}return{handlers:{"gameSaves.list":(M,V)=>Y("list",M,V),"gameSaves.sync":(M,V)=>Y("sync",M,V),"gameSaves.readParsedData":(M,V)=>Y("parsed",M,V),"gameSaves.getFile":(M,V)=>Y("file",M,V)},diagnostics:{async getSnapshot(){const M=r;return i&&await I(i,M,e.operationContext),C(M),Array.from(c,([V,z])=>({id:V,name:z.file.name,sizeBytes:z.sizeBytes}))},async readFile(M,V){const z=r;C(z);const te=c.get(M);if(!te)throw ne("FILE_ACCESS_REVOKED","存档文件已失效,请重新下载");const x=Re(e.operationContext,V);x.signal.throwIfAborted();const Q=await te.file.read(x);try{return x.signal.throwIfAborted(),C(z),{name:te.file.name,bytes:Q}}catch(j){throw Q.fill(0),j}}},allowsRead(M,V){return["file.readBytes","file.readText","file.stat","file.exists"].includes(M)&&Se(V)&&e.fileRegistry.isGameSaveRef(V.target)},dispose(){n||(n=!0,g(!1),b(),y())}}}function o_(e,t){const r=e==="file"?["gameId","accountId","saveId","fileId"]:["gameId","accountId"];if(!Se(t)||Object.keys(t).some(i=>!r.includes(i)))throw ne("INVALID_PARAMS","存档参数不合法");const n=On(t.gameId);if(Number(n)>2147483647)throw ne("INVALID_PARAMS","Steam AppID 超出范围");return{game_id:n,...e==="file"||t.accountId!==void 0?{account_id:On(t.accountId)}:{},...e==="file"?{save_id:On(t.saveId),file_id:On(t.fileId)}:{}}}function On(e){if(typeof e!="string"||!/^[1-9][0-9]{0,19}$/.test(e))throw ne("INVALID_PARAMS","存档标识必须为十进制字符串");return e}function ni(e){try{return On(e)}catch{throw ne("INVALID_RESPONSE","服务端存档标识无效")}}function Fs(e){if(typeof e!="string")throw ne("INVALID_RESPONSE","服务端存档字段无效");return e}function Eo(e){if(typeof e!="number"||!Number.isSafeInteger(e)||e<0)throw ne("INVALID_RESPONSE","服务端存档数值无效");return e}function Cf(e){if(!Se(e))throw ne("INVALID_RESPONSE","存档文件信息无效");return{fileId:ni(e.file_id),name:Fs(e.name),originalPath:Fs(e.original_path),sizeBytes:Eo(e.size_bytes),modifiedAt:Eo(e.modified_at)}}function c_(e){if(!Array.isArray(e.saves)||e.saves.length>500)throw ne("INVALID_RESPONSE","存档列表无效");return{accountId:ni(e.account_id),saves:e.saves.map(t=>{if(!Se(t)||!Array.isArray(t.files)||t.files.length>200)throw ne("INVALID_RESPONSE","存档文件列表无效");return{saveId:ni(t.save_id),createdAt:Eo(t.created_at),files:t.files.map(Cf)}})}}function u_(e,t){return new Promise((r,n)=>{const i=()=>{clearTimeout(s),t.removeEventListener("abort",i),n(ne("REQUEST_CANCELLED","已停止等待存档同步"))},s=setTimeout(()=>{t.removeEventListener("abort",i),r()},Math.max(0,e));t.addEventListener("abort",i,{once:!0}),t.aborted&&i()})}function Rf(e,t){return{auth:"optional",channel:"api",id:e,method:"GET",path:t,query(r){return{...r}},parse(r){return Af(r,"赛事中心接口响应异常")}}}function Lf(e,t){return{auth:"optional",bodyEncoding:"form",body(r){return{...r.body}},channel:"api",id:e,method:"POST",path:t,query(r){return r.query?{...r.query}:void 0},parse(r){return Af(r,"赛事中心接口响应异常")}}}const d_=Rf("heybox.bbs.app.link.tree.get","/bbs/app/link/tree"),l_=Rf("heybox.bbs.app.comment.sub.comments.get","/bbs/app/comment/sub/comments"),f_=Lf("heybox.bbs.app.comment.support.post","/bbs/app/comment/support"),h_=Lf("heybox.bbs.app.comment.delete.post","/bbs/app/comment/delete");function ha(e){return xe(e,"社区评论响应异常")}const Bu={...d_,parse:ha},m_={...l_,parse:ha},E_={...f_,bodyEncoding:"form",body:e=>Object.fromEntries(Object.entries(e.body).map(([t,r])=>[t,String(r)])),parse:ha},g_={...h_,bodyEncoding:"form",body:e=>Object.fromEntries(Object.entries(e.body).map(([t,r])=>[t,String(r)])),parse:ha},p_={auth:"optional",channel:"api",id:"heybox.user_miniprogram.post.favorite",method:"POST",path:"/bbs/app/link/favour",bodyEncoding:"form",failurePresentation:"none",body:e=>({link_id:e.targetId,favour_type:e.enabled?1:0}),parse:e=>xe(e,"社区操作响应异常")},T_={auth:"optional",channel:"api",id:"heybox.user_miniprogram.post.like",method:"POST",path:"/bbs/app/profile/award/link",bodyEncoding:"form",failurePresentation:"none",body:e=>({link_id:e.targetId,award_type:e.enabled?"1":"0"}),parse:e=>xe(e,"社区操作响应异常")},__={auth:"optional",channel:"api",id:"heybox.user_miniprogram.runtime.post.read",method:"POST",path:"/user_miniprogram/runtime/post",bodyEncoding:"form",failurePresentation:"none",body:e=>({...e}),parse:e=>xe(e,"关联帖子响应异常")},A_=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]),Be="�";var E;(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"})(E||(E={}));const at={DASH_DASH:"--",CDATA_START:"[CDATA[",DOCTYPE:"doctype",SCRIPT:"script",PUBLIC:"public",SYSTEM:"system"};function Pf(e){return e>=55296&&e<=57343}function I_(e){return e>=56320&&e<=57343}function b_(e,t){return(e-55296)*1024+9216+t}function vf(e){return e!==32&&e!==10&&e!==13&&e!==9&&e!==12&&e>=1&&e<=31||e>=127&&e<=159}function kf(e){return e>=64976&&e<=65007||A_.has(e)}var G;(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"})(G||(G={}));const y_=65536;class N_{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=y_,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:n,col:i,offset:s}=this,a=i+r,c=s+r;return{code:t,startLine:n,endLine:n,startCol:a,endCol:a,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(I_(r))return this.pos++,this._addGap(),b_(t,r)}else if(!this.lastChunkWritten)return this.endOfChunkHit=!0,E.EOF;return this._err(G.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 n=0;n<t.length;n++)if((this.html.charCodeAt(this.pos+n)|32)!==t.charCodeAt(n))return!1;return!0}peek(t){const r=this.pos+t;if(r>=this.html.length)return this.endOfChunkHit=!this.lastChunkWritten,E.EOF;const n=this.html.charCodeAt(r);return n===E.CARRIAGE_RETURN?E.LINE_FEED:n}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,E.EOF;let t=this.html.charCodeAt(this.pos);return t===E.CARRIAGE_RETURN?(this.isEol=!0,this.skipNextNewLine=!0,E.LINE_FEED):t===E.LINE_FEED&&(this.isEol=!0,this.skipNextNewLine)?(this.line--,this.skipNextNewLine=!1,this._addGap(),this.advance()):(this.skipNextNewLine=!1,Pf(t)&&(t=this._processSurrogate(t)),this.handler.onParseError===null||t>31&&t<127||t===E.LINE_FEED||t===E.CARRIAGE_RETURN||t>159&&t<64976||this._checkForProblematicCharacters(t),t)}_checkForProblematicCharacters(t){vf(t)?this._err(G.controlCharacterInInputStream):kf(t)&&this._err(G.noncharacterInInputStream)}retreat(t){for(this.pos-=t;this.pos<this.lastGapPos;)this.lastGapPos=this.gapStack.pop(),this.pos--;this.isEol=!1}}var Ce;(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"})(Ce||(Ce={}));function xf(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 w_=new Uint16Array('ᵁ<Õıʊҝջאٵ۞ޢߖࠏ੊ઑඡ๭༉༦჊ረዡᐕᒝᓃᓟᔥ\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;䄼ìࢰâ┩;䐻Ȁ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Ȁ;astЃ⹧⹲຅脀¶;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;怌'.split("").map(e=>e.charCodeAt(0))),D_=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 S_(e){var t;return e>=55296&&e<=57343||e>1114111?65533:(t=D_.get(e))!==null&&t!==void 0?t:e}var qe;(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"})(qe||(qe={}));const O_=32;var er;(function(e){e[e.VALUE_LENGTH=49152]="VALUE_LENGTH",e[e.BRANCH_LENGTH=16256]="BRANCH_LENGTH",e[e.JUMP_TABLE=127]="JUMP_TABLE"})(er||(er={}));function go(e){return e>=qe.ZERO&&e<=qe.NINE}function M_(e){return e>=qe.UPPER_A&&e<=qe.UPPER_F||e>=qe.LOWER_A&&e<=qe.LOWER_F}function C_(e){return e>=qe.UPPER_A&&e<=qe.UPPER_Z||e>=qe.LOWER_A&&e<=qe.LOWER_Z||go(e)}function R_(e){return e===qe.EQUALS||C_(e)}var Ye;(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"})(Ye||(Ye={}));var Gt;(function(e){e[e.Legacy=0]="Legacy",e[e.Strict=1]="Strict",e[e.Attribute=2]="Attribute"})(Gt||(Gt={}));class L_{constructor(t,r,n){this.decodeTree=t,this.emitCodePoint=r,this.errors=n,this.state=Ye.EntityStart,this.consumed=1,this.result=0,this.treeIndex=0,this.excess=1,this.decodeMode=Gt.Strict}startEntity(t){this.decodeMode=t,this.state=Ye.EntityStart,this.result=0,this.treeIndex=0,this.excess=1,this.consumed=1}write(t,r){switch(this.state){case Ye.EntityStart:return t.charCodeAt(r)===qe.NUM?(this.state=Ye.NumericStart,this.consumed+=1,this.stateNumericStart(t,r+1)):(this.state=Ye.NamedEntity,this.stateNamedEntity(t,r));case Ye.NumericStart:return this.stateNumericStart(t,r);case Ye.NumericDecimal:return this.stateNumericDecimal(t,r);case Ye.NumericHex:return this.stateNumericHex(t,r);case Ye.NamedEntity:return this.stateNamedEntity(t,r)}}stateNumericStart(t,r){return r>=t.length?-1:(t.charCodeAt(r)|O_)===qe.LOWER_X?(this.state=Ye.NumericHex,this.consumed+=1,this.stateNumericHex(t,r+1)):(this.state=Ye.NumericDecimal,this.stateNumericDecimal(t,r))}addToNumericResult(t,r,n,i){if(r!==n){const s=n-r;this.result=this.result*Math.pow(i,s)+Number.parseInt(t.substr(r,s),i),this.consumed+=s}}stateNumericHex(t,r){const n=r;for(;r<t.length;){const i=t.charCodeAt(r);if(go(i)||M_(i))r+=1;else return this.addToNumericResult(t,n,r,16),this.emitNumericEntity(i,3)}return this.addToNumericResult(t,n,r,16),-1}stateNumericDecimal(t,r){const n=r;for(;r<t.length;){const i=t.charCodeAt(r);if(go(i))r+=1;else return this.addToNumericResult(t,n,r,10),this.emitNumericEntity(i,2)}return this.addToNumericResult(t,n,r,10),-1}emitNumericEntity(t,r){var n;if(this.consumed<=r)return(n=this.errors)===null||n===void 0||n.absenceOfDigitsInNumericCharacterReference(this.consumed),0;if(t===qe.SEMI)this.consumed+=1;else if(this.decodeMode===Gt.Strict)return 0;return this.emitCodePoint(S_(this.result),this.consumed),this.errors&&(t!==qe.SEMI&&this.errors.missingSemicolonAfterCharacterReference(),this.errors.validateNumericCharacterReference(this.result)),this.consumed}stateNamedEntity(t,r){const{decodeTree:n}=this;let i=n[this.treeIndex],s=(i&er.VALUE_LENGTH)>>14;for(;r<t.length;r++,this.excess++){const a=t.charCodeAt(r);if(this.treeIndex=P_(n,i,this.treeIndex+Math.max(1,s),a),this.treeIndex<0)return this.result===0||this.decodeMode===Gt.Attribute&&(s===0||R_(a))?0:this.emitNotTerminatedNamedEntity();if(i=n[this.treeIndex],s=(i&er.VALUE_LENGTH)>>14,s!==0){if(a===qe.SEMI)return this.emitNamedEntityData(this.treeIndex,s,this.consumed+this.excess);this.decodeMode!==Gt.Strict&&(this.result=this.treeIndex,this.consumed+=this.excess,this.excess=0)}}return-1}emitNotTerminatedNamedEntity(){var t;const{result:r,decodeTree:n}=this,i=(n[r]&er.VALUE_LENGTH)>>14;return this.emitNamedEntityData(r,i,this.consumed),(t=this.errors)===null||t===void 0||t.missingSemicolonAfterCharacterReference(),this.consumed}emitNamedEntityData(t,r,n){const{decodeTree:i}=this;return this.emitCodePoint(r===1?i[t]&~er.VALUE_LENGTH:i[t+1],n),r===3&&this.emitCodePoint(i[t+2],n),n}end(){var t;switch(this.state){case Ye.NamedEntity:return this.result!==0&&(this.decodeMode!==Gt.Attribute||this.result===this.treeIndex)?this.emitNotTerminatedNamedEntity():0;case Ye.NumericDecimal:return this.emitNumericEntity(0,2);case Ye.NumericHex:return this.emitNumericEntity(0,3);case Ye.NumericStart:return(t=this.errors)===null||t===void 0||t.absenceOfDigitsInNumericCharacterReference(this.consumed),0;case Ye.EntityStart:return 0}}}function P_(e,t,r,n){const i=(t&er.BRANCH_LENGTH)>>7,s=t&er.JUMP_TABLE;if(i===0)return s!==0&&n===s?r:-1;if(s){const u=n-s;return u<0||u>=i?-1:e[r+u]-1}let a=r,c=a+i-1;for(;a<=c;){const u=a+c>>>1,d=e[u];if(d<n)a=u+1;else if(d>n)c=u-1;else return e[u+i]}return-1}var J;(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/"})(J||(J={}));var yr;(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"})(yr||(yr={}));var gt;(function(e){e.NO_QUIRKS="no-quirks",e.QUIRKS="quirks",e.LIMITED_QUIRKS="limited-quirks"})(gt||(gt={}));var k;(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="strike",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"})(k||(k={}));var o;(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"})(o||(o={}));const v_=new Map([[k.A,o.A],[k.ADDRESS,o.ADDRESS],[k.ANNOTATION_XML,o.ANNOTATION_XML],[k.APPLET,o.APPLET],[k.AREA,o.AREA],[k.ARTICLE,o.ARTICLE],[k.ASIDE,o.ASIDE],[k.B,o.B],[k.BASE,o.BASE],[k.BASEFONT,o.BASEFONT],[k.BGSOUND,o.BGSOUND],[k.BIG,o.BIG],[k.BLOCKQUOTE,o.BLOCKQUOTE],[k.BODY,o.BODY],[k.BR,o.BR],[k.BUTTON,o.BUTTON],[k.CAPTION,o.CAPTION],[k.CENTER,o.CENTER],[k.CODE,o.CODE],[k.COL,o.COL],[k.COLGROUP,o.COLGROUP],[k.DD,o.DD],[k.DESC,o.DESC],[k.DETAILS,o.DETAILS],[k.DIALOG,o.DIALOG],[k.DIR,o.DIR],[k.DIV,o.DIV],[k.DL,o.DL],[k.DT,o.DT],[k.EM,o.EM],[k.EMBED,o.EMBED],[k.FIELDSET,o.FIELDSET],[k.FIGCAPTION,o.FIGCAPTION],[k.FIGURE,o.FIGURE],[k.FONT,o.FONT],[k.FOOTER,o.FOOTER],[k.FOREIGN_OBJECT,o.FOREIGN_OBJECT],[k.FORM,o.FORM],[k.FRAME,o.FRAME],[k.FRAMESET,o.FRAMESET],[k.H1,o.H1],[k.H2,o.H2],[k.H3,o.H3],[k.H4,o.H4],[k.H5,o.H5],[k.H6,o.H6],[k.HEAD,o.HEAD],[k.HEADER,o.HEADER],[k.HGROUP,o.HGROUP],[k.HR,o.HR],[k.HTML,o.HTML],[k.I,o.I],[k.IMG,o.IMG],[k.IMAGE,o.IMAGE],[k.INPUT,o.INPUT],[k.IFRAME,o.IFRAME],[k.KEYGEN,o.KEYGEN],[k.LABEL,o.LABEL],[k.LI,o.LI],[k.LINK,o.LINK],[k.LISTING,o.LISTING],[k.MAIN,o.MAIN],[k.MALIGNMARK,o.MALIGNMARK],[k.MARQUEE,o.MARQUEE],[k.MATH,o.MATH],[k.MENU,o.MENU],[k.META,o.META],[k.MGLYPH,o.MGLYPH],[k.MI,o.MI],[k.MO,o.MO],[k.MN,o.MN],[k.MS,o.MS],[k.MTEXT,o.MTEXT],[k.NAV,o.NAV],[k.NOBR,o.NOBR],[k.NOFRAMES,o.NOFRAMES],[k.NOEMBED,o.NOEMBED],[k.NOSCRIPT,o.NOSCRIPT],[k.OBJECT,o.OBJECT],[k.OL,o.OL],[k.OPTGROUP,o.OPTGROUP],[k.OPTION,o.OPTION],[k.P,o.P],[k.PARAM,o.PARAM],[k.PLAINTEXT,o.PLAINTEXT],[k.PRE,o.PRE],[k.RB,o.RB],[k.RP,o.RP],[k.RT,o.RT],[k.RTC,o.RTC],[k.RUBY,o.RUBY],[k.S,o.S],[k.SCRIPT,o.SCRIPT],[k.SEARCH,o.SEARCH],[k.SECTION,o.SECTION],[k.SELECT,o.SELECT],[k.SOURCE,o.SOURCE],[k.SMALL,o.SMALL],[k.SPAN,o.SPAN],[k.STRIKE,o.STRIKE],[k.STRONG,o.STRONG],[k.STYLE,o.STYLE],[k.SUB,o.SUB],[k.SUMMARY,o.SUMMARY],[k.SUP,o.SUP],[k.TABLE,o.TABLE],[k.TBODY,o.TBODY],[k.TEMPLATE,o.TEMPLATE],[k.TEXTAREA,o.TEXTAREA],[k.TFOOT,o.TFOOT],[k.TD,o.TD],[k.TH,o.TH],[k.THEAD,o.THEAD],[k.TITLE,o.TITLE],[k.TR,o.TR],[k.TRACK,o.TRACK],[k.TT,o.TT],[k.U,o.U],[k.UL,o.UL],[k.SVG,o.SVG],[k.VAR,o.VAR],[k.WBR,o.WBR],[k.XMP,o.XMP]]);function ma(e){var t;return(t=v_.get(e))!==null&&t!==void 0?t:o.UNKNOWN}const re=o,k_={[J.HTML]:new Set([re.ADDRESS,re.APPLET,re.AREA,re.ARTICLE,re.ASIDE,re.BASE,re.BASEFONT,re.BGSOUND,re.BLOCKQUOTE,re.BODY,re.BR,re.BUTTON,re.CAPTION,re.CENTER,re.COL,re.COLGROUP,re.DD,re.DETAILS,re.DIR,re.DIV,re.DL,re.DT,re.EMBED,re.FIELDSET,re.FIGCAPTION,re.FIGURE,re.FOOTER,re.FORM,re.FRAME,re.FRAMESET,re.H1,re.H2,re.H3,re.H4,re.H5,re.H6,re.HEAD,re.HEADER,re.HGROUP,re.HR,re.HTML,re.IFRAME,re.IMG,re.INPUT,re.LI,re.LINK,re.LISTING,re.MAIN,re.MARQUEE,re.MENU,re.META,re.NAV,re.NOEMBED,re.NOFRAMES,re.NOSCRIPT,re.OBJECT,re.OL,re.P,re.PARAM,re.PLAINTEXT,re.PRE,re.SCRIPT,re.SECTION,re.SELECT,re.SOURCE,re.STYLE,re.SUMMARY,re.TABLE,re.TBODY,re.TD,re.TEMPLATE,re.TEXTAREA,re.TFOOT,re.TH,re.THEAD,re.TITLE,re.TR,re.TRACK,re.UL,re.WBR,re.XMP]),[J.MATHML]:new Set([re.MI,re.MO,re.MN,re.MS,re.MTEXT,re.ANNOTATION_XML]),[J.SVG]:new Set([re.TITLE,re.FOREIGN_OBJECT,re.DESC]),[J.XLINK]:new Set,[J.XML]:new Set,[J.XMLNS]:new Set},po=new Set([re.H1,re.H2,re.H3,re.H4,re.H5,re.H6]);k.STYLE,k.SCRIPT,k.XMP,k.IFRAME,k.NOEMBED,k.NOFRAMES,k.PLAINTEXT;var _;(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"})(_||(_={}));const ct={DATA:_.DATA,RCDATA:_.RCDATA,RAWTEXT:_.RAWTEXT,SCRIPT_DATA:_.SCRIPT_DATA,PLAINTEXT:_.PLAINTEXT,CDATA_SECTION:_.CDATA_SECTION};function x_(e){return e>=E.DIGIT_0&&e<=E.DIGIT_9}function Mn(e){return e>=E.LATIN_CAPITAL_A&&e<=E.LATIN_CAPITAL_Z}function U_(e){return e>=E.LATIN_SMALL_A&&e<=E.LATIN_SMALL_Z}function Wt(e){return U_(e)||Mn(e)}function Hu(e){return Wt(e)||x_(e)}function Di(e){return e+32}function Uf(e){return e===E.SPACE||e===E.LINE_FEED||e===E.TABULATION||e===E.FORM_FEED}function Fu(e){return Uf(e)||e===E.SOLIDUS||e===E.GREATER_THAN_SIGN}function B_(e){return e===E.NULL?G.nullCharacterReference:e>1114111?G.characterReferenceOutsideUnicodeRange:Pf(e)?G.surrogateCharacterReference:kf(e)?G.noncharacterCharacterReference:vf(e)||e===E.CARRIAGE_RETURN?G.controlCharacterReference:null}class H_{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=_.DATA,this.returnState=_.DATA,this.entityStartPos=0,this.consumedAfterSnapshot=-1,this.currentCharacterToken=null,this.currentToken=null,this.currentAttr={name:"",value:""},this.preprocessor=new N_(r),this.currentLocation=this.getCurrentLocation(-1),this.entityDecoder=new L_(w_,(n,i)=>{this.preprocessor.pos=this.entityStartPos+i-1,this._flushCodePointConsumedAsCharacterReference(n)},r.onParseError?{missingSemicolonAfterCharacterReference:()=>{this._err(G.missingSemicolonAfterCharacterReference,1)},absenceOfDigitsInNumericCharacterReference:n=>{this._err(G.absenceOfDigitsInNumericCharacterReference,this.entityStartPos-this.preprocessor.pos+n)},validateNumericCharacterReference:n=>{const i=B_(n);i&&this._err(i,1)}}:void 0)}_err(t,r=0){var n,i;(i=(n=this.handler).onParseError)===null||i===void 0||i.call(n,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?.())}write(t,r,n){this.active=!0,this.preprocessor.write(t,r),this._runParsingLoop(),this.paused||n?.()}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:Ce.START_TAG,tagName:"",tagID:o.UNKNOWN,selfClosing:!1,ackSelfClosing:!1,attrs:[],location:this.getCurrentLocation(1)}}_createEndTagToken(){this.currentToken={type:Ce.END_TAG,tagName:"",tagID:o.UNKNOWN,selfClosing:!1,ackSelfClosing:!1,attrs:[],location:this.getCurrentLocation(2)}}_createCommentToken(t){this.currentToken={type:Ce.COMMENT,data:"",location:this.getCurrentLocation(t)}}_createDoctypeToken(t){this.currentToken={type:Ce.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 n=this.currentToken;if(xf(n,this.currentAttr.name)===null){if(n.attrs.push(this.currentAttr),n.location&&this.currentLocation){const i=(t=(r=n.location).attrs)!==null&&t!==void 0?t:r.attrs=Object.create(null);i[this.currentAttr.name]=this.currentLocation,this._leaveAttrValue()}}else this._err(G.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=ma(t.tagName),t.type===Ce.START_TAG?(this.lastStartTagName=t.tagName,this.handler.onStartTag(t)):(t.attrs.length>0&&this._err(G.endTagWithAttributes),t.selfClosing&&this._err(G.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 Ce.CHARACTER:{this.handler.onCharacter(this.currentCharacterToken);break}case Ce.NULL_CHARACTER:{this.handler.onNullCharacter(this.currentCharacterToken);break}case Ce.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:Ce.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=Uf(t)?Ce.WHITESPACE_CHARACTER:t===E.NULL?Ce.NULL_CHARACTER:Ce.CHARACTER;this._appendCharToCurrentCharacterToken(r,String.fromCodePoint(t))}_emitChars(t){this._appendCharToCurrentCharacterToken(Ce.CHARACTER,t)}_startCharacterReference(){this.returnState=this.state,this.state=_.CHARACTER_REFERENCE,this.entityStartPos=this.preprocessor.pos,this.entityDecoder.startEntity(this._isCharacterReferenceInAttribute()?Gt.Attribute:Gt.Legacy)}_isCharacterReferenceInAttribute(){return this.returnState===_.ATTRIBUTE_VALUE_DOUBLE_QUOTED||this.returnState===_.ATTRIBUTE_VALUE_SINGLE_QUOTED||this.returnState===_.ATTRIBUTE_VALUE_UNQUOTED}_flushCodePointConsumedAsCharacterReference(t){this._isCharacterReferenceInAttribute()?this.currentAttr.value+=String.fromCodePoint(t):this._emitCodePoint(t)}_callState(t){switch(this.state){case _.DATA:{this._stateData(t);break}case _.RCDATA:{this._stateRcdata(t);break}case _.RAWTEXT:{this._stateRawtext(t);break}case _.SCRIPT_DATA:{this._stateScriptData(t);break}case _.PLAINTEXT:{this._statePlaintext(t);break}case _.TAG_OPEN:{this._stateTagOpen(t);break}case _.END_TAG_OPEN:{this._stateEndTagOpen(t);break}case _.TAG_NAME:{this._stateTagName(t);break}case _.RCDATA_LESS_THAN_SIGN:{this._stateRcdataLessThanSign(t);break}case _.RCDATA_END_TAG_OPEN:{this._stateRcdataEndTagOpen(t);break}case _.RCDATA_END_TAG_NAME:{this._stateRcdataEndTagName(t);break}case _.RAWTEXT_LESS_THAN_SIGN:{this._stateRawtextLessThanSign(t);break}case _.RAWTEXT_END_TAG_OPEN:{this._stateRawtextEndTagOpen(t);break}case _.RAWTEXT_END_TAG_NAME:{this._stateRawtextEndTagName(t);break}case _.SCRIPT_DATA_LESS_THAN_SIGN:{this._stateScriptDataLessThanSign(t);break}case _.SCRIPT_DATA_END_TAG_OPEN:{this._stateScriptDataEndTagOpen(t);break}case _.SCRIPT_DATA_END_TAG_NAME:{this._stateScriptDataEndTagName(t);break}case _.SCRIPT_DATA_ESCAPE_START:{this._stateScriptDataEscapeStart(t);break}case _.SCRIPT_DATA_ESCAPE_START_DASH:{this._stateScriptDataEscapeStartDash(t);break}case _.SCRIPT_DATA_ESCAPED:{this._stateScriptDataEscaped(t);break}case _.SCRIPT_DATA_ESCAPED_DASH:{this._stateScriptDataEscapedDash(t);break}case _.SCRIPT_DATA_ESCAPED_DASH_DASH:{this._stateScriptDataEscapedDashDash(t);break}case _.SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN:{this._stateScriptDataEscapedLessThanSign(t);break}case _.SCRIPT_DATA_ESCAPED_END_TAG_OPEN:{this._stateScriptDataEscapedEndTagOpen(t);break}case _.SCRIPT_DATA_ESCAPED_END_TAG_NAME:{this._stateScriptDataEscapedEndTagName(t);break}case _.SCRIPT_DATA_DOUBLE_ESCAPE_START:{this._stateScriptDataDoubleEscapeStart(t);break}case _.SCRIPT_DATA_DOUBLE_ESCAPED:{this._stateScriptDataDoubleEscaped(t);break}case _.SCRIPT_DATA_DOUBLE_ESCAPED_DASH:{this._stateScriptDataDoubleEscapedDash(t);break}case _.SCRIPT_DATA_DOUBLE_ESCAPED_DASH_DASH:{this._stateScriptDataDoubleEscapedDashDash(t);break}case _.SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN:{this._stateScriptDataDoubleEscapedLessThanSign(t);break}case _.SCRIPT_DATA_DOUBLE_ESCAPE_END:{this._stateScriptDataDoubleEscapeEnd(t);break}case _.BEFORE_ATTRIBUTE_NAME:{this._stateBeforeAttributeName(t);break}case _.ATTRIBUTE_NAME:{this._stateAttributeName(t);break}case _.AFTER_ATTRIBUTE_NAME:{this._stateAfterAttributeName(t);break}case _.BEFORE_ATTRIBUTE_VALUE:{this._stateBeforeAttributeValue(t);break}case _.ATTRIBUTE_VALUE_DOUBLE_QUOTED:{this._stateAttributeValueDoubleQuoted(t);break}case _.ATTRIBUTE_VALUE_SINGLE_QUOTED:{this._stateAttributeValueSingleQuoted(t);break}case _.ATTRIBUTE_VALUE_UNQUOTED:{this._stateAttributeValueUnquoted(t);break}case _.AFTER_ATTRIBUTE_VALUE_QUOTED:{this._stateAfterAttributeValueQuoted(t);break}case _.SELF_CLOSING_START_TAG:{this._stateSelfClosingStartTag(t);break}case _.BOGUS_COMMENT:{this._stateBogusComment(t);break}case _.MARKUP_DECLARATION_OPEN:{this._stateMarkupDeclarationOpen(t);break}case _.COMMENT_START:{this._stateCommentStart(t);break}case _.COMMENT_START_DASH:{this._stateCommentStartDash(t);break}case _.COMMENT:{this._stateComment(t);break}case _.COMMENT_LESS_THAN_SIGN:{this._stateCommentLessThanSign(t);break}case _.COMMENT_LESS_THAN_SIGN_BANG:{this._stateCommentLessThanSignBang(t);break}case _.COMMENT_LESS_THAN_SIGN_BANG_DASH:{this._stateCommentLessThanSignBangDash(t);break}case _.COMMENT_LESS_THAN_SIGN_BANG_DASH_DASH:{this._stateCommentLessThanSignBangDashDash(t);break}case _.COMMENT_END_DASH:{this._stateCommentEndDash(t);break}case _.COMMENT_END:{this._stateCommentEnd(t);break}case _.COMMENT_END_BANG:{this._stateCommentEndBang(t);break}case _.DOCTYPE:{this._stateDoctype(t);break}case _.BEFORE_DOCTYPE_NAME:{this._stateBeforeDoctypeName(t);break}case _.DOCTYPE_NAME:{this._stateDoctypeName(t);break}case _.AFTER_DOCTYPE_NAME:{this._stateAfterDoctypeName(t);break}case _.AFTER_DOCTYPE_PUBLIC_KEYWORD:{this._stateAfterDoctypePublicKeyword(t);break}case _.BEFORE_DOCTYPE_PUBLIC_IDENTIFIER:{this._stateBeforeDoctypePublicIdentifier(t);break}case _.DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED:{this._stateDoctypePublicIdentifierDoubleQuoted(t);break}case _.DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED:{this._stateDoctypePublicIdentifierSingleQuoted(t);break}case _.AFTER_DOCTYPE_PUBLIC_IDENTIFIER:{this._stateAfterDoctypePublicIdentifier(t);break}case _.BETWEEN_DOCTYPE_PUBLIC_AND_SYSTEM_IDENTIFIERS:{this._stateBetweenDoctypePublicAndSystemIdentifiers(t);break}case _.AFTER_DOCTYPE_SYSTEM_KEYWORD:{this._stateAfterDoctypeSystemKeyword(t);break}case _.BEFORE_DOCTYPE_SYSTEM_IDENTIFIER:{this._stateBeforeDoctypeSystemIdentifier(t);break}case _.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED:{this._stateDoctypeSystemIdentifierDoubleQuoted(t);break}case _.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED:{this._stateDoctypeSystemIdentifierSingleQuoted(t);break}case _.AFTER_DOCTYPE_SYSTEM_IDENTIFIER:{this._stateAfterDoctypeSystemIdentifier(t);break}case _.BOGUS_DOCTYPE:{this._stateBogusDoctype(t);break}case _.CDATA_SECTION:{this._stateCdataSection(t);break}case _.CDATA_SECTION_BRACKET:{this._stateCdataSectionBracket(t);break}case _.CDATA_SECTION_END:{this._stateCdataSectionEnd(t);break}case _.CHARACTER_REFERENCE:{this._stateCharacterReference();break}case _.AMBIGUOUS_AMPERSAND:{this._stateAmbiguousAmpersand(t);break}default:throw new Error("Unknown state")}}_stateData(t){switch(t){case E.LESS_THAN_SIGN:{this.state=_.TAG_OPEN;break}case E.AMPERSAND:{this._startCharacterReference();break}case E.NULL:{this._err(G.unexpectedNullCharacter),this._emitCodePoint(t);break}case E.EOF:{this._emitEOFToken();break}default:this._emitCodePoint(t)}}_stateRcdata(t){switch(t){case E.AMPERSAND:{this._startCharacterReference();break}case E.LESS_THAN_SIGN:{this.state=_.RCDATA_LESS_THAN_SIGN;break}case E.NULL:{this._err(G.unexpectedNullCharacter),this._emitChars(Be);break}case E.EOF:{this._emitEOFToken();break}default:this._emitCodePoint(t)}}_stateRawtext(t){switch(t){case E.LESS_THAN_SIGN:{this.state=_.RAWTEXT_LESS_THAN_SIGN;break}case E.NULL:{this._err(G.unexpectedNullCharacter),this._emitChars(Be);break}case E.EOF:{this._emitEOFToken();break}default:this._emitCodePoint(t)}}_stateScriptData(t){switch(t){case E.LESS_THAN_SIGN:{this.state=_.SCRIPT_DATA_LESS_THAN_SIGN;break}case E.NULL:{this._err(G.unexpectedNullCharacter),this._emitChars(Be);break}case E.EOF:{this._emitEOFToken();break}default:this._emitCodePoint(t)}}_statePlaintext(t){switch(t){case E.NULL:{this._err(G.unexpectedNullCharacter),this._emitChars(Be);break}case E.EOF:{this._emitEOFToken();break}default:this._emitCodePoint(t)}}_stateTagOpen(t){if(Wt(t))this._createStartTagToken(),this.state=_.TAG_NAME,this._stateTagName(t);else switch(t){case E.EXCLAMATION_MARK:{this.state=_.MARKUP_DECLARATION_OPEN;break}case E.SOLIDUS:{this.state=_.END_TAG_OPEN;break}case E.QUESTION_MARK:{this._err(G.unexpectedQuestionMarkInsteadOfTagName),this._createCommentToken(1),this.state=_.BOGUS_COMMENT,this._stateBogusComment(t);break}case E.EOF:{this._err(G.eofBeforeTagName),this._emitChars("<"),this._emitEOFToken();break}default:this._err(G.invalidFirstCharacterOfTagName),this._emitChars("<"),this.state=_.DATA,this._stateData(t)}}_stateEndTagOpen(t){if(Wt(t))this._createEndTagToken(),this.state=_.TAG_NAME,this._stateTagName(t);else switch(t){case E.GREATER_THAN_SIGN:{this._err(G.missingEndTagName),this.state=_.DATA;break}case E.EOF:{this._err(G.eofBeforeTagName),this._emitChars("</"),this._emitEOFToken();break}default:this._err(G.invalidFirstCharacterOfTagName),this._createCommentToken(2),this.state=_.BOGUS_COMMENT,this._stateBogusComment(t)}}_stateTagName(t){const r=this.currentToken;switch(t){case E.SPACE:case E.LINE_FEED:case E.TABULATION:case E.FORM_FEED:{this.state=_.BEFORE_ATTRIBUTE_NAME;break}case E.SOLIDUS:{this.state=_.SELF_CLOSING_START_TAG;break}case E.GREATER_THAN_SIGN:{this.state=_.DATA,this.emitCurrentTagToken();break}case E.NULL:{this._err(G.unexpectedNullCharacter),r.tagName+=Be;break}case E.EOF:{this._err(G.eofInTag),this._emitEOFToken();break}default:r.tagName+=String.fromCodePoint(Mn(t)?Di(t):t)}}_stateRcdataLessThanSign(t){t===E.SOLIDUS?this.state=_.RCDATA_END_TAG_OPEN:(this._emitChars("<"),this.state=_.RCDATA,this._stateRcdata(t))}_stateRcdataEndTagOpen(t){Wt(t)?(this.state=_.RCDATA_END_TAG_NAME,this._stateRcdataEndTagName(t)):(this._emitChars("</"),this.state=_.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 E.SPACE:case E.LINE_FEED:case E.TABULATION:case E.FORM_FEED:return this._advanceBy(this.lastStartTagName.length),this.state=_.BEFORE_ATTRIBUTE_NAME,!1;case E.SOLIDUS:return this._advanceBy(this.lastStartTagName.length),this.state=_.SELF_CLOSING_START_TAG,!1;case E.GREATER_THAN_SIGN:return this._advanceBy(this.lastStartTagName.length),this.emitCurrentTagToken(),this.state=_.DATA,!1;default:return!this._ensureHibernation()}}_stateRcdataEndTagName(t){this.handleSpecialEndTag(t)&&(this._emitChars("</"),this.state=_.RCDATA,this._stateRcdata(t))}_stateRawtextLessThanSign(t){t===E.SOLIDUS?this.state=_.RAWTEXT_END_TAG_OPEN:(this._emitChars("<"),this.state=_.RAWTEXT,this._stateRawtext(t))}_stateRawtextEndTagOpen(t){Wt(t)?(this.state=_.RAWTEXT_END_TAG_NAME,this._stateRawtextEndTagName(t)):(this._emitChars("</"),this.state=_.RAWTEXT,this._stateRawtext(t))}_stateRawtextEndTagName(t){this.handleSpecialEndTag(t)&&(this._emitChars("</"),this.state=_.RAWTEXT,this._stateRawtext(t))}_stateScriptDataLessThanSign(t){switch(t){case E.SOLIDUS:{this.state=_.SCRIPT_DATA_END_TAG_OPEN;break}case E.EXCLAMATION_MARK:{this.state=_.SCRIPT_DATA_ESCAPE_START,this._emitChars("<!");break}default:this._emitChars("<"),this.state=_.SCRIPT_DATA,this._stateScriptData(t)}}_stateScriptDataEndTagOpen(t){Wt(t)?(this.state=_.SCRIPT_DATA_END_TAG_NAME,this._stateScriptDataEndTagName(t)):(this._emitChars("</"),this.state=_.SCRIPT_DATA,this._stateScriptData(t))}_stateScriptDataEndTagName(t){this.handleSpecialEndTag(t)&&(this._emitChars("</"),this.state=_.SCRIPT_DATA,this._stateScriptData(t))}_stateScriptDataEscapeStart(t){t===E.HYPHEN_MINUS?(this.state=_.SCRIPT_DATA_ESCAPE_START_DASH,this._emitChars("-")):(this.state=_.SCRIPT_DATA,this._stateScriptData(t))}_stateScriptDataEscapeStartDash(t){t===E.HYPHEN_MINUS?(this.state=_.SCRIPT_DATA_ESCAPED_DASH_DASH,this._emitChars("-")):(this.state=_.SCRIPT_DATA,this._stateScriptData(t))}_stateScriptDataEscaped(t){switch(t){case E.HYPHEN_MINUS:{this.state=_.SCRIPT_DATA_ESCAPED_DASH,this._emitChars("-");break}case E.LESS_THAN_SIGN:{this.state=_.SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN;break}case E.NULL:{this._err(G.unexpectedNullCharacter),this._emitChars(Be);break}case E.EOF:{this._err(G.eofInScriptHtmlCommentLikeText),this._emitEOFToken();break}default:this._emitCodePoint(t)}}_stateScriptDataEscapedDash(t){switch(t){case E.HYPHEN_MINUS:{this.state=_.SCRIPT_DATA_ESCAPED_DASH_DASH,this._emitChars("-");break}case E.LESS_THAN_SIGN:{this.state=_.SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN;break}case E.NULL:{this._err(G.unexpectedNullCharacter),this.state=_.SCRIPT_DATA_ESCAPED,this._emitChars(Be);break}case E.EOF:{this._err(G.eofInScriptHtmlCommentLikeText),this._emitEOFToken();break}default:this.state=_.SCRIPT_DATA_ESCAPED,this._emitCodePoint(t)}}_stateScriptDataEscapedDashDash(t){switch(t){case E.HYPHEN_MINUS:{this._emitChars("-");break}case E.LESS_THAN_SIGN:{this.state=_.SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN;break}case E.GREATER_THAN_SIGN:{this.state=_.SCRIPT_DATA,this._emitChars(">");break}case E.NULL:{this._err(G.unexpectedNullCharacter),this.state=_.SCRIPT_DATA_ESCAPED,this._emitChars(Be);break}case E.EOF:{this._err(G.eofInScriptHtmlCommentLikeText),this._emitEOFToken();break}default:this.state=_.SCRIPT_DATA_ESCAPED,this._emitCodePoint(t)}}_stateScriptDataEscapedLessThanSign(t){t===E.SOLIDUS?this.state=_.SCRIPT_DATA_ESCAPED_END_TAG_OPEN:Wt(t)?(this._emitChars("<"),this.state=_.SCRIPT_DATA_DOUBLE_ESCAPE_START,this._stateScriptDataDoubleEscapeStart(t)):(this._emitChars("<"),this.state=_.SCRIPT_DATA_ESCAPED,this._stateScriptDataEscaped(t))}_stateScriptDataEscapedEndTagOpen(t){Wt(t)?(this.state=_.SCRIPT_DATA_ESCAPED_END_TAG_NAME,this._stateScriptDataEscapedEndTagName(t)):(this._emitChars("</"),this.state=_.SCRIPT_DATA_ESCAPED,this._stateScriptDataEscaped(t))}_stateScriptDataEscapedEndTagName(t){this.handleSpecialEndTag(t)&&(this._emitChars("</"),this.state=_.SCRIPT_DATA_ESCAPED,this._stateScriptDataEscaped(t))}_stateScriptDataDoubleEscapeStart(t){if(this.preprocessor.startsWith(at.SCRIPT,!1)&&Fu(this.preprocessor.peek(at.SCRIPT.length))){this._emitCodePoint(t);for(let r=0;r<at.SCRIPT.length;r++)this._emitCodePoint(this._consume());this.state=_.SCRIPT_DATA_DOUBLE_ESCAPED}else this._ensureHibernation()||(this.state=_.SCRIPT_DATA_ESCAPED,this._stateScriptDataEscaped(t))}_stateScriptDataDoubleEscaped(t){switch(t){case E.HYPHEN_MINUS:{this.state=_.SCRIPT_DATA_DOUBLE_ESCAPED_DASH,this._emitChars("-");break}case E.LESS_THAN_SIGN:{this.state=_.SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN,this._emitChars("<");break}case E.NULL:{this._err(G.unexpectedNullCharacter),this._emitChars(Be);break}case E.EOF:{this._err(G.eofInScriptHtmlCommentLikeText),this._emitEOFToken();break}default:this._emitCodePoint(t)}}_stateScriptDataDoubleEscapedDash(t){switch(t){case E.HYPHEN_MINUS:{this.state=_.SCRIPT_DATA_DOUBLE_ESCAPED_DASH_DASH,this._emitChars("-");break}case E.LESS_THAN_SIGN:{this.state=_.SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN,this._emitChars("<");break}case E.NULL:{this._err(G.unexpectedNullCharacter),this.state=_.SCRIPT_DATA_DOUBLE_ESCAPED,this._emitChars(Be);break}case E.EOF:{this._err(G.eofInScriptHtmlCommentLikeText),this._emitEOFToken();break}default:this.state=_.SCRIPT_DATA_DOUBLE_ESCAPED,this._emitCodePoint(t)}}_stateScriptDataDoubleEscapedDashDash(t){switch(t){case E.HYPHEN_MINUS:{this._emitChars("-");break}case E.LESS_THAN_SIGN:{this.state=_.SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN,this._emitChars("<");break}case E.GREATER_THAN_SIGN:{this.state=_.SCRIPT_DATA,this._emitChars(">");break}case E.NULL:{this._err(G.unexpectedNullCharacter),this.state=_.SCRIPT_DATA_DOUBLE_ESCAPED,this._emitChars(Be);break}case E.EOF:{this._err(G.eofInScriptHtmlCommentLikeText),this._emitEOFToken();break}default:this.state=_.SCRIPT_DATA_DOUBLE_ESCAPED,this._emitCodePoint(t)}}_stateScriptDataDoubleEscapedLessThanSign(t){t===E.SOLIDUS?(this.state=_.SCRIPT_DATA_DOUBLE_ESCAPE_END,this._emitChars("/")):(this.state=_.SCRIPT_DATA_DOUBLE_ESCAPED,this._stateScriptDataDoubleEscaped(t))}_stateScriptDataDoubleEscapeEnd(t){if(this.preprocessor.startsWith(at.SCRIPT,!1)&&Fu(this.preprocessor.peek(at.SCRIPT.length))){this._emitCodePoint(t);for(let r=0;r<at.SCRIPT.length;r++)this._emitCodePoint(this._consume());this.state=_.SCRIPT_DATA_ESCAPED}else this._ensureHibernation()||(this.state=_.SCRIPT_DATA_DOUBLE_ESCAPED,this._stateScriptDataDoubleEscaped(t))}_stateBeforeAttributeName(t){switch(t){case E.SPACE:case E.LINE_FEED:case E.TABULATION:case E.FORM_FEED:break;case E.SOLIDUS:case E.GREATER_THAN_SIGN:case E.EOF:{this.state=_.AFTER_ATTRIBUTE_NAME,this._stateAfterAttributeName(t);break}case E.EQUALS_SIGN:{this._err(G.unexpectedEqualsSignBeforeAttributeName),this._createAttr("="),this.state=_.ATTRIBUTE_NAME;break}default:this._createAttr(""),this.state=_.ATTRIBUTE_NAME,this._stateAttributeName(t)}}_stateAttributeName(t){switch(t){case E.SPACE:case E.LINE_FEED:case E.TABULATION:case E.FORM_FEED:case E.SOLIDUS:case E.GREATER_THAN_SIGN:case E.EOF:{this._leaveAttrName(),this.state=_.AFTER_ATTRIBUTE_NAME,this._stateAfterAttributeName(t);break}case E.EQUALS_SIGN:{this._leaveAttrName(),this.state=_.BEFORE_ATTRIBUTE_VALUE;break}case E.QUOTATION_MARK:case E.APOSTROPHE:case E.LESS_THAN_SIGN:{this._err(G.unexpectedCharacterInAttributeName),this.currentAttr.name+=String.fromCodePoint(t);break}case E.NULL:{this._err(G.unexpectedNullCharacter),this.currentAttr.name+=Be;break}default:this.currentAttr.name+=String.fromCodePoint(Mn(t)?Di(t):t)}}_stateAfterAttributeName(t){switch(t){case E.SPACE:case E.LINE_FEED:case E.TABULATION:case E.FORM_FEED:break;case E.SOLIDUS:{this.state=_.SELF_CLOSING_START_TAG;break}case E.EQUALS_SIGN:{this.state=_.BEFORE_ATTRIBUTE_VALUE;break}case E.GREATER_THAN_SIGN:{this.state=_.DATA,this.emitCurrentTagToken();break}case E.EOF:{this._err(G.eofInTag),this._emitEOFToken();break}default:this._createAttr(""),this.state=_.ATTRIBUTE_NAME,this._stateAttributeName(t)}}_stateBeforeAttributeValue(t){switch(t){case E.SPACE:case E.LINE_FEED:case E.TABULATION:case E.FORM_FEED:break;case E.QUOTATION_MARK:{this.state=_.ATTRIBUTE_VALUE_DOUBLE_QUOTED;break}case E.APOSTROPHE:{this.state=_.ATTRIBUTE_VALUE_SINGLE_QUOTED;break}case E.GREATER_THAN_SIGN:{this._err(G.missingAttributeValue),this.state=_.DATA,this.emitCurrentTagToken();break}default:this.state=_.ATTRIBUTE_VALUE_UNQUOTED,this._stateAttributeValueUnquoted(t)}}_stateAttributeValueDoubleQuoted(t){switch(t){case E.QUOTATION_MARK:{this.state=_.AFTER_ATTRIBUTE_VALUE_QUOTED;break}case E.AMPERSAND:{this._startCharacterReference();break}case E.NULL:{this._err(G.unexpectedNullCharacter),this.currentAttr.value+=Be;break}case E.EOF:{this._err(G.eofInTag),this._emitEOFToken();break}default:this.currentAttr.value+=String.fromCodePoint(t)}}_stateAttributeValueSingleQuoted(t){switch(t){case E.APOSTROPHE:{this.state=_.AFTER_ATTRIBUTE_VALUE_QUOTED;break}case E.AMPERSAND:{this._startCharacterReference();break}case E.NULL:{this._err(G.unexpectedNullCharacter),this.currentAttr.value+=Be;break}case E.EOF:{this._err(G.eofInTag),this._emitEOFToken();break}default:this.currentAttr.value+=String.fromCodePoint(t)}}_stateAttributeValueUnquoted(t){switch(t){case E.SPACE:case E.LINE_FEED:case E.TABULATION:case E.FORM_FEED:{this._leaveAttrValue(),this.state=_.BEFORE_ATTRIBUTE_NAME;break}case E.AMPERSAND:{this._startCharacterReference();break}case E.GREATER_THAN_SIGN:{this._leaveAttrValue(),this.state=_.DATA,this.emitCurrentTagToken();break}case E.NULL:{this._err(G.unexpectedNullCharacter),this.currentAttr.value+=Be;break}case E.QUOTATION_MARK:case E.APOSTROPHE:case E.LESS_THAN_SIGN:case E.EQUALS_SIGN:case E.GRAVE_ACCENT:{this._err(G.unexpectedCharacterInUnquotedAttributeValue),this.currentAttr.value+=String.fromCodePoint(t);break}case E.EOF:{this._err(G.eofInTag),this._emitEOFToken();break}default:this.currentAttr.value+=String.fromCodePoint(t)}}_stateAfterAttributeValueQuoted(t){switch(t){case E.SPACE:case E.LINE_FEED:case E.TABULATION:case E.FORM_FEED:{this._leaveAttrValue(),this.state=_.BEFORE_ATTRIBUTE_NAME;break}case E.SOLIDUS:{this._leaveAttrValue(),this.state=_.SELF_CLOSING_START_TAG;break}case E.GREATER_THAN_SIGN:{this._leaveAttrValue(),this.state=_.DATA,this.emitCurrentTagToken();break}case E.EOF:{this._err(G.eofInTag),this._emitEOFToken();break}default:this._err(G.missingWhitespaceBetweenAttributes),this.state=_.BEFORE_ATTRIBUTE_NAME,this._stateBeforeAttributeName(t)}}_stateSelfClosingStartTag(t){switch(t){case E.GREATER_THAN_SIGN:{const r=this.currentToken;r.selfClosing=!0,this.state=_.DATA,this.emitCurrentTagToken();break}case E.EOF:{this._err(G.eofInTag),this._emitEOFToken();break}default:this._err(G.unexpectedSolidusInTag),this.state=_.BEFORE_ATTRIBUTE_NAME,this._stateBeforeAttributeName(t)}}_stateBogusComment(t){const r=this.currentToken;switch(t){case E.GREATER_THAN_SIGN:{this.state=_.DATA,this.emitCurrentComment(r);break}case E.EOF:{this.emitCurrentComment(r),this._emitEOFToken();break}case E.NULL:{this._err(G.unexpectedNullCharacter),r.data+=Be;break}default:r.data+=String.fromCodePoint(t)}}_stateMarkupDeclarationOpen(t){this._consumeSequenceIfMatch(at.DASH_DASH,!0)?(this._createCommentToken(at.DASH_DASH.length+1),this.state=_.COMMENT_START):this._consumeSequenceIfMatch(at.DOCTYPE,!1)?(this.currentLocation=this.getCurrentLocation(at.DOCTYPE.length+1),this.state=_.DOCTYPE):this._consumeSequenceIfMatch(at.CDATA_START,!0)?this.inForeignNode?this.state=_.CDATA_SECTION:(this._err(G.cdataInHtmlContent),this._createCommentToken(at.CDATA_START.length+1),this.currentToken.data="[CDATA[",this.state=_.BOGUS_COMMENT):this._ensureHibernation()||(this._err(G.incorrectlyOpenedComment),this._createCommentToken(2),this.state=_.BOGUS_COMMENT,this._stateBogusComment(t))}_stateCommentStart(t){switch(t){case E.HYPHEN_MINUS:{this.state=_.COMMENT_START_DASH;break}case E.GREATER_THAN_SIGN:{this._err(G.abruptClosingOfEmptyComment),this.state=_.DATA;const r=this.currentToken;this.emitCurrentComment(r);break}default:this.state=_.COMMENT,this._stateComment(t)}}_stateCommentStartDash(t){const r=this.currentToken;switch(t){case E.HYPHEN_MINUS:{this.state=_.COMMENT_END;break}case E.GREATER_THAN_SIGN:{this._err(G.abruptClosingOfEmptyComment),this.state=_.DATA,this.emitCurrentComment(r);break}case E.EOF:{this._err(G.eofInComment),this.emitCurrentComment(r),this._emitEOFToken();break}default:r.data+="-",this.state=_.COMMENT,this._stateComment(t)}}_stateComment(t){const r=this.currentToken;switch(t){case E.HYPHEN_MINUS:{this.state=_.COMMENT_END_DASH;break}case E.LESS_THAN_SIGN:{r.data+="<",this.state=_.COMMENT_LESS_THAN_SIGN;break}case E.NULL:{this._err(G.unexpectedNullCharacter),r.data+=Be;break}case E.EOF:{this._err(G.eofInComment),this.emitCurrentComment(r),this._emitEOFToken();break}default:r.data+=String.fromCodePoint(t)}}_stateCommentLessThanSign(t){const r=this.currentToken;switch(t){case E.EXCLAMATION_MARK:{r.data+="!",this.state=_.COMMENT_LESS_THAN_SIGN_BANG;break}case E.LESS_THAN_SIGN:{r.data+="<";break}default:this.state=_.COMMENT,this._stateComment(t)}}_stateCommentLessThanSignBang(t){t===E.HYPHEN_MINUS?this.state=_.COMMENT_LESS_THAN_SIGN_BANG_DASH:(this.state=_.COMMENT,this._stateComment(t))}_stateCommentLessThanSignBangDash(t){t===E.HYPHEN_MINUS?this.state=_.COMMENT_LESS_THAN_SIGN_BANG_DASH_DASH:(this.state=_.COMMENT_END_DASH,this._stateCommentEndDash(t))}_stateCommentLessThanSignBangDashDash(t){t!==E.GREATER_THAN_SIGN&&t!==E.EOF&&this._err(G.nestedComment),this.state=_.COMMENT_END,this._stateCommentEnd(t)}_stateCommentEndDash(t){const r=this.currentToken;switch(t){case E.HYPHEN_MINUS:{this.state=_.COMMENT_END;break}case E.EOF:{this._err(G.eofInComment),this.emitCurrentComment(r),this._emitEOFToken();break}default:r.data+="-",this.state=_.COMMENT,this._stateComment(t)}}_stateCommentEnd(t){const r=this.currentToken;switch(t){case E.GREATER_THAN_SIGN:{this.state=_.DATA,this.emitCurrentComment(r);break}case E.EXCLAMATION_MARK:{this.state=_.COMMENT_END_BANG;break}case E.HYPHEN_MINUS:{r.data+="-";break}case E.EOF:{this._err(G.eofInComment),this.emitCurrentComment(r),this._emitEOFToken();break}default:r.data+="--",this.state=_.COMMENT,this._stateComment(t)}}_stateCommentEndBang(t){const r=this.currentToken;switch(t){case E.HYPHEN_MINUS:{r.data+="--!",this.state=_.COMMENT_END_DASH;break}case E.GREATER_THAN_SIGN:{this._err(G.incorrectlyClosedComment),this.state=_.DATA,this.emitCurrentComment(r);break}case E.EOF:{this._err(G.eofInComment),this.emitCurrentComment(r),this._emitEOFToken();break}default:r.data+="--!",this.state=_.COMMENT,this._stateComment(t)}}_stateDoctype(t){switch(t){case E.SPACE:case E.LINE_FEED:case E.TABULATION:case E.FORM_FEED:{this.state=_.BEFORE_DOCTYPE_NAME;break}case E.GREATER_THAN_SIGN:{this.state=_.BEFORE_DOCTYPE_NAME,this._stateBeforeDoctypeName(t);break}case E.EOF:{this._err(G.eofInDoctype),this._createDoctypeToken(null);const r=this.currentToken;r.forceQuirks=!0,this.emitCurrentDoctype(r),this._emitEOFToken();break}default:this._err(G.missingWhitespaceBeforeDoctypeName),this.state=_.BEFORE_DOCTYPE_NAME,this._stateBeforeDoctypeName(t)}}_stateBeforeDoctypeName(t){if(Mn(t))this._createDoctypeToken(String.fromCharCode(Di(t))),this.state=_.DOCTYPE_NAME;else switch(t){case E.SPACE:case E.LINE_FEED:case E.TABULATION:case E.FORM_FEED:break;case E.NULL:{this._err(G.unexpectedNullCharacter),this._createDoctypeToken(Be),this.state=_.DOCTYPE_NAME;break}case E.GREATER_THAN_SIGN:{this._err(G.missingDoctypeName),this._createDoctypeToken(null);const r=this.currentToken;r.forceQuirks=!0,this.emitCurrentDoctype(r),this.state=_.DATA;break}case E.EOF:{this._err(G.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=_.DOCTYPE_NAME}}_stateDoctypeName(t){const r=this.currentToken;switch(t){case E.SPACE:case E.LINE_FEED:case E.TABULATION:case E.FORM_FEED:{this.state=_.AFTER_DOCTYPE_NAME;break}case E.GREATER_THAN_SIGN:{this.state=_.DATA,this.emitCurrentDoctype(r);break}case E.NULL:{this._err(G.unexpectedNullCharacter),r.name+=Be;break}case E.EOF:{this._err(G.eofInDoctype),r.forceQuirks=!0,this.emitCurrentDoctype(r),this._emitEOFToken();break}default:r.name+=String.fromCodePoint(Mn(t)?Di(t):t)}}_stateAfterDoctypeName(t){const r=this.currentToken;switch(t){case E.SPACE:case E.LINE_FEED:case E.TABULATION:case E.FORM_FEED:break;case E.GREATER_THAN_SIGN:{this.state=_.DATA,this.emitCurrentDoctype(r);break}case E.EOF:{this._err(G.eofInDoctype),r.forceQuirks=!0,this.emitCurrentDoctype(r),this._emitEOFToken();break}default:this._consumeSequenceIfMatch(at.PUBLIC,!1)?this.state=_.AFTER_DOCTYPE_PUBLIC_KEYWORD:this._consumeSequenceIfMatch(at.SYSTEM,!1)?this.state=_.AFTER_DOCTYPE_SYSTEM_KEYWORD:this._ensureHibernation()||(this._err(G.invalidCharacterSequenceAfterDoctypeName),r.forceQuirks=!0,this.state=_.BOGUS_DOCTYPE,this._stateBogusDoctype(t))}}_stateAfterDoctypePublicKeyword(t){const r=this.currentToken;switch(t){case E.SPACE:case E.LINE_FEED:case E.TABULATION:case E.FORM_FEED:{this.state=_.BEFORE_DOCTYPE_PUBLIC_IDENTIFIER;break}case E.QUOTATION_MARK:{this._err(G.missingWhitespaceAfterDoctypePublicKeyword),r.publicId="",this.state=_.DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED;break}case E.APOSTROPHE:{this._err(G.missingWhitespaceAfterDoctypePublicKeyword),r.publicId="",this.state=_.DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED;break}case E.GREATER_THAN_SIGN:{this._err(G.missingDoctypePublicIdentifier),r.forceQuirks=!0,this.state=_.DATA,this.emitCurrentDoctype(r);break}case E.EOF:{this._err(G.eofInDoctype),r.forceQuirks=!0,this.emitCurrentDoctype(r),this._emitEOFToken();break}default:this._err(G.missingQuoteBeforeDoctypePublicIdentifier),r.forceQuirks=!0,this.state=_.BOGUS_DOCTYPE,this._stateBogusDoctype(t)}}_stateBeforeDoctypePublicIdentifier(t){const r=this.currentToken;switch(t){case E.SPACE:case E.LINE_FEED:case E.TABULATION:case E.FORM_FEED:break;case E.QUOTATION_MARK:{r.publicId="",this.state=_.DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED;break}case E.APOSTROPHE:{r.publicId="",this.state=_.DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED;break}case E.GREATER_THAN_SIGN:{this._err(G.missingDoctypePublicIdentifier),r.forceQuirks=!0,this.state=_.DATA,this.emitCurrentDoctype(r);break}case E.EOF:{this._err(G.eofInDoctype),r.forceQuirks=!0,this.emitCurrentDoctype(r),this._emitEOFToken();break}default:this._err(G.missingQuoteBeforeDoctypePublicIdentifier),r.forceQuirks=!0,this.state=_.BOGUS_DOCTYPE,this._stateBogusDoctype(t)}}_stateDoctypePublicIdentifierDoubleQuoted(t){const r=this.currentToken;switch(t){case E.QUOTATION_MARK:{this.state=_.AFTER_DOCTYPE_PUBLIC_IDENTIFIER;break}case E.NULL:{this._err(G.unexpectedNullCharacter),r.publicId+=Be;break}case E.GREATER_THAN_SIGN:{this._err(G.abruptDoctypePublicIdentifier),r.forceQuirks=!0,this.emitCurrentDoctype(r),this.state=_.DATA;break}case E.EOF:{this._err(G.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 E.APOSTROPHE:{this.state=_.AFTER_DOCTYPE_PUBLIC_IDENTIFIER;break}case E.NULL:{this._err(G.unexpectedNullCharacter),r.publicId+=Be;break}case E.GREATER_THAN_SIGN:{this._err(G.abruptDoctypePublicIdentifier),r.forceQuirks=!0,this.emitCurrentDoctype(r),this.state=_.DATA;break}case E.EOF:{this._err(G.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 E.SPACE:case E.LINE_FEED:case E.TABULATION:case E.FORM_FEED:{this.state=_.BETWEEN_DOCTYPE_PUBLIC_AND_SYSTEM_IDENTIFIERS;break}case E.GREATER_THAN_SIGN:{this.state=_.DATA,this.emitCurrentDoctype(r);break}case E.QUOTATION_MARK:{this._err(G.missingWhitespaceBetweenDoctypePublicAndSystemIdentifiers),r.systemId="",this.state=_.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED;break}case E.APOSTROPHE:{this._err(G.missingWhitespaceBetweenDoctypePublicAndSystemIdentifiers),r.systemId="",this.state=_.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED;break}case E.EOF:{this._err(G.eofInDoctype),r.forceQuirks=!0,this.emitCurrentDoctype(r),this._emitEOFToken();break}default:this._err(G.missingQuoteBeforeDoctypeSystemIdentifier),r.forceQuirks=!0,this.state=_.BOGUS_DOCTYPE,this._stateBogusDoctype(t)}}_stateBetweenDoctypePublicAndSystemIdentifiers(t){const r=this.currentToken;switch(t){case E.SPACE:case E.LINE_FEED:case E.TABULATION:case E.FORM_FEED:break;case E.GREATER_THAN_SIGN:{this.emitCurrentDoctype(r),this.state=_.DATA;break}case E.QUOTATION_MARK:{r.systemId="",this.state=_.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED;break}case E.APOSTROPHE:{r.systemId="",this.state=_.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED;break}case E.EOF:{this._err(G.eofInDoctype),r.forceQuirks=!0,this.emitCurrentDoctype(r),this._emitEOFToken();break}default:this._err(G.missingQuoteBeforeDoctypeSystemIdentifier),r.forceQuirks=!0,this.state=_.BOGUS_DOCTYPE,this._stateBogusDoctype(t)}}_stateAfterDoctypeSystemKeyword(t){const r=this.currentToken;switch(t){case E.SPACE:case E.LINE_FEED:case E.TABULATION:case E.FORM_FEED:{this.state=_.BEFORE_DOCTYPE_SYSTEM_IDENTIFIER;break}case E.QUOTATION_MARK:{this._err(G.missingWhitespaceAfterDoctypeSystemKeyword),r.systemId="",this.state=_.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED;break}case E.APOSTROPHE:{this._err(G.missingWhitespaceAfterDoctypeSystemKeyword),r.systemId="",this.state=_.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED;break}case E.GREATER_THAN_SIGN:{this._err(G.missingDoctypeSystemIdentifier),r.forceQuirks=!0,this.state=_.DATA,this.emitCurrentDoctype(r);break}case E.EOF:{this._err(G.eofInDoctype),r.forceQuirks=!0,this.emitCurrentDoctype(r),this._emitEOFToken();break}default:this._err(G.missingQuoteBeforeDoctypeSystemIdentifier),r.forceQuirks=!0,this.state=_.BOGUS_DOCTYPE,this._stateBogusDoctype(t)}}_stateBeforeDoctypeSystemIdentifier(t){const r=this.currentToken;switch(t){case E.SPACE:case E.LINE_FEED:case E.TABULATION:case E.FORM_FEED:break;case E.QUOTATION_MARK:{r.systemId="",this.state=_.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED;break}case E.APOSTROPHE:{r.systemId="",this.state=_.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED;break}case E.GREATER_THAN_SIGN:{this._err(G.missingDoctypeSystemIdentifier),r.forceQuirks=!0,this.state=_.DATA,this.emitCurrentDoctype(r);break}case E.EOF:{this._err(G.eofInDoctype),r.forceQuirks=!0,this.emitCurrentDoctype(r),this._emitEOFToken();break}default:this._err(G.missingQuoteBeforeDoctypeSystemIdentifier),r.forceQuirks=!0,this.state=_.BOGUS_DOCTYPE,this._stateBogusDoctype(t)}}_stateDoctypeSystemIdentifierDoubleQuoted(t){const r=this.currentToken;switch(t){case E.QUOTATION_MARK:{this.state=_.AFTER_DOCTYPE_SYSTEM_IDENTIFIER;break}case E.NULL:{this._err(G.unexpectedNullCharacter),r.systemId+=Be;break}case E.GREATER_THAN_SIGN:{this._err(G.abruptDoctypeSystemIdentifier),r.forceQuirks=!0,this.emitCurrentDoctype(r),this.state=_.DATA;break}case E.EOF:{this._err(G.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 E.APOSTROPHE:{this.state=_.AFTER_DOCTYPE_SYSTEM_IDENTIFIER;break}case E.NULL:{this._err(G.unexpectedNullCharacter),r.systemId+=Be;break}case E.GREATER_THAN_SIGN:{this._err(G.abruptDoctypeSystemIdentifier),r.forceQuirks=!0,this.emitCurrentDoctype(r),this.state=_.DATA;break}case E.EOF:{this._err(G.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 E.SPACE:case E.LINE_FEED:case E.TABULATION:case E.FORM_FEED:break;case E.GREATER_THAN_SIGN:{this.emitCurrentDoctype(r),this.state=_.DATA;break}case E.EOF:{this._err(G.eofInDoctype),r.forceQuirks=!0,this.emitCurrentDoctype(r),this._emitEOFToken();break}default:this._err(G.unexpectedCharacterAfterDoctypeSystemIdentifier),this.state=_.BOGUS_DOCTYPE,this._stateBogusDoctype(t)}}_stateBogusDoctype(t){const r=this.currentToken;switch(t){case E.GREATER_THAN_SIGN:{this.emitCurrentDoctype(r),this.state=_.DATA;break}case E.NULL:{this._err(G.unexpectedNullCharacter);break}case E.EOF:{this.emitCurrentDoctype(r),this._emitEOFToken();break}}}_stateCdataSection(t){switch(t){case E.RIGHT_SQUARE_BRACKET:{this.state=_.CDATA_SECTION_BRACKET;break}case E.EOF:{this._err(G.eofInCdata),this._emitEOFToken();break}default:this._emitCodePoint(t)}}_stateCdataSectionBracket(t){t===E.RIGHT_SQUARE_BRACKET?this.state=_.CDATA_SECTION_END:(this._emitChars("]"),this.state=_.CDATA_SECTION,this._stateCdataSection(t))}_stateCdataSectionEnd(t){switch(t){case E.GREATER_THAN_SIGN:{this.state=_.DATA;break}case E.RIGHT_SQUARE_BRACKET:{this._emitChars("]");break}default:this._emitChars("]]"),this.state=_.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(E.AMPERSAND),this.state=!this._isCharacterReferenceInAttribute()&&Hu(this.preprocessor.peek(1))?_.AMBIGUOUS_AMPERSAND:this.returnState):this.state=this.returnState}_stateAmbiguousAmpersand(t){Hu(t)?this._flushCodePointConsumedAsCharacterReference(t):(t===E.SEMICOLON&&this._err(G.unknownNamedCharacterReference),this.state=this.returnState,this._callState(t))}}const Bf=new Set([o.DD,o.DT,o.LI,o.OPTGROUP,o.OPTION,o.P,o.RB,o.RP,o.RT,o.RTC]),zu=new Set([...Bf,o.CAPTION,o.COLGROUP,o.TBODY,o.TD,o.TFOOT,o.TH,o.THEAD,o.TR]),zs=new Set([o.APPLET,o.CAPTION,o.HTML,o.MARQUEE,o.OBJECT,o.TABLE,o.TD,o.TEMPLATE,o.TH]),F_=new Set([...zs,o.OL,o.UL]),z_=new Set([...zs,o.BUTTON]),ju=new Set([o.ANNOTATION_XML,o.MI,o.MN,o.MO,o.MS,o.MTEXT]),Vu=new Set([o.DESC,o.FOREIGN_OBJECT,o.TITLE]),j_=new Set([o.TR,o.TEMPLATE,o.HTML]),V_=new Set([o.TBODY,o.TFOOT,o.THEAD,o.TEMPLATE,o.HTML]),G_=new Set([o.TABLE,o.TEMPLATE,o.HTML]),Y_=new Set([o.TD,o.TH]);class Q_{get currentTmplContentOrNode(){return this._isInTemplate()?this.treeAdapter.getTemplateContent(this.current):this.current}constructor(t,r,n){this.treeAdapter=r,this.handler=n,this.items=[],this.tagIDs=[],this.stackTop=-1,this.tmplCount=0,this.currentTagId=o.UNKNOWN,this.current=t}_indexOf(t){return this.items.lastIndexOf(t,this.stackTop)}_isInTemplate(){return this.currentTagId===o.TEMPLATE&&this.treeAdapter.getNamespaceURI(this.current)===J.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 n=this._indexOf(t);this.items[n]=r,n===this.stackTop&&(this.current=r)}insertAfter(t,r,n){const i=this._indexOf(t)+1;this.items.splice(i,0,r),this.tagIDs.splice(i,0,n),this.stackTop++,i===this.stackTop&&this._updateCurrentElement(),this.current&&this.currentTagId!==void 0&&this.handler.onItemPush(this.current,this.currentTagId,i===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])!==J.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 n=this._indexOfTagNames(t,r);this.shortenToLength(Math.max(n,0))}popUntilNumberedHeaderPopped(){this.popUntilPopped(po,J.HTML)}popUntilTableCellPopped(){this.popUntilPopped(Y_,J.HTML)}popAllUpToHtmlElement(){this.tmplCount=0,this.shortenToLength(1)}_indexOfTagNames(t,r){for(let n=this.stackTop;n>=0;n--)if(t.has(this.tagIDs[n])&&this.treeAdapter.getNamespaceURI(this.items[n])===r)return n;return-1}clearBackTo(t,r){const n=this._indexOfTagNames(t,r);this.shortenToLength(n+1)}clearBackToTableContext(){this.clearBackTo(G_,J.HTML)}clearBackToTableBodyContext(){this.clearBackTo(V_,J.HTML)}clearBackToTableRowContext(){this.clearBackTo(j_,J.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]===o.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]===o.HTML}hasInDynamicScope(t,r){for(let n=this.stackTop;n>=0;n--){const i=this.tagIDs[n];switch(this.treeAdapter.getNamespaceURI(this.items[n])){case J.HTML:{if(i===t)return!0;if(r.has(i))return!1;break}case J.SVG:{if(Vu.has(i))return!1;break}case J.MATHML:{if(ju.has(i))return!1;break}}}return!0}hasInScope(t){return this.hasInDynamicScope(t,zs)}hasInListItemScope(t){return this.hasInDynamicScope(t,F_)}hasInButtonScope(t){return this.hasInDynamicScope(t,z_)}hasNumberedHeaderInScope(){for(let t=this.stackTop;t>=0;t--){const r=this.tagIDs[t];switch(this.treeAdapter.getNamespaceURI(this.items[t])){case J.HTML:{if(po.has(r))return!0;if(zs.has(r))return!1;break}case J.SVG:{if(Vu.has(r))return!1;break}case J.MATHML:{if(ju.has(r))return!1;break}}}return!0}hasInTableScope(t){for(let r=this.stackTop;r>=0;r--)if(this.treeAdapter.getNamespaceURI(this.items[r])===J.HTML)switch(this.tagIDs[r]){case t:return!0;case o.TABLE:case o.HTML:return!1}return!0}hasTableBodyContextInTableScope(){for(let t=this.stackTop;t>=0;t--)if(this.treeAdapter.getNamespaceURI(this.items[t])===J.HTML)switch(this.tagIDs[t]){case o.TBODY:case o.THEAD:case o.TFOOT:return!0;case o.TABLE:case o.HTML:return!1}return!0}hasInSelectScope(t){for(let r=this.stackTop;r>=0;r--)if(this.treeAdapter.getNamespaceURI(this.items[r])===J.HTML)switch(this.tagIDs[r]){case t:return!0;case o.OPTION:case o.OPTGROUP:break;default:return!1}return!0}generateImpliedEndTags(){for(;this.currentTagId!==void 0&&Bf.has(this.currentTagId);)this.pop()}generateImpliedEndTagsThoroughly(){for(;this.currentTagId!==void 0&&zu.has(this.currentTagId);)this.pop()}generateImpliedEndTagsWithExclusion(t){for(;this.currentTagId!==void 0&&this.currentTagId!==t&&zu.has(this.currentTagId);)this.pop()}}const xa=3;var kt;(function(e){e[e.Marker=0]="Marker",e[e.Element=1]="Element"})(kt||(kt={}));const Gu={type:kt.Marker};class q_{constructor(t){this.treeAdapter=t,this.entries=[],this.bookmark=null}_getNoahArkConditionCandidates(t,r){const n=[],i=r.length,s=this.treeAdapter.getTagName(t),a=this.treeAdapter.getNamespaceURI(t);for(let c=0;c<this.entries.length;c++){const u=this.entries[c];if(u.type===kt.Marker)break;const{element:d}=u;if(this.treeAdapter.getTagName(d)===s&&this.treeAdapter.getNamespaceURI(d)===a){const l=this.treeAdapter.getAttrList(d);l.length===i&&n.push({idx:c,attrs:l})}}return n}_ensureNoahArkCondition(t){if(this.entries.length<xa)return;const r=this.treeAdapter.getAttrList(t),n=this._getNoahArkConditionCandidates(t,r);if(n.length<xa)return;const i=new Map(r.map(a=>[a.name,a.value]));let s=0;for(let a=0;a<n.length;a++){const c=n[a];c.attrs.every(u=>i.get(u.name)===u.value)&&(s+=1,s>=xa&&this.entries.splice(c.idx,1))}}insertMarker(){this.entries.unshift(Gu)}pushElement(t,r){this._ensureNoahArkCondition(t),this.entries.unshift({type:kt.Element,element:t,token:r})}insertElementAfterBookmark(t,r){const n=this.entries.indexOf(this.bookmark);this.entries.splice(n,0,{type:kt.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(Gu);t===-1?this.entries.length=0:this.entries.splice(0,t+1)}getElementEntryInScopeWithTagName(t){const r=this.entries.find(n=>n.type===kt.Marker||this.treeAdapter.getTagName(n.element)===t);return r&&r.type===kt.Element?r:null}getElementEntry(t){return this.entries.find(r=>r.type===kt.Element&&r.element===t)}}const $t={createDocument(){return{nodeName:"#document",mode:gt.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 n=e.childNodes.indexOf(r);e.childNodes.splice(n,0,t),t.parentNode=e},setTemplateContent(e,t){e.content=t},getTemplateContent(e){return e.content},setDocumentType(e,t,r,n){const i=e.childNodes.find(s=>s.nodeName==="#documentType");if(i)i.name=t,i.publicId=r,i.systemId=n;else{const s={nodeName:"#documentType",name:t,publicId:r,systemId:n,parentNode:null};$t.appendChild(e,s)}},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($t.isTextNode(r)){r.value+=t;return}}$t.appendChild(e,$t.createTextNode(t))},insertTextBefore(e,t,r){const n=e.childNodes[e.childNodes.indexOf(r)-1];n&&$t.isTextNode(n)?n.value+=t:$t.insertBefore(e,$t.createTextNode(t),r)},adoptAttributes(e,t){const r=new Set(e.attrs.map(n=>n.name));for(let n=0;n<t.length;n++)r.has(t[n].name)||e.attrs.push(t[n])},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}}},Hf="html",W_="about:legacy-compat",$_="http://www.ibm.com/data/dtd/v11/ibmxhtml1-transitional.dtd",Ff=["+//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//"],K_=[...Ff,"-//w3c//dtd html 4.01 frameset//","-//w3c//dtd html 4.01 transitional//"],Z_=new Set(["-//w3o//dtd w3 html strict 3.0//en//","-/w3c/dtd html 4.0 transitional/en","html"]),zf=["-//w3c//dtd xhtml 1.0 frameset//","-//w3c//dtd xhtml 1.0 transitional//"],X_=[...zf,"-//w3c//dtd html 4.01 frameset//","-//w3c//dtd html 4.01 transitional//"];function Yu(e,t){return t.some(r=>e.startsWith(r))}function J_(e){return e.name===Hf&&e.publicId===null&&(e.systemId===null||e.systemId===W_)}function eA(e){if(e.name!==Hf)return gt.QUIRKS;const{systemId:t}=e;if(t&&t.toLowerCase()===$_)return gt.QUIRKS;let{publicId:r}=e;if(r!==null){if(r=r.toLowerCase(),Z_.has(r))return gt.QUIRKS;let n=t===null?K_:Ff;if(Yu(r,n))return gt.QUIRKS;if(n=t===null?zf:X_,Yu(r,n))return gt.LIMITED_QUIRKS}return gt.NO_QUIRKS}const Qu={TEXT_HTML:"text/html",APPLICATION_XML:"application/xhtml+xml"},tA="definitionurl",rA="definitionURL",nA=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])),iA=new Map([["xlink:actuate",{prefix:"xlink",name:"actuate",namespace:J.XLINK}],["xlink:arcrole",{prefix:"xlink",name:"arcrole",namespace:J.XLINK}],["xlink:href",{prefix:"xlink",name:"href",namespace:J.XLINK}],["xlink:role",{prefix:"xlink",name:"role",namespace:J.XLINK}],["xlink:show",{prefix:"xlink",name:"show",namespace:J.XLINK}],["xlink:title",{prefix:"xlink",name:"title",namespace:J.XLINK}],["xlink:type",{prefix:"xlink",name:"type",namespace:J.XLINK}],["xml:lang",{prefix:"xml",name:"lang",namespace:J.XML}],["xml:space",{prefix:"xml",name:"space",namespace:J.XML}],["xmlns",{prefix:"",name:"xmlns",namespace:J.XMLNS}],["xmlns:xlink",{prefix:"xmlns",name:"xlink",namespace:J.XMLNS}]]),sA=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])),aA=new Set([o.B,o.BIG,o.BLOCKQUOTE,o.BODY,o.BR,o.CENTER,o.CODE,o.DD,o.DIV,o.DL,o.DT,o.EM,o.EMBED,o.H1,o.H2,o.H3,o.H4,o.H5,o.H6,o.HEAD,o.HR,o.I,o.IMG,o.LI,o.LISTING,o.MENU,o.META,o.NOBR,o.OL,o.P,o.PRE,o.RUBY,o.S,o.SMALL,o.SPAN,o.STRONG,o.STRIKE,o.SUB,o.SUP,o.TABLE,o.TT,o.U,o.UL,o.VAR]);function oA(e){const t=e.tagID;return t===o.FONT&&e.attrs.some(({name:n})=>n===yr.COLOR||n===yr.SIZE||n===yr.FACE)||aA.has(t)}function jf(e){for(let t=0;t<e.attrs.length;t++)if(e.attrs[t].name===tA){e.attrs[t].name=rA;break}}function Vf(e){for(let t=0;t<e.attrs.length;t++){const r=nA.get(e.attrs[t].name);r!=null&&(e.attrs[t].name=r)}}function bc(e){for(let t=0;t<e.attrs.length;t++){const r=iA.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 cA(e){const t=sA.get(e.tagName);t!=null&&(e.tagName=t,e.tagID=ma(e.tagName))}function uA(e,t){return t===J.MATHML&&(e===o.MI||e===o.MO||e===o.MN||e===o.MS||e===o.MTEXT)}function dA(e,t,r){if(t===J.MATHML&&e===o.ANNOTATION_XML){for(let n=0;n<r.length;n++)if(r[n].name===yr.ENCODING){const i=r[n].value.toLowerCase();return i===Qu.TEXT_HTML||i===Qu.APPLICATION_XML}}return t===J.SVG&&(e===o.FOREIGN_OBJECT||e===o.DESC||e===o.TITLE)}function lA(e,t,r,n){return(!n||n===J.HTML)&&dA(e,t,r)||(!n||n===J.MATHML)&&uA(e,t)}const fA="hidden",hA=8,mA=3;var A;(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"})(A||(A={}));const EA={startLine:-1,startCol:-1,startOffset:-1,endLine:-1,endCol:-1,endOffset:-1},Gf=new Set([o.TABLE,o.TBODY,o.TFOOT,o.THEAD,o.TR]),qu={scriptingEnabled:!0,sourceCodeLocationInfo:!1,treeAdapter:$t,onParseError:null};class gA{constructor(t,r,n=null,i=null){this.fragmentContext=n,this.scriptHandler=i,this.currentToken=null,this.stopped=!1,this.insertionMode=A.INITIAL,this.originalInsertionMode=A.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={...qu,...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 H_(this.options,this),this.activeFormattingElements=new q_(this.treeAdapter),this.fragmentContextID=n?ma(this.treeAdapter.getTagName(n)):o.UNKNOWN,this._setContextModes(n??this.document,this.fragmentContextID),this.openElements=new Q_(this.document,this.treeAdapter,this)}static parse(t,r){const n=new this(r);return n.tokenizer.write(t,!0),n.document}static getFragmentParser(t,r){const n={...qu,...r};t??(t=n.treeAdapter.createElement(k.TEMPLATE,J.HTML,[]));const i=n.treeAdapter.createElement("documentmock",J.HTML,[]),s=new this(n,i,t);return s.fragmentContextID===o.TEMPLATE&&s.tmplInsertionModeStack.unshift(A.IN_TEMPLATE),s._initTokenizerForFragmentParsing(),s._insertFakeRootElement(),s._resetInsertionMode(),s._findFormInFragmentContext(),s}getFragment(){const t=this.treeAdapter.getFirstChild(this.document),r=this.treeAdapter.createDocumentFragment();return this._adoptNodes(t,r),r}_err(t,r,n){var i;if(!this.onParseError)return;const s=(i=t.location)!==null&&i!==void 0?i:EA,a={code:r,startLine:s.startLine,startCol:s.startCol,startOffset:s.startOffset,endLine:n?s.startLine:s.endLine,endCol:n?s.startCol:s.endCol,endOffset:n?s.startOffset:s.endOffset};this.onParseError(a)}onItemPush(t,r,n){var i,s;(s=(i=this.treeAdapter).onItemPush)===null||s===void 0||s.call(i,t),n&&this.openElements.stackTop>0&&this._setContextModes(t,r)}onItemPop(t,r){var n,i;if(this.options.sourceCodeLocationInfo&&this._setEndLocation(t,this.currentToken),(i=(n=this.treeAdapter).onItemPop)===null||i===void 0||i.call(n,t,this.openElements.current),r){let s,a;this.openElements.stackTop===0&&this.fragmentContext?(s=this.fragmentContext,a=this.fragmentContextID):{current:s,currentTagId:a}=this.openElements,this._setContextModes(s,a)}}_setContextModes(t,r){const n=t===this.document||t&&this.treeAdapter.getNamespaceURI(t)===J.HTML;this.currentNotInHTML=!n,this.tokenizer.inForeignNode=!n&&t!==void 0&&r!==void 0&&!this._isIntegrationPoint(r,t)}_switchToTextParsing(t,r){this._insertElement(t,J.HTML),this.tokenizer.state=r,this.originalInsertionMode=this.insertionMode,this.insertionMode=A.TEXT}switchToPlaintextParsing(){this.insertionMode=A.TEXT,this.originalInsertionMode=A.IN_BODY,this.tokenizer.state=ct.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)===k.FORM){this.formElement=t;break}t=this.treeAdapter.getParentNode(t)}}_initTokenizerForFragmentParsing(){if(!(!this.fragmentContext||this.treeAdapter.getNamespaceURI(this.fragmentContext)!==J.HTML))switch(this.fragmentContextID){case o.TITLE:case o.TEXTAREA:{this.tokenizer.state=ct.RCDATA;break}case o.STYLE:case o.XMP:case o.IFRAME:case o.NOEMBED:case o.NOFRAMES:case o.NOSCRIPT:{this.tokenizer.state=ct.RAWTEXT;break}case o.SCRIPT:{this.tokenizer.state=ct.SCRIPT_DATA;break}case o.PLAINTEXT:{this.tokenizer.state=ct.PLAINTEXT;break}}}_setDocumentType(t){const r=t.name||"",n=t.publicId||"",i=t.systemId||"";if(this.treeAdapter.setDocumentType(this.document,r,n,i),t.location){const a=this.treeAdapter.getChildNodes(this.document).find(c=>this.treeAdapter.isDocumentTypeNode(c));a&&this.treeAdapter.setNodeSourceCodeLocation(a,t.location)}}_attachElementToTree(t,r){if(this.options.sourceCodeLocationInfo){const n=r&&{...r,startTag:r};this.treeAdapter.setNodeSourceCodeLocation(t,n)}if(this._shouldFosterParentOnInsertion())this._fosterParentElement(t);else{const n=this.openElements.currentTmplContentOrNode;this.treeAdapter.appendChild(n??this.document,t)}}_appendElement(t,r){const n=this.treeAdapter.createElement(t.tagName,r,t.attrs);this._attachElementToTree(n,t.location)}_insertElement(t,r){const n=this.treeAdapter.createElement(t.tagName,r,t.attrs);this._attachElementToTree(n,t.location),this.openElements.push(n,t.tagID)}_insertFakeElement(t,r){const n=this.treeAdapter.createElement(t,J.HTML,[]);this._attachElementToTree(n,null),this.openElements.push(n,r)}_insertTemplate(t){const r=this.treeAdapter.createElement(t.tagName,J.HTML,t.attrs),n=this.treeAdapter.createDocumentFragment();this.treeAdapter.setTemplateContent(r,n),this._attachElementToTree(r,t.location),this.openElements.push(r,t.tagID),this.options.sourceCodeLocationInfo&&this.treeAdapter.setNodeSourceCodeLocation(n,null)}_insertFakeRootElement(){const t=this.treeAdapter.createElement(k.HTML,J.HTML,[]);this.options.sourceCodeLocationInfo&&this.treeAdapter.setNodeSourceCodeLocation(t,null),this.treeAdapter.appendChild(this.openElements.current,t),this.openElements.push(t,o.HTML)}_appendCommentNode(t,r){const n=this.treeAdapter.createCommentNode(t.data);this.treeAdapter.appendChild(r,n),this.options.sourceCodeLocationInfo&&this.treeAdapter.setNodeSourceCodeLocation(n,t.location)}_insertCharacters(t){let r,n;if(this._shouldFosterParentOnInsertion()?({parent:r,beforeElement:n}=this._findFosterParentingLocation(),n?this.treeAdapter.insertTextBefore(r,t.chars,n):this.treeAdapter.insertText(r,t.chars)):(r=this.openElements.currentTmplContentOrNode,this.treeAdapter.insertText(r,t.chars)),!t.location)return;const i=this.treeAdapter.getChildNodes(r),s=n?i.lastIndexOf(n):i.length,a=i[s-1];if(this.treeAdapter.getNodeSourceCodeLocation(a)){const{endLine:u,endCol:d,endOffset:l}=t.location;this.treeAdapter.updateNodeSourceCodeLocation(a,{endLine:u,endCol:d,endOffset:l})}else this.options.sourceCodeLocationInfo&&this.treeAdapter.setNodeSourceCodeLocation(a,t.location)}_adoptNodes(t,r){for(let n=this.treeAdapter.getFirstChild(t);n;n=this.treeAdapter.getFirstChild(t))this.treeAdapter.detachNode(n),this.treeAdapter.appendChild(r,n)}_setEndLocation(t,r){if(this.treeAdapter.getNodeSourceCodeLocation(t)&&r.location){const n=r.location,i=this.treeAdapter.getTagName(t),s=r.type===Ce.END_TAG&&i===r.tagName?{endTag:{...n},endLine:n.endLine,endCol:n.endCol,endOffset:n.endOffset}:{endLine:n.startLine,endCol:n.startCol,endOffset:n.startOffset};this.treeAdapter.updateNodeSourceCodeLocation(t,s)}}shouldProcessStartTagTokenInForeignContent(t){if(!this.currentNotInHTML)return!1;let r,n;return this.openElements.stackTop===0&&this.fragmentContext?(r=this.fragmentContext,n=this.fragmentContextID):{current:r,currentTagId:n}=this.openElements,t.tagID===o.SVG&&this.treeAdapter.getTagName(r)===k.ANNOTATION_XML&&this.treeAdapter.getNamespaceURI(r)===J.MATHML?!1:this.tokenizer.inForeignNode||(t.tagID===o.MGLYPH||t.tagID===o.MALIGNMARK)&&n!==void 0&&!this._isIntegrationPoint(n,r,J.HTML)}_processToken(t){switch(t.type){case Ce.CHARACTER:{this.onCharacter(t);break}case Ce.NULL_CHARACTER:{this.onNullCharacter(t);break}case Ce.COMMENT:{this.onComment(t);break}case Ce.DOCTYPE:{this.onDoctype(t);break}case Ce.START_TAG:{this._processStartTag(t);break}case Ce.END_TAG:{this.onEndTag(t);break}case Ce.EOF:{this.onEof(t);break}case Ce.WHITESPACE_CHARACTER:{this.onWhitespaceCharacter(t);break}}}_isIntegrationPoint(t,r,n){const i=this.treeAdapter.getNamespaceURI(r),s=this.treeAdapter.getAttrList(r);return lA(t,i,s,n)}_reconstructActiveFormattingElements(){const t=this.activeFormattingElements.entries.length;if(t){const r=this.activeFormattingElements.entries.findIndex(i=>i.type===kt.Marker||this.openElements.contains(i.element)),n=r===-1?t-1:r-1;for(let i=n;i>=0;i--){const s=this.activeFormattingElements.entries[i];this._insertElement(s.token,this.treeAdapter.getNamespaceURI(s.element)),s.element=this.openElements.current}}}_closeTableCell(){this.openElements.generateImpliedEndTags(),this.openElements.popUntilTableCellPopped(),this.activeFormattingElements.clearToLastMarker(),this.insertionMode=A.IN_ROW}_closePElement(){this.openElements.generateImpliedEndTagsWithExclusion(o.P),this.openElements.popUntilTagNamePopped(o.P)}_resetInsertionMode(){for(let t=this.openElements.stackTop;t>=0;t--)switch(t===0&&this.fragmentContext?this.fragmentContextID:this.openElements.tagIDs[t]){case o.TR:{this.insertionMode=A.IN_ROW;return}case o.TBODY:case o.THEAD:case o.TFOOT:{this.insertionMode=A.IN_TABLE_BODY;return}case o.CAPTION:{this.insertionMode=A.IN_CAPTION;return}case o.COLGROUP:{this.insertionMode=A.IN_COLUMN_GROUP;return}case o.TABLE:{this.insertionMode=A.IN_TABLE;return}case o.BODY:{this.insertionMode=A.IN_BODY;return}case o.FRAMESET:{this.insertionMode=A.IN_FRAMESET;return}case o.SELECT:{this._resetInsertionModeForSelect(t);return}case o.TEMPLATE:{this.insertionMode=this.tmplInsertionModeStack[0];return}case o.HTML:{this.insertionMode=this.headElement?A.AFTER_HEAD:A.BEFORE_HEAD;return}case o.TD:case o.TH:{if(t>0){this.insertionMode=A.IN_CELL;return}break}case o.HEAD:{if(t>0){this.insertionMode=A.IN_HEAD;return}break}}this.insertionMode=A.IN_BODY}_resetInsertionModeForSelect(t){if(t>0)for(let r=t-1;r>0;r--){const n=this.openElements.tagIDs[r];if(n===o.TEMPLATE)break;if(n===o.TABLE){this.insertionMode=A.IN_SELECT_IN_TABLE;return}}this.insertionMode=A.IN_SELECT}_isElementCausesFosterParenting(t){return Gf.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 o.TEMPLATE:{if(this.treeAdapter.getNamespaceURI(r)===J.HTML)return{parent:this.treeAdapter.getTemplateContent(r),beforeElement:null};break}case o.TABLE:{const n=this.treeAdapter.getParentNode(r);return n?{parent:n,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 n=this.treeAdapter.getNamespaceURI(t);return k_[n].has(r)}onCharacter(t){if(this.skipNextNewLine=!1,this.tokenizer.inForeignNode){QI(this,t);return}switch(this.insertionMode){case A.INITIAL:{_n(this,t);break}case A.BEFORE_HTML:{Pn(this,t);break}case A.BEFORE_HEAD:{vn(this,t);break}case A.IN_HEAD:{kn(this,t);break}case A.IN_HEAD_NO_SCRIPT:{xn(this,t);break}case A.AFTER_HEAD:{Un(this,t);break}case A.IN_BODY:case A.IN_CAPTION:case A.IN_CELL:case A.IN_TEMPLATE:{Qf(this,t);break}case A.TEXT:case A.IN_SELECT:case A.IN_SELECT_IN_TABLE:{this._insertCharacters(t);break}case A.IN_TABLE:case A.IN_TABLE_BODY:case A.IN_ROW:{Ua(this,t);break}case A.IN_TABLE_TEXT:{Xf(this,t);break}case A.IN_COLUMN_GROUP:{js(this,t);break}case A.AFTER_BODY:{Vs(this,t);break}case A.AFTER_AFTER_BODY:{zi(this,t);break}}}onNullCharacter(t){if(this.skipNextNewLine=!1,this.tokenizer.inForeignNode){YI(this,t);return}switch(this.insertionMode){case A.INITIAL:{_n(this,t);break}case A.BEFORE_HTML:{Pn(this,t);break}case A.BEFORE_HEAD:{vn(this,t);break}case A.IN_HEAD:{kn(this,t);break}case A.IN_HEAD_NO_SCRIPT:{xn(this,t);break}case A.AFTER_HEAD:{Un(this,t);break}case A.TEXT:{this._insertCharacters(t);break}case A.IN_TABLE:case A.IN_TABLE_BODY:case A.IN_ROW:{Ua(this,t);break}case A.IN_COLUMN_GROUP:{js(this,t);break}case A.AFTER_BODY:{Vs(this,t);break}case A.AFTER_AFTER_BODY:{zi(this,t);break}}}onComment(t){if(this.skipNextNewLine=!1,this.currentNotInHTML){To(this,t);return}switch(this.insertionMode){case A.INITIAL:case A.BEFORE_HTML:case A.BEFORE_HEAD:case A.IN_HEAD:case A.IN_HEAD_NO_SCRIPT:case A.AFTER_HEAD:case A.IN_BODY:case A.IN_TABLE:case A.IN_CAPTION:case A.IN_COLUMN_GROUP:case A.IN_TABLE_BODY:case A.IN_ROW:case A.IN_CELL:case A.IN_SELECT:case A.IN_SELECT_IN_TABLE:case A.IN_TEMPLATE:case A.IN_FRAMESET:case A.AFTER_FRAMESET:{To(this,t);break}case A.IN_TABLE_TEXT:{An(this,t);break}case A.AFTER_BODY:{yA(this,t);break}case A.AFTER_AFTER_BODY:case A.AFTER_AFTER_FRAMESET:{NA(this,t);break}}}onDoctype(t){switch(this.skipNextNewLine=!1,this.insertionMode){case A.INITIAL:{wA(this,t);break}case A.BEFORE_HEAD:case A.IN_HEAD:case A.IN_HEAD_NO_SCRIPT:case A.AFTER_HEAD:{this._err(t,G.misplacedDoctype);break}case A.IN_TABLE_TEXT:{An(this,t);break}}}onStartTag(t){this.skipNextNewLine=!1,this.currentToken=t,this._processStartTag(t),t.selfClosing&&!t.ackSelfClosing&&this._err(t,G.nonVoidHtmlElementStartTagWithTrailingSolidus)}_processStartTag(t){this.shouldProcessStartTagTokenInForeignContent(t)?qI(this,t):this._startTagOutsideForeignContent(t)}_startTagOutsideForeignContent(t){switch(this.insertionMode){case A.INITIAL:{_n(this,t);break}case A.BEFORE_HTML:{DA(this,t);break}case A.BEFORE_HEAD:{OA(this,t);break}case A.IN_HEAD:{Ot(this,t);break}case A.IN_HEAD_NO_SCRIPT:{RA(this,t);break}case A.AFTER_HEAD:{PA(this,t);break}case A.IN_BODY:{et(this,t);break}case A.IN_TABLE:{tn(this,t);break}case A.IN_TABLE_TEXT:{An(this,t);break}case A.IN_CAPTION:{MI(this,t);break}case A.IN_COLUMN_GROUP:{wc(this,t);break}case A.IN_TABLE_BODY:{pa(this,t);break}case A.IN_ROW:{Ta(this,t);break}case A.IN_CELL:{LI(this,t);break}case A.IN_SELECT:{th(this,t);break}case A.IN_SELECT_IN_TABLE:{vI(this,t);break}case A.IN_TEMPLATE:{xI(this,t);break}case A.AFTER_BODY:{BI(this,t);break}case A.IN_FRAMESET:{HI(this,t);break}case A.AFTER_FRAMESET:{zI(this,t);break}case A.AFTER_AFTER_BODY:{VI(this,t);break}case A.AFTER_AFTER_FRAMESET:{GI(this,t);break}}}onEndTag(t){this.skipNextNewLine=!1,this.currentToken=t,this.currentNotInHTML?WI(this,t):this._endTagOutsideForeignContent(t)}_endTagOutsideForeignContent(t){switch(this.insertionMode){case A.INITIAL:{_n(this,t);break}case A.BEFORE_HTML:{SA(this,t);break}case A.BEFORE_HEAD:{MA(this,t);break}case A.IN_HEAD:{CA(this,t);break}case A.IN_HEAD_NO_SCRIPT:{LA(this,t);break}case A.AFTER_HEAD:{vA(this,t);break}case A.IN_BODY:{ga(this,t);break}case A.TEXT:{_I(this,t);break}case A.IN_TABLE:{ii(this,t);break}case A.IN_TABLE_TEXT:{An(this,t);break}case A.IN_CAPTION:{CI(this,t);break}case A.IN_COLUMN_GROUP:{RI(this,t);break}case A.IN_TABLE_BODY:{_o(this,t);break}case A.IN_ROW:{eh(this,t);break}case A.IN_CELL:{PI(this,t);break}case A.IN_SELECT:{rh(this,t);break}case A.IN_SELECT_IN_TABLE:{kI(this,t);break}case A.IN_TEMPLATE:{UI(this,t);break}case A.AFTER_BODY:{ih(this,t);break}case A.IN_FRAMESET:{FI(this,t);break}case A.AFTER_FRAMESET:{jI(this,t);break}case A.AFTER_AFTER_BODY:{zi(this,t);break}}}onEof(t){switch(this.insertionMode){case A.INITIAL:{_n(this,t);break}case A.BEFORE_HTML:{Pn(this,t);break}case A.BEFORE_HEAD:{vn(this,t);break}case A.IN_HEAD:{kn(this,t);break}case A.IN_HEAD_NO_SCRIPT:{xn(this,t);break}case A.AFTER_HEAD:{Un(this,t);break}case A.IN_BODY:case A.IN_TABLE:case A.IN_CAPTION:case A.IN_COLUMN_GROUP:case A.IN_TABLE_BODY:case A.IN_ROW:case A.IN_CELL:case A.IN_SELECT:case A.IN_SELECT_IN_TABLE:{Kf(this,t);break}case A.TEXT:{AI(this,t);break}case A.IN_TABLE_TEXT:{An(this,t);break}case A.IN_TEMPLATE:{nh(this,t);break}case A.AFTER_BODY:case A.IN_FRAMESET:case A.AFTER_FRAMESET:case A.AFTER_AFTER_BODY:case A.AFTER_AFTER_FRAMESET:{Nc(this,t);break}}}onWhitespaceCharacter(t){if(this.skipNextNewLine&&(this.skipNextNewLine=!1,t.chars.charCodeAt(0)===E.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 A.IN_HEAD:case A.IN_HEAD_NO_SCRIPT:case A.AFTER_HEAD:case A.TEXT:case A.IN_COLUMN_GROUP:case A.IN_SELECT:case A.IN_SELECT_IN_TABLE:case A.IN_FRAMESET:case A.AFTER_FRAMESET:{this._insertCharacters(t);break}case A.IN_BODY:case A.IN_CAPTION:case A.IN_CELL:case A.IN_TEMPLATE:case A.AFTER_BODY:case A.AFTER_AFTER_BODY:case A.AFTER_AFTER_FRAMESET:{Yf(this,t);break}case A.IN_TABLE:case A.IN_TABLE_BODY:case A.IN_ROW:{Ua(this,t);break}case A.IN_TABLE_TEXT:{Zf(this,t);break}}}}function pA(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):$f(e,t),r}function TA(e,t){let r=null,n=e.openElements.stackTop;for(;n>=0;n--){const i=e.openElements.items[n];if(i===t.element)break;e._isSpecialElement(i,e.openElements.tagIDs[n])&&(r=i)}return r||(e.openElements.shortenToLength(Math.max(n,0)),e.activeFormattingElements.removeEntry(t)),r}function _A(e,t,r){let n=t,i=e.openElements.getCommonAncestor(t);for(let s=0,a=i;a!==r;s++,a=i){i=e.openElements.getCommonAncestor(a);const c=e.activeFormattingElements.getElementEntry(a),u=c&&s>=mA;!c||u?(u&&e.activeFormattingElements.removeEntry(c),e.openElements.remove(a)):(a=AA(e,c),n===t&&(e.activeFormattingElements.bookmark=c),e.treeAdapter.detachNode(n),e.treeAdapter.appendChild(a,n),n=a)}return n}function AA(e,t){const r=e.treeAdapter.getNamespaceURI(t.element),n=e.treeAdapter.createElement(t.token.tagName,r,t.token.attrs);return e.openElements.replace(t.element,n),t.element=n,n}function IA(e,t,r){const n=e.treeAdapter.getTagName(t),i=ma(n);if(e._isElementCausesFosterParenting(i))e._fosterParentElement(r);else{const s=e.treeAdapter.getNamespaceURI(t);i===o.TEMPLATE&&s===J.HTML&&(t=e.treeAdapter.getTemplateContent(t)),e.treeAdapter.appendChild(t,r)}}function bA(e,t,r){const n=e.treeAdapter.getNamespaceURI(r.element),{token:i}=r,s=e.treeAdapter.createElement(i.tagName,n,i.attrs);e._adoptNodes(t,s),e.treeAdapter.appendChild(t,s),e.activeFormattingElements.insertElementAfterBookmark(s,i),e.activeFormattingElements.removeEntry(r),e.openElements.remove(r.element),e.openElements.insertAfter(t,s,i.tagID)}function yc(e,t){for(let r=0;r<hA;r++){const n=pA(e,t);if(!n)break;const i=TA(e,n);if(!i)break;e.activeFormattingElements.bookmark=n;const s=_A(e,i,n.element),a=e.openElements.getCommonAncestor(n.element);e.treeAdapter.detachNode(s),a&&IA(e,a,s),bA(e,i,n)}}function To(e,t){e._appendCommentNode(t,e.openElements.currentTmplContentOrNode)}function yA(e,t){e._appendCommentNode(t,e.openElements.items[0])}function NA(e,t){e._appendCommentNode(t,e.document)}function Nc(e,t){if(e.stopped=!0,t.location){const r=e.fragmentContext?0:2;for(let n=e.openElements.stackTop;n>=r;n--)e._setEndLocation(e.openElements.items[n],t);if(!e.fragmentContext&&e.openElements.stackTop>=0){const n=e.openElements.items[0],i=e.treeAdapter.getNodeSourceCodeLocation(n);if(i&&!i.endTag&&(e._setEndLocation(n,t),e.openElements.stackTop>=1)){const s=e.openElements.items[1],a=e.treeAdapter.getNodeSourceCodeLocation(s);a&&!a.endTag&&e._setEndLocation(s,t)}}}}function wA(e,t){e._setDocumentType(t);const r=t.forceQuirks?gt.QUIRKS:eA(t);J_(t)||e._err(t,G.nonConformingDoctype),e.treeAdapter.setDocumentMode(e.document,r),e.insertionMode=A.BEFORE_HTML}function _n(e,t){e._err(t,G.missingDoctype,!0),e.treeAdapter.setDocumentMode(e.document,gt.QUIRKS),e.insertionMode=A.BEFORE_HTML,e._processToken(t)}function DA(e,t){t.tagID===o.HTML?(e._insertElement(t,J.HTML),e.insertionMode=A.BEFORE_HEAD):Pn(e,t)}function SA(e,t){const r=t.tagID;(r===o.HTML||r===o.HEAD||r===o.BODY||r===o.BR)&&Pn(e,t)}function Pn(e,t){e._insertFakeRootElement(),e.insertionMode=A.BEFORE_HEAD,e._processToken(t)}function OA(e,t){switch(t.tagID){case o.HTML:{et(e,t);break}case o.HEAD:{e._insertElement(t,J.HTML),e.headElement=e.openElements.current,e.insertionMode=A.IN_HEAD;break}default:vn(e,t)}}function MA(e,t){const r=t.tagID;r===o.HEAD||r===o.BODY||r===o.HTML||r===o.BR?vn(e,t):e._err(t,G.endTagWithoutMatchingOpenElement)}function vn(e,t){e._insertFakeElement(k.HEAD,o.HEAD),e.headElement=e.openElements.current,e.insertionMode=A.IN_HEAD,e._processToken(t)}function Ot(e,t){switch(t.tagID){case o.HTML:{et(e,t);break}case o.BASE:case o.BASEFONT:case o.BGSOUND:case o.LINK:case o.META:{e._appendElement(t,J.HTML),t.ackSelfClosing=!0;break}case o.TITLE:{e._switchToTextParsing(t,ct.RCDATA);break}case o.NOSCRIPT:{e.options.scriptingEnabled?e._switchToTextParsing(t,ct.RAWTEXT):(e._insertElement(t,J.HTML),e.insertionMode=A.IN_HEAD_NO_SCRIPT);break}case o.NOFRAMES:case o.STYLE:{e._switchToTextParsing(t,ct.RAWTEXT);break}case o.SCRIPT:{e._switchToTextParsing(t,ct.SCRIPT_DATA);break}case o.TEMPLATE:{e._insertTemplate(t),e.activeFormattingElements.insertMarker(),e.framesetOk=!1,e.insertionMode=A.IN_TEMPLATE,e.tmplInsertionModeStack.unshift(A.IN_TEMPLATE);break}case o.HEAD:{e._err(t,G.misplacedStartTagForHeadElement);break}default:kn(e,t)}}function CA(e,t){switch(t.tagID){case o.HEAD:{e.openElements.pop(),e.insertionMode=A.AFTER_HEAD;break}case o.BODY:case o.BR:case o.HTML:{kn(e,t);break}case o.TEMPLATE:{Cr(e,t);break}default:e._err(t,G.endTagWithoutMatchingOpenElement)}}function Cr(e,t){e.openElements.tmplCount>0?(e.openElements.generateImpliedEndTagsThoroughly(),e.openElements.currentTagId!==o.TEMPLATE&&e._err(t,G.closingOfElementWithOpenChildElements),e.openElements.popUntilTagNamePopped(o.TEMPLATE),e.activeFormattingElements.clearToLastMarker(),e.tmplInsertionModeStack.shift(),e._resetInsertionMode()):e._err(t,G.endTagWithoutMatchingOpenElement)}function kn(e,t){e.openElements.pop(),e.insertionMode=A.AFTER_HEAD,e._processToken(t)}function RA(e,t){switch(t.tagID){case o.HTML:{et(e,t);break}case o.BASEFONT:case o.BGSOUND:case o.HEAD:case o.LINK:case o.META:case o.NOFRAMES:case o.STYLE:{Ot(e,t);break}case o.NOSCRIPT:{e._err(t,G.nestedNoscriptInHead);break}default:xn(e,t)}}function LA(e,t){switch(t.tagID){case o.NOSCRIPT:{e.openElements.pop(),e.insertionMode=A.IN_HEAD;break}case o.BR:{xn(e,t);break}default:e._err(t,G.endTagWithoutMatchingOpenElement)}}function xn(e,t){const r=t.type===Ce.EOF?G.openElementsLeftAfterEof:G.disallowedContentInNoscriptInHead;e._err(t,r),e.openElements.pop(),e.insertionMode=A.IN_HEAD,e._processToken(t)}function PA(e,t){switch(t.tagID){case o.HTML:{et(e,t);break}case o.BODY:{e._insertElement(t,J.HTML),e.framesetOk=!1,e.insertionMode=A.IN_BODY;break}case o.FRAMESET:{e._insertElement(t,J.HTML),e.insertionMode=A.IN_FRAMESET;break}case o.BASE:case o.BASEFONT:case o.BGSOUND:case o.LINK:case o.META:case o.NOFRAMES:case o.SCRIPT:case o.STYLE:case o.TEMPLATE:case o.TITLE:{e._err(t,G.abandonedHeadElementChild),e.openElements.push(e.headElement,o.HEAD),Ot(e,t),e.openElements.remove(e.headElement);break}case o.HEAD:{e._err(t,G.misplacedStartTagForHeadElement);break}default:Un(e,t)}}function vA(e,t){switch(t.tagID){case o.BODY:case o.HTML:case o.BR:{Un(e,t);break}case o.TEMPLATE:{Cr(e,t);break}default:e._err(t,G.endTagWithoutMatchingOpenElement)}}function Un(e,t){e._insertFakeElement(k.BODY,o.BODY),e.insertionMode=A.IN_BODY,Ea(e,t)}function Ea(e,t){switch(t.type){case Ce.CHARACTER:{Qf(e,t);break}case Ce.WHITESPACE_CHARACTER:{Yf(e,t);break}case Ce.COMMENT:{To(e,t);break}case Ce.START_TAG:{et(e,t);break}case Ce.END_TAG:{ga(e,t);break}case Ce.EOF:{Kf(e,t);break}}}function Yf(e,t){e._reconstructActiveFormattingElements(),e._insertCharacters(t)}function Qf(e,t){e._reconstructActiveFormattingElements(),e._insertCharacters(t),e.framesetOk=!1}function kA(e,t){e.openElements.tmplCount===0&&e.treeAdapter.adoptAttributes(e.openElements.items[0],t.attrs)}function xA(e,t){const r=e.openElements.tryPeekProperlyNestedBodyElement();r&&e.openElements.tmplCount===0&&(e.framesetOk=!1,e.treeAdapter.adoptAttributes(r,t.attrs))}function UA(e,t){const r=e.openElements.tryPeekProperlyNestedBodyElement();e.framesetOk&&r&&(e.treeAdapter.detachNode(r),e.openElements.popAllUpToHtmlElement(),e._insertElement(t,J.HTML),e.insertionMode=A.IN_FRAMESET)}function BA(e,t){e.openElements.hasInButtonScope(o.P)&&e._closePElement(),e._insertElement(t,J.HTML)}function HA(e,t){e.openElements.hasInButtonScope(o.P)&&e._closePElement(),e.openElements.currentTagId!==void 0&&po.has(e.openElements.currentTagId)&&e.openElements.pop(),e._insertElement(t,J.HTML)}function FA(e,t){e.openElements.hasInButtonScope(o.P)&&e._closePElement(),e._insertElement(t,J.HTML),e.skipNextNewLine=!0,e.framesetOk=!1}function zA(e,t){const r=e.openElements.tmplCount>0;(!e.formElement||r)&&(e.openElements.hasInButtonScope(o.P)&&e._closePElement(),e._insertElement(t,J.HTML),r||(e.formElement=e.openElements.current))}function jA(e,t){e.framesetOk=!1;const r=t.tagID;for(let n=e.openElements.stackTop;n>=0;n--){const i=e.openElements.tagIDs[n];if(r===o.LI&&i===o.LI||(r===o.DD||r===o.DT)&&(i===o.DD||i===o.DT)){e.openElements.generateImpliedEndTagsWithExclusion(i),e.openElements.popUntilTagNamePopped(i);break}if(i!==o.ADDRESS&&i!==o.DIV&&i!==o.P&&e._isSpecialElement(e.openElements.items[n],i))break}e.openElements.hasInButtonScope(o.P)&&e._closePElement(),e._insertElement(t,J.HTML)}function VA(e,t){e.openElements.hasInButtonScope(o.P)&&e._closePElement(),e._insertElement(t,J.HTML),e.tokenizer.state=ct.PLAINTEXT}function GA(e,t){e.openElements.hasInScope(o.BUTTON)&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilTagNamePopped(o.BUTTON)),e._reconstructActiveFormattingElements(),e._insertElement(t,J.HTML),e.framesetOk=!1}function YA(e,t){const r=e.activeFormattingElements.getElementEntryInScopeWithTagName(k.A);r&&(yc(e,t),e.openElements.remove(r.element),e.activeFormattingElements.removeEntry(r)),e._reconstructActiveFormattingElements(),e._insertElement(t,J.HTML),e.activeFormattingElements.pushElement(e.openElements.current,t)}function QA(e,t){e._reconstructActiveFormattingElements(),e._insertElement(t,J.HTML),e.activeFormattingElements.pushElement(e.openElements.current,t)}function qA(e,t){e._reconstructActiveFormattingElements(),e.openElements.hasInScope(o.NOBR)&&(yc(e,t),e._reconstructActiveFormattingElements()),e._insertElement(t,J.HTML),e.activeFormattingElements.pushElement(e.openElements.current,t)}function WA(e,t){e._reconstructActiveFormattingElements(),e._insertElement(t,J.HTML),e.activeFormattingElements.insertMarker(),e.framesetOk=!1}function $A(e,t){e.treeAdapter.getDocumentMode(e.document)!==gt.QUIRKS&&e.openElements.hasInButtonScope(o.P)&&e._closePElement(),e._insertElement(t,J.HTML),e.framesetOk=!1,e.insertionMode=A.IN_TABLE}function qf(e,t){e._reconstructActiveFormattingElements(),e._appendElement(t,J.HTML),e.framesetOk=!1,t.ackSelfClosing=!0}function Wf(e){const t=xf(e,yr.TYPE);return t!=null&&t.toLowerCase()===fA}function KA(e,t){e._reconstructActiveFormattingElements(),e._appendElement(t,J.HTML),Wf(t)||(e.framesetOk=!1),t.ackSelfClosing=!0}function ZA(e,t){e._appendElement(t,J.HTML),t.ackSelfClosing=!0}function XA(e,t){e.openElements.hasInButtonScope(o.P)&&e._closePElement(),e._appendElement(t,J.HTML),e.framesetOk=!1,t.ackSelfClosing=!0}function JA(e,t){t.tagName=k.IMG,t.tagID=o.IMG,qf(e,t)}function eI(e,t){e._insertElement(t,J.HTML),e.skipNextNewLine=!0,e.tokenizer.state=ct.RCDATA,e.originalInsertionMode=e.insertionMode,e.framesetOk=!1,e.insertionMode=A.TEXT}function tI(e,t){e.openElements.hasInButtonScope(o.P)&&e._closePElement(),e._reconstructActiveFormattingElements(),e.framesetOk=!1,e._switchToTextParsing(t,ct.RAWTEXT)}function rI(e,t){e.framesetOk=!1,e._switchToTextParsing(t,ct.RAWTEXT)}function Wu(e,t){e._switchToTextParsing(t,ct.RAWTEXT)}function nI(e,t){e._reconstructActiveFormattingElements(),e._insertElement(t,J.HTML),e.framesetOk=!1,e.insertionMode=e.insertionMode===A.IN_TABLE||e.insertionMode===A.IN_CAPTION||e.insertionMode===A.IN_TABLE_BODY||e.insertionMode===A.IN_ROW||e.insertionMode===A.IN_CELL?A.IN_SELECT_IN_TABLE:A.IN_SELECT}function iI(e,t){e.openElements.currentTagId===o.OPTION&&e.openElements.pop(),e._reconstructActiveFormattingElements(),e._insertElement(t,J.HTML)}function sI(e,t){e.openElements.hasInScope(o.RUBY)&&e.openElements.generateImpliedEndTags(),e._insertElement(t,J.HTML)}function aI(e,t){e.openElements.hasInScope(o.RUBY)&&e.openElements.generateImpliedEndTagsWithExclusion(o.RTC),e._insertElement(t,J.HTML)}function oI(e,t){e._reconstructActiveFormattingElements(),jf(t),bc(t),t.selfClosing?e._appendElement(t,J.MATHML):e._insertElement(t,J.MATHML),t.ackSelfClosing=!0}function cI(e,t){e._reconstructActiveFormattingElements(),Vf(t),bc(t),t.selfClosing?e._appendElement(t,J.SVG):e._insertElement(t,J.SVG),t.ackSelfClosing=!0}function $u(e,t){e._reconstructActiveFormattingElements(),e._insertElement(t,J.HTML)}function et(e,t){switch(t.tagID){case o.I:case o.S:case o.B:case o.U:case o.EM:case o.TT:case o.BIG:case o.CODE:case o.FONT:case o.SMALL:case o.STRIKE:case o.STRONG:{QA(e,t);break}case o.A:{YA(e,t);break}case o.H1:case o.H2:case o.H3:case o.H4:case o.H5:case o.H6:{HA(e,t);break}case o.P:case o.DL:case o.OL:case o.UL:case o.DIV:case o.DIR:case o.NAV:case o.MAIN:case o.MENU:case o.ASIDE:case o.CENTER:case o.FIGURE:case o.FOOTER:case o.HEADER:case o.HGROUP:case o.DIALOG:case o.DETAILS:case o.ADDRESS:case o.ARTICLE:case o.SEARCH:case o.SECTION:case o.SUMMARY:case o.FIELDSET:case o.BLOCKQUOTE:case o.FIGCAPTION:{BA(e,t);break}case o.LI:case o.DD:case o.DT:{jA(e,t);break}case o.BR:case o.IMG:case o.WBR:case o.AREA:case o.EMBED:case o.KEYGEN:{qf(e,t);break}case o.HR:{XA(e,t);break}case o.RB:case o.RTC:{sI(e,t);break}case o.RT:case o.RP:{aI(e,t);break}case o.PRE:case o.LISTING:{FA(e,t);break}case o.XMP:{tI(e,t);break}case o.SVG:{cI(e,t);break}case o.HTML:{kA(e,t);break}case o.BASE:case o.LINK:case o.META:case o.STYLE:case o.TITLE:case o.SCRIPT:case o.BGSOUND:case o.BASEFONT:case o.TEMPLATE:{Ot(e,t);break}case o.BODY:{xA(e,t);break}case o.FORM:{zA(e,t);break}case o.NOBR:{qA(e,t);break}case o.MATH:{oI(e,t);break}case o.TABLE:{$A(e,t);break}case o.INPUT:{KA(e,t);break}case o.PARAM:case o.TRACK:case o.SOURCE:{ZA(e,t);break}case o.IMAGE:{JA(e,t);break}case o.BUTTON:{GA(e,t);break}case o.APPLET:case o.OBJECT:case o.MARQUEE:{WA(e,t);break}case o.IFRAME:{rI(e,t);break}case o.SELECT:{nI(e,t);break}case o.OPTION:case o.OPTGROUP:{iI(e,t);break}case o.NOEMBED:case o.NOFRAMES:{Wu(e,t);break}case o.FRAMESET:{UA(e,t);break}case o.TEXTAREA:{eI(e,t);break}case o.NOSCRIPT:{e.options.scriptingEnabled?Wu(e,t):$u(e,t);break}case o.PLAINTEXT:{VA(e,t);break}case o.COL:case o.TH:case o.TD:case o.TR:case o.HEAD:case o.FRAME:case o.TBODY:case o.TFOOT:case o.THEAD:case o.CAPTION:case o.COLGROUP:break;default:$u(e,t)}}function uI(e,t){if(e.openElements.hasInScope(o.BODY)&&(e.insertionMode=A.AFTER_BODY,e.options.sourceCodeLocationInfo)){const r=e.openElements.tryPeekProperlyNestedBodyElement();r&&e._setEndLocation(r,t)}}function dI(e,t){e.openElements.hasInScope(o.BODY)&&(e.insertionMode=A.AFTER_BODY,ih(e,t))}function lI(e,t){const r=t.tagID;e.openElements.hasInScope(r)&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilTagNamePopped(r))}function fI(e){const t=e.openElements.tmplCount>0,{formElement:r}=e;t||(e.formElement=null),(r||t)&&e.openElements.hasInScope(o.FORM)&&(e.openElements.generateImpliedEndTags(),t?e.openElements.popUntilTagNamePopped(o.FORM):r&&e.openElements.remove(r))}function hI(e){e.openElements.hasInButtonScope(o.P)||e._insertFakeElement(k.P,o.P),e._closePElement()}function mI(e){e.openElements.hasInListItemScope(o.LI)&&(e.openElements.generateImpliedEndTagsWithExclusion(o.LI),e.openElements.popUntilTagNamePopped(o.LI))}function EI(e,t){const r=t.tagID;e.openElements.hasInScope(r)&&(e.openElements.generateImpliedEndTagsWithExclusion(r),e.openElements.popUntilTagNamePopped(r))}function gI(e){e.openElements.hasNumberedHeaderInScope()&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilNumberedHeaderPopped())}function pI(e,t){const r=t.tagID;e.openElements.hasInScope(r)&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilTagNamePopped(r),e.activeFormattingElements.clearToLastMarker())}function TI(e){e._reconstructActiveFormattingElements(),e._insertFakeElement(k.BR,o.BR),e.openElements.pop(),e.framesetOk=!1}function $f(e,t){const r=t.tagName,n=t.tagID;for(let i=e.openElements.stackTop;i>0;i--){const s=e.openElements.items[i],a=e.openElements.tagIDs[i];if(n===a&&(n!==o.UNKNOWN||e.treeAdapter.getTagName(s)===r)){e.openElements.generateImpliedEndTagsWithExclusion(n),e.openElements.stackTop>=i&&e.openElements.shortenToLength(i);break}if(e._isSpecialElement(s,a))break}}function ga(e,t){switch(t.tagID){case o.A:case o.B:case o.I:case o.S:case o.U:case o.EM:case o.TT:case o.BIG:case o.CODE:case o.FONT:case o.NOBR:case o.SMALL:case o.STRIKE:case o.STRONG:{yc(e,t);break}case o.P:{hI(e);break}case o.DL:case o.UL:case o.OL:case o.DIR:case o.DIV:case o.NAV:case o.PRE:case o.MAIN:case o.MENU:case o.ASIDE:case o.BUTTON:case o.CENTER:case o.FIGURE:case o.FOOTER:case o.HEADER:case o.HGROUP:case o.DIALOG:case o.ADDRESS:case o.ARTICLE:case o.DETAILS:case o.SEARCH:case o.SECTION:case o.SUMMARY:case o.LISTING:case o.FIELDSET:case o.BLOCKQUOTE:case o.FIGCAPTION:{lI(e,t);break}case o.LI:{mI(e);break}case o.DD:case o.DT:{EI(e,t);break}case o.H1:case o.H2:case o.H3:case o.H4:case o.H5:case o.H6:{gI(e);break}case o.BR:{TI(e);break}case o.BODY:{uI(e,t);break}case o.HTML:{dI(e,t);break}case o.FORM:{fI(e);break}case o.APPLET:case o.OBJECT:case o.MARQUEE:{pI(e,t);break}case o.TEMPLATE:{Cr(e,t);break}default:$f(e,t)}}function Kf(e,t){e.tmplInsertionModeStack.length>0?nh(e,t):Nc(e,t)}function _I(e,t){var r;t.tagID===o.SCRIPT&&((r=e.scriptHandler)===null||r===void 0||r.call(e,e.openElements.current)),e.openElements.pop(),e.insertionMode=e.originalInsertionMode}function AI(e,t){e._err(t,G.eofInElementThatCanContainOnlyText),e.openElements.pop(),e.insertionMode=e.originalInsertionMode,e.onEof(t)}function Ua(e,t){if(e.openElements.currentTagId!==void 0&&Gf.has(e.openElements.currentTagId))switch(e.pendingCharacterTokens.length=0,e.hasNonWhitespacePendingCharacterToken=!1,e.originalInsertionMode=e.insertionMode,e.insertionMode=A.IN_TABLE_TEXT,t.type){case Ce.CHARACTER:{Xf(e,t);break}case Ce.WHITESPACE_CHARACTER:{Zf(e,t);break}}else gi(e,t)}function II(e,t){e.openElements.clearBackToTableContext(),e.activeFormattingElements.insertMarker(),e._insertElement(t,J.HTML),e.insertionMode=A.IN_CAPTION}function bI(e,t){e.openElements.clearBackToTableContext(),e._insertElement(t,J.HTML),e.insertionMode=A.IN_COLUMN_GROUP}function yI(e,t){e.openElements.clearBackToTableContext(),e._insertFakeElement(k.COLGROUP,o.COLGROUP),e.insertionMode=A.IN_COLUMN_GROUP,wc(e,t)}function NI(e,t){e.openElements.clearBackToTableContext(),e._insertElement(t,J.HTML),e.insertionMode=A.IN_TABLE_BODY}function wI(e,t){e.openElements.clearBackToTableContext(),e._insertFakeElement(k.TBODY,o.TBODY),e.insertionMode=A.IN_TABLE_BODY,pa(e,t)}function DI(e,t){e.openElements.hasInTableScope(o.TABLE)&&(e.openElements.popUntilTagNamePopped(o.TABLE),e._resetInsertionMode(),e._processStartTag(t))}function SI(e,t){Wf(t)?e._appendElement(t,J.HTML):gi(e,t),t.ackSelfClosing=!0}function OI(e,t){!e.formElement&&e.openElements.tmplCount===0&&(e._insertElement(t,J.HTML),e.formElement=e.openElements.current,e.openElements.pop())}function tn(e,t){switch(t.tagID){case o.TD:case o.TH:case o.TR:{wI(e,t);break}case o.STYLE:case o.SCRIPT:case o.TEMPLATE:{Ot(e,t);break}case o.COL:{yI(e,t);break}case o.FORM:{OI(e,t);break}case o.TABLE:{DI(e,t);break}case o.TBODY:case o.TFOOT:case o.THEAD:{NI(e,t);break}case o.INPUT:{SI(e,t);break}case o.CAPTION:{II(e,t);break}case o.COLGROUP:{bI(e,t);break}default:gi(e,t)}}function ii(e,t){switch(t.tagID){case o.TABLE:{e.openElements.hasInTableScope(o.TABLE)&&(e.openElements.popUntilTagNamePopped(o.TABLE),e._resetInsertionMode());break}case o.TEMPLATE:{Cr(e,t);break}case o.BODY:case o.CAPTION:case o.COL:case o.COLGROUP:case o.HTML:case o.TBODY:case o.TD:case o.TFOOT:case o.TH:case o.THEAD:case o.TR:break;default:gi(e,t)}}function gi(e,t){const r=e.fosterParentingEnabled;e.fosterParentingEnabled=!0,Ea(e,t),e.fosterParentingEnabled=r}function Zf(e,t){e.pendingCharacterTokens.push(t)}function Xf(e,t){e.pendingCharacterTokens.push(t),e.hasNonWhitespacePendingCharacterToken=!0}function An(e,t){let r=0;if(e.hasNonWhitespacePendingCharacterToken)for(;r<e.pendingCharacterTokens.length;r++)gi(e,e.pendingCharacterTokens[r]);else for(;r<e.pendingCharacterTokens.length;r++)e._insertCharacters(e.pendingCharacterTokens[r]);e.insertionMode=e.originalInsertionMode,e._processToken(t)}const Jf=new Set([o.CAPTION,o.COL,o.COLGROUP,o.TBODY,o.TD,o.TFOOT,o.TH,o.THEAD,o.TR]);function MI(e,t){const r=t.tagID;Jf.has(r)?e.openElements.hasInTableScope(o.CAPTION)&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilTagNamePopped(o.CAPTION),e.activeFormattingElements.clearToLastMarker(),e.insertionMode=A.IN_TABLE,tn(e,t)):et(e,t)}function CI(e,t){const r=t.tagID;switch(r){case o.CAPTION:case o.TABLE:{e.openElements.hasInTableScope(o.CAPTION)&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilTagNamePopped(o.CAPTION),e.activeFormattingElements.clearToLastMarker(),e.insertionMode=A.IN_TABLE,r===o.TABLE&&ii(e,t));break}case o.BODY:case o.COL:case o.COLGROUP:case o.HTML:case o.TBODY:case o.TD:case o.TFOOT:case o.TH:case o.THEAD:case o.TR:break;default:ga(e,t)}}function wc(e,t){switch(t.tagID){case o.HTML:{et(e,t);break}case o.COL:{e._appendElement(t,J.HTML),t.ackSelfClosing=!0;break}case o.TEMPLATE:{Ot(e,t);break}default:js(e,t)}}function RI(e,t){switch(t.tagID){case o.COLGROUP:{e.openElements.currentTagId===o.COLGROUP&&(e.openElements.pop(),e.insertionMode=A.IN_TABLE);break}case o.TEMPLATE:{Cr(e,t);break}case o.COL:break;default:js(e,t)}}function js(e,t){e.openElements.currentTagId===o.COLGROUP&&(e.openElements.pop(),e.insertionMode=A.IN_TABLE,e._processToken(t))}function pa(e,t){switch(t.tagID){case o.TR:{e.openElements.clearBackToTableBodyContext(),e._insertElement(t,J.HTML),e.insertionMode=A.IN_ROW;break}case o.TH:case o.TD:{e.openElements.clearBackToTableBodyContext(),e._insertFakeElement(k.TR,o.TR),e.insertionMode=A.IN_ROW,Ta(e,t);break}case o.CAPTION:case o.COL:case o.COLGROUP:case o.TBODY:case o.TFOOT:case o.THEAD:{e.openElements.hasTableBodyContextInTableScope()&&(e.openElements.clearBackToTableBodyContext(),e.openElements.pop(),e.insertionMode=A.IN_TABLE,tn(e,t));break}default:tn(e,t)}}function _o(e,t){const r=t.tagID;switch(t.tagID){case o.TBODY:case o.TFOOT:case o.THEAD:{e.openElements.hasInTableScope(r)&&(e.openElements.clearBackToTableBodyContext(),e.openElements.pop(),e.insertionMode=A.IN_TABLE);break}case o.TABLE:{e.openElements.hasTableBodyContextInTableScope()&&(e.openElements.clearBackToTableBodyContext(),e.openElements.pop(),e.insertionMode=A.IN_TABLE,ii(e,t));break}case o.BODY:case o.CAPTION:case o.COL:case o.COLGROUP:case o.HTML:case o.TD:case o.TH:case o.TR:break;default:ii(e,t)}}function Ta(e,t){switch(t.tagID){case o.TH:case o.TD:{e.openElements.clearBackToTableRowContext(),e._insertElement(t,J.HTML),e.insertionMode=A.IN_CELL,e.activeFormattingElements.insertMarker();break}case o.CAPTION:case o.COL:case o.COLGROUP:case o.TBODY:case o.TFOOT:case o.THEAD:case o.TR:{e.openElements.hasInTableScope(o.TR)&&(e.openElements.clearBackToTableRowContext(),e.openElements.pop(),e.insertionMode=A.IN_TABLE_BODY,pa(e,t));break}default:tn(e,t)}}function eh(e,t){switch(t.tagID){case o.TR:{e.openElements.hasInTableScope(o.TR)&&(e.openElements.clearBackToTableRowContext(),e.openElements.pop(),e.insertionMode=A.IN_TABLE_BODY);break}case o.TABLE:{e.openElements.hasInTableScope(o.TR)&&(e.openElements.clearBackToTableRowContext(),e.openElements.pop(),e.insertionMode=A.IN_TABLE_BODY,_o(e,t));break}case o.TBODY:case o.TFOOT:case o.THEAD:{(e.openElements.hasInTableScope(t.tagID)||e.openElements.hasInTableScope(o.TR))&&(e.openElements.clearBackToTableRowContext(),e.openElements.pop(),e.insertionMode=A.IN_TABLE_BODY,_o(e,t));break}case o.BODY:case o.CAPTION:case o.COL:case o.COLGROUP:case o.HTML:case o.TD:case o.TH:break;default:ii(e,t)}}function LI(e,t){const r=t.tagID;Jf.has(r)?(e.openElements.hasInTableScope(o.TD)||e.openElements.hasInTableScope(o.TH))&&(e._closeTableCell(),Ta(e,t)):et(e,t)}function PI(e,t){const r=t.tagID;switch(r){case o.TD:case o.TH:{e.openElements.hasInTableScope(r)&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilTagNamePopped(r),e.activeFormattingElements.clearToLastMarker(),e.insertionMode=A.IN_ROW);break}case o.TABLE:case o.TBODY:case o.TFOOT:case o.THEAD:case o.TR:{e.openElements.hasInTableScope(r)&&(e._closeTableCell(),eh(e,t));break}case o.BODY:case o.CAPTION:case o.COL:case o.COLGROUP:case o.HTML:break;default:ga(e,t)}}function th(e,t){switch(t.tagID){case o.HTML:{et(e,t);break}case o.OPTION:{e.openElements.currentTagId===o.OPTION&&e.openElements.pop(),e._insertElement(t,J.HTML);break}case o.OPTGROUP:{e.openElements.currentTagId===o.OPTION&&e.openElements.pop(),e.openElements.currentTagId===o.OPTGROUP&&e.openElements.pop(),e._insertElement(t,J.HTML);break}case o.HR:{e.openElements.currentTagId===o.OPTION&&e.openElements.pop(),e.openElements.currentTagId===o.OPTGROUP&&e.openElements.pop(),e._appendElement(t,J.HTML),t.ackSelfClosing=!0;break}case o.INPUT:case o.KEYGEN:case o.TEXTAREA:case o.SELECT:{e.openElements.hasInSelectScope(o.SELECT)&&(e.openElements.popUntilTagNamePopped(o.SELECT),e._resetInsertionMode(),t.tagID!==o.SELECT&&e._processStartTag(t));break}case o.SCRIPT:case o.TEMPLATE:{Ot(e,t);break}}}function rh(e,t){switch(t.tagID){case o.OPTGROUP:{e.openElements.stackTop>0&&e.openElements.currentTagId===o.OPTION&&e.openElements.tagIDs[e.openElements.stackTop-1]===o.OPTGROUP&&e.openElements.pop(),e.openElements.currentTagId===o.OPTGROUP&&e.openElements.pop();break}case o.OPTION:{e.openElements.currentTagId===o.OPTION&&e.openElements.pop();break}case o.SELECT:{e.openElements.hasInSelectScope(o.SELECT)&&(e.openElements.popUntilTagNamePopped(o.SELECT),e._resetInsertionMode());break}case o.TEMPLATE:{Cr(e,t);break}}}function vI(e,t){const r=t.tagID;r===o.CAPTION||r===o.TABLE||r===o.TBODY||r===o.TFOOT||r===o.THEAD||r===o.TR||r===o.TD||r===o.TH?(e.openElements.popUntilTagNamePopped(o.SELECT),e._resetInsertionMode(),e._processStartTag(t)):th(e,t)}function kI(e,t){const r=t.tagID;r===o.CAPTION||r===o.TABLE||r===o.TBODY||r===o.TFOOT||r===o.THEAD||r===o.TR||r===o.TD||r===o.TH?e.openElements.hasInTableScope(r)&&(e.openElements.popUntilTagNamePopped(o.SELECT),e._resetInsertionMode(),e.onEndTag(t)):rh(e,t)}function xI(e,t){switch(t.tagID){case o.BASE:case o.BASEFONT:case o.BGSOUND:case o.LINK:case o.META:case o.NOFRAMES:case o.SCRIPT:case o.STYLE:case o.TEMPLATE:case o.TITLE:{Ot(e,t);break}case o.CAPTION:case o.COLGROUP:case o.TBODY:case o.TFOOT:case o.THEAD:{e.tmplInsertionModeStack[0]=A.IN_TABLE,e.insertionMode=A.IN_TABLE,tn(e,t);break}case o.COL:{e.tmplInsertionModeStack[0]=A.IN_COLUMN_GROUP,e.insertionMode=A.IN_COLUMN_GROUP,wc(e,t);break}case o.TR:{e.tmplInsertionModeStack[0]=A.IN_TABLE_BODY,e.insertionMode=A.IN_TABLE_BODY,pa(e,t);break}case o.TD:case o.TH:{e.tmplInsertionModeStack[0]=A.IN_ROW,e.insertionMode=A.IN_ROW,Ta(e,t);break}default:e.tmplInsertionModeStack[0]=A.IN_BODY,e.insertionMode=A.IN_BODY,et(e,t)}}function UI(e,t){t.tagID===o.TEMPLATE&&Cr(e,t)}function nh(e,t){e.openElements.tmplCount>0?(e.openElements.popUntilTagNamePopped(o.TEMPLATE),e.activeFormattingElements.clearToLastMarker(),e.tmplInsertionModeStack.shift(),e._resetInsertionMode(),e.onEof(t)):Nc(e,t)}function BI(e,t){t.tagID===o.HTML?et(e,t):Vs(e,t)}function ih(e,t){var r;if(t.tagID===o.HTML){if(e.fragmentContext||(e.insertionMode=A.AFTER_AFTER_BODY),e.options.sourceCodeLocationInfo&&e.openElements.tagIDs[0]===o.HTML){e._setEndLocation(e.openElements.items[0],t);const n=e.openElements.items[1];n&&!(!((r=e.treeAdapter.getNodeSourceCodeLocation(n))===null||r===void 0)&&r.endTag)&&e._setEndLocation(n,t)}}else Vs(e,t)}function Vs(e,t){e.insertionMode=A.IN_BODY,Ea(e,t)}function HI(e,t){switch(t.tagID){case o.HTML:{et(e,t);break}case o.FRAMESET:{e._insertElement(t,J.HTML);break}case o.FRAME:{e._appendElement(t,J.HTML),t.ackSelfClosing=!0;break}case o.NOFRAMES:{Ot(e,t);break}}}function FI(e,t){t.tagID===o.FRAMESET&&!e.openElements.isRootHtmlElementCurrent()&&(e.openElements.pop(),!e.fragmentContext&&e.openElements.currentTagId!==o.FRAMESET&&(e.insertionMode=A.AFTER_FRAMESET))}function zI(e,t){switch(t.tagID){case o.HTML:{et(e,t);break}case o.NOFRAMES:{Ot(e,t);break}}}function jI(e,t){t.tagID===o.HTML&&(e.insertionMode=A.AFTER_AFTER_FRAMESET)}function VI(e,t){t.tagID===o.HTML?et(e,t):zi(e,t)}function zi(e,t){e.insertionMode=A.IN_BODY,Ea(e,t)}function GI(e,t){switch(t.tagID){case o.HTML:{et(e,t);break}case o.NOFRAMES:{Ot(e,t);break}}}function YI(e,t){t.chars=Be,e._insertCharacters(t)}function QI(e,t){e._insertCharacters(t),e.framesetOk=!1}function sh(e){for(;e.treeAdapter.getNamespaceURI(e.openElements.current)!==J.HTML&&e.openElements.currentTagId!==void 0&&!e._isIntegrationPoint(e.openElements.currentTagId,e.openElements.current);)e.openElements.pop()}function qI(e,t){if(oA(t))sh(e),e._startTagOutsideForeignContent(t);else{const r=e._getAdjustedCurrentElement(),n=e.treeAdapter.getNamespaceURI(r);n===J.MATHML?jf(t):n===J.SVG&&(cA(t),Vf(t)),bc(t),t.selfClosing?e._appendElement(t,n):e._insertElement(t,n),t.ackSelfClosing=!0}}function WI(e,t){if(t.tagID===o.P||t.tagID===o.BR){sh(e),e._endTagOutsideForeignContent(t);return}for(let r=e.openElements.stackTop;r>0;r--){const n=e.openElements.items[r];if(e.treeAdapter.getNamespaceURI(n)===J.HTML){e._endTagOutsideForeignContent(t);break}const i=e.treeAdapter.getTagName(n);if(i.toLowerCase()===t.tagName){t.tagName=i,e.openElements.shortenToLength(r);break}}}k.AREA,k.BASE,k.BASEFONT,k.BGSOUND,k.BR,k.COL,k.EMBED,k.FRAME,k.HR,k.IMG,k.INPUT,k.KEYGEN,k.LINK,k.META,k.PARAM,k.SOURCE,k.TRACK,k.WBR;function $I(e,t,r){typeof e=="string"&&(r=t,t=e,e=null);const n=gA.getFragmentParser(e,r);return n.tokenizer.write(t,!0),n.getFragment()}const Xt=e=>{if(!Se(e))throw Ne("帖子响应必须是对象");return e};function lt(e){if(typeof e!="string")throw Ne("帖子响应字符串字段无效");return e}function hr(e){if(typeof e!="number"||!Number.isFinite(e)||e<0)throw Ne("帖子响应数值字段无效");return e}function ji(e){if(typeof e!="boolean")throw Ne("帖子响应状态无效");return e}function KI(e,t){if(!Array.isArray(e))throw Ne("帖子响应列表无效");return e.map(t)}function ZI(e){const t=Xt(e),r=lt(t.revision);if(!/^(0|[1-9]\d*)$/.test(r))throw Ne("绑定版本无效");return{postId:lt(t.postId),revision:r}}function XI(e){const t=Xt(e);return{id:lt(t.id),name:lt(t.name),avatar:lt(t.avatar),isMe:ji(t.isMe)}}function JI(e){const t=Xt(e);return{url:lt(t.url),width:hr(t.width),height:hr(t.height)}}function eb(e){const t=Xt(e),r=Xt(t.stats),n=Xt(t.viewer);return{id:lt(Xt(t.binding).postId),title:lt(t.title),text:lt(t.text),author:XI(t.author),content:KI(t.content,i=>{const s=Xt(i);if(s.type==="text")return{type:"text",text:lt(s.text)};if(s.type==="image")return{type:"image",image:JI(s.image)};if(s.type==="link")return{type:"link",url:lt(s.url)};throw Ne("帖子内容类型无效")}),createdAt:hr(t.createdAt),updatedAt:hr(t.updatedAt),url:lt(t.url),canComment:ji(t.canComment),stats:{likes:hr(r.likes),comments:hr(r.comments),favorites:hr(r.favorites)},viewer:{liked:ji(n.liked),favorited:ji(n.favorited)}}}const tb=new Set(["address","article","aside","blockquote","div","dl","dt","dd","fieldset","figcaption","figure","footer","form","h1","h2","h3","h4","h5","h6","header","hr","li","main","nav","ol","p","pre","section","table","caption","td","th","tr","ul"]);function rb(e){const t=[];let r=!1,n=!1;const i=()=>t.length===0||t[t.length-1].endsWith(`
6
+ `),s=()=>{r&&!i()&&t.push(`
7
+ `),r&&(n=!1),r=!1};function a(c,u=!1){const d="tagName"in c?c.tagName:"";if(["script","style","video"].includes(d))return;if(d==="br"){s(),n=!1,t.push(`
8
+ `);return}const l=tb.has(d);if(l&&t.length>0&&(r=!0),u=u||d==="pre"||d==="textarea","value"in c){const h=c.value;if(!u&&/^[ \t\r\n\f]*$/.test(h)){if(r||i())return;n=!0;return}s(),n&&!t[t.length-1].endsWith(" ")&&t.push(" "),n=!1,t.push(h)}"childNodes"in c&&c.childNodes.forEach(h=>a(h,u)),l&&t.length>0&&(r=!0)}return a($I(lt(e))),t.join("")}function Bt(e){if(!Se(e))throw Ne("社区评论响应无效");return e}function Kt(e){const t=typeof e=="string"&&/^\d+$/.test(e)?Number(e):e;if(typeof t!="number"||!Number.isSafeInteger(t)||t<0)throw Ne("社区评论数值无效");return t}function Bn(e){if(e==null||e===""||e===0||e==="0")return"";if(typeof e!="string"&&!Number.isSafeInteger(e))throw Ne("社区评论 ID 无效");const t=String(e);if(!/^[1-9]\d{0,18}$/.test(t))throw Ne("社区评论 ID 无效");return t}function Ba(e){if(typeof e!="string")throw Ne("社区评论文本无效");return e}function Ao(e,t,r,n){const i=Bt(e),s=Bn(i.commentid);if(!s)throw Ne("社区评论缺少 ID");const a=i.user==null?{}:Bt(i.user),c=Bn(i.userid??a.userid),u=i.is_support==null?void 0:Kt(i.is_support);if(u!==void 0&&![0,1,2].includes(u))throw Ne("社区评论点赞状态无效");const d=i.imgs==null?void 0:(()=>{if(!Array.isArray(i.imgs))throw Ne("社区评论图片无效");return i.imgs.map(h=>{const f=Bt(h);return{url:Ba(f.url),width:Kt(f.width??0),height:Kt(f.height??0)}})})(),l=(d?.length??0)>0||Kt(i.has_imgs??0)>0;return{id:s,rootCommentId:t||s,replyToCommentId:Bn(i.replyid),author:{id:c,name:Ba(a.username??""),avatar:Ba(a.avatar??""),isMe:c===r},text:rb(i.text),hasImages:l,...d?.length||!l?{images:d??[]}:{},createdAt:Kt(i.create_at),likes:Kt(i.up??0),replies:Kt(i.child_num??0),...u!==void 0?{liked:u===1}:{},canDelete:c===r||n===r}}function nb(e,t,r,n,i,s){const a=Bt(t),c=a.comments??[];if(!Array.isArray(c))throw Ne("社区评论列表无效");const u=c.map(h=>{if(r)return Ao(h,r,n,i);const f=Bt(h).comment;if(!Array.isArray(f)||!f.length)throw Ne("社区评论楼层无效");return Ao(f[0],"",n,i)});if(r){if(typeof a.has_more!="boolean")throw Ne("社区回复分页无效");const h=Bn(a.lastval);if(a.has_more&&!h)throw Ne("社区回复缺少游标");return{items:u,cursor:a.has_more?h:"",hasMore:a.has_more}}const d=a.total_page??Bt(e).total_page,l=d==null?u.length>0:s<Kt(d);return{items:u,cursor:l?String(s+1):"",hasMore:l}}function ib(e,t,r,n,i,s){const a=Bt(t),c=a.current_comment??Bt(e).current_comment,u=[...c==null?[]:[c],...Array.isArray(a.comments)?a.comments:[]];for(const d of u){const l=Bt(d).comment;if(!Array.isArray(l))continue;const h=l.find(f=>Bn(Bt(f).commentid)===r);if(h)return Ao(h,n,i,s)}throw{code:"COMMENT_UNAVAILABLE",message:"评论不存在或不可访问"}}const ah=3e4;function sb(e){let t=!1,r=!0,n=!1,i=!1,s;const a=()=>t&&r&&!n,c=()=>{clearTimeout(s),s=void 0},u=()=>{c(),a()&&(s=setTimeout(d,ah*(1+(e.random??Math.random)()*.1)))};async function d(){if(c(),!(!a()||i)){i=!0;try{await e.refresh()}catch{}finally{i=!1,u()}}}return{setEnabled(l){n||t===l||(t=l,t?u():c())},setVisible(l){n||r===l||(r=l,r?d():c())},reset:d,invalidate(l){if(!(!t||n))try{e.emit(l)}catch{}},dispose(){n=!0,c()}}}function ab(e){const t=new Set;let r=0,n=!1,i,s,a=!1,c=new AbortController,u,d=!1,l,h=0,f=0,p,g,b,y;const N=D=>{if(n||e.operationContext.signal.aborted)throw ne("RUNTIME_DESTROYED","小程序已关闭");if(r!==D)throw ne("AUTHORIZATION_CONTEXT_CHANGED","账号或授权已变化")};function C(){if(d)throw ne("BINDING_CHANGED","关联帖子已更换,请重新打开小程序")}function I(D){throw Se(D)&&D.code==="BINDING_CHANGED"&&(U(),C()),D}function U(){if(!d){d=!0,l=void 0,b?.abort(),c.abort(),H.setEnabled(!1);try{e.emit({changed:["binding"]})}catch{}}}function Y(D){return C(),u&&(u.revision!==D.revision||u.postId!==D.postId)&&(U(),C()),u??=D,u}async function R(D,W){N(D),C();const $=await e.account.getCurrentUserId(W);if(N(D),C(),i!==void 0&&i!==$)throw F(),ne("AUTHORIZATION_CONTEXT_CHANGED","账号已变化,请重试");if(!$)throw ne("UNAUTHORIZED","请先登录小黑盒");if(a&&s!==$)throw ne("AUTHORIZATION_CONTEXT_CHANGED","账号已变化,请重试");i=$}async function P(D,W,$,m=r){const w=Re(Re(e.operationContext,c.signal),$);await R(m,w);const B=await W(w);await R(m,w);const K=await mi({network:e.network,operationContext:w,subject:"关联帖子",assertUsable:()=>{N(m),C()},...e.requestGate?{gate:{capability:"post",gate:e.requestGate}}:{},requestPolicyEnabled:e.requestPolicyEnabled},D,B);return await R(m,w),K}async function M(D,W,$){try{const m=await P(__,async B=>{if(!e.authorizationContext)throw ne("METHOD_FORBIDDEN","宿主不支持关联帖子授权上下文");const K=await e.authorizationContext.get(B);if(!K.token||K.expiresAt<=Date.now())throw ne("UNAUTHORIZED","小程序运行上下文已过期");return{runtime_auth_context_token:K.token,action:D,payload:JSON.stringify(W)}},$),w=Je(m,D,"关联帖子");if(!Se(w)||!Se(w.data))throw ne("INVALID_RESPONSE","关联帖子响应缺少数据");return w.data}catch(m){return I(m)}}function V(){if(g)return g;const D=r,W=f,$=M("get",{},e.operationContext.signal).then(m=>{if(N(D),W!==f)return g=void 0,V();Y(ZI(m.binding));const w=eb(m);if(m.commentsRevision!==void 0&&(typeof m.commentsRevision!="string"||!/^\d+$/.test(m.commentsRevision)))throw ne("INVALID_RESPONSE","评论版本无效");const B=[];if(l){const{stats:K,viewer:ce,...pe}=l,{stats:ue,viewer:Te,...we}=w;JSON.stringify(pe)!==JSON.stringify(we)&&B.push("content"),JSON.stringify([K,ce])!==JSON.stringify([ue,Te])&&B.push("stats")}return m.commentsRevision!==void 0&&p!==void 0&&p!==m.commentsRevision&&B.push("comments"),l=w,h=Date.now(),m.commentsRevision!==void 0&&(p=m.commentsRevision),B.length&&H.invalidate({changed:B}),w}).catch(m=>{if(r===D&&f===W&&Se(m)&&["POST_UNAVAILABLE","POST_NOT_BOUND","POST_TYPE_UNSUPPORTED"].includes(String(m.code))){const w=l!==void 0;l=void 0,w&&H.invalidate({changed:["content","stats"]})}throw m}).finally(()=>{g===$&&(g=void 0)});return g=$,$}function z(D){N(D),C(),f++,h=0}async function te(D,W){const $=r;try{await W()}catch(m){if(n||e.operationContext.signal.aborted||r!==$||m instanceof Error&&m.name==="AbortError")return;try{e.onBackgroundError?.(D,m)}catch{}}}function x(D,W){return z(D),H.invalidate({changed:["comments"]}),M("comments.changed",{bindingRevision:u.revision},W)}async function Q(D){const W=r;await R(W,Re(e.operationContext,D));const $=l&&Date.now()-h<ah?l:await be(V,D).catch(m=>{throw C(),m});return N(W),C(),$}async function j(D,W,$,m,w){const K=await P(D==="post.setLiked"?T_:p_,()=>({targetId:$,enabled:W.liked===!0||W.favorited===!0}),m,w);(!Se(K)||K.status!=="ok")&&Je(K,D,"帖子互动")}const H=sb({emit:e.emit,refresh:V});function F(){r++,l&&H.invalidate({changed:["content","stats"]}),l=void 0,h=0,p=void 0,g=void 0,b?.abort(),c.abort(),c=new AbortController,i=void 0,H.reset()}const v=Ei(e.account,D=>{s=D,a=!0,i!==void 0&&D!==i&&F()}),L=e.authorization.onEvent(F),q={};for(const D of[...Zs,...Gn])q[D]=async(W,$)=>{if(N(r),D==="post.watch"){if(W!==void 0)throw ne("INVALID_ARGUMENT","变化订阅无需参数");if(t.size>=32)throw ne("RATE_LIMITED_BY_RUNTIME","帖子订阅过多");const ue=r;if(C(),await Q($.signal),N(ue),C(),$.signal.aborted)return;if(t.size>=32)throw ne("RATE_LIMITED_BY_RUNTIME","帖子订阅过多");return new Promise((Te,we)=>{const Ae=()=>{$.signal.removeEventListener("abort",Ae),t.delete(Ae),H.setEnabled(t.size>0&&!d),Te()};t.add(Ae),$.signal.addEventListener("abort",Ae,{once:!0}),H.setEnabled(!0);try{$.postProgress({watching:!0})}catch(Ie){$.signal.removeEventListener("abort",Ae),t.delete(Ae),H.setEnabled(t.size>0&&!d),we(Ie)}})}if(Gn.includes(D)&&!$.trustedUserGesture)throw ne("USER_GESTURE_REQUIRED","请通过用户操作发起帖子互动");const w=ob(D,W);C();const B=r;if(D==="post.get")return JSON.parse(JSON.stringify(await Q($.signal)));let K;D==="post.comments.openEditor"&&(b?.abort(),b=K=new AbortController,y=$.requestId,$={...$,...Re($,K.signal)});const ce=await Q($.signal),pe=i;if(N(B),C(),D==="post.comments.delete"||D==="post.comments.setLiked"){const ue=await P(D==="post.comments.delete"?g_:E_,()=>({body:{comment_id:w.commentId,...D==="post.comments.setLiked"?{support_type:w.liked?1:2}:{}}}),$.signal,B);(!Se(ue)||ue.status!=="ok")&&Je(ue,D,"帖子评论"),te("post.comments.changed",()=>x(B,c.signal));return}if(D.startsWith("post.comments.")){const{cursor:ue,limit:Te}=w,we=$.signal;if(D==="post.comments.list"){const Ae=String(w.rootCommentId??""),Ie=Ae?1:Number(ue||1),ye=Ae?{root_comment_id:Ae,lastval:ue||"",limit:Te??20}:{link_id:ce.id,page:Ie,limit:Te??20,owner_only:0,hide_cy:1,sort_filter:0,index:2},ve=await P(Ae?m_:Bu,()=>ye,we,B);return nb(ve,Je(ve,D,"帖子评论"),Ae,pe,ce.author.id,Ie)}if(D==="post.comments.openEditor"){const Ae=e.presentation?.openPostCommentEditor;if(!Ae||!K)throw ne("METHOD_FORBIDDEN","当前宿主不支持评论编辑器");let Ie;if(w.replyToCommentId){const Pe=String(w.replyToCommentId),He=String(w.rootCommentId??Pe),Ve=await P(Bu,()=>({link_id:ce.id,root_comment_id:He,comment_id:Pe,page:1,limit:20,owner_only:0,hide_cy:1,sort_filter:0,index:2}),we,B);Ie=ib(Ve,Je(Ve,D,"帖子评论"),Pe,He,pe,ce.author.id)}const ye=Re(Re(e.operationContext,c.signal),K.signal),ve=Re(ye,we);await R(B,ve),await be(()=>Ae({postId:ce.id,...Ie?{reply:Ie}:{},lifetimeSignal:ye.signal,onSubmitted(){b!==K||ye.signal.aborted||r!==B||te("post.comments.changed",async()=>{await R(B,ye),!ye.signal.aborted&&await x(B,ye.signal)})}},ve),ve.signal),await R(B,ve);return}}await j(D,w,ce.id,$.signal,B),z(B),te("post.get",V)};return{handlers:q,setVisible:H.setVisible,dismissEditor(D){D===y&&(y=void 0,b?.abort())},dispose(){if(!n){n=!0;for(const D of[...t])D();r++,c.abort(),H.dispose(),v(),L()}}}}const Si={"post.get":[],"post.comments.list":["rootCommentId","cursor","limit"],"post.comments.openEditor":["replyToCommentId","rootCommentId"],"post.comments.delete":["commentId"],"post.comments.setLiked":["commentId","liked"],"post.setLiked":["liked"],"post.setFavorited":["favorited"]};function ob(e,t){if(Si[e].length===0&&t===void 0)return{};if(!Se(t)||Object.keys(t).some(r=>!Si[e].includes(r)))throw ne("INVALID_ARGUMENT","帖子操作参数无效");for(const r of["liked","favorited"])if(Si[e].includes(r)&&typeof t[r]!="boolean")throw ne("INVALID_ARGUMENT","请提供目标状态");for(const r of["rootCommentId","replyToCommentId","commentId"])if(t[r]!==void 0&&(typeof t[r]!="string"||!/^[1-9]\d{0,18}$/.test(t[r])))throw ne("INVALID_ARGUMENT","评论 ID 无效");if(Si[e].includes("commentId")&&t.commentId===void 0)throw ne("INVALID_ARGUMENT","缺少评论 ID");if(e==="post.comments.openEditor"&&t.rootCommentId!==void 0&&t.replyToCommentId===void 0)throw ne("INVALID_ARGUMENT","根评论 ID 需要同时指定回复目标");if(t.limit!==void 0&&(!Number.isInteger(t.limit)||Number(t.limit)<1||Number(t.limit)>50))throw ne("INVALID_ARGUMENT","分页数量须为 1–50");if(t.cursor!==void 0&&(typeof t.cursor!="string"||!/^(|[1-9]\d{0,18})$/.test(t.cursor)))throw ne("INVALID_ARGUMENT","评论游标无效");if(!t.rootCommentId&&t.cursor&&!Number.isSafeInteger(Number(t.cursor)))throw ne("INVALID_ARGUMENT","评论页码无效");return{...t}}const cb=new Set(["stdio","attachments","notifications"]),oh=new Set(["windows-x64","macos-arm64"]),ub=new Set(["unsigned","valid","invalid","unknown"]),db=/^[a-f0-9]{64}$/,lb=new Set(["exited","terminated","crashed","host-shutdown","permission-revoked","output-limit"]),fb=new Set(Rl),hb=new Set([...Rl,"PERMISSION_DENIED","USER_GESTURE_REQUIRED"]),ch=Object.freeze({COMPANION_UNSUPPORTED:"当前 Host 不支持 Companion",COMPANION_PREVIEW_UNSUPPORTED:"当前 Host 不支持预览 Companion",COMPANION_NOT_DECLARED:"当前版本未声明该 Companion",COMPANION_TARGET_UNSUPPORTED:"当前平台不支持该 Companion target",COMPANION_NOT_PREPARED:"Companion 尚未准备完成",COMPANION_PREPARATION_CANCELLED:"Companion 准备已取消",COMPANION_DOWNLOAD_FAILED:"Companion 下载失败",COMPANION_DESCRIPTOR_UNAVAILABLE:"Companion 授权或描述符暂不可用",COMPANION_ARCHIVE_INVALID:"Companion 归档不合法",COMPANION_INTEGRITY_FAILED:"Companion 完整性校验失败",COMPANION_ENTRYPOINT_INVALID:"Companion 入口不合法",COMPANION_USER_CANCELLED:"用户取消了 Companion 操作",COMPANION_ELEVATION_DENIED:"用户未授予 Companion 管理员权限",COMPANION_OS_BLOCKED:"操作系统安全策略阻止了 Companion",COMPANION_LAUNCH_FAILED:"Companion 启动失败",COMPANION_SESSION_VERSION_MISMATCH:"Companion Session 版本不匹配",COMPANION_SESSION_OWNERSHIP_LOST:"Companion Session 控制权已转移",COMPANION_SESSION_EXITED:"Companion Session 已退出",COMPANION_PIPE_CLOSED:"Companion 通信管道已关闭",COMPANION_OUTPUT_LIMIT:"Companion 输出超过限制",COMPANION_PROCESS_CRASHED:"Companion 进程异常退出",COMPANION_ATTACHMENT_NOT_FOUND:"Companion Attachment 不存在",COMPANION_NOTIFICATION_UNAVAILABLE:"Companion 通知不可用",COMPANION_TERMINATE_FAILED:"Companion 终止失败",PERMISSION_DENIED:"桌面辅助应用权限未启用或已撤销",USER_GESTURE_REQUIRED:"当前操作需要新的可信用户手势"});function mb(e){const t=async(n,i,s,a)=>{const c=Eb(n);try{vt(i.signal);const u=await s(c,{...e.operationContext,signal:i.signal});return vt(i.signal),u}catch(u){throw bo(u,a)}},r=async(n,i,s)=>{if(!s.trustedUserGesture)throw T("USER_GESTURE_REQUIRED","当前操作需要新的可信用户手势");if(!e.companionPresentation)throw T("COMPANION_UNSUPPORTED","Host 未提供 Companion 可信授权界面");const a={...e.operationContext,signal:s.signal},c=await e.companion.getInfo(i,a).then(d=>gb(d,i)).catch(d=>{throw bo(d)});vt(s.signal);const u=await e.companionPresentation.confirmCompanionOperation({action:n,companion:c,miniProgram:e.miniProgramPresentation,signal:s.signal});if(vt(s.signal),u.status!=="granted")throw T("COMPANION_USER_CANCELLED","用户取消了 Companion 操作")};return{[Xs]:(n,i)=>t(n,i,async(s,a)=>Io(await e.companion.getInfo(s,a),s)),[Js]:(n,i)=>t(n,i,async(s,a)=>Ku(await e.companion.getPreparationStatus(s,a))),[ea]:(n,i)=>t(n,i,async(s,a)=>{const c=Ku(await e.companion.getPreparationStatus(s,a));return vt(i.signal),c.state!=="ready"&&c.state!=="preparing"&&await r("prepare",s,i),vt(i.signal),Io(await e.companion.prepare(s,{...a,onProgress:u=>i.postProgress(dh(u))}),s)},"COMPANION_PREPARATION_CANCELLED"),[ta]:(n,i)=>t(n,i,(s,a)=>e.companion.cancelPreparation(s,a)),[ra]:(n,i)=>t(n,i,async(s,a)=>Zu(await e.companion.getActiveSession(s,a),s)),[na]:(n,i)=>t(n,i,async(s,a)=>{const c=Zu(await e.companion.getActiveSession(s,a),s);return vt(i.signal),c||(await r("launch",s,i),vt(i.signal),lh(await e.companion.launch(s,a),s))}),[ia]:(n,i)=>Hr(n,i,e,"write"),[sa]:(n,i)=>Hr(n,i,e,"closeStdin"),[aa]:(n,i)=>Hr(n,i,e,"terminate"),[oa]:(n,i)=>Hr(n,i,e,"ackOutput"),[ca]:async(n,i)=>{const s=await Hr(n,i,e,"openAttachment");return e.fileRegistry.registerFile(s,"companion-attachment","read")},[ua]:(n,i)=>Hr(n,i,e,"showNotification")}}function Eb(e){if(!le(e)||typeof e.alias!="string"||!C0.test(e.alias))throw T("INVALID_PARAMS","Companion alias 不合法");return e.alias}function vt(e){if(e.aborted)throw Object.assign(new Error("Companion 操作已取消"),{name:"AbortError"})}async function Hr(e,t,r,n){if(!le(e)||typeof e.sessionId!="string"||!e.sessionId||!Number.isSafeInteger(e.controllerGeneration)||Number(e.controllerGeneration)<0)throw T("INVALID_PARAMS","Companion Session controller 不合法");try{vt(t.signal);const i=await r.companion[n](pb(e,n),{...r.operationContext,signal:t.signal});return vt(t.signal),i}catch(i){throw bo(i)}}function Dt(){throw T("COMPANION_HOST_FAILED","Companion Host 返回了无效数据")}function uh(e){return!Array.isArray(e)||e.some(t=>!cb.has(t))?Dt():Object.freeze([...new Set(e)])}function Io(e,t){return!le(e)||typeof e.alias!="string"||typeof e.displayName!="string"||t!==void 0&&e.alias!==t||!oh.has(String(e.target))||!Number.isSafeInteger(e.archiveBytes)||Number(e.archiveBytes)<0||!ub.has(String(e.signatureStatus))||e.source!==void 0&&e.source!=="local-dev"&&e.source!=="preview"&&e.source!=="released"?Dt():Object.freeze({alias:e.alias,displayName:e.displayName,target:e.target,capabilities:uh(e.capabilities),archiveBytes:e.archiveBytes,signatureStatus:e.signatureStatus,...e.source===void 0?{}:{source:e.source}})}function gb(e,t){const r=Io(e,t);return!le(e)||e.sha256===void 0?r:typeof e.sha256!="string"||!db.test(e.sha256)?Dt():Object.freeze({...r,sha256:e.sha256})}function dh(e){return le(e)?e.phase==="downloading"&&Number.isSafeInteger(e.loaded)&&Number(e.loaded)>=0&&(e.total===void 0||Number.isSafeInteger(e.total)&&Number(e.total)>=Number(e.loaded))?Object.freeze({phase:"downloading",loaded:e.loaded,...e.total===void 0?{}:{total:e.total}}):(e.phase==="verifying"||e.phase==="extracting")&&Number.isSafeInteger(e.processed)&&Number.isSafeInteger(e.total)&&Number(e.processed)>=0&&Number(e.total)>=Number(e.processed)?Object.freeze({phase:e.phase,processed:e.processed,total:e.total}):Dt():Dt()}function Ku(e){return le(e)?e.state==="not-prepared"?Object.freeze({state:"not-prepared"}):e.state==="preparing"?Object.freeze({state:"preparing",progress:dh(e.progress)}):e.state==="ready"&&Number.isSafeInteger(e.preparedAt)&&Number(e.preparedAt)>=0?Object.freeze({state:"ready",preparedAt:e.preparedAt}):e.state==="failed"&&le(e.error)&&typeof e.error.code=="string"&&fb.has(e.error.code)&&typeof e.error.message=="string"&&typeof e.error.retryable=="boolean"?Object.freeze({state:"failed",error:Object.freeze({code:e.error.code,message:ch[e.error.code]??"Companion 操作失败",retryable:e.error.retryable})}):Dt():Dt()}function lh(e,t){return!le(e)||typeof e.id!="string"||!e.id||typeof e.alias!="string"||t!==void 0&&e.alias!==t||!oh.has(String(e.target))||e.state!=="running"||!Number.isSafeInteger(e.controllerGeneration)||Number(e.controllerGeneration)<0?Dt():Object.freeze({id:e.id,alias:e.alias,target:e.target,capabilities:uh(e.capabilities),state:"running",controllerGeneration:e.controllerGeneration})}function Zu(e,t){return e===void 0?void 0:lh(e,t)}function pb(e,t){const r=e,n={sessionId:r.sessionId,controllerGeneration:r.controllerGeneration};if(t==="write"){if(!Nl(r.data))throw T("INVALID_PARAMS","Companion write data 不合法");return{...n,data:new Uint8Array(r.data)}}if(t==="ackOutput"){if(r.stream!=="stdout"&&r.stream!=="stderr"||!Number.isSafeInteger(r.sequence)||Number(r.sequence)<0)throw T("INVALID_PARAMS","Companion output ack 不合法");return{...n,stream:r.stream,sequence:r.sequence}}if(t==="openAttachment"){if(typeof r.id!="string"||!r.id)throw T("INVALID_PARAMS","Companion Attachment ID 不合法");return{...n,id:r.id}}if(t==="showNotification"){if(!["completed","failed","stopped","attention"].includes(String(r.category)))throw T("INVALID_PARAMS","Companion notification category 不合法");return{...n,category:r.category}}return n}function Tb(e){return!le(e)||!lb.has(String(e.reason))?Dt():e.reason==="exited"?Number.isSafeInteger(e.exitCode)?Object.freeze({reason:"exited",exitCode:e.exitCode}):Dt():e.exitCode!==void 0&&!Number.isSafeInteger(e.exitCode)?Dt():Object.freeze({reason:e.reason,...e.exitCode===void 0?{}:{exitCode:e.exitCode}})}function _b(e){if(!le(e)||!le(e.payload)||typeof e.payload.sessionId!="string"||!e.payload.sessionId)return;const t=e.payload,r=t.sessionId;if(e.type==="companion.session.output")return!Number.isSafeInteger(t.controllerGeneration)||Number(t.controllerGeneration)<0||t.stream!=="stdout"&&t.stream!=="stderr"||!Number.isSafeInteger(t.sequence)||Number(t.sequence)<0||!Nl(t.data)?void 0:{type:e.type,payload:{sessionId:r,controllerGeneration:t.controllerGeneration,stream:t.stream,sequence:t.sequence,data:new Uint8Array(t.data)}};if(e.type==="companion.session.exit")try{return{type:e.type,payload:{sessionId:r,exit:Tb(t.exit)}}}catch{return}if(e.type==="companion.session.ownershipLost"&&Number.isSafeInteger(t.controllerGeneration)&&Number(t.controllerGeneration)>=0)return{type:e.type,payload:{sessionId:r,controllerGeneration:t.controllerGeneration}}}function bo(e,t){return le(e)&&typeof e.code=="string"&&hb.has(e.code)?T(e.code,ch[e.code]??"Companion 操作失败",e.code==="COMPANION_DESCRIPTOR_UNAVAILABLE"?{retryable:!0}:typeof e.retryable=="boolean"?{retryable:e.retryable}:void 0):t&&le(e)&&e.name==="AbortError"?T(t,"Companion 准备已取消"):T("COMPANION_HOST_FAILED","Companion Host 操作失败")}const Xu=5e3,Ju=1e4;function nt(e){throw{code:"INVALID_PARAMS",message:e}}function Dc(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function fh(e,t,r){const n=Object.keys(e).filter(i=>!t.includes(i));n.length&&nt(`${r} 不支持字段: ${n.join(", ")}`)}function Ab(e){if(e===void 0)return{intensity:"light",delay:0};if(!Dc(e))return nt("device.vibrate 参数必须是对象");fh(e,["intensity","delay"],"device.vibrate");const t=e.intensity??"light";if(t!=="light"&&t!=="medium"&&t!=="heavy")return nt("device.vibrate intensity 必须是 light、medium 或 heavy");const r=t,n=e.delay??0;return typeof n!="number"||!Number.isInteger(n)||n<0||n>Xu?nt(`device.vibrate delay 必须是 0-${Xu} 的整数毫秒`):{intensity:r,delay:n}}function Ib(e){return Dc(e)?(fh(e,["text"],"device.setClipboard"),typeof e.text!="string"||!e.text.trim()?nt("device.setClipboard text 必须是非空字符串"):e.text.length>Ju?nt(`device.setClipboard text 不能超过 ${Ju} 字符`):{text:e.text}):nt("device.setClipboard 参数必须是对象")}function bb(e){return typeof e=="string"?e.trim()?e:nt("device.executeProtocol 协议字符串不能为空"):Dc(e)?typeof e.protocol_type!="string"||!e.protocol_type.trim()?nt("device.executeProtocol 协议对象必须包含非空字符串 protocol_type"):(yo(e,new Set),e):nt("device.executeProtocol 参数必须是协议字符串或协议对象")}function yo(e,t){if(e===null)return;switch(typeof e){case"string":case"boolean":return;case"number":Number.isFinite(e)||nt("device.executeProtocol 协议对象不能包含非有限数字");return;case"undefined":nt("device.executeProtocol 协议对象不能包含 undefined");return;case"function":case"symbol":case"bigint":nt(`device.executeProtocol 协议对象只能包含 JSON 数据,不能包含 ${typeof e}`);return}const r=e;if(t.has(r)&&nt("device.executeProtocol 协议对象不能包含循环引用"),t.add(r),Array.isArray(r)){for(const i of r)yo(i,t);t.delete(r);return}const n=Object.getPrototypeOf(r);n!==Object.prototype&&n!==null&&nt("device.executeProtocol 协议对象只能包含普通 JSON 对象,不能包含类实例或特殊对象");for(const i of Object.values(r))yo(i,t);t.delete(r)}function yb(e){return{[Ss]:async(t,r)=>{const n=Re(e.operationContext,r.signal,r.requestId);Oe(n.signal),await be(()=>e.presentation.vibrate(Ab(t),n),n.signal)},[Os]:async(t,r)=>{const n=Re(e.operationContext,r.signal,r.requestId);Oe(n.signal),await be(()=>e.presentation.setClipboard(Ib(t),n),n.signal)},[Ms]:async(t,r)=>{const n=Re(e.operationContext,r.signal,r.requestId);Oe(n.signal);const i=bb(t);await be(()=>e.protocol.invoke(i,n),n.signal)}}}const ed=1e3,Nb=new Set(["FILE_NOT_FOUND","DIRECTORY_NOT_FOUND","FILE_TYPE_MISMATCH"]);function wb(e){const t=r=>Re(e.operationContext,r.signal);return{files:{[Es]:async(r,n)=>{Ha(n);const i=Fa(e.picker),s=Db(r),a=await dt(()=>i.pickFiles(s,t(n)));return e.registry.registerFiles(a,"external",s.mode,s.multiple?void 0:1)},[gs]:async(r,n)=>{Ha(n);const i=Fa(e.picker),s=Sb(r),a=await dt(()=>i.pickDirectory(s,t(n)));return e.registry.registerDirectory(a,"external",s.mode)},[ps]:async(r,n)=>{Ha(n);const i=Fa(e.picker),s=Ob(r).suggestedName,a=t(n);if(!i.saveFile)throw _t("files.saveFile");const c=await dt(()=>i.saveFile({suggestedName:s},a));return e.registry.registerFile(c,"external","readwrite")}},file:{[Wn]:async(r,n)=>{const i=mt(r,["recursive","exclusive"]),s=e.registry.resolveFile(i.target);Fr(s.mode),await dt(()=>s.create(td(i),t(n)))},[$n]:async(r,n)=>{const i=mt(r),s=e.registry.resolveFileEntry(i.target);if(e.registry.assertSandboxOrigin(s),Fr(s.handle.mode),!s.handle.remove)throw _t($n);await dt(()=>s.handle.remove(t(n)))},[Ts]:async(r,n)=>{const i=mt(r);return rd(async()=>{const s=await e.registry.resolveFile(i.target).stat(t(n));if(!le(s)||s.kind!=="file")throw id()})},[Kn]:async(r,n)=>{const i=mt(r),s=nd(await dt(()=>e.registry.resolveFile(i.target).read(t(n))));try{const a=new TextDecoder("utf-8",{fatal:!0}).decode(s);return a.charCodeAt(0)===65279?a.slice(1):a}catch{throw T("FILE_ENCODING_INVALID","文件不是合法 UTF-8 文本")}},[_s]:async(r,n)=>{const i=mt(r,["content"]);typeof i.content!="string"&&At("content 必须是字符串");const s=e.registry.resolveFile(i.target);Fr(s.mode),await dt(()=>s.write(new TextEncoder().encode(i.content),t(n)))},[Zn]:async(r,n)=>{const i=mt(r),s=await dt(()=>e.registry.resolveFile(i.target).read(t(n)));return nd(s)},[As]:async(r,n)=>{const i=mt(r,["content"]),s=e.registry.resolveFile(i.target);Fr(s.mode),await dt(()=>s.write(Cb(i.content),t(n)))},[Xn]:async(r,n)=>{const i=mt(r),s=await dt(()=>e.registry.resolveFile(i.target).stat(t(n)));return Rb(s)}},directory:{[Is]:async(r,n)=>{const i=mt(r,["recursive","exclusive"]),s=e.registry.resolveDirectory(i.target);Fr(s.mode),await dt(()=>s.create(td(i),t(n)))},[Jn]:async(r,n)=>{const i=mt(r,["recursive"]);if(le(i.target)&&i.target.relativePath===".")throw T("FILE_ACCESS_DENIED","不能删除根目录");const s=e.registry.resolveDirectoryEntry(i.target);if(e.registry.assertSandboxOrigin(s),Fr(s.handle.mode),!s.handle.remove)throw _t(Jn);await dt(()=>s.handle.remove({recursive:i.recursive===void 0?!1:Gs(i.recursive,"recursive")},t(n)))},[bs]:async(r,n)=>{const i=mt(r);return rd(async()=>{const s=await e.registry.resolveDirectory(i.target).stat(t(n));if(!le(s)||s.kind!=="directory")throw id()})},[ys]:async(r,n)=>{const i=mt(r,["limit"]),s=Mb(i.limit),a=e.registry.resolveDirectoryEntry(i.target),c=await dt(()=>a.handle.list({limit:s},t(n)));return e.registry.describeListedEntries(a,c,s)}}}}function Db(e){if(e===void 0)return{mode:"read",multiple:!1};le(e)||At("pickFiles 参数必须是对象"),_a(e,["mode","accept","multiple"]);const t=hh(e.mode,"read"),r=e.multiple===void 0?!1:Gs(e.multiple,"multiple");let n;return e.accept!==void 0&&((!Array.isArray(e.accept)||e.accept.some(i=>typeof i!="string"||!/^\.[a-z0-9][a-z0-9._-]*$/i.test(i)))&&At("accept 必须是规范扩展名数组"),n=[...new Set(e.accept)]),{mode:t,multiple:r,...n===void 0?{}:{accept:n}}}function Sb(e){return e===void 0?{mode:"read"}:(le(e)||At("pickDirectory 参数必须是对象"),_a(e,["mode"]),{mode:hh(e.mode,"read")})}function Ob(e){return le(e)||At("saveFile 参数必须是对象"),_a(e,["suggestedName"]),{suggestedName:di(e.suggestedName,"suggestedName")}}function mt(e,t=[]){return(!le(e)||!Object.prototype.hasOwnProperty.call(e,"target"))&&At("文件操作参数必须包含 target"),_a(e,["target",...t]),e}function td(e){return{recursive:e.recursive===void 0?!1:Gs(e.recursive,"recursive"),exclusive:e.exclusive===void 0?!1:Gs(e.exclusive,"exclusive")}}function hh(e,t){return e===void 0?t:(e!=="read"&&e!=="readwrite"&&At("mode 必须是 read 或 readwrite"),e)}function Gs(e,t){return typeof e!="boolean"&&At(`${t} 必须是布尔值`),e}function Mb(e){if(e===void 0)return ed;if((!Number.isSafeInteger(e)||e<=0)&&At("limit 必须是正整数"),e>ed)throw T("DIRECTORY_LIST_LIMIT_EXCEEDED","目录项限制超过 Host 上限");return e}function _a(e,t){const r=Object.keys(e).filter(n=>!t.includes(n));r.length&&At(`不支持字段: ${r.join(", ")}`)}function Fr(e){if(e!=="readwrite")throw T("FILE_ACCESS_DENIED","当前文件授权只允许读取")}function Ha(e){if(!e.trustedUserGesture)throw T("USER_GESTURE_REQUIRED","当前操作需要可信用户手势")}function Fa(e){if(!e)throw _t("files.external");return e}async function rd(e){try{return await e(),!0}catch(t){if(Nb.has(mc(t)??""))return!1;throw Jr(t)}}async function dt(e){try{return await e()}catch(t){throw Jr(t)}}function Cb(e){return e instanceof Uint8Array||At("content 必须是 Uint8Array"),typeof SharedArrayBuffer<"u"&&e.buffer instanceof SharedArrayBuffer&&At("不支持 SharedArrayBuffer-backed Uint8Array"),new Uint8Array(e)}function nd(e){if(!(e instanceof Uint8Array))throw T("FILE_IO_FAILED","Host 返回了无效字节数据");return new Uint8Array(e)}function id(){return T("FILE_TYPE_MISMATCH","文件句柄类型不匹配")}function Rb(e){if(!le(e)||e.kind!=="file"||!Lb(e.size))throw T("FILE_IO_FAILED","Host 返回了无效 FileStat");for(const t of["modifiedAt","createdAt"])if(e[t]!==void 0&&!Pb(e[t]))throw T("FILE_IO_FAILED",`Host 返回了无效 ${t}`);return{kind:"file",size:e.size,...e.modifiedAt===void 0?{}:{modifiedAt:e.modifiedAt},...e.createdAt===void 0?{}:{createdAt:e.createdAt}}}function Lb(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function Pb(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0}function At(e){throw T("INVALID_PARAMS",e)}const sd=16*1024,ad=200;function vb(e){const t=Xl(e.runtimePermissions);function r(n,i){e.capabilities&&Yl(i,e.capabilities);const s=t({kind:"all",permissions:["filesystem"]},i);if(!s.allowed)throw T(s.code,s.message);const a=Re(e.operationContext,n);return No(a),a}return{async list(n,i={}){const s=r(i.signal,"directory.list"),a=e.registry.resolveDirectoryEntry({kind:"directory",root:{kind:"sandbox"},relativePath:n}),c=await od(()=>a.handle.list({limit:ad},s),s);return e.registry.describeListedEntries(a,c,ad).map(({name:u,kind:d})=>({name:u,kind:d}))},async read(n,i={}){const s=i.maxBytes??sd;if(!Number.isSafeInteger(s)||s<1||s>sd)throw T("INVALID_PARAMS","诊断读取最多允许 16384 bytes");const a=r(i.signal,"file.readBytes"),c=e.registry.resolveFile({kind:"file",root:{kind:"sandbox"},relativePath:n});if(!c.readPrefix)throw T("DIAGNOSTICS_UNSUPPORTED","当前 Host 不支持有界文件诊断读取");const u=await od(()=>c.readPrefix({maxBytes:s},a),a);if(!u||!(u.bytes instanceof Uint8Array)||u.bytes.byteLength>s||typeof u.truncated!="boolean")throw T("FILE_IO_FAILED","Host 返回了无效的有界读取结果");return{bytes:new Uint8Array(u.bytes),truncated:u.truncated}}}}function No(e){if(e.signal.aborted)throw T("FILE_ACCESS_REVOKED","诊断文件查询已取消或实例已结束")}async function od(e,t){let r;try{const n=await Promise.race([e(),new Promise((i,s)=>{r=()=>s(T("FILE_ACCESS_REVOKED","诊断文件查询已取消或实例已结束")),t.signal.addEventListener("abort",r,{once:!0}),t.signal.aborted&&r()})]);return No(t),n}catch(n){throw t.signal.aborted&&No(t),Jr(n)}finally{r&&t.signal.removeEventListener("abort",r)}}const kb=new Set(["METHOD_FORBIDDEN","MEDIA_PICKER_CANCELLED","MEDIA_SYSTEM_PERMISSION_DENIED","MEDIA_PREPARE_FAILED","MEDIA_PREVIEW_UNAVAILABLE","REQUEST_UNSUPPORTED","USER_GESTURE_REQUIRED"]),za={METHOD_FORBIDDEN:"当前 Host 未开放媒体选择能力",MEDIA_PICKER_CANCELLED:"用户取消了媒体选择",MEDIA_SYSTEM_PERMISSION_DENIED:"系统未授予相机或相册权限",MEDIA_PREPARE_FAILED:"媒体准备失败,未保留部分结果",MEDIA_PREVIEW_UNAVAILABLE:"当前 Host 无法提供受控媒体预览",REQUEST_UNSUPPORTED:"当前 Host 不支持该媒体请求形态",USER_GESTURE_REQUIRED:"当前操作需要可信用户手势"};function xb(e){if(e instanceof Qe)return T("REQUEST_UNSUPPORTED",za.REQUEST_UNSUPPORTED);const t=mh(e);return t!==void 0&&kb.has(t)?T(t,za[t]??"媒体操作失败"):T("MEDIA_PREPARE_FAILED",za.MEDIA_PREPARE_FAILED)}function mh(e){try{if(!le(e))return;const t=Object.getOwnPropertyDescriptor(e,"code");return t&&"value"in t&&typeof t.value=="string"?t.value:void 0}catch{return}}const Ub=["source","mediaType","maxCount"],Vi=Object.freeze({source:"album",mediaType:"all",maxCount:1});function Bb(e){if(e===void 0)return Vi;if(!u0(e))throw T("INVALID_PARAMS",Fb(e));return Hb(e)}function Hb(e){return Object.freeze({source:e.source??Vi.source,mediaType:e.mediaType??Vi.mediaType,maxCount:e.maxCount??Vi.maxCount})}function Fb(e){if(!le(e))return"media.pick 参数必须是对象";const t=Object.keys(e).filter(r=>!Ub.includes(r));if(t.length>0)return`media.pick 不支持字段: ${t.join(", ")}`;if(e.source!==void 0&&e.source!=="album"&&e.source!=="camera")return"source 必须是 album 或 camera";if(e.mediaType!==void 0&&e.mediaType!=="image"&&e.mediaType!=="video"&&e.mediaType!=="all")return"mediaType 必须是 image、video 或 all";if(e.maxCount!==void 0){if(typeof e.maxCount!="number"||!Number.isSafeInteger(e.maxCount))return"maxCount 必须是安全整数";if(e.source==="camera"&&e.maxCount!==1)return"相机只支持 maxCount 为 1 或省略,不能静默收窄"}return"media.pick 参数不合法"}const zb=new Set(["METHOD_FORBIDDEN","FILE_QUOTA_EXCEEDED","FILE_ACCESS_REVOKED","FILE_ACCESS_DENIED"]),jb={kind:"file",name:"media-probe",mode:"read",ref:{kind:"file",handleId:"media-probe"}};class Vb{constructor(t,r,n){this.registry=t,this.media=r,this.operationContext=n}committed=new Set;disposed=!1;commit(t,r){const n=Gb(t,r);let i=[];try{i=this.registerBatch(n,r.maxCount);const s=n.map((a,c)=>Qb(a,i[c]));if(!d0(s))throw Ut("Host 返回的媒体结果未通过协议校验");for(const a of n)this.committed.add(a);return s}catch(s){throw this.registry.revokeFiles(i.map(qb).filter(a=>a!==void 0)),s}}releaseBatch(t,r){this.releaseItems(t,r)}dispose(){if(this.disposed)return;this.disposed=!0;const t=[...this.committed];this.committed.clear(),this.releaseItems(t,{...this.operationContext,lifecycle:"cleanup"})}registerBatch(t,r){try{return this.registry.registerFiles(t.map(n=>n.file),"external","read",r)}catch(n){const i=mh(n);throw i!==void 0&&zb.has(i)?n:Ut("Host 返回的媒体文件资源无法登记为只读句柄")}}releaseItems(t,r){if(t.length!==0)try{const n=this.media.release(t,r);Promise.resolve(n).catch(()=>{})}catch{}}}function cd(e,t){if(e.signal.aborted)throw T("RUNTIME_DESTROYED","小程序 Runtime 已终止");if(t.aborted)throw T("REQUEST_CANCELLED","media.pick 已取消")}function Gb(e,t){if(!Array.isArray(e))throw Ut("Host 返回了无效媒体选择结果");const r=e.length;if(r===0)throw Ut("Host 未返回任何媒体项;用户取消不得作为空数组成功");if(r>t.maxCount)throw Ut("Host 返回的媒体项超过本次 maxCount");if(t.source==="camera"&&r!==1)throw Ut("相机必须恰好返回 1 项");for(let n=0;n<r;n+=1){if(!Object.prototype.hasOwnProperty.call(e,n))throw Ut("Host 返回了稀疏媒体结果");Yb(e[n],n)}return e}function Yb(e,t){if(!le(e))throw Ut(`第 ${t+1} 项不是对象`);if(!yl({...e,file:jb}))throw Ut(`第 ${t+1} 项不符合 media.pick 媒体项契约`);if(!le(e.file))throw Ut(`第 ${t+1} 项缺少文件句柄`)}function Qb(e,t){const r={mimeType:e.mimeType,size:e.size,width:e.width,height:e.height,previewUrl:e.previewUrl,file:t};return e.type==="video"?{...r,type:"video",durationMs:e.durationMs}:{...r,type:"image"}}function qb(e){return"handleId"in e.ref?e.ref.handleId:void 0}function Ut(e){return T("MEDIA_PREPARE_FAILED",e)}function Wb(e){const t=e.media?new Vb(e.registry,e.media,e.operationContext):void 0;return{handlers:{[ei]:async(n,i)=>{const s=Bb(n);Kb(i);const a=e.media,c=t;if(!a||typeof a.pick!="function"||!c)throw _t(ei);const u=Re(e.operationContext,i.signal);cd(e.operationContext,i.signal);const d=await $b(a,s,u,e.operationContext,i.signal);cd(e.operationContext,i.signal);try{return c.commit(d,s)}catch(l){throw c.releaseBatch(d,u),l}}},dispose(){t?.dispose()}}}async function $b(e,t,r,n,i){try{return await be(()=>e.pick(t,r),r.signal)}catch(s){throw n.signal.aborted?T("RUNTIME_DESTROYED","小程序 Runtime 已终止"):i.aborted?T("REQUEST_CANCELLED","media.pick 已取消"):xb(s)}}function Kb(e){if(!e.trustedUserGesture)throw T("USER_GESTURE_REQUIRED","当前操作需要可信用户手势")}const Oi=4294967296;function Zb(e){const t=new Xb;return t.write(e),t.finish()}class Xb{bytes=new Uint8Array(128);view=new DataView(this.bytes.buffer);offset=0;write(t){if(t===null)this.writeUint8(192);else if(typeof t=="boolean")this.writeUint8(t?195:194);else if(typeof t=="number")this.writeNumber(t);else if(typeof t=="string")this.writeString(t);else if(Array.isArray(t))this.writeArray(t);else if(typeof t=="object")this.writeMap(t);else throw new Error("unsupported share extra value")}finish(){return this.bytes.slice(0,this.offset)}writeNumber(t){if(!Number.isSafeInteger(t)){this.writeUint8(203),this.writeFloat64(t);return}if(t>=0){t<128?this.writeUint8(t):t<256?(this.writeUint8(204),this.writeUint8(t)):t<65536?(this.writeUint8(205),this.writeUint16(t)):t<Oi?(this.writeUint8(206),this.writeUint32(t)):(this.writeUint8(207),this.writeUint64(t));return}t>=-32?this.writeUint8(224|t+32):t>=-128?(this.writeUint8(208),this.writeInt8(t)):t>=-32768?(this.writeUint8(209),this.writeInt16(t)):t>=-2147483648?(this.writeUint8(210),this.writeInt32(t)):(this.writeUint8(211),this.writeInt64(t))}writeString(t){const r=Jb(t),n=r.byteLength;if(n<32)this.writeUint8(160+n);else if(n<256)this.writeUint8(217),this.writeUint8(n);else if(n<65536)this.writeUint8(218),this.writeUint16(n);else if(n<Oi)this.writeUint8(219),this.writeUint32(n);else throw new Error("share extra string is too long");this.writeBytes(r)}writeArray(t){const r=t.length;r<16?this.writeUint8(144+r):r<65536?(this.writeUint8(220),this.writeUint16(r)):(this.writeUint8(221),this.writeUint32(r));for(const n of t)this.write(n)}writeMap(t){const r=Object.keys(t),n=r.length;n<16?this.writeUint8(128+n):n<65536?(this.writeUint8(222),this.writeUint16(n)):(this.writeUint8(223),this.writeUint32(n));for(const i of r)this.writeString(i),this.write(t[i])}ensureCapacity(t){const r=this.offset+t;if(r<=this.bytes.byteLength)return;const n=new Uint8Array(Math.max(r,this.bytes.byteLength*2));n.set(this.bytes),this.bytes=n,this.view=new DataView(n.buffer)}writeBytes(t){this.ensureCapacity(t.byteLength),this.bytes.set(t,this.offset),this.offset+=t.byteLength}writeUint8(t){this.ensureCapacity(1),this.view.setUint8(this.offset,t),this.offset+=1}writeInt8(t){this.ensureCapacity(1),this.view.setInt8(this.offset,t),this.offset+=1}writeUint16(t){this.ensureCapacity(2),this.view.setUint16(this.offset,t),this.offset+=2}writeInt16(t){this.ensureCapacity(2),this.view.setInt16(this.offset,t),this.offset+=2}writeUint32(t){this.ensureCapacity(4),this.view.setUint32(this.offset,t),this.offset+=4}writeInt32(t){this.ensureCapacity(4),this.view.setInt32(this.offset,t),this.offset+=4}writeFloat64(t){this.ensureCapacity(8),this.view.setFloat64(this.offset,t),this.offset+=8}writeUint64(t){this.ensureCapacity(8),this.view.setUint32(this.offset,t/Oi),this.view.setUint32(this.offset+4,t),this.offset+=8}writeInt64(t){this.ensureCapacity(8),this.view.setUint32(this.offset,Math.floor(t/Oi)),this.view.setUint32(this.offset+4,t),this.offset+=8}}function Jb(e){const t=new Uint8Array(ey(e));let r=0,n=0;for(;r<e.length;){let i=e.charCodeAt(r++);if(i>=55296&&i<=56319&&r<e.length){const s=e.charCodeAt(r);s>=56320&&s<=57343&&(r+=1,i=((i&1023)<<10)+(s&1023)+65536)}i<128?t[n++]=i:i<2048?(t[n++]=i>>6&31|192,t[n++]=i&63|128):i<65536?(t[n++]=i>>12&15|224,t[n++]=i>>6&63|128,t[n++]=i&63|128):(t[n++]=i>>18&7|240,t[n++]=i>>12&63|128,t[n++]=i>>6&63|128,t[n++]=i&63|128)}return t}function ey(e){let t=0,r=0;for(;r<e.length;){let n=e.charCodeAt(r++);if(n<128)t+=1;else if(n<2048)t+=2;else{if(n>=55296&&n<=56319&&r<e.length){const i=e.charCodeAt(r);i>=56320&&i<=57343&&(r+=1,n=((n&1023)<<10)+(i&1023)+65536)}t+=n<65536?3:4}}return t}function Eh(e){wo(e);const t=Zb(e);if(t.byteLength>128)throw new Error("launch extra is too large");return btoa(String.fromCharCode(...t)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function wo(e,t=0,r=new WeakSet){if(t>8)throw new Error("extra nesting depth exceeded");if(e===null||typeof e=="string"||typeof e=="boolean")return;if(typeof e=="number"){if(Number.isFinite(e))return;throw new Error("extra number must be finite")}if(typeof e!="object")throw new Error("extra value must be JSON-compatible");if(r.has(e))throw new Error("extra value must not contain cycles");if(r.add(e),Array.isArray(e)){if(e.length>64)throw new Error("extra array is too large");for(const s of e)wo(s,t+1,r);r.delete(e);return}const n=Object.getPrototypeOf(e);if(n!==Object.prototype&&n!==null)throw new Error("extra object must be a plain object");const i=Object.entries(e);if(i.length>64)throw new Error("extra object has too many fields");for(const[s,a]of i){if(s==="__proto__")throw new Error("extra object key is not supported");wo(a,t+1,r)}r.delete(e)}const ty=["pc","console","mobile"],ry=["game","wiki"];function Ys(e){throw{code:"INVALID_PARAMS",message:e}}function ny(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function sr(e,t){return typeof e!="string"||!e.trim()?Ys(t):e.trim()}function ud(e,t,r){return typeof e!="string"||!t.includes(e)?Ys(r):e}function iy(e){const t={target:"game_detail",appId:sr(e.appId,"navigation.openAppPage appId 必须是非空字符串"),gameType:ud(e.gameType,ty,"navigation.openAppPage gameType 必须是 pc、console 或 mobile")};return e.page!==void 0&&(t.page=ud(e.page,ry,"navigation.openAppPage page 必须是 game 或 wiki")),e.hSrc!==void 0&&(t.hSrc=sr(e.hSrc,"navigation.openAppPage hSrc 必须是非空字符串")),e.skuId!==void 0&&(t.skuId=sr(e.skuId,"navigation.openAppPage skuId 必须是非空字符串")),t}function sy(e){return{target:"user_detail",userId:sr(e.userId,"navigation.openAppPage userId 必须是非空字符串")}}function ay(e){const t={target:"post_detail",linkId:sr(e.linkId,"navigation.openAppPage linkId 必须是非空字符串")};return e.rootCommentId!==void 0&&(t.rootCommentId=sr(e.rootCommentId,"navigation.openAppPage rootCommentId 必须是非空字符串")),e.commentId!==void 0&&(t.commentId=sr(e.commentId,"navigation.openAppPage commentId 必须是非空字符串")),t}function oy(e){const t={target:"mini_program",miniProgramId:sr(e.miniProgramId,"navigation.openAppPage miniProgramId 必须是非空字符串")};return e.extra!==void 0&&(t.extra=e.extra),t}function cy(e){return ny(e)?e.target==="game_detail"?iy(e):e.target==="user_detail"?sy(e):e.target==="post_detail"?ay(e):e.target==="mini_program"?oy(e):Ys("navigation.openAppPage target 不支持"):Ys("navigation.openAppPage options 必须是对象")}function uy(e){return{protocolType:"openRouterPath",path:"/game/detail",params:{app_id:e.appId,game_type:e.gameType,...e.page===void 0?{}:{page:e.page},...e.hSrc===void 0?{}:{h_src:e.hSrc},...e.skuId===void 0?{}:{sku_id:e.skuId}}}}function dy(e){return{protocolType:"openRouterPath",path:"/user_home",params:{userid:e.userId}}}function ly(e){return{protocolType:"openRouterPath",path:"/bbs/link",params:{link_id:e.linkId,...e.rootCommentId===void 0?{}:{root_comment_id:e.rootCommentId},...e.commentId===void 0?{}:{comment_id:e.commentId}}}}function fy(e){const t=e;return t.target==="game_detail"?uy(t):t.target==="user_detail"?dy(t):ly(t)}const hy="data:image/svg+xml;base64,PHN2ZyBwcmVzZXJ2ZUFzcGVjdFJhdGlvPSJub25lIiBvdmVyZmxvdz0idmlzaWJsZSIgc3R5bGU9ImRpc3BsYXk6IGJsb2NrOyIgd2lkdGg9IjIwIiBoZWlnaHQ9IjIwIiB2aWV3Qm94PSIwIDAgMjAgMjAiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxnIGlkPSJJY29uIj4KPHBhdGggaWQ9IlVuaW9uIiBkPSJNNS4wMzMzOCAxLjI5Mjg5QzUuNDIzOSAwLjkwMjM2OSA2LjA1NzI0IDAuOTAyMzY5IDYuNDQ3NzYgMS4yOTI4OUM2LjgzODI3IDEuNjgzNDIgNi44MzgyOCAyLjMxNjc2IDYuNDQ3NzYgMi43MDcyN0w1LjIzODQ2IDMuOTE2NThIMTEuNjY2N0MxNS40NDA1IDMuOTE2NzEgMTguNTAwMSA2Ljk3NjIgMTguNTAwMSAxMC43NTAxQzE4LjUgMTQuNTIzOCAxNS40NDA0IDE3LjU4MzQgMTEuNjY2NyAxNy41ODM1SDMuMzMzMzVDMi43ODExMiAxNy41ODM1IDIuMzMzMjcgMTcuMTM1NiAyLjMzMzE5IDE2LjU4MzRDMi4zMzMxOSAxNi4wMzExIDIuNzgxMDcgMTUuNTgzMiAzLjMzMzM1IDE1LjU4MzJIMTEuNjY2N0MxNC4zMzU5IDE1LjU4MzEgMTYuNDk5NyAxMy40MTkzIDE2LjQ5OTggMTAuNzUwMUMxNi40OTk4IDguMDgwNzYgMTQuMzM1OSA1LjkxNzAzIDExLjY2NjcgNS45MTY5SDQuNTkwNjdMNi40NDc3NiA3Ljc3NDhDNi44MzgyMSA4LjE2NTMzIDYuODM4MjYgOC43OTg2OCA2LjQ0Nzc2IDkuMTg5MThDNi4wNTcyNCA5LjU3OTQ1IDUuNDIzODMgOS41Nzk1NiA1LjAzMzM4IDkuMTg5MThMMS43OTI4MyA1Ljk0NzgyQzEuNDAyMzEgNS41NTczIDEuNDAyMzEgNC45MjM5NiAxLjc5MjgzIDQuNTMzNDRMNS4wMzMzOCAxLjI5Mjg5WiIgZmlsbD0id2hpdGUiLz4KPC9nPgo8L3N2Zz4K",my="data-hb-sdk-fullscreen-exit",Ey=3e3,gy=2e3,dd="var(--white-70a,rgba(255,255,255,.7))",ld="0 0 var(--space-8,8px) var(--white-20a,rgba(255,255,255,.2))";function py(e){if(typeof document>"u"||!document.body)return;const t=document.createElement("button");t.type="button",t.setAttribute(my,""),t.setAttribute("aria-label","退出全屏"),t.setAttribute("aria-expanded","true");const r=window.matchMedia?.("(prefers-reduced-motion: reduce)").matches??!1;t.style.cssText=["position:fixed","right:0","top:50%","z-index:2147483647","box-sizing:border-box","width:48px","height:44px","padding:5px 0",`border:1px solid ${dd}`,`box-shadow:${ld}`,"border-radius:var(--radius-m-token,5px)","display:flex","flex-direction:column","align-items:center","justify-content:center","gap:3px","background:var(--general-color-text-2,#64696e)","color:var(--white-100a,#fff)",'font:400 var(--font-size-9,9px)/var(--line-height-12,12px) "PingFang SC",sans-serif',"cursor:pointer","touch-action:manipulation","opacity:1","transform:translateY(-50%)",r?"transition:none":"transition:width var(--token-transition-arrow,220ms cubic-bezier(.2,.8,.2,1))"].join(";");const n=document.createElement("img");n.src=hy,n.alt="",n.draggable=!1,n.style.cssText="display:block;width:16px;height:16px;flex-shrink:0;";const i=document.createElement("span");i.textContent="退出全屏",i.style.cssText="white-space:nowrap;overflow:hidden;text-overflow:ellipsis;max-width:100%;",t.append(n,i);let s=!0,a=!1,c=!1,u,d;function l(){return window.innerWidth>window.innerHeight?"var(--space-12,12px)":"var(--space-8,8px)"}function h(){s||(t.style.width=l())}function f(){d?.cancel(),d=void 0}function p(y=gy){clearTimeout(u),u=setTimeout(()=>{f(),s=!1,t.style.width=l(),t.style.opacity="0.5",t.style.borderColor="var(--white-40a,rgba(255,255,255,.4))",t.style.boxShadow="none",n.style.visibility="hidden",i.style.display="none",t.setAttribute("aria-label","展开退出全屏按钮"),t.setAttribute("aria-expanded","false")},y)}function g(){f(),s=!0,t.style.width="48px",t.style.opacity="1",t.style.borderColor=dd,t.style.boxShadow=ld,n.style.visibility="",i.style.display="",t.setAttribute("aria-label","退出全屏"),t.setAttribute("aria-expanded","true"),p()}async function b(){if(!(a||c)){if(!s){g();return}c=!0,clearTimeout(u),f();try{await e()}catch{}finally{c=!1,a||g()}}}return t.addEventListener("click",b),window.addEventListener("resize",h),document.body.append(t),!r&&t.animate&&(d=t.animate([{transform:"translate(48px,-50%)",opacity:0,offset:0},{transform:"translate(0,-50%)",opacity:1,offset:.2},{transform:"translate(-6px,-50%)",offset:.4},{transform:"translate(0,-50%)",offset:.55},{transform:"translate(-6px,-50%)",offset:.75},{transform:"translate(0,-50%)",offset:1}],{duration:900,easing:"ease-in-out"})),p(Ey),{dispose(){a=!0,clearTimeout(u),f(),t.removeEventListener("click",b),window.removeEventListener("resize",h),t.remove()}}}const gh=1e4;function ph(e,t){const r=new AbortController;let n;const i=()=>{n??={code:"REQUEST_CANCELLED",message:"方向设置已取消"},r.abort()};e.addEventListener("abort",i,{once:!0}),t?.addEventListener("abort",i,{once:!0}),(e.aborted||t?.aborted)&&i();const s=setTimeout(()=>{n??={code:"ORIENTATION_TIMEOUT",message:"方向切换超时"},r.abort()},gh);return{signal:r.signal,async run(a){try{return await be(a,r.signal)}catch(c){throw n??c}},dispose(){clearTimeout(s),e.removeEventListener("abort",i),t?.removeEventListener("abort",i)}}}function fd(e){if(typeof e!="object"||e===null||Array.isArray(e))throw{code:"INVALID_PARAMS",message:"viewport.setDisplay 参数必须是对象"};const{orientation:t,fullscreen:r}=e;if(t!==void 0&&t!=="portrait"&&t!=="landscape")throw{code:"INVALID_PARAMS",message:"viewport.setDisplay orientation 必须是 portrait 或 landscape"};if(r!==void 0&&typeof r!="boolean")throw{code:"INVALID_PARAMS",message:"viewport.setDisplay fullscreen 必须是布尔值"};if(t===void 0&&r===void 0)throw{code:"INVALID_PARAMS",message:"viewport.setDisplay 至少设置 orientation 或 fullscreen"};return{orientation:t,fullscreen:r}}function ja(e,t){return e.mode===t.mode&&e.hideCapsule===t.hideCapsule}function In(){return{code:"REQUEST_CANCELLED",message:"方向设置已取消"}}function Ty(e){let t=0,r=0,n,i,s={mode:"portrait",hideCapsule:!1},a={mode:"portrait",hideCapsule:!1},c;function u(){c?.dispose(),c=void 0}function d(g){if(!g.hideCapsule){u();return}c??=py(()=>p.apply({orientation:"portrait",fullscreen:!1},void 0,"user"))}e.operationContext.signal.addEventListener("abort",u,{once:!0});function l(g,b){if(n===g){if(n=void 0,clearTimeout(g.timer),e.operationContext.signal.removeEventListener("abort",h),"error"in b)g.controller.abort();else if(i={options:g.options,result:b.result},s=g.options,d(g.options),e.onApplied?.(g.options),b.result.supported&&!ja(a,g.options)){a={...g.options};try{e.onDisplayChange?.({orientation:a.mode,fullscreen:a.hideCapsule,source:g.source})}catch{}}for(const y of g.subscribers)y.dispose(),"error"in b?y.reject(b.error):y.resolve(b.result);g.subscribers.clear()}}function h(){n&&l(n,{error:In()})}function f(g,b){return new Promise((y,N)=>{const C=()=>{g.subscribers.delete(I),I.dispose(),N(In()),g.subscribers.size===0&&l(g,{error:In()})},I={resolve:y,reject:N,dispose:()=>b?.removeEventListener("abort",C)};g.subscribers.add(I),b?.addEventListener("abort",C,{once:!0}),b?.aborted&&C()})}const p={async runDisplayRequest(g,b,y){const N=++t,C=ph(b,e.operationContext.signal);try{return await C.run(async()=>{if(await y(C.signal),C.signal.aborted)throw In();if(fd(g),N<r)throw{code:"ORIENTATION_SUPERSEDED",message:"方向设置已被后续设置替换"};return r=N,p.apply(g,C.signal)})}finally{C.dispose()}},async apply(g,b,y="api"){if(Oe(e.operationContext.signal),b?.aborted)throw In();const N=fd(g),C=n?.options??s,I={mode:N.orientation??C.mode,hideCapsule:N.fullscreen??C.hideCapsule};I.mode==="landscape"&&(I.hideCapsule=!0);const U=e.presentation.applyOrientation;if(!U)throw{code:"METHOD_FORBIDDEN",message:"当前宿主暂不支持方向控制"};if(n&&ja(n.options,I))return f(n,b);if(n&&l(n,{error:{code:"ORIENTATION_SUPERSEDED",message:"方向设置已被后续设置替换"}}),i&&ja(i.options,I))return i.result;i=void 0;const Y={options:I,source:y,controller:new AbortController,subscribers:new Set};n=Y;const R=f(Y,b);return e.operationContext.signal.addEventListener("abort",h,{once:!0}),b||(Y.timer=setTimeout(()=>{l(Y,{error:{code:"ORIENTATION_TIMEOUT",message:"方向切换超时"}})},gh)),be(()=>U.call(e.presentation,I,{...e.operationContext,signal:Y.controller.signal}),Y.controller.signal).then(P=>l(Y,{result:P??{supported:!0}}),P=>l(Y,{error:P})),R},dispose(){e.operationContext.signal.removeEventListener("abort",u),u()}};return p}function Th(e){throw{code:"INVALID_PARAMS",message:e}}function hd(e,t){e!==void 0&&(typeof e!="object"||e===null||Array.isArray(e)||Object.keys(e).length)&&Th(`${t} 不支持参数`)}function _y(e){return{[Cs]:async(t,r)=>{const n=Re(e.operationContext,r.signal,r.requestId);Oe(n.signal),hd(t,"navigation.close"),await be(()=>e.presentation.close(n),n.signal)},[Rs]:async(t,r)=>{const n=Re(e.operationContext,r.signal,r.requestId);Oe(n.signal),hd(t,"navigation.reload"),await be(()=>e.presentation.reload(n),n.signal)},[Ls]:async(t,r)=>{const n=Re(e.operationContext,r.signal,r.requestId);Oe(n.signal);const i=cy(t);if(i.target==="mini_program"){let s;if(i.extra!==void 0)try{s=Eh(i.extra)}catch{Th("navigation.openAppPage extra 必须是符合限制的 JSON-compatible 数据")}const a=e.resetDisplay;if(a){const c=ph(n.signal);try{await c.run(()=>a(c.signal))}finally{c.dispose()}}Oe(n.signal),await be(()=>e.presentation.openWindow({miniProgramId:i.miniProgramId,...s===void 0?{}:{extra:s}},n),n.signal);return}await be(()=>e.presentation.openAppPage(fy(i),n),n.signal)}}}const md={UPLOAD_CANCELLED:"上传已取消",UPLOAD_TIMEOUT:"上传空闲超时",UPLOAD_NETWORK_FAILED:"上传网络失败",FILE_CHANGED:"上传源文件已变化",METHOD_FORBIDDEN:"当前 Host 未开放上传能力"};async function Ay(e,t,r){const n=r.transfer?.upload,i=r.fileRegistry;if(!n||!i)throw _t("network.upload");const s=Re(r.operationContext,t.signal),a=()=>{if(s.signal.aborted)throw T("UPLOAD_CANCELLED","上传已取消")};a();let c,u;try{c=i.resolveFileEntry(e.from).hostHandle,u=await c.stat(s)}catch(f){throw a(),Jr(f)}if(a(),u.kind!=="file"||!Number.isSafeInteger(u.size)||u.size<0)throw T("FILE_IO_FAILED","上传源文件状态无效");if(e.maxBytes!==void 0&&u.size>e.maxBytes)throw T("FILE_TOO_LARGE","文件超过大小限制");let d=0,l=!1;const h=f=>{l||s.signal.aborted||!Number.isSafeInteger(f)||f<d||f>u.size||(d=f,t.postProgress({loaded:d,total:u.size,lengthComputable:!0}))};try{const{from:f,...p}=e,g=await n.upload(c,{...p,expectedBytes:u.size,...e.format==="multipart"?{fileName:e.fileName??c.name}:{}},{...s,onProgress:h});if(l=!0,!Number.isSafeInteger(g.uploadedBytes)||g.uploadedBytes<d||g.uploadedBytes>u.size)throw T("UPLOAD_NETWORK_FAILED","Host 返回的上传字节数无效");if(g.status>=200&&g.status<300&&g.uploadedBytes!==u.size)throw T("FILE_CHANGED","上传源文件已变化");return t.postProgress({loaded:g.uploadedBytes,total:u.size,lengthComputable:!0}),g}catch(f){l=!0;const p=mc(f);throw p&&md[p]?T(p,md[p]):s.signal.aborted?T("UPLOAD_CANCELLED","上传已取消"):p?.startsWith("FILE_")||p?.startsWith("DIRECTORY_")?Jr(f):T("UPLOAD_NETWORK_FAILED","上传网络失败")}}const Sc="withCredentials",Iy=new Set(["url","method","params","data","headers","timeout",Sc]),by=new Set(["url","to","params","headers","timeout","suggestedName","overwrite","maxBytes",Sc]),yy=new Set(["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"]),Ed=3e4,Do=2*1024*1024,Ny=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,_h=/[\u0000-\u0008\u000A-\u001F\u007F]/,wy=/^(?:authorization|authentication-info|proxy-authentication-info|cookie|set-cookie|set-cookie2|pkey|x-pkey|x-access-token|x-auth-token)$/i,Dy="network.request 不支持 multipart/form-data,请使用专用上传能力";function Sy(e){const t=Oy(e.runtimePermissions);t.allowDevelopmentHttp=e.allowDevelopmentHttp===!0,t.firstParty=e.firstParty===!0,t.networkPolicy=t.firstParty?void 0:Wl(e.networkPolicy);const r=jy(e.allowedHttpOrigins);return{[ms]:async(n,i)=>{const s=Cy(n,{permission:t,allowedHttpOrigins:r}),a=await Ay(s,i,e),{uploadedBytes:c,...u}=a;return pd(u)},[hs]:async(n,i)=>{const s=Ry(n,{permission:t,allowedHttpOrigins:r});return af(s,i,{transfer:e.transfer,fileRegistry:e.fileRegistry,operationContext:e.operationContext})},[fs]:async(n,i)=>{const s=Re(e.operationContext,i?.signal);Oe(s.signal);const a=My(n,{permission:t,allowedHttpOrigins:r});let c;try{c=await be(()=>e.network.request(a,s),s.signal)}catch(u){throw Gy(u)?u:Yy(u,"REQUEST_UNSUPPORTED")?De("REQUEST_UNSUPPORTED","当前 Host 不支持该网络请求"):De("REQUEST_FAILED","网络请求失败")}return pd(c)}}}function Oy(e){const t=it(e),r=t.permissions.network;return{enabled:t.valid&&r?.status==="enabled",useOfficialDomain:t.valid&&r?.status==="enabled"&&r.config.useOfficialDomain===!0}}function My(e,t){const r=rn(e,"network.request 参数必须是对象"),n=Object.keys(r).filter(u=>!Iy.has(u));if(n.length>0)throw De("INVALID_PARAMS",`network.request 不支持字段: ${n.join(", ")}`);Ah(r,"network.request");const i=Oc(r,t,"network.request"),s=Py(r.method),a=r.data;a!==void 0&&xy(a),By(i.headers,a);const c=Hy(i.headers,a,i.official);return{source:"public-sdk",target:{kind:"absolute-url",url:i.url.href},redirectPolicy:"error",route:i.official?"official":"external",...s===void 0?{}:{method:s},...i.params===void 0?{}:{params:i.params},...a===void 0?{}:{data:a},...i.headers===void 0?{}:{headers:i.headers},...c===void 0?{}:{bodyEncoding:c},...i.timeout===void 0?{}:{timeout:i.timeout}}}function Cy(e,t){const r=rn(e,"network.upload 参数必须是对象"),n=new Set(["url","from","format","method","params","headers","timeout","maxBytes","fieldName","fields","fileName","contentType"]);if(Object.keys(r).some(l=>!n.has(l)))throw De("INVALID_PARAMS","network.upload 包含不支持的字段");const i=Oc(r,t,"network.upload");if(!t.permission.firstParty&&i.official)throw De("PERMISSION_DENIED","上传暂不支持官方域名");if(i.timeout!==void 0&&i.timeout<=0)throw De("INVALID_PARAMS","上传 timeout 必须是有限正数");if(!Ir(r.from))throw De("INVALID_PARAMS","from 必须是有效 File ref");if(r.maxBytes!==void 0&&(!Number.isSafeInteger(r.maxBytes)||r.maxBytes<=0))throw De("INVALID_PARAMS","maxBytes 必须是正的 safe integer");if(r.format!=="raw"&&r.format!=="multipart")throw De("INVALID_PARAMS","format 必须是 raw 或 multipart");const s=r.method??(r.format==="raw"?"PUT":"POST");if(s!=="POST"&&(r.format!=="raw"||s!=="PUT"))throw De("INVALID_PARAMS","上传 HTTP 方法不支持");const a={from:r.from,format:r.format,request:{source:"public-sdk",target:{kind:"absolute-url",url:i.url.href},redirectPolicy:"error",route:"upload",method:s,...i.params===void 0?{}:{params:i.params},...i.headers===void 0?{}:{headers:i.headers},...i.timeout===void 0?{}:{timeout:i.timeout}},...r.maxBytes===void 0?{}:{maxBytes:r.maxBytes}};if(r.format==="raw"){if(["fieldName","fields","fileName","contentType"].some(l=>r[l]!==void 0))throw De("INVALID_PARAMS","raw 不接受 multipart 字段");return a}if(Object.keys(i.headers??{}).some(l=>l.toLowerCase()==="content-type"))throw De("INVALID_PARAMS","multipart Content-Type 由 Host 生成");const c=gd(r.fieldName),u=r.fields===void 0?void 0:rn(r.fields,"fields 必须是字符串字典");for(const[l,h]of Object.entries(u??{}))if(gd(l),typeof h!="string"||l===c)throw De("INVALID_PARAMS","fields 必须是字符串且不得与文件字段重名");if(r.fileName!==void 0&&typeof r.fileName!="string")throw De("INVALID_PARAMS","fileName 必须是字符串");if(r.contentType!==void 0&&(typeof r.contentType!="string"||_h.test(r.contentType)||!/^[^\s/;]+\/[^\s;]+(?:;[^\r\n]*)?$/.test(r.contentType)))throw De("INVALID_PARAMS","contentType 必须是有效 MIME type");const d={fieldName:c,fields:u,fileName:r.fileName,contentType:r.contentType};if(new TextEncoder().encode(JSON.stringify(d)).byteLength>Do)throw De("INVALID_PARAMS","multipart 元数据超过 2 MiB");return{...a,fieldName:c,...u===void 0?{}:{fields:{...u}},...r.fileName===void 0?{}:{fileName:gc(r.fileName)},contentType:r.contentType??"application/octet-stream"}}function gd(e){if(typeof e!="string"||!e||/[\u0000-\u001F\u007F"\\]/.test(e))throw De("INVALID_PARAMS","multipart 字段名必须是非空且无控制字符的字符串");return e}function Ry(e,t){const r=rn(e,"network.download 参数必须是对象"),n=Object.keys(r).filter(u=>!by.has(u));if(n.length>0)throw De("INVALID_PARAMS",`network.download 不支持字段: ${n.join(", ")}`);Ah(r,"network.download");const i=Oc(r,t,"network.download");if(i.timeout!==void 0&&i.timeout<=0)throw De("INVALID_PARAMS","network.download timeout 必须是有限正数");Ap(i.headers);const s=Ir(r.to),a=Il(r.to);if(!s&&!a)throw De("INVALID_PARAMS","network.download to 必须是有效 File/Directory ref");if(s&&(r.suggestedName!==void 0||r.overwrite!==void 0))throw De("INVALID_PARAMS","File 下载目标不接受 suggestedName/overwrite");let c;if(r.suggestedName!==void 0){if(typeof r.suggestedName!="string")throw De("INVALID_PARAMS","suggestedName 必须是字符串");c=gc(r.suggestedName)}if(r.overwrite!==void 0&&typeof r.overwrite!="boolean")throw De("INVALID_PARAMS","overwrite 必须是布尔值");if(r.maxBytes!==void 0&&(!Number.isSafeInteger(r.maxBytes)||r.maxBytes<=0))throw De("INVALID_PARAMS","maxBytes 必须是正的 safe integer");return{request:{source:"public-sdk",target:{kind:"absolute-url",url:i.url.href},redirectPolicy:"error",route:"download",method:"GET",...i.params===void 0?{}:{params:i.params},...i.headers===void 0?{}:{headers:i.headers},...i.timeout===void 0?{}:{timeout:i.timeout}},url:i.url,to:r.to,targetKind:s?"file":"directory",...c===void 0?{}:{suggestedName:c},...r.overwrite===void 0?{}:{overwrite:r.overwrite},...r.maxBytes===void 0?{}:{maxBytes:r.maxBytes}}}function Oc(e,t,r){const n=Ly(e.url,t.allowedHttpOrigins,r,t.permission.allowDevelopmentHttp===!0),i=fg(n);if(!t.permission.firstParty){const s=t.permission.networkPolicy,a=s?.enforcement==="approved_domains"&&n.protocol==="http:"&&(t.permission.allowDevelopmentHttp===!0||t.allowedHttpOrigins.has(n.origin));if(s&&!a&&(n.protocol!=="https:"||n.port!==""||!s.entries.some(c=>c.domain===n.hostname.toLowerCase())))throw De("PERMISSION_DENIED",`${r} 目标不在平台批准的域名清单中`);if(i&&!t.permission.useOfficialDomain)throw De("PERMISSION_DENIED","当前小程序暂不支持访问官方域名")}if(lg(n.pathname,i))throw De("PERMISSION_DENIED",`${r} 不允许访问 Runtime 或账号敏感接口`);return{url:n,official:i,params:e.params===void 0?void 0:{...rn(e.params,`${r} params 必须是对象`)},headers:e.headers===void 0?void 0:vy(e.headers,r),timeout:ky(e.timeout,r)}}function Ly(e,t,r="network.request",n=!1){if(typeof e!="string"||!e.trim())throw De("INVALID_PARAMS",`${r} url 必须是 HTTP(S) URL`);let i;try{i=new URL(e)}catch{throw De("INVALID_PARAMS",`${r} url 必须是 HTTP(S) URL`)}if(i.protocol!=="http:"&&i.protocol!=="https:")throw De("INVALID_PARAMS",`${r} url 必须是 HTTP(S) URL`);if(i.username||i.password)throw De("INVALID_PARAMS",`${r} url 不允许包含用户信息`);if(i.protocol==="http:"&&!n&&!t.has(i.origin))throw De("PERMISSION_DENIED",`${r} 生产环境只允许 HTTPS`);return i}function Py(e){if(e===void 0)return;if(typeof e!="string"||!e.trim())throw De("INVALID_PARAMS","network.request method 必须是字符串");const t=e.trim().toUpperCase();if(!yy.has(t))throw De("INVALID_PARAMS","network.request method 不合法");return t}function vy(e,t="network.request"){const r=rn(e,`${t} headers 必须是 Record<string, string>`),n={};for(const[i,s]of Object.entries(r)){const a=i.trim();if(!a||a!==i||!Ny.test(a)||typeof s!="string"||_h.test(s))throw De("INVALID_PARAMS",`${t} headers 必须是 Record<string, string>`);if(hg(a))throw De("INVALID_PARAMS",`${t} 不允许设置敏感请求头: ${i}`);n[a]=s}return n}function Ah(e,t){const r=e[Sc];if(r!==void 0&&typeof r!="boolean")throw De("INVALID_PARAMS",`${t} 旧版凭据字段必须是布尔值`)}function ky(e,t="network.request"){if(e!==void 0){if(typeof e!="number"||!Number.isFinite(e)||e<0)throw De("INVALID_PARAMS",`${t} timeout 必须是非负数字`);if(t==="network.request"&&e>Ed)throw De("INVALID_PARAMS",`${t} timeout 不能超过 ${Ed}ms`);return e}}function xy(e){if(typeof Blob<"u"&&e instanceof Blob||typeof FormData<"u"&&e instanceof FormData)throw De("INVALID_PARAMS","network.request data 不支持 File、Blob 或 FormData,请使用专用上传能力");if(Uy(e)>Do)throw De("INVALID_PARAMS",`network.request data 不能超过 ${Do} 字节`)}function Uy(e){if(typeof e=="string")return Va(e);if(e instanceof ArrayBuffer||ArrayBuffer.isView(e))return e.byteLength;if(typeof URLSearchParams<"u"&&e instanceof URLSearchParams)return Va(e.toString());try{const t=JSON.stringify(e);return t?Va(t):0}catch{throw De("INVALID_PARAMS","network.request data 必须可序列化")}}function By(e,t){const r=Ih(e),n=typeof t=="string"&&t.trimStart().startsWith("--")&&/content-disposition\s*:\s*form-data/i.test(t);if(r?.includes("multipart/form-data")||n)throw De("INVALID_PARAMS",Dy)}function Hy(e,t,r){if(t===void 0)return;const n=Ih(e);return n?.includes("application/x-www-form-urlencoded")?"form":n?.includes("application/json")?"json":typeof URLSearchParams<"u"&&t instanceof URLSearchParams||r&&(Array.isArray(t)||zy(t))?"form":Fy(t)?"json":void 0}function Ih(e){return e?Object.entries(e).find(([r])=>r.trim().toLowerCase()==="content-type")?.[1].toLowerCase():void 0}function Fy(e){return e===null||typeof e=="boolean"||typeof e=="number"||typeof e=="object"&&!ArrayBuffer.isView(e)&&!(e instanceof ArrayBuffer)}function zy(e){if(typeof e!="object"||e===null)return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function jy(e){const t=new Set;for(const r of e??[])try{const n=new URL(r);n.protocol==="http:"&&!n.username&&!n.password&&n.pathname==="/"&&!n.search&&!n.hash&&Vy(n.hostname)&&t.add(n.origin)}catch{}return t}function Vy(e){const t=e.toLowerCase();if(t==="[::1]")return!0;const r=t.split(".").map(Number);return r.length!==4||r.some((n,i)=>!/^\d+$/.test(t.split(".")[i])||n<0||n>255)?!1:r[0]===127||r[0]===10||r[0]===172&&r[1]>=16&&r[1]<=31||r[0]===192&&r[1]===168}function pd(e){return Object.keys(e.headers).some(Td)?{...e,headers:Object.fromEntries(Object.entries(e.headers).filter(([t])=>!Td(t)))}:e}function Td(e){const t=e.trim().toLowerCase();return wy.test(t)||t.startsWith("x-heybox-")||t.startsWith("x-xhh-")}function Gy(e){return e instanceof Error&&e.name==="AbortError"}function Yy(e,t){return typeof e=="object"&&e!==null&&"code"in e&&e.code===t}function rn(e,t){if(typeof e!="object"||e===null||Array.isArray(e))throw De("INVALID_PARAMS",t);return e}function Va(e){return new TextEncoder().encode(e).length}function De(e,t){return{code:e,message:t}}function Qy(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function qy(e){if(typeof e=="number")return Number.isSafeInteger(e)&&e>0?String(e):void 0;if(typeof e=="string")return e.trim()||void 0}function Wy(e){if(e===void 0)return{invalidMessages:[],values:[]};if(!Array.isArray(e))return{invalidMessages:["post.topicIds 必须是数组"],values:[]};const t=[],r=new Set,n=[];for(const i of e){const s=qy(i);s?r.has(s)||(r.add(s),n.push(s)):t.push("post.topicIds 每项必须是正整数或非空字符串")}return{invalidMessages:t,values:n}}function $y(e){if(e===void 0)return{invalidMessages:[],values:[]};if(!Array.isArray(e))return{invalidMessages:["post.topics 必须是数组"],values:[]};const t=[],r=new Set,n=[];for(const i of e){const s=typeof i=="string"?i.trim():"";!s||s.startsWith("#")||s.endsWith("#")?t.push("post.topics 每项必须是不含首尾 # 的非空字符串"):r.has(s)||(r.add(s),n.push(s))}return{invalidMessages:t,values:n}}function bh(e,t){if(e==null)return{};if(!Qy(e))return{invalidMessage:`${t.method} post 必须是对象或 null`};const r=Wy(e.topicIds),n=$y(e.topics),i=[...r.invalidMessages,...n.invalidMessages];let s=r.values;t.maxTopicIds!==void 0&&s.length>t.maxTopicIds&&(i.push(`${t.method} post.topicIds 最多允许 ${t.maxTopicIds} 项`),s=s.slice(0,t.maxTopicIds));const a=s.length||n.values.length?{...s.length?{topicIds:s}:{},...n.values.length?{topics:n.values}:{}}:void 0;return a||i.push(`${t.method} post 至少需要一个有效的 topicIds 或 topics`),{invalidMessage:i[0],post:a}}function Ky(e){try{return new URL(e).protocol==="heybox-mini-dev:"}catch{return!1}}async function Zy(e){try{if(Ky(e.getCurrentHref()))return!0}catch{}try{return!!await e.isDevRuntime()}catch{return!1}}function Ke(e){throw{code:"INVALID_PARAMS",message:e}}function pi(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function So(e,t){return typeof e!="string"||!e.trim()?Ke(t):e}function Xy(e,t){const r=So(e,t);try{const n=new URL(r);return n.protocol!=="http:"&&n.protocol!=="https:"?Ke(t):r}catch{return Ke(t)}}function Jy(e){return e==="wechatSession"||e==="wechatTimeline"||e==="qqFriend"||e==="qzone"||e==="weibo"}function yh(e,t,r){const n=e.identity.get(),i=n?.miniProgramId.trim();if(!i)return Ke(`${t} 缺少有效的小程序分享地址`);try{const s=new URL(e.environment.getCurrentHref()),a=new URL("/tools/common_share",s);a.searchParams.set("user_miniprogram_id",i);const c=n?.version?.trim();c&&a.searchParams.set("miniprogram_version",c);const u=s.searchParams.get("h_src");return u?.trim()&&a.searchParams.set("h_src",u),r!==void 0&&a.searchParams.set("extra",r),a.href}catch{return Ke(`${t} 缺少有效的小程序分享地址`)}}function eN(e,t){if(!pi(e))return Ke("share.showShareMenu 参数必须是对象");if(Object.prototype.hasOwnProperty.call(e,"url"))return Ke("share.showShareMenu 不支持自定义 url");const r=e.channel;if(r!==void 0&&!Jy(r))return Ke("share.showShareMenu channel 不合法");const n=Nh(e.extra,"share.showShareMenu");return{title:So(e.title,"share.showShareMenu title 必须是非空字符串"),description:So(e.desc,"share.showShareMenu desc 必须是非空字符串"),url:yh(t,"share.showShareMenu",n),...e.imageUrl===void 0?{}:{imageUrl:Xy(e.imageUrl,"share.showShareMenu imageUrl 必须是 HTTP(S) URL")},...r===void 0?{}:{channel:r}}}function Nh(e,t){if(e!==void 0)try{return Eh(e)}catch{return Ke(`${t} extra 必须是符合限制的 JSON-compatible 数据`)}}async function wh(e,t){return e.invalidMessage&&await be(()=>Zy(t.environment),t.operationContext.signal)?Ke(e.invalidMessage):e.post}function _d(e,t){const r=Number(e);return Number.isFinite(r)&&r>0?r:t}function tN(e){const t=e.getViewportMetrics();return{left:0,top:0,width:_d(t.windowWidth,0),height:_d(t.windowHeight,0)}}function Oo(e,t){const r=Number(e);return!Number.isFinite(r)||r<0?Ke(t):r}function Ad(e,t){const r=Number(e);return!Number.isFinite(r)||r<=0?Ke(t):r}function rN(e){return pi(e)?{left:Oo(e.left,"share.screenshot rect.left 必须是非负数字"),top:Oo(e.top,"share.screenshot rect.top 必须是非负数字"),width:Ad(e.width,"share.screenshot rect.width 必须是正数"),height:Ad(e.height,"share.screenshot rect.height 必须是正数")}:Ke("share.screenshot rect 必须是对象")}function Id(e,t){if(e!=null&&!pi(e))return Ke("share.screenshot 参数必须是对象");const r=e??{};return r.saveToAlbum!==void 0&&typeof r.saveToAlbum!="boolean"?Ke("share.screenshot saveToAlbum 必须是布尔值"):r.watermarkTheme!==void 0&&r.watermarkTheme!=="light"&&r.watermarkTheme!=="dark"?Ke("share.screenshot watermarkTheme 必须是 light 或 dark"):{watermarkTheme:r.watermarkTheme??"dark",rect:r.rect===void 0?tN(t):rN(r.rect),...r.delay===void 0?{}:{delay:Oo(r.delay,"share.screenshot delay 必须是非负数字")},...r.saveToAlbum===void 0?{}:{saveToAlbum:r.saveToAlbum}}}async function nN(e,t){Oe(t.operationContext.signal);const r=eN(e,t);let n=bh(e.post,{maxTopicIds:1,method:"share.showShareMenu"});r.channel&&n.post&&(n={invalidMessage:n.invalidMessage||"share.showShareMenu channel 与 post 不能同时使用"});const i=await wh(n,t);return be(()=>t.presentation.showShareMenu({...r,post:i},t.operationContext),t.operationContext.signal)}async function iN(e,t){if(Oe(t.operationContext.signal),e!==void 0&&!pi(e))return Ke("share.copyLink 参数必须是对象");const r=Nh(e?.extra,"share.copyLink"),n=yh(t,"share.copyLink",r);return await be(()=>t.presentation.setClipboard({text:n},t.operationContext),t.operationContext.signal),n}async function bd(e,t,r,n=!1){Oe(t.operationContext.signal);const i=bh(pi(e)?e.post:void 0,{method:"share.screenshot"}),s=await wh(i,t),a=t.identity.get()?.miniProgramId.trim()||void 0,c=sN(),{watermarkTheme:u,...d}=r;let l=!1,h,f,p;try{if(n&&(!t.presentation.supportsLongScreenshot||!t.prepareLongScreenshot))throw{code:"REQUEST_UNSUPPORTED",message:"当前宿主不支持 DOM 长图,请更新宿主"};if(l=!0,await be(()=>t.presentation.setScreenshotChromeHidden(!0,t.operationContext),t.operationContext.signal),n){const y=await t.prepareLongScreenshot(r.rect,t.operationContext.signal);h=y.restore,d.rect=y.rect}f=await t.prepareScreenshot?.(d.rect,t.operationContext.signal,u),p={status:"fulfilled",value:await be(()=>t.presentation.captureAndShare({...d,...n?{longContent:!0}:{},post:s,...a?{sourceMiniProgramId:a}:{}},t.operationContext),t.operationContext.signal)}}catch(b){p={status:"rejected",error:b}}finally{try{f?.()}finally{h?.()}}const g=l?await aN(t.presentation,c,t.operationContext.signal):void 0;if(p.status==="rejected")throw p.error;if(g)throw g;return p.value}function sN(){return{lifecycle:"cleanup",signal:new AbortController().signal}}async function aN(e,t,r){let n;try{n=Promise.resolve(e.setScreenshotChromeHidden(!1,t))}catch{return}try{await be(()=>n,r,{invokeWhenAborted:!0})}catch(i){if(r.aborted)return i}}function oN(e){let t=Promise.resolve();const r=async(n,i)=>{const s=Re(e.operationContext,i.signal,i.requestId),a=Id(n,e.presentation);(a.rect.top+a.rect.height>1e4||a.rect.left+a.rect.width>2048||a.rect.width*a.rect.height>4e6)&&Ke("长图尺寸超出限制");const c=t.then(()=>bd(n,{...e,operationContext:s},a,!0));return t=c.then(()=>{},()=>{}),c};return{[us]:r,[as]:(n,i)=>iN(n,{...e,operationContext:Re(e.operationContext,i.signal,i.requestId)}),[os]:(n,i)=>nN(n,{...e,operationContext:Re(e.operationContext,i.signal,i.requestId)}),[cs]:async(n,i)=>{const s=Re(e.operationContext,i.signal,i.requestId);Oe(s.signal);const a=Id(n,e.presentation),c=t.then(()=>bd(n,{...e,operationContext:s},a));return t=c.then(()=>{},()=>{}),be(()=>c,s.signal)}}}const yd=new WeakMap,Mi=new Map;function Dh(e){const t=e.canonicalIdentity?.miniProgramId?.trim();if(t)return PE(t);const r=e.anonymousStorageScope?.trim();if(r)return`anon_${Gl(r)}`;throw Object.assign(new Error("storage scope 只能在 canonical identity 绑定后使用"),{code:"INVALID_STATE"})}function Sh(e){const t=e.coordinationKey??e.storage;let r;const n=()=>r??=Promise.resolve().then(e.resolveScope).catch(u=>{throw r=void 0,u}),i=async(u,d)=>{const l=await n();let h=yd.get(t);h||(h=new Map,yd.set(t,h));const f=h.get(l)??Promise.resolve(),p=async()=>(Oe(u.signal,{preserveReason:!0}),d(l)),g=f.catch(()=>{}).then(()=>e.lock?e.lock(l,p):p());h.set(l,g);try{return await g}finally{h.get(l)===g&&h.delete(l)}},s=async(u,d,l=!1)=>{const h=vr(u,"");if(e.diagnostics)return[...new Set((await e.diagnostics.listRaw(d)).filter(g=>g.key.startsWith(h)&&g.value!=="").map(g=>g.key.slice(h.length)))];const f=await e.storage.getRaw(Ii(u),d);if((f===void 0||f==="")&&!l)throw Object.assign(new Error("当前客户端缺少数据索引,且不支持遍历本地数据,暂无法清理"),{code:"STORAGE_INDEX_MISSING"});let p;try{p=f?JSON.parse(f):[]}catch{throw new Error("本地数据索引异常")}if(!Array.isArray(p)||p.length>ru||p.some(g=>typeof g!="string"||!/^[A-Za-z0-9_-]{1,128}$/.test(g)))throw new Error("本地数据索引异常");return[...new Set(p)]},a=async(u,d)=>{if(e.diagnostics){const f=vr(u,"");return(await e.diagnostics.listRaw(d)).filter(p=>p.key.startsWith(f)&&p.value!=="").map(p=>({...p,key:p.key.slice(f.length)}))}const l=[],h=await s(u,d);for(let f=0;f<h.length;f+=16){Oe(d.signal,{preserveReason:!0});const p=await Promise.all(h.slice(f,f+16).map(async g=>{const b=await e.storage.getRaw(vr(u,g),d);return b!==void 0&&b!==""?{area:"local",key:g,value:b}:void 0}));for(const g of p)g&&l.push(g)}return l},c=u=>{if(!/^[A-Za-z0-9_-]{1,128}$/.test(u))throw Object.assign(new Error("storage key 不合法"),{code:"INVALID_REQUEST"})};return{get(u,d){return c(u),i(d,l=>e.storage.getRaw(vr(l,u),d))},set(u,d,l){return c(u),i(l,async h=>{const f=await s(h,l,!0);if(!f.includes(u)&&f.length>=ru)throw Object.assign(new Error("storage key 数量超出上限"),{code:"STORAGE_QUOTA_EXCEEDED"});if(!e.diagnostics){const p=[...new Set([...f,u])];await e.storage.setRaw(Ii(h),JSON.stringify(p),l)}Oe(l.signal,{preserveReason:!0}),await e.storage.setRaw(vr(h,u),d,l),Oe(l.signal,{preserveReason:!0})})},list(u){return i(u,d=>a(d,u))},clear(u){return i(u,async d=>{const l=await s(d,u);e.diagnostics||await e.storage.setRaw(Ii(d),JSON.stringify(l),u);for(let h=0;h<l.length;h+=16){Oe(u.signal,{preserveReason:!0});const p=(await Promise.allSettled(l.slice(h,h+16).map(g=>e.storage.setRaw(vr(d,g),"",u)))).find(g=>g.status==="rejected");if(p)throw p.reason}Oe(u.signal,{preserveReason:!0}),await e.storage.setRaw(Ii(d),"[]",u)})}}}function Oh(e,t){if(typeof navigator<"u"&&navigator.locks)return new Promise((n,i)=>{navigator.locks.request(`hb-miniprogram-storage:${e}`,()=>t().then(n,i)).catch(i)});const r=(Mi.get(e)??Promise.resolve()).catch(()=>{}).then(t);return Mi.set(e,r),r.finally(()=>{Mi.get(e)===r&&Mi.delete(e)})}const cN=128,uN=/^[A-Za-z0-9_-]+$/;function dN(e){const t=e.scopedStorage??Sh({storage:e.storage,resolveScope:()=>Dh({canonicalIdentity:e.identity.get(),anonymousStorageScope:e.anonymousStorageScope}),diagnostics:e.storageDiagnostics}),r={[Qn]:async n=>{Oe(e.operationContext.signal);const i=Nd(n,Qn,e.storageLimits?.maxKeyLength),s=await be(()=>t.get(i,e.operationContext),e.operationContext.signal);return{data:wd(s)}},[qn]:async n=>{Oe(e.operationContext.signal);const i=Mh(n,"storage.setStorage 参数必须是对象"),s=Nd(i,qn,e.storageLimits?.maxKeyLength),a=lN(i.data,e.storageLimits?.maxValueBytes);await be(()=>t.set(s,a,e.operationContext),e.operationContext.signal)}};return!e.storageDiagnostics&&!e.scopedStorage?{handlers:r}:{handlers:r,diagnostics:{getSnapshot:async()=>(Oe(e.operationContext.signal),(await be(()=>t.list(e.operationContext),e.operationContext.signal).catch(i=>{throw i&&typeof i=="object"&&"code"in i&&i.code==="INVALID_STATE"?Nr("STORAGE_DIAGNOSTICS_NOT_READY","Storage diagnostics 只能在 canonical identity 绑定后使用"):i})).map(i=>{const s=i.value;return{area:i.area,key:i.key,value:wd(s),serializedValue:s,bytes:Ch(s)}}).sort((i,s)=>i.key.localeCompare(s.key)))}}}function Nd(e,t,r=cN){const i=Mh(e,`${t} 参数必须是对象`).key;if(typeof i!="string")throw Nr("INVALID_PARAMS",`${t} key 必须是字符串`);if(!i||i.length>r||!uN.test(i))throw Nr("INVALID_PARAMS",`storage key 仅支持 1-${r} 位字母、数字、下划线和连字符`);return i}function lN(e,t){let r;try{r=JSON.stringify(e)}catch{throw Nr("INVALID_PARAMS","storage.setStorage data 必须可 JSON 序列化")}if(typeof r!="string")throw Nr("INVALID_PARAMS","storage.setStorage data 必须可 JSON 序列化");if(t!==void 0&&Ch(r)>t)throw Nr("STORAGE_QUOTA_EXCEEDED",`storage.setStorage data 超出 ${t} 字节限制`);return r}function wd(e){if(!(e===void 0||e===""))try{return JSON.parse(e)}catch{return e}}function Mh(e,t){if(typeof e!="object"||e===null||Array.isArray(e))throw Nr("INVALID_PARAMS",t);return e}function Ch(e){return new TextEncoder().encode(e).length}function Nr(e,t){return{code:e,message:t}}const Dd=120;function tr(e){throw{code:"INVALID_PARAMS",message:e}}function Mc(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Rh(e,t,r){const n=Object.keys(e).filter(i=>!t.includes(i));n.length&&tr(`${r} 不支持字段: ${n.join(", ")}`)}function fN(e){if(!Mc(e))return tr("ui.showToast 参数必须是对象");if(Rh(e,["message","status"],"ui.showToast"),typeof e.message!="string"||!e.message.trim())return tr("ui.showToast message 必须是非空字符串");const t=e.message.trim();if(t.length>Dd)return tr(`ui.showToast message 不能超过 ${Dd} 字符`);const r=e.status;if(r!==void 0&&r!=="success"&&r!=="error")return tr("ui.showToast status 必须是 success 或 error");const n=r;return{message:t,...n===void 0?{}:{status:n}}}function hN(e){return e===void 0?{dismissible:!1}:Mc(e)?(Rh(e,["dismissible"],"ui.showLoading"),e.dismissible!==void 0&&typeof e.dismissible!="boolean"?tr("ui.showLoading dismissible 必须是布尔值"):{dismissible:e.dismissible??!1}):tr("ui.showLoading 参数必须是对象")}function mN(e){e!==void 0&&(!Mc(e)||Object.keys(e).length)&&tr("ui.hideLoading 不支持参数")}function EN(e){return{[Ns]:async(t,r)=>{const n=Re(e.operationContext,r.signal,r.requestId);Oe(n.signal),await be(()=>e.presentation.showToast(fN(t),n),n.signal)},[ws]:async(t,r)=>{const n=Re(e.operationContext,r.signal,r.requestId);Oe(n.signal),await be(()=>e.presentation.showLoading(hN(t),n),n.signal)},[Ds]:async(t,r)=>{const n=Re(e.operationContext,r.signal,r.requestId);Oe(n.signal),mN(t),await be(()=>e.presentation.hideLoading(n),n.signal)}}}const gN={auth:"optional",channel:"api",failurePresentation:"none",id:"heybox.account.home_v2.get",method:"GET",path:"/account/home_v2/",parse(e){return xe(e,"当前用户首页资料接口响应异常")}},pN=3e4;function TN(e,t,r={}){const n=r.ttlMs??pN,i=r.requestPolicyEnabled!==!1,s=r.requestGate?{capability:"user",gate:r.requestGate}:void 0;let a=0,c,u;async function d(){let h;try{h=await fa(e,gN,void 0,{...t,credentials:"heybox-session",...s?{gate:s}:{}})}catch(f){throw t.signal.aborted?T("RUNTIME_DESTROYED","小程序 Runtime 已终止"):f instanceof Qe?T("REQUEST_UNSUPPORTED",f.message):f instanceof hi?T("INVALID_RESPONSE","user home_v2 响应不合法"):f instanceof en?T("REQUEST_FAILED","user home_v2 请求失败"):f instanceof fi?i&&(f.status===403||f.status===429)?T("RATE_LIMITED","user home_v2 请求已被网关限流,请稍后重试",{status:f.status,...f.retryAfterMs===void 0?{}:{retryAfterMs:f.retryAfterMs}}):T("REQUEST_FAILED",f.message):AN(f)?f:T("REQUEST_FAILED","user home_v2 请求失败")}return _N(h,"user home_v2")}function l(h){const f=Date.now();if(c?.userId===h&&c.expiresAt>f)return Promise.resolve(c.value);if(u?.userId===h&&u.generation===a)return u.promise;const p=a,g=d().then(b=>(a===p&&(c={userId:h,value:b,expiresAt:Date.now()+n}),b)).finally(()=>{u?.promise===g&&(u=void 0)});return u={userId:h,generation:p,promise:g},g}return{get:l,clear(){a+=1,c=void 0,u=void 0}}}function _N(e,t){if(!le(e))throw T("INVALID_RESPONSE",`${t}响应必须是对象`);if(e.status!=="ok"){const r=typeof e.msg=="string"&&e.msg.trim()?e.msg.trim():`${t}请求失败`,n=["login","relogin","lack_token"].includes(String(e.status))?"HEYBOX_APP_LOGIN_REQUIRED":"REQUEST_FAILED";throw T(n,r)}if(!le(e.result))throw T("INVALID_RESPONSE",`${t} result 必须是对象`);return e.result}function AN(e){return le(e)&&typeof e.code=="string"&&typeof e.message=="string"}const IN={auth:"optional",channel:"api",id:"heybox.bbs.app.profile.follow.user.post",method:"POST",path:"/bbs/app/profile/follow/user",bodyEncoding:"form",failurePresentation:"none",query(e){return e.query?{...e.query}:void 0},body(e){return{...e.body??{}}},parse(e,t){return xe(e,"关注用户接口响应异常")}},bN={auth:"none",channel:"api",id:"heybox.user_miniprogram.runtime.author.follow_status.post",method:"POST",path:"/user_miniprogram/runtime/author/follow_status",bodyEncoding:"form",failurePresentation:"none",body(e){return{...e}},parse(e,t){return xe(e,"ApiXiaoheiheCnUserMiniprogramRuntimeAuthorFollowStatus 接口响应异常")}},yN={auth:"none",channel:"api",id:"heybox.user_miniprogram.runtime.author.follow_guidance.begin.post",method:"POST",path:"/user_miniprogram/runtime/author/follow_guidance/begin",bodyEncoding:"form",failurePresentation:"none",body(e){return{...e}},parse(e,t){return xe(e,"ApiXiaoheiheCnUserMiniprogramRuntimeAuthorFollowGuidanceBegin 接口响应异常")}},NN={auth:"optional",channel:"api",failurePresentation:"none",id:"heybox.game.steam.get_game_list.get",method:"GET",path:"/game/steam/get_game_list",query(e){return{userid:e.userId,...e.steamId?{steam_id:e.steamId}:{},limit:e.limit,offset:e.offset,sort:e.sort,need_hidden:e.includeHidden,...e.personalInformationOpen===void 0?{}:{personal_infomation_open:e.personalInformationOpen},...e.q?{q:e.q}:{}}},parse(e,t){return xe(e,"Steam 游戏库接口响应异常")}};function wN(e,t=lo){const r=Dp({version:"2",validate:SN}),n={ttlMs:Number.isFinite(t)?Math.max(0,Math.floor(t)):lo,memoryMaxEntries:64,diskMaxEntries:256,diskMaxBytes:10*1024*1024,maxEntryBytes:512*1024};return{persistent:e.register({namespace:"user.steam-game-list",codec:r,policy:{...n,persistence:"memory-and-disk"}}),unresolved:e.register({namespace:"user.steam-game-list.unresolved",codec:r,policy:{...n,persistence:"memory"}})}}function Sd(e,t){if(e.steamId)return e.steamId;for(const r of["steamid","steam_id","steamId"]){const n=t[r];if(typeof n=="string"&&n.trim())return n.trim()}}function DN(e){const{query:t}=e;return JSON.stringify([e.miniProgramId,e.userId,e.effectiveSteamId??null,e.personalInformationOpen??null,t.limit,t.offset,t.sort,t.q??"",t.includeHidden])}function SN(e){if(!le(e)||!Array.isArray(e.gameList)||typeof e.hasMore!="boolean"||!Number.isInteger(e.nextOffset)||Number(e.nextOffset)<0||(Od(e,"total"),e.isMe!==void 0&&typeof e.isMe!="boolean"))throw Yr();for(const t of e.gameList){if(!le(t)||!Mo(t.appid)||!Mo(t.steamAppid)||typeof t.name!="string"||!t.name.trim())throw Yr();for(const r of["image","portraitImage","icon"])ON(t,r);for(const r of["playtimeForever","playtime2Weeks"])Od(t,r);if(t.tags!==void 0&&(!Array.isArray(t.tags)||t.tags.some(r=>typeof r!="string"||!r.trim())))throw Yr()}return e}function Mo(e){return typeof e=="number"&&Number.isFinite(e)}function Od(e,t){if(e[t]!==void 0&&!Mo(e[t]))throw Yr()}function ON(e,t){if(e[t]!==void 0&&typeof e[t]!="string")throw Yr()}function Yr(){return T("INVALID_RESPONSE","Steam 游戏库缓存数据不合法")}const Lh=20,MN=100,CN=128,Ph=0,vh="weeks",RN=100,LN=new Set(["weeks","all","achieved"]);function PN(){return{nickname:"",avatar:""}}function vN(e){const t=TN(e.network,e.operationContext,{requestGate:e.requestGate,requestPolicyEnabled:e.requestPolicyEnabled}),r=e.requestPolicyEnabled!==!1,n=e.cacheManager??uf(),i=wN(n,r?e.steamGameListTtlMs:0);let s;const a=new Map;let c=Promise.resolve();function u(j,H){const F=JSON.stringify([j,H]);return(!s||s.key!==F)&&(s={key:F,scope:n.createScope(H,n.createScope(j))}),s.scope}function d(){const j=s;s=void 0,j&&n.invalidateScope(j.scope).catch(()=>{}),a.clear()}const l=bf({ttlMs:Math.max(0,Math.floor(e.profileTtlMs??Tf))}),h=e.requestGate?{capability:"user",gate:e.requestGate}:void 0;let f,p,g=0,b=!1;const y=e.account.onChange(()=>{g+=1,t.clear(),l.invalidate(),d()}),N=e.authorization.onEvent((j,H)=>{j==="user_info_authorization_change"&&Object.values(H).some(F=>F==="denied")&&(g+=1,t.clear(),l.invalidate(),d(),c=c.then(async()=>{if(b)return;const F=await e.account.getCurrentUserId(e.operationContext);typeof F=="string"&&F.trim()&&await n.invalidateScope(u(I(),F.trim()))}).catch(()=>{}))});function C(){if(b||e.operationContext.signal.aborted)throw T("RUNTIME_DESTROYED","小程序 Runtime 已终止")}function I(){const j=e.identity.get()?.miniProgramId?.trim();if(!j)throw T("INVALID_STATE","用户能力缺少 canonical 小程序身份");return j}async function U(){C(),await c,C();let j;try{j=await e.account.getCurrentUserId(e.operationContext)}catch(H){throw e.operationContext.signal.aborted?T("RUNTIME_DESTROYED","小程序 Runtime 已终止"):bn(H)?H:T("REQUEST_FAILED","读取小黑盒账号失败")}return typeof j=="string"&&j.trim()?j.trim():void 0}async function Y(j,H){const F=await U();if(g!==H||F!==j)throw T("AUTHORIZATION_CONTEXT_CHANGED","用户请求期间账号上下文已变化,请重新操作")}async function R(j,H,F=e.operationContext.signal){try{return await fa(e.network,j,H,{...e.operationContext,signal:F,credentials:"heybox-session",...h?{gate:h}:{}})}catch(v){throw e.operationContext.signal.aborted?T("RUNTIME_DESTROYED","小程序 Runtime 已终止"):v instanceof Qe?T("REQUEST_UNSUPPORTED",v.message):v instanceof hi?T("INVALID_RESPONSE","用户接口响应不合法"):v instanceof en?T("REQUEST_FAILED","用户请求失败"):v instanceof fi?r&&(v.status===403||v.status===429)?T("RATE_LIMITED","用户请求已被网关限流,请稍后重试",{status:v.status,...v.retryAfterMs===void 0?{}:{retryAfterMs:v.retryAfterMs}}):T("REQUEST_FAILED",v.message):bn(v)?v:T("REQUEST_FAILED","用户请求失败")}}async function P(j,H){if(!e.authorizationContext)return{mini_program_id:j};let F;try{F=await be(()=>e.authorizationContext.get({...e.operationContext,signal:H}),H)}catch(v){if(bn(v))throw v;const L=T("REQUEST_FAILED","读取 Runtime auth context 失败");throw Object.defineProperty(L,"cause",{configurable:!0,value:v}),L}if(!F.token?.trim())throw T("INVALID_STATE","关注作者缺少启动凭据");return{mini_program_id:j,runtime_auth_context_token:F.token}}async function M(){C();const j=I(),H=g,F=await U();if(!F){if(g!==H)throw T("AUTHORIZATION_CONTEXT_CHANGED","查询期间账号已变化");return"notFollowing"}const v=await P(j,e.operationContext.signal);await Y(F,H);const L=await R(bN,v);if(await Y(F,H),I()!==j)throw T("AUTHORIZATION_CONTEXT_CHANGED","查询期间小程序上下文已变化");return Rd(Cd(L))}function V(j,H){if(!j)return Promise.reject(T("USER_GESTURE_REQUIRED","请点击按钮关注作者"));if(H?.aborted)return Promise.reject(T("REQUEST_CANCELLED","关注操作已取消"));if(f)return Promise.reject(T("FOLLOW_IN_PROGRESS","关注确认流程尚未结束"));if(!e.authPresentation?.confirmFollowAuthor)return Promise.reject(T("METHOD_FORBIDDEN","当前宿主不支持关注确认框"));const F=z(H).finally(()=>{f===F&&(f=void 0)});return f=F,F}async function z(j){C();const H=I(),F=new AbortController;p=F;const v=()=>F.abort();e.operationContext.signal.addEventListener("abort",v,{once:!0}),j?.addEventListener("abort",v,{once:!0});let L=()=>{},q=!1;try{try{await be(()=>e.account.ensureAuthenticated({trustedUserGesture:!0,reason:"user_action",signal:F.signal}),F.signal)}catch(Te){throw bn(Te)&&["AUTH_CANCELLED","AUTHORIZATION_CANCELLED","HEYBOX_APP_LOGIN_REQUIRED","LOGIN_CANCELLED"].includes(Te.code)?T("FOLLOW_CANCELLED","已取消小黑盒登录"):Te}C();const D=g;L=e.account.onChange(()=>{q=!0,v()});const W=await be(U,F.signal);if(!W)throw T("FOLLOW_CANCELLED","未完成小黑盒登录");const $=async()=>{if(await be(()=>Y(W,D),F.signal),C(),I()!==H)throw T("AUTHORIZATION_CONTEXT_CHANGED","关注期间小程序上下文已变化")};await $();const m=await P(H,F.signal);await $();const w=VN(),B=await be(()=>R(yN,{...m,request_id:w},F.signal),F.signal);await $();const K=Cd(B);if(K.status!=="notFollowing")return Rd(K);if(K.rateLimited)throw T("FOLLOW_GUIDANCE_LIMIT_REACHED","今日关注引导次数已达上限");const ce=await be(()=>e.authPresentation.confirmFollowAuthor({miniProgramId:H,signal:F.signal}),F.signal);if(await $(),ce!=="confirmed")throw T("FOLLOW_CANCELLED","已取消关注作者");const pe=K.authorId,ue=await be(()=>R(IN,{body:{following_id:pe}},F.signal),F.signal);if(await $(),ue.status!=="ok"){const Te=["login","relogin","lack_token"].includes(ue.status)?"HEYBOX_APP_LOGIN_REQUIRED":"REQUEST_FAILED";throw T(Te,typeof ue.msg=="string"&&ue.msg.trim()?ue.msg.trim():"关注作者失败,请稍后重试")}return"following"}catch(D){throw C(),q?T("AUTHORIZATION_CONTEXT_CHANGED","关注期间账号已变化,请重新操作"):j?.aborted?T("REQUEST_CANCELLED","关注操作已取消"):bn(D)?D:T("REQUEST_FAILED","关注作者失败,请稍后重试")}finally{L(),e.operationContext.signal.removeEventListener("abort",v),j?.removeEventListener("abort",v),p===F&&(p=void 0)}}async function te(){I();const j=g,H=await U();if(!H)return{isHeyboxAppLoggedIn:!1,authorization:null,userInfo:null};const[F,v]=await Promise.all([e.authorization.getOrCreateLocalIdentity(H),x(H).catch(()=>PN())]);return await Y(H,j),{isHeyboxAppLoggedIn:!0,authorization:e.authorization.getAuthorization(),userInfo:{app_user_id:F.appUserId,profile:v,...F.steamId?{steam_id:F.steamId}:{}}}}function x(j){return l.read(j,()=>R(If,void 0).then(H=>{const F=Co(H,"账号基础信息");if(F.display_username!==void 0&&typeof F.display_username!="string")throw T("INVALID_RESPONSE","账号基础信息 nickname 不合法");if(F.display_avatar!==void 0&&typeof F.display_avatar!="string")throw T("INVALID_RESPONSE","账号基础信息 avatar 不合法");return{nickname:F.display_username??"",avatar:F.display_avatar??""}}))}async function Q(j){const H=kN(j),F=I(),v=g,L=await U();if(!L)return d(),{isLogin:!1,isBound:!1,data:null};const q=await t.get(L);await Y(L,v);const D=kh(q.steam_id_info);if(Object.keys(D).length===0)return await n.invalidateScope(u(F,L)).catch(()=>{}),await Y(L,v),a.delete(JSON.stringify([F,L])),{isLogin:!0,isBound:!1,data:null};const W=JSON.stringify([F,L]),$=u(F,L),m=Sd({...H,steamId:void 0},D),w=xh(D.personal_infomation_open??D.personal_information_open),B=JSON.stringify([m??null,w??null]),K=a.get(W);K&&K.identity!==B&&(await n.invalidateScope($).catch(()=>{}),await Y(L,v));const ce={identity:B,scope:n.createScope(B,$)};a.set(W,ce);const pe=Sd(H,D),ue=pe?i.persistent:i.unresolved,Te=n.createScope(pe??"unresolved",ce.scope),we=async()=>{if(await Y(L,v),I()!==F||a.get(W)?.identity!==B)throw T("AUTHORIZATION_CONTEXT_CHANGED","Steam 游戏库请求期间绑定上下文已变化")},Ae=await ue.read({scope:Te,key:DN({miniProgramId:F,userId:L,effectiveSteamId:pe,personalInformationOpen:w,query:H}),signal:e.operationContext.signal,load:async Ie=>{const ye=await R(NN,{userId:L,...H,personalInformationOpen:w},Ie);return await we(),FN(Co(ye,"Steam 游戏库"),H)}}).catch(async Ie=>{throw await we(),Ie});return await we(),{isLogin:!0,isBound:!0,data:Ae}}return{getFollowStatus:M,requestFollowAuthor:V,getInfo:te,getSteamGameList:Q,async invalidateSteamGameListCache(){const j=I(),H=g,F=await U();if(!F)return;const v=u(j,F);await Promise.all([i.persistent.invalidateScope(v),i.unresolved.invalidateScope(v)]),t.clear(),a.delete(JSON.stringify([j,F])),await Y(F,H)},dispose(){b||(b=!0,p?.abort(),g+=1,y(),N(),t.clear(),l.dispose(),i.persistent.dispose(),i.unresolved.dispose(),e.cacheManager||n.dispose())}}}function kN(e){if(e==null)return{limit:Lh,offset:Ph,sort:vh,includeHidden:!1};if(!le(e))throw rr("user.getSteamGameList 参数必须是对象");const t=Object.keys(e).find(n=>!["steamId","limit","offset","sort","q","includeHidden"].includes(n));if(t)throw rr(`user.getSteamGameList 不支持字段: ${t}`);const r={limit:xN(e.limit),offset:UN(e.offset),sort:BN(e.sort),includeHidden:HN(e.includeHidden)};if(e.steamId!==void 0){if(typeof e.steamId!="string"||!e.steamId.trim()||e.steamId.trim().length>CN)throw rr("user.getSteamGameList steamId 必须是非空字符串");r.steamId=e.steamId.trim()}if(e.q!==void 0){if(typeof e.q!="string")throw rr("user.getSteamGameList q 必须是字符串");const n=e.q.trim();n&&(r.q=n.slice(0,RN))}return r}function xN(e){if(e===void 0)return Lh;if(!Number.isInteger(e)||Number(e)<1)throw rr("user.getSteamGameList limit 必须是正整数");return Math.min(Number(e),MN)}function UN(e){if(e===void 0)return Ph;if(!Number.isInteger(e)||Number(e)<0)throw rr("user.getSteamGameList offset 必须是非负整数");return Number(e)}function BN(e){if(e===void 0)return vh;if(typeof e!="string"||!LN.has(e))throw rr("user.getSteamGameList sort 不支持");return e}function HN(e){if(e===void 0)return!1;if(typeof e!="boolean")throw rr("user.getSteamGameList includeHidden 必须是 boolean");return e}function FN(e,t){if(!Array.isArray(e.game_list))throw T("INVALID_RESPONSE","Steam 游戏库 game_list 必须是数组");const r=e.game_list.map(zN).filter(c=>c!==void 0),n=Qs(e.total),i=t.offset+r.length,s={gameList:r,hasMore:r.length>=t.limit,nextOffset:i};n!==void 0&&(s.total=n,s.hasMore=i<n);const a=xh(e.is_me);return a!==void 0&&(s.isMe=a),s}function zN(e){const t=kh(e),r=Qs(t.appid),n=Qs(t.steam_appid)??r,i=Cc(t.name);if(r===void 0||n===void 0||!i)return;const s={appid:r,steamAppid:n,name:i};Ga(s,"image",t.image),typeof t.vertical_head_image=="string"&&Ga(s,"portraitImage",t.vertical_head_image),Ga(s,"icon",t.appicon??t.icon),Md(s,"playtimeForever",t.playtime_forever),Md(s,"playtime2Weeks",t.playtime_2weeks);const a=jN(t.external_tags??t.tags);return a.length&&(s.tags=a),s}function Co(e,t){if(!le(e))throw T("INVALID_RESPONSE",`${t}响应必须是对象`);if(e.status!=="ok"){const r=typeof e.msg=="string"&&e.msg.trim()?e.msg.trim():`${t}请求失败`,n=["login","relogin","lack_token"].includes(String(e.status))?"HEYBOX_APP_LOGIN_REQUIRED":"REQUEST_FAILED";throw T(n,r)}if(!le(e.result))throw T("INVALID_RESPONSE",`${t} result 必须是对象`);return e.result}function kh(e){return le(e)?e:{}}function Cc(e){return typeof e=="string"?e.trim():typeof e=="number"||typeof e=="boolean"?String(e):""}function jN(e){return Array.isArray(e)?e.map(Cc).filter(Boolean):[]}function Qs(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"&&e.trim()&&Number.isFinite(Number(e)))return Number(e)}function xh(e){if(e===!0||e===1||e==="1")return!0;if(e===!1||e===0||e==="0")return!1}function Ga(e,t,r){const n=Cc(r);n&&Object.assign(e,{[t]:n})}function Md(e,t,r){const n=Qs(r);n!==void 0&&Object.assign(e,{[t]:n})}function rr(e){return T("INVALID_PARAMS",e)}function bn(e){return le(e)&&typeof e.code=="string"&&typeof e.message=="string"}function Cd(e){const t=Co(e,"关注状态");if(![0,1,2].includes(t.follow_status)||typeof t.author_id!="string"||!/^[1-9]\d*$/.test(t.author_id)||typeof t.rate_limited!="boolean")throw T("INVALID_RESPONSE","关注状态响应不合法");return{status:t.follow_status===2?"self":t.follow_status===1?"following":"notFollowing",authorId:t.author_id,rateLimited:t.rate_limited}}function Rd(e){return e.status}function VN(){const e=globalThis.crypto.getRandomValues(new Uint8Array(16));e[6]=e[6]&15|64,e[8]=e[8]&63|128;const t=Array.from(e,r=>r.toString(16).padStart(2,"0")).join("");return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}function GN(e){return{[ts]:async t=>(Ci(t,"user.getFollowStatus"),e.user.getFollowStatus()),[rs]:async(t,r)=>(Ci(t,"user.requestFollowAuthor"),e.user.requestFollowAuthor(r.trustedUserGesture,r.signal)),[ns]:async t=>(Ci(t,"user.getInfo"),e.user.getInfo()),[is]:async(t,r)=>{Ci(t,"user.revokeAuthorization"),await e.authorization.revoke(r.trustedUserGesture)},[ss]:async t=>e.user.getSteamGameList(t)}}function Ci(e,t){if(e!==void 0)throw T("INVALID_PARAMS",`${t} 不接收入参`)}function YN(){return T("USER_DATA_PERMISSION_STATE_INVALID","本地用户数据许可状态异常,已停止访问")}function Ld(e){return T("USER_DATA_PERMISSION_SAVE_FAILED","本次运行已停止访问,设置未保存,请重试",e===void 0?void 0:{reason:e instanceof Error?e.message:String(e)})}function QN(e){const t=e.managedResources??gr,r=typeof e.storage.withLock=="function"||typeof navigator<"u"&&!!navigator.locks,n=e.hash??dc,i=new Map,s=new Set;let a=!1;function c(){if(a)throw T("RUNTIME_DESTROYED","小程序 Runtime 已终止")}function u(I,U){if(e.storage.withLock)return e.storage.withLock(l(I),U);if(typeof navigator<"u"&&navigator.locks)return Oh(l(I),U);throw T("REQUEST_UNSUPPORTED","当前宿主不支持跨实例保存资料许可")}function d(I){return zE({miniProgramId:e.resolveMiniProgramId(),userId:I,environment:e.resolveEnvironment()})}function l(I){return kE(FE(d(I)))}function h(I,U){return e.purposeOf?n(Ol(I,e.revisionOf(I),U,e.purposeOf(I))):n(`${I}\0${e.revisionOf(I)}\0${U}`)}function f(I,U){return`${I}\0${U}`}async function p(I,U){let Y;try{Y=await e.storage.getRaw(l(I),U)}catch(P){throw c(),U.signal.aborted?T("REQUEST_CANCELLED","许可操作已取消"):T("USER_DATA_PERMISSION_STORAGE_UNAVAILABLE","无法读取本地用户数据许可",{reason:P instanceof Error?P.message:String(P)})}if(c(),U.signal.aborted)throw T("REQUEST_CANCELLED","许可操作已取消");const R=Y===void 0||Y===""?void 0:HE(Y);if(Y!==void 0&&Y!==""&&R===void 0)throw YN();return R??{schema_version:1,records:{}}}async function g(I,U,Y){if(c(),Y.signal.aborted)throw T("REQUEST_CANCELLED","许可操作已取消");await e.storage.setRaw(l(I),JSON.stringify(U),Y)}function b(I){return I?.revision??0}function y(I,U,Y){const R=new Set(Y.declared??[]),P=new Set(t);for(const z of Object.keys(U.records))Zt(z)&&P.add(z);for(const z of i.keys())z.startsWith(`${I}\0`)&&P.add(z.slice(I.length+1));const V=[...P].sort((z,te)=>{const x=gr.indexOf(z),Q=gr.indexOf(te);return(x<0?Number.MAX_SAFE_INTEGER:x)-(Q<0?Number.MAX_SAFE_INTEGER:Q)}).map(z=>{const te=U.records[z],x=b(te),Q=Y.egressTier===void 0?void 0:h(z,Y.egressTier),j=i.get(f(I,z)),H=j!==void 0&&j.revision===x&&(Q===void 0||j.consentFingerprint===Q);return{resource:z,name:oc(z)?.name??z,purposeText:e.purposeOf?.(z)??"",scopeFingerprint:Q??"",declared:R.has(z),available:R.has(z),decision:te?.decision??"ask",revision:x,...te?.decision==="allow"&&te.consentFingerprint?{consentFingerprint:te.consentFingerprint}:{},sessionAllowed:H,allowed:!s.has(f(I,z))&&R.has(z)&&te?.decision!=="deny"&&(H||r&&te?.decision==="allow"&&Q!==void 0&&te.consentFingerprint===Q)}});return Object.freeze({schema_version:1,canPersist:r,resources:Object.freeze(V),...Y.egressTier===void 0?{}:{egressTier:Y.egressTier}})}function N(I,U,Y,R){const P=U.records[Y],M=f(I,Y);if(s.has(M))return{status:"denied",reason:"tightening"};if(P?.decision==="deny")return{status:"denied",reason:"deny"};const V=h(Y,R);if(r&&P?.decision==="allow"&&P.consentFingerprint===V)return{status:"allowed",source:"persistent"};const z=i.get(M);return z&&z.revision===b(P)&&z.consentFingerprint===V?{status:"allowed",source:"session"}:{status:"ask"}}function C(I){if(typeof I!="string"||!gr.includes(I))throw T("INVALID_PARAMS","用户数据资源标识不合法")}return{canPersist:r,async read(I,U,Y={}){c();const R=await p(I,U);return y(I,R,Y)},async evaluate(I,U,Y){c(),C(U.resource);const R=await p(I,Y);return N(I,R,U.resource,U.egressTier)},async decide(I,U){c(),C(I.resource);const Y=async()=>{c();const R=await p(I.userId,U);if(c(),U.signal.aborted)throw T("REQUEST_CANCELLED","许可操作已取消");const P=R.records[I.resource],M=b(P);if(I.expectedRevision!==void 0&&M!==I.expectedRevision)throw T("AUTHORIZATION_CONTEXT_CHANGED","资料许可已变化,请重新确认");const V=f(I.userId,I.resource),z=h(I.resource,I.egressTier);if(I.expectedFingerprint!==void 0&&I.expectedFingerprint!==z)throw T("AUTHORIZATION_CONTEXT_CHANGED","资料披露范围已变化,请重新确认");if(I.scope==="session"){if(I.decision!=="allow")throw T("INVALID_PARAMS","本次许可只支持允许");return i.set(V,Object.freeze({revision:M,consentFingerprint:z})),y(I.userId,R,{egressTier:I.egressTier})}const te=M+1,x=I.decision==="allow"?{decision:"allow",revision:te,consentFingerprint:z}:{decision:I.decision,revision:te},Q={schema_version:1,records:{...R.records,[I.resource]:x}};I.decision!=="allow"&&(s.add(V),i.delete(V));try{await g(I.userId,Q,U)}catch(j){throw Ld(j)}return s.delete(V),i.delete(V),y(I.userId,Q,{egressTier:I.egressTier})};return I.scope==="session"?Y():u(I.userId,Y)},async revokeSession(I,U){c(),I.resource!==void 0&&C(I.resource);for(const R of[...i.keys()])R.startsWith(`${I.userId}\0`)&&(I.resource===void 0||R===f(I.userId,I.resource))&&i.delete(R);const Y=await p(I.userId,U);return y(I.userId,Y,{})},async reset(I,U){return c(),u(I.userId,async()=>{c();const Y=await p(I.userId,U);if(c(),U.signal.aborted)throw T("REQUEST_CANCELLED","许可操作已取消");const R=new Set(t);for(const V of Object.keys(Y.records))R.add(V);for(const V of i.keys())V.startsWith(`${I.userId}\0`)&&R.add(V.slice(I.userId.length+1));for(const V of R)s.add(f(I.userId,V));for(const V of[...i.keys()])V.startsWith(`${I.userId}\0`)&&i.delete(V);const P={...Y.records};for(const V of R)P[V]={decision:"ask",revision:(P[V]?.revision??0)+1};const M={schema_version:1,records:P};try{await g(I.userId,M,U)}catch(V){throw Ld(V)}for(const V of R)s.delete(f(I.userId,V));return y(I.userId,M,{})})},dispose(){a||(a=!0,i.clear(),s.clear())}}}const Aa={auth:"none",channel:"api",method:"POST",bodyEncoding:"form",failurePresentation:"none",parse(e){return xe(e,"游戏资料接口响应异常")}};function Ia(e){return{runtime_auth_context_token:e.runtime_auth_context_token,resource:e.resource,disclosure_revision:e.disclosure_revision}}const qN={...Aa,id:"heybox.user_miniprogram.runtime.user_game_data.query.post",path:"/user_miniprogram/runtime/user_game_data/query",body(e){return{...Ia(e),operation:e.operation,schema_version:e.schema_version,...e.cursor===void 0?{}:{cursor:e.cursor},...e.limit===void 0?{}:{limit:e.limit}}}},WN={...Aa,id:"heybox.user_miniprogram.runtime.user_game_data.sync.post",path:"/user_miniprogram/runtime/user_game_data/sync",body:Ia},Pd={...Aa,id:"heybox.user_miniprogram.runtime.user_game_data.sync_status.post",path:"/user_miniprogram/runtime/user_game_data/sync_status",body(e){return{...Ia(e),task_id:e.task_id}}},$N={...Aa,id:"heybox.user_miniprogram.runtime.user_game_data.file.post",path:"/user_miniprogram/runtime/user_game_data/file",body(e){return{...Ia(e),save_id:e.save_id,file_id:e.file_id}}};function KN(e){const t=Mf(e.storage),r=e.fileDownloads??(e.files&&e.transfer?Tc({files:e.files,transfer:e.transfer,registry:e.registry,signal:e.signal}):void 0),n=new Set,i=d=>{if(e.signal.aborted||d.signal.aborted)throw ne("REQUEST_CANCELLED","资料请求已取消")};async function s(d,l){if(i(l),!e.authorizationContext)throw ne("REQUEST_UNSUPPORTED","宿主缺少受信运行上下文");const h=await e.authorizationContext.get(l);if(!h.token||!Number.isFinite(h.expiresAt)||h.expiresAt<=Date.now())throw ne("UNAUTHORIZED","受信运行上下文已过期");return{runtime_auth_context_token:h.token,resource:d.key,disclosure_revision:d.disclosureRevision}}async function a(d,l,h){i(h);const f=await mi({network:e.network,operationContext:h,subject:"游戏资料",assertUsable:()=>i(h),requestPolicyEnabled:e.requestPolicyEnabled,...e.requestGate?{gate:{capability:"userGameData",gate:e.requestGate}}:{}},d,l),p=Je(f,"user.data","游戏资料");if(!Se(p))throw ne("INVALID_RESPONSE","游戏资料响应无效");return i(h),p}const c=d=>{const l=oc(d);if(!l)throw ne("REQUEST_UNSUPPORTED","未开放资料资源");return l};async function u(d){n.delete(d),await r?.release(d)}return{releaseFile:u,invalidate(){for(const d of n)r?.release(d);n.clear()},async query(d,l){const h=c(d.resource),f=h.queries[d.operation];if(!f)throw ne("REQUEST_UNSUPPORTED","未开放资料操作");const p=await a(qN,{...await s(h,l),operation:d.operation,schema_version:f.version,...d.cursor===void 0?{}:{cursor:d.cursor},...d.limit===void 0?{}:{limit:d.limit}},l);if(p.resource!==d.resource||p.operation!==d.operation||p.schema_version!==f.version||p.disclosure_revision!==h.disclosureRevision)throw ne("INVALID_RESPONSE","游戏资料合同不匹配");if(p.status==="ready"){if(!RE(f.schema,p.data))throw ne("INVALID_RESPONSE","游戏资料正文不匹配公开 schema");return{status:"ready",data:p.data,meta:{},schemaVersion:f.version}}if(p.status==="empty"&&(p.reason==="no_data"||p.reason==="not_ready")&&typeof p.message=="string")return{status:"empty",reason:p.reason,message:p.message,meta:{},schemaVersion:f.version};throw ne("INVALID_RESPONSE","游戏资料状态无效")},async sync(d,l,h){const f=c(d.resource);if(!f.operations.includes("sync"))throw ne("REQUEST_UNSUPPORTED","资源不支持同步");const p=await s(f,l),g=new AbortController,b=()=>g.abort();l.signal.addEventListener("abort",b,{once:!0}),l.signal.aborted&&b();let y=!1;const N=setTimeout(()=>{y=!0,b()},5*6e4),C={...l,signal:g.signal},I={...h,gameId:f.game,resource:d.resource};let U;try{const Y=await t.run(I,C,async()=>{const P=await t.get(I,C);if(P)return U=P,{id:P,status:await a(Pd,{...await s(f,C),task_id:P},C)};const M=await a(WN,p,C);if(typeof M.task_id!="string"||!M.task_id||M.task_id.length>128)throw ne("INVALID_RESPONSE","同步任务缺失");return await t.set(I,M.task_id,C),{id:M.task_id,status:M}});let R=Y.status;for(U=Y.id;;){if(i(C),R.state==="succeeded")return await t.remove(I,U,C),{status:"succeeded"};if(R.state==="failed")throw await t.remove(I,U,C),ne(typeof R.error_code=="string"?R.error_code:"SYNC_FAILED","存档同步失败");if(R.state!=="syncing"&&R.state!=="uploading")throw ne("INVALID_RESPONSE","同步状态无效");if(await ZN(C.signal),R=await a(Pd,{...await s(f,C),task_id:U},C),R.task_id!==U)throw ne("INVALID_RESPONSE","同步任务不匹配")}}catch(Y){throw U&&Se(Y)&&["SYNC_TASK_NOT_FOUND","SYNC_TASK_CHANGED","STEAM_ACCOUNT_CHANGED"].includes(String(Y.code))&&await t.remove(I,U,C),y?ne("REQUEST_TIMEOUT","等待同步超时,后台任务可能仍在执行"):Y}finally{clearTimeout(N),l.signal.removeEventListener("abort",b)}},async file(d,l,h){const f=c(d.resource);if(!f.operations.includes("file")||!r)throw ne("REQUEST_UNSUPPORTED","宿主不支持资料文件下载");const p=async b=>{await h(b);const y=await a($N,{...await s(f,b),save_id:d.saveId,file_id:d.fileId},b);if(!Se(y.file)||y.file.file_id!==d.fileId)throw ne("INVALID_RESPONSE","文件标识不匹配");return await h(b),y},g=await r.download(await p(l),async b=>{await p(b)},l);try{return i(l),await h(l),i(l),n.add(g),g}catch(b){throw await u(g),b}}}}function ZN(e){return new Promise((t,r)=>{const n=()=>{clearTimeout(i),e.removeEventListener("abort",n),r(ne("REQUEST_CANCELLED","已停止等待同步"))},i=setTimeout(()=>{e.removeEventListener("abort",n),t()},2e3);e.addEventListener("abort",n,{once:!0}),e.aborted&&n()})}const yn=["event_id","miniProgramId","environment","host_platform","host_version","sdk_version","runtime_version","egress_tier","resource","call_id","flow_id"],XN=Object.freeze({user_game_data_permission_show:new Set([...yn,"entry","reason"]),user_game_data_permission_result:new Set([...yn,"choice","apply_result"]),user_game_data_permission_manage:new Set([...yn,"operation","apply_result","succeeded_count","failed_count"]),user_game_data_action:new Set([...yn,"stage","action_type","outcome","duration_ms"]),user_game_data_access_result:new Set([...yn,"api","trigger","status","error_code","failure_stage","duration_ms","cache_hit","sample_rate","overview_status_counts"])}),vd=10*6e4,JN=256;function ew(e){const t=e.now??Date.now,r=e.random??Math.random,n=e.createId??iw,i=rw(e.sampleRate),s=new Map,a=new Map,c=new Map;let u=!1,d=0,l=0,h=0,f=0;const p={get emitted(){return d},get failed(){return l},get skipped(){return h},get deduplicated(){return f}};function g(R){return`${R}${n()}`}function b(){const R=t();for(const[P,M]of s)R-M.createdAt<=vd||(s.delete(P),a.get(M.key)===P&&a.delete(M.key));for(const[P,M]of c){if(R-M<=vd&&c.size<=JN)break;c.delete(P)}}function y(R){const P=s.get(R);P!==void 0&&(s.delete(R),a.get(P.key)===R&&a.delete(P.key))}function N(R){y(R),c.delete(R),c.set(R,t())}function C(R,P){const M=XN[R],V={};for(const[z,te]of Object.entries(P))te===void 0||!M.has(z)||(V[z]=te);return Object.freeze(V)}function I(R){const P={event_id:g("evt_"),miniProgramId:zr(()=>e.resolveMiniProgramId())??"unknown",environment:tw(zr(()=>e.resolveEnvironment())),host_platform:zr(e.resolveHostPlatform)??"unknown",host_version:zr(e.resolveHostVersion)??"unknown",sdk_version:zr(e.resolveSdkVersion)??"unknown",runtime_version:zr(e.resolveRuntimeVersion)??"unknown",egress_tier:nw(e)};return R.resource!==void 0&&(P.resource=R.resource),R.callId!==void 0&&(P.call_id=R.callId),R.flowId!==void 0&&(P.flow_id=R.flowId),P}function U(R,P){if(u){h+=1;return}try{if(e.sink===void 0){h+=1;return}e.sink.postEvent(R,C(R,P)),d+=1}catch{l+=1}}function Y(R,P){if(R===void 0)return!1;const M=s.get(R);return M===void 0?!1:P==="start"&&M.started||P==="shown"&&M.shown||P==="decided"&&M.decided?!0:(P==="start"&&(M.started=!0),P==="shown"&&(M.shown=!0),P==="decided"&&(M.decided=!0),!1)}return{diagnostics:p,createCallId(){return g("call_")},beginFlow(R){b();const P=`${R.resource??""}\0${R.actionType}`,M=a.get(P);if(M!==void 0&&s.has(M))return M;const V=g("flow_");return s.set(V,{key:P,createdAt:t(),started:!1,shown:!1,decided:!1}),a.set(P,V),V},permissionShow(R){if(Y(R.flowId,"shown")){f+=1;return}U("user_game_data_permission_show",{...I(R),entry:R.entry,reason:R.reason})},permissionResult(R){if(Y(R.flowId,"decided")){f+=1;return}U("user_game_data_permission_result",{...I(R),choice:R.choice,apply_result:R.applyResult})},permissionManage(R){U("user_game_data_permission_manage",{...I(R),operation:R.operation,apply_result:R.applyResult,...R.succeededCount===void 0?{}:{succeeded_count:R.succeededCount},...R.failedCount===void 0?{}:{failed_count:R.failedCount}})},action(R){if(R.stage==="start"&&Y(R.flowId,"start")){f+=1;return}if(R.stage==="finish"){if(R.flowId!==void 0&&c.has(R.flowId)){f+=1;return}R.flowId!==void 0&&N(R.flowId)}U("user_game_data_action",{...I(R),stage:R.stage,action_type:R.actionType,...R.outcome===void 0?{}:{outcome:R.outcome},...R.durationMs===void 0?{}:{duration_ms:Math.max(0,Math.round(R.durationMs))}})},access(R){if(i<=0){h+=1;return}if(i<1&&r()>=i){h+=1;return}U("user_game_data_access_result",{...I(R),api:R.api,trigger:R.trigger,status:R.status,duration_ms:Math.max(0,Math.round(R.durationMs)),sample_rate:i,...R.errorCode===void 0?{}:{error_code:R.errorCode},...R.failureStage===void 0?{}:{failure_stage:R.failureStage},...R.cacheHit===void 0?{}:{cache_hit:R.cacheHit},...R.overviewStatusCounts===void 0?{}:{overview_status_counts:R.overviewStatusCounts}})},dispose(){u||(u=!0,s.clear(),a.clear(),c.clear())}}}function tw(e){switch(e){case"public":case"production":return"production";case"preview":return"preview";case"development":case"dev":case"local":return"development";case"mock":return"mock";default:return"unknown"}}function rw(e){return e===void 0||!Number.isFinite(e)?1:e<=0?0:e>=1?1:e}function zr(e){if(e!==void 0)try{const t=e();if(typeof t!="string")return;const r=t.trim();return r===""?void 0:r}catch{return}}function nw(e){try{return e.resolveEgressTier()==="upload"?"upload":"no_network"}catch{return"no_network"}}function iw(){const e=globalThis.crypto;if(typeof e?.randomUUID=="function")return e.randomUUID();const t=new Uint8Array(16);if(typeof globalThis.crypto?.getRandomValues=="function")globalThis.crypto.getRandomValues(t);else for(let r=0;r<t.length;r+=1)t[r]=Math.floor(Math.random()*256);return Array.from(t,r=>r.toString(16).padStart(2,"0")).join("")}function Lt(e){const t=it(e);return t.valid?t.permissions.network?.status==="enabled"||t.permissions.companion?.status==="enabled"?"upload":"no_network":"upload"}function sw(e){let t=!1,r=0,n,i=!1;const s=new Map,a=new Map,c=new Set,u=new Map,d=e.now??Date.now,l=m=>N()[m]?.purpose??"",h=m=>{const w=oc(m);if(!w)throw T("REQUEST_UNSUPPORTED","未开放的资料资源");return w},f=m=>Ol(m,h(m).disclosureRevision,Lt(e.runtimePermissions),l(m)),p=()=>QN({storage:e.storage,resolveMiniProgramId:()=>e.identity.get()?.miniProgramId,resolveEnvironment:()=>e.environment,revisionOf:m=>h(m).disclosureRevision,purposeOf:l,...e.hash?{hash:e.hash}:{}});let g=p();const b=ew({resolveMiniProgramId:()=>e.identity.get()?.miniProgramId,resolveEnvironment:()=>e.environment,resolveEgressTier:()=>Lt(e.runtimePermissions),...e.telemetry??{}}),y=KN({network:e.network,authorizationContext:e.authorizationContext,files:e.files,transfer:e.transfer,storage:e.storage,registry:e.fileRegistry,fileDownloads:e.fileDownloads,requestGate:e.requestGate,requestPolicyEnabled:e.requestPolicyEnabled,signal:e.operationContext.signal});function N(){const m=it(e.runtimePermissions),w=m.valid?m.permissions.user_game_data:void 0;return w?.status==="enabled"?ti(w.config.resources):{}}function C(m){if(t||e.operationContext.signal.aborted)throw T("RUNTIME_DESTROYED","小程序已关闭");if(m?.signal.aborted)throw T("REQUEST_CANCELLED","资料请求已取消")}function I(m){for(const[w,B]of s)B!==void 0&&(m===void 0||B===m)&&w.abort()}function U(m){for(const[w,B]of a)(m===void 0||w===m)&&(B.abort(),a.delete(w))}function Y(){r++,U();for(const m of s.keys())m.abort();for(const m of c)e.fileRegistry.revokeFiles([m]);c.clear(),u.clear(),y.invalidate()}const R=Ei(e.account,m=>{if(i&&n===m)return;const w=n;i=!0,n=m,w!==void 0&&(Y(),g.dispose(),g=p())}),P=()=>Y();e.operationContext.signal.addEventListener("abort",P,{once:!0});async function M(m,w){C(m);const B=new AbortController,K=()=>B.abort();s.set(B,void 0),m.signal.addEventListener("abort",K,{once:!0}),m.signal.aborted&&K();const ce={...e.operationContext,...m,signal:B.signal};try{const pe=await w(ce);return C(ce),pe}catch(pe){throw le(pe)&&pe.name==="AbortError"?T("REQUEST_CANCELLED","资料操作已取消"):pe}finally{m.signal.removeEventListener("abort",K),s.delete(B)}}function V(m){const w=h(m);if(!l(w.key))throw T("USER_DATA_RESOURCE_NOT_DECLARED","小程序未声明这项游戏资料",{resource:w.key});return w}async function z(m){C(m);const w=await e.account.getCurrentUserId(m);if(C(m),!i)i=!0,n=w;else if(n!==w){const B=n;n=w,B!==void 0&&(Y(),g.dispose(),g=p(),C(m))}return w}function te(m,w){const B={login_required:"请先登录小黑盒",permission_required:"尚未允许读取这项资料",permission_denied:"已拒绝读取这项资料",source_not_linked:"请先在小黑盒关联对应游戏账号",source_login_required:"请先在小黑盒更新游戏来源登录"},K=w==="login_required"?{type:"user_login",label:"登录并授权"}:w==="permission_required"?{type:"permission",label:"允许读取"}:w==="permission_denied"&&e.presentation?.openDataPermissions?{type:"manage",label:"管理数据权限"}:void 0;return{status:"blocked",resource:m,reason:w,message:B[w],...K?{interaction:K}:{}}}async function x(m,w){V(m);const B=await z(w);if(!B)return te(m,"login_required");const K=await g.evaluate(B,{resource:m,egressTier:Lt(e.runtimePermissions)},w);return C(w),K.status==="allowed"?{userId:B}:te(m,K.status==="denied"?"permission_denied":"permission_required")}async function Q(m,w,B,K,ce){if(C(ce),r!==B||await z(ce)!==w||f(m)!==K)throw T("AUTHORIZATION_CONTEXT_CHANGED","账号或资料范围已变化");return x(m,ce)}function j(m,w){if(!le(m)||typeof m.resource!="string")throw T("INVALID_PARAMS","资料请求无效");if(!Zt(m.resource))throw T("REQUEST_UNSUPPORTED","当前宿主尚未开放该资料资源");const B=w==="query"?["resource","operation","schemaVersion","cursor","limit"]:["resource","saveId","fileId"];if(Object.keys(m).some(ce=>!B.includes(ce)))throw T("INVALID_PARAMS","资料请求包含未知参数");const K=V(m.resource);if(w==="query"){if(m.operation!=="get"&&m.operation!=="list")throw T("INVALID_PARAMS","资料查询操作无效");const ce=K.queries[m.operation];if(!ce)throw T("REQUEST_UNSUPPORTED","资源不支持该查询");if(m.schemaVersion!==ce.version)throw T("REQUEST_UNSUPPORTED","SDK 与宿主正文合同版本不匹配");if(m.operation!=="list"&&(m.cursor!==void 0||m.limit!==void 0))throw T("INVALID_PARAMS","单份查询不能分页");if(m.cursor!==void 0&&(typeof m.cursor!="string"||!m.cursor||m.cursor.length>32768))throw T("INVALID_PARAMS","分页游标无效");if(!ce.page&&(m.cursor!==void 0||m.limit!==void 0))throw T("INVALID_PARAMS","该列表不支持分页");if(m.limit!==void 0&&(typeof m.limit!="number"||!Number.isInteger(m.limit)||m.limit<1||m.limit>(ce.page?.maxSize??100)))throw T("INVALID_PARAMS","分页数量无效")}else if(!K.operations.includes(w))throw T("REQUEST_UNSUPPORTED","资源不支持该操作");if(w==="file"&&(typeof m.saveId!="string"||!m.saveId||typeof m.fileId!="string"||!m.fileId))throw T("INVALID_PARAMS","资料文件标识无效");return w==="query"?{resource:m.resource,operation:m.operation,schemaVersion:m.schemaVersion,...m.cursor===void 0?{}:{cursor:m.cursor},...m.limit===void 0?{}:{limit:m.limit}}:{resource:m.resource,saveId:m.saveId,fileId:m.fileId}}async function H(m,w,B,K){const ce=d(),pe=r,ue=f(w.resource);for(const Te of s.keys())Te.signal===B.signal&&s.set(Te,w.resource);try{const Te=await x(w.resource,B);if("status"in Te)return b.access({resource:w.resource,api:m,trigger:"initial",status:"blocked",durationMs:d()-ce}),Te;let we;try{we=await K()}catch(Ie){const ye=le(Ie)?Ie.code:void 0;if(ye==="USER_DATA_SOURCE_NOT_LINKED"||ye==="USER_DATA_SOURCE_LOGIN_REQUIRED")return b.access({resource:w.resource,api:m,trigger:"initial",status:"blocked",durationMs:d()-ce}),te(w.resource,ye==="USER_DATA_SOURCE_NOT_LINKED"?"source_not_linked":"source_login_required");throw Ie}const Ae=await Q(w.resource,Te.userId,pe,ue,B);return"status"in Ae?(b.access({resource:w.resource,api:m,trigger:"initial",status:"blocked",durationMs:d()-ce}),Ae):(b.access({resource:w.resource,api:m,trigger:"initial",status:le(we)&&we.status==="empty"?"empty":m===Rn?"succeeded":"ready",durationMs:d()-ce}),we)}catch(Te){throw b.access({resource:w.resource,api:m,trigger:"initial",status:"error",durationMs:d()-ce,errorCode:le(Te)?String(Te.code):"REQUEST_FAILED"}),Te}}async function F(m){const w=await z(m);if(!w)throw T("UNAUTHORIZED","请先登录小黑盒");return g.read(w,m,{declared:Object.keys(N()),egressTier:Lt(e.runtimePermissions)})}async function v(m,w){const B=V(m);let K=await z(w);if(K||(await e.account.ensureAuthenticated({trustedUserGesture:!0,reason:"user_action",signal:w.signal}),K=await z(w)),!K)return{status:"cancelled"};let ce=await g.evaluate(K,{resource:m,egressTier:Lt(e.runtimePermissions)},w);if(ce.status==="allowed")return{status:"allowed"};if(ce.status==="denied"){if(e.presentation?.openDataPermissions){const Pe=r,He=f(m),Ve=await e.presentation.openDataPermissions({resource:m,miniProgramName:e.miniProgramPresentation?.name,signal:w.signal});if(!("status"in await Q(m,K,Pe,He,w)))return{status:"allowed"};if(!Ve)return{status:"cancelled"}}return ce=await g.evaluate(K,{resource:m,egressTier:Lt(e.runtimePermissions)},w),{status:ce.status==="allowed"?"allowed":"denied"}}if(!e.presentation?.confirmDataPermission)throw T("REQUEST_UNSUPPORTED","当前宿主不支持资料许可弹窗");U(m);const pe=new AbortController;a.set(m,pe);const ue=()=>pe.abort();w.signal.addEventListener("abort",ue,{once:!0}),w.signal.aborted&&ue();const Te={...w,signal:pe.signal},we=r,Ae=f(m),Ie=g,ye=b.beginFlow({resource:m,actionType:"permission"});let ve="error";try{const He=(await Ie.read(K,Te,{egressTier:Lt(e.runtimePermissions)})).resources.find(cr=>cr.resource===m);b.action({resource:m,flowId:ye,stage:"start",actionType:"permission"}),b.permissionShow({resource:m,flowId:ye,entry:"other",reason:He?.decision==="allow"?"scope_changed":"first"});const Ve=await be(()=>e.presentation.confirmDataPermission({miniProgramName:e.miniProgramPresentation?.name,resource:m,scopeText:`此黑盒账号关联的${B.name}${B.operations.includes("sync")?`。${I0}`:""}`,purposeText:l(m),egress:Lt(e.runtimePermissions),canPersist:Ie.canPersist,signal:pe.signal}),pe.signal);if(C(Te),r!==we||await z(Te)!==K||f(m)!==Ae)throw T("AUTHORIZATION_CONTEXT_CHANGED","资料许可范围已变化");return Ve.decision==="cancelled"?(ve="cancelled",b.permissionResult({resource:m,flowId:ye,choice:"cancel",applyResult:"cancelled"}),{status:"cancelled"}):(await Ie.decide({userId:K,resource:m,decision:Ve.decision==="deny"?"deny":"allow",scope:Ve.decision==="session"?"session":"persistent",egressTier:Lt(e.runtimePermissions),expectedRevision:He?.revision??0,expectedFingerprint:He?.scopeFingerprint},Te),Ve.decision==="deny"&&I(m),ve=Ve.decision==="deny"?"unresolved":"resolved",b.permissionResult({resource:m,flowId:ye,choice:Ve.decision,applyResult:"applied"}),{status:Ve.decision==="deny"?"denied":"allowed"})}catch(Pe){throw ve=Te.signal.aborted?"cancelled":"error",b.permissionResult({resource:m,flowId:ye,choice:"cancel",applyResult:Te.signal.aborted?"cancelled":"error"}),Pe}finally{b.action({resource:m,flowId:ye,stage:"finish",actionType:"permission",outcome:ve}),w.signal.removeEventListener("abort",ue),a.get(m)===pe&&a.delete(m)}}async function L(m,w,B,K,ce,pe){w==="allow"?V(m):h(m);const ue=await z(K);if(!ue)throw T("UNAUTHORIZED","请先登录小黑盒");try{await g.decide({userId:ue,resource:m,decision:w,scope:B,expectedRevision:ce,expectedFingerprint:pe,egressTier:Lt(e.runtimePermissions)},K)}catch(Te){throw le(Te)&&Te.code==="USER_DATA_PERMISSION_SAVE_FAILED"&&I(m),Te}return U(m),w!=="allow"&&I(m),F(K)}async function q(m,w,B){try{const K=await B();return b.permissionManage({operation:m,resource:w,applyResult:"applied"}),K}catch(K){throw b.permissionManage({operation:m,resource:w,applyResult:le(K)&&K.code==="USER_DATA_PERMISSION_SAVE_FAILED"?"save_failed":"error"}),K}}async function D(m,w){U(m),I(m);const B=await z(w);if(!B)throw T("UNAUTHORIZED","请先登录小黑盒");return q("revoke",m,async()=>(await g.revokeSession({userId:B,resource:m},w),F(w)))}function W(){let m;const w=B=>M(e.operationContext,async K=>{const ce=await z(K);if(!ce)throw T("UNAUTHORIZED","请先登录小黑盒");if(m&&(m.userId!==ce||m.generation!==r))throw T("AUTHORIZATION_CONTEXT_CHANGED","管理页面所属账号已变化,请重新打开");return m??={userId:ce,generation:r},B(K)});return{getSnapshot:()=>w(F),setDecision:B=>w(K=>q("modify",B.resource,()=>L(B.resource,B.decision,B.scope,K,B.expectedRevision,B.expectedFingerprint))),revokeSession:B=>w(K=>D(B?.resource,K)),resetAll:()=>w(async B=>{U(),I();const K=await z(B);return q("reset",void 0,async()=>(await g.reset({userId:K},B),F(B)))})}}return{handlers:{[ec]:async(m,w)=>M(w,async B=>{if(m!==void 0&&(!le(m)||Object.keys(m).some(pe=>pe!=="game")||m.game!==void 0&&typeof m.game!="string"))throw T("INVALID_PARAMS","概览参数无效");if(le(m)&&typeof m.game=="string"&&!qc(m.game))throw T("REQUEST_UNSUPPORTED","当前宿主尚未开放该游戏");const K=Object.keys(N()),ce=le(m)?m.game:void 0;return Dl.filter(pe=>ce===void 0||pe===ce).map(pe=>({game:pe,name:wl[pe],resources:br.filter(ue=>ue.game===pe&&K.includes(ue.key)).map(ue=>({resource:ue.key,name:ue.name,status:"not_checked",statusText:"尚未检查"}))})).filter(pe=>pe.resources.length>0)}),[Ki]:async(m,w)=>M(w,B=>{const K=j(m,"query");return H(Ki,K,B,()=>y.query(K,B))}),[Rn]:async(m,w)=>M(w,async B=>{if(!le(m)||Object.keys(m).length!==1||typeof m.game!="string"||!qc(m.game))throw T("INVALID_PARAMS","同步需要指定已开放的游戏");const K={game:m.game};if(!br.some(we=>we.game===K.game&&we.sync))throw T("REQUEST_UNSUPPORTED","该游戏不支持存档同步");const ce=br.filter(we=>we.game===K.game&&we.sync&&l(we.key));if(ce.length===0)throw T("USER_DATA_RESOURCE_NOT_DECLARED","小程序未声明可同步的资料");let pe,ue;for(const we of ce){const Ae=await x(we.key,B);if(!("status"in Ae)){pe=we.key;break}(!ue||ue.reason==="permission_denied")&&(ue=Ae)}if(!pe)return ue;const Te={resource:pe};return H(Rn,Te,B,async()=>{const we=await z(B),Ae=`${we}\0${Te.resource}`;let Ie=u.get(Ae);if(!Ie){const ye=new AbortController;s.set(ye,Te.resource);const ve={controller:ye,waiters:0,settled:!1,promise:Promise.resolve(void 0)};ve.promise=y.sync(Te,{...e.operationContext,signal:ye.signal},{userId:we,miniProgramId:e.identity.get()?.miniProgramId??""}).finally(()=>{ve.settled=!0,s.delete(ye),u.get(Ae)===ve&&u.delete(Ae)}),ve.promise.catch(()=>{}),u.set(Ae,ve),Ie=ve}Ie.waiters++;try{return await be(()=>Ie.promise,B.signal)}finally{Ie.waiters--,Ie.waiters===0&&!Ie.settled&&Ie.controller.abort()}})}),[Zi]:async(m,w)=>M(w,async B=>{const K=j(m,"file"),ce=await z(B),pe=r,ue=f(K.resource),Te=async Ae=>{try{const Ie=await Q(K.resource,ce,pe,ue,Ae);if("status"in Ie)throw T("FILE_ACCESS_REVOKED","文件授权已撤销",{reason:Ie.reason})}catch(Ie){throw le(Ie)&&["AUTHORIZATION_CONTEXT_CHANGED","USER_DATA_RESOURCE_NOT_DECLARED"].includes(String(Ie.code))?T("FILE_ACCESS_REVOKED","文件授权已失效",{causeCode:Ie.code}):Ie}};let we;try{const Ae=await H(Zi,K,B,async()=>(we=await y.file(K,B,Te),{handle:we}));if(le(Ae)&&Ae.status==="blocked"){const Pe=String(Ae.reason);throw T(Pe==="source_not_linked"?"USER_DATA_SOURCE_NOT_LINKED":Pe==="source_login_required"?"USER_DATA_SOURCE_LOGIN_REQUIRED":Pe==="login_required"?"UNAUTHORIZED":"PERMISSION_DENIED",String(Ae.message),{reason:Pe})}const Ie=Ae.handle,ye={...Ie,read:async Pe=>{await Te(Pe);const He=await Ie.read(Pe);try{return await Te(Pe),He}catch(Ve){throw He.fill(0),Ve}},stat:async Pe=>{await Te(Pe);const He=await Ie.stat(Pe);return await Te(Pe),He}},ve=e.fileRegistry.registerFile(ye,"download","read");return"handleId"in ve.ref&&c.add(ve.ref.handleId),ve}catch(Ae){throw we&&await y.releaseFile(we),Ae}}),[tc]:async(m,w)=>{if(!w.trustedUserGesture)throw T("USER_GESTURE_REQUIRED","许可操作需要点击");return M(w,B=>{if(!le(m)||Object.keys(m).length!==1||typeof m.resource!="string"||!Zt(m.resource))throw T("INVALID_PARAMS","许可资源无效");return v(m.resource,B)})},[rc]:async(m,w)=>M(w,F),[nc]:async(m,w)=>{if(!w.trustedUserGesture)throw T("USER_GESTURE_REQUIRED","修改许可需要点击");if(!le(m)||typeof m.resource!="string"||!Zt(m.resource)||m.decision!=="deny"||m.scope!=="persistent"||Object.keys(m).some(B=>!["resource","decision","scope"].includes(B)))throw T("INVALID_PARAMS","允许许可只能由可信弹窗确认");return M(w,B=>L(m.resource,m.decision,"persistent",B))},[ic]:async(m,w)=>{if(!w.trustedUserGesture)throw T("USER_GESTURE_REQUIRED","管理资料许可需要点击");if(!e.presentation?.openDataPermissions)throw T("REQUEST_UNSUPPORTED","宿主未提供资料管理界面");if(m!==void 0&&(!le(m)||Object.keys(m).some(B=>B!=="resource")||m.resource!==void 0&&(typeof m.resource!="string"||!Zt(m.resource))))throw T("INVALID_PARAMS","管理资源无效");return M(w,async B=>(await e.presentation.openDataPermissions({resource:le(m)?m.resource:void 0,miniProgramName:e.miniProgramPresentation?.name,signal:B.signal}),F(B)))},[sc]:async(m,w)=>{if(!w.trustedUserGesture)throw T("USER_GESTURE_REQUIRED","撤销许可需要点击");if(m!==void 0&&(!le(m)||Object.keys(m).some(B=>B!=="resource")||m.resource!==void 0&&(typeof m.resource!="string"||!Zt(m.resource))))throw T("INVALID_PARAMS","撤销资源无效");return M(w,B=>D(le(m)?m.resource:void 0,B))}},get permissionBridge(){return W()},diagnostics:{telemetry:b.diagnostics},dispose(){t||(t=!0,Y(),R(),e.operationContext.signal.removeEventListener("abort",P),g.dispose(),b.dispose())}}}function kd(e){throw{code:"INVALID_PARAMS",message:e}}function Nn(e,t){const r=Number(e);return Number.isFinite(r)&&r>0?r:t}function Uh(e,t){const r=Number(e);return Number.isFinite(r)&&r>=0?r:t}function Ri(e,t,r){return Math.min(Uh(e,t),r)}async function aw(e){try{return Uh(await e.getNavigationBarHeight(),0)}catch{return 0}}function ow(e,t,r,n){const i=Ri(e.safeArea?.left,0,t),s=Math.max(i,Ri(e.safeArea?.right,t,t)),a=Ri(e.safeArea?.top,n,r),c=Math.max(a,Ri(e.safeArea?.bottom,r,r));return{left:i,right:s,top:a,bottom:c,width:s-i,height:c-a}}async function xd(e){const t=e.getViewportMetrics(),r=Nn(t.windowWidth,0),n=Nn(t.windowHeight,0),i=await aw(e);return{pixelRatio:Nn(t.pixelRatio,1),screenWidth:Nn(t.screenWidth,r),screenHeight:Nn(t.screenHeight,n),windowWidth:r,windowHeight:n,statusBarHeight:i,safeArea:ow(t,r,n,i),screenTop:i}}function cw(e){const t=new AbortController,r={...e,operationContext:{...e.operationContext,signal:t.signal}};let n=!1,i=0,s,a;const c=()=>{if(n||r.operationContext.signal.aborted||!r.onViewportChange)return;const h=++i;xd(r.presentation).then(f=>{if(n||r.operationContext.signal.aborted||h!==i)return;const p=JSON.stringify(f);p!==s&&(s=p,r.onViewportChange?.(f))}).catch(()=>{})},u=Ty({...r,onApplied:c}),d=()=>{n||(n=!0,e.operationContext.signal.removeEventListener("abort",d),t.abort(),u.dispose(),a?.())};return e.operationContext.signal.aborted?d():(a=r.presentation.onViewportChange?.(c),e.operationContext.signal.addEventListener("abort",d,{once:!0})),{handlers:{[wr]:async(h,f)=>u.apply(h,f?.signal),[ds]:async()=>(Oe(r.operationContext.signal),xd(r.presentation)),[ls]:async h=>{if(Oe(r.operationContext.signal),typeof h!="object"||h===null||Array.isArray(h))return kd("viewport.setNavigationBarStyle 参数必须是对象");const f=h.foregroundStyle;if(f!=="light"&&f!=="dark")return kd("viewport.setNavigationBarStyle foregroundStyle 必须是 light 或 dark");await be(()=>r.presentation.setNavigationBarStyle(f,e.operationContext),r.operationContext.signal)}},runDisplayRequest:u.runDisplayRequest,applyOrientation:(h,f)=>u.apply({orientation:h.mode,fullscreen:h.hideCapsule},f),notifyChange:()=>{s=void 0,c()},dispose:d}}function uw(e){if(e===void 0)return{};if(!e||typeof e!="object"||Array.isArray(e))throw Me("INVALID_PARAMS","工作区卡片刷新参数必须是对象");const t=e;if(Object.keys(t).some(i=>i!=="gameAppId"&&i!=="cardIds"))throw Me("INVALID_PARAMS","工作区卡片刷新包含未知参数");const{gameAppId:r,cardIds:n}=t;if(r!==void 0&&(typeof r!="string"||!/^[1-9][0-9]{0,9}$/.test(r)||Number(r)>2147483647))throw Me("INVALID_PARAMS","工作区卡片游戏编号无效");if(n!==void 0&&(!Array.isArray(n)||n.length>3||n.some(i=>typeof i!="string"||!/^[a-z][a-z0-9-]{0,63}$/.test(i))||new Set(n).size!==n.length))throw Me("INVALID_PARAMS","工作区卡片编号无效");return{...r===void 0?{}:{gameAppId:r},...n===void 0?{}:{cardIds:[...n]}}}function dw(e,t){return{[Xi]:async(r,n)=>{const i=Re(t,n.signal,n.requestId);if(Oe(i.signal),!e)throw Me("CAPABILITY_UNAVAILABLE","当前 Host 不支持工作区卡片");const s=uw(r),a=await be(()=>e.requestRefresh(s,i),i.signal);if(!a||typeof a!="object"||Array.isArray(a)||Object.keys(a).some(c=>c!=="scheduled")||!Number.isSafeInteger(a.scheduled)||a.scheduled<0)throw Me("HOST_INVALID_RESPONSE","工作区卡片刷新回执无效");return{scheduled:a.scheduled}}}}const lw=new Map(ir.map(e=>[e.method,e]));function Ya(e,t,r){return{code:e,message:t,...r===void 0?{}:{data:r}}}function fw(e){const t=Xl(e);return r=>t(r.requirement,r.method)}function hw(e,t,r,n){let i;try{i=Promise.resolve(e(t,r))}catch(s){return n.aborted?Promise.resolve({status:"dropped"}):Promise.reject(s)}return n.aborted?(i.catch(()=>{}),Promise.resolve({status:"dropped"})):new Promise((s,a)=>{let c=!1;const u=l=>{c||(c=!0,n.removeEventListener("abort",d),l())},d=()=>u(()=>s({status:"dropped"}));n.addEventListener("abort",d,{once:!0}),i.then(l=>u(()=>s({status:"handled",value:l})),l=>u(()=>a(l)))})}function mw(e){const t=fw(e.runtimePermissions),r=it(e.runtimePermissions);let n=0;return{async dispatch(i,s,a){const c=e.now??Ew,u=e.onTrace?c():0,d=e.onTrace?Date.now():0,l=e.onTrace?a.requestId??`runtime_${++n}`:"";e.onTrace&&Qa(e.onTrace,{callId:l,method:i,startedAt:d,outcome:"started"},()=>u,u);try{if(e.terminalSignal.aborted)throw Ya("RUNTIME_DESTROYED","小程序 Runtime 已终止");Yl(i,e.effectiveCapabilities);const h=lw.get(i);if(!h)throw new Error(`Capability method ${i} 缺少 protocol metadata`);const f=t(h),p=!f.allowed&&r.valid&&r.permissions.companion?.status==="enabled"&&e.allowsCompanionAttachmentAccess?.(i,s)===!0,g=!f.allowed&&r.valid&&r.permissions.gameSaves?.status==="enabled"&&e.allowsGameSaveAccess?.(i,s)===!0,b=!f.allowed&&r.valid&&r.permissions.user_game_data?.status==="enabled"&&e.allowsUserGameDataFileAccess?.(i,s)===!0;if(!f.allowed&&!p&&!g&&!b)throw Ya(f.code,f.message,f.data);const y=e.handlers[i];if(!y)throw new Error(`Capability method ${i} 缺少 handler`);const N=async U=>{for(const Y of e.policies??[]){const R=await Y.evaluate({method:i,payload:s,capability:h});if(e.terminalSignal.aborted||U.aborted)throw Bd();if(!R.allowed)throw Ya(R.code,R.message,R.data)}if(e.terminalSignal.aborted||U.aborted)throw Bd()},I=await hw(async()=>{if(i===wr){if(!e.runDisplayRequest)throw new Error("viewport.setDisplay 缺少执行 Module");return e.runDisplayRequest(s,a.signal,N)}return await N(e.terminalSignal),y(s,a)},void 0,a,e.terminalSignal);return e.onTrace&&Qa(e.onTrace,Ud(l,i,s,d,I),c,u),I}catch(h){throw e.onTrace&&Qa(e.onTrace,Ud(l,i,s,d,{status:"error",error:h}),c,u),h}}}}function Ew(){return typeof performance>"u"?Date.now():performance.now()}function Qa(e,t,r,n){if(!e)return;const i=r()-n,s=Date.now();try{e({...t,phase:"host",timestamp:s,durationMs:Math.max(0,Number.isFinite(i)?i:0)})}catch{}}function Ud(e,t,r,n,i){const s=i.status==="handled"?"success":i.status;return{callId:e,method:t,startedAt:n,outcome:s,...i.status==="error"?{errorCode:gw(i.error)}:{},...pw(t,r,i)}}function gw(e){return typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"?e.code:void 0}function pw(e,t,r){if(e!=="network.request"||typeof t!="object"||t===null||!("url"in t)||typeof t.url!="string")return{};try{const n=new URL(t.url);if(n.protocol!=="http:"&&n.protocol!=="https:"||n.username||n.password)return{};const s=("method"in t&&typeof t.method=="string"?t.method:"GET").trim().toUpperCase();if(!["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"].includes(s))return{};const a=r.status==="handled"&&Ro(r.value)&&typeof r.value.status=="number"?r.value.status:void 0;return{network:{method:s,origin:n.origin,pathname:n.pathname,...a===void 0?{}:{responseStatus:a}}}}catch{return{}}}function Ro(e){return typeof e=="object"&&e!==null}function Bd(){const e=new Error("The operation was aborted");return e.name="AbortError",e}function Tw(e){const t={signal:e.terminalSignal,...e.miniProgramDetail===void 0?{}:{miniProgramDetail:e.miniProgramDetail}},r=jp(e.requestPolicy);let n;if(e.files)try{n=Lp(e.files,t)}catch{}const i=uf({store:n}),s=e.onRequestPolicyReport??(r.debugReport?_w:void 0),a=r.enabled?Bp({...r.gateOptions,...s?{onReport:s}:{}}):void 0,c=new Ec(e.files,e.miniProgramDetail),u=wb({registry:c,picker:e.picker,operationContext:t}),d=hT({account:e.account,network:e.network,identity:e.identity,operationContext:t,authPresentation:e.authPresentation,miniProgramPresentation:e.miniProgramPresentation,steamAccount:e.runtimeFeatures?.steamAccount===!0,userDataMode:e.runtimeFeatures?.userDataMode,authorizationContext:e.authorizationContext,identityTtlMs:r.identityTtlMs,requestGate:a,requestPolicyEnabled:r.enabled});let l,h,f,p,g,b,y,N=()=>{},C=()=>{};try{l=cw({operationContext:t,presentation:e.hostPresentation,onDisplayChange:j=>e.eventSink.postEvent("display_change",j),onViewportChange:j=>e.eventSink.postEvent("viewport_change",j)}),f=vN({authPresentation:e.authPresentation,authorizationContext:e.authorizationContext,account:e.account,network:e.network,identity:e.identity,operationContext:t,authorization:d,profileTtlMs:r.profileTtlMs,steamGameListTtlMs:r.steamGameListTtlMs,cacheManager:i,requestGate:a,requestPolicyEnabled:r.enabled}),N=d.onEvent((j,H)=>e.eventSink.postEvent(j,H)),C=e.hostCompanion?.onSessionEvent?.(j=>{const H=_b(j);!e.terminalSignal.aborted&&H&&e.eventSink.postEvent(H.type,H.payload)})??(()=>{}),p=WT({authorizationContext:e.authorizationContext,account:e.account,identity:e.identity,network:e.network,operationContext:t,requestGate:a,requestPolicyEnabled:r.enabled});const I=e.files&&e.transfer?Tc({files:e.files,transfer:e.transfer,registry:c,signal:t.signal}):void 0,U=sw({identity:e.identity,account:e.account,storage:e.storage,network:e.network,authorizationContext:e.authorizationContext,files:e.files,transfer:e.transfer,fileDownloads:I,requestGate:a,requestPolicyEnabled:r.enabled,fileRegistry:c,...e.userDataPresentation===void 0?{}:{presentation:e.userDataPresentation},...e.miniProgramPresentation===void 0?{}:{miniProgramPresentation:e.miniProgramPresentation},runtimePermissions:e.runtimePermissions,environment:e.miniProgramDetail?.releaseChannel,operationContext:t,...e.onUserDataTelemetry===void 0?{}:{telemetry:{sink:{postEvent(j,H){e.onUserDataTelemetry?.({name:j,payload:H})}}}}});y=U,g=a_({identity:e.identity,storage:e.storage,account:e.account,presentation:e.hostPresentation,network:e.network,authorization:d,authorizationContext:e.authorizationContext,operationContext:t,files:e.files,transfer:e.transfer,fileRegistry:c,fileDownloads:I,requestGate:a,requestPolicyEnabled:r.enabled}),b=ab({presentation:e.hostPresentation,account:e.account,network:e.network,authorization:d,authorizationContext:e.authorizationContext,operationContext:t,requestGate:a,requestPolicyEnabled:r.enabled,onBackgroundError:e.onBackgroundError,emit:j=>e.eventSink.postEvent("post_change",j)});const Y=dN({storage:e.storage,scopedStorage:e.scopedStorage,storageDiagnostics:e.storageDiagnostics,identity:e.identity,operationContext:t,anonymousStorageScope:e.anonymousStorageScope,storageLimits:e.storageLimits});h=Wb({registry:c,media:e.media,operationContext:t});const R=[{name:"post",handlers:b.handlers},{name:"gameSaves",handlers:Object.fromEntries(Object.entries(g.handlers).map(([j,H])=>[j,async(F,v)=>{const L=e.verifiedSdkVersion,q=L?_c(L,"0.10.0-0"):void 0;if(q===void 0||q>=0)throw T("REQUEST_UNSUPPORTED","当前 SDK 不支持旧游戏存档入口,请使用 user.games.get(...).saves");return H(F,v)}]))},{name:"auth",handlers:IT({authorization:d})},{name:"user",handlers:{...GN({user:f,authorization:d,runtimePermissions:e.runtimePermissions,steamAccount:e.runtimeFeatures?.steamAccount===!0,userDataMode:e.runtimeFeatures?.userDataMode}),...wp({operationContext:t,presentation:e.hostPresentation,miniProgramPresentation:e.miniProgramPresentation})}},{name:"share",handlers:oN({prepareScreenshot:e.prepareScreenshot,prepareLongScreenshot:e.prepareLongScreenshot,environment:e.environment,identity:e.identity,operationContext:t,presentation:e.hostPresentation})},{name:"viewport",handlers:l.handlers},{name:"storage",handlers:Y.handlers},{name:"network",handlers:Sy({network:e.network,transfer:e.transfer,fileRegistry:c,operationContext:t,runtimePermissions:e.runtimePermissions,allowedHttpOrigins:e.allowedHttpOrigins,allowDevelopmentHttp:e.allowDevelopmentHttp,networkPolicy:e.networkPolicy,firstParty:e.firstParty})},{name:"workspaceCards",handlers:dw(e.workspaceCards,t)},{name:"files",handlers:u.files},{name:"file",handlers:u.file},{name:"directory",handlers:u.directory},{name:"media",handlers:h.handlers},{name:"ui",handlers:EN({operationContext:t,presentation:e.hostPresentation})},{name:"device",handlers:yb({operationContext:t,presentation:e.hostPresentation,protocol:e.hostProtocol})},{name:"navigation",handlers:_y({operationContext:t,presentation:e.hostPresentation,...e.hostPresentation.applyOrientation?{resetDisplay:j=>l.applyOrientation({mode:"portrait",hideCapsule:!1},j)}:{}})},{name:"cloud",handlers:p.handlers},{name:"userGameData",handlers:y.handlers},{name:"companion",handlers:mb({companion:e.hostCompanion,companionPresentation:e.companionPresentation,miniProgramPresentation:e.miniProgramPresentation,operationContext:t,fileRegistry:c})}],P=Aw(R);let M=!1;const V=()=>{M||(M=!0,e.terminalSignal.removeEventListener("abort",V),l?.dispose(),h?.dispose(),p?.dispose(),g?.dispose(),b?.dispose(),y?.dispose(),N(),C(),f?.dispose(),i.dispose(),d.dispose(),a?.dispose(),c.dispose())};e.terminalSignal.aborted?V():e.terminalSignal.addEventListener("abort",V,{once:!0});const z=new Set(["file.readText","file.readBytes","file.stat"]),te=(j,H)=>z.has(j)&&Ro(H)&&c.isCompanionAttachmentRef(H.target),x=new Set(["file.readText","file.readBytes","file.stat","file.exists"]),Q=(j,H)=>x.has(j)&&Ro(H)&&c.isUserDataDownloadRef(H.target);return{get permissionBridge(){return U.permissionBridge},modules:R,setPostVisible:b.setVisible,dismissPostEditor:b.dismissEditor,handlers:P,runDisplayRequest:l.runDisplayRequest,allowsCompanionAttachmentAccess:te,allowsGameSaveAccess:g.allowsRead,allowsUserGameDataFileAccess:Q,gameSaveDiagnostics:g.diagnostics,applyOrientation:l.applyOrientation,notifyViewportChange:l.notifyChange,...Y.diagnostics?{storageDiagnostics:Y.diagnostics}:{},...e.files?{sandboxDiagnostics:vb({registry:c,operationContext:t,runtimePermissions:e.runtimePermissions,capabilities:e.diagnosticCapabilities})}:{},dispose:V}}catch(I){throw l?.dispose(),h?.dispose(),p?.dispose(),g?.dispose(),b?.dispose(),y?.dispose(),N(),C(),f?.dispose(),i.dispose(),d.dispose(),a?.dispose(),c.dispose(),I}}function _w(e){try{console.warn("[hb-sdk-runtime] request-policy",e)}catch{}}function Aw(e){const t=new Map(ir.map(i=>[i.method,i.module])),r=new Map;for(const i of e)for(const[s,a]of Object.entries(i.handlers)){const c=s,u=t.get(c);if(!u)throw new Error(`Capability Module ${i.name} 注册了未知 method: ${c}`);if(u!==i.name)throw new Error(`Capability method ${c} 应由 ${u} 拥有,不能注册到 ${i.name}`);if(r.has(c))throw new Error(`Capability method ${c} 存在重复 owner`);if(typeof a!="function")throw new Error(`Capability method ${c} 缺少 handler`);r.set(c,a)}const n=ir.map(i=>i.method).filter(i=>!r.has(i));if(n.length>0)throw new Error(`Capability registry 缺少 method: ${n.join(", ")}`);if(r.size!==ir.length)throw new Error(`Capability registry method 数量不合法: ${r.size}`);return Object.freeze(Object.fromEntries(r))}const Iw="heybox-mini-dev:";function Hd(e){try{return bw(new URL(e))}catch{return!1}}function bw(e){return e.protocol===Iw}function yw(e){return e==="localhost"||e==="127.0.0.1"||e==="[::1]"||Nw(e)}function Nw(e){const t=e.split(".");if(t.length!==4)return!1;const r=t.map(n=>/^\d+$/.test(n)?Number(n):Number.NaN);return r.some(n=>!Number.isInteger(n)||n<0||n>255)?!1:r[0]===10||r[0]===172&&r[1]>=16&&r[1]<=31||r[0]===192&&r[1]===168}const ww=new Set(["android","ios","ohos","windows","macos","linux","unknown"]);function Dw(e,t){const r=[],n=Sw(e.environmentInfo,r),i=Gi(n?.appVersion,"host.appVersion",r),s=Mw(n?.operatingSystem,r);return{info:Object.freeze({runtime:Object.freeze({mode:Ow(e.sdkVersionPolicy?.releaseChannel,r)}),host:Object.freeze({appVersion:i}),miniProgram:Object.freeze({id:Gi(t.miniProgramId),version:Gi(t.miniProgramVersion)}),operatingSystem:Object.freeze(s)}),invalidFields:Object.freeze(r)}}function Sw(e,t){if(e!=null){if(Bh(e))return e;t.push("environmentInfo")}}function Ow(e,t){return e==="public"?"production":e==="preview"||e==="development"?e:(e!=null&&t.push("runtime.mode"),"unknown")}function Mw(e,t){if(e==null)return{name:"unknown",version:null};if(!Bh(e))return t.push("operatingSystem"),{name:"unknown",version:null};const r=ww.has(e.name)?e.name:"unknown";return r==="unknown"&&e.name!==void 0&&e.name!==null&&e.name!=="unknown"&&t.push("operatingSystem.name"),{name:r,version:Gi(e.version,"operatingSystem.version",t)}}function Gi(e,t,r){return e==null?null:typeof e=="string"&&e.trim()?e.trim():(t&&r&&r.push(t),null)}function Bh(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const Cw="data:image/svg+xml;base64,PHN2ZyBwcmVzZXJ2ZUFzcGVjdFJhdGlvPSJub25lIiBvdmVyZmxvdz0idmlzaWJsZSIgc3R5bGU9ImRpc3BsYXk6IGJsb2NrOyIgd2lkdGg9IjY3IiBoZWlnaHQ9IjIyIiB2aWV3Qm94PSIwIDAgNjcgMjIiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxwYXRoIGlkPSJTdWJ0cmFjdCIgZD0iTTY2IDBDNjYuMzM3MiAwIDY2LjY3MDYgMC4wMTcxODM4IDY3IDAuMDQ2ODc1QzYxLjM5MzYgMC41NTIxODkgNTcgNS4yNjIwMiA1NyAxMUM1NyAxNi43MzggNjEuMzkzNiAyMS40NDY4IDY3IDIxLjk1MjFDNjYuNjcwNiAyMS45ODE4IDY2LjMzNzIgMjIgNjYgMjJIMTFDNC45MjQ4NyAyMiAwIDE3LjA3NTEgMCAxMUMwIDQuOTI0ODcgNC45MjQ4NyAyLjY1NzU2ZS0wNyAxMSAwSDY2Wk04LjI0MzE2IDYuNzM1MzVDOC4yNDMxNiA2LjU5Mzk3IDguMTQyNTggNi41MzU3NiA4LjAxOTUzIDYuNjA2NDVMNi4yMjI2NiA3LjY0MDYyQzYuMTU3ODcgNy42ODIyOCA2LjEwNDE2IDcuNzM5MTcgNi4wNjU0MyA3LjgwNTY2QzYuMDI2NzIgNy44NzIyNyA2LjAwNDEgNy45NDc1MiA2IDguMDI0NDFWMTMuOTY1OEM2LjAwMzcxIDE0LjA0MzQgNi4wMjU4NSAxNC4xMTkxIDYuMDY0NDUgMTQuMTg2NUM2LjEwMzE5IDE0LjI1NCA2LjE1NzQgMTQuMzEyIDYuMjIyNjYgMTQuMzU0NUw5Ljg3MTA5IDE2LjQ1OEM5Ljk5MzQ2IDE2LjUyNzIgMTAuMDkzNiAxNi41ODQyIDEwLjA5NDcgMTYuNTg1OUMxMC4wOTQ3IDE2LjU4NzEgMTAuMTkzNCAxNi42NDUxIDEwLjMxNjQgMTYuNzE1OEwxMi41MDEgMTcuOTY5N0MxMi42MjI4IDE4LjA0MDMgMTIuNzIzNiAxNy45ODIyIDEyLjcyMzYgMTcuODQwOFYxMi4zNjcyQzEyLjcyMyAxMi4yOTk0IDEyLjY5NTcgMTIuMjM0MyAxMi42NDc1IDEyLjE4NjVDMTIuNTk5MiAxMi4xMzg4IDEyLjUzMzggMTIuMTEyMyAxMi40NjU4IDEyLjExMjNIMTAuNzM3M0MxMC42NzAyIDEyLjExMzIgMTAuNjA1OSAxMi4xMzk5IDEwLjU1ODYgMTIuMTg3NUMxMC41MTEzIDEyLjIzNTIgMTAuNDg0NyAxMi4zMDAxIDEwLjQ4NDQgMTIuMzY3MlYxMy44Mzc5QzEwLjQ4NDIgMTMuOTc4OSAxMC4zODQ2IDE0LjAzNjQgMTAuMjYxNyAxMy45NjU4TDguNDY0ODQgMTIuOTM1NUM4LjQwMDI2IDEyLjg5MzUgOC4zNDYxNCAxMi44MzcyIDguMzA3NjIgMTIuNzcwNUM4LjI2OTE5IDEyLjcwNCA4LjI0NzM1IDEyLjYyOTQgOC4yNDMxNiAxMi41NTI3VjYuNzM1MzVaTTI0LjMzNCAxNC4zOTI2QzI0LjMzMzkgMTQuOTk4NSAyNC4yMDU1IDE1LjE4NDYgMjMuNTk4NiAxNS4xOTYzTDIyLjMwMTggMTUuMjU0OUwyMi42NjUgMTYuMjU0OUgyNS4wODY5QzI1LjY3MDUgMTYuMDg0IDI1Ljg3MjEgMTUuNzE5NCAyNS44NzIxIDE0LjgyMzJWNS43ODIyM0wyNC4zMzQgNS43MjM2M1YxNC4zOTI2Wk0zMi4yODIyIDE0LjQ3NTZDMzEuOTQ2IDE1LjA0OTIgMzEuNDY1OSAxNS43NTcxIDMxLjA5OTYgMTYuMjU0OUgzMi42MTkxQzMzLjA2NzMgMTUuNTIxMiAzMy4zNzUxIDE0LjkyOCAzMy41NDg4IDE0LjQ3NTZIMzIuMjgyMlpNMzQuODEwNSAxNS4zOTc1QzM0Ljg3OTEgMTUuNzEwMSAzNC45MzExIDE1Ljk5ODIgMzQuOTczNiAxNi4yNTQ5SDM2LjE4NjVMMzYuMTgxNiAxNi4yMzU0QzM2LjA2NjIgMTUuNzM4OCAzNS44OTg5IDE1LjAxOCAzNS43NDEyIDE0LjQ3NTZIMzQuNTI5M0wzNC44MTA1IDE1LjM5NzVaTTM2Ljk4MTQgMTQuNjUzM0MzNy4wOTg0IDE0Ljg3NyAzNy4yNDExIDE1LjE1MDEgMzcuMzMzIDE1LjQwMjNMMzcuNjM1NyAxNi4yNTQ5SDM5LjA4MDFDMzkuMDMzNiAxNS44MzI1IDM4LjU5NCAxNS4wNTUzIDM4LjIzODMgMTQuNDc1NkgzNi44ODg3QzM2LjkxNjEgMTQuNTI5OCAzNi45NDggMTQuNTg5NCAzNi45ODE0IDE0LjY1MzNaTTM5LjI3MDUgMTQuNDc1NkMzOS44MzAxIDE1LjE4MjEgNDAuMTg2MyAxNS44MDA0IDQwLjQxMzEgMTYuMjU0OUg0MS44MzVDNDEuNzM2NyAxNS42NjU2IDQxLjIyOTIgMTQuOTkzNiA0MC43NzY0IDE0LjQ3NTZIMzkuMjcwNVpNNDMuOTIyOSAxNS4wMDQ5SDQyLjc2NjZWMTUuOTk2MUg1My4xMjVWMTUuMDA0OUg1MS45Njg4VjEyLjQ3NTZINDMuOTIyOVYxNS4wMDQ5Wk0xMC43MDQxIDQuMDMwMjdDMTAuNTgxMSAzLjk1OTU4IDEwLjQ4MDUgNC4wMTc4IDEwLjQ4MDUgNC4xNTkxOFY5LjYyMzA1QzEwLjQ4MDYgOS42OTA3NCAxMC41MDc4IDkuNzU1NzggMTAuNTU1NyA5LjgwMzcxQzEwLjYwMzcgOS44NTE3MSAxMC42NjkzIDkuODc4ODcgMTAuNzM3MyA5Ljg3ODkxSDEyLjQ2NDhDMTIuNDk4NiA5Ljg3OTA1IDEyLjUzMjIgOS44NzIxNyAxMi41NjM1IDkuODU5MzhDMTIuNTk0NCA5Ljg0NjY2IDEyLjYyMjcgOS44MjgyMSAxMi42NDY1IDkuODA0NjlDMTIuNjcwNCA5Ljc4MDg5IDEyLjY5MDIgOS43NTE4NSAxMi43MDMxIDkuNzIwN0MxMi43MTYgOS42ODk3NSAxMi43MjI2IDkuNjU2NTQgMTIuNzIyNyA5LjYyMzA1VjguMTUyMzRDMTIuNzIyNyA4LjAxMSAxMi44MjIzIDcuOTUyODIgMTIuOTQ1MyA4LjAyMzQ0TDE0Ljc0MTIgOS4wNjE1MkMxNC44MDYgOS4xMDM2MiAxNC44NTk3IDkuMTYwNzcgMTQuODk4NCA5LjIyNzU0QzE0LjkzNzEgOS4yOTQzIDE0Ljk1OTYgOS4zNjkyOSAxNC45NjM5IDkuNDQ2MjlWMTUuMjU5OEMxNC45NjQxIDE1LjQwMDcgMTUuMDYzNyAxNS40NTcgMTUuMTg2NSAxNS4zODc3TDE2Ljk4NDQgMTQuMzUwNkMxNy4wNDkgMTQuMzA4NyAxNy4xMDMgMTQuMjUyMSAxNy4xNDE2IDE0LjE4NTVDMTcuMTgwMyAxNC4xMTg3IDE3LjIwMyAxNC4wNDMgMTcuMjA3IDEzLjk2NThWOC4wMjQ0MUMxNy4yMDI5IDcuOTQ3MzYgMTcuMTgwMyA3Ljg3MjQ2IDE3LjE0MTYgNy44MDU2NkMxNy4xMDI5IDcuNzM4ODQgMTcuMDQ5MyA3LjY4MTY0IDE2Ljk4NDQgNy42Mzk2NUwxMS44MjMyIDQuNjY3OTdDMTEuNzAwMiA0LjU5NzI4IDExLjU5NzcgNC41NDEwMiAxMS41OTc3IDQuNTQxMDJDMTEuNTg0NiA0LjUzMDQ3IDExLjQ4NzkgNC40ODIxMyAxMS4zNzIxIDQuNDE1MDRMMTAuNzA0MSA0LjAzMDI3Wk00Ni4yNDcxIDE1LjAwNDlINDUuMDkwOFYxMy4zMzY5SDQ2LjI0NzFWMTUuMDA0OVpNNDguNTI0NCAxNS4wMDQ5SDQ3LjM3OTlWMTMuMzM2OUg0OC41MjQ0VjE1LjAwNDlaTTUwLjgzNTkgMTUuMDA0OUg0OS42NTcyVjEzLjMzNjlINTAuODM1OVYxNS4wMDQ5Wk0zMi4wNjE1IDEwLjM2NTJIMzUuODAwOFYxMC45ODI0SDMxLjk4NjNWMTIuMDkwOEgzNS44MDA4VjEyLjc1NDlIMzEuMjUxVjEzLjgyNzFINDEuNzY1NlYxMi43NTQ5SDM3LjI2MjdWMTIuMDkwOEg0MS4wMjkzVjEwLjk4MjRIMzcuMjYyN1YxMC4zNjUySDM5Ljg1ODRDNDAuNDYzNCAxMC4zNjUyIDQwLjk1NCA5Ljg3NTQzIDQwLjk1NDEgOS4yNzE0OFY2LjAxNjZIMzIuMDYxNVYxMC4zNjUyWk0yMS4yNDQxIDguMzAzNzFDMjAuOTY4NiA5LjU3MTM4IDIwLjcxMzcgMTAuNTAxIDIwLjQ4MDUgMTEuMDkzOEMyMC4yNDcyIDExLjY4NjMgMTkuODEyNiAxMi41MDg2IDE5LjE3NDggMTMuNTYyNUwxOS4xMTUyIDEzLjY2MTFIMjAuNTc5MUwyMC41OTg2IDEzLjYzMzhDMjEuMzE2NiAxMi42MTg4IDIxLjgwNzUgMTEuNzYwNCAyMi4wNjc0IDExLjA1OTZDMjIuMzI1NyAxMC4zNjI4IDIyLjU4MzUgOS40NTMxMSAyMi44NDA4IDguMzMyMDNMMjIuODU4NCA4LjI1MjkzSDIxLjI1NDlMMjEuMjQ0MSA4LjMwMzcxWk0yNy4xOTA0IDguNjk4MjRDMjcuNDE5MiA5LjY1Mjc1IDI3LjY0ODMgMTAuNDQwMiAyNy44Nzc5IDExLjA1OTZDMjguMTM3OCAxMS43NjAzIDI4LjYyNzggMTIuNjE4OSAyOS4zNDU3IDEzLjYzMzhMMjkuMzY1MiAxMy42NjExSDMwLjgyOTFMMzAuNjE0MyAxMy4zMDQ3QzMwLjA2MDQgMTIuMzczNiAyOS42Nzc2IDExLjYzNjggMjkuNDYzOSAxMS4wOTM4QzI5LjIzMDYgMTAuNTAxIDI4Ljk3NTggOS41NzEzOCAyOC43MDAyIDguMzAzNzFMMjguNjg5NSA4LjI1MjkzSDI3LjA4NTlMMjcuMTkwNCA4LjY5ODI0Wk00NC4zNTQ1IDExLjg5MjZINTAuNDc2NkM1MS4wODE1IDExLjg5MjUgNTEuNTcyMSAxMS40MDI3IDUxLjU3MjMgMTAuNzk4OFY5LjM1MDU5SDQ0LjM1NDVWMTEuODkyNlpNNTAuNDI3NyAxMC40MDE0QzUwLjQyNzUgMTAuNzAzMiA1MC4xODIzIDEwLjk0ODIgNDkuODc5OSAxMC45NDgySDQ1LjQ5OVYxMC4yODMySDUwLjQyNzdWMTAuNDAxNFpNMzUuODAwOCA5LjI1NzgxSDMzLjI1MjlWNi45NDgyNEgzNS44MDA4VjkuMjU3ODFaTTM5Ljc2MzcgOC43MTA5NEMzOS43NjM1IDkuMDEyNjYgMzkuNTE4MSA5LjI1NzYgMzkuMjE1OCA5LjI1NzgxSDM3LjI2MjdWNi45NDgyNEgzOS43NjM3VjguNzEwOTRaTTQ3LjQ1NDEgNS41ODU5NEM0Ni4yMTQ0IDYuOTI4NCA0NC41Mzc1IDcuODYyNTcgNDIuNjQ5NCA4LjE2NDA2VjkuMDczMjRDNDMuNDc4NiA4Ljk1Mjc3IDQ0LjY1ODcgOC43NTU5OCA0NS4zNzExIDguNDA2MjVWOC43NDMxNkg1MC41NDM5VjguNDE3OTdDNTEuMTk3OCA4Ljc0NDM0IDUyLjQxMjIgOC45NDExMSA1My4yNzY0IDkuMDczMjRMNTMuMjc3MyA4LjE5NjI5QzUzLjI0OCA4LjE4Njc5IDUzLjIxODYgOC4xNzc1MiA1My4xODk1IDguMTY3OTdDNTEuMzA2IDcuODcyNjcgNDkuNjMxNiA2Ljk0OCA0OC4zODk2IDUuNjE2MjFMNDcuNDU0MSA1LjU4NTk0Wk0zMy42OTkyIDcuMTY3OTdDMzMuODU5OCA4LjIyNTk3IDM0LjQ2NTQgOS4wMjk4NiAzNC40Nzc1IDkuMDQ1OUgzNS40NTEyQzM1LjQ0NDIgOS4wMzEwOCAzNC45MzE2IDcuOTM5OTcgMzQuOTMxNiA3LjE2Nzk3SDMzLjY5OTJaTTM4LjExMTMgNy4xNjc5N0MzOC4xMTEzIDcuOTM3OCAzNy42MDE2IDkuMDI1MTEgMzcuNTkxOCA5LjA0NTlIMzguNTY1NEMzOC41ODE1IDkuMDI0NjUgMzkuMTgzNyA4LjIyMjQ0IDM5LjM0MzggNy4xNjc5N0gzOC4xMTEzWk00Ny45NjM5IDYuNjExMzNDNDguMzI1OSA3LjA0MjU0IDQ4Ljg3NDggNy40NzQwNiA0OS42MTA0IDcuOTA1MjdINDYuMjkzQzQ3LjA1MjEgNy40NjIyNSA0Ny42MDE4IDcuMDMxMDMgNDcuOTYzOSA2LjYxMTMzWiIgZmlsbD0id2hpdGUiLz4KPC9zdmc+Cg==",Rw="data:image/svg+xml;base64,PHN2ZyBwcmVzZXJ2ZUFzcGVjdFJhdGlvPSJub25lIiBvdmVyZmxvdz0idmlzaWJsZSIgc3R5bGU9ImRpc3BsYXk6IGJsb2NrOyIgd2lkdGg9IjEyIiBoZWlnaHQ9IjEyIiB2aWV3Qm94PSIwIDAgMTIgMTIiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxnIGlkPSIxLWNvbW1vbl9zZWFyY2hfbGluZV8yNHgyNCI+CjxnIGlkPSJ1bmlvbiI+CjxwYXRoIGZpbGwtcnVsZT0iZXZlbm9kZCIgY2xpcC1ydWxlPSJldmVub2RkIiBkPSJNNS44NjAxMyAxLjkyNTAxQzMuNzI4NzkgMS45MjUwMSAyLjAwMDAyIDMuNjU0NiAyLjAwMDAyIDUuNzg5MzdDMi4wMDAwMiA3LjkyNDEzIDMuNzI4NzkgOS42NTM3MiA1Ljg2MDEzIDkuNjUzNzJDNy45OTE0NyA5LjY1MzcyIDkuNzIwMjQgNy45MjQxMyA5LjcyMDI0IDUuNzg5MzdDOS43MjAyNCAzLjY1NDYgNy45OTE0NyAxLjkyNTAxIDUuODYwMTMgMS45MjUwMVpNMC44MDAwMjQgNS43ODkzN0MwLjgwMDAyNCAyLjk5Mjk0IDMuMDY0OTcgMC43MjUwMTIgNS44NjAxMyAwLjcyNTAxMkM4LjY1NTI5IDAuNzI1MDEyIDEwLjkyMDIgMi45OTI5NCAxMC45MjAyIDUuNzg5MzdDMTAuOTIwMiA4LjU4NTggOC42NTUyOSAxMC44NTM3IDUuODYwMTMgMTAuODUzN0MzLjA2NDk3IDEwLjg1MzcgMC44MDAwMjQgOC41ODU4IDAuODAwMDI0IDUuNzg5MzdaIiBmaWxsPSJ3aGl0ZSIvPgo8cGF0aCBmaWxsLXJ1bGU9ImV2ZW5vZGQiIGNsaXAtcnVsZT0iZXZlbm9kZCIgZD0iTTkuMDEzMTkgOC45MzQ5N0M5LjI0NzQgOC43MDA1NCA5LjYyNzExIDguNzAwNTQgOS44NjEzMiA4LjkzNDk3TDExLjA1MDggMTAuMTI1NkMxMS4yODUgMTAuMzYgMTEuMjg1IDEwLjc0MDEgMTEuMDUwOCAxMC45NzQ1QzEwLjgxNjYgMTEuMjA4OSAxMC40MzY5IDExLjIwODkgMTAuMjAyNyAxMC45NzQ1TDkuMDEzMTkgOS43ODM5QzguNzc4OTkgOS41NDk0OCA4Ljc3ODk5IDkuMTY5NCA5LjAxMzE5IDguOTM0OTdaIiBmaWxsPSJ3aGl0ZSIvPgo8L2c+CjwvZz4KPC9zdmc+Cg==",Lw="data:image/svg+xml;base64,PHN2ZyBwcmVzZXJ2ZUFzcGVjdFJhdGlvPSJub25lIiBvdmVyZmxvdz0idmlzaWJsZSIgc3R5bGU9ImRpc3BsYXk6IGJsb2NrOyIgd2lkdGg9IjY3IiBoZWlnaHQ9IjIyIiB2aWV3Qm94PSIwIDAgNjcgMjIiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxwYXRoIGlkPSJTdWJ0cmFjdCIgZD0iTTY2IDBDNjYuMzM3MiAwIDY2LjY3MDYgMC4wMTcxODM4IDY3IDAuMDQ2ODc1QzYxLjM5MzYgMC41NTIxODkgNTcgNS4yNjIwMiA1NyAxMUM1NyAxNi43MzggNjEuMzkzNiAyMS40NDY4IDY3IDIxLjk1MjFDNjYuNjcwNiAyMS45ODE4IDY2LjMzNzIgMjIgNjYgMjJIMTFDNC45MjQ4NyAyMiAwIDE3LjA3NTEgMCAxMUMwIDQuOTI0ODcgNC45MjQ4NyAyLjY1NzU2ZS0wNyAxMSAwSDY2Wk04LjI0MzE2IDYuNzM1MzVDOC4yNDMxNiA2LjU5Mzk3IDguMTQyNTggNi41MzU3NiA4LjAxOTUzIDYuNjA2NDVMNi4yMjI2NiA3LjY0MDYyQzYuMTU3ODcgNy42ODIyOCA2LjEwNDE2IDcuNzM5MTcgNi4wNjU0MyA3LjgwNTY2QzYuMDI2NzIgNy44NzIyNyA2LjAwNDEgNy45NDc1MiA2IDguMDI0NDFWMTMuOTY1OEM2LjAwMzcxIDE0LjA0MzQgNi4wMjU4NSAxNC4xMTkxIDYuMDY0NDUgMTQuMTg2NUM2LjEwMzE5IDE0LjI1NCA2LjE1NzQgMTQuMzEyIDYuMjIyNjYgMTQuMzU0NUw5Ljg3MTA5IDE2LjQ1OEM5Ljk5MzQ2IDE2LjUyNzIgMTAuMDkzNiAxNi41ODQyIDEwLjA5NDcgMTYuNTg1OUMxMC4wOTQ3IDE2LjU4NzEgMTAuMTkzNCAxNi42NDUxIDEwLjMxNjQgMTYuNzE1OEwxMi41MDEgMTcuOTY5N0MxMi42MjI4IDE4LjA0MDMgMTIuNzIzNiAxNy45ODIyIDEyLjcyMzYgMTcuODQwOFYxMi4zNjcyQzEyLjcyMyAxMi4yOTk0IDEyLjY5NTcgMTIuMjM0MyAxMi42NDc1IDEyLjE4NjVDMTIuNTk5MiAxMi4xMzg4IDEyLjUzMzggMTIuMTEyMyAxMi40NjU4IDEyLjExMjNIMTAuNzM3M0MxMC42NzAyIDEyLjExMzIgMTAuNjA1OSAxMi4xMzk5IDEwLjU1ODYgMTIuMTg3NUMxMC41MTEzIDEyLjIzNTIgMTAuNDg0NyAxMi4zMDAxIDEwLjQ4NDQgMTIuMzY3MlYxMy44Mzc5QzEwLjQ4NDIgMTMuOTc4OSAxMC4zODQ2IDE0LjAzNjQgMTAuMjYxNyAxMy45NjU4TDguNDY0ODQgMTIuOTM1NUM4LjQwMDI2IDEyLjg5MzUgOC4zNDYxNCAxMi44MzcyIDguMzA3NjIgMTIuNzcwNUM4LjI2OTE5IDEyLjcwNCA4LjI0NzM1IDEyLjYyOTQgOC4yNDMxNiAxMi41NTI3VjYuNzM1MzVaTTI0LjMzNCAxNC4zOTI2QzI0LjMzMzkgMTQuOTk4NSAyNC4yMDU1IDE1LjE4NDYgMjMuNTk4NiAxNS4xOTYzTDIyLjMwMTggMTUuMjU0OUwyMi42NjUgMTYuMjU0OUgyNS4wODY5QzI1LjY3MDUgMTYuMDg0IDI1Ljg3MjEgMTUuNzE5NCAyNS44NzIxIDE0LjgyMzJWNS43ODIyM0wyNC4zMzQgNS43MjM2M1YxNC4zOTI2Wk0zMi4yODIyIDE0LjQ3NTZDMzEuOTQ2IDE1LjA0OTIgMzEuNDY1OSAxNS43NTcxIDMxLjA5OTYgMTYuMjU0OUgzMi42MTkxQzMzLjA2NzMgMTUuNTIxMiAzMy4zNzUxIDE0LjkyOCAzMy41NDg4IDE0LjQ3NTZIMzIuMjgyMlpNMzQuODEwNSAxNS4zOTc1QzM0Ljg3OTEgMTUuNzEwMSAzNC45MzExIDE1Ljk5ODIgMzQuOTczNiAxNi4yNTQ5SDM2LjE4NjVMMzYuMTgxNiAxNi4yMzU0QzM2LjA2NjIgMTUuNzM4OCAzNS44OTg5IDE1LjAxOCAzNS43NDEyIDE0LjQ3NTZIMzQuNTI5M0wzNC44MTA1IDE1LjM5NzVaTTM2Ljk4MTQgMTQuNjUzM0MzNy4wOTg0IDE0Ljg3NyAzNy4yNDExIDE1LjE1MDEgMzcuMzMzIDE1LjQwMjNMMzcuNjM1NyAxNi4yNTQ5SDM5LjA4MDFDMzkuMDMzNiAxNS44MzI1IDM4LjU5NCAxNS4wNTUzIDM4LjIzODMgMTQuNDc1NkgzNi44ODg3QzM2LjkxNjEgMTQuNTI5OCAzNi45NDggMTQuNTg5NCAzNi45ODE0IDE0LjY1MzNaTTM5LjI3MDUgMTQuNDc1NkMzOS44MzAxIDE1LjE4MjEgNDAuMTg2MyAxNS44MDA0IDQwLjQxMzEgMTYuMjU0OUg0MS44MzVDNDEuNzM2NyAxNS42NjU2IDQxLjIyOTIgMTQuOTkzNiA0MC43NzY0IDE0LjQ3NTZIMzkuMjcwNVpNNDMuOTIyOSAxNS4wMDQ5SDQyLjc2NjZWMTUuOTk2MUg1My4xMjVWMTUuMDA0OUg1MS45Njg4VjEyLjQ3NTZINDMuOTIyOVYxNS4wMDQ5Wk0xMC43MDQxIDQuMDMwMjdDMTAuNTgxMSAzLjk1OTU4IDEwLjQ4MDUgNC4wMTc4IDEwLjQ4MDUgNC4xNTkxOFY5LjYyMzA1QzEwLjQ4MDYgOS42OTA3NCAxMC41MDc4IDkuNzU1NzggMTAuNTU1NyA5LjgwMzcxQzEwLjYwMzcgOS44NTE3MSAxMC42NjkzIDkuODc4ODcgMTAuNzM3MyA5Ljg3ODkxSDEyLjQ2NDhDMTIuNDk4NiA5Ljg3OTA1IDEyLjUzMjIgOS44NzIxNyAxMi41NjM1IDkuODU5MzhDMTIuNTk0NCA5Ljg0NjY2IDEyLjYyMjcgOS44MjgyMSAxMi42NDY1IDkuODA0NjlDMTIuNjcwNCA5Ljc4MDg5IDEyLjY5MDIgOS43NTE4NSAxMi43MDMxIDkuNzIwN0MxMi43MTYgOS42ODk3NSAxMi43MjI2IDkuNjU2NTQgMTIuNzIyNyA5LjYyMzA1VjguMTUyMzRDMTIuNzIyNyA4LjAxMSAxMi44MjIzIDcuOTUyODIgMTIuOTQ1MyA4LjAyMzQ0TDE0Ljc0MTIgOS4wNjE1MkMxNC44MDYgOS4xMDM2MiAxNC44NTk3IDkuMTYwNzcgMTQuODk4NCA5LjIyNzU0QzE0LjkzNzEgOS4yOTQzIDE0Ljk1OTYgOS4zNjkyOSAxNC45NjM5IDkuNDQ2MjlWMTUuMjU5OEMxNC45NjQxIDE1LjQwMDcgMTUuMDYzNyAxNS40NTcgMTUuMTg2NSAxNS4zODc3TDE2Ljk4NDQgMTQuMzUwNkMxNy4wNDkgMTQuMzA4NyAxNy4xMDMgMTQuMjUyMSAxNy4xNDE2IDE0LjE4NTVDMTcuMTgwMyAxNC4xMTg3IDE3LjIwMyAxNC4wNDMgMTcuMjA3IDEzLjk2NThWOC4wMjQ0MUMxNy4yMDI5IDcuOTQ3MzYgMTcuMTgwMyA3Ljg3MjQ2IDE3LjE0MTYgNy44MDU2NkMxNy4xMDI5IDcuNzM4ODQgMTcuMDQ5MyA3LjY4MTY0IDE2Ljk4NDQgNy42Mzk2NUwxMS44MjMyIDQuNjY3OTdDMTEuNzAwMiA0LjU5NzI4IDExLjU5NzcgNC41NDEwMiAxMS41OTc3IDQuNTQxMDJDMTEuNTg0NiA0LjUzMDQ3IDExLjQ4NzkgNC40ODIxMyAxMS4zNzIxIDQuNDE1MDRMMTAuNzA0MSA0LjAzMDI3Wk00Ni4yNDcxIDE1LjAwNDlINDUuMDkwOFYxMy4zMzY5SDQ2LjI0NzFWMTUuMDA0OVpNNDguNTI0NCAxNS4wMDQ5SDQ3LjM3OTlWMTMuMzM2OUg0OC41MjQ0VjE1LjAwNDlaTTUwLjgzNTkgMTUuMDA0OUg0OS42NTcyVjEzLjMzNjlINTAuODM1OVYxNS4wMDQ5Wk0zMi4wNjE1IDEwLjM2NTJIMzUuODAwOFYxMC45ODI0SDMxLjk4NjNWMTIuMDkwOEgzNS44MDA4VjEyLjc1NDlIMzEuMjUxVjEzLjgyNzFINDEuNzY1NlYxMi43NTQ5SDM3LjI2MjdWMTIuMDkwOEg0MS4wMjkzVjEwLjk4MjRIMzcuMjYyN1YxMC4zNjUySDM5Ljg1ODRDNDAuNDYzNCAxMC4zNjUyIDQwLjk1NCA5Ljg3NTQzIDQwLjk1NDEgOS4yNzE0OFY2LjAxNjZIMzIuMDYxNVYxMC4zNjUyWk0yMS4yNDQxIDguMzAzNzFDMjAuOTY4NiA5LjU3MTM4IDIwLjcxMzcgMTAuNTAxIDIwLjQ4MDUgMTEuMDkzOEMyMC4yNDcyIDExLjY4NjMgMTkuODEyNiAxMi41MDg2IDE5LjE3NDggMTMuNTYyNUwxOS4xMTUyIDEzLjY2MTFIMjAuNTc5MUwyMC41OTg2IDEzLjYzMzhDMjEuMzE2NiAxMi42MTg4IDIxLjgwNzUgMTEuNzYwNCAyMi4wNjc0IDExLjA1OTZDMjIuMzI1NyAxMC4zNjI4IDIyLjU4MzUgOS40NTMxMSAyMi44NDA4IDguMzMyMDNMMjIuODU4NCA4LjI1MjkzSDIxLjI1NDlMMjEuMjQ0MSA4LjMwMzcxWk0yNy4xOTA0IDguNjk4MjRDMjcuNDE5MiA5LjY1Mjc1IDI3LjY0ODMgMTAuNDQwMiAyNy44Nzc5IDExLjA1OTZDMjguMTM3OCAxMS43NjAzIDI4LjYyNzggMTIuNjE4OSAyOS4zNDU3IDEzLjYzMzhMMjkuMzY1MiAxMy42NjExSDMwLjgyOTFMMzAuNjE0MyAxMy4zMDQ3QzMwLjA2MDQgMTIuMzczNiAyOS42Nzc2IDExLjYzNjggMjkuNDYzOSAxMS4wOTM4QzI5LjIzMDYgMTAuNTAxIDI4Ljk3NTggOS41NzEzOCAyOC43MDAyIDguMzAzNzFMMjguNjg5NSA4LjI1MjkzSDI3LjA4NTlMMjcuMTkwNCA4LjY5ODI0Wk00NC4zNTQ1IDExLjg5MjZINTAuNDc2NkM1MS4wODE1IDExLjg5MjUgNTEuNTcyMSAxMS40MDI3IDUxLjU3MjMgMTAuNzk4OFY5LjM1MDU5SDQ0LjM1NDVWMTEuODkyNlpNNTAuNDI3NyAxMC40MDE0QzUwLjQyNzUgMTAuNzAzMiA1MC4xODIzIDEwLjk0ODIgNDkuODc5OSAxMC45NDgySDQ1LjQ5OVYxMC4yODMySDUwLjQyNzdWMTAuNDAxNFpNMzUuODAwOCA5LjI1NzgxSDMzLjI1MjlWNi45NDgyNEgzNS44MDA4VjkuMjU3ODFaTTM5Ljc2MzcgOC43MTA5NEMzOS43NjM1IDkuMDEyNjYgMzkuNTE4MSA5LjI1NzYgMzkuMjE1OCA5LjI1NzgxSDM3LjI2MjdWNi45NDgyNEgzOS43NjM3VjguNzEwOTRaTTQ3LjQ1NDEgNS41ODU5NEM0Ni4yMTQ0IDYuOTI4NCA0NC41Mzc1IDcuODYyNTcgNDIuNjQ5NCA4LjE2NDA2VjkuMDczMjRDNDMuNDc4NiA4Ljk1Mjc3IDQ0LjY1ODcgOC43NTU5OCA0NS4zNzExIDguNDA2MjVWOC43NDMxNkg1MC41NDM5VjguNDE3OTdDNTEuMTk3OCA4Ljc0NDM0IDUyLjQxMjIgOC45NDExMSA1My4yNzY0IDkuMDczMjRMNTMuMjc3MyA4LjE5NjI5QzUzLjI0OCA4LjE4Njc5IDUzLjIxODYgOC4xNzc1MiA1My4xODk1IDguMTY3OTdDNTEuMzA2IDcuODcyNjcgNDkuNjMxNiA2Ljk0OCA0OC4zODk2IDUuNjE2MjFMNDcuNDU0MSA1LjU4NTk0Wk0zMy42OTkyIDcuMTY3OTdDMzMuODU5OCA4LjIyNTk3IDM0LjQ2NTQgOS4wMjk4NiAzNC40Nzc1IDkuMDQ1OUgzNS40NTEyQzM1LjQ0NDIgOS4wMzEwOCAzNC45MzE2IDcuOTM5OTcgMzQuOTMxNiA3LjE2Nzk3SDMzLjY5OTJaTTM4LjExMTMgNy4xNjc5N0MzOC4xMTEzIDcuOTM3OCAzNy42MDE2IDkuMDI1MTEgMzcuNTkxOCA5LjA0NTlIMzguNTY1NEMzOC41ODE1IDkuMDI0NjUgMzkuMTgzNyA4LjIyMjQ0IDM5LjM0MzggNy4xNjc5N0gzOC4xMTEzWk00Ny45NjM5IDYuNjExMzNDNDguMzI1OSA3LjA0MjU0IDQ4Ljg3NDggNy40NzQwNiA0OS42MTA0IDcuOTA1MjdINDYuMjkzQzQ3LjA1MjEgNy40NjIyNSA0Ny42MDE4IDcuMDMxMDMgNDcuOTYzOSA2LjYxMTMzWiIgZmlsbD0iYmxhY2siLz4KPC9zdmc+Cg==",Pw="data:image/svg+xml;base64,PHN2ZyBwcmVzZXJ2ZUFzcGVjdFJhdGlvPSJub25lIiBvdmVyZmxvdz0idmlzaWJsZSIgc3R5bGU9ImRpc3BsYXk6IGJsb2NrOyIgd2lkdGg9IjEyIiBoZWlnaHQ9IjEyIiB2aWV3Qm94PSIwIDAgMTIgMTIiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxnIGlkPSIxLWNvbW1vbl9zZWFyY2hfbGluZV8yNHgyNCI+CjxnIGlkPSJ1bmlvbiI+CjxwYXRoIGZpbGwtcnVsZT0iZXZlbm9kZCIgY2xpcC1ydWxlPSJldmVub2RkIiBkPSJNNS44NjAxMyAxLjkyNTAxQzMuNzI4NzkgMS45MjUwMSAyLjAwMDAyIDMuNjU0NiAyLjAwMDAyIDUuNzg5MzdDMi4wMDAwMiA3LjkyNDEzIDMuNzI4NzkgOS42NTM3MiA1Ljg2MDEzIDkuNjUzNzJDNy45OTE0NyA5LjY1MzcyIDkuNzIwMjQgNy45MjQxMyA5LjcyMDI0IDUuNzg5MzdDOS43MjAyNCAzLjY1NDYgNy45OTE0NyAxLjkyNTAxIDUuODYwMTMgMS45MjUwMVpNMC44MDAwMjQgNS43ODkzN0MwLjgwMDAyNCAyLjk5Mjk0IDMuMDY0OTcgMC43MjUwMTIgNS44NjAxMyAwLjcyNTAxMkM4LjY1NTI5IDAuNzI1MDEyIDEwLjkyMDIgMi45OTI5NCAxMC45MjAyIDUuNzg5MzdDMTAuOTIwMiA4LjU4NTggOC42NTUyOSAxMC44NTM3IDUuODYwMTMgMTAuODUzN0MzLjA2NDk3IDEwLjg1MzcgMC44MDAwMjQgOC41ODU4IDAuODAwMDI0IDUuNzg5MzdaIiBmaWxsPSJibGFjayIvPgo8cGF0aCBmaWxsLXJ1bGU9ImV2ZW5vZGQiIGNsaXAtcnVsZT0iZXZlbm9kZCIgZD0iTTkuMDEzMTkgOC45MzQ5N0M5LjI0NzQgOC43MDA1NCA5LjYyNzExIDguNzAwNTQgOS44NjEzMiA4LjkzNDk3TDExLjA1MDggMTAuMTI1NkMxMS4yODUgMTAuMzYgMTEuMjg1IDEwLjc0MDEgMTEuMDUwOCAxMC45NzQ1QzEwLjgxNjYgMTEuMjA4OSAxMC40MzY5IDExLjIwODkgMTAuMjAyNyAxMC45NzQ1TDkuMDEzMTkgOS43ODM5QzguNzc4OTkgOS41NDk0OCA4Ljc3ODk5IDkuMTY5NCA5LjAxMzE5IDguOTM0OTdaIiBmaWxsPSJibGFjayIvPgo8L2c+CjwvZz4KPC9zdmc+Cg==";async function vw(e,t,r,n,i="dark"){Oe(n);const s=e.defaultView;if(!s||!e.body)throw new Error("截图水印缺少可用的展示窗口");const a=e.createElement("div"),c=i==="light",u=c?"black":"white";a.dataset.miniProgramScreenshotWatermark="",a.setAttribute("aria-hidden","true");const d=Math.min(1,r.width/200,r.height/57);a.style.cssText=`position:absolute;left:${r.left+s.scrollX}px;top:${r.top+s.scrollY+r.height-57*d}px;width:${r.width}px;height:${57*d}px;z-index:2147483647;pointer-events:none;overflow:hidden;`;const l=e.createElement("div");l.style.cssText=`display:flex;flex-direction:column;align-items:center;width:max-content;max-width:${r.width/d-24}px;transform:scale(${d});transform-origin:top left;font-family:"PingFang SC",sans-serif;`;const h=e.createElement("div");h.style.cssText="display:flex;align-items:center;max-width:100%;height:22px;flex-shrink:0;";const f=e.createElement("img");f.src=c?Lw:Cw,f.style.cssText="width:67px;height:22px;flex-shrink:0;margin-right:-11px;";const p=e.createElement("div");p.style.cssText=`display:flex;align-items:center;gap:2px;min-width:0;height:22px;box-sizing:border-box;border:1.5px solid ${u};border-radius:11px;padding:0 7px 0 6px;`;const g=e.createElement("img");g.src=c?Pw:Rw,g.style.cssText="width:12px;height:12px;flex-shrink:0;";const b=e.createElement("span");b.textContent=t?.trim()||"小程序工坊",b.style.cssText=`color:${u};font-size:11px;font-weight:500;line-height:16px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;`;const y=e.createElement("div");y.textContent="小黑盒工坊小程序",y.style.cssText=`margin-top:6px;color:${c?"rgba(0,0,0,0.4)":"rgba(255,255,255,0.4)"};font-size:11px;font-weight:400;line-height:16px;white-space:nowrap;`,p.append(g,b),h.append(f,p),l.append(h,y),a.append(l),e.body.append(a);const N=()=>{a.remove(),n.removeEventListener("abort",N)};n.addEventListener("abort",N,{once:!0});try{await be(()=>Promise.all([f.decode(),g.decode()]),n);const C=l.getBoundingClientRect();return a.style.left=`${r.left+s.scrollX+(r.width-C.width)/2}px`,a.style.width=`${C.width}px`,a.style.height=`${C.height}px`,l.style.width=`${C.width/d}px`,l.style.height=`${C.height/d}px`,l.style.maxWidth="none",await be(()=>new Promise(I=>{let U=s.requestAnimationFrame(()=>{U=s.requestAnimationFrame(()=>{n.removeEventListener("abort",Y),I()})});const Y=()=>s.cancelAnimationFrame(U);n.addEventListener("abort",Y,{once:!0})}),n),N}catch(C){throw N(),C}}const kw=new Set(["base-uri","child-src","connect-src","default-src","font-src","form-action","frame-src","img-src","manifest-src","media-src","object-src","prefetch-src","script-src","script-src-attr","script-src-elem","style-src","style-src-attr","style-src-elem","worker-src"]),xw=new Set(["url","inline","eval","unknown"]),Uw=/^\/(?:\:segment(?:\/\:segment)*)?$/,Bw=/^[a-f0-9]{64}$/,Hw=255,Fw=160,zw=256;function jw(e,t){const r=e;if(!r||typeof r.sdkVersion!="string"||r.sdkVersion!==t||typeof r.effectiveDirective!="string"||!kw.has(r.effectiveDirective)||typeof r.violatedDirective!="string"||r.violatedDirective.length>zw||r.violatedDirective.split(/\s/,1)[0]!==r.effectiveDirective||!["enforce","report"].includes(r.disposition??"")||typeof r.blockedResourceType!="string"||!xw.has(r.blockedResourceType)||typeof r.timestamp!="number"||!Number.isFinite(r.timestamp)||r.timestamp<0)return;const n=Vw(r.blockedOrigin);if(r.blockedOrigin!==void 0&&!n)return;const i=r.redactedPathname;if(i!==void 0&&(typeof i!="string"||i.length>Fw||!Uw.test(i)))return;const s=r.sanitizedPathnameHash;if(!(s!==void 0&&(typeof s!="string"||!Bw.test(s)||i===void 0)))return{effectiveDirective:r.effectiveDirective,violatedDirective:r.effectiveDirective,blockedResourceType:r.blockedResourceType,origin:n,sanitizedPathname:i,sanitizedPathnameHash:s,sdkVersion:r.sdkVersion,timestamp:r.timestamp}}function Vw(e){if(e!==void 0&&!(typeof e!="string"||e.length>Hw))try{const t=new URL(e);return["http:","https:"].includes(t.protocol)&&t.origin===e?t.origin:void 0}catch{return}}const ba=["android","ios","ohos","windows","macos","linux"],Gw="0.9.0",Yw=Object.freeze(["android","ios","ohos","windows","macos"]),Hh="该小程序暂不支持当前平台",Qw="PLATFORM_UNSUPPORTED";function qw(e){return typeof e=="string"&&ba.includes(e)}function Ww(e){if(typeof e!="string")return;const t=e.trim().toLowerCase().replace(/[\s_-]/g,"");if(t==="android")return"android";if(t==="ios")return"ios";if(t==="ohos"||t==="harmony"||t==="harmonyos")return"ohos";if(t==="windows"||t==="win32"||t==="win64")return"windows";if(t==="mac"||t==="macos"||t==="darwin")return"macos";if(t==="linux")return"linux"}function $w(e){const t=e.manifest;if(!eD(t))return{status:"invalid",reason:"manifest_not_object"};if(!Object.prototype.hasOwnProperty.call(t,"platforms")){const n=zd(e.sdkVersion)??zd(t.sdkVersion);return Xw(n)?{status:"invalid",reason:"platforms_missing_after_hard_cutover"}:Zw()}const r=Fh(t.platforms);return"reason"in r?{status:"invalid",reason:r.reason}:{status:"resolved",declaredPlatforms:r.platforms,effectivePlatforms:r.platforms,platformsDeclared:!0,policy:"explicit"}}function Kw(e){const t=Ww(e.operatingSystemName);if(!t)return Vr("host_operating_system_unknown");const r=e.platformAccess;if(!r)return Vr("platform_access_missing",{platform:t});if(r.source==="compatibility-window")return{status:"allowed",platform:t,effectivePlatforms:ba,platformsDeclared:!1,policy:"legacy_mobile_default",compatibility:r.reason};if(r.source==="manifest"){const a=$w({manifest:r.manifest,...r.sdkVersion===void 0?{}:{sdkVersion:r.sdkVersion}});return a.status==="invalid"?Vr("platform_declaration_invalid",{invalidReason:a.reason,platform:t}):Fd(t,a)}if(r.effectivePlatforms===void 0)return Vr("platform_declaration_invalid",{invalidReason:"effective_platforms_missing",platform:t});const n=Fh(r.effectivePlatforms);if("reason"in n)return Vr("platform_declaration_invalid",{invalidReason:n.reason,platform:t});const i=typeof r.platformsDeclared=="boolean"?r.platformsDeclared:!0,s=Jw(r.platformPolicy)?r.platformPolicy:i?"explicit":"legacy_mobile_default";return Fd(t,{declaredPlatforms:i?n.platforms:[],effectivePlatforms:n.platforms,platformsDeclared:i,policy:s})}function Fd(e,t){return t.effectivePlatforms.includes(e)?{status:"allowed",platform:e,effectivePlatforms:t.effectivePlatforms,platformsDeclared:t.platformsDeclared,policy:t.policy}:Vr("platform_not_supported",{effectivePlatforms:t.effectivePlatforms,platform:e})}function Vr(e,t={}){return{status:"denied",reason:e,message:Hh,...t}}function Zw(){return{status:"resolved",declaredPlatforms:[],effectivePlatforms:Yw,platformsDeclared:!1,policy:"legacy_mobile_default"}}function Fh(e){if(!Array.isArray(e))return{reason:"platforms_not_array"};if(e.length===0)return{reason:"platforms_empty"};const t=new Set;for(const r of e){if(!qw(r))return{reason:"platform_unknown_value"};if(t.has(r))return{reason:"platform_duplicate_value"};t.add(r)}return{platforms:Object.freeze(ba.filter(r=>t.has(r)))}}function Xw(e){if(typeof e!="string"||!e.trim())return!1;const t=_c(e.trim(),Gw);return t!==void 0&&t>=0}function zd(e){return typeof e=="string"&&e.trim()?e.trim():void 0}function Jw(e){return e==="explicit"||e==="legacy_mobile_default"}function eD(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function tD(e,t,r){const n=Date.now();try{const i=new URL(t);return{type:"security_violation",errorCode:e,timestamp:n,sdkVersion:r,origin:i.origin,sanitizedPathname:rD(i.pathname),sanitizedPathnameHash:dc(i.pathname)}}catch{return{type:"security_violation",errorCode:e,timestamp:n,sdkVersion:r}}}function rD(e){return(e==="/"?e:e.replace(/\/+$/,"")).split("/").map(r=>r?":segment":"").join("/")}const nD=1e4,iD=3e4,sD=1e4,qa=2e3,aD=2,oD="open-with-native-credential-policy",zh="安全提示",jh="即将打开未经验证的开发网页。该页面可能由本机或局域网服务提供,请确认来源可信后继续。";class cD{nonce=uu();runtimeId=uu();terminalController=new AbortController;options;handshakeTimeout;ports;primitiveAvailability;effectiveCapabilities;identity;identityRef;iframe;iframeErrorListener;iframeLoadListener;bridgeServer=null;miniProgramSrc="";launchUrl="";startPromise=null;readyContext=null;resolveReady;rejectReady;terminalError;status="idle";stateValue="idle";handshakeTimeoutTimer;lifecycleDisposer;workspaceCardsDisposer;capabilityGraph;iframeTornDown=!1;runtimeResourcesDisposed=!1;failureTransitionInProgress=!1;destroyRequestedDuringFailure=!1;sdkVersionDecision;platformGateDecision;compatibilityWithoutSdk=!1;heartbeatTimer;pendingProbeId;consecutiveHeartbeatMisses=0;probeSequence=0;hostVisible=!0;awaitingControlledDocumentLoad=!1;awaitingDevelopmentDocumentLoad=!1;unexpectedDocumentLoadTimer;devDocumentDisposer;documentRevalidationPending=!1;documentRevalidationTimer;documentRevalidationGeneration=0;preparedHistoryTraversalGeneration;iframeVisibilityBeforeRevalidation;iframeHiddenForRevalidation=!1;devRuntimePromise;runtimePermissions=void 0;firstParty=!1;networkPolicy;networkPolicyDisposer;runtimeFeatures;miniProgramPresentation;miniProgramDetail;locationBasePath;anonymousStorageScope;allowedHttpOrigins;allowDevelopmentHttp=!1;environmentInfo;constructor(t){this.options=t,this.iframe=t.iframe;const r=ql(t.ports,{callerCapabilities:t.capabilities,hostCapabilities:t.hostCapabilities,hasUserDataPresentation:t.userDataPresentation!==void 0,hasUserDataSettings:t.userDataPresentation?.openDataPermissions!==void 0});this.ports=r.ports,this.primitiveAvailability=r.primitiveAvailability,this.effectiveCapabilities=r.effectiveCapabilities,this.identity={},this.identityRef={get:()=>{const n=this.identity.miniProgramId?.trim();if(n)return{miniProgramId:n,...this.identity.miniProgramVersion?{version:this.identity.miniProgramVersion}:{}}}},this.handshakeTimeout=t.handshakeTimeout??nD,this.iframeErrorListener=n=>{this.onIframeError(n)},this.iframeLoadListener=()=>{if(this.awaitingControlledDocumentLoad){if(this.awaitingControlledDocumentLoad=!1,this.awaitingDevelopmentDocumentLoad&&(this.awaitingDevelopmentDocumentLoad=!1,this.stateValue==="starting"&&this.armHandshakeTimeout()),this.stateValue==="ready"&&this.bridgeServer?.protocolVersion===2&&this.sdkVersionDecision?.heartbeatEnabled){this.beginDocumentRevalidation();return}this.compatibilityWithoutSdk&&!this.readyContext&&this.completeCompatibilityLaunch();return}this.stateValue==="ready"&&(this.bridgeServer?.protocolVersion===2&&this.sdkVersionDecision?.heartbeatEnabled?this.beginDocumentRevalidation():this.scheduleUnexpectedDocumentLoadFailure())},this.iframe.addEventListener("error",this.iframeErrorListener),this.iframe.addEventListener("load",this.iframeLoadListener)}get state(){return this.stateValue}getMiniProgramDetail(){return this.miniProgramDetail}getDataPermissionBridge(){return this.capabilityGraph?.permissionBridge}get diagnostics(){const t=this.capabilityGraph?.storageDiagnostics,r=this.capabilityGraph?.sandboxDiagnostics,n=this.capabilityGraph?.gameSaveDiagnostics;return{...t?{storage:t}:{},...r?{sandbox:r}:{},...n?{gameSaves:n}:{}}}start(){return this.stateValue==="destroyed"?Promise.reject(this.terminalError??Me("RUNTIME_DESTROYED","小程序运行时已销毁")):this.stateValue==="failed"?Promise.reject(this.terminalError??Me("STARTUP_ERROR","小程序运行时启动失败")):this.readyContext?Promise.resolve(this.readyContext):this.startPromise?this.startPromise:(AD(),this.startPromise=this.createReadyPromise(),this.setState("starting"),this.setStatus("starting"),this.launch().catch(t=>{this.failRuntime(t)}),this.startPromise)}destroy(){if(this.failureTransitionInProgress){this.destroyRequestedDuringFailure=!0;return}if(this.stateValue==="destroyed")return;const t=this.terminalError??Me("RUNTIME_DESTROYED","小程序运行时已销毁");this.terminalError=t,this.terminalController.abort(t),this.disposeRuntimeResources(),this.setStatus("destroyed"),this.setState("destroyed"),this.teardownIframe(),this.rejectReady?.(t)}show(){const t=this.hostVisible;this.hostVisible=!0,this.capabilityGraph?.setPostVisible(!0),this.emitLifecycleEvent("show"),this.capabilityGraph?.notifyViewportChange(),!t&&this.stateValue==="ready"&&this.sdkVersionDecision?.heartbeatEnabled&&(this.documentRevalidationPending?this.preparedHistoryTraversalGeneration!==void 0?this.armDocumentRevalidationTimer(this.documentRevalidationGeneration,{waitingForDocument:!0}):this.resendDocumentRevalidationProbe():this.sendLocationProbe())}hide(){this.hostVisible=!1,this.capabilityGraph?.setPostVisible(!1),this.clearHeartbeat(),this.clearDocumentRevalidationTimer(),this.emitLifecycleEvent("hide")}prepareForHistoryTraversal(){if(this.stateValue!=="ready"||this.bridgeServer?.protocolVersion!==2||!this.sdkVersionDecision?.heartbeatEnabled)return()=>{};const t=this.beginDocumentRevalidation({deferProbe:!0});return this.isInactive()||t!==this.documentRevalidationGeneration?()=>{}:(this.preparedHistoryTraversalGeneration=t,()=>{this.preparedHistoryTraversalGeneration===t&&this.cancelPreparedHistoryTraversal()})}createReadyPromise(){return new Promise((t,r)=>{this.resolveReady=t,this.rejectReady=r})}async launch(){const t=await this.resolveRuntimeLaunchConfiguration();if(this.isInactive())return;if(this.runtimePermissions=kg(t.runtimePermissions),this.firstParty=t.firstParty===!0,this.networkPolicy=this.firstParty?void 0:Wl(t.networkPolicy),this.networkPolicy?.enforcement==="restricted"){const a=t.canonicalIdentity?.miniProgramId?.trim();if(!a||!this.options.networkPolicyEnforcement)throw{code:"NETWORK_POLICY_UNSUPPORTED",message:"当前 Host 尚未具备严格网络策略执行能力,请更新 Host 后重新打开"};const c=await pg(this.options.networkPolicyEnforcement,{policy:this.networkPolicy,miniProgramId:a,launchUrl:t.launchUrl,onInvalidated:()=>this.failRuntime({code:"NETWORK_POLICY_CHANGED",message:"网络权限已变更,请重新打开小程序"})},{signal:this.terminalController.signal});if(this.isInactive()){c();return}this.networkPolicyDisposer=c}this.runtimeFeatures=t.runtimeFeatures?Object.freeze({...t.runtimeFeatures}):void 0,this.miniProgramPresentation=t.miniProgramPresentation,this.locationBasePath=t.locationBasePath,this.anonymousStorageScope=t.anonymousStorageScope??this.options.anonymousStorageScope;const r=t.allowedHttpOrigins??this.options.allowedHttpOrigins;this.allowedHttpOrigins=r?Object.freeze([...r]):void 0,this.bindCanonicalIdentity(t.canonicalIdentity),this.sdkVersionDecision=yp(t.sdkVersionPolicy),this.allowDevelopmentHttp=t.sdkVersionPolicy?.releaseChannel==="development";const n=Dw(t,this.identity);if(this.environmentInfo=n.info,n.invalidFields.length>0&&this.trace({runtimeId:this.runtimeId,timestamp:Date.now(),type:"environment_invalid",message:`环境字段已降级:${n.invalidFields.join(", ")}`}),this.platformGateDecision=Kw({operatingSystemName:t.environmentInfo?.operatingSystem?.name,...t.platformAccess===void 0?{}:{platformAccess:t.platformAccess}}),this.platformGateDecision.status==="denied")throw yD(this.platformGateDecision);if(this.miniProgramDetail=ND(t),this.effectiveCapabilities=Ql(this.primitiveAvailability,{callerCapabilities:this.options.capabilities,hostCapabilities:this.options.hostCapabilities,miniProgramDetail:this.miniProgramDetail}),console.info("[hb-sdk-runtime] host capability",Object.freeze({filesAccessPrimitive:this.primitiveAvailability["files.access"],callerFileCreate:this.options.capabilities?.["file.create"]??"default",hostFileCreate:this.options.hostCapabilities?.["file.create"]??"default",canonicalMiniProgramDetail:!!this.miniProgramDetail?.miniProgramId.trim(),effectiveFileCreate:this.effectiveCapabilities["file.create"]===!0})),this.compatibilityWithoutSdk=!!(t.sdkVersionPolicy&&t.sdkVersionPolicy.releaseChannel!==void 0&&!this.sdkVersionDecision.sdkVersion&&!this.sdkVersionDecision.heartbeatEnabled),ED(this.options.onLaunchConfigurationResolved,t,this.sdkVersionDecision),this.isInactive())return;this.applyIframeDefaults(),this.startBridgeServer(),this.installSubscriptions();const i=await this.normalizeLaunchUrl(t.launchUrl);if(this.isInactive())return;const s=await this.confirmDevMiniProgramLaunch(i);if(!this.isInactive()){if(!s){await this.closeAfterDevLaunchCancellation();return}if(this.bridgeServer?.setTargetOrigin(pD(i)),this.launchUrl=i,this.options.onDevDocumentReload&&t.sdkVersionPolicy?.releaseChannel==="development"){const a=$l(new URL(i),this.locationBasePath);this.devDocumentDisposer=vg({iframe:this.iframe,launchUrl:i,nonce:this.nonce,locationBasePath:a,onLeaving:()=>{this.prepareForHistoryTraversal()},onResume:()=>{!this.isInactive()&&this.documentRevalidationPending&&this.beginDocumentRevalidation()},onReload:c=>{this.isInactive()||yt(u=>this.options.onDevDocumentReload?.(u,a),c)}})}if(this.miniProgramSrc=Dg(i,this.nonce),this.traceSecurityPolicy(i),this.setStatus("src_resolved"),this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"src_resolved"}),this.primitiveAvailability["presentation.applyOrientation"]){try{await this.capabilityGraph?.applyOrientation({mode:"portrait",hideCapsule:!1})}catch(a){if(this.isInactive())return;const c=vs(a);this.trace({runtimeId:this.runtimeId,timestamp:Date.now(),type:"error",method:wr,errorCode:c.code,message:`默认展示设置失败,沿用宿主当前布局:${c.message}`})}if(this.isInactive())return}this.awaitingDevelopmentDocumentLoad=t.sdkVersionPolicy?.releaseChannel==="development",this.awaitingControlledDocumentLoad=!0,this.iframe.src=this.miniProgramSrc,yt(this.options.onLaunch,this.createLaunchContext()),this.armHandshakeTimeout(this.awaitingDevelopmentDocumentLoad)}}startBridgeServer(){const t={postEvent:(n,i)=>{this.stateValue==="ready"&&(n!=="viewport_change"||this.effectiveCapabilities["viewport.getWindowInfo"])&&(n!=="display_change"||this.effectiveCapabilities[wr])&&this.bridgeServer?.postEvent(n,i)}};this.capabilityGraph=Tw({verifiedSdkVersion:this.sdkVersionDecision?.sdkVersion,diagnosticCapabilities:this.effectiveCapabilities,account:this.ports.account,network:this.ports.network,files:this.ports.files,picker:this.ports.picker,media:this.ports.media,transfer:this.ports.transfer,storage:this.ports.storage,scopedStorage:this.ports.scopedStorage,storageDiagnostics:this.ports.storageDiagnostics,hostPresentation:this.ports.presentation,hostCompanion:this.ports.companion,hostProtocol:this.ports.protocol,...this.options.userDataPresentation===void 0?{}:{userDataPresentation:this.options.userDataPresentation},...this.options.onUserDataTelemetry===void 0?{}:{onUserDataTelemetry:this.options.onUserDataTelemetry},workspaceCards:this.ports.workspaceCards,environment:this.options.environment,identity:this.identityRef,runtimePermissions:this.runtimePermissions,runtimeFeatures:this.runtimeFeatures,networkPolicy:this.networkPolicy,firstParty:this.firstParty,authorizationContext:this.options.authorizationContext,terminalSignal:this.terminalController.signal,eventSink:t,authPresentation:this.options.authPresentation,companionPresentation:this.options.companionPresentation,miniProgramPresentation:this.miniProgramPresentation,prepareLongScreenshot:(n,i)=>gg(this.iframe,n,i),prepareScreenshot:(n,i,s)=>{const a=this.sdkVersionDecision?.sdkVersion;return!a||(_c(a,"0.9.1")??-1)<0?Promise.resolve(()=>{}):vw(this.iframe.ownerDocument,this.miniProgramPresentation?.name,n,i,s)},miniProgramDetail:this.miniProgramDetail,anonymousStorageScope:this.anonymousStorageScope,storageLimits:this.options.storageLimits,allowedHttpOrigins:this.allowedHttpOrigins,allowDevelopmentHttp:this.allowDevelopmentHttp,requestPolicy:this.options.requestPolicy,onBackgroundError:(n,i)=>{const s=vs(i);this.trace({runtimeId:this.runtimeId,timestamp:Date.now(),type:"error",errorCode:s.code,message:`后台任务 ${n} 失败:${s.message}`})},...this.options.onRequestPolicyReport?{onRequestPolicyReport:this.options.onRequestPolicyReport}:{}}),this.capabilityGraph.setPostVisible(this.hostVisible);const r=mw({handlers:this.capabilityGraph.handlers,runDisplayRequest:this.capabilityGraph.runDisplayRequest,effectiveCapabilities:this.effectiveCapabilities,runtimePermissions:this.runtimePermissions,terminalSignal:this.terminalController.signal,allowsCompanionAttachmentAccess:this.capabilityGraph.allowsCompanionAttachmentAccess,allowsGameSaveAccess:this.capabilityGraph.allowsGameSaveAccess,allowsUserGameDataFileAccess:this.capabilityGraph.allowsUserGameDataFileAccess,policies:this.options.policies,...this.options.onCapabilityTrace?{onTrace:({callId:n,method:i,startedAt:s,timestamp:a,durationMs:c,outcome:u,errorCode:d,network:l})=>{const h={type:"capability",phase:"host",runtimeId:this.runtimeId,callId:n,method:i,startedAt:s,timestamp:a,durationMs:c,outcome:u,...d?{errorCode:d}:{},...this.identity,...l?{network:l}:{}};yt(this.options.onCapabilityTrace,h)}}:{}});this.bridgeServer=new Fg({iframe:this.iframe,nonce:this.nonce,dispatcher:r,environmentInfo:this.environmentInfo,...this.options.onDevUploadSession?{onDevUploadSession:n=>{this.isInactive()||yt(this.options.onDevUploadSession,n)}}:{},...this.ports.workspaceCards?{getWorkspaceCardLaunchContext:()=>this.ports.workspaceCards.getLaunchContext()}:{},onHandshake:n=>this.handleBridgeHandshake(n),onReady:()=>{this.handleBridgeReady()},onDuplicateHandshake:()=>{this.handleDuplicateBridgeHandshake()},onInternalEvent:n=>{this.handleInternalBridgeEvent(n)},onResponsePosted:({method:n,outcome:i,errorCode:s})=>{this.trace({runtimeId:this.runtimeId,timestamp:Date.now(),type:"bridge_response",method:n,outcome:i,...s?{errorCode:s}:{}})}}),this.bridgeServer.start(),this.workspaceCardsDisposer=this.ports.workspaceCards?.onLaunchContextChange(()=>this.publishWorkspaceCardLaunchContext()),this.setStatus("bridge_started"),this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"bridge_started"})}onIframeError(t=new Error("小程序 iframe 加载失败")){if(this.isInactive())return;const r=t instanceof Error?t.message:"小程序 iframe 加载失败";this.failRuntime(Me("IFRAME_LOAD_ERROR",r,t))}emitLifecycleEvent(t){if(this.stateValue!=="ready"){this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"lifecycle_ignored",event:t,reason:this.isInactive()?"inactive":"not_ready"});return}this.bridgeServer?.postEvent(t,{timestamp:Date.now()}),this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"lifecycle",method:t})}async resolveRuntimeLaunchConfiguration(){try{return await this.options.resolveLaunchConfiguration()}catch(t){throw mD(t)?t:Vh(Me("STARTUP_ERROR",t instanceof Error?t.message:"获取小程序启动配置失败"),t)}}bindCanonicalIdentity(t){const r=t?.miniProgramId?.trim();r&&(this.identity.miniProgramId=r);const n=t?.miniProgramVersion?.trim();n&&(this.identity.miniProgramVersion=n)}async normalizeLaunchUrl(t){try{const r=this.options.environment.getCurrentHref();return wg(t,r,{allowPrivateNetwork:Hd(r)||jd(r)||await this.isDevRuntime()})}catch(r){throw Me("INVALID_LAUNCH_URL",r instanceof Error?r.message:"小程序链接不合法",r)}}async confirmDevMiniProgramLaunch(t){return await this.shouldConfirmDevMiniProgramLaunch(t)?this.isInactive()?!1:!!await(this.options.confirmDevMiniProgramLaunch??_D)({message:jh,title:zh,url:t}):!0}async shouldConfirmDevMiniProgramLaunch(t){if(lu(t)==="production")return!1;const r=this.options.environment.getCurrentHref();return!Hd(r)&&!jd(r)}async closeAfterDevLaunchCancellation(){const t=Me("LAUNCH_CANCELLED","小程序启动已取消");this.terminalError=t,this.destroyBridgeServer();const r=new AbortController;let n;try{n=Promise.resolve(this.ports.presentation.close({signal:r.signal}))}catch{Vd(),n=Promise.resolve()}this.terminalController.abort(t),this.disposeRuntimeResources(),this.setStatus("destroyed"),this.setState("destroyed"),this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"launch_cancelled"}),this.rejectReady?.(t),await n.catch(()=>Vd())}async isDevRuntime(){return this.devRuntimePromise??=Promise.resolve().then(()=>this.options.environment.isDevRuntime()).then(Boolean).catch(()=>!1),this.devRuntimePromise}applyIframeDefaults(){this.iframe.setAttribute("allow",Ig),this.iframe.setAttribute("referrerpolicy",bg),this.iframe.setAttribute("sandbox",Kl)}removeIframeListeners(){this.iframe.removeEventListener("error",this.iframeErrorListener),this.iframe.removeEventListener("load",this.iframeLoadListener)}installSubscriptions(){if(this.options.lifecycle&&!this.lifecycleDisposer){const t=this.options.lifecycle.subscribe({show:this.show.bind(this),hide:this.hide.bind(this)});this.lifecycleDisposer=typeof t=="function"?t:null}}clearLifecycleDisposer(){const t=[this.lifecycleDisposer,this.workspaceCardsDisposer];this.lifecycleDisposer=null,this.workspaceCardsDisposer=null;for(const r of t)try{r?.()}catch{}}publishWorkspaceCardLaunchContext(){this.stateValue!=="ready"||!this.ports.workspaceCards||this.bridgeServer?.postEvent("workspace_cards_launch_context_change",this.ports.workspaceCards.getLaunchContext())}handleBridgeReady(){if(this.isInactive())return;if(this.readyContext){this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"duplicate_handshake"});return}this.clearHandshakeTimeout(),this.setStatus("bridge_ready");const t=this.createReadyContext();this.readyContext=t,this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"bridge",method:"ready"}),this.setState("ready"),this.sdkVersionDecision?.heartbeatEnabled&&this.hostVisible&&this.sendLocationProbe(),this.resolveReady?.(t),this.capabilityGraph?.notifyViewportChange(),yt(this.options.onReady,t)}completeCompatibilityLaunch(){if(this.stateValue!=="starting"||this.isInactive()||this.readyContext)return;this.clearHandshakeTimeout(),this.setStatus("bridge_ready");const t=this.createReadyContext();this.readyContext=t,this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"status",status:"bridge_ready"}),this.setState("ready"),this.resolveReady?.(t),this.capabilityGraph?.notifyViewportChange(),yt(this.options.onReady,t)}handleBridgeHandshake(t){const r=this.sdkVersionDecision?.sdkVersion;if(r)try{Np(r,t?.sdkVersion)}catch(n){return this.failRuntime(n),!1}return!0}armHandshakeTimeout(t=!1){this.clearHandshakeTimeout(),!(this.handshakeTimeout<=0)&&(this.handshakeTimeoutTimer=setTimeout(()=>{if(!(this.stateValue==="ready"||this.isInactive())){if(t){this.onIframeError(new Error("开发页面加载超时,请检查 Vite 服务、入口脚本和网络连接"));return}this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"handshake_timeout"}),this.failRuntime(Me("SDK_HANDSHAKE_TIMEOUT","小程序 SDK 握手超时"))}},t?iD:this.handshakeTimeout))}clearHandshakeTimeout(){this.handshakeTimeoutTimer&&(clearTimeout(this.handshakeTimeoutTimer),this.handshakeTimeoutTimer=void 0)}sendLocationProbe(){if(this.isInactive()||!this.hostVisible||!this.sdkVersionDecision?.heartbeatEnabled||this.documentRevalidationPending)return;if(this.pendingProbeId&&(this.consecutiveHeartbeatMisses+=1,this.consecutiveHeartbeatMisses>=aD)){this.failRuntime(Me("HEARTBEAT_TIMEOUT","小程序 SDK 心跳超时"));return}const t=`${Date.now().toString(36)}_${++this.probeSequence}`;this.pendingProbeId=t,this.bridgeServer?.postInternalRequest(_i,t,{probeId:t,timestamp:Date.now()}),this.heartbeatTimer=setTimeout(()=>{this.heartbeatTimer=void 0,this.sendLocationProbe()},qa),this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"location_probe",method:_i})}clearHeartbeat(){this.heartbeatTimer&&(clearTimeout(this.heartbeatTimer),this.heartbeatTimer=void 0),this.pendingProbeId=void 0,this.consecutiveHeartbeatMisses=0}beginDocumentRevalidation(t={}){this.clearUnexpectedDocumentLoadFailure(),this.clearHeartbeat(),this.clearDocumentRevalidationTimer(),this.preparedHistoryTraversalGeneration=void 0,this.documentRevalidationPending=!0;const r=++this.documentRevalidationGeneration;return this.iframeHiddenForRevalidation||(this.iframeVisibilityBeforeRevalidation=this.iframe.style.visibility,this.iframe.style.visibility="hidden",this.iframeHiddenForRevalidation=!0),t.deferProbe?this.armDocumentRevalidationTimer(r,{waitingForDocument:!0}):this.sendDocumentRevalidationProbe(),this.traceDocumentValidation(),r}sendDocumentRevalidationProbe(){if(this.isInactive()||!this.hostVisible||!this.documentRevalidationPending||!this.sdkVersionDecision?.heartbeatEnabled)return;const t=`${Date.now().toString(36)}_${++this.probeSequence}`;this.pendingProbeId=t,this.armDocumentRevalidationTimer(this.documentRevalidationGeneration),this.postLocationProbe(t)}resendDocumentRevalidationProbe(){if(!(this.isInactive()||!this.hostVisible||!this.documentRevalidationPending||!this.sdkVersionDecision?.heartbeatEnabled||this.preparedHistoryTraversalGeneration!==void 0)){if(!this.pendingProbeId){this.sendDocumentRevalidationProbe();return}this.postLocationProbe(this.pendingProbeId)}}postLocationProbe(t){this.bridgeServer?.postInternalRequest(_i,t,{probeId:t,timestamp:Date.now()}),this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"location_probe",method:_i})}armDocumentRevalidationTimer(t,r={}){this.clearDocumentRevalidationTimer(),this.hostVisible&&(this.documentRevalidationTimer=setTimeout(()=>{this.documentRevalidationTimer=void 0,!(this.isInactive()||!this.documentRevalidationPending||t!==this.documentRevalidationGeneration)&&this.failRuntime(Me("DOCUMENT_REVALIDATION_TIMEOUT",r.waitingForDocument?"小程序 iframe 目标文档加载超时":"小程序 iframe 文档再验证超时"))},r.waitingForDocument?sD:qa))}clearDocumentRevalidationTimer(){this.documentRevalidationTimer&&(clearTimeout(this.documentRevalidationTimer),this.documentRevalidationTimer=void 0)}completeDocumentRevalidation(){this.clearDocumentRevalidationTimer(),this.documentRevalidationPending=!1,this.preparedHistoryTraversalGeneration=void 0,this.pendingProbeId=void 0,this.consecutiveHeartbeatMisses=0,this.iframeHiddenForRevalidation&&this.iframe.style.visibility==="hidden"&&(this.iframe.style.visibility=this.iframeVisibilityBeforeRevalidation??""),this.iframeVisibilityBeforeRevalidation=void 0,this.iframeHiddenForRevalidation=!1,this.hostVisible&&this.sdkVersionDecision?.heartbeatEnabled&&(this.heartbeatTimer=setTimeout(()=>{this.heartbeatTimer=void 0,this.sendLocationProbe()},qa)),this.traceDocumentValidation()}traceDocumentValidation(){this.isInactive()||this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"document_validation",documentVerifying:this.documentRevalidationPending,message:this.documentRevalidationPending?"当前文档正在验证":"当前文档验证等待已结束"})}clearDocumentRevalidation(){this.clearDocumentRevalidationTimer(),this.documentRevalidationPending=!1,this.preparedHistoryTraversalGeneration=void 0,this.iframeVisibilityBeforeRevalidation=void 0,this.iframeHiddenForRevalidation=!1}cancelPreparedHistoryTraversal(){this.clearDocumentRevalidationTimer(),this.documentRevalidationPending=!1,this.preparedHistoryTraversalGeneration=void 0,this.pendingProbeId=void 0,this.consecutiveHeartbeatMisses=0,this.iframeHiddenForRevalidation&&this.iframe.style.visibility==="hidden"&&(this.iframe.style.visibility=this.iframeVisibilityBeforeRevalidation??""),this.iframeVisibilityBeforeRevalidation=void 0,this.iframeHiddenForRevalidation=!1,this.hostVisible&&this.sdkVersionDecision?.heartbeatEnabled&&this.sendLocationProbe(),this.traceDocumentValidation()}handleDuplicateBridgeHandshake(){this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"duplicate_handshake"}),this.documentRevalidationPending&&this.resendDocumentRevalidationProbe()}handleInternalBridgeEvent(t){if(t.method==="sdk.post.editor.dismiss"){const i=t.payload;typeof i?.requestId=="string"&&this.capabilityGraph?.dismissPostEditor(i.requestId);return}if(t.method===n0){this.handleCspViolation(t.payload);return}if(t.method!==r0)return;const r=this.sdkVersionDecision?.sdkVersion;if(!r)return;const n=t.payload;if(!n||n.sdkVersion!==r){this.failRuntime(Me("SDK_VERSION_MISMATCH","URL report 的 SDK 版本不一致"));return}if(!(n.probeId!==void 0&&n.probeId!==this.pendingProbeId)){if(typeof n.href!="string"||!Zl(this.launchUrl,n.href,this.locationBasePath)){typeof n.href=="string"&&this.emitUrlSecurityViolation("URL_OUT_OF_SCOPE",n.href),this.failRuntime(Me("URL_OUT_OF_SCOPE","小程序页面地址超出允许范围"));return}n.probeId!==void 0?(this.pendingProbeId=void 0,this.consecutiveHeartbeatMisses=0,this.documentRevalidationPending&&this.completeDocumentRevalidation()):this.documentRevalidationPending&&!this.pendingProbeId&&(this.preparedHistoryTraversalGeneration=void 0,this.sendDocumentRevalidationProbe())}}handleCspViolation(t){const r=jw(t,this.sdkVersionDecision?.sdkVersion);r&&this.emitSecurityViolation({type:"security_violation",errorCode:"CSP_VIOLATION",timestamp:r.timestamp,sdkVersion:r.sdkVersion,origin:r.origin,sanitizedPathname:r.sanitizedPathname,sanitizedPathnameHash:r.sanitizedPathnameHash,effectiveDirective:r.effectiveDirective,violatedDirective:r.violatedDirective,blockedResourceType:r.blockedResourceType})}emitSecurityViolation(t){yt(this.options.onSecurityViolation,t),this.trace({runtimeId:this.nonce,...t})}emitUrlSecurityViolation(t,r){const n=tD(t,r,this.sdkVersionDecision?.sdkVersion);this.emitSecurityViolation(n)}scheduleUnexpectedDocumentLoadFailure(){this.clearUnexpectedDocumentLoadFailure(),this.unexpectedDocumentLoadTimer=setTimeout(()=>{this.unexpectedDocumentLoadTimer=void 0,this.emitUrlSecurityViolation("UNEXPECTED_DOCUMENT_LOAD",this.launchUrl),this.failRuntime(Me("UNEXPECTED_DOCUMENT_LOAD","小程序 iframe 发生未授权文档加载"))},50)}clearUnexpectedDocumentLoadFailure(){this.unexpectedDocumentLoadTimer&&(clearTimeout(this.unexpectedDocumentLoadTimer),this.unexpectedDocumentLoadTimer=void 0)}traceSecurityPolicy(t){this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"security",sandboxPolicyVersion:Ag,launchUrlType:lu(t),networkPolicy:oD})}failRuntime(t){const r=uD(t);if(this.isInactive())return r;this.terminalError=r,this.stateValue="failed",this.failureTransitionInProgress=!0;try{this.setStatus("failed"),this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"error",errorCode:r.code,message:r.message}),yt(this.options.onError,dD(r)),yt(this.options.onStateChange,"failed"),this.terminalController.abort(r),this.postBridgeError(r);try{this.disposeRuntimeResources()}finally{this.teardownIframe(r)}}finally{this.rejectReady?.(r),this.failureTransitionInProgress=!1,this.destroyRequestedDuringFailure&&(this.destroyRequestedDuringFailure=!1,this.destroy())}return r}postBridgeError(t){try{this.bridgeServer?.postEvent("error",{code:t.code,message:t.message,...t.data!==void 0?{data:t.data}:{}})}catch{}return t}destroyBridgeServer(){const t=this.bridgeServer;this.bridgeServer=null;try{t?.destroy()}catch{}}disposeRuntimeResources(){if(this.devDocumentDisposer?.(),this.devDocumentDisposer=void 0,!this.runtimeResourcesDisposed){this.runtimeResourcesDisposed=!0;try{this.networkPolicyDisposer?.()}catch{}this.networkPolicyDisposer=void 0,this.clearHandshakeTimeout(),this.clearHeartbeat(),this.clearUnexpectedDocumentLoadFailure(),this.clearDocumentRevalidation(),this.destroyBridgeServer(),this.capabilityGraph?.dispose(),this.capabilityGraph=void 0,this.clearLifecycleDisposer(),this.removeIframeListeners();try{this.options.dispose?.()}catch{}}}teardownIframe(t){if(!this.iframeTornDown){this.iframeTornDown=!0;try{this.options.teardownIframe?this.options.teardownIframe(this.iframe,t):this.iframe.remove()}catch{}}}setStatus(t){this.status!==t&&(this.status=t,this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"status",status:t}))}setState(t){this.stateValue!==t&&(this.stateValue=t,yt(this.options.onStateChange,t))}isInactive(){return this.stateValue==="failed"||this.stateValue==="destroyed"}trace(t){yt(this.options.onTrace,{...t,runtimeId:this.runtimeId,...this.identity})}createLaunchContext(){return{launchUrl:this.launchUrl,src:this.miniProgramSrc,sdkVersion:this.sdkVersionDecision?.sdkVersion,heartbeatEnabled:!!this.sdkVersionDecision?.heartbeatEnabled,...this.identity}}createReadyContext(){return this.readyContext??this.createLaunchContext()}}function uD(e){const t=vs(e);return qs(e)&&"cause"in e&&Vh(t,e.cause),t}function Vh(e,t){return Object.defineProperty(e,"cause",{configurable:!0,enumerable:!1,value:t}),e}function dD(e){return{code:e.code,message:e.message,...e.data!==void 0?{data:e.data}:{},...e.cause!==void 0?{cause:hD(e.cause)}:{}}}const Wa=(()=>{const e=Object.getOwnPropertyDescriptor(new Error,"stack")?.get,t=Object.getOwnPropertyDescriptor(new Error,"stack")?.get;return typeof e=="function"&&e===t?e:void 0})(),lD=new Set([Error.prototype,TypeError.prototype,RangeError.prototype,ReferenceError.prototype,SyntaxError.prototype,URIError.prototype,EvalError.prototype]);function fD(e,t){const r=Object.getOwnPropertyDescriptor(e,t);if(!r)return;if("value"in r)return r.value;if(t!=="stack"||!Wa||r.get!==Wa)return;const n=Object.getPrototypeOf(e);if(lD.has(n)){for(const i of["name","message"]){const s=Object.getOwnPropertyDescriptor(e,i),a=Object.getOwnPropertyDescriptor(n,i)??Object.getOwnPropertyDescriptor(Error.prototype,i);if(s&&!("value"in s)||a&&!("value"in a))return}return Wa.call(e)}}function hD(e){if(!(!e||typeof e!="object"))try{const t={};for(const r of["name","message","stack"]){const n=fD(e,r);typeof n=="string"&&(t[r]=n.slice(0,r==="stack"?8192:2048).replace(/(https?:\/\/)[^\s/@]+:[^\s/@]+@/gi,"$1[redacted]@").replace(/([?&][^=\s]+)=([^&#\s]*)/g,"$1=[redacted]").replace(/(authorization|cookie|password|secret|token|pkey|api[_-]?key)([\"'\s:=]+)([^\s,}]+)/gi,"$1$2[redacted]"))}return Object.keys(t).length?t:void 0}catch{return}}function mD(e){return qs(e)&&typeof e.code=="string"&&typeof e.message=="string"}function qs(e){return!!e&&typeof e=="object"}function yt(e,t){try{e?.(t)}catch{}}function ED(e,t,r){try{e?.(t,r)}catch{}}function jd(e){try{const t=new URL(e);return t.protocol==="http:"&&yw(t.hostname)}catch{return!1}}function gD(e){try{return new URL(e).origin}catch{return}}function pD(e){return yg()?"*":gD(e)}function TD(e){return`${zh}
9
+
10
+ ${jh}
11
+
12
+ URL: ${e}`}function _D(e){return typeof window>"u"||typeof window.confirm!="function"?!1:window.confirm(TD(e.url))}function Vd(){typeof window<"u"&&typeof window.close=="function"&&window.close()}function AD(){const e=typeof navigator>"u"?void 0:navigator,t=typeof screen>"u"?void 0:screen,r=typeof window>"u"?void 0:window,n=Object.freeze({protocolVersion:gl,knownMethodCount:ir.length,supportsFileCreate:ir.some(i=>i.method===Wn),system:ID(e?.userAgent,e?.platform),userAgent:e?.userAgent??"",platform:e?.platform??"",language:e?.language??"",hardwareConcurrency:jr(e?.hardwareConcurrency),maxTouchPoints:jr(e?.maxTouchPoints),screen:{width:jr(t?.width),height:jr(t?.height)},viewport:{width:jr(r?.innerWidth),height:jr(r?.innerHeight),devicePixelRatio:bD(r?.devicePixelRatio)}});console.info("[hb-sdk-runtime] environment",n)}function ID(e="",t=""){const r=`${t} ${e}`.toLowerCase();return/iphone|ipad|ipod/.test(r)?"ios":r.includes("android")?"android":/win32|win64|windows/.test(r)?"windows":/darwin|macintosh|macintel|mac os/.test(r)?"macos":/linux|x11/.test(r)?"linux":"unknown"}function jr(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0?Math.floor(e):0}function bD(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:1}function yD(e){return Me(Qw,Hh,{reason:e.reason,...e.platform===void 0?{}:{platform:e.platform},...e.invalidReason===void 0?{}:{invalidReason:e.invalidReason},...e.effectivePlatforms===void 0?{}:{effectivePlatforms:e.effectivePlatforms}})}function ND(e){const t=e.canonicalIdentity?.miniProgramId?.trim();if(!t)return;const r=e.canonicalIdentity?.miniProgramVersion?.trim(),n=e.miniProgramPresentation?.name?.trim(),i=e.miniProgramPresentation?.avatarUrl?.trim(),s=e.miniProgramPresentation?.author?.trim();return Object.freeze({miniProgramId:t,...r?{version:r}:{},...n?{name:n}:{},...i?{iconUrl:i}:{},...s?{author:s}:{},...e.sdkVersionPolicy.releaseChannel===void 0?{}:{releaseChannel:e.sdkVersionPolicy.releaseChannel}})}function wD(e){if(!qs(e?.ports)||Array.isArray(e.ports))throw new TypeError("createMiniProgramRuntime 必须显式提供 ports");if(!qs(e.environment)||typeof e.environment.getCurrentHref!="function"||typeof e.environment.isDevRuntime!="function")throw new TypeError("createMiniProgramRuntime 必须显式提供 environment");if(typeof e.resolveLaunchConfiguration!="function")throw new TypeError("createMiniProgramRuntime 必须显式提供 resolveLaunchConfiguration");return new cD(e)}function DD(e={}){return async(t,r,n)=>{if(n.signal.aborted)throw new DOMException("账号标识读取已取消","AbortError");const i=e.indexedDB??globalThis.indexedDB,s=e.crypto??globalThis.crypto;if(!i||!s?.getRandomValues)throw new Error("Host 缺少持久化账号标识能力");const a=await new Promise((c,u)=>{const d=i.open("heybox-mini-program-private-account-v1",1);let l=!1;const h=()=>n.signal.removeEventListener("abort",p),f=g=>{l||(l=!0,h(),u(g))},p=()=>f(new DOMException("账号标识读取已取消","AbortError"));d.onupgradeneeded=()=>{l?d.transaction?.abort():d.result.createObjectStore("accounts")},d.onerror=()=>f(d.error),d.onblocked=()=>f(new Error("账号存储被阻塞")),d.onsuccess=()=>{l?d.result.close():(l=!0,h(),c(d.result))},n.signal.addEventListener("abort",p,{once:!0}),n.signal.aborted&&p()});try{if(n.signal.aborted)throw new DOMException("账号标识读取已取消","AbortError");return await new Promise((c,u)=>{const d=a.transaction("accounts","readwrite"),l=d.objectStore("accounts"),h=JSON.stringify([t,r]);let f;const p=()=>{try{d.abort()}catch{}g(),u(new DOMException("账号标识读取已取消","AbortError"))};n.signal.addEventListener("abort",p,{once:!0});const g=()=>n.signal.removeEventListener("abort",p);d.oncomplete=()=>{g(),c(f)},d.onabort=d.onerror=()=>{g(),u(d.error??new Error("账号存储事务失败"))};const b=l.get(h);b.onsuccess=()=>{try{if(typeof b.result=="string"&&/^ak_[0-9a-f]{64}$/.test(b.result))f=b.result;else{const y=s.getRandomValues(new Uint8Array(32));f=`ak_${Array.from(y,N=>N.toString(16).padStart(2,"0")).join("")}`,l.put(f,h)}}catch{d.abort()}}})}finally{a.close()}}}const SD=/^(?:authentication-info|authorization|cookie|cookie2|proxy-authenticate|proxy-authentication-info|proxy-authorization|set-cookie|set-cookie2|www-authenticate|pkey|x-pkey|x-access-token|x-auth-token)$/i,OD=new Set(["origin","referer","user-agent"]);function MD(e,t){return qE({mode:"request-only",request:(r,n={signal:t.signal})=>t.run(n.signal,async i=>{const s={...n,signal:i},a=CD(r),c=await e.authenticatedRequest(a,s);return PD(c)})}).network}function CD(e){const t=RD(e.headers);return{...e,target:{...e.target},...e.params===void 0?{}:{params:{...e.params}},...t===void 0?{headers:void 0}:{headers:t}}}function RD(e){if(e!==void 0)return Object.fromEntries(Object.entries(e).filter(([t])=>!LD(t)))}function LD(e){const t=e.trim().toLowerCase();return OD.has(t)}function PD(e){return{status:e.status,...e.statusText===void 0?{}:{statusText:e.statusText},data:e.data,headers:vD(e.headers)??{}}}function vD(e){if(e!==void 0)return Object.fromEntries(Object.entries(e).filter(([t])=>!kD(t)))}function kD(e){const t=e.trim().toLowerCase();return SD.test(t)||t.startsWith("x-heybox-")||t.startsWith("x-xhh-")}function xD(e,t,r){const n=zD(e.presentation,t);return{account:HD(e,t,r),network:MD(e,t),...e.storage===void 0?{}:{storage:FD(e,t)},...e.storage===void 0?{}:UD(e,t),...n===void 0?{}:{presentation:n},...e.protocol===void 0?{}:{protocol:e.protocol}}}function UD(e,t){const r=e.storage;return typeof r.storage.key!="function"||typeof r.storage.length!="number"?{}:{storageDiagnostics:{listRaw:n=>t.run(n.signal,()=>{const i=[];for(let s=0;s<r.storage.length;s+=1){const a=r.storage.key(s);if(a===null)continue;const c=r.storage.getItem(a);c!==null&&i.push({area:r.area,key:a,value:c})}return i})}}}function BD(e,t){return{getCurrentHref:()=>(t.assertActive(),e.environment.getCurrentHref()),isDevRuntime:()=>t.run(void 0,()=>e.environment.isDevRuntime()),...e.environment.setDocumentTitle===void 0?{}:{setDocumentTitle:r=>{t.assertActive(),e.environment.setDocumentTitle?.(r)}}}}function HD(e,t,r){const n=e.account.getAccountKey?.bind(e.account)??DD();return{getAccountKey:(i,s,a)=>t.run(a.signal,c=>n(i,s,{...a,signal:c})),getCurrentUserId:i=>t.run(i.signal,s=>e.account.getCurrentUserId({signal:s})),ensureAuthenticated:i=>t.run(i.signal,s=>e.account.ensureAuthenticated({trustedUserGesture:i.trustedUserGesture,reason:i.reason,signal:s})),onChange:i=>{t.assertActive();const s=e.account.onChange(a=>{t.signal.aborted||i(a)});return r(s)}}}function FD(e,t){const r=e.storage.storage;return{getRaw:(n,i)=>t.run(i.signal,()=>{const s=r.getItem(n);return s===null?void 0:s}),setRaw:(n,i,s)=>t.run(s.signal,()=>{r.setItem(n,i)})}}function zD(e,t){if(!e)return;const r={};return e.close&&(r.close=n=>t.run(n.signal,i=>e.close({...n,signal:i}))),e.reload&&(r.reload=n=>t.run(n.signal,i=>e.reload({...n,signal:i}))),e.openAppPage&&(r.openAppPage=(n,i)=>t.run(i.signal,s=>e.openAppPage(n,{...i,signal:s}))),e.openWindow&&(r.openWindow=(n,i)=>t.run(i.signal,s=>e.openWindow(n,{...i,signal:s}))),e.applyOrientation&&(r.applyOrientation=(n,i)=>t.run(i.signal,s=>e.applyOrientation(n,{...i,signal:s}))),e.onViewportChange&&(r.onViewportChange=n=>{t.assertActive();const i=e.onViewportChange(()=>{t.signal.aborted||n()});let s=!1;const a=()=>{s||(s=!0,t.signal.removeEventListener("abort",a),i())};return t.signal.addEventListener("abort",a,{once:!0}),a}),e.getViewportMetrics&&(r.getViewportMetrics=()=>(t.assertActive(),e.getViewportMetrics())),e.getNavigationBarHeight&&(r.getNavigationBarHeight=()=>(t.assertActive(),e.getNavigationBarHeight())),e.setNavigationBarStyle&&(r.setNavigationBarStyle=(n,i)=>t.run(i.signal,s=>e.setNavigationBarStyle(n,{...i,signal:s}))),e.showShareMenu&&(r.showShareMenu=(n,i)=>t.run(i.signal,s=>e.showShareMenu(n,{...i,signal:s}))),e.setScreenshotChromeHidden&&(r.setScreenshotChromeHidden=(n,i)=>sg(i)?e.setScreenshotChromeHidden(n,i):t.run(i.signal,s=>e.setScreenshotChromeHidden(n,{...i,signal:s}))),e.captureAndShare&&(r.captureAndShare=(n,i)=>t.run(i.signal,s=>e.captureAndShare(n,{...i,signal:s}))),e.showToast&&(r.showToast=(n,i)=>t.run(i.signal,s=>e.showToast(n,{...i,signal:s}))),e.showLoading&&(r.showLoading=(n,i)=>t.run(i.signal,s=>e.showLoading(n,{...i,signal:s}))),e.hideLoading&&(r.hideLoading=n=>t.run(n.signal,i=>e.hideLoading({...n,signal:i}))),e.vibrate&&(r.vibrate=(n,i)=>t.run(i.signal,s=>e.vibrate(n,{...i,signal:s}))),e.setClipboard&&(r.setClipboard=(n,i)=>t.run(i.signal,s=>e.setClipboard(n,{...i,signal:s}))),Object.keys(r).length===0?void 0:r}function jD(){const e=new AbortController;return{signal:e.signal,abort:t=>{e.signal.aborted||e.abort(t)},assertActive:t=>{const r=[e.signal,t].find(n=>n?.aborted);if(r)throw Li(r.reason)},run:async(t,r)=>{const n=t===e.signal||t===void 0?[e.signal]:[e.signal,t],i=n.find(l=>l.aborted);if(i)throw Li(i.reason);const s=new AbortController;let a;const c=new Promise((l,h)=>{a=h}),u=n.map(l=>{const h=()=>{s.signal.aborted||s.abort(l.reason),a(Li(l.reason))};return l.addEventListener("abort",h,{once:!0}),{listener:h,source:l}});let d;try{d=Promise.resolve(r(s.signal))}catch(l){d=Promise.reject(l)}try{const l=await Promise.race([d,c]),h=n.find(f=>f.aborted);if(h)throw Li(h.reason);return l}finally{for(const{listener:l,source:h}of u)h.removeEventListener("abort",l)}}}}function Li(e){return new DOMException("Web Host operation aborted","AbortError")}async function VD(e){const t=jD(),r=new Set;let n=!1;const i=f=>{if(n||t.signal.aborted)return $a(f),()=>{};let p=!0;const g=()=>{p&&(p=!1,r.delete(g),$a(f))};return r.add(g),g},s=()=>a(e.signal.reason),a=f=>{if(!n){n=!0,e.signal.removeEventListener("abort",s),t.abort(f);for(const p of[...r])p();e.onDispose&&$a(e.onDispose)}};e.signal.addEventListener("abort",s,{once:!0}),e.signal.aborted&&a(e.signal.reason);const c=xD(e,t,i);c.storage?.getRaw&&c.storage.setRaw&&(c.scopedStorage=Sh({storage:c.storage,diagnostics:c.storageDiagnostics,coordinationKey:e.storage.storage,lock:Oh,resolveScope:async()=>Dh((await h()).configuration)}));const u=ql(c,{hostCapabilities:e.hostCapabilities,hasUserDataPresentation:e.userDataPresentation!==void 0,hasUserDataSettings:e.userDataPresentation?.openDataPermissions!==void 0}),d=BD(e,t);let l;const h=()=>l??=t.run(void 0,f=>e.resolveLaunch(f));return{platform:"web",ports:c,environment:d,resolveLaunch:h,...e.authPresentation===void 0?{}:{authPresentation:GD(e.authPresentation,t)},...e.userDataPresentation===void 0?{}:{userDataPresentation:YD(e.userDataPresentation,t)},hostCapabilities:u.effectiveCapabilities,dispose:a}}function $a(e){try{e()}catch{}}function GD(e,t){return{...e.confirmFollowAuthor?{confirmFollowAuthor:r=>t.run(r.signal,n=>e.confirmFollowAuthor({...r,signal:n}))}:{},confirmAuthorization:r=>t.run(r.signal,n=>e.confirmAuthorization({...r,signal:n}))}}function YD(e,t){return{...e.openDataPermissions?{openDataPermissions:r=>t.run(r.signal,n=>e.openDataPermissions({...r,signal:n}))}:{},confirmDataPermission:r=>t.run(r.signal,n=>e.confirmDataPermission({...r,signal:n}))}}function QD(e){const t=`hb-game-saves-${crypto.randomUUID()}`,r=u=>`hb-sdk:game-save-cache:${u}`;let n,i;const s=new Promise((u,d)=>{n=u,i=d});let a;const c=new Promise(u=>{a=u});return e.signal.addEventListener("abort",a,{once:!0}),e.signal.aborted&&a(),e.locks.request(r(t),async()=>{let u;try{u=await e.getRoot();const d=await e.locks.request("hb-sdk:game-save-cache:gc",async()=>{e.signal.throwIfAborted();for await(const[l,h]of u)h.kind!=="directory"||!/^hb-game-saves-[a-f0-9-]{36}$/.test(l)||await e.locks.request(r(l),{ifAvailable:!0},async f=>{f&&await Gd(u,l)});return e.signal.throwIfAborted(),u.getDirectoryHandle(t,{create:!0})});e.signal.throwIfAborted(),n(d),await c}catch(d){i(d)}finally{e.signal.removeEventListener("abort",a),u&&await Gd(u,t).catch(()=>{})}}).catch(i),s.catch(()=>{}),s}async function Gd(e,t){for(let r=0;;r++)try{await e.removeEntry(t,{recursive:!0});return}catch(n){if(n instanceof DOMException&&n.name==="NotFoundError")return;if(!(n instanceof DOMException)||n.name!=="NoModificationAllowedError"||r>=4)throw n;await new Promise(i=>setTimeout(i,25*(r+1)))}}const Ka=8*1024*1024,qD=new Set(["content-length","content-type","content-encoding","transfer-encoding","content-disposition","content-range"]),WD="/__hb_sdk__/game-save-download",rt=(e,t)=>({code:e,message:t});function $D(e){const t=e.getRoot??(navigator.storage?.getDirectory?()=>navigator.storage.getDirectory():void 0),r=e.locks??navigator.locks,n=e.supportsWritable??(typeof FileSystemFileHandle<"u"&&typeof FileSystemFileHandle.prototype.createWritable=="function");if(!t||!r||!n)return;const i=QD({getRoot:t,locks:r,signal:e.signal}),s=new WeakMap,a=new WeakSet,c=g=>{g.signal.throwIfAborted(),g.lifecycle!=="cleanup"&&e.signal.throwIfAborted()},u=()=>i;function d(g){if(!/^\.hb-game-saves\/[a-zA-Z0-9_-]+\.zip$/.test(g))throw rt("FILE_ACCESS_DENIED","浏览器仅开放存档私有缓存");return g.slice(15)}async function l(g,b){c(b);const y=d(g);try{return await(await u()).getFileHandle(y)}catch(N){throw N instanceof DOMException&&N.name==="NotFoundError"?rt("FILE_NOT_FOUND","存档缓存不存在"):N}}function h(g){const b={kind:"file",mode:"readwrite",name:g.split("/").at(-1),async create(y,N){c(N);const C=d(g),I=await u();if(y.exclusive)try{throw await I.getFileHandle(C),rt("FILE_ALREADY_EXISTS","存档缓存已存在")}catch(U){if(!(U instanceof DOMException&&U.name==="NotFoundError"))throw U}c(N),await I.getFileHandle(C,{create:!0}),c(N)},async remove(y){c(y);const N=d(g);if(i)try{await(await i).removeEntry(N)}catch(C){if(!(C instanceof DOMException&&C.name==="NotFoundError"))throw C}},async read(y){const N=await(await l(g,y)).getFile();if(N.size>Ka)throw rt("FILE_TOO_LARGE","存档文件超过 8 MiB");const C=new Uint8Array(await N.arrayBuffer());try{return c(y),C}catch(I){throw C.fill(0),I}},async write(){throw rt("FILE_ACCESS_DENIED","存档缓存仅允许受控下载写入")},async stat(y){const N=await(await l(g,y)).getFile();return c(y),{kind:"file",size:N.size,modifiedAt:N.lastModified}}};return s.set(b,g),b}const f=async()=>{throw rt("FILE_ACCESS_DENIED","浏览器仅开放存档私有缓存")},p={kind:"directory",mode:"readwrite",name:"",file:h,directory(g){return{...p,name:g,async create(b,y){if(c(y),g!==".hb-game-saves")return f();await u(),c(y)}}},create:f,stat:f,list:f};return{files:{sandbox:p},transfer:{network:{async open(g,b){if(c(b),!jl(g))throw rt("METHOD_FORBIDDEN","仅支持受控存档下载");const y=await(e.fetch??fetch)(WD,{method:"POST",credentials:"same-origin",redirect:"error",headers:{"content-type":"application/json","x-hb-sdk-csrf":e.csrfToken()},body:JSON.stringify(g),signal:AbortSignal.any([b.signal,e.signal,AbortSignal.timeout(6e4)])});if(!y.ok){const N=await y.json().catch(()=>({}));throw rt(N.code==="FILE_TOO_LARGE"?"FILE_TOO_LARGE":"DOWNLOAD_NETWORK_FAILED","存档下载失败")}return a.add(y),{status:y.status,headers:Object.fromEntries(Array.from(y.headers).filter(([N])=>qD.has(N)).map(([N,C])=>[N,[C]])),body:y}},async release(g){a.delete(g),await g.body?.cancel()}},files:{async writeResource(g,b,y,N){let C,I;try{c(N);const U=s.get(g);if(!U||!a.delete(b))throw rt("FILE_ACCESS_DENIED","下载资源不属于当前存档会话");if(y.mode!=="replace-existing")throw rt("FILE_ACCESS_DENIED","存档下载目标必须先创建");if(C=await(await l(U,N)).createWritable(),!b.body)throw rt("DOWNLOAD_NETWORK_FAILED","存档下载没有响应内容");I=b.body.getReader();let R=0;for(;;){c(N);const P=await I.read().catch(M=>{throw c(N),rt(M instanceof DOMException&&M.name==="TimeoutError"?"DOWNLOAD_TIMEOUT":"DOWNLOAD_NETWORK_FAILED","存档下载流中断")});if(c(N),P.done)break;if(R+=P.value.byteLength,R>Math.min(y.maxBytes??Ka,Ka))throw rt("FILE_TOO_LARGE","存档文件超过 8 MiB");await C.write(new Uint8Array(P.value)),N.onProgress(R)}if(y.expectedBytes!==void 0&&R!==y.expectedBytes)throw rt("DOWNLOAD_NETWORK_FAILED","存档下载长度不匹配");return c(N),await C.close(),C=void 0,{committedBytes:R}}catch(U){throw U instanceof DOMException&&U.name==="QuotaExceededError"?rt("FILE_QUOTA_EXCEEDED","浏览器存储空间不足"):U}finally{await I?.cancel().catch(()=>{}),I||await b.body?.cancel().catch(()=>{}),await C?.abort().catch(()=>{}),a.delete(b)}}}}}}function Pt(e,t){throw{code:e,message:t}}function wn(e){return JSON.stringify(e,(t,r)=>r&&typeof r=="object"&&!Array.isArray(r)?Object.fromEntries(Object.keys(r).sort().map(n=>[n,r[n]])):r)}function KD(e){return{declaredPermissions:e.declaredPermissions??{},platforms:[...e.platforms??[]].sort(),runtimePermissions:e.runtimePermissions,networkPolicy:e.networkPolicy}}function ZD(e){const t=e.now??Date.now;let r;const n=new Map,i=()=>{r=void 0};e.signal.addEventListener("abort",i,{once:!0});function s(){if(e.signal.aborted)throw new DOMException("调试会话已结束","AbortError");const u=e.readState();u.userId||(i(),Pt("UNAUTHORIZED","请先通过 hb-sdk login 登录小黑盒"));const{signed:d,browser:l}=u,h=TE(d.developmentSnapshot);(d.source!=="remote"||!d.miniProgramId||!d.localDevLaunchToken||!d.expiresAt||d.expiresAt<=t()||!h||!d.developmentSnapshotDigest||!/^[a-f0-9]{64}$/.test(d.developmentSnapshotDigest))&&(i(),Pt("INVALID_STATE","开发启动授权尚未就绪,请检查 CLI 登录、项目绑定及开发票据状态"));let f;try{f=Fl({...h,declared_permissions:l.declaredPermissions??{},platforms:l.platforms??[]})}catch{}(l.source!=="remote"||l.miniProgramId!==d.miniProgramId||l.devSessionId!==h.session_id||d.devSessionId!==h.session_id||d.contextRevision!==h.revision||f!==d.developmentSnapshot||wn(l.runtimePermissions)!==wn(d.runtimePermissions)||wn(l.networkPolicy)!==wn(d.networkPolicy))&&(i(),Pt("AUTHORIZATION_CONTEXT_CHANGED","开发快照正在更新,请稍后重试"));const p={mini_program_id:d.miniProgramId,launch_kind:"remote-dev",version_identity:`dev:${h.session_id}:${h.revision}`,sdk_version:h.sdk_version,local_dev_launch_token:d.localDevLaunchToken,dev_snapshot_digest:d.developmentSnapshotDigest,dev_network_enabled:u.networkEnabled};return{body:p,key:wn([u.userId,u.accountRevision,p,l.contextRevision,KD(l)]),expiresAt:d.expiresAt}}async function a(u,d){const l=d.signal;let h;try{h=await e.request({source:"runtime-private",credentials:"heybox-session",redirectPolicy:"error",target:{kind:"heybox-api",endpointId:"heybox.user_miniprogram.runtime.auth.context.post",path:"/user_miniprogram/runtime/auth/context",channel:"api"},method:"POST",bodyEncoding:"form",data:u.body,timeout:1e4},d)}catch(y){l.throwIfAborted();const N=y&&typeof y=="object"&&"code"in y?String(y.code):"";if(["SESSION_UNAUTHENTICATED","SESSION_INVALIDATED","UNAUTHORIZED"].includes(N)&&Pt("UNAUTHORIZED","小黑盒登录已失效,请重新登录"),["REQUEST_CANCELLED","REQUEST_TIMEOUT"].includes(N)||y instanceof DOMException&&["AbortError","TimeoutError"].includes(y.name))throw y;Pt("REQUEST_FAILED","获取开发运行授权失败,请稍后重试")}l.throwIfAborted(),await e.refreshAccount(l),l.throwIfAborted(),s().key!==u.key&&Pt("AUTHORIZATION_CONTEXT_CHANGED","账号或开发快照已变化,请重试");const f=h.data;(h.status===401||f?.status==="login"||f?.status==="relogin")&&Pt("UNAUTHORIZED","小黑盒登录已失效,请重新登录"),(h.status!==200||f?.status!=="ok")&&Pt("REQUEST_FAILED","获取开发运行授权失败,请检查开发资格后重试");const p=f.result,g=Number(p?.expires_at)*1e3;(typeof p?.token!="string"||!p.token.trim()||!Number.isSafeInteger(p?.expires_at)||!Number.isSafeInteger(g)||g<=t()||!["legacy","local","server"].includes(String(p.user_data_mode)))&&Pt("INVALID_RESPONSE","开发运行授权响应无效");const b={token:p.token,expiresAt:Math.min(g,u.expiresAt),steamAccount:p.steam_account===!0,userDataMode:p.user_data_mode};return r={key:u.key,value:b},b}const c={async get(u){const d=AbortSignal.any([u.signal,e.signal]);d.throwIfAborted(),await e.refreshAccount(d),d.throwIfAborted();const l=s();if(r?.key===l.key&&r.value.expiresAt>t()+3e4)return r.value;i();let h=n.get(l.key);if(!h||h.controller.signal.aborted){const p=new AbortController,g=a(l,{...u,signal:AbortSignal.any([p.signal,e.signal])});h={promise:g,controller:p,users:0},n.set(l.key,h);const b=h;g.finally(()=>{n.get(l.key)===b&&n.delete(l.key)}).catch(()=>{})}h.users++;let f;try{const p=await Promise.race([h.promise,new Promise((g,b)=>{f=()=>b(d.reason),d.addEventListener("abort",f,{once:!0}),d.aborted&&f()})]);return d.throwIfAborted(),s().key!==l.key&&Pt("AUTHORIZATION_CONTEXT_CHANGED","账号或开发快照已变化,请重试"),p}finally{d.removeEventListener("abort",f),--h.users===0&&h.controller.abort()}}};return{...c,async resolveLaunchConfiguration(u,d){const l=AbortSignal.any([d.signal,e.signal]);l.throwIfAborted(),await e.refreshAccount(l),l.throwIfAborted();const h=e.readState();if(!u.canonicalIdentity?.miniProgramId||!h.userId||!h.signed.localDevLaunchToken)return u;const f=await c.get({...d,signal:l});return{...u,runtimeFeatures:{steamAccount:f.steamAccount,userDataMode:f.userDataMode}}}}}function Yd(e,t){return si(e)&&(e.source==="remote"||e.source==="anonymous")?{source:e.source,miniProgramId:typeof e.miniProgramId=="string"?e.miniProgramId:void 0,developmentSnapshot:typeof e.developmentSnapshot=="string"?e.developmentSnapshot:void 0,developmentSnapshotDigest:typeof e.developmentSnapshotDigest=="string"?e.developmentSnapshotDigest:void 0,localDevLaunchToken:typeof e.localDevLaunchToken=="string"?e.localDevLaunchToken:void 0,runtimePermissions:e.runtimePermissions,networkPolicy:e.networkPolicy,...e.source==="remote"&&e.firstParty===!0?{firstParty:!0}:{},publishedRuntimePermissions:e.publishedRuntimePermissions,warning:typeof e.warning=="string"?e.warning:void 0,declaredPermissions:si(e.declaredPermissions)?e.declaredPermissions:void 0,platforms:Array.isArray(e.platforms)?e.platforms.filter(r=>["android","ios","ohos","windows","macos","linux"].includes(String(r))):void 0,localDevGrant:e.localDevGrant,contextRevision:typeof e.contextRevision=="number"?e.contextRevision:void 0,devSessionId:typeof e.devSessionId=="string"?e.devSessionId:void 0,expiresAt:typeof e.expiresAt=="number"?e.expiresAt:void 0,companionManifestSha256:typeof e.companionManifestSha256=="string"?e.companionManifestSha256:void 0}:{source:"anonymous",runtimePermissions:t}}function Hn(e,t=Date.now()){if(e.localDevGrant===void 0)return e;const r=Ml(e.localDevGrant);return!r.valid||!e.devSessionId?.trim()||!Number.isSafeInteger(e.contextRevision)||e.contextRevision!==r.grant.revision||!e.expiresAt||!Number.isFinite(e.expiresAt)||e.source!=="remote"&&e.expiresAt<=t?{...e,localDevGrant:void 0,warning:"本地临时授权无效或已过期,已降权"}:{...e,...e.expiresAt<=t?{source:"anonymous",localDevLaunchToken:void 0,expiresAt:t+3e4}:{},localDevGrant:O0({declaredPermissions:e.declaredPermissions??{},runtimePermissions:e.runtimePermissions,revision:r.grant.revision,eligiblePermissionKeys:e.platforms?.some(n=>["windows","macos","linux"].includes(n))?["network","companion","appProtocol"]:["network","appProtocol"]})}}function XD(e){if(!si(e)||!Qd(e,["networkRequest"]))return;const t=e.networkRequest;if(!(!si(t)||!Qd(t,["status","useOfficialDomain"]))&&!(t.status!=="enabled"&&t.status!=="disabled")&&typeof t.useOfficialDomain=="boolean")return{networkRequest:{status:t.status,useOfficialDomain:t.useOfficialDomain}}}const JD={networkRequest:{status:"disabled",useOfficialDomain:!1}};function Rc(e){const t=it(e.localDevGrant?uc({declaredPermissions:e.declaredPermissions??{},runtimePermissions:e.runtimePermissions,localDevGrant:e.localDevGrant}).runtimePermissions:e.runtimePermissions),r=t.permissions.network;return t.valid&&r?{networkRequest:{status:r.status,useOfficialDomain:r.config.useOfficialDomain===!0}}:e1()}function Gh(e,t,r){return r?.localDevGrant?uc({declaredPermissions:r.declaredPermissions??{},runtimePermissions:e,localDevGrant:r.localDevGrant}).runtimePermissions:t1(e,t,t.networkRequest.useOfficialDomain)}function e1(){return{networkRequest:{...JD.networkRequest}}}function t1(e,t,r){const n=it(e);if(!n.valid)return{schema_version:1,entries:[]};const i=[];for(const a of Or){const c=n.permissions[a];c&&i.push(a==="network"?{key:a,status:t.networkRequest.status,config:{useOfficialDomain:r}}:a==="user_game_data"||a==="post"?{key:a,status:c.status,config:{...c.config}}:{key:a,status:c.status,config:{}})}const s=si(e)&&typeof e.revision=="number"&&Number.isInteger(e.revision)&&e.revision>=0?e.revision:void 0;return{schema_version:1,...s===void 0?{}:{revision:s},entries:i}}function si(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&Object.getPrototypeOf(e)===Object.prototype}function Qd(e,t){return Object.keys(e).length===t.length&&t.every(n=>Object.hasOwn(e,n))}function r1(e){let t,r=!1,n=!1,i;return{invalidate(c){return n?Promise.resolve({ok:!1}):e.shouldSkip?.(c,{draining:i!==void 0})?i??Promise.resolve({ok:!0}):(r=!0,i??=s().finally(()=>{i=void 0}),i)},dispose(){n||(n=!0,r=!1,t?.abort(),t=void 0)}};async function s(){let c={ok:!0};for(;r&&!n;){r=!1;const u=new AbortController;t=u;let d;try{d=await e.fetch(u.signal)}catch(h){c={ok:!1},!n&&!u.signal.aborted&&a(h);continue}finally{t===u&&(t=void 0)}if(n)return{ok:!1};let l;try{l=e.apply(d)}catch(h){c={ok:!1},n||a(h);continue}if(n)return{ok:!1};if(c={ok:!0},!!e.hasChanged(l))try{await e.onChanged(l)}catch(h){c={ok:!1},n||a(h)}}return n?{ok:!1}:c}function a(c){try{e.onError(c)}catch{}}}function n1(e){return r1({apply:e.applyStatus,fetch:e.fetchStatus,hasChanged:t=>t.changed,onChanged:t=>e.reconcile(t.status),onError:e.onError,shouldSkip:t=>t!==void 0&&t<=e.getCanonicalRevision()})}function i1(e){const t=e.minDelayMs??1e3,r=e.maxDelayMs??15e3;let n=t,i=!1,s;return{schedule:a,reset(){n=t,c()},dispose(){i||(i=!0,c())}};function a(){i||e.isDisposed()||(c(),s=e.timers.setTimeout(async()=>{s=void 0;let u;try{u=await e.invalidate()}catch{u={ok:!1}}if(!(i||e.isDisposed())){if(u.ok){n=t,e.connectEvents();return}n=Math.min(n*2,r),a()}},n))}function c(){s!==void 0&&e.timers.clearTimeout(s),s=void 0}}const Za=new WeakMap;function Lc(e){return new Promise((t,r)=>{if(e.signal?.aborted){r(e.signal.reason);return}const{root:n,signal:i}=e;Za.set(n,document.activeElement);const s=[...n.querySelectorAll("button[data-action]")];n.dataset.hostDialog="true",n.style.zIndex="40";const a=()=>[...document.querySelectorAll("[data-host-dialog]")].at(-1);n.setAttribute("role","dialog"),n.setAttribute("aria-modal","true"),n.setAttribute("aria-label",e.title);let c;const u=()=>{i?.removeEventListener("abort",l),document.removeEventListener("keydown",f);const g=a()===n;if(n.remove(),g){const b=a();b&&(b.inert=!1,b.removeAttribute("aria-hidden"));let y=Za.get(n)??null;for(;y instanceof HTMLElement&&!y.isConnected;){const N=y.closest("[data-host-dialog]");y=N?Za.get(N)??null:null}y instanceof HTMLElement&&(!b||b.contains(y))?y.focus():b?.querySelector("button")?.focus()}},d=Im({kind:"dialog",mode:e.mode??"simulated",title:e.title,method:e.method,...e.callId?{callId:e.callId}:{},actions:s.map(g=>g.textContent?.trim()??"")},g=>{u(),c!==void 0?t(c):r(i?.reason??new DOMException(`宿主弹窗已${g}`,"AbortError"))});function l(){d.finish("cancelled")}function h(g){c=g,d.finish(g===e.cancelAction?"cancelled":"confirmed")}function f(g){if(a()!==n||(g.key==="Escape"&&e.cancelAction&&(g.preventDefault(),h(e.cancelAction)),g.key!=="Tab"||s.length===0))return;const b=s[0],y=s.at(-1);g.shiftKey&&document.activeElement===b?(g.preventDefault(),y.focus()):!g.shiftKey&&document.activeElement===y&&(g.preventDefault(),b.focus())}if(!d.active)return;if(i?.aborted){l();return}for(const g of s)g.addEventListener("click",()=>h(g.dataset.action));n.addEventListener("click",g=>{g.target===n&&e.cancelAction&&h(e.cancelAction)}),n.dataset.interactionId=d.interactionId;const p=a();p&&(p.inert=!0,p.setAttribute("aria-hidden","true")),(document.querySelector("#host-overlay-layer")??document.body).appendChild(n),i?.addEventListener("abort",l,{once:!0}),document.addEventListener("keydown",f),s[0]?.focus(),i?.aborted&&l()})}function Et(e){return e.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&#039;")}const qd="hb-sdk-action-dialog-style";async function ya(e){await Yh(e)}async function s1(e){return await Yh({title:"关注作者",detail:"是否关注当前小程序的作者?",signal:e.signal,method:"user.requestFollowAuthor",mode:"browser",confirmation:!0})?"confirmed":"cancelled"}async function Yh(e){d1();const t=document.createElement("div");return t.className="hb-sdk-action-dialog",t.innerHTML=`
13
+ <div class="hb-sdk-action-dialog__panel">
14
+ <h2>${Et(e.title)}</h2>
15
+ <pre class="hb-sdk-action-dialog__detail">${Et(e.detail)}</pre>
16
+ <div class="hb-sdk-action-dialog__actions">
17
+ ${e.confirmation?'<button type="button" data-action="cancel">取消</button>':""}
18
+ <button type="button" class="primary" data-action="confirm">${e.confirmation?"关注":"确定"}</button>
19
+ </div>
20
+ </div>`,await Lc({root:t,title:e.title,method:e.method??"host.action",signal:e.signal,callId:e.callId,mode:e.mode,...e.confirmation?{cancelAction:"cancel"}:{}})==="confirm"}async function a1(e,t){await ya({method:"navigation.openAppPage",title:"打开页面",detail:["protocolType: "+e.protocolType,"path: "+e.path,"params: "+nn(e.params)].join(`
21
+ `),signal:t.signal,callId:t.requestId})}async function o1(e,t){await ya({method:"navigation.openAppPage",title:"打开小程序",detail:["miniProgramId: "+e.miniProgramId,"extra: "+nn(e.extra)].join(`
22
+ `),signal:t.signal,callId:t.requestId})}async function c1(e,t){await ya({method:"share.showShareMenu",title:"分享",detail:["title: "+e.title,"description: "+e.description,"url: "+e.url,"channel: "+nn(e.channel),"post: "+nn(e.post)].join(`
23
+ `),signal:t.signal,callId:t.requestId})}async function u1(e,t){await ya({method:"share.screenshot",title:"截图分享",detail:["rect: "+nn(e.rect),"post: "+nn(e.post)].join(`
24
+ `),signal:t.signal,callId:t.requestId})}function nn(e){return JSON.stringify(e,null,2)}function d1(){if(document.getElementById(qd))return;const e=document.createElement("style");e.id=qd,e.textContent=`
25
+ .hb-sdk-action-dialog {
26
+ position: absolute;
27
+ inset: 0;
28
+ display: grid;
29
+ place-items: center;
30
+ padding: 24px;
31
+ background: rgba(15, 23, 42, 0.45);
32
+ }
33
+
34
+ .hb-sdk-action-dialog__panel {
35
+ width: min(420px, 100%);
36
+ border-radius: 12px;
37
+ padding: 20px;
38
+ background: #fff;
39
+ box-shadow: 0 20px 45px rgba(15, 23, 42, 0.2);
40
+ }
41
+
42
+ .hb-sdk-action-dialog__panel h2 {
43
+ margin: 0 0 8px;
44
+ font-size: 18px;
45
+ }
46
+
47
+ .hb-sdk-action-dialog__detail {
48
+ margin: 0 0 16px;
49
+ max-height: 40vh;
50
+ overflow: auto;
51
+ color: #1f2933;
52
+ font-family: inherit;
53
+ font-size: 12px;
54
+ line-height: 1.6;
55
+ white-space: pre-wrap;
56
+ overflow-wrap: anywhere;
57
+ word-break: break-word;
58
+ }
59
+
60
+ .hb-sdk-action-dialog__actions {
61
+ display: flex;
62
+ justify-content: flex-end;
63
+ gap: 8px;
64
+ }
65
+
66
+ .hb-sdk-action-dialog__actions button {
67
+ min-height: 36px;
68
+ border: 1px solid #cad5e2;
69
+ border-radius: 6px;
70
+ padding: 0 12px;
71
+ background: #fff;
72
+ cursor: pointer;
73
+ }
74
+
75
+ .hb-sdk-action-dialog__actions .primary {
76
+ border-color: #2563eb;
77
+ color: #fff;
78
+ background: #2563eb;
79
+ }
80
+ `,document.head.appendChild(e)}const l1={identity:"小程序身份",profile:"昵称和头像",steam_account:"Steam 账号"};async function f1(e){const t=document.createElement("div");return t.className="hb-sdk-auth-dialog",t.innerHTML=`
81
+ <div class="hb-sdk-auth-dialog__panel">
82
+ <h2>授权请求</h2>
83
+ <p class="hb-sdk-auth-dialog__app">${Et(e.miniProgram?.name||"当前小程序")} 申请访问:</p>
84
+ <ul class="hb-sdk-auth-dialog__scopes">${e.scopes.map(n=>`<li>${Et(l1[n]||n)}</li>`).join("")}</ul>
85
+ ${e.userProfile?.nickname?`<p class="hb-sdk-auth-dialog__profile">当前账号:${Et(e.userProfile.nickname)}</p>`:""}
86
+ <div class="hb-sdk-auth-dialog__actions">
87
+ <button type="button" data-action="deny">拒绝</button>
88
+ <button type="button" class="primary" data-action="allow">允许</button>
89
+ </div>
90
+ </div>
91
+ `,await Lc({root:t,title:"授权请求",method:"auth.authorize",mode:"browser",signal:e.signal,cancelAction:"deny"})==="allow"?{status:"granted",grantedScopes:[...e.scopes]}:{status:"cancelled"}}function h1(e){const t=e.miniProgramName?.trim();return{launchUrl:e.launchUrl,...e.locationBasePath!==void 0?{locationBasePath:e.locationBasePath}:{},...t?{miniProgramPresentation:{name:t}}:{},sdkVersionPolicy:{minimumSdkVersion:"0.5.0",sdkVersion:Hc,releaseChannel:"development"},runtimePermissions:e.runtimePermissions,networkPolicy:e.networkPolicy,firstParty:e.firstParty===!0,...e.anonymousStorageScope?{anonymousStorageScope:e.anonymousStorageScope}:{},platformAccess:{source:"manifest",manifest:{platforms:ba},sdkVersion:Hc},environmentInfo:{appVersion:null,operatingSystem:{name:e.operatingSystem??"unknown",version:null}},...e.miniProgramId?{canonicalIdentity:{miniProgramId:e.miniProgramId}}:{}}}const Wd="hb-sdk-user-data-dialog-style",m1=new Map(br.map(e=>[e.key,e.name]));function E1(e){return(Zt(e)?m1.get(e):void 0)??"游戏资料"}function g1(e){return e==="upload"?"可上传":"无网络权限"}async function p1(e){_1();const t=e.miniProgramName?.trim()||"当前小程序",r=E1(e.resource),n=`“${t}”想读取你的${r}`,i=g1(e.egress),s=BE[e.egress],a=e.egress==="upload"?"↑":"⊘",c=document.createElement("div");c.className="hb-sdk-user-data-dialog",c.innerHTML=`
92
+ <div class="hb-sdk-user-data-dialog__panel">
93
+ <h2>${Et(n)}</h2>
94
+ <dl class="hb-sdk-user-data-dialog__meta">
95
+ <dt>范围</dt><dd>${Et(e.scopeText)}</dd>
96
+ <dt>用途</dt><dd>${Et(e.purposeText)}</dd>
97
+ </dl>
98
+ <p class="hb-sdk-user-data-dialog__egress" data-egress="${Et(e.egress)}">
99
+ <span class="hb-sdk-user-data-dialog__egress-label" aria-hidden="true">${Et(a)}</span>
100
+ <span class="hb-sdk-user-data-dialog__egress-tag">${Et(i)}</span>
101
+ <span>${Et(s)}</span>
102
+ </p>
103
+ <p class="hb-sdk-user-data-dialog__browser-note">读取当前登录黑盒账号的真实资料。许可仅适用于本浏览器,不会同步到手机或其他客户端;来源登录需另行完成。</p>
104
+ <div class="hb-sdk-user-data-dialog__actions">
105
+ <button type="button" data-action="deny">拒绝</button>
106
+ <button type="button" data-action="session">本次使用允许</button>
107
+ ${e.canPersist===!1?"":'<button type="button" class="primary" data-action="persistent">在此浏览器上始终允许</button>'}
108
+ </div>
109
+ </div>
110
+ `;const u=await Lc({root:c,title:n,method:"user.dataPermission.confirm",mode:"browser",signal:e.signal,cancelAction:"cancelled"});return{decision:T1(u)}}function T1(e){return e==="deny"||e==="session"||e==="persistent"?e:"cancelled"}function _1(){if(document.getElementById(Wd))return;const e=document.createElement("style");e.id=Wd,e.textContent=`
111
+ .hb-sdk-user-data-dialog {
112
+ position: absolute;
113
+ inset: 0;
114
+ display: grid;
115
+ place-items: center;
116
+ padding: 24px;
117
+ background: rgba(15, 23, 42, 0.45);
118
+ }
119
+
120
+ .hb-sdk-user-data-dialog__panel {
121
+ width: min(440px, 100%);
122
+ border-radius: 12px;
123
+ padding: 20px;
124
+ background: #fff;
125
+ box-shadow: 0 20px 45px rgba(15, 23, 42, 0.2);
126
+ }
127
+
128
+ .hb-sdk-user-data-dialog__panel h2 {
129
+ margin: 0 0 12px;
130
+ font-size: 17px;
131
+ line-height: 1.45;
132
+ color: #1f2933;
133
+ overflow-wrap: anywhere;
134
+ }
135
+
136
+ .hb-sdk-user-data-dialog__meta {
137
+ display: grid;
138
+ grid-template-columns: auto 1fr;
139
+ gap: 4px 10px;
140
+ margin: 0 0 12px;
141
+ font-size: 12px;
142
+ line-height: 1.6;
143
+ }
144
+
145
+ .hb-sdk-user-data-dialog__meta dt {
146
+ color: #7b8794;
147
+ white-space: nowrap;
148
+ }
149
+
150
+ .hb-sdk-user-data-dialog__meta dd {
151
+ white-space: pre-wrap;
152
+ margin: 0;
153
+ color: #1f2933;
154
+ overflow-wrap: anywhere;
155
+ }
156
+
157
+ .hb-sdk-user-data-dialog__egress {
158
+ display: flex;
159
+ flex-wrap: wrap;
160
+ align-items: baseline;
161
+ gap: 6px;
162
+ margin: 0 0 10px;
163
+ padding: 10px 12px;
164
+ border: 1px solid #cad5e2;
165
+ border-radius: 8px;
166
+ font-size: 12px;
167
+ line-height: 1.6;
168
+ color: #1f2933;
169
+ }
170
+
171
+ .hb-sdk-user-data-dialog__egress[data-egress="upload"] {
172
+ border-color: #e0b34d;
173
+ background: #fff8e6;
174
+ }
175
+
176
+ .hb-sdk-user-data-dialog__egress[data-egress="no_network"] {
177
+ border-color: #9fb3c8;
178
+ background: #f2f6fa;
179
+ }
180
+
181
+ .hb-sdk-user-data-dialog__egress-label {
182
+ font-weight: 700;
183
+ }
184
+
185
+ .hb-sdk-user-data-dialog__egress-tag {
186
+ font-weight: 700;
187
+ white-space: nowrap;
188
+ }
189
+
190
+ .hb-sdk-user-data-dialog__browser-note {
191
+ margin: 0 0 16px;
192
+ font-size: 11px;
193
+ line-height: 1.6;
194
+ color: #7b8794;
195
+ }
196
+
197
+ .hb-sdk-user-data-dialog__actions {
198
+ display: flex;
199
+ flex-wrap: wrap;
200
+ justify-content: flex-end;
201
+ gap: 8px;
202
+ }
203
+
204
+ .hb-sdk-user-data-dialog__actions button {
205
+ min-height: 36px;
206
+ border: 1px solid #cad5e2;
207
+ border-radius: 6px;
208
+ padding: 0 12px;
209
+ background: #fff;
210
+ color: #1f2933;
211
+ cursor: pointer;
212
+ }
213
+
214
+ .hb-sdk-user-data-dialog__actions .primary {
215
+ border-color: #2563eb;
216
+ color: #fff;
217
+ background: #2563eb;
218
+ }
219
+ `,document.head.appendChild(e)}function A1(e){let t,r,n,i,s,a=0,c=0,u=0,d=!1,l=Promise.resolve();const h=new Set,f=()=>{const N=e.resolveScope();return N?JSON.stringify(N):void 0},p=()=>{if(!d)for(const N of h)N()},g=async()=>{if(d||u)return;const N=t,C=f(),I=++a;if(!N||!C){r=void 0,i=void 0,p();return}try{const U=await N.getSnapshot();if(d||I!==a||t!==N||C!==f())return;r=U,n=C,i=void 0}catch(U){if(d||I!==a||t!==N||C!==f())return;r=void 0,s=C,i=U instanceof Error?U.message:"许可状态不可用"}p()},b=N=>{const C=t,I=f(),U=c;if(d||!C||!I)return Promise.resolve();const Y=++a;u++;const R=l.then(async()=>{if(!(d||c!==U||I!==f()))try{const P=await N(C);if(d||Y!==a||c!==U||I!==f())return;r=P,n=I,i=void 0}catch(P){if(d||Y!==a||c!==U||I!==f())return;r=void 0,s=I,i=P instanceof Error?P.message:"许可设置失败"}}).finally(()=>{c===U&&u--,p()});return l=R,R},y=()=>{c++,a++,u=0,l=Promise.resolve(),t=void 0,r=void 0,i=void 0};return{snapshot(){const N=f(),C=N&&N===n?r:void 0,I=e.declared?.();return{scenario:"unknown",dataScenario:"unknown",egressTier:e.egressTier(),declaredSource:I?.source??"manifest",permissionStateReady:C!==void 0,stateError:N&&N===s?i:void 0,simulatedSession:[],resources:br.map(U=>{const Y=C?.resources.find(P=>P.resource===U.key),R=Y?.allowed===!0;return{resource:U.key,name:U.name,declared:I?.resources.includes(U.key)??!1,decision:Y?.decision??"ask",revision:Y?.revision??0,sessionAllowed:Y?.sessionAllowed??!1,sessionSimulated:!1,licensed:R,...R?{sourceStatus:"unknown"}:{}}})}},subscribe(N){return d||h.add(N),()=>h.delete(N)},bind(N){d||(y(),t=N,g())},refresh:g,revokeSession:()=>b(N=>N.revokeSession()),resetAll:()=>b(N=>N.resetAll()),clearSession(){y(),p()},dispose(){d=!0,y(),h.clear()}}}function I1(e){const t="hb_user_game_data_consent_",r="hb_browser_real_user_game_data_consent_",n=i=>i.startsWith(t)?`${r}${i.slice(t.length)}`:i;return{getItem(i){return e.getItem(n(i))},setItem(i,s){e.setItem(n(i),s)},get length(){return e.length},key(i){const s=e.key(i);return s?.startsWith(t)?null:s?.startsWith(r)?`${t}${s.slice(r.length)}`:s}}}function b1(e){const t=it(e.runtimePermissions);let r={};return t.valid&&t.permissions.user_game_data?.status==="enabled"?r=ti(t.permissions.user_game_data.config.resources):e.runtimePermissions===void 0&&e.declaredPermissions?.user_game_data?.enabled&&(r=ti(e.declaredPermissions.user_game_data.resources)),{resources:w0(r),source:"manifest"}}const y1=Object.freeze({user_game_data_permission_show:["entry","reason"],user_game_data_permission_result:["choice","apply_result"],user_game_data_permission_manage:["operation","apply_result","succeeded_count","failed_count"],user_game_data_action:["stage","action_type","outcome","duration_ms"],user_game_data_access_result:["api","trigger","status","error_code","failure_stage","duration_ms","cache_hit"]}),N1="host.userDataTelemetry",$d=80;function w1(e){return{method:N1,detail:{...e.payload,eventName:e.name,message:D1(e)}}}function D1(e){const t=y1[e.name]??[],r=[];for(const n of t){const i=e.payload[n];i!==void 0&&r.push(`${n}: ${Qh(i)}`)}return[e.name,...r].join(" · ")}function Qh(e){let t;if(typeof e=="string")t=e;else if(typeof e=="number"||typeof e=="boolean")t=String(e);else if(Array.isArray(e))t=e.map(r=>Qh(r)).join(",");else try{t=JSON.stringify(e)??""}catch{t="[无法序列化]"}return t.length>$d?`${t.slice(0,$d)}…`:t}const S1=44;function O1(e){const t=()=>e.isCapsuleHidden?.()?0:S1,r=()=>{const n=e.getDeviceMetrics?.();return n?{windowWidth:n.screenWidth,windowHeight:n.screenHeight,screenWidth:n.screenWidth,screenHeight:n.screenHeight,pixelRatio:n.pixelRatio,safeArea:{top:n.safeAreaInsets.top+t(),right:n.screenWidth-n.safeAreaInsets.right,bottom:n.screenHeight-n.safeAreaInsets.bottom,left:n.safeAreaInsets.left}}:{windowWidth:window.innerWidth,windowHeight:window.innerHeight,screenWidth:window.screen.width,screenHeight:window.screen.height,pixelRatio:window.devicePixelRatio}};return{...e.applyDisplay?{applyOrientation:async(n,i)=>(await e.applyDisplay(n,i.signal),{supported:!0})}:{},...e.onViewportChange?{onViewportChange:e.onViewportChange}:{},close:async()=>{await e.close()},reload:async()=>{await e.reload()},getViewportMetrics:()=>e.getViewportMetrics?.()??r(),getNavigationBarHeight:()=>{if(e.getNavigationBarHeight)return e.getNavigationBarHeight();const n=e.getDeviceMetrics?.().statusBarHeight;return n===void 0?0:n+t()},setNavigationBarStyle:n=>{document.documentElement.dataset.navigationBarStyle=n,e.onNavigationBarStyleChange?.(n)},setClipboard:async({text:n})=>{await navigator.clipboard.writeText(n)},showToast:Dm,showLoading:wm,hideLoading:Nm,vibrate:ym,openAppPage:a1,openWindow:o1,showShareMenu:c1,captureAndShare:u1,setScreenshotChromeHidden:bm}}const Kd=["launch-only","stdio","full","prepare-fail","prepare-cancel","launch-cancel","os-blocked","normal-exit","crash","output-limit"],Pi=[{phase:"downloading",loaded:4,total:12},{phase:"verifying",processed:8,total:12},{phase:"extracting",processed:12,total:12}],Zd={"launch-only":[],stdio:["stdio"],full:["stdio","attachments","notifications"],"prepare-fail":[],"prepare-cancel":[],"launch-cancel":[],"os-blocked":[],"normal-exit":["stdio"],crash:["stdio"],"output-limit":["stdio"]};class M1{port;presentation;now;schedule;clearSchedule;onDiagnostic;preparations=new Map;sessions=new Map;eventSink;sessionEventListeners=new Set;nextSessionId=0;constructor(t={}){this.now=t.now??Date.now,this.schedule=t.schedule??((r,n)=>setTimeout(r,n)),this.clearSchedule=t.clearSchedule??(r=>clearTimeout(r)),this.onDiagnostic=t.onDiagnostic??(()=>{}),this.port={getInfo:async r=>this.getInfo(r),getPreparationStatus:async r=>this.getPreparationStatus(r),prepare:(r,n)=>this.prepare(r,n),cancelPreparation:async r=>this.cancelPreparation(r),getActiveSession:async r=>this.getActiveSession(r),launch:async r=>this.launch(r),write:async r=>this.write(r),closeStdin:async r=>this.closeStdin(r),terminate:async r=>this.terminate(r),ackOutput:async r=>this.ackOutput(r),openAttachment:async r=>this.openAttachment(r),showNotification:async r=>this.showNotification(r),onSessionEvent:r=>(this.sessionEventListeners.add(r),()=>this.sessionEventListeners.delete(r))},this.presentation={confirmCompanionOperation:async({action:r,companion:n})=>{const i=n.alias===`${r}-cancel`;return this.diagnostic(`authorization.${i?"cancelled":"granted"}`,n.alias,{action:r}),i?{status:"cancelled"}:{status:"granted"}}}}bindEventSink(t){this.eventSink=t,this.diagnostic(t?"runtime.connected":"runtime.disconnected")}reset(t){const r=t?[t]:[...Kd];for(const n of r){const i=this.preparations.get(n);for(const s of i?.operation?.timers??[])this.clearSchedule(s);i?.operation?.reject(Ze("COMPANION_PREPARATION_CANCELLED","固定 Fake 已重置")),this.preparations.delete(n),this.sessions.delete(n)}this.diagnostic("reset",t)}getInfo(t){const r=this.readAlias(t);return{alias:r,displayName:`Browser Fake: ${r}`,target:r==="os-blocked"?"macos-arm64":"windows-x64",capabilities:Zd[r],archiveBytes:12,signatureStatus:"unsigned"}}getPreparationStatus(t){const r=this.readAlias(t);return this.preparations.get(r)?.status??{state:"not-prepared"}}prepare(t,r){const n=this.readAlias(t),i=this.preparations.get(n);if(i?.status.state==="ready")return Promise.resolve(this.getInfo(n));if(i?.operation)return i.operation.listeners.add(r.onProgress),this.diagnostic("prepare.joined",n),r.onProgress(i.status.state==="preparing"?i.status.progress:Pi[0]),i.operation.promise;let s,a;const c=new Promise((d,l)=>{s=d,a=l}),u={cancelled:!1,listeners:new Set([r.onProgress]),promise:c,reject:a,resolve:s,timers:new Set};{const d={status:{state:"preparing",progress:Pi[0]},operation:u};this.preparations.set(n,d),this.diagnostic("prepare.started",n),Pi.forEach((l,h)=>{const f=this.schedule(()=>{if(u.timers.delete(f),!u.cancelled){d.status={state:"preparing",progress:l};try{u.listeners.forEach(p=>p(l))}catch(p){u.cancelled=!0;for(const g of u.timers)this.clearSchedule(g);d.operation=void 0,d.status={state:"failed",error:{code:"COMPANION_PREPARATION_CANCELLED",message:"Fake progress sink failed",retryable:!0}},this.diagnostic("prepare.progress-handler-failed",n,{message:p instanceof Error?p.message:String(p)}),u.reject(p);return}if(this.diagnostic("prepare.progress",n,{phase:l.phase}),h===Pi.length-1){if(d.operation=void 0,n==="prepare-fail"){d.status={state:"failed",error:{code:"COMPANION_INTEGRITY_FAILED",message:"固定 Fake 完整性校验失败",retryable:!0}},u.reject(Ze("COMPANION_INTEGRITY_FAILED","固定 Fake 完整性校验失败")),this.diagnostic("prepare.failed",n,{code:"COMPANION_INTEGRITY_FAILED"});return}d.status={state:"ready",preparedAt:this.now()},u.resolve(this.getInfo(n)),this.diagnostic("prepare.ready",n)}}},h+1);u.timers.add(f)})}return c}cancelPreparation(t){const r=this.readAlias(t),n=this.preparations.get(r);if(n?.operation){n.operation.cancelled=!0;for(const i of n.operation.timers)this.clearSchedule(i);n.operation.reject(Ze("COMPANION_PREPARATION_CANCELLED","准备已取消")),n.operation=void 0,n.status={state:"not-prepared"},this.diagnostic("prepare.cancelled",r)}}getActiveSession(t){const r=this.readAlias(t),n=this.sessions.get(r);if(!n||n.exited)return;const i=n.snapshot.controllerGeneration;return n.snapshot={...n.snapshot,controllerGeneration:i+1},this.emit(a0,{sessionId:n.snapshot.id,controllerGeneration:i}),n.waitingOutput&&(n.queuedOutput.unshift(n.waitingOutput),n.waitingOutput=void 0,this.flushOutput(n)),this.diagnostic("session.controller-transferred",r,{controllerGeneration:n.snapshot.controllerGeneration}),{...n.snapshot,capabilities:[...n.snapshot.capabilities]}}launch(t){const r=this.readAlias(t);if(this.getPreparationStatus(r).state!=="ready")throw Ze("COMPANION_NOT_PREPARED","固定 Fake 尚未准备完成");if(r==="os-blocked")throw Ze("COMPANION_OS_BLOCKED","操作系统安全策略已阻止启动");const n=this.sessions.get(r);if(n&&!n.exited)throw Ze("COMPANION_LAUNCH_FAILED","固定 Fake Session 已在运行");const i={id:`browser-fake-${++this.nextSessionId}`,alias:r,target:this.getInfo(r).target,capabilities:Zd[r],state:"running",controllerGeneration:1},s={snapshot:i,stdinClosed:!1,exited:!1,queuedOutput:[]};return this.sessions.set(r,s),this.diagnostic("session.launched",r,{capabilities:[...i.capabilities],sessionId:i.id}),i.capabilities.includes("stdio")&&this.schedule(()=>{this.queueOutput(s,"stdout",1,`fake:ready
220
+ `),this.queueOutput(s,"stderr",1,`fake:diagnostic
221
+ `)},20),r==="normal-exit"&&this.schedule(()=>this.requestExit(s,{reason:"exited",exitCode:0}),40),r==="crash"&&this.schedule(()=>this.requestExit(s,{reason:"crashed",exitCode:1}),40),r==="output-limit"&&this.schedule(()=>this.requestExit(s,{reason:"output-limit"}),40),{...i,capabilities:[...i.capabilities]}}write(t){const r=this.readController(t);if(!r.snapshot.capabilities.includes("stdio"))throw Ze("COMPANION_PIPE_CLOSED","stdio 未启用");if(r.stdinClosed)throw Ze("COMPANION_PIPE_CLOSED","stdin 已关闭");const n=Math.max(1,...r.queuedOutput.map(i=>i.sequence),r.waitingOutput?.sequence??0)+1;this.queueOutput(r,"stdout",n,new Uint8Array(t.data)),this.diagnostic("stdio.write",r.snapshot.alias,{bytes:t.data.byteLength})}closeStdin(t){const r=this.readController(t);r.stdinClosed=!0,this.diagnostic("stdio.closed",r.snapshot.alias)}terminate(t){const r=this.readController(t);this.exit(r,{reason:"terminated"})}ackOutput(t){const r=this.readController(t),n=r.waitingOutput;!n||n.stream!==t.stream||n.sequence!==t.sequence||(r.waitingOutput=void 0,this.diagnostic("stdio.ack",r.snapshot.alias,{sequence:t.sequence,stream:t.stream}),this.flushOutput(r))}openAttachment(t){const r=this.readController(t);if(!r.snapshot.capabilities.includes("attachments"))throw Ze("COMPANION_ATTACHMENT_NOT_FOUND","attachments 未启用");if(t.id!=="report")throw Ze("COMPANION_ATTACHMENT_NOT_FOUND","固定 Fake Attachment 不存在");this.diagnostic("attachment.opened",r.snapshot.alias,{id:t.id});const n=new TextEncoder().encode(`Browser Fake Companion report
222
+ `);return{kind:"file",name:"browser-fake-report.txt",mode:"read",create:async()=>{throw Ze("FILE_ACCESS_DENIED","Attachment 只读")},read:async()=>new Uint8Array(n),write:async()=>{throw Ze("FILE_ACCESS_DENIED","Attachment 只读")},stat:async()=>({kind:"file",size:n.byteLength})}}showNotification(t){const r=this.readController(t);if(!r.snapshot.capabilities.includes("notifications"))throw Ze("COMPANION_NOTIFICATION_UNAVAILABLE","notifications 未启用");this.diagnostic("notification.shown",r.snapshot.alias,{category:t.category})}queueOutput(t,r,n,i){t.queuedOutput.push({stream:r,sequence:n,data:typeof i=="string"?new TextEncoder().encode(i):i}),this.flushOutput(t)}flushOutput(t){if(t.exited||t.waitingOutput||!this.eventSink&&this.sessionEventListeners.size===0)return;const r=t.queuedOutput.shift();if(!r){t.pendingExit&&this.exit(t,t.pendingExit);return}t.waitingOutput=r,this.emit(i0,{sessionId:t.snapshot.id,controllerGeneration:t.snapshot.controllerGeneration,...r}),this.diagnostic("stdio.chunk",t.snapshot.alias,{bytes:r.data.byteLength,sequence:r.sequence,stream:r.stream})}requestExit(t,r){t.pendingExit=r,!t.waitingOutput&&t.queuedOutput.length===0&&this.exit(t,r)}exit(t,r){t.exited||(t.exited=!0,t.pendingExit=void 0,t.waitingOutput=void 0,t.queuedOutput.length=0,this.emit(s0,{sessionId:t.snapshot.id,exit:r}),this.diagnostic("session.exit",t.snapshot.alias,{...r}))}readController(t){const r=[...this.sessions.values()].find(n=>n.snapshot.id===t.sessionId);if(!r||r.exited)throw Ze("COMPANION_SESSION_EXITED","固定 Fake Session 不存在");if(r.snapshot.controllerGeneration!==t.controllerGeneration)throw Ze("COMPANION_SESSION_OWNERSHIP_LOST","固定 Fake Session 控制权已转移");return r}readAlias(t){if(!Kd.includes(t))throw Ze("COMPANION_NOT_DECLARED","未知固定 Companion Fake 场景");return t}emit(t,r){this.eventSink?.(t,r),this.sessionEventListeners.forEach(n=>n({type:t,payload:r}))}diagnostic(t,r,n){this.onDiagnostic({action:t,...r?{alias:r}:{},...n?{detail:n}:{}})}}const C1=Object.freeze({[Xs]:!0,[Js]:!0,[ea]:!0,[ta]:!0,[ra]:!0,[na]:!0,[ia]:!0,[sa]:!0,[aa]:!0,[oa]:!0,[ca]:!0,[ua]:!0,[Zn]:!0,[Kn]:!0,[Xn]:!0});function R1(e){return new M1(e)}function Ze(e,t){return Object.assign(new Error(t),{code:e})}function L1(e={}){const t=e.source??B1(e.document??document),r=e.readMetadata??H1,n=e.createPreviewUrl??(d=>URL.createObjectURL(d)),i=e.revokePreviewUrl??(d=>URL.revokeObjectURL(d)),s=new WeakMap,a=new Set,c=d=>{if(!(!d||!a.has(d))){a.delete(d);try{i(d)}catch{}}},u=()=>{for(const d of[...a])c(d)};return e.signal?.addEventListener("abort",u,{once:!0}),{async pick(d,l){switch(Cn(l.signal),e.getMode?.()??"normal"){case"cancel":throw Fe("MEDIA_PICKER_CANCELLED","用户取消了媒体选择");case"system-permission-denied":throw Fe("MEDIA_SYSTEM_PERMISSION_DENIED","系统未授予相机或相册权限");case"prepare-failure":throw Fe("MEDIA_PREPARE_FAILED","媒体准备失败,未保留部分结果");case"preview-unavailable":throw Fe("MEDIA_PREVIEW_UNAVAILABLE","当前 Host 无法提供受控媒体预览")}const h=d.source==="camera"?[await t.capture({mediaType:d.mediaType})]:await P1(t,d);if(Cn(l.signal),d.source==="camera"&&h.length!==1)throw Fe("MEDIA_PREPARE_FAILED","相机模拟必须恰好返回 1 项");const f=[];try{for(const p of h)Cn(l.signal),f.push(await k1(p,d,l.signal,r,n,s,a));Cn(l.signal)}catch(p){for(const g of f)c(s.get(g.file));throw p}return f},release(d){for(const l of d)c(s.get(l.file))}}}async function P1(e,t){const r=await e.pickAlbum({accept:v1(t.mediaType),maxCount:t.maxCount,multiple:t.maxCount>1});if(!r||r.length===0)throw Fe("MEDIA_PICKER_CANCELLED","用户取消了媒体选择");if(r.length>t.maxCount)throw Fe("MEDIA_PREPARE_FAILED",`本次选择 ${r.length} 项,超过 maxCount ${t.maxCount}`);return r}function v1(e){switch(e){case"image":return"image/*";case"video":return"video/*";default:return"image/*,video/*"}}async function k1(e,t,r,n,i,s,a){const c=x1(e.type);if(!c)throw Fe("MEDIA_PREPARE_FAILED",`浏览器未提供可识别的媒体类型: ${e.name}`);if(t.mediaType!=="all"&&t.mediaType!==c)throw Fe("MEDIA_PREPARE_FAILED",`所选媒体 ${e.name} 与 mediaType 不匹配`);const u=await n(e);Cn(r);const d=Xd(u.width),l=Xd(u.height);if(d===void 0||l===void 0)throw Fe("MEDIA_PREPARE_FAILED",`无法读取 ${e.name} 的显示尺寸`);if(c==="video"){if(Jd(u.durationMs)===void 0)throw Fe("MEDIA_PREPARE_FAILED",`无法读取 ${e.name} 的视频时长`)}else if(u.durationMs!==void 0)throw Fe("MEDIA_PREPARE_FAILED",`图片 ${e.name} 不应携带视频时长`);const h=i(e);if(!h)throw Fe("MEDIA_PREVIEW_UNAVAILABLE","无法提供受控媒体预览");const f=U1(e);s.set(f,h),a.add(h);const p={type:c,mimeType:e.type,size:e.size,width:d,height:l,previewUrl:h,file:f};return c==="video"?{...p,durationMs:Jd(u.durationMs)}:p}function x1(e){if(e.startsWith("image/"))return"image";if(e.startsWith("video/"))return"video"}function U1(e){const t=()=>Promise.reject(Object.assign(new Error("Browser Dev Host 媒体句柄只读"),{code:"FILE_ACCESS_DENIED"}));return{kind:"file",name:e.name,mode:"read",create:t,read:async()=>new Uint8Array(await e.arrayBuffer()),write:t,stat:async()=>({kind:"file",size:e.size,...e.lastModified?{modifiedAt:e.lastModified}:{}})}}function B1(e=document){return{pickAlbum(t){return new Promise(r=>{const n=e.createElement("input");n.type="file",n.accept=t.accept,n.multiple=t.multiple,n.style.display="none";let i=!1;const s=()=>{n.removeEventListener("change",c),n.removeEventListener("cancel",u),n.remove()},a=d=>{i||(i=!0,s(),r(d))},c=()=>a(n.files?Array.from(n.files):[]),u=()=>a(void 0);n.addEventListener("change",c),n.addEventListener("cancel",u),e.body.append(n),n.click()})},capture(t){return t.mediaType==="video"?G1():V1()}}}async function H1(e){return e.type.startsWith("video/")?z1(e):F1(e)}async function F1(e){if(typeof globalThis.createImageBitmap=="function"){const r=await globalThis.createImageBitmap(e),n={width:r.width,height:r.height};return r.close?.(),n}const t=URL.createObjectURL(e);try{const r=new Image;return await new Promise((n,i)=>{r.onload=()=>n(),r.onerror=()=>i(Fe("MEDIA_PREPARE_FAILED","无法解码所选图片")),r.src=t}),{width:r.naturalWidth,height:r.naturalHeight}}finally{URL.revokeObjectURL(t)}}async function z1(e){const t=URL.createObjectURL(e),r=document.createElement("video");r.preload="metadata";try{await new Promise((i,s)=>{r.onloadedmetadata=()=>i(),r.onerror=()=>s(Fe("MEDIA_PREPARE_FAILED","无法读取所选视频元数据")),r.src=t});let n=r.duration;return Number.isFinite(n)||(n=await j1(r)),{width:r.videoWidth,height:r.videoHeight,durationMs:Number.isFinite(n)?Math.max(0,Math.round(n*1e3)):0}}finally{r.removeAttribute("src"),URL.revokeObjectURL(t)}}function j1(e){return new Promise(t=>{const r=()=>{e.removeEventListener("durationchange",r),e.removeEventListener("timeupdate",r),t(e.duration)};e.addEventListener("durationchange",r),e.addEventListener("timeupdate",r),e.currentTime=1e101})}async function V1(){const e=document.createElement("canvas");e.width=640,e.height=480;const t=e.getContext("2d");if(!t)throw Fe("MEDIA_PREPARE_FAILED","当前浏览器不支持 2D 画布");const r=t.createLinearGradient(0,0,e.width,e.height);r.addColorStop(0,"#2b2b3a"),r.addColorStop(1,"#0f7b6c"),t.fillStyle=r,t.fillRect(0,0,e.width,e.height),t.fillStyle="#ffffff",t.font="28px sans-serif",t.fillText("Browser Dev Host 模拟拍摄",40,e.height/2);const n=await new Promise(i=>e.toBlob(i,"image/png"));if(!n)throw Fe("MEDIA_PREPARE_FAILED","无法生成测试图片");return new File([n],"browser-dev-camera.png",{type:"image/png"})}async function G1(){const e=document.createElement("canvas");e.width=320,e.height=240;const t=e.getContext("2d");if(!t)throw Fe("MEDIA_PREPARE_FAILED","当前浏览器不支持 2D 画布");const r=e.captureStream?.bind(e),n=globalThis.MediaRecorder;if(!r||!n)throw Fe("MEDIA_PREPARE_FAILED","当前浏览器不支持 MediaRecorder 视频模拟");const i=r.call(e,12),s=new n(i,{mimeType:Y1(n)}),a=[],c=new Promise((l,h)=>{s.ondataavailable=f=>{f.data.size>0&&a.push(f.data)},s.onstop=()=>l(),s.onerror=()=>h(Fe("MEDIA_PREPARE_FAILED","模拟拍摄录制失败"))});s.start();const u=Date.now();await Q1(t,e,()=>Date.now()-u<900),s.stop(),await c;for(const l of i.getTracks())l.stop();const d=new Blob(a,{type:s.mimeType||"video/webm"});if(d.size===0)throw Fe("MEDIA_PREPARE_FAILED","模拟拍摄未生成视频数据");return new File([d],"browser-dev-camera.webm",{type:d.type})}function Y1(e){for(const t of["video/webm;codecs=vp8","video/webm","video/mp4"])if(e.isTypeSupported?.(t))return t;return"video/webm"}async function Q1(e,t,r){for(;r();){const n=Math.min(1,Date.now()%900/900);e.fillStyle="#101820",e.fillRect(0,0,t.width,t.height),e.fillStyle=`rgb(${Math.round(40+n*180)}, 120, ${Math.round(200-n*120)})`,e.fillRect(0,t.height*(1-n),t.width,8),e.fillStyle="#ffffff",e.font="18px sans-serif",e.fillText("模拟拍摄中",24,t.height/2),await new Promise(i=>setTimeout(i,60))}}function Cn(e){if(e.aborted){const t=new Error("Browser Dev Host 媒体选择已取消");throw t.name="AbortError",t}}function Fe(e,t){const r=new Error(t);return r.name="BrowserDevMediaError",r.code=e,r}function Xd(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>0?e:void 0}function Jd(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0?e:void 0}function q1(e){const t=it(e.runtimePermissions),r=uc({declaredPermissions:e.declaredPermissions??{},runtimePermissions:e.runtimePermissions,localDevGrant:e.localDevGrant}),n=[],i=it(e.publishedRuntimePermissions),s=it(r.runtimePermissions);for(const a of cc){const c=a.key,u={network:"Network",companion:"Companion",appProtocol:"AppProtocol"}[c]??a.name;if(!e.declaredPermissions?.[c]?.enabled)continue;const d=t.valid&&t.permissions[c]?.status==="enabled",l=r.temporaryPermissionKeys.some(h=>h===c);n.push({key:c,label:u,state:a.access==="declaration"?"declared":d?"approved":l?"temporary":"unavailable",facts:{platformApproval:a.access==="declaration"?null:d,temporary:l,effective:s.permissions[c]?.status==="enabled",online:i.valid?i.permissions[c]?.status??"missing":"unknown"},...l?{releaseDifference:"本次使用临时授权,发布后仍需平台批准。"}:i.valid&&!i.permissions[c]?{releaseDifference:"线上快照尚未包含该权限,需发布包含声明的新版本。"}:{},...c==="appProtocol"?{highestRisk:!0}:{},...a.access!=="declaration"&&!d&&!l?{reason:c==="appProtocol"?"最高危险权限:可执行任意协议并绕过其他 SDK 能力权限;当前没有有效临时授权,线上未批准":"没有有效的本地临时授权,线上未批准"}:{}})}if(e.declaredPermissions?.network?.useOfficialDomain){const a=t.valid&&t.permissions.network?.status==="enabled"&&t.permissions.network.config.useOfficialDomain===!0;n.push({key:"network.useOfficialDomain",label:"官方域名",state:a?"approved":"unavailable",...a?{}:{reason:"不支持本地临时授权,获得线上批准后才能使用"}})}return n}function Tr(e){return JSON.stringify({source:e.source,miniProgramId:e.miniProgramId,devSessionId:e.devSessionId,contextRevision:e.contextRevision,declaredPermissions:e.declaredPermissions,runtimePermissions:e.runtimePermissions,localDevGrant:e.localDevGrant,companionManifestSha256:e.companionManifestSha256})}const el="__hb_sdk_mini_dev_console_installed__",W1=["log","debug","info","warn","error"];function $1(e,t=console){if(t[el])return;let r=!1;for(const n of W1){const i=t[n];if(typeof i!="function")continue;const s=function(...a){try{e(n,a)}catch{}return i.apply(this,a)};try{t[n]=s,r=!0}catch{break}}r&&(t[el]=!0)}const Lo=1,tl=64*1024,K1=64,Z1=/^[A-Za-z0-9_-]{22}$/;class ft extends TypeError{code;constructor(t,r){super(r),this.name="BrowserDevHostChannelError",this.code=t}}function X1(e,t=!1){const r=eS(e,t);switch(Po(r,"Server message"),tS(r),r.type){case"grant":return Fn(r,["version","type","connectionEpoch","nextClientSequence","nextServerSequence","snapshot"],"grant"),zn(r.connectionEpoch,"connectionEpoch"),_r(r.nextClientSequence,"nextClientSequence"),_r(r.nextServerSequence,"nextServerSequence"),rl(r.snapshot),r;case"event":return Fn(r,["version","type","connectionEpoch","sequence","event","snapshot"],"event"),zn(r.connectionEpoch,"connectionEpoch"),_r(r.sequence,"sequence"),r.event!=="account.changed"&&r.event!=="status.changed"&&or("event must be account.changed or status.changed"),rl(r.snapshot),r;case"heartbeat":return Fn(r,["version","type","connectionEpoch","sequence"],"heartbeat"),zn(r.connectionEpoch,"connectionEpoch"),_r(r.sequence,"sequence"),r;default:return or("Unknown server message type")}}function J1(e){const t=e.connectionEpoch;zn(t,"connectionEpoch"),_r(e.nextSequence,"nextSequence");let r=e.nextSequence;return{get nextSequence(){return r},accept(n){if(zn(n.connectionEpoch,"connectionEpoch"),_r(n.sequence,"sequence"),n.connectionEpoch!==t)throw new ft("INVALID_SEQUENCE","Connection epoch does not match");if(r===void 0)throw new ft("INVALID_SEQUENCE","Sequence is exhausted");if(n.sequence!==r)throw new ft("INVALID_SEQUENCE",`Expected sequence ${r}`);r=r===Number.MAX_SAFE_INTEGER?void 0:r+1}}}function eS(e,t){if(t)throw new ft("BINARY_FRAME","Binary frames are not supported");if(typeof e!="string")throw new ft("TEXT_FRAME_REQUIRED","Channel frame must be text");if(e.length>tl)throw new ft("TEXT_FRAME_TOO_LARGE","Channel text frame exceeds 64 KiB");if(new TextEncoder().encode(e).byteLength>tl)throw new ft("TEXT_FRAME_TOO_LARGE","Channel text frame exceeds 64 KiB");try{return rS(e),JSON.parse(e)}catch(r){throw r instanceof ft?r:new ft("INVALID_JSON","Channel frame must contain strict JSON")}}function rl(e){Po(e,"snapshot"),Fn(e,["account","permissions"],"snapshot"),Po(e.account,"snapshot.account"),Fn(e.account,["revision"],"snapshot.account"),_r(e.account.revision,"snapshot.account.revision"),XD(e.permissions)||or("snapshot.permissions is invalid")}function tS(e){e.version!==Lo&&or("version must be 1")}function Po(e,t){(typeof e!="object"||e===null||Array.isArray(e)||Object.getPrototypeOf(e)!==Object.prototype)&&or(`${t} must be a plain JSON object`)}function Fn(e,t,r,n=[]){const i=Object.keys(e);(t.some(s=>!Object.hasOwn(e,s))||i.some(s=>!t.includes(s)&&!n.includes(s)))&&or(`${r} fields are invalid`)}function _r(e,t){(typeof e!="number"||!Number.isSafeInteger(e)||e<0)&&or(`${t} must be a non-negative safe integer`)}function zn(e,t){(typeof e!="string"||!Z1.test(e))&&or(`${t} must be a 22-character base64url value`)}function or(e){throw new ft("INVALID_MESSAGE",e)}function rS(e){new nS(e).scan()}class nS{constructor(t){this.source=t}position=0;scan(){if(this.skipWhitespace(),this.scanValue(),this.skipWhitespace(),this.position!==this.source.length)throw new SyntaxError("Unexpected trailing JSON data")}scanValue(t=0){const r=this.source[this.position];if(r==="{"||r==="["){if(t>=K1)throw new ft("INVALID_JSON","Channel JSON exceeds maximum nesting depth");return r==="{"?this.scanObject(t):this.scanArray(t)}if(r==='"'){this.scanString();return}this.scanPrimitive()}scanObject(t){this.position+=1,this.skipWhitespace();const r=new Set;if(!this.consume("}"))for(;;){if(this.source[this.position]!=='"')throw new SyntaxError("JSON object key must be a string");const n=this.scanString(),i=JSON.parse(n);if(typeof i!="string")throw new SyntaxError("JSON object key must be a string");if(r.has(i))throw new ft("INVALID_JSON","Channel JSON contains a duplicate key");if(r.add(i),this.skipWhitespace(),!this.consume(":"))throw new SyntaxError("Missing JSON object colon");if(this.skipWhitespace(),this.scanValue(t+1),this.skipWhitespace(),this.consume("}"))return;if(!this.consume(","))throw new SyntaxError("Missing JSON object comma");this.skipWhitespace()}}scanArray(t){if(this.position+=1,this.skipWhitespace(),!this.consume("]"))for(;;){if(this.scanValue(t+1),this.skipWhitespace(),this.consume("]"))return;if(!this.consume(","))throw new SyntaxError("Missing JSON array comma");this.skipWhitespace()}}scanString(){const t=this.position;for(this.position+=1;this.position<this.source.length;){const r=this.source[this.position];if(r==='"')return this.position+=1,this.source.slice(t,this.position);r==="\\"?this.position+=2:this.position+=1}throw new SyntaxError("Unterminated JSON string")}scanPrimitive(){const t=this.position;for(;this.position<this.source.length&&!/[\s,\]}]/.test(this.source[this.position]??"");)this.position+=1;if(t===this.position)throw new SyntaxError("Missing JSON value")}skipWhitespace(){for(;/[\t\n\r ]/.test(this.source[this.position]??"");)this.position+=1}consume(t){return this.source[this.position]!==t?!1:(this.position+=1,!0)}}const nl=[1e3,2e3,4e3,8e3,15e3];function iS(e){const t=new Set,r=e.webSocketFactory??(z=>new WebSocket(z)),n=e.randomValues??(z=>crypto.getRandomValues(z)),i=e.timers??{clearTimeout:z=>window.clearTimeout(z),setTimeout:(z,te)=>window.setTimeout(z,te)},s=e.onlineTarget??(typeof window>"u"?void 0:window),a=e.visibilityTarget??(typeof document>"u"?void 0:document),c=e.isOnline??(()=>typeof navigator>"u"||navigator.onLine!==!1);let u,d,l,h=!1,f=0,p,g=!1,b=!1;const y=new Set,N=(z,te)=>{if(!(!e.onDiagnostic||y.has(z))){y.add(z);try{e.onDiagnostic({phase:z,...te?{code:te}:{}})}catch{}}},C=(z,te,x=!1)=>{if(l&&z.account.revision<l.account.revision)return;const Q=l&&JSON.stringify(z)===JSON.stringify(l);if(l=z,!(Q&&!x))for(const j of t)j(z,te)},I=()=>{if(h||p!==void 0||u)return;const z=nl[Math.min(f,nl.length-1)];f+=1,p=i.setTimeout(()=>{p=void 0,V()},z)},U=()=>{h||!g||u||(p!==void 0&&(i.clearTimeout(p),p=void 0),V())},Y=()=>{c()&&U()},R=()=>{a&&!a.hidden&&U()},P=()=>{b||(b=!0,s?.addEventListener("online",Y),a?.addEventListener("visibilitychange",R))},M=()=>{b&&(b=!1,s?.removeEventListener("online",Y),a?.removeEventListener("visibilitychange",R))},V=()=>{if(h||u)return;g=!0,P(),p!==void 0&&(i.clearTimeout(p),p=void 0);let z,te;try{z=r(e.url)}catch{N("constructor","WEBSOCKET_CONSTRUCTION_FAILED"),I();return}try{te=aS(n)}catch{N("entropy","NONCE_GENERATION_FAILED");try{z?.close(1011,"channel initialization failed")}catch{}I();return}u=z;let x,Q,j;const H=()=>{z.removeEventListener("open",v),z.removeEventListener("message",L),z.removeEventListener("close",q),z.removeEventListener("error",D),d===H&&(d=void 0)},F=()=>{if(u===z){u=void 0,H();try{z.close(1008,"invalid channel state")}catch{}I()}},v=()=>{if(!(h||u!==z))try{z.send(JSON.stringify({version:Lo,type:"hello",csrfToken:e.csrfToken,clientNonce:te}))}catch{N("send","HELLO_SEND_FAILED"),F()}},L=W=>{if(h||u!==z)return;if(typeof W.data!="string"){N("parse","TEXT_FRAME_REQUIRED"),F();return}let $;try{$=X1(W.data)}catch(m){N("parse",m instanceof ft?m.code:"INVALID_MESSAGE"),F();return}if($.type==="grant"){if(j){N("sequence","DUPLICATE_GRANT"),F();return}x=$.connectionEpoch,Q=$.nextClientSequence,j=J1({connectionEpoch:x,nextSequence:$.nextServerSequence}),f=0,y.clear(),C($.snapshot,{type:"grant"});return}if(!j||!x||Q===void 0){N("sequence","MESSAGE_BEFORE_GRANT"),F();return}try{j.accept($)}catch{N("sequence","INVALID_SEQUENCE"),F();return}if($.type==="heartbeat"){try{z.send(JSON.stringify({version:Lo,type:"heartbeat.ack",connectionEpoch:x,sequence:Q}))}catch{N("send","HEARTBEAT_ACK_SEND_FAILED"),F()}Q=Q===Number.MAX_SAFE_INTEGER?void 0:Q+1;return}C($.snapshot,{type:"event",event:$.event},!0)},q=()=>{u===z&&(N("close","SOCKET_CLOSED"),u=void 0,H(),I())},D=()=>{N("open","SOCKET_ERROR"),F()};z.addEventListener("open",v),z.addEventListener("message",L),z.addEventListener("close",q),z.addEventListener("error",D),d=H};return{connect:V,subscribeUpdates(z){return t.add(z),()=>t.delete(z)},dispose(){if(h)return;h=!0,g=!1,M(),p!==void 0&&i.clearTimeout(p),p=void 0;const z=u;u=void 0,d?.(),z?.close(1e3,"client disposed"),t.clear()}}}function sS(e){const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";let r="";for(let n=0;n<e.length;n+=3){const i=e[n]??0,s=e[n+1],a=e[n+2];r+=t[i>>2],r+=t[(i&3)<<4|(s??0)>>4],s!==void 0&&(r+=t[(s&15)<<2|(a??0)>>6]),a!==void 0&&(r+=t[a&63])}return r}function aS(e){const t=e(new Uint8Array(16));if(!(t instanceof Uint8Array)||t.byteLength!==16)throw new TypeError("Channel nonce source must fill 16 bytes");const r=sS(t);if(!/^[A-Za-z0-9_-]{22}$/.test(r))throw new TypeError("Channel nonce source returned invalid bytes");return r}let Ue=!1,qh=!1,$e;const Wh=new AbortController;try{$1((e,t)=>{Ar(`console.${e}`,{source:"host",message:t.map(r=>yS(r)).join(" ")},Date.now(),e==="log"||e==="debug"?"log":e)})}catch{}const oS="/__hb_sdk_bootstrap__",cS="/__hb_sdk__/network",uS="/session/status",dS="/session/request",lS="/session/events",fS=1e3,hS=1e3,mS=15e3,il="dark",ES=["windows","macos","linux","unknown"],$h=new URL(location.href).searchParams,Kh=$h.get("mini_url"),st=$h.get("ui_preview")==="1",gS={get device(){return KS("#device")}};if(!Kh&&!st)throw gS.device.innerHTML='<div class="error">Missing mini_url query.</div>',new Error("Missing mini_url query.");const Zh=Kh??"about:blank",ke=await fm(),Pc=st?void 0:await wt.configure({csrfToken:ke.csrfToken??"",diagnosticsToken:ke.diagnosticsToken??"",signal:Wh.signal,query:VS,onDropped:e=>{ee.diagnosticsDropped=e},onOwnershipLost:sm});ee.diagnosticTargetId=Pc?.targetId??"";ee.diagnosticOwnerId=Pc?.ownerId??"";ee.diagnosticTargetName=Pc?.metadata.displayName??"";ee.openPlatformBaseUrl=ke.openPlatformBaseUrl;ee.devReadiness=ke.devReadiness;ee.miniProgramSupportsDesktop=ke.miniProgramSupportsDesktop;ee.miniProgramPlatforms=ke.devContext.platforms??[];ee.desktopLaunch.workspaceCardsEnabled=ke.workspaceCardsEnabled;cl(ke.hostPlatform);ul(ke.windowForm);ke.lanAddresses;ke.defaultLanAddressId;ke.mobileLaunchRedirect;let Xh=ke.nativeAppLaunchUnavailableReason,jn=ke.devSessionId,vo=ke.miniProgramManifestAccessToken,Yi=ke.workspaceCardsEnabled,Jh=Uc(ke),pt=ke.devContext,qr=ke.browserDevContext,We=Hn(qr);Ks();let sn=Rc(We),Na=0;const Mr=new AbortController;let vc=0,Ht,ko=0,xo,Uo,Xa=!1;const an=zm({apply:jm,waitForLayout:async e=>{await $i(),await hl(e),await ml(e)}});let kc=!1;function Ja(e){if(e.throwIfAborted(),Ue)throw new Er("SESSION_CLOSED","调试台已关闭");if(ee.diagnosticOwnershipLost)throw new Er("TARGET_OWNERSHIP_LOST","此调试页已失效,请重新打开预览");if(!kc)throw new Er("PREVIEW_NOT_READY","调试台正在初始化,请稍后重试");if(Qr)throw new Er("SESSION_DISCONNECTED","开发服务已断开,请重新启动 dev")}const Bo=Hm({observe:()=>{const e=oi()?{width:Wi.value.width,height:Wi.value.height}:{width:oo.value.screenWidth,height:oo.value.screenHeight};return{preset:ee.deviceSelectionId,orientation:oi()?e.width>=e.height?"landscape":"portrait":ee.display.orientation,runtimeStatus:ee.runtimeStatus,viewport:e,instanceId:$e?.mounted?$e.instanceId:null,browserPixelRatio:window.devicePixelRatio,presentation:Gm()}},async selectPreset(e,t){Ja(t),ee.deviceSelectOpen=!1;const r=ee.previewMode,n=$e;Vm(e),await $i(),t.throwIfAborted(),ee.previewMode!==r&&await sl(n,t)},async applyOrientation(e,t){Ja(t),ee.deviceSelectOpen=!1,await an.applyDisplay({mode:e,hideCapsule:ee.display.capsuleHidden},t)},async reload(e){Ja(e),ee.deviceSelectOpen=!1;const t=$e;ar("runtime.restart",{boundary:vc+1}),Rr("manual restart").catch(()=>{}),await sl(t,e)},async waitForLayout(e){await $i(),e.throwIfAborted(),await hl(e),await ml(e)}}),Qi=Km(),em={...Bo.bridge,prepareCapture:Qi.prepare,restoreCapture:Qi.restore,cancel(e){Bo.bridge.cancel(e),Qi.cancel(e)}};window.__HB_SDK_PREVIEW__=em;async function sl(e,t){for(;;){if(t.throwIfAborted(),Ue)throw new Er("SESSION_CLOSED","调试台已关闭");if($e!==e&&Ht===void 0){const r=ee.runtimeStatus;if(r==="ready"||st&&r==="idle")return;if(r==="error")throw new Er("RUNTIME_START_FAILED","小程序 Runtime 启动失败,请查看调试日志");if(r==="closed")throw new Er("RUNTIME_CLOSED","预览窗口已关闭或最小化,请先恢复窗口")}await new Promise((r,n)=>{const i=()=>{clearTimeout(s),n(t.reason)},s=setTimeout(()=>{t.removeEventListener("abort",i),r()},20);t.addEventListener("abort",i,{once:!0}),t.aborted&&i()})}}let Ho,Fo,zo,jo,Vo,Go,al=Date.now(),Qr=!1,Wr=-1,ai=!1,Qt,Yo,Qo,qi,mr;const Ws=new Set,ol="hb-sdk:browser-dev-host:user-data-device";function pS(){try{const e=localStorage.getItem(ol)?.trim();if(e)return e;const t=typeof crypto.randomUUID=="function"?crypto.randomUUID():`mock-${Date.now().toString(36)}`;return localStorage.setItem(ol,t),t}catch{return"browser-mock-device"}}const TS=pS();function _S(){return{miniProgramId:pt.miniProgramId?.trim().toLowerCase()||"anonymous-mini-program",userId:Qt?.trim()||"anonymous-user",deviceId:TS,environment:"development"}}function tm(){return Gh(We.runtimePermissions,sn,We)}function AS(){const e=it(tm());return e.valid&&e.permissions.network?.status==="enabled"?"upload":"no_network"}function IS(){return b1({declaredPermissions:We.declaredPermissions,runtimePermissions:tm()})}const Ft=A1({resolveScope:_S,egressTier:AS,declared:IS});function on(){qh&&Fm({...Ft.snapshot(),targetId:ee.diagnosticTargetId,instanceId:$e?.instanceId})}Ft.subscribe(on);qh=!0;on();function eo(){const e=Ft.snapshot().stateError;if(e)throw new Error(e)}Sm({async refresh(){await Ft.refresh(),eo()},async revokeSession(){await Ft.revokeSession(),eo()},async resetAll(){await Ft.resetAll(),eo()}});const qo=R1({onDiagnostic:({action:e,alias:t,detail:r})=>ar(`companion.fake.${e}`,{...t?{alias:t}:{},...r})}),cn=n1({applyStatus:e=>dm(e,!0),fetchStatus:e=>um(Bc(Mr.signal,e)),getCanonicalRevision:()=>Wr,onError:YS,reconcile:()=>RS(Na)}),Wo=i1({connectEvents:lm,invalidate:()=>cn.invalidate(),isDisposed:()=>Ue,maxDelayMs:mS,minDelayMs:hS,timers:{clearTimeout:e=>window.clearTimeout(e),setTimeout:(e,t)=>window.setTimeout(()=>{e()},t)}});let to=0,vi="",ro=!1,$o,Ko;function rm(){st||Ue||ee.diagnosticOwnershipLost||wt.poll().finally(()=>{!Ue&&!ee.diagnosticOwnershipLost&&(Ko=window.setTimeout(rm,1e3))})}rm();await $s(!1);hm();Em(mm(ke));st&&NS();ci();st||await im();bS();nm();US();await Rr("initial");st||(lm(),MS());kc=!0;function nm(){!st&&!Ue&&($o=window.setTimeout(()=>{im().finally(nm)},1e3))}async function im(){if(!(ro||Ue)){ro=!0;try{const e=await fetch(`${Fc}?after=${to}&limit=500`,{headers:{"x-hb-sdk-csrf":ke.csrfToken??""},signal:AbortSignal.any([Mr.signal,AbortSignal.timeout(5e3)])});if(!e.ok){ee.diagnosticsStale=!0;return}const t=await e.json();if(Ue)return;if(vi&&t.epoch!==vi){to=0,vi=t.epoch,Om();return}vi=t.epoch,ee.uploadSessions=t.uploadSessions;const r=await fetch(`${Fc}?mode=inspect`,{headers:{"x-hb-sdk-csrf":ke.csrfToken??""},signal:AbortSignal.any([Mr.signal,AbortSignal.timeout(5e3)])});if(r.ok){const s=await r.json();ee.diagnosticInstances=s.instances,ee.diagnosticTargets=s.targets,ee.diagnosticPrimaryTargetId=s.primaryTargetId;const a=s.targets.find(c=>c.targetId===ee.diagnosticTargetId);a&&(ee.diagnosticTargetName=a.metadata.displayName),a&&(a.state==="closed"||a.ownerId!==ee.diagnosticOwnerId)&&sm()}ee.diagnosticsStale=!r.ok,ee.diagnosticsGap=ee.diagnosticsGap||t.gap===!0;const n=new Map(ee.diagnosticTargets.map(s=>[s.targetId,s.metadata.displayName])),i=new Map(ee.diagnosticInstances.map(s=>[s.instanceId,n.get(s.targetId)]));for(const s of t.items){const a=Mm(s);a&&(a.targetName=n.get(s.targetId)??i.get(s.instanceId),a.uploadSessionId=s.uploadSessionId,a.uploadSessionName=t.uploadSessions.find(c=>c.id===s.uploadSessionId)?.name,a.dedupeKey=void 0,Cm(a,s.cursor))}to=t.nextCursor}catch{ee.diagnosticsStale=!0}finally{ro=!1}}}function bS(){window.addEventListener("beforeunload",QS),window.addEventListener("hb-sdk:refresh-storage",ci),Ho=Rm(()=>document.querySelector("#host-fullscreen-exit-mount")),Fo=mn(()=>[Vn.value,io.value,ki.value?.state,ki.value?.stale,ki.value?.capabilities.storage].join("|"),()=>{ee.storage=[],ee.storageError="",ci()}),zo=mn(()=>ee.devicePresetId,()=>an.notifyViewportChange(),{flush:"post"}),jo=mn(()=>ee.previewMode,()=>{qt("preview mode changed"),dl(!1),Lm(!1),un("preview mode changed")},{flush:"sync"}),Vo=mn(()=>Wi.value,()=>an.notifyViewportChange(),{flush:"post"}),Go=mn(()=>ee.desktopWindow.closed,(e,t)=>{if(oi()){if(e){qt("desktop window closed"),ee.runtimeStatus="closed";return}t&&ee.runtimeStatus==="closed"&&un("desktop window reopened")}},{flush:"sync"})}function yS(e){if(typeof e=="string")return e;if(e instanceof Error)return(typeof e.stack=="string"?e.stack.split(`
223
+ `).slice(0,4).join(`
224
+ `):"")||`${e.name}: ${e.message}`;if(typeof e=="object"&&e!==null)try{return JSON.stringify(e,null,2)??String(e)}catch{return String(e)}return String(e)}function un(e){Ue||Ht!==void 0||(ar("runtime.restart",{boundary:vc+1}),Ht=window.setTimeout(()=>{Ht=void 0,Ue||Rr(e)},0))}async function Rr(e,t=Zh,r){if(Ue||Qr||ee.diagnosticOwnershipLost)return;if(Ht!==void 0&&window.clearTimeout(Ht),Ht=void 0,qt(e),oi()&&ee.desktopWindow.closed){ee.runtimeStatus="closed";return}const n=document.createElement("iframe");n.dataset.testid="device-iframe",n.title="小程序预览",n.allow="clipboard-read; clipboard-write",n.name="__hb_sdk_mini_dev__";const i=crypto.randomUUID(),s=Pm(i,u=>{st||wt.event(i,u)}),a={instanceId:i,launchUrl:t,locationBasePath:r,interactions:s,sequence:++vc,state:"starting",iframe:n,terminal:new AbortController,permissions:Tm(sn),mounted:!1,hadReady:!1,pendingNavigationReload:!1};if(a.iframe.dataset.hbSdkInstanceId=a.instanceId,$e=a,ee.runtimeStatus="loading",om(),st||wt.send({operation:"register",instanceId:a.instanceId}),await $i(),!Xe(a))return;const c=Am("#device");if(!c){no(a,new Error("预览容器尚未挂载"));return}if(st){c.innerHTML='<div class="browser-mock-preview"><span class="browser-mock-preview__icon">UI</span><strong>Browser Mock</strong><small>mp_preview</small></div>',ee.runtimeStatus="idle";return}c.replaceChildren(a.iframe),a.mounted=!0,wt.send({operation:"activate",instanceId:a.instanceId});try{const u=await VD(wS(a));if(!Xe(a)){u.dispose();return}a.assembly=u,u.ports.companion=qo.port,u.ports.media=L1({getMode:()=>ee.mediaSimulation,signal:a.terminal.signal});const d=$D({signal:a.terminal.signal,csrfToken:()=>ke.csrfToken??""}),l=ZD({signal:a.terminal.signal,refreshAccount:f=>$s(!0,f),request:cm,readState:()=>({signed:pt,browser:We,userId:Qt,accountRevision:Wr,networkEnabled:a.permissions.networkRequest.status==="enabled"})}),h=wD({iframe:a.iframe,authorizationContext:l,ports:{...u.ports,...d},environment:u.environment,hostCapabilities:{...u.hostCapabilities,"media.pick":!0,...d?{"gameSaves.getFile":!0,"user.data.file":!0,"file.readBytes":!0,"file.readText":!0,"file.stat":!0,"file.exists":!0}:{},...C1},authPresentation:u.authPresentation,userDataPresentation:u.userDataPresentation,companionPresentation:qo.presentation,resolveLaunchConfiguration:async()=>l.resolveLaunchConfiguration((await u.resolveLaunch()).configuration,{signal:a.terminal.signal}),dispose:()=>Zo(a),onDevDocumentReload:(f,p)=>{Xe(a)&&Rr("development document reloaded",f,p)},onDevUploadSession:f=>{Xe(a)&&(a.uploadSessionId=f,dn(a,{uploadSessionId:f}))},onReady:()=>{Xe(a)&&(a.state="ready",a.hadReady=!0,Jo.value=d?h.diagnostics.gameSaves:void 0,ee.runtimeStatus="ready",dn(a),Ar("runtime.ready",{generation:a.sequence},Date.now(),void 0,a.instanceId))},onUserDataTelemetry:f=>{Ft.refresh();const p=w1(f);Ar(p.method,p.detail,Date.now(),"info",a.instanceId)},onTrace:f=>OS(a,f),onError:f=>{Xe(a)&&no(a,f)},onCapabilityTrace:f=>{Ar(f.method,{...f,source:"host"},f.timestamp,void 0,a.instanceId),Xe(a)&&f.method==="storage.setStorage"&&f.outcome==="success"&&ci()}});a.runtime=h,await h.start(),Xe(a)&&Ft.bind(h.getDataPermissionBridge())}catch(u){if(!Xe(a))return;no(a,u),Ar("runtime.start.failed",gm(u,a),Date.now(),"error",a.instanceId),a.terminal.abort(u),a.runtime?.destroy(),a.iframe.remove(),Zo(a)}}function sm(){Ue||ee.diagnosticOwnershipLost||(ee.diagnosticOwnershipLost=!0,qt("预览页面授权已失效"),ee.runtimeStatus="closed",kc=!1)}function Xe(e){return $e===e&&!Ue&&!e.terminal.signal.aborted&&e.state!=="closed"&&e.state!=="failed"}function dn(e,t={}){wt.send({operation:"update",instanceId:e.instanceId,state:e.state,...t})}function am(e,t){e.mounted&&(e.mounted=!1,wt.send({operation:"detach",instanceId:e.instanceId,reason:t}))}function Zo(e){$e===e&&(Jo.value=void 0),e.interactions.dispose();const t=e.assembly;e.assembly=void 0,t?.dispose()}function no(e,t){e.state==="failed"||e.state==="closed"||(e.state="failed",e.interactions.dispose(),dn(e,{error:gm(t,e),...e.uploadSessionId?{uploadSessionId:e.uploadSessionId}:{}}),am(e,"Runtime failed"),$e===e&&(ee.runtimeStatus="error"))}function qt(e){const t=$e;t&&($e=void 0,Jo.value=void 0,Ft.clearSession(),t.state!=="failed"&&(t.state="closed",dn(t,{reason:e})),am(t,e),(!Vn.value||Vn.value===ee.diagnosticTargetId)&&(ko+=1,xo?.abort()),vm(),qo.reset(),t.terminal.abort(new DOMException(e,"AbortError")),t.runtime?.destroy(),t.iframe.remove(),Zo(t),an.reset())}function NS(){const e=Qm();ee.diagnosticTargetId=e.targetId,ee.diagnosticOwnerId=e.ownerId,ee.diagnosticPrimaryTargetId=e.targetId,ee.diagnosticTargetName=e.metadata.displayName,ee.diagnosticTargets=[e],ee.diagnosticInstances=[{instanceId:e.currentInstanceId,targetId:e.targetId,ownerId:e.ownerId,adapterId:e.adapterId,kind:"browser",capabilities:e.capabilities,state:"ready",startedAt:Date.now(),updatedAt:Date.now(),startCursor:0,lastCursor:0,stale:!1}];const t={...e,targetId:"ui-preview-phone",ownerId:"ui-preview-phone-owner",kind:"mobile",currentInstanceId:"ui-preview-phone-instance",metadata:{displayName:"小黑盒",deviceModel:"iPhone 16 Pro",os:"iOS"}};ee.diagnosticTargets.push(t),ee.diagnosticInstances.push({...ee.diagnosticInstances[0],instanceId:t.currentInstanceId,targetId:t.targetId,ownerId:t.ownerId,kind:"mobile"}),so({...ao("console.error",{source:"app",message:"真机示例:请求超时"},Date.now(),"error"),targetId:t.targetId,instanceId:t.currentInstanceId}),ar("runtime.ready",{generation:1}),so(ao("console.info",{source:"app",message:"页面初始化完成"},Date.now(),"info")),ar("user.getInfo",{durationMs:34,outcome:"success"}),ar("network.request",{durationMs:86,network:{method:"GET",origin:"https://api.example.com",pathname:"/demo",responseStatus:200},outcome:"success"})}function wS(e){const t=e.terminal.signal,r=We,n=jn,i=Gh(r.runtimePermissions,e.permissions,r),s=oi();return{signal:t,account:{async getCurrentUserId(){return(await $s(!1,t)).user_id},async ensureAuthenticated({signal:a}){await $s(!1,a)},onChange(a){return Ws.add(a),()=>Ws.delete(a)}},authenticatedRequest:cm,storage:{area:"local",storage:I1(localStorage)},presentation:O1({close:async()=>{Xe(e)&&(qt("mini program closed"),om(),ee.runtimeStatus="closed",s&&dl(!0))},reload:()=>{Xe(e)&&(e.pendingNavigationReload=!0)},onNavigationBarStyleChange:a=>{Xe(e)&&ll(a)},...s?{getViewportMetrics:()=>{const a=Wi.value;return{windowWidth:a.width,windowHeight:a.height,screenWidth:window.screen.width,screenHeight:window.screen.height,pixelRatio:window.devicePixelRatio,safeArea:{left:0,right:a.width,top:0,bottom:a.height}}},getNavigationBarHeight:()=>Ym}:{getDeviceMetrics:()=>oo.value,applyDisplay:(a,c)=>an.applyDisplay(a,c),isCapsuleHidden:()=>ee.display.capsuleHidden},onViewportChange:a=>an.onViewportChange(a)}),environment:{getCurrentHref:()=>location.href,isDevRuntime:()=>!0,setDocumentTitle:a=>{document.title=a}},resolveLaunch:async()=>({configuration:h1({launchUrl:e.launchUrl,locationBasePath:e.locationBasePath,runtimePermissions:i,networkPolicy:r.networkPolicy,firstParty:r.source==="remote"&&r.firstParty===!0,...ee.miniProgram.bound&&ee.miniProgram.name.trim()?{miniProgramName:ee.miniProgram.name}:{},...r.miniProgramId?{miniProgramId:r.miniProgramId}:n?{anonymousStorageScope:n}:{},operatingSystem:s?ee.hostPlatform:km.value.platform}),hostHints:{launchKind:r.source==="remote"?"dev-session":"anonymous-local-dev"}}),authPresentation:{confirmAuthorization:a=>f1(a),confirmFollowAuthor:a=>s1(a)},userDataPresentation:{confirmDataPermission:p1},protocol:DS(e)}}function oi(){return ee.previewMode==="desktop"}function DS(e){return{async invoke(t){Ar("device.executeProtocol",{outcome:"success",delivery:"mock",protocolType:SS(t)},Date.now(),void 0,e.instanceId)}}}function SS(e){if(typeof e!="string")return typeof e.protocol_type=="string"?e.protocol_type:void 0;const t=/^heybox:\/\/(.+)$/i.exec(e.trim());if(t)try{const r=JSON.parse(decodeURIComponent(t[1]));return Tt(r)&&typeof r.protocol_type=="string"?r.protocol_type:void 0}catch{return}}function om(){document.documentElement.dataset.navigationBarStyle=il,ll(il)}function OS(e,t){Xe(e)&&t.type==="document_validation"&&typeof t.documentVerifying=="boolean"&&dn(e,{documentVerifying:t.documentVerifying}),Ue||wt.event(e.instanceId,{source:"runtime",level:t.type==="error"||t.type==="security_violation"?"error":"info",timestamp:t.timestamp,phase:t.type,method:t.method??`runtime.${t.type}`,message:JSON.stringify(xm({...t,generation:e.sequence})),...t.errorCode?{errorCode:t.errorCode}:{}}),e.runtimeId!==t.runtimeId&&(e.runtimeId=t.runtimeId,dn(e,{runtimeId:t.runtimeId})),Xe(e)&&e.pendingNavigationReload&&t.type==="bridge_response"&&t.method==="navigation.reload"&&t.outcome==="success"&&(e.pendingNavigationReload=!1,un("navigation.reload"))}async function cm(e,t){if(e.redirectPolicy!=="error")throw new Error("Browser Dev Host network 只允许 no-follow redirect policy");const n=e.target.kind==="absolute-url"&&e.source==="public-sdk"&&e.target.kind==="absolute-url"?{url:e.target.url,method:e.method,params:e.params,data:e.data,bodyEncoding:e.bodyEncoding,headers:e.headers,timeout:e.timeout}:void 0;if(!n&&e.source!=="runtime-private")throw new Error("Browser Dev Host 的公开请求只支持 absolute URL");const i=await xS(n?cS:dS,{method:"POST",body:JSON.stringify(n??{target:e.target,method:e.method,params:e.params,data:e.data,headers:e.headers,credentials:e.source==="runtime-private"?e.credentials:void 0,security:e.source==="runtime-private"?e.security:void 0,bodyEncoding:e.bodyEncoding,timeout:e.timeout}),signal:t.signal});!n&&i.status===401&&cn.invalidate();const s=await i.json();if(!i.ok)throw s;return s}async function $s(e,t){const r=Na,n=await um(Bc(Mr.signal,t));return pm(r)?dm(n,e).status:Xo()}async function um(e){return await(await fetch(uS,{cache:"no-store",credentials:"same-origin",redirect:"error",signal:e})).json()}function dm(e,t){if(!Number.isSafeInteger(e.revision)||e.revision<Wr)return{changed:!1,status:Xo()};const r=e.authenticated?e.user_id:void 0,n=e.authenticated?ze(e.nickname):void 0,i=e.authenticated?ze(e.avatar):void 0,s=e.revision!==Wr||e.authenticated!==ai||r!==Qt||n!==Yo||i!==Qo;return Wr=e.revision,ai=e.authenticated,Qt=r,Yo=n,Qo=i,hm(),on(),t&&s&&Ws.forEach(a=>a(Qt)),{changed:s,status:Xo()}}function Xo(){return{authenticated:ai,revision:Wr,...ai&&Qt?{user_id:Qt}:{}}}function MS(){if(!(!ke.csrfToken||Ue))try{const e=new URL("/__hb_sdk__/channel",location.href);e.protocol=e.protocol==="https:"?"wss:":"ws:",mr=iS({csrfToken:ke.csrfToken,onDiagnostic:t=>ar("channel.diagnostic",t),url:e.toString()}),mr.subscribeUpdates((t,r)=>CS(t,r)),mr.connect()}catch{mr?.dispose(),mr=void 0}}function CS(e,t){cn.invalidate(e.account.revision),$S(sn,e.permissions)?t.type==="event"&&t.event==="status.changed"&&Rr("status changed"):(sn=Tm(e.permissions),LS())}function lm(){if(qi?.close(),qi=void 0,!Qt||Ue)return;const e=new EventSource(lS);qi=e,e.addEventListener("account-invalidated",()=>{cn.invalidate()}),e.addEventListener("account-revision",()=>{cn.invalidate()}),e.onopen=()=>{Wo.reset()},e.onerror=()=>{e.close(),Wo.schedule()}}async function RS(e){pm(e)&&await Rr("account revision changed")}async function LS(){Ue||await Rr("permission changed")}async function fm(e){const t=await fetch(oS,{cache:"no-store",credentials:"same-origin",redirect:"error",signal:Bc(AbortSignal.timeout(5e3),e)});if(!t.ok)throw new Error("Browser Dev Host bootstrap request failed");const r=await t.json();if(!Tt(r))throw new Error("Browser Dev Host bootstrap is invalid");const n=WS(r.mobileLaunchRedirect);if(Object.hasOwn(r,"mobileLaunchRedirect")&&r.mobileLaunchRedirect!==void 0&&!n)throw new HS;return{openPlatformBaseUrl:typeof r.openPlatformBaseUrl=="string"?r.openPlatformBaseUrl:void 0,devReadiness:kS(r.devReadiness),csrfToken:typeof r.csrfToken=="string"?r.csrfToken:void 0,diagnosticsToken:typeof r.diagnosticsToken=="string"?r.diagnosticsToken:void 0,defaultLanAddressId:typeof r.defaultLanAddressId=="string"?r.defaultLanAddressId:void 0,devSessionId:typeof r.devSessionId=="string"&&/^[a-f0-9]{32}$/.test(r.devSessionId)?r.devSessionId:void 0,devContext:Yd(r.devContext,r.runtimePermissions),browserDevContext:Yd(r.browserDevContext??r.devContext,r.runtimePermissions),lanAddresses:Array.isArray(r.lanAddresses)?r.lanAddresses.filter(qS):[],loginAvailable:r.loginAvailable===!0,miniProgram:zS(r.miniProgram),miniProgramSupportsDesktop:r.miniProgramSupportsDesktop===!0,workspaceCardsEnabled:r.workspaceCardsEnabled===!0,mobileLaunchRedirect:n,nativeAppLaunchUnavailableReason:typeof r.nativeAppLaunchUnavailableReason=="string"?r.nativeAppLaunchUnavailableReason:void 0,miniProgramManifestAccessToken:typeof r.miniProgramManifestAccessToken=="string"?r.miniProgramManifestAccessToken:void 0,windowForm:vS(r.windowForm),hostPlatform:PS(r.hostPlatform)}}function PS(e){return ES.includes(e)?e:"unknown"}function vS(e){if(!Tt(e))return;const t=a=>typeof a=="number"&&Number.isFinite(a)&&a>0?a:void 0,r=t(e.defaultWidth),n=t(e.defaultHeight),i=t(e.minWidth),s=t(e.minHeight);return{...r===void 0?{}:{defaultWidth:r},...n===void 0?{}:{defaultHeight:n},...i===void 0?{}:{minWidth:i},...s===void 0?{}:{minHeight:s},...typeof e.resizable=="boolean"?{resizable:e.resizable}:{}}}function kS(e){if(!Tt(e))return;const t=a=>{if(!(!Tt(a)||!["ready","pending","blocked","not-configured"].includes(String(a.state))))return{state:a.state,...typeof a.reason=="string"?{reason:a.reason.slice(0,240)}:{}}},r=t(e.browser),n=t(e.mobile),i=t(e.companion);if(!r||!n||!i||!Tt(e.companion))return;const s=e.companion;return{browser:r,mobile:n,companion:{...i,...typeof s.digest=="string"&&/^[a-f0-9]{64}$/.test(s.digest)?{digest:s.digest}:{},artifacts:Array.isArray(s.artifacts)?s.artifacts.filter(a=>Tt(a)&&typeof a.alias=="string"&&/^[a-z][a-z0-9-]{0,31}$/.test(a.alias)&&["windows-x64","macos-arm64"].includes(String(a.target))).map(({alias:a,target:c})=>({alias:a,target:c})):[]}}}async function xS(e,t){const r=new Headers(t.headers);return r.set("content-type","application/json"),ke.csrfToken&&r.set("x-hb-sdk-csrf",ke.csrfToken),fetch(e,{...t,headers:r,cache:"no-store",credentials:"same-origin",redirect:"error"})}function US(){xc(),st||(Uo=window.setInterval(()=>{FS()},fS))}function BS(e){const t=Tr(We),r=!!pt.localDevLaunchToken,n=pt.developmentSnapshotDigest;ee.devReadiness=e.devReadiness,ee.miniProgramSupportsDesktop=e.miniProgramSupportsDesktop,ee.miniProgramPlatforms=e.devContext.platforms??[],cl(e.hostPlatform),ul(e.windowForm),Yi=e.workspaceCardsEnabled,Jh=Uc(e),pt=e.devContext,qr=e.browserDevContext,We=Hn(qr),sn=Rc(We),Ks(),e.lanAddresses,e.defaultLanAddressId,e.mobileLaunchRedirect,Xh=e.nativeAppLaunchUnavailableReason,jn=e.devSessionId,vo=e.miniProgramManifestAccessToken,Em(mm(e)),xc(),(t!==Tr(We)||r!==!!pt.localDevLaunchToken||n!==pt.developmentSnapshotDigest&&($e?.state==="starting"||$e?.state==="failed"))&&(qt("local permission context changed"),un("local permission context changed"))}function Ks(){if(st){ee.localPermissions=qm(),ee.devContextWarning="";return}ee.localPermissions=q1(We),ee.devContextWarning=We.source==="anonymous"?"未连接线上上下文":We.warning?"本地上下文受限,请检查 CLI 状态":"",on()}function xc(){let e;try{e=Um(Zh)}catch{}const t=pt.miniProgramId?.trim().toLowerCase();let r=Xh?.trim()??"";!r&&(pt.source!=="remote"||!t)&&(r="请先绑定可管理的小程序"),!r&&!pt.localDevLaunchToken?.trim()&&(r="正在等待有效的本地调试启动票"),!r&&Yi&&!jn&&(r="本地调试会话尚未就绪"),!r&&pt.expiresAt!==void 0&&pt.expiresAt<=Date.now()&&(r="本地调试启动票已过期"),!r&&!e&&(r="未发现可用的本机调试地址"),fl({...e?{address:e}:{},...t?{miniProgramId:t}:{},...Yi&&jn?{devSessionId:jn}:{},...vo?{miniProgramManifestToken:vo}:{},workspaceCardsEnabled:Yi,ready:r==="",...r?{unavailableReason:r}:{}})}class HS extends Error{}async function FS(){if(!(Xa||Ue)){Xa=!0;try{const e=await fm();al=Date.now();const t=Qr;Qr=!1;const r=Uc(e);if(!t&&r===Jh&&Tr(Hn(e.browserDevContext))===Tr(We)){qr=e.browserDevContext,We=Hn(qr),Ks();return}BS(e),t&&un("CLI dev session reconnected")}catch{const t=Hn(qr);Tr(t)!==Tr(We)&&(We=t,sn=Rc(We),Ks(),qt("local permission context expired"),un("local permission context expired"),xc()),Date.now()-al>=3e4&&!Qr&&(Qr=!0,qt("CLI dev session disconnected"),Am("#device")?.replaceChildren(),ee.runtimeStatus="closed",ee.localPermissions=[],ee.devContextWarning="调试会话已断开",fl({ready:!1,unavailableReason:"调试会话已断开"}),ee.devReadiness={browser:{state:"blocked",reason:"调试会话已断开,等待 CLI 恢复"},mobile:{state:"blocked",reason:"调试会话已断开"},companion:{state:"blocked",reason:"调试会话已断开"}})}finally{Xa=!1}}}function Uc(e){return JSON.stringify({devReadiness:e.devReadiness,devSessionId:e.devSessionId,defaultLanAddressId:e.defaultLanAddressId,lanAddresses:e.lanAddresses,mobileLaunchRedirect:e.mobileLaunchRedirect?{addressId:e.mobileLaunchRedirect.addressId,expiresAt:e.mobileLaunchRedirect.expiresAt,token:e.mobileLaunchRedirect.token}:void 0,devContext:{platforms:e.devContext.platforms,permissionContext:Tr(e.devContext),expiresAt:e.devContext.expiresAt,localDevLaunchToken:e.devContext.localDevLaunchToken,miniProgramId:e.devContext.miniProgramId,source:e.devContext.source},nativeAppLaunchUnavailableReason:e.nativeAppLaunchUnavailableReason,miniProgramManifestAccessToken:e.miniProgramManifestAccessToken,miniProgramSupportsDesktop:e.miniProgramSupportsDesktop,workspaceCardsEnabled:e.workspaceCardsEnabled,hostPlatform:e.hostPlatform,windowForm:e.windowForm})}function hm(){if(!ai){ee.account={authenticated:!1,avatar:"",nickname:"未登录"};return}ee.account={authenticated:!0,avatar:Qo??"",nickname:Yo||Qt||"已登录"}}function mm(e){if(e.miniProgram?.miniProgramId)return e.miniProgram;const t=e.devContext.miniProgramId?.trim();return t?{miniProgramId:t}:e.miniProgram??null}function Em(e){if(!!!e?.miniProgramId||!e){ee.miniProgram={bound:!1,id:"",iconUrl:"",name:"未绑定小程序",detail:"本地调试",description:"",version:""},on();return}ee.miniProgram={bound:!0,id:e.miniProgramId,iconUrl:e.iconUrl??"",name:e.name||e.miniProgramId,detail:[e.miniProgramId,e.version].filter(Boolean).join(" · "),description:e.description??"",version:e.version??""},on()}function zS(e){if(e===null)return null;if(!Tt(e))return;const t=ze(e.miniProgramId)??ze(e.mini_program_id);if(t)return{miniProgramId:t,...ze(e.description)?{description:ze(e.description)}:{},...ze(e.name)?{name:ze(e.name)}:{},...ze(e.iconUrl)??ze(e.icon_url)?{iconUrl:ze(e.iconUrl)??ze(e.icon_url)}:{},...ze(e.status)?{status:ze(e.status)}:{},...ze(e.version)?{version:ze(e.version)}:{},...ze(e.developerName)??ze(e.developer_name)?{developerName:ze(e.developerName)??ze(e.developer_name)}:{}}}function ze(e){return typeof e=="string"&&e.trim()?e.trim():void 0}async function ci(){const e=++ko;xo?.abort();const t=new AbortController;xo=t;const r=Vn.value,n=!r||r===ee.diagnosticTargetId,i=ki.value,s=io.value||(n?$e?.instanceId:void 0),a=()=>!Ue&&e===ko&&r===Vn.value&&s===(io.value||(n?$e?.instanceId:void 0));if(!n&&(!i||!s||i.stale||i.state!=="attached"||!i.capabilities.storage)){ee.storage=[],ee.storageError=!i||!i.capabilities.storage?"当前设备不支持存储诊断":"当前设备未连接或没有运行实例";return}if(st){ee.storage=[{area:"local",key:"preferences",serializedValue:'{"theme":"light","language":"zh-CN"}',bytes:36},{area:"local",key:n?"lastOpenedProject":"deviceModel",serializedValue:n?'"demo-project"':'"iPhone 16 Pro"',bytes:n?14:15}],ee.storageError="";return}if(!s){ee.storage=[],ee.storageError="";return}try{const c=await Bm({instanceId:s,resource:"storage"},{csrfToken:ke.csrfToken,signal:AbortSignal.any([t.signal,Mr.signal])});if(!a())return;if(c.code)throw new Error(c.error??"Storage 诊断查询失败");ee.storage=c.value,ee.storageError=""}catch(c){if(!a())return;ee.storage=[],ee.storageError=_m(c)}}function gm(e,t=$e){const r=(u,d)=>{if(!(!u||typeof u!="object"))try{return Object.getOwnPropertyDescriptor(u,d)?.value}catch{return}},n=(u,d)=>{const l=r(u,d);return typeof l=="string"?l.slice(0,8192):void 0},i=r(e,"cause"),s=n(e,"stack")??n(i,"stack"),a=n(e,"name")??n(i,"name"),c=typeof i=="string"?i:[n(i,"name"),n(i,"message")].filter(Boolean).join(": ");return{code:n(e,"code")??"RUNTIME_START_FAILED",message:n(e,"message")??(typeof e=="string"?e:"Runtime 启动失败"),phase:t?.hadReady?"running":"starting",...a?{name:a}:{},...s?{stack:s}:{},...c?{cause:c}:{}}}function Ar(e,t,r=Date.now(),n,i){jS(ao(e,t,r,n==="debug"?"log":n),i)}function jS(e,t){if(Ue)return;if(st){so({...e,targetId:ee.diagnosticTargetId});return}const r=Tt(e.detail)?e.detail:{};wt.event(t,{source:t&&e.source==="runtime"?"runtime":"host",level:e.level,timestamp:e.timestamp,message:e.summary,method:e.method,...typeof r.phase=="string"?{phase:r.phase}:{},...e.callId?{callId:e.callId}:{},...e.outcome?{outcome:e.outcome}:typeof r.outcome=="string"?{outcome:r.outcome}:{},...e.durationMs===void 0?{}:{durationMs:e.durationMs},...typeof r.startedAt=="number"?{startedAt:r.startedAt}:{},...e.errorCode?{errorCode:e.errorCode}:{},...Tt(r.network)?{network:r.network}:{}})}async function VS(e){const t=$e;if(!t||e.instanceId!==t.instanceId||!Xe(t)||!t.runtime)return{code:"closed",error:"该实例已结束"};if(Date.now()>=e.deadline)return{code:"timeout",error:"查询已超过期限"};if(e.resource==="presentation")return{value:t.interactions.snapshot()};if(e.resource==="sandbox")return{code:"unsupported",error:"Browser Dev Host 不提供文件系统能力"};const r=t.runtime,n=r.diagnostics.storage;if(!n)return{code:"unsupported",error:"当前 Host 不支持 Storage 诊断"};const i=AbortSignal.any([Mr.signal,t.terminal.signal,AbortSignal.timeout(Math.max(1,e.deadline-Date.now()))]);let s,a;try{a=await Promise.race([n.getSnapshot(),new Promise((c,u)=>{s=()=>u(i.reason),i.addEventListener("abort",s,{once:!0}),i.aborted&&s()})])}catch{return{code:Date.now()>=e.deadline?"timeout":"closed",error:"实例查询已结束或超过期限"}}finally{s&&i.removeEventListener("abort",s)}return!Xe(t)||r!==t.runtime||e.instanceId!==t.instanceId?{code:"closed",error:"查询期间实例已结束"}:{value:a}}function GS(e,t){ar("host.message",{message:e,status:t})}function YS(e){Ue||GS(_m(e),"error")}function ar(e,t){Ar(e,t)}function QS(){wt.close(),$o!==void 0&&window.clearTimeout($o),Ko!==void 0&&window.clearTimeout(Ko),!Ue&&(Ue=!0,Qi.dispose(),Bo.dispose(),window.__HB_SDK_PREVIEW__===em&&delete window.__HB_SDK_PREVIEW__,window.removeEventListener("hb-sdk:refresh-storage",ci),Na+=1,Mr.abort(new DOMException("Browser Dev Host disposed","AbortError")),cn.dispose(),qt("Browser Dev Host disposed"),Ft.dispose(),wt.send({operation:"close-target",reason:"Browser Dev Host disposed"}),window.setTimeout(()=>Wh.abort(),2e3),qi?.close(),mr?.dispose(),mr=void 0,Wo.dispose(),Ht!==void 0&&window.clearTimeout(Ht),Ht=void 0,Uo!==void 0&&window.clearInterval(Uo),Ws.clear(),Ho?.(),Ho=void 0,Fo?.(),Fo=void 0,zo?.(),zo=void 0,jo?.(),jo=void 0,Vo?.(),Vo=void 0,Go?.(),Go=void 0)}function Bc(e,t){return t?AbortSignal.any([e,t]):e}function pm(e){return!Ue&&e===Na}function qS(e){return Tt(e)&&typeof e.address=="string"&&typeof e.appUrl=="string"&&typeof e.id=="string"&&typeof e.name=="string"&&(e.mobileAppQrPayload===void 0||typeof e.mobileAppQrPayload=="string")}function WS(e){if(!(!Tt(e)||typeof e.addressId!="string"||!e.addressId||typeof e.expiresAt!="number"||!Number.isFinite(e.expiresAt)||typeof e.token!="string"||!/^[A-Za-z0-9_-]{22}$/.test(e.token)))return{addressId:e.addressId,expiresAt:e.expiresAt,token:e.token}}function Tm(e){return{networkRequest:{...e.networkRequest}}}function $S(e,t){return e.networkRequest.status===t.networkRequest.status&&e.networkRequest.useOfficialDomain===t.networkRequest.useOfficialDomain}function _m(e){return e instanceof Error&&e.message?e.message:"操作失败"}function Tt(e){return Object.prototype.toString.call(e)==="[object Object]"}function KS(e){const t=document.querySelector(e);if(!t)throw new Error(`Missing Browser Dev Host element: ${e}`);return t}function Am(e){return document.querySelector(e)??void 0}