@heybox/hb-sdk 0.9.6-alpha.11 → 0.9.6-alpha.14

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 (48) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/README.md +4 -1
  3. package/THIRD_PARTY_NOTICES.md +472 -48
  4. package/dist/cli-chunks/{artifact-BW6SD1G6.cjs → artifact-DTqf7LjW.cjs} +6 -5
  5. package/dist/cli-chunks/{build-B0Id0UTN.cjs → build-BY4DoIBI.cjs} +6 -5
  6. package/dist/cli-chunks/{create-DVu93Ekp.cjs → create-DG-eZzS2.cjs} +322 -4
  7. package/dist/cli-chunks/{dev-CeSjpEZQ.cjs → dev-BeSGi9u8.cjs} +20 -16
  8. package/dist/cli-chunks/{dev-context-CVc_BsWR.cjs → dev-context-7fvQuwt0.cjs} +22 -14
  9. package/dist/cli-chunks/{doctor-BF9mtkJr.cjs → doctor-DcxJh-U3.cjs} +1 -1
  10. package/dist/cli-chunks/{games-BKnDCklM.cjs → games-CbQNW3Z3.cjs} +1 -1
  11. package/dist/cli-chunks/{index-Cgui_8Rk.cjs → index-NJUh9sVX.cjs} +1 -1
  12. package/dist/cli-chunks/{index-Rp3UMZIO.cjs → index-lnwfzT8S.cjs} +73 -20
  13. package/dist/cli-chunks/index.esm-CvMA_ppV.cjs +7977 -0
  14. package/dist/cli-chunks/{index.esm-BK0eVYaM.cjs → index.esm-DOXvj-ZK.cjs} +7 -6
  15. package/dist/cli-chunks/{login-DpeDN-mt.cjs → login-PYy4XDVv.cjs} +1 -1
  16. package/dist/cli-chunks/{project-vite-Cg3jYqAJ.cjs → project-vite-Dzd2JLIc.cjs} +1 -1
  17. package/dist/cli-chunks/{remote-BQ-9rhTb.cjs → remote-r0tXpJh6.cjs} +13 -8
  18. package/dist/cli-chunks/{runtime-permission-env-BgipCJ0Z.cjs → runtime-permission-env-CN2K4GG7.cjs} +52 -6990
  19. package/dist/cli-chunks/{skill-D7pd4yPq.cjs → skill-BbrtzJTC.cjs} +2 -2
  20. package/dist/cli-chunks/{version-DbjRZkb6.cjs → version-SpegXNoR.cjs} +1 -1
  21. package/dist/cli.cjs +1 -1
  22. package/dist/devtools/browser-dev-host/assets/browser-dev-host-DdLOxwBk.js +228 -0
  23. package/dist/devtools/browser-dev-host/assets/desktop-app-launch-DeuOZXeW.js +6 -0
  24. package/dist/devtools/browser-dev-host/assets/index-B-2wxdQX.js +567 -0
  25. package/dist/devtools/browser-dev-host/assets/index-ophYZqpX.css +1 -0
  26. package/dist/devtools/browser-dev-host/assets/linux-DwJAcUeD.svg +1 -0
  27. package/dist/devtools/browser-dev-host/index.html +6 -4
  28. package/dist/index.cjs.js +1030 -155
  29. package/dist/index.esm.js +1030 -155
  30. package/dist/miniapp-publish.cjs.js +1071 -130
  31. package/dist/miniapp-publish.esm.js +1071 -130
  32. package/dist/protocol.cjs.js +727 -158
  33. package/dist/protocol.esm.js +711 -159
  34. package/dist/templates/vanilla-vite-js/README.md.ejs +27 -0
  35. package/dist/templates/vanilla-vite-js/package.json.ejs +1 -1
  36. package/dist/templates/vanilla-vite-js/src/user-game-data.js.ejs +1 -0
  37. package/dist/vite.cjs.js +1076 -133
  38. package/dist/vite.esm.js +1076 -133
  39. package/package.json +6 -7
  40. package/skill/SKILL.md +4 -0
  41. package/skill/skill.json +5 -5
  42. package/types/index.d.ts +386 -9
  43. package/types/miniapp-publish/index.d.ts +18 -2
  44. package/types/protocol.d.ts +1 -1
  45. package/dist/devtools/browser-dev-host/assets/browser-dev-host-DVlT56iQ.js +0 -100
  46. package/dist/devtools/browser-dev-host/assets/desktop-app-launch-BzRxl_MM.js +0 -6
  47. package/dist/devtools/browser-dev-host/assets/index-CHYEXFEg.css +0 -1
  48. package/dist/devtools/browser-dev-host/assets/index-DY5ZynQp.js +0 -586
@@ -1,100 +0,0 @@
1
- import{i as tn,r as ef,H as sa,aV as tf,bq as rf,a6 as nf,b9 as of,ba as sf,s as Ue,bA as B,b4 as Od,q as vd,g as aa,aF as af,p as cf,aN as df,bu as rn,aZ as Ld,a$ as uf,k as Pn,A as lf,as as kn,K as ff,a0 as Cs,aQ as hf,o as Cd,aw as Rd,m as mf,b6 as Pd,aJ as gf,N as pf,aX as kd,h as yf,J as Ef,I as wf,b5 as If,bs as xd,br as Ud,b1 as Af,l as Ko,aI as Nf,d as At,e as Df}from"./desktop-app-launch-BzRxl_MM.js";const ca=15e3,Mf=32*1024*1024,da="data-hb-preview-capture-device",Zi="data-hb-preview-capture-ancestor",ua="data-hb-preview-capture-surface",la=64,Sf=1024;function _f(e={}){const t=e.document??globalThis.document,r=t.defaultView,n=e.leaseMs??ca;if(!Number.isFinite(n)||n<=0||n>ca)throw we("INVALID_CAPTURE_LEASE","截图租约无效");let i;function o(d,u,l){d.attributes.push({element:u,name:l,previous:u.getAttribute(l)}),u.setAttribute(l,d.token)}function s(d){const u=i;if(!u||u.token!==d)return!1;const l=a(u),f=!!u.style?.isConnected;i=void 0,clearTimeout(u.timer),u.removeAbort?.(),u.removeResize?.(),u.observer?.disconnect(),u.style?.remove(),u.bounds?.remove();for(const{element:m,name:h,previous:g}of u.attributes)m.getAttribute(h)===d&&(g===null?m.removeAttribute(h):m.setAttribute(h,g));return u.overlay.remove(),f&&(r.scrollX!==u.scroll.x||r.scrollY!==u.scroll.y)&&r.scrollTo(u.scroll.x,u.scroll.y),l}function a(d){const{viewport:u,target:l,rect:f}=d;if(!l?.isConnected||!f||Date.now()>=d.expiresAt||r.innerWidth!==u.width||r.innerHeight!==u.height||r.devicePixelRatio!==u.devicePixelRatio)return!1;const m=l.getBoundingClientRect();return["left","top","width","height"].every(h=>Math.abs(m[h]-f[h])<.01)}async function c(d,u){if(u?.throwIfAborted(),!Number.isFinite(d.deadlineAt)||Date.now()>=d.deadlineAt)throw we("PREVIEW_TIMEOUT","截图操作已超时");if(d.scope==="workbench"||!Object.hasOwn(tn,d.scope))throw we("INVALID_CAPTURE_SCOPE","设备像素截图仅支持 device、screen 或 app");if(!d.operationId||d.operationId.length>128)throw we("INVALID_OPERATION","截图操作标识无效");if(!d.previewImage.startsWith("data:image/png;base64,")||d.previewImage.length>Mf)throw we("INVALID_CAPTURE_IMAGE","共享窗口冻结图无效或过大");if(i)throw we("PREVIEW_BUSY","已有设备截图正在执行");const l=t.querySelectorAll(tn.device);if(l.length!==1)throw we("DEVICE_NOT_UNIQUE","设备画面不唯一或尚未创建");const f=l[0],m=d.scope==="device"?f:t.querySelector(tn[d.scope]);if(!m||m!==f&&!f.contains(m))throw we("CAPTURE_TARGET_UNAVAILABLE","截图内容尚未创建");const h=f.getBoundingClientRect();if(!(h.width>0&&h.height>0))throw we("CAPTURE_TARGET_UNAVAILABLE","设备画面当前不可见");const g=t.createElement("img");g.alt="",g.setAttribute("aria-hidden","true"),g.setAttribute("data-hb-preview-capture-freeze",""),g.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;`,g.addEventListener("wheel",j=>j.preventDefault(),{passive:!1}),g.addEventListener("touchmove",j=>j.preventDefault(),{passive:!1});const I=Math.min(Date.now()+n,d.deadlineAt),y={operationId:d.operationId,token:r.crypto.randomUUID(),overlay:g,attributes:[],scroll:{x:r.scrollX,y:r.scrollY},viewport:{width:r.innerWidth,height:r.innerHeight,devicePixelRatio:r.devicePixelRatio},expiresAt:I};i=y,y.timer=setTimeout(()=>s(y.token),Math.max(0,I-Date.now()));const b=()=>s(y.token);u?.addEventListener("abort",b,{once:!0}),y.removeAbort=()=>u?.removeEventListener("abort",b);const _=()=>{const{viewport:j}=y;(r.innerWidth!==j.width||r.innerHeight!==j.height||r.devicePixelRatio!==j.devicePixelRatio)&&s(y.token)};r.addEventListener("resize",_),y.removeResize=()=>r.removeEventListener("resize",_);const P=()=>{if(u?.throwIfAborted(),i!==y||Date.now()>=I)throw we("CAPTURE_EXPIRED","截图布局租约已结束,请重新截图")};try{g.src=d.previewImage,await g.decode(),P();const j=y.token,U=`[${da}="${j}"]`,O=r.getComputedStyle(f),w=new r.DOMMatrixReadOnly(O.transform==="none"?void 0:O.transform),S=Math.atan2(w.b,w.a),v=f.querySelector(".desktop-window__surface"),C=v?v.offsetWidth:Number.parseFloat(O.width),E=v?v.offsetHeight:Number.parseFloat(O.height),D=O.backgroundColor,M=r.getComputedStyle(t.body).backgroundColor,R=ie=>!ie||ie==="transparent"||ie==="rgba(0, 0, 0, 0)",T=R(D)?R(M)?"#fff":M:D;if(!(C>0&&E>0))throw we("CAPTURE_TARGET_UNAVAILABLE","设备布局尺寸无效");P(),t.body.append(g),o(y,f,da),v&&o(y,v,ua);for(let ie=f.parentElement;ie;ie=ie.parentElement)o(y,ie,Zi);const N=t.createElement("style");y.style=N;const A=`
2
- [${Zi}="${j}"] {overflow:visible!important;scrollbar-width:none!important;}
3
- [${Zi}="${j}"]::-webkit-scrollbar {display:none!important;}
4
- [${ua}="${j}"] {transform:none!important;transition:none!important;}
5
- `,L=(ie,Rt,mt=0,gt=0)=>`${U} {position:absolute!important;left:${ie}px!important;top:${Rt}px!important;width:${C}px!important;height:${E}px!important;transform:translate(${mt}px,${gt}px) rotate(${S}rad)!important;transition:none!important;z-index:2147483646!important;background-color:${T}!important;}`;N.textContent=A+L(0,0),P(),t.head.append(N);const k=f.getBoundingClientRect(),x=t.querySelector(tn.app),H=x&&f.contains(x)?x.getBoundingClientRect():void 0,F=H&&H.width>0&&H.height>0?H:void 0,V=F?Math.floor(r.innerWidth-1-(F.left-k.left)):r.innerWidth+64,q=F?Math.floor(r.innerHeight-1-(F.top-k.top)):32,J=V-k.left,K=q-k.top;P(),N.textContent=A+L(J,K);const Z=f.getBoundingClientRect();N.textContent=A+L(J,K,V-Z.left,q-Z.top),P();const Y=m.getBoundingClientRect(),re=Math.floor(Pt(Y.left+r.scrollX)),Me=Math.floor(Pt(Y.top+r.scrollY)),le={x:re,y:Me,width:Math.ceil(Pt(Y.right+r.scrollX))-re,height:Math.ceil(Pt(Y.bottom+r.scrollY))-Me};if(!(le.width>0&&le.height>0)||le.x<0||le.y<0)throw we("CAPTURE_LAYOUT_INVALID","无法建立完整设备截图布局");if(F&&x){const ie=x.getBoundingClientRect();if(!(ie.left<r.innerWidth&&ie.top<r.innerHeight&&ie.right>0&&ie.bottom>0))throw we("CAPTURE_LAYOUT_INVALID","无法保持 iframe 的最小绘制区域");const Rt=f.getBoundingClientRect(),mt=Math.floor(Pt(Rt.left))-1,gt=Math.floor(Pt(Rt.top))-1,Xr=r.innerWidth-mt,en=r.innerHeight-gt;if(mt<0||gt<0||Xr<=0||en<=0||Xr>la||en>la||Xr*en>Sf)throw we("CAPTURE_LAYOUT_INVALID","无法在有界角部保持完整设备绘制,请改用 --scale css");g.style.clipPath=`polygon(0 0,100% 0,100% ${gt}px,${mt}px ${gt}px,${mt}px 100%,0 100%)`,g.setAttribute("data-hb-preview-capture-corner",JSON.stringify({x:mt,y:gt,width:Xr,height:en}))}const fe=t.createElement("div");if(fe.setAttribute("aria-hidden","true"),fe.style.cssText=`position:absolute;left:${le.x+le.width+2}px;top:${le.y+le.height+2}px;width:1px;height:1px;pointer-events:none;opacity:0;`,y.bounds=fe,P(),t.body.append(fe),y.target=m,y.rect=Y,await bf(r,u),P(),!a(y))throw we("CAPTURE_LAYOUT_INVALID","截图准备期间布局发生变化,请重新截图");y.observer=new r.ResizeObserver(()=>{i===y&&!a(y)&&s(y.token)});for(const{element:ie}of y.attributes)y.observer.observe(ie);return{token:j,clip:le,devicePixelRatio:r.devicePixelRatio,expiresAt:I}}catch(j){throw s(y.token),j}}return{prepare:c,restore:s,cancel:d=>i?.operationId!==d?!1:(s(i.token),!0),dispose:()=>{i&&s(i.token)}}}function bf(e,t){return new Promise((r,n)=>{let i=e.requestAnimationFrame(()=>{i=e.requestAnimationFrame(s)});const o=()=>{e.cancelAnimationFrame(i),t?.removeEventListener("abort",o),n(t?.reason)};function s(){t?.removeEventListener("abort",o),r()}t?.addEventListener("abort",o,{once:!0}),t?.aborted&&o()})}function we(e,t){return Object.assign(new Error(t),{name:"PreviewError",code:e})}function Pt(e){const t=Math.round(e);return Math.abs(e-t)<.001?t:e}const xn="workspaceCards.requestRefresh",Un="auth.getAccountState",jn="auth.login",zn="user.getFollowStatus",Hn="user.requestFollowAuthor",Tf="gameSaves.list",Of="gameSaves.sync",vf="gameSaves.getFile",Lf="gameSaves.readParsedData",Fn="user.getInfo",Bn="user.revokeAuthorization",Vn="user.getSteamGameList",Lr="user.showAppreciation",Gn="share.copyLink",qn="share.showShareMenu",Qn="share.screenshot",Yn="share.screenshotLong",_t="viewport.setDisplay",Wn="viewport.getWindowInfo",$n="viewport.setNavigationBarStyle",Cr="storage.getStorage",Rr="storage.setStorage",Kn="network.request",Zn="network.download",Jn="network.upload",Xn="files.pickFiles",ei="files.pickDirectory",ti="files.saveFile",Pr="file.create",kr="file.remove",ri="file.exists",xr="file.readText",ni="file.writeText",Ur="file.readBytes",ii="file.writeBytes",jr="file.stat",oi="directory.create",zr="directory.remove",si="directory.exists",ai="directory.list",Hr="media.pick",ci="ui.showToast",di="ui.showLoading",ui="ui.hideLoading",li="device.vibrate",fi="device.setClipboard",hi="device.executeProtocol",mi="navigation.close",gi="navigation.reload",pi="navigation.openAppPage",Xe="cloud.leaderboard.submit",xe="cloud.leaderboard.getList",at="cloud.leaderboard.getCurrentUserEntry",bt="cloud.leaderboard.deleteCurrentUserEntry",Ye="cloud.leaderboard.getInfo",Jt="cloud.storage.getStorage",Xt="cloud.storage.setStorage",er="cloud.storage.removeItem",Tt="cloud.storage.getKeys",Oi="companion.getInfo",vi="companion.getPreparationStatus",Li="companion.prepare",Ci="companion.cancelPreparation",Ri="companion.getActiveSession",Pi="companion.launch",ki="companion.session.write",xi="companion.session.closeStdin",Ui="companion.session.terminate",ji="companion.session.ackOutput",zi="companion.openAttachment",Hi="companion.showNotification",ct=[...[Tf,Of,vf,Lf].map(e=>({method:e,module:"gameSaves",capability:e,requirement:{kind:"all",permissions:["gameSaves"]},risk:"high"})),{method:xn,module:"workspaceCards",capability:xn,requirement:{kind:"all",permissions:["workspaceCards"]},risk:"high"},{method:Un,module:"auth",capability:Un,requirement:{kind:"none"},risk:"low"},{method:jn,module:"auth",capability:jn,requirement:{kind:"all",permissions:["userInfo"]},risk:"medium"},{method:zn,module:"user",capability:zn,requirement:{kind:"none"},risk:"low"},{method:Hn,module:"user",capability:Hn,requirement:{kind:"none"},risk:"high"},{method:Fn,module:"user",capability:Fn,requirement:{kind:"all",permissions:["userInfo"]},risk:"medium"},{method:Bn,module:"user",capability:Bn,requirement:{kind:"none"},risk:"high"},{method:Vn,module:"user",capability:Vn,requirement:{kind:"all",permissions:["steamLibrary"]},risk:"high"},{method:Lr,module:"user",capability:Lr,requirement:{kind:"none"},risk:"medium"},{method:Gn,module:"share",capability:Gn,requirement:{kind:"all",permissions:["share"]},risk:"medium"},{method:qn,module:"share",capability:qn,requirement:{kind:"all",permissions:["share"]},risk:"low"},{method:Qn,module:"share",capability:Qn,requirement:{kind:"all",permissions:["share"]},risk:"medium"},{method:Yn,module:"share",capability:Yn,requirement:{kind:"all",permissions:["share"]},risk:"medium"},{method:Wn,module:"viewport",capability:Wn,requirement:{kind:"none"},risk:"low"},{method:$n,module:"viewport",capability:$n,requirement:{kind:"none"},risk:"low"},{method:_t,module:"viewport",capability:_t,requirement:{kind:"none"},risk:"low"},{method:Cr,module:"storage",capability:Cr,requirement:{kind:"all",permissions:["storage"]},risk:"low"},{method:Rr,module:"storage",capability:Rr,requirement:{kind:"all",permissions:["storage"]},risk:"medium"},{method:Kn,module:"network",capability:Kn,requirement:{kind:"all",permissions:["network"]},risk:"high"},{method:Zn,module:"network",capability:Zn,requirement:{kind:"all",permissions:["network","filesystem"]},risk:"high"},{method:Jn,module:"network",capability:Jn,requirement:{kind:"all",permissions:["network","filesystem"]},risk:"high"},{method:Xn,module:"files",capability:Xn,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:ei,module:"files",capability:ei,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:ti,module:"files",capability:ti,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Pr,module:"file",capability:Pr,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:kr,module:"file",capability:kr,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:ri,module:"file",capability:ri,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:xr,module:"file",capability:xr,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:ni,module:"file",capability:ni,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Ur,module:"file",capability:Ur,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:ii,module:"file",capability:ii,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:jr,module:"file",capability:jr,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:oi,module:"directory",capability:oi,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:zr,module:"directory",capability:zr,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:si,module:"directory",capability:si,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:ai,module:"directory",capability:ai,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Hr,module:"media",capability:Hr,requirement:{kind:"all",permissions:["media"]},risk:"high"},{method:ci,module:"ui",capability:ci,requirement:{kind:"none"},risk:"low"},{method:di,module:"ui",capability:di,requirement:{kind:"none"},risk:"low"},{method:ui,module:"ui",capability:ui,requirement:{kind:"none"},risk:"low"},{method:li,module:"device",capability:li,requirement:{kind:"none"},risk:"low"},{method:fi,module:"device",capability:fi,requirement:{kind:"all",permissions:["clipboard"]},risk:"medium"},{method:hi,module:"device",capability:hi,requirement:{kind:"all",permissions:["appProtocol"]},risk:"high"},{method:mi,module:"navigation",capability:mi,requirement:{kind:"none"},risk:"medium"},{method:gi,module:"navigation",capability:gi,requirement:{kind:"none"},risk:"medium"},{method:pi,module:"navigation",capability:pi,requirement:{kind:"none"},risk:"medium"},{method:Xe,module:"cloud",capability:Xe,requirement:{kind:"all",permissions:["leaderboard"]},risk:"medium"},{method:xe,module:"cloud",capability:xe,requirement:{kind:"all",permissions:["leaderboard"]},risk:"low"},{method:at,module:"cloud",capability:at,requirement:{kind:"all",permissions:["leaderboard"]},risk:"medium"},{method:bt,module:"cloud",capability:bt,requirement:{kind:"all",permissions:["leaderboard"]},risk:"medium"},{method:Ye,module:"cloud",capability:Ye,requirement:{kind:"all",permissions:["leaderboard"]},risk:"low"},{method:Jt,module:"cloud",capability:Jt,requirement:{kind:"all",permissions:["cloud_storage"]},risk:"low"},{method:Xt,module:"cloud",capability:Xt,requirement:{kind:"all",permissions:["cloud_storage"]},risk:"medium"},{method:er,module:"cloud",capability:er,requirement:{kind:"all",permissions:["cloud_storage"]},risk:"medium"},{method:Tt,module:"cloud",capability:Tt,requirement:{kind:"all",permissions:["cloud_storage"]},risk:"low"},...[Oi,vi,Li,Ci,Ri,Pi,ki,xi,Ui,ji,zi,Hi].map(e=>({method:e,module:"companion",capability:e,requirement:{kind:"all",permissions:["companion"]},risk:"high"}))],Et="heybox:miniprogram",jd=2,zd="hb_mini_bridge_nonce",Hd="sdk.handshake",nn="runtime.location.probe",Cf="sdk.location.report",Rf="sdk.csp.violation",Fd="operation.progress",Pf="companion.session.output",kf="companion.session.exit",xf="companion.session.ownershipLost";function Uf(e){return!He(e)||e.namespace!==Et||e.version!==1&&e.version!==2||!ue(e.nonce)?!1:e.type==="handshake"?ue(e.id)&&e.method===Hd&&e.error===void 0&&qf(e.payload):e.type==="request"?ue(e.id)&&ue(e.method)&&e.error===void 0:e.type==="response"?ue(e.id)&&(e.method===void 0||ue(e.method))&&(e.error===void 0||Qf(e.error)):e.type==="event"?!ue(e.method)||e.error!==void 0?!1:e.method===Fd?e.version===2&&ue(e.id)&&Gf(e.payload):e.id===void 0||ue(e.id):e.type==="cancel"?e.version===2&&ue(e.id)&&e.method===void 0&&e.payload===void 0&&e.error===void 0:!1}function Rs(e){return typeof e!="string"||!e||e.startsWith("/")||e.endsWith("/")||/[\\\u0000-\u001f\u007f]/.test(e)?!1:e.split("/").every(t=>!!t&&t!=="."&&t!=="..")}function Bd(e){return He(e)?e.kind==="sandbox"?Re(e,["kind"]):e.kind==="directory"&&ue(e.handleId)&&Re(e,["kind","handleId"]):!1}function tr(e){return!He(e)||e.kind!=="file"?!1:ue(e.handleId)?Re(e,["kind","handleId"]):Bd(e.root)&&Rs(e.relativePath)&&Re(e,["kind","root","relativePath"])}function Vd(e){return!He(e)||e.kind!=="directory"?!1:ue(e.handleId)?Re(e,["kind","handleId"]):Bd(e.root)&&(e.relativePath==="."||Rs(e.relativePath))&&Re(e,["kind","root","relativePath"])}function jf(e){return He(e)&&e.kind==="file"&&ue(e.name)&&Yf(e.mode)&&tr(e.ref)&&Re(e,["kind","name","mode","ref"])}const Gd=20,fa=["type","mimeType","size","width","height","previewUrl","file"];function zf(e){return e===void 0?!0:!(!He(e)||!Re(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&&(!Wf(e.maxCount,1,Gd)||e.source==="camera"&&e.maxCount!==1))}function qd(e){if(!He(e)||e.type!=="image"&&e.type!=="video")return!1;const t=e.type==="video";return!Re(e,t?[...fa,"durationMs"]:fa)||!ue(e.mimeType)||!it(e.size)||!ha(e.width)||!ha(e.height)||!ue(e.previewUrl)||!Ff(e.file)?!1:t?it(e.durationMs):!0}function Hf(e){if(!Array.isArray(e)||e.length<1||e.length>Gd)return!1;for(let t=0;t<e.length;t+=1)if(!Object.prototype.hasOwnProperty.call(e,t)||!qd(e[t]))return!1;return!0}function Ff(e){return!jf(e)||e.mode!=="read"?!1:e.ref.kind==="file"&&"handleId"in e.ref&&ue(e.ref.handleId)}function Qd(e){return e instanceof Uint8Array&&e.buffer instanceof ArrayBuffer}function Bf(e){return!He(e)||!it(e.loaded)||typeof e.lengthComputable!="boolean"||!Re(e,["loaded","total","lengthComputable"])?!1:e.lengthComputable?it(e.total)&&e.loaded<=e.total:e.total===void 0}function Vf(e){return He(e)?e.phase==="downloading"?it(e.loaded)&&(e.total===void 0||it(e.total)&&e.loaded<=e.total)&&Re(e,["phase","loaded","total"]):e.phase!=="verifying"&&e.phase!=="extracting"?!1:it(e.processed)&&it(e.total)&&e.processed<=e.total&&Re(e,["phase","processed","total"]):!1}function Gf(e){return Bf(e)||Vf(e)}function qf(e){return He(e)&&ue(e.href)&&typeof e.userAgent=="string"&&ue(e.sdkVersion)}function Qf(e){return He(e)&&ue(e.code)&&typeof e.message=="string"}function Yf(e){return e==="read"||e==="readwrite"}function it(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function ha(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>0}function Wf(e,t,r){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=t&&e<=r}function ue(e){return typeof e=="string"&&e.length>0}function Re(e,t){const r=new Set(t);return Object.keys(e).every(n=>r.has(n))}function He(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const Ot=["userInfo","steamLibrary","share","storage","cloud_storage","gameSaves","filesystem","media","clipboard","leaderboard","network","companion","appProtocol","workspaceCards"],Yd=[{key:"gameSaves",name:"游戏存档",description:"获取和同步当前用户指定游戏的 Steam 云存档,并读取存档文件,无需单独弹窗确认。",access:"declaration",risk:"high",config:{},methods:["gameSaves.list","gameSaves.sync","gameSaves.getFile","gameSaves.readParsedData"],conditions:["需声明权限并校验当前 Steam 账号,无需额外授权弹窗;可读取受支持游戏已有的完整结构化数据,不触发解析。同步需有效 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 支持与有效执行租约;不隐式授予网络或存储权限。"]}];new Set(Ot);const $f=new Set(Ot);function Kf(e){return $f.has(e)}function je(e){if(!on(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(!on(n)||typeof n.key!="string"||!n.key.trim())return{valid:!1,permissions:{}};const i=n.key.trim(),o=i==="network.request"?"network":i;if(t.has(o)||n.status!=="enabled"&&n.status!=="disabled")return{valid:!1,permissions:{}};if(t.add(o),!!Kf(o)){if(o==="network"){const s=n.config;if(!on(s)||typeof s.useOfficialDomain!="boolean")return{valid:!1,permissions:{}};r[o]={key:o,status:n.status,config:{useOfficialDomain:s.useOfficialDomain}};continue}if(n.config!==null&&n.config!==void 0&&(!on(n.config)||Object.keys(n.config).length>0))return{valid:!1,permissions:{}};r[o]={key:o,status:n.status,config:{}}}}return{valid:!0,permissions:r}}function on(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const wn=["network","companion","appProtocol"];function Wd(e){if(!gr(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>wn.length)return{valid:!1};const t=[],r=new Set;for(const n of e.entries){if(!gr(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(!gr(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(!gr(n.config,[]))return{valid:!1};t.push({key:"companion",status:"enabled",config:{}})}else if(n.key==="appProtocol"){if(!gr(n.config,[]))return{valid:!1};t.push({key:"appProtocol",status:"enabled",config:{}})}else return{valid:!1}}return t.sort((n,i)=>wn.indexOf(n.key)-wn.indexOf(i.key)),{valid:!0,grant:{schema_version:1,revision:e.revision,entries:t}}}function Zf(e){if(!Number.isSafeInteger(e.revision)||e.revision<0)throw new Error("本地调试权限 revision 必须是非负安全整数");const t=je(e.runtimePermissions),r=new Set(e.eligiblePermissionKeys??["network","appProtocol"]),n=[];for(const i of wn)!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 Ps(e){const t=je(e.runtimePermissions),r=Wd(e.localDevGrant),n=t.valid?t.permissions:{};for(const s of Ot)e.declaredPermissions[s]?.enabled!==!0?delete n[s]:Yd.some(a=>a.key===s&&a.access==="declaration")?n[s]={key:s,status:"enabled",config:{}}:s==="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 s of r.grant.entries)e.declaredPermissions[s.key]?.enabled!==!0||n[s.key]?.status==="enabled"||(n[s.key]=s,i.push(s.key));const o=$d(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,...o===void 0?{}:{revision:o},entries:Ot.flatMap(s=>n[s]?[n[s]]:[])},temporaryPermissionKeys:i,grantValid:r.valid}}function $d(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function gr(e,t){return $d(e)&&Object.keys(e).length===t.length&&t.every(r=>Object.prototype.hasOwnProperty.call(e,r))}const rr=["identity","profile","steam_account"],Jf=/^[a-z][a-z0-9-]{0,31}$/,Kd=["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"];function Xf(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 Ot){const n=e.declared_permissions[r];if(n){if(typeof n.enabled!="boolean")throw new Error("开发权限声明无效");t[r]=r==="network"?{enabled:n.enabled,useOfficialDomain:n.useOfficialDomain===!0}:{enabled:n.enabled}}}if(Object.keys(e.declared_permissions).some(r=>!Ot.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 eh(e){if(!(typeof e!="string"||e.length>16384))try{const t=JSON.parse(e);return Xf(t)===e?t:void 0}catch{return}}ct.map(e=>e.method);function In(){const e=new Error("The operation was aborted");return e.name="AbortError",e}function X(e,t={}){if(e.aborted)throw t.preserveReason?e.reason===void 0?new DOMException("存储操作已取消","AbortError"):e.reason:In()}function Zd(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 Jd="METHOD_FORBIDDEN";function Ce(e){const t=new Error(`小程序能力已禁用: ${e}`);return t.name="MethodForbiddenError",t.code=Jd,t}class ge 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 th=/^[A-Za-z0-9_-]{1,64}$/,ma=1e3;function Xd(e){return th.test(e)?e:nh(e)}function rh(e){return`id_${Xd(e.trim())}`}function kt(e,t){return`hb_miniprogram_${e}_${t}`}function sn(e){return`hb_miniprogram_keys_${e}`}function nh(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)}function ee(e,t,r){return{code:e,message:t,data:r}}function ks(e){return ih(e)?{code:e.code,message:e.message,data:e.data}:e instanceof Error?ee("RUNTIME_ERROR",e.message):ee("UNKNOWN_ERROR","小程序运行时异常",e)}function ih(e){return!!e&&typeof e=="object"&&typeof e.code=="string"&&typeof e.message=="string"}const ga={"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"],[xn]:["workspaceCards.requestRefresh"],[Un]:["account.getCurrentUserId","account.getAccountKey","account.onChange"],[jn]:["account.getCurrentUserId","account.ensureAuthenticated","account.onChange","network.request"],[zn]:["account.getCurrentUserId","account.onChange","network.request"],[Hn]:["account.getCurrentUserId","account.ensureAuthenticated","account.onChange","network.request"],[Fn]:["account.getCurrentUserId","account.onChange","network.request"],[Bn]:["account.getCurrentUserId","account.onChange","network.request"],[Vn]:["account.getCurrentUserId","account.onChange","network.request"],[Gn]:["presentation.setClipboard"],[qn]:["presentation.showShareMenu"],[Qn]:["presentation.getViewportMetrics","presentation.captureAndShare"],[Yn]:["presentation.getViewportMetrics","presentation.captureAndShare"],[_t]:["presentation.applyOrientation"],[Wn]:["presentation.getViewportMetrics","presentation.getNavigationBarHeight"],[$n]:["presentation.setNavigationBarStyle"],[Cr]:["storage.getRaw"],[Rr]:["storage.setRaw"],[Kn]:["network.request"],[Zn]:["network.stream","files.transfer","files.access"],[Jn]:["network.upload","files.access"],[Xn]:["files.external"],[ei]:["files.external"],[ti]:["files.save"],[Pr]:["files.access"],[kr]:["files.removeFile"],[ri]:["files.access"],[xr]:["files.access"],[ni]:["files.access"],[Ur]:["files.access"],[ii]:["files.access"],[jr]:["files.access"],[oi]:["files.access"],[zr]:["files.removeDirectory"],[si]:["files.access"],[ai]:["files.access"],[Hr]:["media.pick"],[Lr]:["presentation.showAppreciation"],[ci]:["presentation.showToast"],[di]:["presentation.showLoading"],[ui]:["presentation.hideLoading"],[li]:["presentation.vibrate"],[fi]:["presentation.setClipboard"],[hi]:["protocol.invoke"],[mi]:["presentation.close"],[gi]:["presentation.reload"],[pi]:["presentation.openAppPage"],[Xe]:["account.getCurrentUserId","account.onChange","network.request"],[xe]:["account.onChange","network.request"],[at]:["account.getCurrentUserId","account.onChange","network.request"],[bt]:["account.getCurrentUserId","account.onChange","network.request"],[Ye]:["account.onChange","network.request"],[Jt]:["account.getCurrentUserId","account.onChange","network.request"],[Xt]:["account.getCurrentUserId","account.onChange","network.request"],[er]:["account.getCurrentUserId","account.onChange","network.request"],[Tt]:["account.getCurrentUserId","account.onChange","network.request"],[Oi]:["companion.getInfo"],[vi]:["companion.getPreparationStatus"],[Li]:["companion.getInfo","companion.getPreparationStatus","companion.prepare"],[Ci]:["companion.cancelPreparation"],[Ri]:["companion.getActiveSession"],[Pi]:["companion.getInfo","companion.launch"],[ki]:["companion.session.write"],[xi]:["companion.session.closeStdin"],[Ui]:["companion.session.terminate"],[ji]:["companion.session.ackOutput"],[zi]:["companion.openAttachment"],[Hi]:["companion.showNotification"]},oh=new Set([Lr]);function eu(e,t){if(t[e]!==!0)throw oh.has(e)?ee("REQUEST_UNSUPPORTED","当前宿主不支持该能力"):Ce(e)}const sh=32*1024*1024,ah=/^application\/(?:[a-z0-9!#$&^_.+-]+\+)?json(?:\s*;|$)/i;function ch(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 o=await r.open(n,i);let s;try{const a=await t(o.body,{maxBytes:sh},i);return dh(o,a)}catch(a){throw s=a,a}finally{try{await r.release(o.body)}catch(a){if(s===void 0)throw a}}}}}}function dh(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:uh(t,fh(e,"content-type"))}}function uh(e,t){lh(t);let r;try{r=new TextDecoder("utf-8",{fatal:!0}).decode(e)}catch(n){throw new ge("Host network response 不是合法 UTF-8 文本",{cause:n})}if(r.charCodeAt(0)===65279&&(r=r.slice(1)),!t||!ah.test(t)||r==="")return r;try{return JSON.parse(r)}catch{return r}}function lh(e){if(!e)return;const t=/(?:^|;)\s*charset\s*=\s*["']?([^;"'\s]+)/i.exec(e)?.[1];if(t&&!/^utf-?8$/i.test(t))throw new ge(`Host network response 不支持 charset=${t}`)}function fh(e,t){return Object.entries(e.headers).find(([r])=>r.toLowerCase()===t)?.[1]?.[0]}function z(e){return typeof e=="function"}function pa(e){return(...t)=>{throw Ce(e)}}function he(e){return async(...t)=>{throw Ce(e)}}const hh=(e,t)=>{},mh=()=>()=>{};function gh(e){const t={request:z(e.network?.request)?e.network.request.bind(e.network):he("network.request")},r={...z(e.account?.getAccountKey)?{getAccountKey:e.account.getAccountKey.bind(e.account)}:{},getCurrentUserId:z(e.account?.getCurrentUserId)?e.account.getCurrentUserId.bind(e.account):he("account.getCurrentUserId"),ensureAuthenticated:z(e.account?.ensureAuthenticated)?e.account.ensureAuthenticated.bind(e.account):he("account.ensureAuthenticated"),onChange:z(e.account?.onChange)?e.account.onChange.bind(e.account):mh},n={getRaw:z(e.storage?.getRaw)?e.storage.getRaw.bind(e.storage):he("storage.getRaw"),setRaw:z(e.storage?.setRaw)?e.storage.setRaw.bind(e.storage):he("storage.setRaw")},i={...z(e.presentation?.showSteamLoginRequired)?{showSteamLoginRequired:e.presentation.showSteamLoginRequired.bind(e.presentation)}:{},...z(e.presentation?.applyOrientation)?{applyOrientation:e.presentation.applyOrientation.bind(e.presentation)}:{},...z(e.presentation?.onViewportChange)?{onViewportChange:e.presentation.onViewportChange.bind(e.presentation)}:{},close:z(e.presentation?.close)?e.presentation.close.bind(e.presentation):he("presentation.close"),reload:z(e.presentation?.reload)?e.presentation.reload.bind(e.presentation):he("presentation.reload"),openAppPage:z(e.presentation?.openAppPage)?e.presentation.openAppPage.bind(e.presentation):he("presentation.openAppPage"),openWindow:z(e.presentation?.openWindow)?e.presentation.openWindow.bind(e.presentation):he("presentation.openWindow"),getViewportMetrics:z(e.presentation?.getViewportMetrics)?e.presentation.getViewportMetrics.bind(e.presentation):pa("presentation.getViewportMetrics"),getNavigationBarHeight:z(e.presentation?.getNavigationBarHeight)?e.presentation.getNavigationBarHeight.bind(e.presentation):pa("presentation.getNavigationBarHeight"),setNavigationBarStyle:z(e.presentation?.setNavigationBarStyle)?e.presentation.setNavigationBarStyle.bind(e.presentation):he("presentation.setNavigationBarStyle"),showShareMenu:z(e.presentation?.showShareMenu)?e.presentation.showShareMenu.bind(e.presentation):he("presentation.showShareMenu"),setScreenshotChromeHidden:z(e.presentation?.setScreenshotChromeHidden)?e.presentation.setScreenshotChromeHidden.bind(e.presentation):hh,supportsLongScreenshot:e.presentation?.supportsLongScreenshot===!0,captureAndShare:z(e.presentation?.captureAndShare)?e.presentation.captureAndShare.bind(e.presentation):he("presentation.captureAndShare"),showAppreciation:z(e.presentation?.showAppreciation)?e.presentation.showAppreciation.bind(e.presentation):async()=>{throw ee("REQUEST_UNSUPPORTED","当前宿主不支持赞赏码")},showToast:z(e.presentation?.showToast)?e.presentation.showToast.bind(e.presentation):he("presentation.showToast"),showLoading:z(e.presentation?.showLoading)?e.presentation.showLoading.bind(e.presentation):he("presentation.showLoading"),hideLoading:z(e.presentation?.hideLoading)?e.presentation.hideLoading.bind(e.presentation):he("presentation.hideLoading"),vibrate:z(e.presentation?.vibrate)?e.presentation.vibrate.bind(e.presentation):he("presentation.vibrate"),setClipboard:z(e.presentation?.setClipboard)?e.presentation.setClipboard.bind(e.presentation):he("presentation.setClipboard")},o=z(e.storageDiagnostics?.listRaw)?{listRaw:e.storageDiagnostics.listRaw.bind(e.storageDiagnostics)}:void 0,s=Object.fromEntries(["getInfo","getPreparationStatus","prepare","cancelPreparation","getActiveSession","launch","write","closeStdin","terminate","ackOutput","openAttachment","showNotification"].map(c=>[c,z(e.companion?.[c])?e.companion[c].bind(e.companion):he(`companion.${c}`)]));z(e.companion?.onSessionEvent)&&(s.onSessionEvent=e.companion.onSessionEvent.bind(e.companion));const a={invoke:z(e.protocol?.invoke)?e.protocol.invoke.bind(e.protocol):he("protocol.invoke")};return{network:t,...e.workspaceCards?{workspaceCards:e.workspaceCards}:{},account:r,storage:n,presentation:i,companion:s,protocol:a,...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}:{},...o?{storageDiagnostics:o}:{}}}function ph(e){const t=yh(e.files?.sandbox),r=z(e.picker?.pickFiles)&&z(e.picker?.pickDirectory),n=z(e.picker?.saveFile),i=t||r||n||z(e.companion?.openAttachment),o=t?e.files?.sandbox.file(".hb-remove-capability"):void 0;return{"account.getAccountKey":z(e.account?.getAccountKey),"account.getCurrentUserId":z(e.account?.getCurrentUserId),"account.ensureAuthenticated":z(e.account?.ensureAuthenticated),"account.onChange":z(e.account?.onChange),"network.request":z(e.network?.request),"network.stream":z(e.transfer?.network.open)&&z(e.transfer?.network.release),"network.upload":z(e.transfer?.upload?.upload),"files.sandbox":t,"files.external":r,"files.save":n,"files.access":i,"files.removeFile":z(o?.remove),"files.removeDirectory":z(e.files?.sandbox.remove),"files.transfer":z(e.transfer?.files.writeResource),"media.pick":z(e.media?.pick),"storage.getRaw":z(e.scopedStorage?.get)||z(e.storage?.getRaw),"storage.setRaw":z(e.scopedStorage?.set)||z(e.storage?.setRaw),"presentation.close":z(e.presentation?.close),"presentation.reload":z(e.presentation?.reload),"presentation.openAppPage":z(e.presentation?.openAppPage),"presentation.applyOrientation":z(e.presentation?.applyOrientation),"presentation.openWindow":z(e.presentation?.openWindow),"presentation.getViewportMetrics":z(e.presentation?.getViewportMetrics),"presentation.getNavigationBarHeight":z(e.presentation?.getNavigationBarHeight),"presentation.setNavigationBarStyle":z(e.presentation?.setNavigationBarStyle),"presentation.showShareMenu":z(e.presentation?.showShareMenu),"presentation.setScreenshotChromeHidden":!0,"presentation.captureAndShare":z(e.presentation?.captureAndShare),"presentation.showAppreciation":z(e.presentation?.showAppreciation),"presentation.showToast":z(e.presentation?.showToast),"presentation.showLoading":z(e.presentation?.showLoading),"presentation.hideLoading":z(e.presentation?.hideLoading),"presentation.vibrate":z(e.presentation?.vibrate),"presentation.setClipboard":z(e.presentation?.setClipboard),"workspaceCards.requestRefresh":z(e.workspaceCards?.requestRefresh),"companion.getInfo":z(e.companion?.getInfo),"companion.getPreparationStatus":z(e.companion?.getPreparationStatus),"companion.prepare":z(e.companion?.prepare),"companion.cancelPreparation":z(e.companion?.cancelPreparation),"companion.getActiveSession":z(e.companion?.getActiveSession),"companion.launch":z(e.companion?.launch),"companion.session.write":z(e.companion?.write),"companion.session.closeStdin":z(e.companion?.closeStdin),"companion.session.terminate":z(e.companion?.terminate),"companion.session.ackOutput":z(e.companion?.ackOutput),"companion.openAttachment":z(e.companion?.openAttachment),"companion.showNotification":z(e.companion?.showNotification),"protocol.invoke":z(e.protocol?.invoke)}}function yh(e){if(!e||typeof e!="object")return!1;const t=e;return t.kind==="directory"&&(t.mode==="read"||t.mode==="readwrite")&&z(t.file)&&z(t.directory)&&z(t.create)&&z(t.stat)&&z(t.list)}function ya(e,t){return t?.[e]!==!1}function Eh(e){return e==="network.download"||e.startsWith("files.")||e.startsWith("file.")||e.startsWith("directory.")||e.startsWith("media.")||e.startsWith("companion.")}function tu(e,t={}){const r={};for(const n of Object.keys(ga)){const o=ga[n].every(a=>e[a]),s=!Eh(n)||!!t.miniProgramDetail?.miniProgramId.trim();r[n]=ya(n,t.callerCapabilities)&&ya(n,t.hostCapabilities)&&o&&s}return r}function ru(e={},t={}){const r=ph(e),n=tu(r,t);return{ports:gh(e),primitiveAvailability:r,availablePrimitives:r,effectiveCapabilities:n}}function ae(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]):wh(e.signal,t);return{...e,signal:n,...r===void 0?{}:{requestId:r}}}function wh(e,t){const r=new AbortController,n=()=>{e.removeEventListener("abort",o),t.removeEventListener("abort",s)},i=a=>{r.signal.aborted||(n(),r.abort(a.reason))},o=()=>i(e),s=()=>i(t);return e.aborted?i(e):t.aborted?i(t):(e.addEventListener("abort",o,{once:!0}),t.addEventListener("abort",s,{once:!0})),r.signal}function Ih(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 Ah=4,Nh=["xiaoheihe.cn","max-c.com","debugmode.cn","maxjia.com"],Dh=new Set(["connection","content-length","host","origin","referer","keep-alive","proxy-connection","te","trailer","transfer-encoding","upgrade","x-heybox-runtime-auth-context-token"]),Mh=["/user_miniprogram/runtime/auth","/user_miniprogram/openapi/v1"],Sh=["/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 _h(e,t){const r=Oh(e);return r===null||Ea(r,Mh)?!0:t&&Ea(r,Sh)}function bh(e){const t=e.hostname.toLowerCase().replace(/\.$/,"");return Nh.some(r=>t===r||t.endsWith(`.${r}`))}function Th(e){const t=e.trim().toLowerCase();return t.startsWith("x-hb-sdk-")||t.startsWith("sec-")||Dh.has(t)||/^(?:x-heybox|x-xhh)-(?:access-token|auth|authorization|pkey|session|token)$/.test(t)}function Oh(e){let t=e;for(let r=0;r<Ah;r+=1){let n;try{n=decodeURIComponent(t)}catch{return null}if(n===t)return wa(t);t=n}try{if(decodeURIComponent(t)!==t)return null}catch{return null}return wa(t)}function Ea(e,t){return t.some(r=>e===r||e.startsWith(`${r}/`))}function wa(e){const t=[];for(const r of e.replace(/\\/g,"/").split("/"))!r||r==="."||(r===".."?t.pop():t.push(r));return`/${t.join("/")}`}function vh(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 nu(e){if(e==null)return;if(typeof e!="object"||Array.isArray(e))throw Ji("网络策略格式无效");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 Ji("网络策略格式无效");const n=new Set;for(const i of r){const o=vh(i&&typeof i=="object"?i.domain:void 0);if(!o)throw Ji("网络策略包含无效域名");n.add(o)}return Object.freeze({revision:t.revision,enforcement:t.enforcement,entries:Object.freeze([...n].sort().map(i=>Object.freeze({domain:i})))})}function Ji(e){return Object.assign(new TypeError(e),{code:"NETWORK_POLICY_INVALID"})}function Ia(e){return e instanceof ge?{code:"REQUEST_UNSUPPORTED",message:e.message}:e}function $(e,t,r={}){if(t.aborted&&!r.invokeWhenAborted)return Promise.reject(In());let n;try{n=e()}catch(i){return Promise.reject(Ia(i))}return t.aborted?(Promise.resolve(n).catch(()=>{}),Promise.reject(In())):new Promise((i,o)=>{let s=!1;const a=d=>{s||(s=!0,t.removeEventListener("abort",c),d())},c=()=>a(()=>o(In()));t.addEventListener("abort",c,{once:!0}),Promise.resolve(n).then(d=>a(()=>i(d)),d=>a(()=>o(Ia(d))))})}async function Lh(e,t,r){X(r);const i=e.ownerDocument.defaultView;if(!i||!e.isConnected)throw new Error("长图容器不可用");const o=e.getAttribute("style"),s=i.scrollX,a=i.scrollY,c=e.getBoundingClientRect().width,d=()=>{o===null?e.removeAttribute("style"):e.setAttribute("style",o),i.scrollTo(s,a)};try{e.style.setProperty("width",`${c}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 $(()=>new Promise(l=>i.requestAnimationFrame(()=>i.requestAnimationFrame(()=>l()))),r);const u=e.getBoundingClientRect();if(u.height+1<t.top+t.height||u.width+1<t.left+t.width||u.left<0||u.top<0)throw new Error("宿主布局无法容纳长图");for(let l=e.parentElement;l;l=l.parentElement){const f=i.getComputedStyle(l),m=l.getBoundingClientRect();if(["hidden","clip","scroll","auto"].includes(f.overflowY)&&(u.top+t.top<m.top-1||u.top+t.top+t.height>m.bottom+1))throw new Error("宿主布局无法容纳长图:祖先容器存在纵向裁剪")}return{rect:{...t,left:t.left+u.left,top:t.top+u.top},restore:d}}catch(u){throw d(),u}}function Ch(e,t,r,n=1e4){const i=new AbortController;return new Promise((o,s)=>{let a=!1;const c=l=>{a||(a=!0,clearTimeout(u),r.signal.removeEventListener("abort",d),i.abort(l),s(l))},d=()=>{i.abort(),c({code:"NETWORK_POLICY_CHANGED",message:"网络策略初始化已取消"})},u=setTimeout(()=>c({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(l=>{if(typeof l!="function"){c({code:"NETWORK_POLICY_UNSUPPORTED",message:"Host 未完成严格网络策略初始化"});return}if(a){try{l()}catch{}return}a=!0,clearTimeout(u),o(()=>{r.signal.removeEventListener("abort",d),i.abort(),l()})},c)})}function iu(e,t){return Rh(t)??Ph(e.pathname)}function Rh(e){if(!e)return;const t=new URL(e,"https://mini-program.invalid").pathname;return t.endsWith("/")?t:`${t}/`}function Ph(e){const t=/^(\/u\/[^/]+\/[^/]+\/)/.exec(e)?.[1];if(t)return t;const r=e.lastIndexOf("/");return r>=0?e.slice(0,r+1):"/"}const kh=1,ou="allow-scripts allow-same-origin",xh="",Uh="no-referrer";function jh(e=ou){return!e.split(/\s+/).includes("allow-same-origin")}function Aa(){return window.crypto?.randomUUID?window.crypto.randomUUID():`${Date.now().toString(36)}_${Math.random().toString(36).slice(2)}`}const zh=new Set(["javascript:","data:","blob:","file:"]),Na="xiaoheihe.cn";function Hh(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(zh.has(i.protocol)||!["http:","https:"].includes(i.protocol))throw new Error("不支持的小程序链接协议");if(!Bh(i,t,r))throw new Error("小程序链接必须属于 https://*.xiaoheihe.cn 或本地调试地址");return i.toString()}function Fh(e,t){const r=new URL(e);return r.searchParams.set(zd,t),r.toString()}function su(e,t,r){try{const n=new URL(e),i=new URL(t);if(n.origin!==i.origin)return!1;const o=iu(n,r);return i.pathname.startsWith(o)}catch{return!1}}function Da(e){const t=new URL(e);return xs(t)?"loopback":Us(t)?"lan":"production"}function Bh(e,t,r){return Vh(e)||xs(e)||Us(e)&&qh(t,r)}function Vh(e){return e.protocol==="https:"&&Wh(e.hostname)}function xs(e){return e.protocol==="http:"&&Gh(e.hostname)}function Gh(e){return e==="localhost"||e==="127.0.0.1"||e==="[::1]"}function Us(e){return e.protocol==="http:"&&Qh(e.hostname)}function qh(e,t){if(t.allowPrivateNetwork)return!0;try{const r=new URL(e);return xs(r)||Us(r)}catch{return!1}}function Qh(e){const t=Yh(e);return t?t[0]===10||t[0]===172&&t[1]>=16&&t[1]<=31||t[0]===192&&t[1]===168:!1}function Yh(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 Wh(e){return e===Na||e.endsWith(`.${Na}`)}function $h(e){let t,r=!1,n=!1;const i=new URL(e.launchUrl).origin,o=s=>{const a=s.data;if(n||!e.iframe.contentWindow||s.source!==e.iframe.contentWindow||s.origin!==i||a?.type!=="hb-sdk:dev-document"||a.nonce!==e.nonce||typeof a.documentId!="string"||!/^[a-f0-9]{32}$/.test(a.documentId)||typeof a.href!="string"||a.href.length>8192||!su(e.launchUrl,a.href,e.locationBasePath))return;const c=new URL(a.href);if(!(c.username||c.password||c.searchParams.get(zd)!==e.nonce)){if(a.phase==="leaving"){a.documentId===t&&!r&&(r=!0,e.onLeaving());return}if(a.phase==="boot"){if(t!==void 0&&t!==a.documentId&&a.navigationType==="reload"){n=!0,e.onReload(c.href);return}r&&t===a.documentId&&e.onResume(),t=a.documentId,r=!1}}};return window.addEventListener("message",o),()=>{window.removeEventListener("message",o)}}function au(e){const t=je(e);return(r,n)=>{if(r.kind==="none")return{allowed:!0};for(const i of r.permissions){const o=t.valid?t.permissions[i]:void 0;if(!o)return{allowed:!1,code:"PERMISSION_NOT_IN_SNAPSHOT",message:`当前运行快照不包含权限: ${i};正式入口需发布包含该声明的新版本,开发入口请重新打开调试`,data:{permission:i,method:n}};if(o.status!=="enabled")return{allowed:!1,code:"PERMISSION_DENIED",message:`小程序权限未启用: ${i}`,data:{permission:i,method:n}}}return{allowed:!0}}}function Kh(e){const t=je(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 Zh(){try{return{activeElement:globalThis.document?.activeElement??null,userActivation:globalThis.navigator?.userActivation}}catch{return{activeElement:null}}}const Jh=1e3;function Xh(e,t=Zh()){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<=Jh}const em="runtime.gate.probe",cu=new Set(ct.map(e=>e.method));class tm{iframe;nonce;onReady;getWorkspaceCardLaunchContext;onHandshake;onDuplicateHandshake;onInternalEvent;onResponsePosted;onDevUploadSession;handleMessage;handleUserInteraction;dispatcher;environmentInfo;started=!1;destroyed=!1;handshaken=!1;bridgeVersion=jd;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:Et,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:Et,version:this.bridgeVersion,nonce:this.nonce,type:"event",method:t,payload:r})}postInternalRequest(t,r,n){this.destroyed||this.postMessage({namespace:Et,version:this.bridgeVersion,nonce:this.nonce,type:"request",id:r,method:t,payload:n})}postProgress(t,r){this.bridgeVersion===2&&this.postMessage({namespace:Et,version:2,nonce:this.nonce,type:"event",id:t,method:Fd,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{n=Xh(this.iframe,{activeElement:document.activeElement,userActivation:navigator.userActivation,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&&Uf(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,o=!this.handshaken;if(o){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:Et,version:this.bridgeVersion,nonce:this.nonce,type:"response",id:t.id,method:Hd,payload:{environment:this.environmentInfo,...this.getWorkspaceCardLaunchContext?{workspaceCardLaunchContext:this.getWorkspaceCardLaunchContext()}:{}}}),this.postEvent("ready",{timestamp:Date.now()}),o?this.onReady?.(n):this.onDuplicateHandshake?.()}async handleRequest(t,r){if(!t.id||!t.method)return;if(!this.handshaken&&t.method===em){this.postResponse(t,{ready:!0});return}if(!this.handshaken){this.postResponse(t,void 0,ee("BRIDGE_NOT_READY","小程序 SDK 尚未完成握手"));return}if(!cu.has(t.method)){this.postResponse(t,void 0,ee("METHOD_NOT_FOUND",`未开放小程序能力: ${t.method}`));return}if(this.operations.has(t.id)){this.postResponse(t,void 0,ee("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:o=>{this.operations.get(t.id)===n&&this.postProgress(t.id,o)},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 o=ks(i);this.postResponse(t,void 0,o),this.postEvent("error",o)}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:Et,version:t.version,nonce:this.nonce,type:"response",id:t.id,method:t.method,payload:r,error:n})||!rm(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 rm(e){return typeof e=="string"&&cu.has(e)}function p(e,t,r){return r===void 0?{code:e,message:t}:{code:e,message:t,data:r}}function Q(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function nm(e){return{[Lr]:async(t,r)=>{const n=ae(e.operationContext,r.signal);if(X(n.signal),t!==void 0)throw p("INVALID_PARAMS","user.showAppreciation 不支持参数");if(!r.trustedUserGesture)throw p("USER_GESTURE_REQUIRED","请通过点击打开赞赏码");const i=e.miniProgramPresentation;if(!i?.name||!i.author)throw p("INVALID_STATE","缺少小程序名称或开发者信息,无法展示赞赏码");const o=e.presentation.showAppreciation;if(!o)throw p("REQUEST_UNSUPPORTED","当前宿主不支持赞赏码");await $(()=>o({name:i.name,author:i.author},n),n.signal)}}}function xt(){const e=new Error("Runtime cache read cancelled");return e.name="AbortError",e}function Ma(e,t){return e.length===t.length&&e.every((r,n)=>r===t[n])}function du(e={}){const t=e.now??Date.now,r=new WeakMap,n=new Map,i=new Set,o=new Map,s=new Set,a=new Set;let c=!1;function d(g,I){try{e.onEvent&&Promise.resolve(e.onEvent({namespace:g,type:I})).catch(()=>{})}catch{}}function u(g){const I=r.get(g);if(!I)throw new Error("Unknown runtime cache scope");return I}function l(g,I){return g.flatMap((y,b)=>{const _=JSON.stringify(g.slice(0,b+1));return[JSON.stringify([_]),JSON.stringify([_,I])]})}function f(g,I){return JSON.stringify(l(g,I).map(y=>n.get(y)??0))}async function m(g,I){const y=u(g),b=JSON.stringify([JSON.stringify(y),...I?[I]:[]]),_=(n.get(b)??0)+1;n.set(b,_),i.add(b);for(const P of a)P(y,I);if(!e.store){i.delete(b),d(I??"*","invalidation");return}try{await e.store.invalidate(y,I)}catch(P){throw d(I??"*","storage_error"),P}n.get(b)===_&&i.delete(b),d(I??"*","invalidation")}function h(g){if(c)throw new Error("Runtime cache manager disposed");const I=o.get(g.namespace);if(I){if(I.sourceCodec!==g.codec||I.definition.codec.version!==g.codec.version||JSON.stringify(I.definition.policy)!==JSON.stringify(g.policy))throw new Error("Conflicting runtime cache namespace");return I.cache}if(!g.namespace||!g.codec.version)throw new Error("Invalid runtime cache definition");const y=Object.freeze({...g.policy}),b=Object.freeze({version:g.codec.version,encode:g.codec.encode.bind(g.codec),decode:g.codec.decode.bind(g.codec),validate:g.codec.validate.bind(g.codec),clone:g.codec.clone.bind(g.codec)}),_=g.namespace;for(const N of[y.ttlMs,y.memoryMaxEntries,y.diskMaxEntries,y.diskMaxBytes,y.maxEntryBytes])if(!Number.isFinite(N)||N<0)throw new Error("Invalid runtime cache policy");const P=new Map,j=new Map,U=new Map;let O=!1;function w(N,A,L){if(c||O||N.aborted||f(A,_)!==L)throw xt()}function S(N){return y.ttlMs>0&&y.persistence==="memory-and-disk"&&!!e.store&&!l(N,_).some(A=>i.has(A))}function v(N,A,L){const k=t();return N.envelopeVersion===1&&JSON.stringify(N.address)===JSON.stringify(A)&&Ma(N.revisions,L)&&N.payload.byteLength<=y.maxEntryBytes&&Number.isFinite(N.cachedAt)&&Number.isFinite(N.expiresAt)&&N.cachedAt<=k&&N.cachedAt>=0&&N.expiresAt>N.cachedAt&&Math.min(N.expiresAt,N.cachedAt+y.ttlMs)>k}function C(N,A,L,k,x){if(!(y.ttlMs<=0||y.memoryMaxEntries<1)){for(const[H,F]of P)Math.min(F.entry.expiresAt,F.entry.cachedAt+y.ttlMs)<=t()&&P.delete(H);for(P.delete(N);P.size>=Math.floor(y.memoryMaxEntries);){const H=P.keys().next();if(H.done)break;P.delete(H.value)}P.set(N,{entry:A,value:L,epoch:k,persistent:x})}}async function E(N,A,L,k){const x={namespace:_,codecVersion:b.version,scopeIds:A,key:N.key},H=JSON.stringify(x);let F=[],V=S(A);if(V)try{F=await e.store.readRevisions(A,_)}catch{V=!1,d(_,"storage_error")}w(k.signal,A,L);async function q(){if(!V)return!0;try{return Ma(F,await e.store.readRevisions(A,_))}catch{return V=!1,d(_,"storage_error"),!1}}const J=P.get(H);if(y.ttlMs>0&&J&&J.epoch===L&&v(J.entry,x,F)&&J.persistent===V&&await q())return w(k.signal,A,L),d(_,"memory_hit"),J.value;if(P.delete(H),V){let Y,re;try{Y=await e.store.read(x,y.maxEntryBytes),Y&&v(Y,x,F)?re=b.decode(Y.payload):Y=void 0}catch{Y=void 0,d(_,"storage_error")}if(w(k.signal,A,L),Y&&await q())return w(k.signal,A,L),C(H,Y,re,L,!0),d(_,"disk_hit"),re}d(_,"miss");const K=b.validate(await N.load(k.signal));w(k.signal,A,L);const Z=b.clone(K);if(!await q()&&V)throw xt();if(w(k.signal,A,L),y.ttlMs>0){const Y=t();let re;try{re=b.encode(Z)}catch{return Z}const Me={envelopeVersion:1,address:x,revisions:V?F:[],cachedAt:Y,expiresAt:Y+y.ttlMs,payload:re};if(V&&re.byteLength<=y.maxEntryBytes){let le=!0,fe=!1;try{le=await e.store.publish(Me,y),fe=le}catch{d(_,"storage_error")}if(w(k.signal,A,L),!le)throw xt();fe&&d(_,"published")}w(k.signal,A,L),C(H,Me,Z,L,V)}return Z}async function D(N){if(c||O||N.signal?.aborted)return Promise.reject(xt());const A=u(N.scope),L=f(A,_);let k;if(S(A)){const V=new AbortController;U.set(V,A);const q=()=>V.abort();N.signal?.addEventListener("abort",q,{once:!0});let J=()=>{};try{k=await Promise.race([e.store.readRevisions(A,_),new Promise((K,Z)=>{const Y=()=>Z(xt());V.signal.addEventListener("abort",Y,{once:!0}),J=()=>V.signal.removeEventListener("abort",Y)})])}catch{V.signal.aborted||d(_,"storage_error")}finally{J(),U.delete(V),N.signal?.removeEventListener("abort",q)}}w(N.signal??new AbortController().signal,A,L);const x=JSON.stringify([A,N.key,L,k]);let H=j.get(x);if(H?.controller.signal.aborted&&(H=void 0),!H){const V=new AbortController;H={ids:A,controller:V,waiters:0,promise:Promise.resolve(void 0)};const q=H;q.promise=E(N,A,L,V).finally(()=>{j.get(x)===q&&j.delete(x)}),j.set(x,q)}const F=H;return F.waiters+=1,new Promise((V,q)=>{let J=!1;function K(Y){J||(J=!0,N.signal?.removeEventListener("abort",Z),F.controller.signal.removeEventListener("abort",Z),F.waiters-=1,F.waiters===0&&F.controller.abort(),Y())}function Z(){K(()=>q(xt()))}N.signal?.addEventListener("abort",Z,{once:!0}),F.controller.signal.addEventListener("abort",Z,{once:!0}),F.promise.then(Y=>K(()=>{try{w(N.signal??new AbortController().signal,A,L),V(b.clone(Y))}catch(re){q(re)}}),Y=>K(()=>q(Y)))})}function M(N,A){if(A&&A!==_)return;const L=k=>N.every((x,H)=>k[H]===x);for(const[k,x]of P)L(x.entry.address.scopeIds)&&P.delete(k);for(const[k,x]of j)L(x.ids)&&(x.controller.abort(),j.delete(k));for(const[k,x]of U)L(x)&&k.abort()}function R(){if(!O){O=!0,P.clear();for(const N of U.keys())N.abort();U.clear();for(const N of j.values())N.controller.abort();j.clear(),s.delete(R),a.delete(M),o.get(_)?.cache===T&&o.delete(_)}}const T={read:D,invalidateScope:N=>m(N,_),dispose:R};return s.add(R),a.add(M),o.set(_,{definition:{namespace:_,codec:b,policy:y},sourceCodec:g.codec,cache:T}),T}return{createScope(g,I){if(c||!g)throw new Error("Invalid runtime cache scope");const y=Object.freeze({});return r.set(y,[...I?u(I):[],g]),y},register:h,invalidateScope:g=>m(g),dispose(){if(!c){c=!0;for(const g of[...s])g();o.clear(),n.clear(),i.clear()}}}}function im(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 om=".hb-runtime-cache-v1",sm=1e3,Xi=64*1024,Ut=1e3,am=2048,pr=32*1024*1024,cm=1024,An=new TextEncoder,Sa=new TextDecoder("utf-8",{fatal:!0});function yr(){return Object.assign(new Error("缓存文件操作已取消"),{name:"AbortError"})}async function an(e){const t=await globalThis.crypto.subtle.digest("SHA-256",An.encode(JSON.stringify(e)));return Array.from(new Uint8Array(t),r=>r.toString(16).padStart(2,"0")).join("")}function Fe(e,t){return JSON.stringify(e)===JSON.stringify(t)}function _a(){return Array.from(globalThis.crypto.getRandomValues(new Uint8Array(16)),e=>e.toString(16).padStart(2,"0")).join("")}function dm(e){return!!e&&typeof e=="object"&&["METHOD_FORBIDDEN","NOT_SUPPORTED","UNSUPPORTED_OPERATION","ENOSYS","ENOTSUP","EOPNOTSUPP"].includes(String(e.code))}function ba(e,t){if(t.some(r=>typeof e[r]!="function"))throw Object.assign(new Error("Host 文件原语不完整,关闭磁盘缓存"),{code:"METHOD_FORBIDDEN"})}function um(e,t){const r=e.sandbox.directory(om),n=r.directory("revisions"),i=r.directory("entries");for(const E of[r,n,i,i.directory("capability-check")])ba(E,["directory","file","create","stat","list","remove"]),ba(E.file("capability-check"),["create","stat","read","write","remove"]);const o=new AbortController,s=()=>o.abort();t.signal.aborted?s():t.signal.addEventListener("abort",s,{once:!0});const a={...t,signal:o.signal};let c=Promise.resolve(),d;function u(E){d=E,o.abort(),t.signal.removeEventListener("abort",s)}function l(E){if(dm(E))throw u(E),E}function f(){if(d)throw d;if(a.signal.aborted)throw yr()}function m(E,D=a.signal){const M=c.then(()=>{if(D.aborted)throw d??yr();return f(),E()},()=>{if(D.aborted)throw d??yr();return f(),E()}).catch(A=>{throw l(A),A});if(c=M.catch(()=>{}),D.aborted)return Promise.reject(d??yr());let R=()=>{};const T=new Promise((A,L)=>{const k=()=>L(d??yr());D.addEventListener("abort",k,{once:!0}),R=()=>D.removeEventListener("abort",k)}),N=setTimeout(()=>{u(Object.assign(new Error("缓存文件操作超时,已降级为内存缓存"),{code:"CACHE_STORAGE_TIMEOUT"}))},sm);return Promise.race([M,T]).finally(()=>{clearTimeout(N),R()})}async function h(){f(),await n.create({recursive:!0,exclusive:!1},a),f(),await i.create({recursive:!0,exclusive:!1},a),f()}async function g(E,D){const M=n.file(`${await an([E,D??null])}.revision`);await y(M);let R=!1;try{await M.create({recursive:!1,exclusive:!0},a),R=!0}catch(A){l(A),f()}if(R){const A=_a();return await M.write(An.encode(A),a),f(),A}const T=await M.stat(a);if(T.size<1||T.size>128)throw new Error("缓存 revision 文件损坏");const N=Sa.decode(await M.read(a));if(!/^(?:[0-9a-f]{32}|[0-9a-f-]{36})$/.test(N))throw new Error("缓存 revision 文件损坏");return f(),N}async function I(E){const D=await E.list({limit:Ut},a);if(D.length>=Ut)throw new Error("缓存目录超过治理上限");return D}async function y(E){try{await E.stat(a);return}catch(M){if(!cn(M))throw M}if((await I(n)).length>=Ut-1)throw new Error("缓存 metadata 超过治理上限")}async function b(E,D){await h();const M=[];for(let R=0;R<E.length;R+=1){const T=E.slice(0,R+1);M.push(await g(T),await g(T,D))}return M}async function _(E){return r.directory(`entries/${await an([E.namespace,E.codecVersion,E.scopeIds])}`)}async function P(E){return(await _(E)).file(`${await an(E.key)}.cache`)}async function j(E,D){const M=await E.stat(a);if(M.size<5||M.size>D+Xi+4)throw new Error("缓存条目超过大小限制");const R=await E.read(a);if(f(),R.length!==M.size)throw new Error("缓存条目读取不完整");const T=new DataView(R.buffer,R.byteOffset,R.byteLength).getUint32(0);if(T<1||T>Xi||T+4>R.length)throw new Error("缓存信封损坏");const N=JSON.parse(Sa.decode(R.subarray(4,T+4))),A=R.slice(T+4);if(N.envelopeVersion!==1||!N.address||!Array.isArray(N.address.scopeIds)||!N.address.scopeIds.every(L=>typeof L=="string")||typeof N.address.namespace!="string"||typeof N.address.codecVersion!="string"||typeof N.address.key!="string"||!Array.isArray(N.revisions)||N.revisions.length!==N.address.scopeIds.length*2||!N.revisions.every(L=>typeof L=="string"&&L.length>0)||!Number.isSafeInteger(N.cachedAt)||!Number.isSafeInteger(N.expiresAt)||N.cachedAt<0||N.expiresAt<=N.cachedAt||N.payloadBytes!==A.length||A.length>D)throw new Error("缓存信封损坏");return{envelopeVersion:1,address:N.address,revisions:N.revisions,cachedAt:N.cachedAt,expiresAt:N.expiresAt,payload:A}}async function U(E){if(!E.remove)throw new Error("Host 不支持缓存文件删除");await E.remove(a)}async function O(E){try{if((await E.file.stat(a)).size!==E.size)return!1;const D=await j(E.file,pr);return!Fe(D.address,E.entry.address)||!Fe(D.revisions,E.entry.revisions)||D.cachedAt!==E.entry.cachedAt||D.expiresAt!==E.entry.expiresAt||!Fe(await w(D.payload),await w(E.entry.payload))?!1:(await U(E.file),!0)}catch(D){if(cn(D))return!0;throw D}}async function w(E){const D=await globalThis.crypto.subtle.digest("SHA-256",E);return Array.from(new Uint8Array(D),M=>M.toString(16).padStart(2,"0")).join("")}async function S(){const E=await I(n);let D=0;for(const N of E)if(N.kind==="file"&&(D+=(await N.stat(a)).size,D>pr))throw new Error("缓存扫描超过字节上限");const M=[];let R=0,T=D;for(const N of await I(i)){if(N.kind!=="directory")throw new Error("缓存目录结构损坏");for(const A of await I(N)){if(A.kind!=="file"||++R>am)throw new Error("缓存文件超过治理上限");const L=(await A.stat(a)).size;if(T+=L,T>pr)throw new Error("缓存扫描超过字节上限");try{const k=await j(A,pr);M.push({file:A,entry:k,size:(await A.stat(a)).size,bucketName:N.name})}catch(k){l(k),f(),cn(k)||await U(A)}}}return{entries:M,metadataBytes:D}}async function v(){for(const E of await I(i))if(E.kind==="directory"&&E.remove&&(await I(E)).length===0)try{await E.remove({recursive:!1},a)}catch(D){l(D),f()}}function C(E){const{payload:D,...M}=E,R=An.encode(JSON.stringify({...M,payloadBytes:D.length}));if(R.length>Xi)throw new Error("缓存信封过大");const T=new Uint8Array(4+R.length+D.length);return new DataView(T.buffer).setUint32(0,R.length),T.set(R,4),T.set(D,R.length+4),T}return{readRevisions:(E,D)=>m(()=>b(E,D)),read:(E,D)=>m(async()=>{f();const M=await P(E);let R;try{R=await j(M,D)}catch(T){if(f(),cn(T))return;throw T}if(!(!Fe(R.address,E)||R.expiresAt<=Date.now())&&Fe(R.revisions,await b(E.scopeIds,E.namespace)))return R}),publish:(E,D)=>m(async()=>{f();const{address:M}=E;if(!Fe(E.revisions,await b(M.scopeIds,M.namespace)))return!1;const R=C(E);if(E.payload.length>D.maxEntryBytes||R.length>D.diskMaxBytes||D.diskMaxEntries<1)throw new Error("缓存条目超出容量预算");await h();const T=await _(M),N=await P(M),A=await S(),L=[],k=new Map;for(const F of A.entries){if(F.bucketName===T.name&&F.file.name===N.name)continue;const V=JSON.stringify([F.entry.address.scopeIds,F.entry.address.namespace]);let q=k.get(V);if(q||(q=await b(F.entry.address.scopeIds,F.entry.address.namespace),k.set(V,q)),F.entry.expiresAt<=Date.now()||!Fe(F.entry.revisions,q)){if(!await O(F))throw new Error("缓存治理期间条目已变化")}else L.push(F)}L.sort((F,V)=>F.entry.cachedAt-V.entry.cachedAt);function x(){const F=L.filter(V=>V.bucketName===T.name);return L.length+1>cm||R.length+A.metadataBytes+L.reduce((V,q)=>V+q.size,0)>pr||F.length+1>Math.min(D.diskMaxEntries,Ut-1)||R.length+F.reduce((V,q)=>V+q.size,0)>D.diskMaxBytes}for(;x();){const F=L.filter(J=>J.bucketName===T.name),q=F.length+1>Math.min(D.diskMaxEntries,Ut-1)||R.length+F.reduce((J,K)=>J+K.size,0)>D.diskMaxBytes?F[0]:L[0];if(!q||!await O(q))throw new Error("缓存容量不足或条目已变化");L.splice(L.indexOf(q),1)}await v();const H=await I(i);if(!H.some(F=>F.name===T.name)&&H.length>=Ut-1)throw new Error("缓存目录超过治理上限");if(await T.create({recursive:!0,exclusive:!1},a),!Fe(E.revisions,await b(M.scopeIds,M.namespace)))return!1;try{await N.create({recursive:!1,exclusive:!0},a)}catch(F){l(F),await N.stat(a)}return await N.write(R,a),f(),Fe(E.revisions,await b(M.scopeIds,M.namespace))}),invalidate:(E,D)=>m(async()=>{await h();const M=n.file(`${await an([E,D??null])}.revision`);await y(M);try{await M.create({recursive:!1,exclusive:!0},a)}catch(R){l(R),await M.stat(a)}await M.write(An.encode(_a()),a),f();try{const{entries:R}=await S();for(const T of R){if(D!==void 0&&T.entry.address.namespace!==D||!E.every((A,L)=>T.entry.address.scopeIds[L]===A))continue;const N=await b(T.entry.address.scopeIds,T.entry.address.namespace);Fe(T.entry.revisions,N)||await O(T)}await v()}catch(R){l(R),f()}})}}function cn(e){return!!e&&typeof e=="object"&&["FILE_NOT_FOUND","ENOENT","NOT_FOUND"].includes(String(e.code))}const lm="RATE_LIMITED_BY_RUNTIME",fm="RATE_LIMITED",uu=20,lu=40,fu=150,hu=20,mu=1e4,gu=45e3,pu=1,hm=300*1e3,mm=64;function jt(e,t){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:t}function gm(e,t){return typeof e=="number"&&Number.isFinite(e)&&e>=0?Math.floor(e):t}function pm(e={}){const t=e.now??Date.now,r=gm(e.coalesceWindowMs,fu),n=e.budget===!1?void 0:{ratePerSecond:Math.max(.001,jt(e.budget?.ratePerSecond,uu)),burst:Math.max(1,Math.floor(jt(e.budget?.burst,lu)))},i=e.loopDetection===!1?void 0:{maxCalls:Math.max(1,Math.floor(jt(e.loopDetection?.maxCalls,hu))),windowMs:Math.max(1,Math.floor(jt(e.loopDetection?.windowMs,mu)))},o=e.circuitBreaker===!1?void 0:{failureThreshold:Math.max(1,Math.floor(jt(e.circuitBreaker?.failureThreshold,pu))),openMs:Math.max(1,Math.floor(jt(e.circuitBreaker?.openMs,gu)))},s=new Map,a=new Map,c=new Set,d=new Map,u=n?{tokens:n.burst,updatedAt:t()}:{tokens:0,updatedAt:0},l={coalesced:0,budgetRejected:0,loopRejected:0,circuitOpened:0,circuitRejected:0};let f=!1;function m(O){try{e.onReport?.(O)}catch{}}function h(O,w){if(!i)return{exceeded:!1,count:0};const S=a.get(O)??[],v=w-i.windowMs;let C=0;for(;C<S.length&&S[C]<=v;)C+=1;C>0&&S.splice(0,C);const E=S.length>=i.maxCalls;return E||(S.push(w),S.length>i.maxCalls+1&&S.splice(0,S.length-(i.maxCalls+1))),a.set(O,S),{exceeded:E,count:S.length}}function g(O){if(!n)return!0;const w=Math.max(0,O-u.updatedAt)/1e3;return u.tokens=Math.min(n.burst,u.tokens+w*n.ratePerSecond),u.updatedAt=O,u.tokens<1?!1:(u.tokens-=1,!0)}function I(O){if(!n)return 0;const w=Math.max(0,O-u.updatedAt)/1e3,S=Math.min(n.burst,u.tokens+w*n.ratePerSecond);return Math.max(0,Math.ceil((1-S)/n.ratePerSecond*1e3))}function y(O,w,S,v,C){if(!o)return;const E=d.get(w),D=(E?.open?0:E?.failures??0)+1;if(D<o.failureThreshold){d.set(w,{open:!1,openedAt:0,openMs:0,failures:D});return}const M=Math.min(Math.max(o.openMs,v),hm);d.set(w,{open:!0,openedAt:C,openMs:M,failures:D}),l.circuitOpened+=1,m({type:"circuit_opened",capability:O,endpointId:w,status:S,openMs:M,timestamp:C})}function b(O){const w=d.get(O);w&&!w.open&&d.delete(O)}function _(O){for(const[w,S]of s)!S.pending&&S.expiresAt<=O&&s.delete(w);for(;s.size>=mm;){const w=[...s].find(([,S])=>!S.pending);if(!w)break;s.delete(w[0])}}function P(O,w){if(O===void 0)return;const S=s.get(O);S?.promise===w&&(S.pending=!1)}function j(O,w){if(O===void 0)return;s.get(O)?.promise===w&&s.delete(O)}async function U(O){if(f)return O.load();const w=t();if(o){const E=d.get(O.endpointId);if(E?.open){const D=E.openedAt+E.openMs-w;if(D>0)throw l.circuitRejected+=1,m({type:"circuit_rejected",capability:O.capability,endpointId:O.endpointId,retryAfterMs:D,timestamp:w}),wm("上游已被网关限流,Runtime 熔断中,请稍后重试",{origin:"circuit",reason:"circuit_open",endpointId:O.endpointId,retryAfterMs:D});d.delete(O.endpointId)}}const S=h(O.endpointId,w);S.exceeded&&i?c.has(O.endpointId)||(c.add(O.endpointId),m({type:"loop_detected",capability:O.capability,endpointId:O.endpointId,count:S.count,windowMs:i.windowMs,timestamp:w})):c.delete(O.endpointId);const v=r>0?O.coalesceKey:void 0;if(v!==void 0){const E=s.get(v);if(E&&(E.pending||E.expiresAt>w))return l.coalesced+=1,m({type:"coalesced",capability:O.capability,endpointId:O.endpointId,timestamp:w}),E.promise;E&&s.delete(v)}if(S.exceeded&&i)throw l.loopRejected+=1,Ta("检测到同一 endpoint 的高频循环调用,本次请求已在 Runtime 本地拒绝",{origin:"loop",reason:"loop",capability:O.capability,endpointId:O.endpointId,count:S.count,windowMs:i.windowMs});if(!g(w)){l.budgetRejected+=1;const E=I(w);throw m({type:"budget_exhausted",capability:O.capability,endpointId:O.endpointId,retryAfterMs:E,timestamp:w}),Ta("请求过于频繁,已触发 Runtime 本地配额限制",{origin:"budget",reason:"budget",capability:O.capability,endpointId:O.endpointId,retryAfterMs:E})}v!==void 0&&_(w);const C=O.load().then(E=>(P(v,C),b(O.endpointId),E),E=>{j(v,C);const D=ym(E);throw D!==void 0&&y(O.capability,O.endpointId,D,Em(E),w),E});return v!==void 0&&s.set(v,{endpointId:O.endpointId,promise:C,expiresAt:w+r,pending:!0}),C}return{execute:U,invalidateCoalescing(O){if(O===void 0){s.clear();return}for(const[w,S]of s)O.includes(S.endpointId)&&s.delete(w)},snapshot(){return{...l,openCircuits:[...d.entries()].filter(([,O])=>O.open).map(([O])=>O)}},dispose(){f||(f=!0,s.clear(),a.clear(),c.clear(),d.clear())}}}function ym(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 Em(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 Ta(e,t){return{code:lm,message:e,data:t}}function wm(e,t){return{code:fm,message:e,data:t}}const yu=3e4,Eu=6e4,Zo=1440*60*1e3;function Im(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??yu)):0,profileTtlMs:t?Math.max(0,Math.floor(r?.profileTtlMs??Eu)):0,steamGameListTtlMs:t?Am(r?.steamGameListTtlMs):0,gateOptions:{budget:r?.budget??{ratePerSecond:uu,burst:lu},coalesceWindowMs:r?.coalesceWindowMs??fu,loopDetection:r?.loopDetection??{maxCalls:hu,windowMs:mu},circuitBreaker:r?.circuitBreaker??{failureThreshold:pu,openMs:gu}}}}function Am(e){return e===void 0||!Number.isFinite(e)?Zo:Math.max(0,Math.floor(e))}function Nm(e){return typeof e=="object"&&e!==null}function de(e,t){const r=e.data;if(!Nm(r)||typeof r.status!="string")throw new Error(t);return r}const wu={auth:"optional",channel:"api",id:"heybox.account.user_base_info.envelope.get",method:"GET",path:"/account/get_user_base_info"},Dm={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 de(e,"工坊小程序详情加载失败")}};function Yr(e){const t=e.runtimeAuthContextToken?.trim();return{mini_program_id:e.miniProgramId,...t?{runtime_auth_context_token:t}:{}}}function Mm(e){return{challenge:e.challenge,expiresIn:e.expires_in,requestedScopes:e.requested_scopes||[],displayedScopes:e.displayed_scopes||[],consentUiVersion:e.consent_ui_version}}function Sm(e){const t=de(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=Mm(r.consent_challenge)),{...t,result:n}}const _m={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=>({...Yr(e.runtimeContext),challenge:e.challenge}),parse:e=>de(e,"小程序授权取消接口响应异常")},bm={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=>Yr(e.runtimeContext),parse:e=>de(e,"小程序授权撤销接口响应异常")},Tm={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=>Yr(e.runtimeContext),parse(e){const t=de(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}:{}}}}},Om={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=>({...Yr(e.runtimeContext),...e.scopes?.length?{scopes:e.scopes.join(",")}:{}}),parse:e=>Sm(e)},vm={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=>({...Yr(e.runtimeContext),challenge:e.challenge,...e.selectedScopes.length?{selected_scopes:e.selectedScopes.join(",")}:{}}),parse(e){const t=de(e,"小程序登录确认接口响应异常");return{...t,result:{code:t.result.code,expiresIn:t.result.expires_in,scopes:t.result.scopes}}}},Lm=64;function Iu(e){const t=e.ttlMs,r=Math.max(1,Math.floor(e.maxEntries??Lm)),n=e.now??Date.now,i=new Map,o=new Map;let s=0,a=!1;function c(l){for(const[f,m]of i)m.expiresAt<=l&&i.delete(f)}function d(l,f,m){if(a||t<=0||m!==s)return;const h=n();for(c(h),i.delete(l);i.size>=r;){const g=i.keys().next();if(g.done)break;i.delete(g.value)}i.set(l,{expiresAt:h+t,value:f})}function u(l,f){if(a)return f();if(t>0){const I=i.get(l);if(I&&I.expiresAt>n())return Promise.resolve(I.value);I&&i.delete(l)}const m=o.get(l);if(m)return m;const h=s,g=f().then(I=>(d(l,I,h),I)).finally(()=>{o.get(l)===g&&o.delete(l)});return o.set(l,g),g}return{read:u,invalidate(){s+=1,i.clear(),o.clear()},dispose(){a||(a=!0,s+=1,i.clear(),o.clear())},get size(){return i.size}}}function Cm(e,t){return t?e?"server":"local":"legacy"}function Rm(e,t){if(e==="local")throw p("SERVER_API_REQUIRED",`${t} 需要 effective network 启用后才能使用`)}const Pm=["baseURL","errorMode","jsonParseMode","observability","queryEncoding","responseType","security"],km=new Set(["auth","body","bodyEncoding","channel","failurePresentation","headers","id","method","parse","path","query","timeout"]),xm=/authorization|cookie|pkey|password|secret|token/i,Au=/authorization|cookie|pkey|token|password|secret/i;function Be(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function Um(e){for(const t of Object.keys(e))if(!km.has(t))throw new ge(`endpoint 字段不受 hb-sdk-runtime private mapper 支持: ${t}`);for(const t of Pm)if(Object.prototype.hasOwnProperty.call(e,t)&&Be(e,t)!==void 0)throw new ge(`endpoint 字段不受 hb-sdk-runtime private mapper 支持: ${t}`);if(Be(e,"bodyEncoding")!==void 0&&Be(e,"bodyEncoding")!=="json"&&Be(e,"bodyEncoding")!=="form")throw new ge("endpoint bodyEncoding 不受 HostNetworkPort 支持");if(Be(e,"failurePresentation")!==void 0&&Be(e,"failurePresentation")!=="none")throw new ge("endpoint failurePresentation 必须为 none");if(Be(e,"auth")!==void 0&&Be(e,"auth")!=="none"&&Be(e,"auth")!=="optional"&&Be(e,"auth")!=="required")throw new ge("endpoint auth 必须为 none、optional 或 required")}function Sr(e){if(Array.isArray(e))return e.map(Sr);if(!e||typeof e!="object")return e;const t=e,r={};for(const[n,i]of Object.entries(t))xm.test(n)||(r[n]=Sr(i));return r}function Oa(e){if(!e)return;const t={};for(const[r,n]of Object.entries(e))Au.test(r)||(t[r]=n);return t}function jm(e){if(!e)return;const t=Object.keys(e).find(r=>Au.test(r));if(t)throw new ge(`endpoint 禁止声明 credential-bearing header: ${t}`)}class Wr 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 va=1440*60*1e3,zm=/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun)\b/i;function Hm(e,t=Date.now){if(!e)return;const r=Object.entries(e).find(([s])=>s.trim().toLowerCase()==="retry-after")?.[1];if(typeof r!="string"||!r.trim())return;const n=r.trim();if(/^\d+$/.test(n)){const s=Number(n)*1e3;return s>0?Math.min(s,va):void 0}if(!zm.test(n))return;const i=Date.parse(n);if(!Number.isFinite(i))return;const o=i-t();return o>0?Math.min(o,va):void 0}function Fm(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 Nu(e,t){Object.defineProperty(e,"cause",{configurable:!1,enumerable:!1,value:t,writable:!1})}class nr extends Error{code="INTERNAL_ENDPOINT_REQUEST_FAILED";endpointId;constructor(t){super(`内部 endpoint 请求执行失败: ${t.endpointId}`),this.name="InternalEndpointRequestError",this.endpointId=t.endpointId,Nu(this,t.cause),Object.setPrototypeOf(this,new.target.prototype)}}class $r extends Error{code="INTERNAL_ENDPOINT_PARSE_FAILED";endpointId;constructor(t){super(`内部 endpoint 响应解析失败: ${t.endpointId}`),this.name="InternalEndpointParseError",this.endpointId=t.endpointId,Nu(this,t.cause),Object.setPrototypeOf(this,new.target.prototype)}}function Bm(e,t,r,n,i,o,s,a){return{config:{auth:e.auth,body:Sr(i),bodyEncoding:e.bodyEncoding,channel:e.channel,credentials:s.credentials,headers:Oa(o),method:e.method,metadata:{endpointId:e.id},query:Sr(n),timeout:e.timeout,url:r},data:Sr(a.data),headers:Oa(a.headers)||{},status:a.status,statusText:a.statusText}}async function Fi(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(Um(t),typeof t.id!="string"||!t.id)throw new ge("endpoint id 必须为非空字符串");if(!["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"].includes(t.method))throw new ge("endpoint method 不受 HostNetworkPort 支持");const i=typeof t.path=="function"?await t.path(r):t.path;if(typeof i!="string"||!i)throw new ge("endpoint path 必须为非空字符串");const o=t.query?await t.query(r):void 0,s=t.body?await t.body(r):void 0,a=t.headers?await t.headers(r):void 0;jm(a);const c=async()=>{let l;try{l=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,...o===void 0?{}:{params:o},...s===void 0?{}:{data:s},...a===void 0?{}:{headers:a},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(m){throw m instanceof ge?m:new nr({endpointId:t.id,cause:m})}if(l.status<200||l.status>=300)throw new Wr({endpointId:t.id,status:l.status,responseData:l.data,retryAfterMs:Hm(l.headers)});const f=Bm(t,r,i,o,s,a,n,l);if(t.parse)try{return await t.parse(f,r)}catch(m){throw new $r({endpointId:t.id,cause:m})}return f.data},d=n.gate;if(!d)return c();const u=Fm(t,o,s,n.credentials);return d.gate.execute({capability:d.capability,endpointId:t.id,...u===void 0?{}:{coalesceKey:u},load:c})}const Vm=new Set(["MINIPROGRAM_UNAVAILABLE","RUNTIME_CONTEXT_INVALID","CAPABILITY_NOT_GRANTED","AUTHORIZATION_CONTEXT_CHANGED","SERVER_API_REQUIRED","AUTHORIZATION_CANCELLED"]),Gm=new Set(rr),js="steam_account",Du=new Set(rr.filter(e=>e!==js)),qm=1e3;function Qm(e){const t=new Set,r=Iu({ttlMs:Math.max(0,Math.floor(e.identityTtlMs??yu))}),n=new Set;let i=0,o=!1,s=Promise.resolve(),a;const c=e.steamAccount===!0,d=e.userDataMode??Cm(e.networkEnabled===!0,c),u=e.requestPolicyEnabled!==!1,l=e.requestGate?{capability:"auth",gate:e.requestGate}:void 0;async function f(){if(!c&&!e.authorizationContext)return{};if(!e.authorizationContext)throw p("METHOD_FORBIDDEN","新能力版本缺少 Runtime auth context Port");let A;try{A=await e.authorizationContext.get(e.operationContext)}catch(k){throw Xo(k)?eo(k.code,k.message,k):eo("REQUEST_FAILED","读取 Runtime auth context 失败",k)}if(A.steamAccount!==c||A.userDataMode!==d)throw p("AUTHORIZATION_CONTEXT_CHANGED","Runtime auth context 已变化,请重新打开小程序");const L=A.token.trim();if(!L)throw p("REQUEST_FAILED","Runtime auth context 为空");return{runtimeAuthContextToken:L}}const m=e.account.onChange(A=>{if(h(),g("heybox_app_login_change",A?{isHeyboxAppLoggedIn:!0}:{isHeyboxAppLoggedIn:!1,accountKey:null}),A&&e.account.getAccountKey){const L=i;j().then(k=>{!o&&i===L&&g("heybox_app_login_change",k)}).catch(()=>{})}});function h(){i+=1,a?.abort(),r.invalidate(),e.requestGate?.invalidateCoalescing(),n.clear()}function g(A,L){A==="user_info_authorization_change"&&Jm(L)&&r.invalidate();for(const k of t)try{k(A,L)}catch{}}function I(){const A=e.identity.get()?.miniProgramId?.trim();if(!A)throw p("INVALID_STATE","当前能力缺少 canonical 小程序身份");return A}function y(){if(o||e.operationContext.signal.aborted)throw p("RUNTIME_DESTROYED","小程序 Runtime 已终止")}async function b(){y();let A;try{A=await e.account.getCurrentUserId(e.operationContext)}catch(L){throw Pa(L,e.operationContext.signal,"读取小黑盒账号失败")}return typeof A=="string"&&A.trim()?A.trim():void 0}async function _(A,L){const k=await b();if(i!==L||k!==A)throw p("AUTHORIZATION_CONTEXT_CHANGED","授权期间账号上下文已变化,请重新操作")}async function P(A,L,k=I()){if(!e.account.getAccountKey)throw p("METHOD_FORBIDDEN","Host 不支持持久化账号比较");let x;try{x=await e.account.getAccountKey(k,A,e.operationContext)}catch{throw y(),p("REQUEST_FAILED","读取本地账号标识失败")}if(await _(A,L),I()!==k)throw p("AUTHORIZATION_CONTEXT_CHANGED","读取期间小程序上下文已变化");if(typeof x!="string"||!x.trim())throw p("INVALID_RESPONSE","Host 返回了无效的账号标识");return x}async function j(){const A=I(),L=i,k=await b();if(y(),i!==L)throw p("AUTHORIZATION_CONTEXT_CHANGED","读取期间账号上下文已变化");return k?{isHeyboxAppLoggedIn:!0,accountKey:await P(k,L,A)}:{isHeyboxAppLoggedIn:!1,accountKey:null}}async function U(A){y();try{await e.account.ensureAuthenticated({trustedUserGesture:A,reason:"runtime_auth",signal:e.operationContext.signal})}catch(k){throw Pa(k,e.operationContext.signal,"小黑盒登录失败")}const L=await b();if(!L)throw p("HEYBOX_APP_LOGIN_REQUIRED","请先登录小黑盒");return L}async function O(A,L,k=e.operationContext.signal){try{if(k.aborted)throw Jo();return await Zm(Fi(e.network,A,L,{...e.operationContext,credentials:"heybox-session",signal:k,...l?{gate:l}:{}}),k)}catch(x){throw e.operationContext.signal.aborted?p("RUNTIME_DESTROYED","小程序 Runtime 已终止"):x instanceof ge?p("REQUEST_UNSUPPORTED",x.message):x instanceof $r?p("INVALID_RESPONSE","授权接口响应不合法"):x instanceof nr?p("REQUEST_FAILED","授权请求失败"):x instanceof Wr?u&&(x.status===403||x.status===429)?p("RATE_LIMITED","授权请求已被网关限流,请稍后重试",{status:x.status,...x.retryAfterMs===void 0?{}:{retryAfterMs:x.retryAfterMs}}):p("REQUEST_FAILED",x.message):Xo(x)?x:p("REQUEST_FAILED","授权请求失败")}}async function w(A,L){await O(_m,{runtimeContext:{miniProgramId:A,...await f()},challenge:L}).catch(()=>{})}function S(A){const L=async()=>{const x=Ca(e.operationContext.signal);a=x;try{return await A(x.signal)}finally{a===x&&(a=void 0),x.abort()}},k=s.then(L,L);return s=k.then(()=>{},()=>{}),k}async function v(A,L,k,x,H){if(!k)throw await w(A,L.challenge),p("USER_GESTURE_REQUIRED","展示授权确认需要用户手势");if(!e.authPresentation)throw await w(A,L.challenge),p("AUTHORIZATION_PRESENTATION_UNAVAILABLE","授权确认界面不可用");return S(async F=>{await _(x,H);const V=await C(A,L.displayedScopes,F);await _(x,H);let q;try{q=await e.authPresentation.confirmAuthorization({miniProgramId:A,scopes:L.displayedScopes,...V,signal:F})}catch(K){throw e.operationContext.signal.aborted?p("RUNTIME_DESTROYED","小程序 Runtime 已终止"):(await _(x,H),await w(A,L.challenge),eo("REQUEST_FAILED","授权确认界面执行失败",K))}if(await _(x,H),q.status!=="granted")throw await w(A,L.challenge),p("AUTHORIZATION_CANCELLED","用户取消授权");const J=$m(q.grantedScopes,L.displayedScopes,c);if(!J.includes("identity"))throw await w(A,L.challenge),p("AUTHORIZATION_CANCELLED","用户拒绝授权");return J})}async function C(A,L,k){const x=Ca(k),H=setTimeout(()=>x.abort(),qm);try{const F=Km(e.miniProgramPresentation),[V,q]=await Promise.all([F?Promise.resolve(F):E(A,x.signal),L.includes("profile")?D(x.signal):Promise.resolve(void 0)]);return{...V?{miniProgram:V}:{},...q?{userProfile:q}:{}}}finally{clearTimeout(H),x.abort()}}async function E(A,L){try{const k=e.identity.get()?.version?.trim(),x=await O(Dm,{mini_program_id:A,...k?{miniprogram_version:k}:{}},L),H=zt(x,"小程序公开资料"),F=Qt(H.name),V=Qt(H.icon_url);return F||V?{...F?{name:F}:{},...V?{avatarUrl:V}:{}}:void 0}catch{return}}async function D(A){try{const L=await O(wu,void 0,A),k=zt(L,"账号基础信息"),x=Qt(k.display_username),H=Qt(k.display_avatar);return x||H?{...x?{nickname:x}:{},...H?{avatar:H}:{}}:void 0}catch{return}}async function M(A,L){if(Rm(d,"auth.login"),!c&&A.includes(js))throw p("INVALID_PARAMS","auth.login 参数不合法");const k=I(),x=await U(L),H=i,F=await O(Om,{runtimeContext:{miniProgramId:k,...await f()},scopes:A});await _(x,H);const V=zt(F,"小程序登录"),q=Ra(V,"loginCode"),J=Ra(V,"consentChallenge");if(q===J)throw p("INVALID_RESPONSE","小程序登录 begin 必须返回 exact oneof");let K;if(q)K=La(V.loginCode,c);else{const Y=Ym(V.consentChallenge,c),re=await v(k,Y,L,x,H);await _(x,H);const Me=await O(vm,{runtimeContext:{miniProgramId:k,...await f()},challenge:Y.challenge,selectedScopes:re});if(await _(x,H),K=La(zt(Me,"小程序登录确认"),c),K.scopes.some(le=>!re.includes(le)))throw p("INVALID_RESPONSE","小程序登录确认返回了未选择的 scope")}n.clear();for(const Y of K.scopes)n.add(Y);r.invalidate();const Z=e.account.getAccountKey?await P(x,H,k):void 0;return g("heybox_app_login_change",{isHeyboxAppLoggedIn:!0,...Z===void 0?{}:{accountKey:Z}}),g("user_info_authorization_change",to(n,c)),{...K,...Z===void 0?{}:{accountKey:Z}}}async function R(A,L){const k=i,x=await O(Tm,{runtimeContext:{miniProgramId:L,...await f()}});await _(A,k);const H=Wm(zt(x,"用户本地身份"),c);for(const F of c?rr:Du)n.add(F);return g("user_info_authorization_change",to(n,c)),H}function T(A){y();const L=I(),k=`${A}\0${L}\0${i}\0${c}`;return r.read(k,()=>R(A,L))}async function N(A){if(!A)throw p("USER_GESTURE_REQUIRED","撤销授权需要用户手势");const L=I(),k=i,x=await b();if(!x)throw p("HEYBOX_APP_LOGIN_REQUIRED","请先登录小黑盒");const H=await O(bm,{runtimeContext:{miniProgramId:L,...await f()}});await _(x,k),zt(H,"用户授权撤销"),h(),g("user_info_authorization_change",{identity:"denied",profile:"denied",...c?{steam_account:"denied"}:{}})}return{getAccountState:j,login:M,async confirmGameSaves(A){if(!A)throw p("USER_GESTURE_REQUIRED","读取游戏存档需要点击按钮授权");if(!e.authPresentation)throw p("AUTHORIZATION_PRESENTATION_UNAVAILABLE","授权确认界面不可用");const L=I(),k=await U(A),x=i;await S(async H=>{await _(k,x);const F=await C(L,["identity"],H),V=await e.authPresentation.confirmAuthorization({miniProgramId:L,scopes:["identity","game_saves"],...F,signal:H});if(await _(k,x),V.status!=="granted"||!V.grantedScopes.includes("game_saves")||!V.grantedScopes.includes("identity"))throw p("AUTHORIZATION_CANCELLED","用户取消存档授权")})},getOrCreateLocalIdentity:T,invalidateLocalIdentity(){r.invalidate()},getAuthorization:()=>to(n,c),revoke:N,onEvent(A){return t.add(A),()=>t.delete(A)},dispose(){o||(o=!0,h(),r.dispose(),m(),t.clear())}}}function eo(e,t,r){const n=p(e,t);return Object.defineProperty(n,"cause",{configurable:!0,enumerable:!1,value:r}),n}function zt(e,t){if(!Q(e))throw p("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":Vm.has(r)?r:"REQUEST_FAILED";throw p(n,r)}if(!Q(e.result))throw p("INVALID_RESPONSE",`${t} result 必须是对象`);return e.result}function La(e,t){if(!Q(e))throw p("INVALID_RESPONSE","login code 必须是对象");const r=yi(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 p("INVALID_RESPONSE","login code 响应不合法");return{code:e.code,expiresIn:Number(e.expiresIn),scopes:r}}function Ym(e,t){if(!Q(e))throw p("INVALID_RESPONSE","授权 challenge 必须是对象");const r=yi(e.requestedScopes,"challenge requestedScopes",t),n=yi(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 p("INVALID_RESPONSE","授权 challenge 响应不合法");return{challenge:e.challenge.trim(),requestedScopes:r,displayedScopes:n}}function Wm(e,t){if(!Q(e)||typeof e.appUserId!="string"||!e.appUserId.trim())throw p("INVALID_RESPONSE","本地身份 appUserId 必须是非空字符串");const r=e.appUserId.trim();if(!t)return{appUserId:r};if(e.steamId!==void 0&&typeof e.steamId!="string")throw p("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 $m(e,t,r){const n=yi(e,"授权选择 scopes",r);if(n.some(i=>!t.includes(i)))throw p("INVALID_RESPONSE","授权选择包含未展示的 scope");return n}function Qt(e){return typeof e=="string"&&e.trim()?e.trim():void 0}function Km(e){const t=Qt(e?.name),r=Qt(e?.avatarUrl);return t||r?{...t?{name:t}:{},...r?{avatarUrl:r}:{}}:void 0}function Ca(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 Zm(e,t){return t.aborted?Promise.reject(Jo()):new Promise((r,n)=>{let i=!1;const o=a=>{i||(i=!0,t.removeEventListener("abort",s),a())},s=()=>o(()=>n(Jo()));t.addEventListener("abort",s,{once:!0}),e.then(a=>o(()=>r(a)),a=>o(()=>n(a)))})}function Jo(){const e=new Error("The operation was aborted");return e.name="AbortError",e}function yi(e,t,r){const n=r?Gm:Du;if(!Array.isArray(e)||e.some(i=>typeof i!="string"||!n.has(i))||new Set(e).size!==e.length)throw p("INVALID_RESPONSE",`${t} 不合法`);return[...e]}function to(e,t){const r=t?rr:rr.filter(n=>n!==js);return Object.fromEntries(r.map(n=>[n,e.has(n)?"granted":"not_requested"]))}function Ra(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function Jm(e){return Q(e)?Object.values(e).some(t=>t==="denied"):!1}function Xo(e){return Q(e)&&typeof e.code=="string"&&typeof e.message=="string"}function Pa(e,t,r){return t.aborted?p("RUNTIME_DESTROYED","小程序 Runtime 已终止"):Xo(e)?e:p("REQUEST_FAILED",r)}const Xm=new Set(rr);function eg(e){return{[Un]:async t=>{if(t!==void 0)throw p("INVALID_PARAMS","auth.getAccountState 不接受参数");return e.authorization.getAccountState()},[jn]:async(t,r)=>e.authorization.login(tg(t),r.trustedUserGesture)}}function tg(e){if(e===void 0)return["identity"];if(!Q(e)||Object.keys(e).some(t=>t!=="scopes"))throw ka();if(e.scopes===void 0)return["identity"];if(!Array.isArray(e.scopes)||e.scopes.some(t=>typeof t!="string"||!Xm.has(t))||new Set(e.scopes).size!==e.scopes.length)throw ka();return[...e.scopes]}function ka(){return p("INVALID_PARAMS","auth.login 参数不合法")}const rg={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 de(e,"排行榜记录删除接口响应异常")}},ng={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 de(e,"当前排行榜记录接口响应异常")}},ig={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 de(e,"排行榜信息接口响应异常")}},og={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 de(e,"排行榜列表接口响应异常")}},sg={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 de(e,"排行榜提交接口响应异常")}},ag={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 zs(e,t,r){e.assertUsable();const n={request:async(i,o)=>(e.assertUsable(),e.network.request(i,o))};try{return await $(()=>Fi(n,t,r,{...e.operationContext,credentials:"heybox-session",...e.gate?{gate:e.gate}:{}}),e.operationContext.signal)}catch(i){if(Ii(i)||Dr(i,"REQUEST_UNSUPPORTED")||Dr(i,"RATE_LIMITED")||Dr(i,"RATE_LIMITED_BY_RUNTIME"))throw i;if(i instanceof ge)throw G("REQUEST_UNSUPPORTED",`当前 Host 不支持该${e.subject}请求`);if(i instanceof nr&&Dr(i.cause,"INVALID_STATE"))throw i.cause;if(i instanceof Wr){if(e.requestPolicyEnabled!==!1&&(i.status===403||i.status===429))throw G("RATE_LIMITED",`${e.subject}请求已被网关限流,请稍后重试`,{status:i.status,...i.retryAfterMs===void 0?{}:{retryAfterMs:i.retryAfterMs}});if(i.status===401||i.status===403)throw G("UNAUTHORIZED","当前用户未登录");const o=cg(i.responseData);if(ne(o)&&typeof o.status=="string"&&o.status!=="ok"){const s=ne(o.result)?Je(o.result.error_code):void 0;if(o.status==="login"||o.status==="relogin"||Ei(o.result)||Ei(o)||s&&/^[A-Z][A-Z0-9_]+$/.test(s))throw Mu(o,e.subject)}throw G("HTTP_ERROR",`${e.subject}请求失败(HTTP ${i.status})`,{status:i.status})}throw i instanceof nr?wi(e.subject):i instanceof $r?oe(i.cause instanceof Error?i.cause.message:`${e.subject}响应不合法`):oe(i instanceof Error?i.message:`${e.subject}响应不合法`)}}function We(e,t,r){if(!ne(e)||typeof e.status!="string")throw oe(`${t} 响应必须是标准信封`);if(e.status!=="ok")throw Mu(e,r);if(!Object.prototype.hasOwnProperty.call(e,"result")||e.result===void 0||e.result===null)throw oe(`${t} 响应缺少 result`);return e.result}function Hs(e,t){try{return e.onChange(t)}catch(r){if(Dr(r,Jd))return()=>{};throw r}}function Mu(e,t){if(e.status==="login"||e.status==="relogin")throw G("UNAUTHORIZED",Je(e.msg)||"当前用户未登录");if(ne(e.result)){const i=Je(e.result.error_code);if(i&&/^[A-Z][A-Z0-9_]+$/.test(i))throw G(i,Je(e.result.message)||Je(e.msg)||`${t}请求失败`)}const r=Ei(e.result)??Ei(e),n=Je(r?.user_message)||Je(e.msg)||Je(r?.developer_message)||`${t}请求失败`;throw r?G(dg(r),n,{status:e.status,sbe:r}):G("HEYBOX_API_ERROR",n,{status:e.status})}function cg(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return}}function Ei(e){return ne(e)&&ne(e.sbe)?e.sbe:void 0}function dg(e){const t=Je(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 ag[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 ne(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Je(e){return typeof e=="string"&&e.trim()?e.trim():void 0}function Dr(e,t){return ne(e)&&e.code===t}function G(e,t,r){return r===void 0?{code:e,message:t}:{code:e,message:t,data:r}}function oe(e){return G("INVALID_RESPONSE",e)}function wi(e){return G("REQUEST_FAILED",`${e}请求失败`)}function Ii(e){return e instanceof Error&&e.name==="AbortError"}const ug="default",pt="排行榜",lg=/^[A-Za-z0-9_-]{1,64}$/,fg=300*1e3,hg=250,mg=3;class gg{constructor(t){this.options=t,this.requestGateContext=t.requestGate?{capability:"cloud",gate:t.requestGate}:void 0,this.unsubscribeAccountChange=Hs(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(sg,{miniProgramId:n,...t});this.assertAccountGeneration(r);const o=We(i,Xe,pt);return this.invalidateMutableReads(this.createBucketKey(n,t.key)),ro(o,Xe)}getList(t){this.assertUsable();const r=this.readMiniProgramId(),n=this.createBucketKey(r,t.key),i=Er("list",t.limit,t.cursor??null);return this.read(n,"list",i,async()=>{const o=await this.request(og,{miniProgramId:r,...t}),s=We(o,xe,pt);if(!ne(s)||!Array.isArray(s.entries)||typeof s.has_more!="boolean")throw oe(`${xe} 返回值不合法`);if(s.cursor!==void 0&&s.cursor!==null&&typeof s.cursor!="string")throw oe(`${xe} 返回的 cursor 必须是字符串`);return{entries:s.entries.map(a=>ro(a,xe)),...typeof s.cursor=="string"&&s.cursor?{cursor:s.cursor}:{},hasMore:s.has_more}})}async getCurrentUserEntry(t){this.assertUsable();const r=this.accountGeneration,n=this.readMiniProgramId(),i=await this.requireCurrentUser(r),o=this.createBucketKey(n,t.key),s=Er("current",i);return this.read(o,"current",s,async()=>{const a=await this.request(ng,{miniProgramId:n,...t}),c=We(a,at,pt);if(!ne(c))throw oe(`${at} 返回值必须是对象`);return c.entry===void 0||c.entry===null?void 0:ro(c.entry,at)})}async deleteCurrentUserEntry(t){this.assertUsable();const r=this.accountGeneration,n=this.readMiniProgramId();await this.requireCurrentUser(r);const i=await this.request(rg,{miniProgramId:n,...t});this.assertAccountGeneration(r);const o=We(i,bt,pt);if(this.invalidateMutableReads(this.createBucketKey(n,t.key)),!ne(o)||typeof o.deleted!="boolean")throw oe(`${bt} 返回的 deleted 必须是布尔值`);return{deleted:o.deleted}}getInfo(t){this.assertUsable();const r=this.readMiniProgramId(),n=this.createBucketKey(r,t.key);return this.read(n,"info",Er("info"),async()=>{const i=await this.request(ig,{miniProgramId:r,...t}),o=We(i,Ye,pt);if(!ne(o)||typeof o.key!="string"||!lg.test(o.key))throw oe(`${Ye} 返回的 key 不合法`);if(t.key!==void 0&&o.key!==t.key)throw oe(`${Ye} 返回的 key 与请求不一致`);if(o.order!=="asc"&&o.order!=="desc")throw oe(`${Ye} 返回的 order 必须是 asc 或 desc`);if(typeof o.rank_limit!="number"||!Number.isInteger(o.rank_limit)||o.rank_limit<0)throw oe(`${Ye} 返回的 rankLimit 必须是非负整数`);return{key:o.key,order:o.order,rankLimit:o.rank_limit}})}read(t,r,n,i){this.assertUsable();const o=this.getOrCreateBucket(t),s=o?.caches[r],a=s?.get(n);if(a&&a.expiresAt>Date.now())return Promise.resolve(a.value);s?.delete(n);const c=Er(t,n),d=this.inflight.get(c);if(d)return d.promise;const u=this.accountGeneration,l=o?.generation,f=i().then(m=>(this.assertAccountGeneration(u),o&&s&&o.generation===l&&(r==="list"?s.size>=hg&&s.delete(s.keys().next().value):s.clear(),s.set(n,{expiresAt:Date.now()+fg,value:m})),m)).finally(()=>{this.inflight.get(c)?.promise===f&&this.inflight.delete(c),o&&this.removeEmptyBucket(t,o)});return this.inflight.set(c,{bucketKey:t,promise:f}),f}getOrCreateBucket(t){const r=this.buckets.get(t);if(r)return r;if(this.pruneExpiredBuckets(),this.buckets.size>=mg)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)xa(n,t),this.isBucketEmpty(r,n)&&this.buckets.delete(r)}removeEmptyBucket(t,r){xa(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 $(()=>this.options.account.getCurrentUserId(this.options.operationContext),this.options.operationContext.signal)}catch(n){throw Ii(n)?n:wi(pt)}if(this.assertAccountGeneration(t),typeof r!="string"||!r.trim())throw G("UNAUTHORIZED","当前用户未登录");return r.trim()}readMiniProgramId(){const t=this.options.identity.get()?.miniProgramId.trim();if(!t)throw G("INVALID_STATE","canonical mini-program identity 尚未绑定");return t}createBucketKey(t,r){return Er(t,r??ug)}assertAccountGeneration(t){if(this.assertUsable(),t!==this.accountGeneration)throw G("UNAUTHORIZED","登录状态已变化,请重试")}request(t,r){return zs({network:this.options.network,operationContext:this.options.operationContext,...this.requestGateContext?{gate:this.requestGateContext}:{},...this.options.requestPolicyEnabled===void 0?{}:{requestPolicyEnabled:this.options.requestPolicyEnabled},subject:pt,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(X(this.options.operationContext.signal),this.disposed)throw G("INVALID_STATE","Cloud capability 已释放")}}function pg(e){return new gg(e)}function ro(e,t){if(!ne(e))throw oe(`${t} 返回的 entry 必须是对象`);if(typeof e.ranked!="boolean")throw oe(`${t} 返回的 ranked 必须是布尔值`);if(typeof e.rank!="number"||!Number.isInteger(e.rank)||(e.ranked?e.rank<=0:e.rank!==0))throw oe(`${t} 返回的 rank/ranked 不合法`);if(typeof e.app_user_id!="string"||!e.app_user_id.trim())throw oe(`${t} 返回的 appUserId 必须是非空字符串`);if(typeof e.score!="number"||!Number.isFinite(e.score))throw oe(`${t} 返回的 score 必须是有限数字`);if(!ne(e.extra))throw oe(`${t} 返回的 extra 必须是对象`);if(typeof e.created_at!="number"||!Number.isFinite(e.created_at)||typeof e.updated_at!="number"||!Number.isFinite(e.updated_at))throw oe(`${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 xa(e,t){for(const r of Object.values(e.caches))for(const[n,i]of r)i.expiresAt<=t&&r.delete(n)}function Er(...e){return JSON.stringify(e)}const yg={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 de(e,"云端存储删除接口响应异常")}},Ua={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 de(e,"云端存储读取接口响应异常")}},ja={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 de(e,"云端存储 key 列表接口响应异常")}},Eg={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 de(e,"云端存储写入接口响应异常")}},yt="云端存储",wg=3e4,Ig=128,Ag=500;class Ng{constructor(t){this.options=t,this.requestGateContext=t.requestGate?{capability:"cloud.storage",gate:t.requestGate}:void 0,this.unsubscribeAccountChange=Hs(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(s=>s.key===t).at(-1);if(n)return n.kind==="set"?n.value:void 0;const i=this.keyGenerations.get(t)??0,o=await this.readStored(t,r,!1);return this.assertAccountGeneration(r),(this.keyGenerations.get(t)??0)!==i?this.getItem(t):(this.blockedKeys.delete(t),o.found?o.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=We(await this.request(ja,{}),Tt,yt);if(this.assertAccountGeneration(t),!ne(r)||r.keys!==void 0&&(!Array.isArray(r.keys)||!r.keys.every(i=>typeof i=="string")))throw oe("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((o,s)=>{const a=this.queues.get(r)??[],c=a.at(-1);if(t==="set"&&c?.kind==="set"&&c.generation===this.accountGeneration&&c.readyAt>Date.now())c.value=n,c.waiters.push({resolve:o,reject:s});else{const d={kind:t,key:r,value:n,generation:this.accountGeneration,readyAt:Date.now()+(t==="set"?Ag:0),waiters:[{resolve:o,reject:s}]};a.push(d),this.unfinished.add(d)}this.queues.set(r,a),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=We(await this.request(yg,{key:t}),er,yt);if(this.assertAccountGeneration(r.generation),!ne(i)||i.deleted!==void 0&&typeof i.deleted!="boolean")throw oe("删除结果不合法");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 oe("云存储版本超出安全整数范围");const o=We(await this.request(Eg,{key:t,value:r.value,expectedVersion:i.version,expectedRevision:i.revision}),Xt,yt);if(this.assertAccountGeneration(r.generation),!ne(o)||o.success!==!0)throw oe("云存储写入结果不合法");const s=za({...o,found:!0,value:r.value});if(s.version!==i.version+1||i.found&&s.revision!==i.revision)throw oe("写入版本凭证不匹配");this.writeCache(t,s)}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 o of this.queues.get(t)??[])this.finish(o,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 o=this.inflight.get(t);if(o)return o;const s=this.keyGenerations.get(t)??0,a=this.request(Ua,{key:t}).then(c=>{this.assertAccountGeneration(r);const d=za(We(c,Jt,yt));return(this.keyGenerations.get(t)??0)===s&&this.writeCache(t,d),d}).finally(()=>{this.inflight.get(t)===a&&this.inflight.delete(t)});return this.inflight.set(t,a),a}writeCache(t,r){this.cache.delete(t),this.cache.size>=Ig&&this.cache.delete(this.cache.keys().next().value),this.cache.set(t,{expiresAt:Date.now()+wg,value:r})}invalidateRead(t){this.keyGenerations.set(t,(this.keyGenerations.get(t)??0)+1),this.inflight.delete(t),this.options.requestGate?.invalidateCoalescing([Ua.id,ja.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(G("INVALID_STATE","Cloud capability 已释放")))}invalidateForAccountChange(){this.purge(G("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 $(()=>this.options.account.getCurrentUserId(this.options.operationContext),this.options.operationContext.signal)}catch(o){throw Ii(o)?o:wi(yt)}if(this.assertAccountGeneration(t),this.hasAccountObservation&&(n?.trim()||void 0)!==this.observedUserId)throw this.invalidateForAccountChange(),G("UNAUTHORIZED","登录状态已变化,请重试");const i=JSON.stringify([r,n]);if(this.boundScope!==void 0&&this.boundScope!==i)throw this.invalidateForAccountChange(),G("UNAUTHORIZED","登录状态已变化,请重试");if(typeof n!="string"||!n.trim())throw G("UNAUTHORIZED","当前用户未登录");return this.boundScope=i,this.boundUserId=n.trim(),n}readMiniProgramId(){const t=this.options.identity.get()?.miniProgramId.trim();if(!t)throw G("INVALID_STATE","canonical mini-program identity 尚未绑定");return t}assertAccountGeneration(t){if(this.assertUsable(),t!==this.accountGeneration)throw G("UNAUTHORIZED","登录状态已变化,请重试")}async request(t,r){const n=this.accountGeneration;if(this.assertUsable(),!this.options.authorizationContext)throw G("METHOD_FORBIDDEN","云端存储缺少受信运行上下文");let i;try{i=await $(()=>this.options.authorizationContext.get(this.options.operationContext),this.options.operationContext.signal)}catch(s){throw Ii(s)?s:wi(yt)}this.assertAccountGeneration(n);const o=i.token.trim();if(!o||i.expiresAt<=Date.now())throw G("UNAUTHORIZED","小程序运行上下文无效,请重新打开");return zs({network:this.options.network,operationContext:this.options.operationContext,...this.requestGateContext?{gate:this.requestGateContext}:{},...this.options.requestPolicyEnabled===void 0?{}:{requestPolicyEnabled:this.options.requestPolicyEnabled},subject:yt,assertUsable:()=>this.assertAccountGeneration(n)},t,{...r,runtimeAuthContextToken:o})}assertUsable(){if(X(this.options.operationContext.signal),this.disposed)throw G("INVALID_STATE","Cloud capability 已释放")}}function Dg(e){return new Ng(e)}function za(e){if(!ne(e))throw oe("云存储读取结果必须是对象");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 oe("云存储读取结果不合法");if(t&&(n===0||!/^[0-9a-f]{24}$/.test(i)||/^0+$/.test(i)))throw oe("云存储版本凭证不合法");return t?{value:r,found:t,version:n,revision:i}:{value:"",found:!1,version:0,revision:""}}const Mg=/^[A-Za-z0-9_-]{1,64}$/,Ha=20,Sg=100,Fa=2048,_g=/^[A-Za-z0-9_-]{1,128}$/,Ba=16*1024;function bg(e){const t=pg(e),r=Dg(e);return{handlers:{[Xe]:async i=>t.submit(Tg(i)),[xe]:async i=>t.getList(Og(i)),[at]:async i=>t.getCurrentUserEntry(no(i,at)),[bt]:async i=>t.deleteCurrentUserEntry(no(i,bt)),[Ye]:async i=>t.getInfo(no(i,Ye)),[Jt]:async i=>r.getItem(Va(i,Jt)),[Xt]:async i=>{const{key:o,value:s}=vg(i);return r.setItem(o,s)},[er]:async i=>r.removeItem(Va(i,er)),[Tt]:async i=>(Cg(i),r.getKeys())},dispose:()=>{t.dispose(),r.dispose()}}}function Tg(e){const t=hr(e,Xe,!1);if(mr(t,["key","score","extra"],Xe),typeof t.score!="number"||!Number.isFinite(t.score)||Math.abs(t.score)>Number.MAX_SAFE_INTEGER)throw Se("INVALID_PARAMS","cloud.leaderboard.submit score 必须是有限安全数字");return{...Fs(t.key,Xe),score:t.score,...t.extra===void 0?{}:{extra:Rg(t.extra)}}}function Og(e){if(e===void 0)return{limit:Ha};const t=hr(e,xe,!0);mr(t,["key","limit","cursor"],xe);const r=t.limit===void 0?Ha:t.limit;if(typeof r!="number"||!Number.isInteger(r)||r<=0||r>Sg)throw Se("INVALID_PARAMS","cloud.leaderboard.getList limit 必须是 1-100 的整数");if(t.cursor!==void 0&&typeof t.cursor!="string")throw Se("INVALID_PARAMS","cloud.leaderboard.getList cursor 必须是字符串");return{...Fs(t.key,xe),limit:r,...t.cursor===void 0?{}:{cursor:t.cursor}}}function no(e,t){if(e===void 0)return{};const r=hr(e,t,!0);return mr(r,["key"],t),Fs(r.key,t)}function Va(e,t){const r=hr(e,t,!1);return mr(r,["key"],t),Su(r.key,t)}function vg(e){const t=Xt,r=hr(e,t,!1);mr(r,["key","value"],t);const n=Su(r.key,t);if(typeof r.value!="string")throw Se("INVALID_PARAMS",`${t} value 必须是字符串`);if(Lg(r.value))throw Se("INVALID_PARAMS",`${t} value 不能包含不成对的代理字符`);if(new TextEncoder().encode(r.value).length>Ba)throw Se("INVALID_PARAMS",`${t} value 不能超过 ${Ba} 字节`);return{key:n,value:r.value}}function Lg(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 Cg(e){const t=hr(e,Tt,!0);mr(t,[],Tt)}function Su(e,t){if(typeof e!="string"||!_g.test(e))throw Se("INVALID_PARAMS",`${t} key 仅支持 1–128 位英文字母、数字、下划线和连字符`);return e}function hr(e,t,r){if(e===void 0&&r)return{};if(!_u(e))throw Se("INVALID_PARAMS",`${t} 参数必须是对象`);return e}function mr(e,t,r){const n=Object.keys(e).find(i=>!t.includes(i));if(n)throw Se("INVALID_PARAMS",`${r} 不支持参数 ${n}`)}function Fs(e,t){if(e===void 0)return{};if(typeof e!="string"||!Mg.test(e))throw Se("INVALID_PARAMS",`${t} key 仅支持 1-64 位字母、数字、下划线和连字符`);return{key:e}}function Rg(e){if(!_u(e))throw Se("INVALID_PARAMS","cloud.leaderboard.submit extra 必须是对象");let t;try{t=JSON.stringify(e)}catch{throw Se("INVALID_PARAMS","cloud.leaderboard.submit extra 必须可序列化")}if(typeof t!="string")throw Se("INVALID_PARAMS","cloud.leaderboard.submit extra 必须可序列化");if(new TextEncoder().encode(t).length>Fa)throw Se("INVALID_PARAMS",`cloud.leaderboard.submit extra 不能超过 ${Fa} 字节`);return e}function _u(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Se(e,t){return{code:e,message:t}}const Pg={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 de(e,"游戏存档接口响应异常")}};function es(){const e=globalThis.crypto;if(!e||typeof e.getRandomValues!="function")throw p("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 p("FILE_IO_FAILED","无法生成安全文件标识")}}function bu(e,t,r={}){const n=t==="readwrite"&&e.mode==="readwrite"?"readwrite":"read",i=n==="readwrite",o=r.allowRemove!==!1&&typeof e.remove=="function";return Object.freeze({kind:"file",name:e.name,mode:n,create:i?(s,a)=>e.create(s,a):ts,remove:o?s=>e.remove(s):Ou,read:s=>e.read(s),...typeof e.readPrefix=="function"?{readPrefix:(s,a)=>e.readPrefix(s,a)}:{},write:i?(s,a)=>e.write(s,a):ts,stat:s=>e.stat(s)})}function Tu(e,t,r={}){const n=t==="readwrite"&&e.mode==="readwrite"?"readwrite":"read",i=n==="readwrite",o=r.allowRemove!==!1,s=o&&typeof e.remove=="function";return Object.freeze({kind:"directory",name:e.name,mode:n,file:a=>bu(e.file(a),n,{allowRemove:o}),directory:a=>Tu(e.directory(a),n,{allowRemove:o}),create:i?(a,c)=>e.create(a,c):ts,remove:s?(a,c)=>e.remove(a,c):Ou,stat:a=>e.stat(a),list:(a,c)=>e.list(a,c)})}function ts(){return Promise.reject(p("FILE_ACCESS_DENIED","当前文件授权只允许读取"))}function Ou(){return Promise.reject(p("FILE_ACCESS_DENIED","外部文件授权不允许删除"))}const kg=new Set(["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"]),xg={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 ir(e){const t=Bs(e),r=t&&kg.has(t)?p(t,xg[t]??"文件操作失败"):p("FILE_IO_FAILED","文件操作失败");return Object.defineProperty(r,"cause",{value:e,enumerable:!1}),r}function Ze(e){try{return e()}catch(t){throw ir(t)}}function Bs(e){try{if(!Q(e))return;const t=Object.getOwnPropertyDescriptor(e,"code");return t&&"value"in t&&typeof t.value=="string"?t.value:void 0}catch{return}}const Ga=1024;class Vs{constructor(t,r){this.files=t,this.miniProgramDetail=r}handles=new Map;disposed=!1;createTransferScope(){return this.assertCanonicalDetail(),new Vs(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),[o]=this.registerMany([i]);return dn(i.handle,{kind:"file",handleId:o})}registerFiles(t,r="external",n,i){this.assertCanonicalDetail();const o=Ze(()=>{if(!Array.isArray(t))throw p("FILE_IO_FAILED","Host 返回了无效文件选择结果");const a=t.length;if(i!==void 0&&a>i)throw p("FILE_IO_FAILED","Host 返回了过多文件选择结果");if(this.handles.size+a>Ga)throw p("FILE_QUOTA_EXCEEDED","当前会话的文件授权句柄已达上限");const c=[];for(let d=0;d<a;d+=1){if(!Object.prototype.hasOwnProperty.call(t,d))throw p("FILE_IO_FAILED","Host 返回了稀疏文件选择结果");c.push(this.prepareFile(t[d],r,n))}return c}),s=this.registerMany(o);return o.map((a,c)=>dn(a.handle,{kind:"file",handleId:s[c]}))}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),[o]=this.registerMany([i]);return Qa(i.handle,{kind:"directory",handleId:o})}resolveFile(t){return this.resolveFileEntry(t).handle}resolveDirectory(t){return this.resolveDirectoryEntry(t).handle}isCompanionAttachmentRef(t){return!tr(t)||!("handleId"in t)?!1:this.handles.get(t.handleId)?.origin==="companion-attachment"}isGameSaveRef(t){return!tr(t)||!("handleId"in t)?!1:this.handles.get(t.handleId)?.origin==="game-save"}resolveFileEntry(t){this.assertCanonicalDetail();const r=jg(t);if("handleId"in r){const s=this.readDirect(r.handleId,"file");return{ref:r,...s}}const n=this.resolveRoot(r.root),i=Fr(r.relativePath);io(n.origin,i);const o=this.prepareFile(Ze(()=>n.hostHandle.file(i)),n.origin,n.handle.mode);return{ref:r,...o}}resolveDirectoryEntry(t){this.assertCanonicalDetail();const r=zg(t);if("handleId"in r){const s=this.readDirect(r.handleId,"directory");return{ref:r,...s}}const n=this.resolveRoot(r.root),i=r.relativePath==="."?".":Fr(r.relativePath);io(n.origin,i);const o=this.prepareDirectory(i==="."?n.hostHandle:Ze(()=>n.hostHandle.directory(i)),n.origin,n.handle.mode,!0);return{ref:r,...o}}describeFile(t,r){return Wa(t),dn(t,r)}describeListedEntries(t,r,n){return this.assertCanonicalDetail(),Ze(()=>{if(!Array.isArray(r))throw p("FILE_IO_FAILED","Host 返回了无效目录列表");const i=r.length;if(i>n)throw p("DIRECTORY_LIST_LIMIT_EXCEEDED","目录项数量超过限制");const o=[];for(let s=0;s<i;s+=1){if(!Object.prototype.hasOwnProperty.call(r,s))throw p("FILE_IO_FAILED","Host 返回了稀疏目录列表");const a=r[s];t.origin==="sandbox"&&Q(a)&&typeof a.name=="string"&&vu(a.name)||o.push(this.describeListedEntry(t,a))}return this.assertCanonicalDetail(),o})}describeListedEntry(t,r){return Ze(()=>{if(Q(r)&&r.kind==="file"){const n=this.prepareFile(r,t.origin,t.handle.mode);return dn(n.handle,qa(t.ref,n.handle.name))}if(Q(r)&&r.kind==="directory"){const n=this.prepareDirectory(r,t.origin,t.handle.mode);return Qa(n.handle,Ug(t.ref,n.handle.name))}throw p("FILE_IO_FAILED","Host 返回了无效目录项")})}deriveFile(t,r){this.assertCanonicalDetail();const n=Kr(r);io(t.origin,n);const i=this.prepareFile(Ze(()=>t.hostHandle.file(n)),t.origin,t.handle.mode);return{ref:qa(t.ref,n),...i}}assertSandboxOrigin(t){if(t.origin!=="sandbox")throw p("FILE_ACCESS_DENIED","外部文件授权不允许删除")}prepareFile(t,r,n){return Ze(()=>{Wa(t);const i=n??t.mode;return Ya(t.mode,i),{handle:bu(t,i,{allowRemove:r==="sandbox"}),hostHandle:t,origin:r}})}prepareDirectory(t,r,n,i=!1){return Ze(()=>{Fg(t,i);const o=n??t.mode;return Ya(t.mode,o),{handle:Tu(t,o,{allowRemove:r==="sandbox"}),hostHandle:t,origin:r}})}registerMany(t){if(this.assertCanonicalDetail(),this.handles.size+t.length>Ga)throw p("FILE_QUOTA_EXCEEDED","当前会话的文件授权句柄已达上限");const r=new Set,n=t.map(()=>{for(let i=0;i<8;i+=1){const o=es();if(!this.handles.has(o)&&!r.has(o))return r.add(o),o}throw p("FILE_IO_FAILED","无法创建文件授权句柄")});return t.forEach((i,o)=>this.handles.set(n[o],i)),n}readDirect(t,r){if(!Hg(t))throw p("FILE_ACCESS_REVOKED","文件授权句柄无效");const n=this.handles.get(t);if(!n)throw p("FILE_ACCESS_REVOKED","文件授权已失效");if(n.handle.kind!==r||n.hostHandle.kind!==r)throw p("FILE_TYPE_MISMATCH","文件句柄类型不匹配");return n}resolveRoot(t){if(this.assertCanonicalDetail(),t.kind==="sandbox"){if(!this.files)throw Ce("files.sandbox");return this.prepareDirectory(Ze(()=>this.files.sandbox),"sandbox",void 0,!0)}return this.readDirect(t.handleId,"directory")}assertCanonicalDetail(){if(this.disposed)throw p("FILE_ACCESS_REVOKED","文件授权已失效");if(!this.miniProgramDetail?.miniProgramId.trim())throw Ce("files")}}function Fr(e){if(!Rs(e))throw p("INVALID_PARAMS","relativePath 不是规范逻辑路径");return e}function io(e,t){if(e==="sandbox"&&vu(t))throw p("FILE_ACCESS_DENIED","Runtime 私有缓存不能通过沙箱路径访问")}function vu(e){return e.split("/").some(t=>t.replace(/[. ]+$/,"").toLowerCase()===".hb-game-saves")}function Kr(e,t="文件名"){const r=Fr(e);if(r.includes("/"))throw p("INVALID_PARAMS",`${t} 只能是 basename`);return r}function qa(e,t){return"handleId"in e?{kind:"file",root:{kind:"directory",handleId:e.handleId},relativePath:t}:{kind:"file",root:e.root,relativePath:Fr(e.relativePath==="."?t:`${e.relativePath}/${t}`)}}function Ug(e,t){return"handleId"in e?{kind:"directory",root:{kind:"directory",handleId:e.handleId},relativePath:t}:{kind:"directory",root:e.root,relativePath:Fr(e.relativePath==="."?t:`${e.relativePath}/${t}`)}}function dn(e,t){return{kind:"file",name:e.name,mode:e.mode,ref:t}}function Qa(e,t){return{kind:"directory",name:e.name,mode:e.mode,ref:t}}function Ya(e,t){if(t==="readwrite"&&e!=="readwrite")throw p("FILE_ACCESS_DENIED","Host 未授予请求的文件写权限")}function jg(e){return tr(e)||Lu(),e}function zg(e){return Vd(e)||Lu(),e}function Lu(){throw p("INVALID_PARAMS","文件引用不合法")}function Hg(e){return/^[0-9a-f]{32}$/.test(e)}function Wa(e){if(!Q(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")throw p("FILE_IO_FAILED","Host 返回了无效 File handle");Kr(e.name,"Host File name")}function Fg(e,t=!1){if(!Q(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 p("FILE_IO_FAILED","Host 返回了无效 Directory handle");if(!t&&e.name.length===0)throw p("FILE_IO_FAILED","Host Directory name 不能为空");e.name&&Kr(e.name,"Host Directory name")}const Bg=new Set(["content-length","content-encoding","transfer-encoding","content-disposition","content-range","content-type"]),Vg=new Set(["content-length","content-encoding","content-disposition","content-range","content-type"]),Gg=new Set(["range","if-range","a-im"]),qg=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"]),Qg=/^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\..*)?$/i,un={initial:0,target:1,open:2,validate:3,transfer:4,committed:5,completed:6};class Yg{constructor(t){this.signal=t}phase="initial";transition(t){if(un[t]<=un[this.phase])throw p("FILE_IO_FAILED","下载状态转换不合法");this.phase=t}throwIfCancelled(){if(un[this.phase]<un.committed&&this.signal.aborted)throw Pu()}normalizeHostError(t,r){return this.throwIfCancelled(),qs(t,r,this.signal)}}async function Cu(e,t,r){const n=r.transfer,i=r.fileRegistry;if(!n||!i)throw Ce("network.download");const o=ae(r.operationContext,t.signal),s=new Yg(o.signal);s.transition("target"),s.throwIfCancelled();let a;try{a=await Zg(e,i,o)}catch(u){throw s.normalizeHostError(u,"file")}s.throwIfCancelled();let c;s.transition("open");try{c=await n.network.open(e.request,o)}catch(u){throw s.normalizeHostError(u,"network")}let d=!1;try{s.throwIfCancelled(),s.transition("validate");const u=Xg(c);ep(c,u);const l=tp(c.status,u);if(e.maxBytes!==void 0&&l.expectedBytes!==void 0&&l.expectedBytes>e.maxBytes)throw p("FILE_TOO_LARGE","下载响应超过 maxBytes");s.throwIfCancelled();const f=Jg(e,a,u,i);let m=0;const h=$g(l.expectedBytes,e.maxBytes);so(t,oo(0,l));const g={...o,onProgress(b){!Number.isSafeInteger(b)||b<m||h!==void 0&&b>h||(m=b,so(t,oo(m,l)))}};s.transition("transfer"),d=!0;let I;try{I=await n.files.writeResource(f.hostHandle,c.body,{mode:f.mode,...e.maxBytes===void 0?{}:{maxBytes:e.maxBytes},...l.expectedBytes===void 0?{}:{expectedBytes:l.expectedBytes}},g)}catch(b){throw s.normalizeHostError(b,"transfer")}s.transition("committed"),m=Wg(I,l,m,e.maxBytes),so(t,oo(m,l));const y=i.describeFile(f.handle,f.ref);return s.transition("completed"),y}finally{d||Kg(n.network,c.body)}}function Wg(e,t,r,n){if(t.expectedBytes!==void 0)return t.expectedBytes;const i=n===void 0?r:Math.min(r,n);try{const o=e?.committedBytes;if(typeof o=="number"&&Number.isSafeInteger(o)&&o>=i&&(n===void 0||o<=n))return o}catch{}return i}function $g(e,t){return e===void 0?t:t===void 0?e:Math.min(e,t)}function Kg(e,t){try{Promise.resolve(e.release(t)).catch(()=>{})}catch{}}async function Zg(e,t,r){if(e.targetKind==="file"){const i=t.resolveFileEntry(e.to);return rs(i.handle.mode),await cp(i.handle,r),{kind:"file",...i}}const n=t.resolveDirectoryEntry(e.to);return rs(n.handle.mode),await dp(n.handle,r),{kind:"directory",...n}}function Jg(e,t,r,n){if(t.kind==="file")return{ref:t.ref,handle:t.handle,hostHandle:t.hostHandle,mode:"replace-existing"};const i=np(e,r),o=n.deriveFile(t,i);return rs(o.handle.mode),{...o,mode:e.overwrite===!0?"upsert":"create-exclusive"}}function Xg(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 p("DOWNLOAD_NETWORK_FAILED","Host 返回了无效 stream response");if(!Q(e.headers))throw p("DOWNLOAD_NETWORK_FAILED","Host 返回了无效 stream headers");const t={};for(const[r,n]of Object.entries(e.headers)){if(r!==r.toLowerCase()||!Bg.has(r)||!Array.isArray(n)||n.length===0)throw p("DOWNLOAD_NETWORK_FAILED","Host 返回了不安全 stream header");if(n.some(i=>typeof i!="string"||/[\r\n]/.test(i)))throw p("DOWNLOAD_NETWORK_FAILED","Host 返回了无效 stream header value");t[r]=[...n]}return t}function ep(e,t){if(e.status<200||e.status>=300||e.status===206||e.status===226)throw p("DOWNLOAD_HTTP_STATUS",`下载请求失败: HTTP ${e.status}`,{status:e.status,...e.statusText===void 0?{}:{statusText:e.statusText},headers:ap(t,Vg)});if((t["content-range"]?.length??0)>0)throw p("DOWNLOAD_NETWORK_FAILED","下载响应包含 Content-Range")}function tp(e,t){const r=t["content-length"]??[],n=t["transfer-encoding"]??[];if(r.length>0&&n.length>0)throw p("DOWNLOAD_NETWORK_FAILED","下载响应同时包含 Transfer-Encoding 与 Content-Length");if((e===204||e===205)&&r.some(d=>d!=="0"))throw p("DOWNLOAD_NETWORK_FAILED","无内容响应声明了非零 Content-Length");if((e===204||e===205)&&n.length>0)throw p("DOWNLOAD_NETWORK_FAILED","无内容响应不允许 Transfer-Encoding");const i=r.length===1&&/^(?:0|[1-9]\d*)$/.test(r[0])?Number(r[0]):void 0,o=i!==void 0&&Number.isSafeInteger(i)?i:void 0,s=rp(t["content-encoding"]),a=e===204||e===205?0:n.length===0&&s?o:void 0,c=a!==void 0;return{...a===void 0?{}:{expectedBytes:a},...c?{total:a}:{},lengthComputable:c}}function rp(e){return!e||e.length===0?!0:e.length===1&&e[0].trim().toLowerCase()==="identity"}function oo(e,t){return{loaded:e,...t.total===void 0?{}:{total:t.total},lengthComputable:t.lengthComputable}}function so(e,t){try{e.postProgress(t)}catch{}}function np(e,t){const r=t["content-disposition"]??[];for(const i of r){const o=ip(i);if(o&&Nn(o))return o}for(const i of r){const o=op(i);if(o&&Nn(o))return o}if(e.suggestedName!==void 0)return Gs(e.suggestedName);const n=sp(e.url);return n&&Nn(n)?n:"download.bin"}function ip(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 op(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 sp(e){const t=e.pathname.split("/").pop();if(t)try{return decodeURIComponent(t)}catch{return}}function Gs(e){try{Kr(e,"suggestedName")}catch{throw p("INVALID_PARAMS","suggestedName 不是安全 basename")}if(!Nn(e))throw p("INVALID_PARAMS","suggestedName 不是安全 basename");return e}function Nn(e){return!(!e||e==="."||e===".."||Array.from(e).length>255||/[\\/<>:"|?*\u0000-\u001f\u007f]/.test(e)||/[. ]$/.test(e)||Qg.test(e))}function ap(e,t){return Object.fromEntries(Object.entries(e).filter(([r])=>t.has(r)).map(([r,n])=>[r,n.join(", ")]))}async function cp(e,t){try{const r=await e.stat(t);if(!r||r.kind!=="file")throw Ru()}catch(r){throw qs(r,"file",t.signal)}}async function dp(e,t){try{const r=await e.stat(t);if(!r||r.kind!=="directory")throw Ru()}catch(r){throw qs(r,"file",t.signal)}}function rs(e){if(e!=="readwrite")throw p("FILE_ACCESS_DENIED","下载目标只允许读取")}const up={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 qs(e,t,r){if(r.aborted)return Pu();const n=lp(e);if(n&&qg.has(n)){const o=p(n,up[n]??"下载失败");return Object.defineProperty(o,"cause",{value:e,enumerable:!1}),o}if(e instanceof Error&&e.name==="AbortError")return t==="network"||t==="transfer"?p("DOWNLOAD_TIMEOUT","下载网络请求超时"):p("FILE_IO_FAILED","下载文件写入失败");const i=t==="network"?p("DOWNLOAD_NETWORK_FAILED","下载网络请求失败"):p("FILE_IO_FAILED","下载文件写入失败");return Object.defineProperty(i,"cause",{value:e,enumerable:!1}),i}function lp(e){return Q(e)&&typeof e.code=="string"?e.code:void 0}function Ru(){return p("FILE_TYPE_MISMATCH","下载目标类型不匹配")}function Pu(){return p("DOWNLOAD_CANCELLED","下载已取消")}function fp(e){if(!e)return;const t=Object.keys(e).find(r=>Gg.has(r.trim().toLowerCase()));if(t)throw p("INVALID_PARAMS",`network.download 不允许设置请求头: ${t}`)}const hp=new Map([["2358720","blackMythWukong"],["3678970","taskbarHero"],["4115450","phantomBladeZero"],["1245620","eldenRing"],["413150","stardewValley"],["2246340","monsterHunterWilds"],["3167020","duckov"],["3489700","stellarBlade"],["2001120","splitFiction"]]);function ns(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=>ns(r,t+1)):ne(e)&&Object.values(e).every(r=>ns(r,t+1))}function mp(e,t){const r=hp.get(t);if(!r||ne(e)&&e.status==="unsupported")return{status:"unsupported"};if(ne(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 G(String(e.error_code),"账号或授权已变化");if(e.status==="ready"&&ne(e.data)&&ns(e.data))return{status:"ready",data:e.data}}return{status:"failed",error:{code:"STRUCTURED_DATA_UNAVAILABLE",message:"结构化数据暂时无法读取,请稍后重试"}}}function gp(e){const t=new Map,r=new Map,n=a=>`hb_runtime_game_save_sync_v1_${[a.miniProgramId,a.userId,a.gameId].map(encodeURIComponent).join(":")}`;async function i(a,c,d){const u=n(a),l=r.get(u)??Promise.resolve();let f;const m=new Promise(g=>{f=g}),h=l.then(()=>m);r.set(u,h);try{return await $(()=>l,c.signal),X(c.signal),await d()}finally{f(),r.get(u)===h&&h.then(()=>{r.get(u)===h&&r.delete(u)})}}async function o(a,c){const d=n(a);if(t.has(d))return t.get(d);if(e)try{const u=await $(()=>e.getRaw(d,c),c.signal);if(!u)return;const l=JSON.parse(u);if(!l||typeof l!="object")return;const f=l;return f.version!==1||f.miniProgramId!==a.miniProgramId||f.userId!==a.userId||f.gameId!==a.gameId||typeof f.accountId!="string"||!/^[1-9][0-9]{0,19}$/.test(f.accountId)||typeof f.taskId!="string"||!/^[1-9][0-9]{0,19}$/.test(f.taskId)?void 0:(t.set(d,f),f)}catch{X(c.signal);return}}async function s(a,c,d){X(d.signal);const u=n(a),l=c?{...a,version:1,taskId:c}:void 0;if(t.set(u,l),!!e)try{await $(()=>e.setRaw(u,l?JSON.stringify(l):"",d),d.signal)}catch{X(d.signal)}}return{run:i,async get(a,c){const d=await o(a,c);if(d&&d.accountId!==a.accountId){await s(a,void 0,c);return}return d?.taskId},set:s,async remove(a,c,d){await i(a,d,async()=>{const u=await o(a,d);u?.taskId===c&&u.accountId===a.accountId&&await s(a,void 0,d)})},clear(a){for(const c of t.values())c&&i(c,a,()=>s(c,void 0,a)).catch(()=>{})}}}const ao=8*1024*1024,$a=32*1024*1024,pp=2e3,yp=5*6e4;function Ep(e){const t=gp(e.storage);let r=0,n=!1,i,o=0;const s=new Set,a=new Map,c={...e.operationContext,lifecycle:"cleanup",signal:new AbortController().signal},d=w=>w.remove(c),u=new Set;let l=new AbortController,f;const m=()=>{l.abort(),l=new AbortController,f=void 0},h=(w=!0)=>{w&&t.clear(c),r++,m();for(const S of u)S.abort();for(const S of s)d(S).catch(()=>{});s.clear(),a.clear(),o=0},g=Hs(e.account,w=>{i&&w!==i&&(h(),i=void 0)}),I=e.authorization.onEvent(()=>h());function y(w,S,v,C){if(b(v),C.signal.aborted||!w.account_id||!e.presentation?.showSteamLoginRequired)return;const E=`${w.account_id}:${w.game_id}:${w.task_id??"sync"}`;if(f!==E){f=E;try{e.presentation.showSteamLoginRequired({userId:S,accountId:w.account_id},ae(e.operationContext,l.signal))}catch{}}}function b(w){if(n||e.operationContext.signal.aborted)throw G("RUNTIME_DESTROYED","小程序已关闭");if(w!==r)throw G("AUTHORIZATION_CONTEXT_CHANGED","账号或授权已变化")}async function _(w,S,v){if(b(S),await e.account.getCurrentUserId(v)!==w)throw h(),G("AUTHORIZATION_CONTEXT_CHANGED","账号已变化");b(S)}async function P(w,S,v,C){if(await _(S,v,C),!e.authorizationContext)throw G("METHOD_FORBIDDEN","宿主不支持存档授权上下文");const E=await e.authorizationContext.get(C);if(!E.token||E.expiresAt<=Date.now())throw G("UNAUTHORIZED","小程序运行上下文已过期");const D=await zs({network:e.network,operationContext:C,subject:"游戏存档",assertUsable:()=>b(v),...e.requestGate?{gate:{capability:"gameSaves",gate:e.requestGate}}:{},requestPolicyEnabled:e.requestPolicyEnabled},Pg,{...w,runtime_auth_context_token:E.token});if(await _(S,v,C),D.status==="failed"&&ne(D.result)&&D.result.error_code==="RECENT_SAVE_AVAILABLE")throw G("RECENT_SAVE_AVAILABLE",typeof D.msg=="string"&&D.msg?D.msg:"已有近期存档,请直接查询使用");const M=We(D,w.action,"游戏存档");if(!ne(M))throw G("INVALID_RESPONSE","存档响应不合法");return M}async function j(w,S,v){const C=wp(w,S),E=r;if(b(E),w==="file"&&(!e.transfer||!e.files))throw G("METHOD_FORBIDDEN","宿主不支持存档文件读取");const D=new AbortController;u.add(D);let M=!1;const R=w==="sync"?setTimeout(()=>{M=!0,D.abort()},yp):void 0,T=ae(ae(e.operationContext,v.signal),D.signal);try{const N=await e.account.getCurrentUserId(T);if(!N)throw G("UNAUTHORIZED","请先登录小黑盒");if(i&&i!==N)throw h(),G("AUTHORIZATION_CONTEXT_CHANGED","账号已变化");if(i=N,w==="sync"||w==="parsed"){if(w==="sync"&&m(),!C.account_id){const J=await P({action:"check",game_id:C.game_id},N,E,T);C.account_id=Br(J.account_id)}if(w==="sync")return await U(C,N,E,T)}const A=await P({action:w,...C},N,E,T);if(w==="list")return Ip(A);if(w==="parsed")return mp(A.parsed_data,C.game_id);const L=ku(A.file);if(L.fileId!==C.file_id)throw G("INVALID_RESPONSE","文件标识不匹配");if(L.sizeBytes>ao)throw G("FILE_TOO_LARGE","首期存档文件上限为 8 MiB");if(o+L.sizeBytes>$a)throw G("FILE_QUOTA_EXCEEDED","当前会话存档文件已达 32 MiB");const k={source:"runtime-private",credentials:"omit",route:"game-save",redirectPolicy:"error",method:"GET",target:{kind:"absolute-url",url:wt(A.download_url)},timeout:6e4};if(!Zd(k)||new URL(wt(A.download_url)).pathname!=="/cloud_archive/"+C.file_id+".zip"||Ai(A.expires_at)<=Date.now())throw G("INVALID_RESPONSE","存档下载地址无效");const x=".hb-game-saves/"+es()+".zip",H=e.files.sandbox.file(x);if(!H.remove)throw G("METHOD_FORBIDDEN","宿主不支持存档临时文件清理");await e.files.sandbox.directory(".hb-game-saves").create({recursive:!0,exclusive:!1},T);const F=e.fileRegistry.createTransferScope();let V=!1,q=!1;try{await H.create({recursive:!0,exclusive:!0},T),q=!0;const J=F.registerFile(H,"game-save","readwrite");await Cu({request:k,url:new URL(wt(A.download_url)),to:J.ref,targetKind:"file",maxBytes:ao},{...v,signal:T.signal,postProgress:()=>{}},{transfer:e.transfer,fileRegistry:F,operationContext:T}),await _(N,E,T);const K=await H.stat(T);if(K.size===void 0||!Number.isSafeInteger(K.size)||K.size<0||K.size>ao)throw G("FILE_TOO_LARGE","存档文件超过 8 MiB");if(await _(N,E,T),o+K.size>$a)throw G("FILE_QUOTA_EXCEEDED","当前会话存档缓存已达 32 MiB");if(T.signal.aborted)throw G("DOWNLOAD_CANCELLED","存档下载已取消");const Z=K.size,Y=async fe=>{try{b(E),await P({action:"check",game_id:C.game_id,account_id:C.account_id},N,E,fe)}catch(ie){throw ne(ie)&&["GAME_SAVES_AUTHORIZATION_REQUIRED","AUTHORIZATION_CONTEXT_CHANGED","STEAM_ACCOUNT_CHANGED","UNAUTHORIZED"].includes(String(ie.code))?(h(),G("FILE_ACCESS_REVOKED","游戏存档授权已失效")):ie}},re=async()=>{throw G("FILE_ACCESS_DENIED","存档文件只读")},Me={kind:"file",mode:"read",name:L.name,create:re,write:re,async read(fe){await Y(fe);const ie=await H.read(fe);try{if(await _(N,E,fe),!(ie instanceof Uint8Array)||ie.byteLength!==Z)throw G("INVALID_RESPONSE","存档文件长度不匹配");return ie}catch(Rt){throw ie instanceof Uint8Array&&ie.fill(0),Rt}},async stat(fe){return await Y(fe),{kind:"file",size:Z,modifiedAt:L.modifiedAt}}},le=e.fileRegistry.registerFile(Me,"game-save","read");return s.add(H),o+=Z,a.set(es(),{file:Me,sizeBytes:Z}),V=!0,le}finally{F.dispose(),q&&!V&&await d(H)}}catch(N){throw M?G("REQUEST_TIMEOUT","等待同步超时,任务可能仍在执行,请稍后查询存档列表"):N}finally{R!==void 0&&clearTimeout(R),u.delete(D)}}async function U(w,S,v,C){const E=e.identity.get()?.miniProgramId;if(!E)throw G("INVALID_STATE","小程序身份尚未确认");const D={miniProgramId:E,userId:S,gameId:w.game_id,accountId:w.account_id},M=T=>P({action:"status",...w,task_id:T},S,v,C);let R;try{const T=await t.run(D,C,async()=>{await _(S,v,C);const A=await t.get(D,C);if(A){R=A;try{return{taskId:A,status:await M(A)}}catch(k){if(!ne(k)||!["SYNC_TASK_NOT_FOUND","SYNC_TASK_CHANGED"].includes(String(k.code)))throw k;await t.set(D,void 0,C),R=void 0}}const L=await P({action:"sync",...w},S,v,C);return R=Br(L.task_id),await t.set(D,R,C),await _(S,v,C),{taskId:R,status:void 0}});R=T.taskId;let N=T.status;for(;;){if(b(v),C.signal.aborted)throw G("REQUEST_CANCELLED","已停止等待存档同步");if(N??=await M(R),N.state==="succeeded"||N.state==="failed"){if(await t.remove(D,R,C),await _(S,v,C),N.state==="succeeded")return{state:"succeeded"};throw G(N.error_code?wt(N.error_code):"SYNC_FAILED",N.message?wt(N.message):"存档同步失败")}if(N.state!=="syncing"&&N.state!=="uploading")throw G("INVALID_RESPONSE","同步状态不合法");N=void 0,await Ap(pp,C.signal)}}catch(T){if(ne(T)){const N=String(T.code);N==="STEAM_LOGIN_REQUIRED"&&y({...w,task_id:R},S,v,C),R&&["SYNC_TASK_NOT_FOUND","SYNC_TASK_CHANGED","STEAM_ACCOUNT_CHANGED","STEAM_ACCOUNT_REQUIRED","GAME_SAVES_AUTHORIZATION_REQUIRED","AUTHORIZATION_CONTEXT_CHANGED","UNAUTHORIZED"].includes(N)&&await t.remove(D,R,c)}throw T}}return{handlers:{"gameSaves.list":(w,S)=>j("list",w,S),"gameSaves.sync":(w,S)=>j("sync",w,S),"gameSaves.readParsedData":(w,S)=>j("parsed",w,S),"gameSaves.getFile":(w,S)=>j("file",w,S)},diagnostics:{async getSnapshot(){const w=r;return i&&await _(i,w,e.operationContext),b(w),Array.from(a,([S,v])=>({id:S,name:v.file.name,sizeBytes:v.sizeBytes}))},async readFile(w,S){const v=r;b(v);const C=a.get(w);if(!C)throw G("FILE_ACCESS_REVOKED","存档文件已失效,请重新下载");const E=ae(e.operationContext,S);E.signal.throwIfAborted();const D=await C.file.read(E);try{return E.signal.throwIfAborted(),b(v),{name:C.file.name,bytes:D}}catch(M){throw D.fill(0),M}}},allowsRead(w,S){return["file.readBytes","file.readText","file.stat","file.exists"].includes(w)&&ne(S)&&e.fileRegistry.isGameSaveRef(S.target)},dispose(){n||(n=!0,h(!1),g(),I())}}}function wp(e,t){const r=e==="file"?["gameId","accountId","saveId","fileId"]:["gameId","accountId"];if(!ne(t)||Object.keys(t).some(i=>!r.includes(i)))throw G("INVALID_PARAMS","存档参数不合法");const n=Mr(t.gameId);if(Number(n)>2147483647)throw G("INVALID_PARAMS","Steam AppID 超出范围");return{game_id:n,...e==="file"||t.accountId!==void 0?{account_id:Mr(t.accountId)}:{},...e==="file"?{save_id:Mr(t.saveId),file_id:Mr(t.fileId)}:{}}}function Mr(e){if(typeof e!="string"||!/^[1-9][0-9]{0,19}$/.test(e))throw G("INVALID_PARAMS","存档标识必须为十进制字符串");return e}function Br(e){try{return Mr(e)}catch{throw G("INVALID_RESPONSE","服务端存档标识无效")}}function wt(e){if(typeof e!="string")throw G("INVALID_RESPONSE","服务端存档字段无效");return e}function Ai(e){if(typeof e!="number"||!Number.isSafeInteger(e)||e<0)throw G("INVALID_RESPONSE","服务端存档数值无效");return e}function ku(e){if(!ne(e))throw G("INVALID_RESPONSE","存档文件信息无效");return{fileId:Br(e.file_id),name:wt(e.name),originalPath:wt(e.original_path),sizeBytes:Ai(e.size_bytes),modifiedAt:Ai(e.modified_at)}}function Ip(e){if(!Array.isArray(e.saves)||e.saves.length>500)throw G("INVALID_RESPONSE","存档列表无效");return{accountId:Br(e.account_id),saves:e.saves.map(t=>{if(!ne(t)||!Array.isArray(t.files)||t.files.length>200)throw G("INVALID_RESPONSE","存档文件列表无效");return{saveId:Br(t.save_id),createdAt:Ai(t.created_at),files:t.files.map(ku)}})}}function Ap(e,t){return new Promise((r,n)=>{const i=()=>{clearTimeout(o),t.removeEventListener("abort",i),n(G("REQUEST_CANCELLED","已停止等待存档同步"))},o=setTimeout(()=>{t.removeEventListener("abort",i),r()},Math.max(0,e));t.addEventListener("abort",i,{once:!0}),t.aborted&&i()})}const Np=new Set(["stdio","attachments","notifications"]),xu=new Set(["windows-x64","macos-arm64"]),Dp=new Set(["unsigned","valid","invalid","unknown"]),Mp=/^[a-f0-9]{64}$/,Sp=new Set(["exited","terminated","crashed","host-shutdown","permission-revoked","output-limit"]),_p=new Set(Kd),bp=new Set([...Kd,"PERMISSION_DENIED","USER_GESTURE_REQUIRED"]),Uu=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 Tp(e){const t=async(n,i,o,s)=>{const a=Op(n);try{Qe(i.signal);const c=await o(a,{...e.operationContext,signal:i.signal});return Qe(i.signal),c}catch(c){throw os(c,s)}},r=async(n,i,o)=>{if(!o.trustedUserGesture)throw p("USER_GESTURE_REQUIRED","当前操作需要新的可信用户手势");if(!e.companionPresentation)throw p("COMPANION_UNSUPPORTED","Host 未提供 Companion 可信授权界面");const s={...e.operationContext,signal:o.signal},a=await e.companion.getInfo(i,s).then(d=>vp(d,i)).catch(d=>{throw os(d)});Qe(o.signal);const c=await e.companionPresentation.confirmCompanionOperation({action:n,companion:a,miniProgram:e.miniProgramPresentation,signal:o.signal});if(Qe(o.signal),c.status!=="granted")throw p("COMPANION_USER_CANCELLED","用户取消了 Companion 操作")};return{[Oi]:(n,i)=>t(n,i,async(o,s)=>is(await e.companion.getInfo(o,s),o)),[vi]:(n,i)=>t(n,i,async(o,s)=>Ka(await e.companion.getPreparationStatus(o,s))),[Li]:(n,i)=>t(n,i,async(o,s)=>{const a=Ka(await e.companion.getPreparationStatus(o,s));return Qe(i.signal),a.state!=="ready"&&a.state!=="preparing"&&await r("prepare",o,i),Qe(i.signal),is(await e.companion.prepare(o,{...s,onProgress:c=>i.postProgress(zu(c))}),o)},"COMPANION_PREPARATION_CANCELLED"),[Ci]:(n,i)=>t(n,i,(o,s)=>e.companion.cancelPreparation(o,s)),[Ri]:(n,i)=>t(n,i,async(o,s)=>Za(await e.companion.getActiveSession(o,s),o)),[Pi]:(n,i)=>t(n,i,async(o,s)=>{const a=Za(await e.companion.getActiveSession(o,s),o);return Qe(i.signal),a||(await r("launch",o,i),Qe(i.signal),Hu(await e.companion.launch(o,s),o))}),[ki]:(n,i)=>Ht(n,i,e,"write"),[xi]:(n,i)=>Ht(n,i,e,"closeStdin"),[Ui]:(n,i)=>Ht(n,i,e,"terminate"),[ji]:(n,i)=>Ht(n,i,e,"ackOutput"),[zi]:async(n,i)=>{const o=await Ht(n,i,e,"openAttachment");return e.fileRegistry.registerFile(o,"companion-attachment","read")},[Hi]:(n,i)=>Ht(n,i,e,"showNotification")}}function Op(e){if(!Q(e)||typeof e.alias!="string"||!Jf.test(e.alias))throw p("INVALID_PARAMS","Companion alias 不合法");return e.alias}function Qe(e){if(e.aborted)throw Object.assign(new Error("Companion 操作已取消"),{name:"AbortError"})}async function Ht(e,t,r,n){if(!Q(e)||typeof e.sessionId!="string"||!e.sessionId||!Number.isSafeInteger(e.controllerGeneration)||Number(e.controllerGeneration)<0)throw p("INVALID_PARAMS","Companion Session controller 不合法");try{Qe(t.signal);const i=await r.companion[n](Lp(e,n),{...r.operationContext,signal:t.signal});return Qe(t.signal),i}catch(i){throw os(i)}}function ze(){throw p("COMPANION_HOST_FAILED","Companion Host 返回了无效数据")}function ju(e){return!Array.isArray(e)||e.some(t=>!Np.has(t))?ze():Object.freeze([...new Set(e)])}function is(e,t){return!Q(e)||typeof e.alias!="string"||typeof e.displayName!="string"||t!==void 0&&e.alias!==t||!xu.has(String(e.target))||!Number.isSafeInteger(e.archiveBytes)||Number(e.archiveBytes)<0||!Dp.has(String(e.signatureStatus))||e.source!==void 0&&e.source!=="local-dev"&&e.source!=="preview"&&e.source!=="released"?ze():Object.freeze({alias:e.alias,displayName:e.displayName,target:e.target,capabilities:ju(e.capabilities),archiveBytes:e.archiveBytes,signatureStatus:e.signatureStatus,...e.source===void 0?{}:{source:e.source}})}function vp(e,t){const r=is(e,t);return!Q(e)||e.sha256===void 0?r:typeof e.sha256!="string"||!Mp.test(e.sha256)?ze():Object.freeze({...r,sha256:e.sha256})}function zu(e){return Q(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}):ze():ze()}function Ka(e){return Q(e)?e.state==="not-prepared"?Object.freeze({state:"not-prepared"}):e.state==="preparing"?Object.freeze({state:"preparing",progress:zu(e.progress)}):e.state==="ready"&&Number.isSafeInteger(e.preparedAt)&&Number(e.preparedAt)>=0?Object.freeze({state:"ready",preparedAt:e.preparedAt}):e.state==="failed"&&Q(e.error)&&typeof e.error.code=="string"&&_p.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:Uu[e.error.code]??"Companion 操作失败",retryable:e.error.retryable})}):ze():ze()}function Hu(e,t){return!Q(e)||typeof e.id!="string"||!e.id||typeof e.alias!="string"||t!==void 0&&e.alias!==t||!xu.has(String(e.target))||e.state!=="running"||!Number.isSafeInteger(e.controllerGeneration)||Number(e.controllerGeneration)<0?ze():Object.freeze({id:e.id,alias:e.alias,target:e.target,capabilities:ju(e.capabilities),state:"running",controllerGeneration:e.controllerGeneration})}function Za(e,t){return e===void 0?void 0:Hu(e,t)}function Lp(e,t){const r=e,n={sessionId:r.sessionId,controllerGeneration:r.controllerGeneration};if(t==="write"){if(!Qd(r.data))throw p("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 p("INVALID_PARAMS","Companion output ack 不合法");return{...n,stream:r.stream,sequence:r.sequence}}if(t==="openAttachment"){if(typeof r.id!="string"||!r.id)throw p("INVALID_PARAMS","Companion Attachment ID 不合法");return{...n,id:r.id}}if(t==="showNotification"){if(!["completed","failed","stopped","attention"].includes(String(r.category)))throw p("INVALID_PARAMS","Companion notification category 不合法");return{...n,category:r.category}}return n}function Cp(e){return!Q(e)||!Sp.has(String(e.reason))?ze():e.reason==="exited"?Number.isSafeInteger(e.exitCode)?Object.freeze({reason:"exited",exitCode:e.exitCode}):ze():e.exitCode!==void 0&&!Number.isSafeInteger(e.exitCode)?ze():Object.freeze({reason:e.reason,...e.exitCode===void 0?{}:{exitCode:e.exitCode}})}function Rp(e){if(!Q(e)||!Q(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||!Qd(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:Cp(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 os(e,t){return Q(e)&&typeof e.code=="string"&&bp.has(e.code)?p(e.code,Uu[e.code]??"Companion 操作失败",e.code==="COMPANION_DESCRIPTOR_UNAVAILABLE"?{retryable:!0}:typeof e.retryable=="boolean"?{retryable:e.retryable}:void 0):t&&Q(e)&&e.name==="AbortError"?p(t,"Companion 准备已取消"):p("COMPANION_HOST_FAILED","Companion Host 操作失败")}const Ja=5e3,Xa=1e4;function Ne(e){throw{code:"INVALID_PARAMS",message:e}}function Qs(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Fu(e,t,r){const n=Object.keys(e).filter(i=>!t.includes(i));n.length&&Ne(`${r} 不支持字段: ${n.join(", ")}`)}function Pp(e){if(e===void 0)return{intensity:"light",delay:0};if(!Qs(e))return Ne("device.vibrate 参数必须是对象");Fu(e,["intensity","delay"],"device.vibrate");const t=e.intensity??"light";if(t!=="light"&&t!=="medium"&&t!=="heavy")return Ne("device.vibrate intensity 必须是 light、medium 或 heavy");const r=t,n=e.delay??0;return typeof n!="number"||!Number.isInteger(n)||n<0||n>Ja?Ne(`device.vibrate delay 必须是 0-${Ja} 的整数毫秒`):{intensity:r,delay:n}}function kp(e){return Qs(e)?(Fu(e,["text"],"device.setClipboard"),typeof e.text!="string"||!e.text.trim()?Ne("device.setClipboard text 必须是非空字符串"):e.text.length>Xa?Ne(`device.setClipboard text 不能超过 ${Xa} 字符`):{text:e.text}):Ne("device.setClipboard 参数必须是对象")}function xp(e){return typeof e=="string"?e.trim()?e:Ne("device.executeProtocol 协议字符串不能为空"):Qs(e)?typeof e.protocol_type!="string"||!e.protocol_type.trim()?Ne("device.executeProtocol 协议对象必须包含非空字符串 protocol_type"):(ss(e,new Set),e):Ne("device.executeProtocol 参数必须是协议字符串或协议对象")}function ss(e,t){if(e===null)return;switch(typeof e){case"string":case"boolean":return;case"number":Number.isFinite(e)||Ne("device.executeProtocol 协议对象不能包含非有限数字");return;case"undefined":Ne("device.executeProtocol 协议对象不能包含 undefined");return;case"function":case"symbol":case"bigint":Ne(`device.executeProtocol 协议对象只能包含 JSON 数据,不能包含 ${typeof e}`);return}const r=e;if(t.has(r)&&Ne("device.executeProtocol 协议对象不能包含循环引用"),t.add(r),Array.isArray(r)){for(const i of r)ss(i,t);t.delete(r);return}const n=Object.getPrototypeOf(r);n!==Object.prototype&&n!==null&&Ne("device.executeProtocol 协议对象只能包含普通 JSON 对象,不能包含类实例或特殊对象");for(const i of Object.values(r))ss(i,t);t.delete(r)}function Up(e){return{[li]:async(t,r)=>{const n=ae(e.operationContext,r.signal,r.requestId);X(n.signal),await $(()=>e.presentation.vibrate(Pp(t),n),n.signal)},[fi]:async(t,r)=>{const n=ae(e.operationContext,r.signal,r.requestId);X(n.signal),await $(()=>e.presentation.setClipboard(kp(t),n),n.signal)},[hi]:async(t,r)=>{const n=ae(e.operationContext,r.signal,r.requestId);X(n.signal);const i=xp(t);await $(()=>e.protocol.invoke(i,n),n.signal)}}}const ec=1e3,jp=new Set(["FILE_NOT_FOUND","DIRECTORY_NOT_FOUND","FILE_TYPE_MISMATCH"]);function zp(e){const t=r=>ae(e.operationContext,r.signal);return{files:{[Xn]:async(r,n)=>{co(n);const i=uo(e.picker),o=Hp(r),s=await be(()=>i.pickFiles(o,t(n)));return e.registry.registerFiles(s,"external",o.mode,o.multiple?void 0:1)},[ei]:async(r,n)=>{co(n);const i=uo(e.picker),o=Fp(r),s=await be(()=>i.pickDirectory(o,t(n)));return e.registry.registerDirectory(s,"external",o.mode)},[ti]:async(r,n)=>{co(n);const i=uo(e.picker),o=Bp(r).suggestedName,s=t(n);if(!i.saveFile)throw Ce("files.saveFile");const a=await be(()=>i.saveFile({suggestedName:o},s));return e.registry.registerFile(a,"external","readwrite")}},file:{[Pr]:async(r,n)=>{const i=ve(r,["recursive","exclusive"]),o=e.registry.resolveFile(i.target);Ft(o.mode),await be(()=>o.create(tc(i),t(n)))},[kr]:async(r,n)=>{const i=ve(r),o=e.registry.resolveFileEntry(i.target);if(e.registry.assertSandboxOrigin(o),Ft(o.handle.mode),!o.handle.remove)throw Ce(kr);await be(()=>o.handle.remove(t(n)))},[ri]:async(r,n)=>{const i=ve(r);return rc(async()=>{const o=await e.registry.resolveFile(i.target).stat(t(n));if(!Q(o)||o.kind!=="file")throw ic()})},[xr]:async(r,n)=>{const i=ve(r),o=nc(await be(()=>e.registry.resolveFile(i.target).read(t(n))));try{const s=new TextDecoder("utf-8",{fatal:!0}).decode(o);return s.charCodeAt(0)===65279?s.slice(1):s}catch{throw p("FILE_ENCODING_INVALID","文件不是合法 UTF-8 文本")}},[ni]:async(r,n)=>{const i=ve(r,["content"]);typeof i.content!="string"&&Pe("content 必须是字符串");const o=e.registry.resolveFile(i.target);Ft(o.mode),await be(()=>o.write(new TextEncoder().encode(i.content),t(n)))},[Ur]:async(r,n)=>{const i=ve(r),o=await be(()=>e.registry.resolveFile(i.target).read(t(n)));return nc(o)},[ii]:async(r,n)=>{const i=ve(r,["content"]),o=e.registry.resolveFile(i.target);Ft(o.mode),await be(()=>o.write(Gp(i.content),t(n)))},[jr]:async(r,n)=>{const i=ve(r),o=await be(()=>e.registry.resolveFile(i.target).stat(t(n)));return qp(o)}},directory:{[oi]:async(r,n)=>{const i=ve(r,["recursive","exclusive"]),o=e.registry.resolveDirectory(i.target);Ft(o.mode),await be(()=>o.create(tc(i),t(n)))},[zr]:async(r,n)=>{const i=ve(r,["recursive"]);if(Q(i.target)&&i.target.relativePath===".")throw p("FILE_ACCESS_DENIED","不能删除根目录");const o=e.registry.resolveDirectoryEntry(i.target);if(e.registry.assertSandboxOrigin(o),Ft(o.handle.mode),!o.handle.remove)throw Ce(zr);await be(()=>o.handle.remove({recursive:i.recursive===void 0?!1:Ni(i.recursive,"recursive")},t(n)))},[si]:async(r,n)=>{const i=ve(r);return rc(async()=>{const o=await e.registry.resolveDirectory(i.target).stat(t(n));if(!Q(o)||o.kind!=="directory")throw ic()})},[ai]:async(r,n)=>{const i=ve(r,["limit"]),o=Vp(i.limit),s=e.registry.resolveDirectoryEntry(i.target),a=await be(()=>s.handle.list({limit:o},t(n)));return e.registry.describeListedEntries(s,a,o)}}}}function Hp(e){if(e===void 0)return{mode:"read",multiple:!1};Q(e)||Pe("pickFiles 参数必须是对象"),Bi(e,["mode","accept","multiple"]);const t=Bu(e.mode,"read"),r=e.multiple===void 0?!1:Ni(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)))&&Pe("accept 必须是规范扩展名数组"),n=[...new Set(e.accept)]),{mode:t,multiple:r,...n===void 0?{}:{accept:n}}}function Fp(e){return e===void 0?{mode:"read"}:(Q(e)||Pe("pickDirectory 参数必须是对象"),Bi(e,["mode"]),{mode:Bu(e.mode,"read")})}function Bp(e){return Q(e)||Pe("saveFile 参数必须是对象"),Bi(e,["suggestedName"]),{suggestedName:Kr(e.suggestedName,"suggestedName")}}function ve(e,t=[]){return(!Q(e)||!Object.prototype.hasOwnProperty.call(e,"target"))&&Pe("文件操作参数必须包含 target"),Bi(e,["target",...t]),e}function tc(e){return{recursive:e.recursive===void 0?!1:Ni(e.recursive,"recursive"),exclusive:e.exclusive===void 0?!1:Ni(e.exclusive,"exclusive")}}function Bu(e,t){return e===void 0?t:(e!=="read"&&e!=="readwrite"&&Pe("mode 必须是 read 或 readwrite"),e)}function Ni(e,t){return typeof e!="boolean"&&Pe(`${t} 必须是布尔值`),e}function Vp(e){if(e===void 0)return ec;if((!Number.isSafeInteger(e)||e<=0)&&Pe("limit 必须是正整数"),e>ec)throw p("DIRECTORY_LIST_LIMIT_EXCEEDED","目录项限制超过 Host 上限");return e}function Bi(e,t){const r=Object.keys(e).filter(n=>!t.includes(n));r.length&&Pe(`不支持字段: ${r.join(", ")}`)}function Ft(e){if(e!=="readwrite")throw p("FILE_ACCESS_DENIED","当前文件授权只允许读取")}function co(e){if(!e.trustedUserGesture)throw p("USER_GESTURE_REQUIRED","当前操作需要可信用户手势")}function uo(e){if(!e)throw Ce("files.external");return e}async function rc(e){try{return await e(),!0}catch(t){if(jp.has(Bs(t)??""))return!1;throw ir(t)}}async function be(e){try{return await e()}catch(t){throw ir(t)}}function Gp(e){return e instanceof Uint8Array||Pe("content 必须是 Uint8Array"),typeof SharedArrayBuffer<"u"&&e.buffer instanceof SharedArrayBuffer&&Pe("不支持 SharedArrayBuffer-backed Uint8Array"),new Uint8Array(e)}function nc(e){if(!(e instanceof Uint8Array))throw p("FILE_IO_FAILED","Host 返回了无效字节数据");return new Uint8Array(e)}function ic(){return p("FILE_TYPE_MISMATCH","文件句柄类型不匹配")}function qp(e){if(!Q(e)||e.kind!=="file"||!Qp(e.size))throw p("FILE_IO_FAILED","Host 返回了无效 FileStat");for(const t of["modifiedAt","createdAt"])if(e[t]!==void 0&&!Yp(e[t]))throw p("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 Qp(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function Yp(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0}function Pe(e){throw p("INVALID_PARAMS",e)}const oc=16*1024,sc=200;function Wp(e){const t=au(e.runtimePermissions);function r(n,i){e.capabilities&&eu(i,e.capabilities);const o=t({kind:"all",permissions:["filesystem"]},i);if(!o.allowed)throw p(o.code,o.message);const s=ae(e.operationContext,n);return as(s),s}return{async list(n,i={}){const o=r(i.signal,"directory.list"),s=e.registry.resolveDirectoryEntry({kind:"directory",root:{kind:"sandbox"},relativePath:n}),a=await ac(()=>s.handle.list({limit:sc},o),o);return e.registry.describeListedEntries(s,a,sc).map(({name:c,kind:d})=>({name:c,kind:d}))},async read(n,i={}){const o=i.maxBytes??oc;if(!Number.isSafeInteger(o)||o<1||o>oc)throw p("INVALID_PARAMS","诊断读取最多允许 16384 bytes");const s=r(i.signal,"file.readBytes"),a=e.registry.resolveFile({kind:"file",root:{kind:"sandbox"},relativePath:n});if(!a.readPrefix)throw p("DIAGNOSTICS_UNSUPPORTED","当前 Host 不支持有界文件诊断读取");const c=await ac(()=>a.readPrefix({maxBytes:o},s),s);if(!c||!(c.bytes instanceof Uint8Array)||c.bytes.byteLength>o||typeof c.truncated!="boolean")throw p("FILE_IO_FAILED","Host 返回了无效的有界读取结果");return{bytes:new Uint8Array(c.bytes),truncated:c.truncated}}}}function as(e){if(e.signal.aborted)throw p("FILE_ACCESS_REVOKED","诊断文件查询已取消或实例已结束")}async function ac(e,t){let r;try{const n=await Promise.race([e(),new Promise((i,o)=>{r=()=>o(p("FILE_ACCESS_REVOKED","诊断文件查询已取消或实例已结束")),t.signal.addEventListener("abort",r,{once:!0}),t.signal.aborted&&r()})]);return as(t),n}catch(n){throw t.signal.aborted&&as(t),ir(n)}finally{r&&t.signal.removeEventListener("abort",r)}}const $p=new Set(["METHOD_FORBIDDEN","MEDIA_PICKER_CANCELLED","MEDIA_SYSTEM_PERMISSION_DENIED","MEDIA_PREPARE_FAILED","MEDIA_PREVIEW_UNAVAILABLE","REQUEST_UNSUPPORTED","USER_GESTURE_REQUIRED"]),lo={METHOD_FORBIDDEN:"当前 Host 未开放媒体选择能力",MEDIA_PICKER_CANCELLED:"用户取消了媒体选择",MEDIA_SYSTEM_PERMISSION_DENIED:"系统未授予相机或相册权限",MEDIA_PREPARE_FAILED:"媒体准备失败,未保留部分结果",MEDIA_PREVIEW_UNAVAILABLE:"当前 Host 无法提供受控媒体预览",REQUEST_UNSUPPORTED:"当前 Host 不支持该媒体请求形态",USER_GESTURE_REQUIRED:"当前操作需要可信用户手势"};function Kp(e){if(e instanceof ge)return p("REQUEST_UNSUPPORTED",lo.REQUEST_UNSUPPORTED);const t=Vu(e);return t!==void 0&&$p.has(t)?p(t,lo[t]??"媒体操作失败"):p("MEDIA_PREPARE_FAILED",lo.MEDIA_PREPARE_FAILED)}function Vu(e){try{if(!Q(e))return;const t=Object.getOwnPropertyDescriptor(e,"code");return t&&"value"in t&&typeof t.value=="string"?t.value:void 0}catch{return}}const Zp=["source","mediaType","maxCount"],Dn=Object.freeze({source:"album",mediaType:"all",maxCount:1});function Jp(e){if(e===void 0)return Dn;if(!zf(e))throw p("INVALID_PARAMS",ey(e));return Xp(e)}function Xp(e){return Object.freeze({source:e.source??Dn.source,mediaType:e.mediaType??Dn.mediaType,maxCount:e.maxCount??Dn.maxCount})}function ey(e){if(!Q(e))return"media.pick 参数必须是对象";const t=Object.keys(e).filter(r=>!Zp.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 ty=new Set(["METHOD_FORBIDDEN","FILE_QUOTA_EXCEEDED","FILE_ACCESS_REVOKED","FILE_ACCESS_DENIED"]),ry={kind:"file",name:"media-probe",mode:"read",ref:{kind:"file",handleId:"media-probe"}};class ny{constructor(t,r,n){this.registry=t,this.media=r,this.operationContext=n}committed=new Set;disposed=!1;commit(t,r){const n=iy(t,r);let i=[];try{i=this.registerBatch(n,r.maxCount);const o=n.map((s,a)=>sy(s,i[a]));if(!Hf(o))throw $e("Host 返回的媒体结果未通过协议校验");for(const s of n)this.committed.add(s);return o}catch(o){throw this.registry.revokeFiles(i.map(ay).filter(s=>s!==void 0)),o}}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=Vu(n);throw i!==void 0&&ty.has(i)?n:$e("Host 返回的媒体文件资源无法登记为只读句柄")}}releaseItems(t,r){if(t.length!==0)try{const n=this.media.release(t,r);Promise.resolve(n).catch(()=>{})}catch{}}}function cc(e,t){if(e.signal.aborted)throw p("RUNTIME_DESTROYED","小程序 Runtime 已终止");if(t.aborted)throw p("REQUEST_CANCELLED","media.pick 已取消")}function iy(e,t){if(!Array.isArray(e))throw $e("Host 返回了无效媒体选择结果");const r=e.length;if(r===0)throw $e("Host 未返回任何媒体项;用户取消不得作为空数组成功");if(r>t.maxCount)throw $e("Host 返回的媒体项超过本次 maxCount");if(t.source==="camera"&&r!==1)throw $e("相机必须恰好返回 1 项");for(let n=0;n<r;n+=1){if(!Object.prototype.hasOwnProperty.call(e,n))throw $e("Host 返回了稀疏媒体结果");oy(e[n],n)}return e}function oy(e,t){if(!Q(e))throw $e(`第 ${t+1} 项不是对象`);if(!qd({...e,file:ry}))throw $e(`第 ${t+1} 项不符合 media.pick 媒体项契约`);if(!Q(e.file))throw $e(`第 ${t+1} 项缺少文件句柄`)}function sy(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 ay(e){return"handleId"in e.ref?e.ref.handleId:void 0}function $e(e){return p("MEDIA_PREPARE_FAILED",e)}function cy(e){const t=e.media?new ny(e.registry,e.media,e.operationContext):void 0;return{handlers:{[Hr]:async(n,i)=>{const o=Jp(n);uy(i);const s=e.media,a=t;if(!s||typeof s.pick!="function"||!a)throw Ce(Hr);const c=ae(e.operationContext,i.signal);cc(e.operationContext,i.signal);const d=await dy(s,o,c,e.operationContext,i.signal);cc(e.operationContext,i.signal);try{return a.commit(d,o)}catch(u){throw a.releaseBatch(d,c),u}}},dispose(){t?.dispose()}}}async function dy(e,t,r,n,i){try{return await $(()=>e.pick(t,r),r.signal)}catch(o){throw n.signal.aborted?p("RUNTIME_DESTROYED","小程序 Runtime 已终止"):i.aborted?p("REQUEST_CANCELLED","media.pick 已取消"):Kp(o)}}function uy(e){if(!e.trustedUserGesture)throw p("USER_GESTURE_REQUIRED","当前操作需要可信用户手势")}const ln=4294967296;function ly(e){const t=new fy;return t.write(e),t.finish()}class fy{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<ln?(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=hy(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<ln)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/ln),this.view.setUint32(this.offset+4,t),this.offset+=8}writeInt64(t){this.ensureCapacity(8),this.view.setUint32(this.offset,Math.floor(t/ln)),this.view.setUint32(this.offset+4,t),this.offset+=8}}function hy(e){const t=new Uint8Array(my(e));let r=0,n=0;for(;r<e.length;){let i=e.charCodeAt(r++);if(i>=55296&&i<=56319&&r<e.length){const o=e.charCodeAt(r);o>=56320&&o<=57343&&(r+=1,i=((i&1023)<<10)+(o&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 my(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 Gu(e){cs(e);const t=ly(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 cs(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 o of e)cs(o,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[o,s]of i){if(o==="__proto__")throw new Error("extra object key is not supported");cs(s,t+1,r)}r.delete(e)}const gy=["pc","console","mobile"],py=["game","wiki"];function Di(e){throw{code:"INVALID_PARAMS",message:e}}function yy(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function dt(e,t){return typeof e!="string"||!e.trim()?Di(t):e.trim()}function dc(e,t,r){return typeof e!="string"||!t.includes(e)?Di(r):e}function Ey(e){const t={target:"game_detail",appId:dt(e.appId,"navigation.openAppPage appId 必须是非空字符串"),gameType:dc(e.gameType,gy,"navigation.openAppPage gameType 必须是 pc、console 或 mobile")};return e.page!==void 0&&(t.page=dc(e.page,py,"navigation.openAppPage page 必须是 game 或 wiki")),e.hSrc!==void 0&&(t.hSrc=dt(e.hSrc,"navigation.openAppPage hSrc 必须是非空字符串")),e.skuId!==void 0&&(t.skuId=dt(e.skuId,"navigation.openAppPage skuId 必须是非空字符串")),t}function wy(e){return{target:"user_detail",userId:dt(e.userId,"navigation.openAppPage userId 必须是非空字符串")}}function Iy(e){const t={target:"post_detail",linkId:dt(e.linkId,"navigation.openAppPage linkId 必须是非空字符串")};return e.rootCommentId!==void 0&&(t.rootCommentId=dt(e.rootCommentId,"navigation.openAppPage rootCommentId 必须是非空字符串")),e.commentId!==void 0&&(t.commentId=dt(e.commentId,"navigation.openAppPage commentId 必须是非空字符串")),t}function Ay(e){const t={target:"mini_program",miniProgramId:dt(e.miniProgramId,"navigation.openAppPage miniProgramId 必须是非空字符串")};return e.extra!==void 0&&(t.extra=e.extra),t}function Ny(e){return yy(e)?e.target==="game_detail"?Ey(e):e.target==="user_detail"?wy(e):e.target==="post_detail"?Iy(e):e.target==="mini_program"?Ay(e):Di("navigation.openAppPage target 不支持"):Di("navigation.openAppPage options 必须是对象")}function Dy(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 My(e){return{protocolType:"openRouterPath",path:"/user_home",params:{userid:e.userId}}}function Sy(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 _y(e){const t=e;return t.target==="game_detail"?Dy(t):t.target==="user_detail"?My(t):Sy(t)}const by="data:image/svg+xml;base64,PHN2ZyBwcmVzZXJ2ZUFzcGVjdFJhdGlvPSJub25lIiBvdmVyZmxvdz0idmlzaWJsZSIgc3R5bGU9ImRpc3BsYXk6IGJsb2NrOyIgd2lkdGg9IjIwIiBoZWlnaHQ9IjIwIiB2aWV3Qm94PSIwIDAgMjAgMjAiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxnIGlkPSJJY29uIj4KPHBhdGggaWQ9IlVuaW9uIiBkPSJNNS4wMzMzOCAxLjI5Mjg5QzUuNDIzOSAwLjkwMjM2OSA2LjA1NzI0IDAuOTAyMzY5IDYuNDQ3NzYgMS4yOTI4OUM2LjgzODI3IDEuNjgzNDIgNi44MzgyOCAyLjMxNjc2IDYuNDQ3NzYgMi43MDcyN0w1LjIzODQ2IDMuOTE2NThIMTEuNjY2N0MxNS40NDA1IDMuOTE2NzEgMTguNTAwMSA2Ljk3NjIgMTguNTAwMSAxMC43NTAxQzE4LjUgMTQuNTIzOCAxNS40NDA0IDE3LjU4MzQgMTEuNjY2NyAxNy41ODM1SDMuMzMzMzVDMi43ODExMiAxNy41ODM1IDIuMzMzMjcgMTcuMTM1NiAyLjMzMzE5IDE2LjU4MzRDMi4zMzMxOSAxNi4wMzExIDIuNzgxMDcgMTUuNTgzMiAzLjMzMzM1IDE1LjU4MzJIMTEuNjY2N0MxNC4zMzU5IDE1LjU4MzEgMTYuNDk5NyAxMy40MTkzIDE2LjQ5OTggMTAuNzUwMUMxNi40OTk4IDguMDgwNzYgMTQuMzM1OSA1LjkxNzAzIDExLjY2NjcgNS45MTY5SDQuNTkwNjdMNi40NDc3NiA3Ljc3NDhDNi44MzgyMSA4LjE2NTMzIDYuODM4MjYgOC43OTg2OCA2LjQ0Nzc2IDkuMTg5MThDNi4wNTcyNCA5LjU3OTQ1IDUuNDIzODMgOS41Nzk1NiA1LjAzMzM4IDkuMTg5MThMMS43OTI4MyA1Ljk0NzgyQzEuNDAyMzEgNS41NTczIDEuNDAyMzEgNC45MjM5NiAxLjc5MjgzIDQuNTMzNDRMNS4wMzMzOCAxLjI5Mjg5WiIgZmlsbD0id2hpdGUiLz4KPC9nPgo8L3N2Zz4K",Ty="data-hb-sdk-fullscreen-exit",Oy=3e3,vy=2e3,uc="var(--white-70a,rgba(255,255,255,.7))",lc="0 0 var(--space-8,8px) var(--white-20a,rgba(255,255,255,.2))";function Ly(e){if(typeof document>"u"||!document.body)return;const t=document.createElement("button");t.type="button",t.setAttribute(Ty,""),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 ${uc}`,`box-shadow:${lc}`,"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=by,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 o=!0,s=!1,a=!1,c,d;function u(){return window.innerWidth>window.innerHeight?"var(--space-12,12px)":"var(--space-8,8px)"}function l(){o||(t.style.width=u())}function f(){d?.cancel(),d=void 0}function m(I=vy){clearTimeout(c),c=setTimeout(()=>{f(),o=!1,t.style.width=u(),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")},I)}function h(){f(),o=!0,t.style.width="48px",t.style.opacity="1",t.style.borderColor=uc,t.style.boxShadow=lc,n.style.visibility="",i.style.display="",t.setAttribute("aria-label","退出全屏"),t.setAttribute("aria-expanded","true"),m()}async function g(){if(!(s||a)){if(!o){h();return}a=!0,clearTimeout(c),f();try{await e()}catch{}finally{a=!1,s||h()}}}return t.addEventListener("click",g),window.addEventListener("resize",l),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"})),m(Oy),{dispose(){s=!0,clearTimeout(c),f(),t.removeEventListener("click",g),window.removeEventListener("resize",l),t.remove()}}}const qu=1e4;function Qu(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 o=setTimeout(()=>{n??={code:"ORIENTATION_TIMEOUT",message:"方向切换超时"},r.abort()},qu);return{signal:r.signal,async run(s){try{return await $(s,r.signal)}catch(a){throw n??a}},dispose(){clearTimeout(o),e.removeEventListener("abort",i),t?.removeEventListener("abort",i)}}}function fc(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 fo(e,t){return e.mode===t.mode&&e.hideCapsule===t.hideCapsule}function wr(){return{code:"REQUEST_CANCELLED",message:"方向设置已取消"}}function Cy(e){let t=0,r=0,n,i,o={mode:"portrait",hideCapsule:!1},s={mode:"portrait",hideCapsule:!1},a;function c(){a?.dispose(),a=void 0}function d(h){if(!h.hideCapsule){c();return}a??=Ly(()=>m.apply({orientation:"portrait",fullscreen:!1},void 0,"user"))}e.operationContext.signal.addEventListener("abort",c,{once:!0});function u(h,g){if(n===h){if(n=void 0,clearTimeout(h.timer),e.operationContext.signal.removeEventListener("abort",l),"error"in g)h.controller.abort();else if(i={options:h.options,result:g.result},o=h.options,d(h.options),e.onApplied?.(h.options),g.result.supported&&!fo(s,h.options)){s={...h.options};try{e.onDisplayChange?.({orientation:s.mode,fullscreen:s.hideCapsule,source:h.source})}catch{}}for(const I of h.subscribers)I.dispose(),"error"in g?I.reject(g.error):I.resolve(g.result);h.subscribers.clear()}}function l(){n&&u(n,{error:wr()})}function f(h,g){return new Promise((I,y)=>{const b=()=>{h.subscribers.delete(_),_.dispose(),y(wr()),h.subscribers.size===0&&u(h,{error:wr()})},_={resolve:I,reject:y,dispose:()=>g?.removeEventListener("abort",b)};h.subscribers.add(_),g?.addEventListener("abort",b,{once:!0}),g?.aborted&&b()})}const m={async runDisplayRequest(h,g,I){const y=++t,b=Qu(g,e.operationContext.signal);try{return await b.run(async()=>{if(await I(b.signal),b.signal.aborted)throw wr();if(fc(h),y<r)throw{code:"ORIENTATION_SUPERSEDED",message:"方向设置已被后续设置替换"};return r=y,m.apply(h,b.signal)})}finally{b.dispose()}},async apply(h,g,I="api"){if(X(e.operationContext.signal),g?.aborted)throw wr();const y=fc(h),b=n?.options??o,_={mode:y.orientation??b.mode,hideCapsule:y.fullscreen??b.hideCapsule};_.mode==="landscape"&&(_.hideCapsule=!0);const P=e.presentation.applyOrientation;if(!P)throw{code:"METHOD_FORBIDDEN",message:"当前宿主暂不支持方向控制"};if(n&&fo(n.options,_))return f(n,g);if(n&&u(n,{error:{code:"ORIENTATION_SUPERSEDED",message:"方向设置已被后续设置替换"}}),i&&fo(i.options,_))return i.result;i=void 0;const j={options:_,source:I,controller:new AbortController,subscribers:new Set};n=j;const U=f(j,g);return e.operationContext.signal.addEventListener("abort",l,{once:!0}),g||(j.timer=setTimeout(()=>{u(j,{error:{code:"ORIENTATION_TIMEOUT",message:"方向切换超时"}})},qu)),$(()=>P.call(e.presentation,_,{...e.operationContext,signal:j.controller.signal}),j.controller.signal).then(O=>u(j,{result:O??{supported:!0}}),O=>u(j,{error:O})),U},dispose(){e.operationContext.signal.removeEventListener("abort",c),c()}};return m}function Yu(e){throw{code:"INVALID_PARAMS",message:e}}function hc(e,t){e!==void 0&&(typeof e!="object"||e===null||Array.isArray(e)||Object.keys(e).length)&&Yu(`${t} 不支持参数`)}function Ry(e){return{[mi]:async(t,r)=>{const n=ae(e.operationContext,r.signal,r.requestId);X(n.signal),hc(t,"navigation.close"),await $(()=>e.presentation.close(n),n.signal)},[gi]:async(t,r)=>{const n=ae(e.operationContext,r.signal,r.requestId);X(n.signal),hc(t,"navigation.reload"),await $(()=>e.presentation.reload(n),n.signal)},[pi]:async(t,r)=>{const n=ae(e.operationContext,r.signal,r.requestId);X(n.signal);const i=Ny(t);if(i.target==="mini_program"){let o;if(i.extra!==void 0)try{o=Gu(i.extra)}catch{Yu("navigation.openAppPage extra 必须是符合限制的 JSON-compatible 数据")}const s=e.resetDisplay;if(s){const a=Qu(n.signal);try{await a.run(()=>s(a.signal))}finally{a.dispose()}}X(n.signal),await $(()=>e.presentation.openWindow({miniProgramId:i.miniProgramId,...o===void 0?{}:{extra:o}},n),n.signal);return}await $(()=>e.presentation.openAppPage(_y(i),n),n.signal)}}}const mc={UPLOAD_CANCELLED:"上传已取消",UPLOAD_TIMEOUT:"上传空闲超时",UPLOAD_NETWORK_FAILED:"上传网络失败",FILE_CHANGED:"上传源文件已变化",METHOD_FORBIDDEN:"当前 Host 未开放上传能力"};async function Py(e,t,r){const n=r.transfer?.upload,i=r.fileRegistry;if(!n||!i)throw Ce("network.upload");const o=ae(r.operationContext,t.signal),s=()=>{if(o.signal.aborted)throw p("UPLOAD_CANCELLED","上传已取消")};s();let a,c;try{a=i.resolveFileEntry(e.from).hostHandle,c=await a.stat(o)}catch(f){throw s(),ir(f)}if(s(),c.kind!=="file"||!Number.isSafeInteger(c.size)||c.size<0)throw p("FILE_IO_FAILED","上传源文件状态无效");if(e.maxBytes!==void 0&&c.size>e.maxBytes)throw p("FILE_TOO_LARGE","文件超过大小限制");let d=0,u=!1;const l=f=>{u||o.signal.aborted||!Number.isSafeInteger(f)||f<d||f>c.size||(d=f,t.postProgress({loaded:d,total:c.size,lengthComputable:!0}))};try{const{from:f,...m}=e,h=await n.upload(a,{...m,expectedBytes:c.size,...e.format==="multipart"?{fileName:e.fileName??a.name}:{}},{...o,onProgress:l});if(u=!0,!Number.isSafeInteger(h.uploadedBytes)||h.uploadedBytes<d||h.uploadedBytes>c.size)throw p("UPLOAD_NETWORK_FAILED","Host 返回的上传字节数无效");if(h.status>=200&&h.status<300&&h.uploadedBytes!==c.size)throw p("FILE_CHANGED","上传源文件已变化");return t.postProgress({loaded:h.uploadedBytes,total:c.size,lengthComputable:!0}),h}catch(f){u=!0;const m=Bs(f);throw m&&mc[m]?p(m,mc[m]):o.signal.aborted?p("UPLOAD_CANCELLED","上传已取消"):m?.startsWith("FILE_")||m?.startsWith("DIRECTORY_")?ir(f):p("UPLOAD_NETWORK_FAILED","上传网络失败")}}const Ys="withCredentials",ky=new Set(["url","method","params","data","headers","timeout",Ys]),xy=new Set(["url","to","params","headers","timeout","suggestedName","overwrite","maxBytes",Ys]),Uy=new Set(["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"]),gc=3e4,ds=2*1024*1024,jy=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,Wu=/[\u0000-\u0008\u000A-\u001F\u007F]/,zy=/^(?:authorization|authentication-info|proxy-authentication-info|cookie|set-cookie|set-cookie2|pkey|x-pkey|x-access-token|x-auth-token)$/i,Hy="network.request 不支持 multipart/form-data,请使用专用上传能力";function Fy(e){const t=By(e.runtimePermissions);t.networkPolicy=nu(e.networkPolicy);const r=rE(e.allowedHttpOrigins);return{[Jn]:async(n,i)=>{const o=Gy(n,{permission:t,allowedHttpOrigins:r}),s=await Py(o,i,e),{uploadedBytes:a,...c}=s;return yc(c)},[Zn]:async(n,i)=>{const o=qy(n,{permission:t,allowedHttpOrigins:r});return Cu(o,i,{transfer:e.transfer,fileRegistry:e.fileRegistry,operationContext:e.operationContext})},[Kn]:async(n,i)=>{const o=ae(e.operationContext,i?.signal);X(o.signal);const s=Vy(n,{permission:t,allowedHttpOrigins:r});let a;try{a=await $(()=>e.network.request(s,o),o.signal)}catch(c){throw iE(c)?c:oE(c,"REQUEST_UNSUPPORTED")?W("REQUEST_UNSUPPORTED","当前 Host 不支持该网络请求"):W("REQUEST_FAILED","网络请求失败")}return yc(a)}}}function By(e){const t=je(e),r=t.permissions.network;return{enabled:t.valid&&r?.status==="enabled",useOfficialDomain:t.valid&&r?.status==="enabled"&&r.config.useOfficialDomain===!0}}function Vy(e,t){const r=or(e,"network.request 参数必须是对象"),n=Object.keys(r).filter(c=>!ky.has(c));if(n.length>0)throw W("INVALID_PARAMS",`network.request 不支持字段: ${n.join(", ")}`);$u(r,"network.request");const i=Ws(r,t,"network.request"),o=Yy(r.method),s=r.data;s!==void 0&&Ky(s),Jy(i.headers,s);const a=Xy(i.headers,s,i.official);return{source:"public-sdk",target:{kind:"absolute-url",url:i.url.href},redirectPolicy:"error",route:i.official?"official":"external",...o===void 0?{}:{method:o},...i.params===void 0?{}:{params:i.params},...s===void 0?{}:{data:s},...i.headers===void 0?{}:{headers:i.headers},...a===void 0?{}:{bodyEncoding:a},...i.timeout===void 0?{}:{timeout:i.timeout}}}function Gy(e,t){const r=or(e,"network.upload 参数必须是对象"),n=new Set(["url","from","format","method","params","headers","timeout","maxBytes","fieldName","fields","fileName","contentType"]);if(Object.keys(r).some(u=>!n.has(u)))throw W("INVALID_PARAMS","network.upload 包含不支持的字段");const i=Ws(r,t,"network.upload");if(i.official)throw W("PERMISSION_DENIED","上传暂不支持官方域名");if(i.timeout!==void 0&&i.timeout<=0)throw W("INVALID_PARAMS","上传 timeout 必须是有限正数");if(!tr(r.from))throw W("INVALID_PARAMS","from 必须是有效 File ref");if(r.maxBytes!==void 0&&(!Number.isSafeInteger(r.maxBytes)||r.maxBytes<=0))throw W("INVALID_PARAMS","maxBytes 必须是正的 safe integer");if(r.format!=="raw"&&r.format!=="multipart")throw W("INVALID_PARAMS","format 必须是 raw 或 multipart");const o=r.method??(r.format==="raw"?"PUT":"POST");if(o!=="POST"&&(r.format!=="raw"||o!=="PUT"))throw W("INVALID_PARAMS","上传 HTTP 方法不支持");const s={from:r.from,format:r.format,request:{source:"public-sdk",target:{kind:"absolute-url",url:i.url.href},redirectPolicy:"error",route:"upload",method:o,...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(u=>r[u]!==void 0))throw W("INVALID_PARAMS","raw 不接受 multipart 字段");return s}if(Object.keys(i.headers??{}).some(u=>u.toLowerCase()==="content-type"))throw W("INVALID_PARAMS","multipart Content-Type 由 Host 生成");const a=pc(r.fieldName),c=r.fields===void 0?void 0:or(r.fields,"fields 必须是字符串字典");for(const[u,l]of Object.entries(c??{}))if(pc(u),typeof l!="string"||u===a)throw W("INVALID_PARAMS","fields 必须是字符串且不得与文件字段重名");if(r.fileName!==void 0&&typeof r.fileName!="string")throw W("INVALID_PARAMS","fileName 必须是字符串");if(r.contentType!==void 0&&(typeof r.contentType!="string"||Wu.test(r.contentType)||!/^[^\s/;]+\/[^\s;]+(?:;[^\r\n]*)?$/.test(r.contentType)))throw W("INVALID_PARAMS","contentType 必须是有效 MIME type");const d={fieldName:a,fields:c,fileName:r.fileName,contentType:r.contentType};if(new TextEncoder().encode(JSON.stringify(d)).byteLength>ds)throw W("INVALID_PARAMS","multipart 元数据超过 2 MiB");return{...s,fieldName:a,...c===void 0?{}:{fields:{...c}},...r.fileName===void 0?{}:{fileName:Gs(r.fileName)},contentType:r.contentType??"application/octet-stream"}}function pc(e){if(typeof e!="string"||!e||/[\u0000-\u001F\u007F"\\]/.test(e))throw W("INVALID_PARAMS","multipart 字段名必须是非空且无控制字符的字符串");return e}function qy(e,t){const r=or(e,"network.download 参数必须是对象"),n=Object.keys(r).filter(c=>!xy.has(c));if(n.length>0)throw W("INVALID_PARAMS",`network.download 不支持字段: ${n.join(", ")}`);$u(r,"network.download");const i=Ws(r,t,"network.download");if(i.timeout!==void 0&&i.timeout<=0)throw W("INVALID_PARAMS","network.download timeout 必须是有限正数");fp(i.headers);const o=tr(r.to),s=Vd(r.to);if(!o&&!s)throw W("INVALID_PARAMS","network.download to 必须是有效 File/Directory ref");if(o&&(r.suggestedName!==void 0||r.overwrite!==void 0))throw W("INVALID_PARAMS","File 下载目标不接受 suggestedName/overwrite");let a;if(r.suggestedName!==void 0){if(typeof r.suggestedName!="string")throw W("INVALID_PARAMS","suggestedName 必须是字符串");a=Gs(r.suggestedName)}if(r.overwrite!==void 0&&typeof r.overwrite!="boolean")throw W("INVALID_PARAMS","overwrite 必须是布尔值");if(r.maxBytes!==void 0&&(!Number.isSafeInteger(r.maxBytes)||r.maxBytes<=0))throw W("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:o?"file":"directory",...a===void 0?{}:{suggestedName:a},...r.overwrite===void 0?{}:{overwrite:r.overwrite},...r.maxBytes===void 0?{}:{maxBytes:r.maxBytes}}}function Ws(e,t,r){const n=Qy(e.url,t.allowedHttpOrigins,r),i=t.permission.networkPolicy,o=i?.enforcement==="approved_domains"&&n.protocol==="http:"&&t.allowedHttpOrigins.has(n.origin);if(i&&!o&&(n.protocol!=="https:"||n.port!==""||!i.entries.some(a=>a.domain===n.hostname.toLowerCase())))throw W("PERMISSION_DENIED",`${r} 目标不在平台批准的域名清单中`);const s=bh(n);if(s&&!t.permission.useOfficialDomain)throw W("PERMISSION_DENIED","当前小程序暂不支持访问官方域名");if(_h(n.pathname,s))throw W("PERMISSION_DENIED",`${r} 不允许访问 Runtime 或账号敏感接口`);return{url:n,official:s,params:e.params===void 0?void 0:{...or(e.params,`${r} params 必须是对象`)},headers:e.headers===void 0?void 0:Wy(e.headers,r),timeout:$y(e.timeout,r)}}function Qy(e,t,r="network.request"){if(typeof e!="string"||!e.trim())throw W("INVALID_PARAMS",`${r} url 必须是 HTTP(S) URL`);let n;try{n=new URL(e)}catch{throw W("INVALID_PARAMS",`${r} url 必须是 HTTP(S) URL`)}if(n.protocol!=="http:"&&n.protocol!=="https:")throw W("INVALID_PARAMS",`${r} url 必须是 HTTP(S) URL`);if(n.username||n.password)throw W("INVALID_PARAMS",`${r} url 不允许包含用户信息`);if(n.protocol==="http:"&&!t.has(n.origin))throw W("PERMISSION_DENIED",`${r} 生产环境只允许 HTTPS`);return n}function Yy(e){if(e===void 0)return;if(typeof e!="string"||!e.trim())throw W("INVALID_PARAMS","network.request method 必须是字符串");const t=e.trim().toUpperCase();if(!Uy.has(t))throw W("INVALID_PARAMS","network.request method 不合法");return t}function Wy(e,t="network.request"){const r=or(e,`${t} headers 必须是 Record<string, string>`),n={};for(const[i,o]of Object.entries(r)){const s=i.trim();if(!s||s!==i||!jy.test(s)||typeof o!="string"||Wu.test(o))throw W("INVALID_PARAMS",`${t} headers 必须是 Record<string, string>`);if(Th(s))throw W("INVALID_PARAMS",`${t} 不允许设置敏感请求头: ${i}`);n[s]=o}return n}function $u(e,t){const r=e[Ys];if(r!==void 0&&typeof r!="boolean")throw W("INVALID_PARAMS",`${t} 旧版凭据字段必须是布尔值`)}function $y(e,t="network.request"){if(e!==void 0){if(typeof e!="number"||!Number.isFinite(e)||e<0)throw W("INVALID_PARAMS",`${t} timeout 必须是非负数字`);if(t==="network.request"&&e>gc)throw W("INVALID_PARAMS",`${t} timeout 不能超过 ${gc}ms`);return e}}function Ky(e){if(typeof Blob<"u"&&e instanceof Blob||typeof FormData<"u"&&e instanceof FormData)throw W("INVALID_PARAMS","network.request data 不支持 File、Blob 或 FormData,请使用专用上传能力");if(Zy(e)>ds)throw W("INVALID_PARAMS",`network.request data 不能超过 ${ds} 字节`)}function Zy(e){if(typeof e=="string")return ho(e);if(e instanceof ArrayBuffer||ArrayBuffer.isView(e))return e.byteLength;if(typeof URLSearchParams<"u"&&e instanceof URLSearchParams)return ho(e.toString());try{const t=JSON.stringify(e);return t?ho(t):0}catch{throw W("INVALID_PARAMS","network.request data 必须可序列化")}}function Jy(e,t){const r=Ku(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 W("INVALID_PARAMS",Hy)}function Xy(e,t,r){if(t===void 0)return;const n=Ku(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)||tE(t))?"form":eE(t)?"json":void 0}function Ku(e){return e?Object.entries(e).find(([r])=>r.trim().toLowerCase()==="content-type")?.[1].toLowerCase():void 0}function eE(e){return e===null||typeof e=="boolean"||typeof e=="number"||typeof e=="object"&&!ArrayBuffer.isView(e)&&!(e instanceof ArrayBuffer)}function tE(e){if(typeof e!="object"||e===null)return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function rE(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&&nE(n.hostname)&&t.add(n.origin)}catch{}return t}function nE(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 yc(e){return Object.keys(e.headers).some(Ec)?{...e,headers:Object.fromEntries(Object.entries(e.headers).filter(([t])=>!Ec(t)))}:e}function Ec(e){const t=e.trim().toLowerCase();return zy.test(t)||t.startsWith("x-heybox-")||t.startsWith("x-xhh-")}function iE(e){return e instanceof Error&&e.name==="AbortError"}function oE(e,t){return typeof e=="object"&&e!==null&&"code"in e&&e.code===t}function or(e,t){if(typeof e!="object"||e===null||Array.isArray(e))throw W("INVALID_PARAMS",t);return e}function ho(e){return new TextEncoder().encode(e).length}function W(e,t){return{code:e,message:t}}function sE(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function aE(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 cE(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 o=aE(i);o?r.has(o)||(r.add(o),n.push(o)):t.push("post.topicIds 每项必须是正整数或非空字符串")}return{invalidMessages:t,values:n}}function dE(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 o=typeof i=="string"?i.trim():"";!o||o.startsWith("#")||o.endsWith("#")?t.push("post.topics 每项必须是不含首尾 # 的非空字符串"):r.has(o)||(r.add(o),n.push(o))}return{invalidMessages:t,values:n}}function Zu(e,t){if(e==null)return{};if(!sE(e))return{invalidMessage:`${t.method} post 必须是对象或 null`};const r=cE(e.topicIds),n=dE(e.topics),i=[...r.invalidMessages,...n.invalidMessages];let o=r.values;t.maxTopicIds!==void 0&&o.length>t.maxTopicIds&&(i.push(`${t.method} post.topicIds 最多允许 ${t.maxTopicIds} 项`),o=o.slice(0,t.maxTopicIds));const s=o.length||n.values.length?{...o.length?{topicIds:o}:{},...n.values.length?{topics:n.values}:{}}:void 0;return s||i.push(`${t.method} post 至少需要一个有效的 topicIds 或 topics`),{invalidMessage:i[0],post:s}}function uE(e){try{return new URL(e).protocol==="heybox-mini-dev:"}catch{return!1}}async function lE(e){try{if(uE(e.getCurrentHref()))return!0}catch{}try{return!!await e.isDevRuntime()}catch{return!1}}function pe(e){throw{code:"INVALID_PARAMS",message:e}}function Zr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function us(e,t){return typeof e!="string"||!e.trim()?pe(t):e}function fE(e,t){const r=us(e,t);try{const n=new URL(r);return n.protocol!=="http:"&&n.protocol!=="https:"?pe(t):r}catch{return pe(t)}}function hE(e){return e==="wechatSession"||e==="wechatTimeline"||e==="qqFriend"||e==="qzone"||e==="weibo"}function Ju(e,t,r){const n=e.identity.get(),i=n?.miniProgramId.trim();if(!i)return pe(`${t} 缺少有效的小程序分享地址`);try{const o=new URL(e.environment.getCurrentHref()),s=new URL("/tools/common_share",o);s.searchParams.set("user_miniprogram_id",i);const a=n?.version?.trim();a&&s.searchParams.set("miniprogram_version",a);const c=o.searchParams.get("h_src");return c?.trim()&&s.searchParams.set("h_src",c),r!==void 0&&s.searchParams.set("extra",r),s.href}catch{return pe(`${t} 缺少有效的小程序分享地址`)}}function mE(e,t){if(!Zr(e))return pe("share.showShareMenu 参数必须是对象");if(Object.prototype.hasOwnProperty.call(e,"url"))return pe("share.showShareMenu 不支持自定义 url");const r=e.channel;if(r!==void 0&&!hE(r))return pe("share.showShareMenu channel 不合法");const n=Xu(e.extra,"share.showShareMenu");return{title:us(e.title,"share.showShareMenu title 必须是非空字符串"),description:us(e.desc,"share.showShareMenu desc 必须是非空字符串"),url:Ju(t,"share.showShareMenu",n),...e.imageUrl===void 0?{}:{imageUrl:fE(e.imageUrl,"share.showShareMenu imageUrl 必须是 HTTP(S) URL")},...r===void 0?{}:{channel:r}}}function Xu(e,t){if(e!==void 0)try{return Gu(e)}catch{return pe(`${t} extra 必须是符合限制的 JSON-compatible 数据`)}}async function el(e,t){return e.invalidMessage&&await $(()=>lE(t.environment),t.operationContext.signal)?pe(e.invalidMessage):e.post}function wc(e,t){const r=Number(e);return Number.isFinite(r)&&r>0?r:t}function gE(e){const t=e.getViewportMetrics();return{left:0,top:0,width:wc(t.windowWidth,0),height:wc(t.windowHeight,0)}}function ls(e,t){const r=Number(e);return!Number.isFinite(r)||r<0?pe(t):r}function Ic(e,t){const r=Number(e);return!Number.isFinite(r)||r<=0?pe(t):r}function pE(e){return Zr(e)?{left:ls(e.left,"share.screenshot rect.left 必须是非负数字"),top:ls(e.top,"share.screenshot rect.top 必须是非负数字"),width:Ic(e.width,"share.screenshot rect.width 必须是正数"),height:Ic(e.height,"share.screenshot rect.height 必须是正数")}:pe("share.screenshot rect 必须是对象")}function Ac(e,t){if(e!=null&&!Zr(e))return pe("share.screenshot 参数必须是对象");const r=e??{};return r.saveToAlbum!==void 0&&typeof r.saveToAlbum!="boolean"?pe("share.screenshot saveToAlbum 必须是布尔值"):r.watermarkTheme!==void 0&&r.watermarkTheme!=="light"&&r.watermarkTheme!=="dark"?pe("share.screenshot watermarkTheme 必须是 light 或 dark"):{watermarkTheme:r.watermarkTheme??"dark",rect:r.rect===void 0?gE(t):pE(r.rect),...r.delay===void 0?{}:{delay:ls(r.delay,"share.screenshot delay 必须是非负数字")},...r.saveToAlbum===void 0?{}:{saveToAlbum:r.saveToAlbum}}}async function yE(e,t){X(t.operationContext.signal);const r=mE(e,t);let n=Zu(e.post,{maxTopicIds:1,method:"share.showShareMenu"});r.channel&&n.post&&(n={invalidMessage:n.invalidMessage||"share.showShareMenu channel 与 post 不能同时使用"});const i=await el(n,t);return $(()=>t.presentation.showShareMenu({...r,post:i},t.operationContext),t.operationContext.signal)}async function EE(e,t){if(X(t.operationContext.signal),e!==void 0&&!Zr(e))return pe("share.copyLink 参数必须是对象");const r=Xu(e?.extra,"share.copyLink"),n=Ju(t,"share.copyLink",r);return await $(()=>t.presentation.setClipboard({text:n},t.operationContext),t.operationContext.signal),n}async function Nc(e,t,r,n=!1){X(t.operationContext.signal);const i=Zu(Zr(e)?e.post:void 0,{method:"share.screenshot"}),o=await el(i,t),s=t.identity.get()?.miniProgramId.trim()||void 0,a=wE(),{watermarkTheme:c,...d}=r;let u=!1,l,f,m;try{if(n&&(!t.presentation.supportsLongScreenshot||!t.prepareLongScreenshot))throw{code:"REQUEST_UNSUPPORTED",message:"当前宿主不支持 DOM 长图,请更新宿主"};if(u=!0,await $(()=>t.presentation.setScreenshotChromeHidden(!0,t.operationContext),t.operationContext.signal),n){const I=await t.prepareLongScreenshot(r.rect,t.operationContext.signal);l=I.restore,d.rect=I.rect}f=await t.prepareScreenshot?.(d.rect,t.operationContext.signal,c),m={status:"fulfilled",value:await $(()=>t.presentation.captureAndShare({...d,...n?{longContent:!0}:{},post:o,...s?{sourceMiniProgramId:s}:{}},t.operationContext),t.operationContext.signal)}}catch(g){m={status:"rejected",error:g}}finally{try{f?.()}finally{l?.()}}const h=u?await IE(t.presentation,a,t.operationContext.signal):void 0;if(m.status==="rejected")throw m.error;if(h)throw h;return m.value}function wE(){return{lifecycle:"cleanup",signal:new AbortController().signal}}async function IE(e,t,r){let n;try{n=Promise.resolve(e.setScreenshotChromeHidden(!1,t))}catch{return}try{await $(()=>n,r,{invokeWhenAborted:!0})}catch(i){if(r.aborted)return i}}function AE(e){let t=Promise.resolve();const r=async(n,i)=>{const o=ae(e.operationContext,i.signal,i.requestId),s=Ac(n,e.presentation);(s.rect.top+s.rect.height>1e4||s.rect.left+s.rect.width>2048||s.rect.width*s.rect.height>4e6)&&pe("长图尺寸超出限制");const a=t.then(()=>Nc(n,{...e,operationContext:o},s,!0));return t=a.then(()=>{},()=>{}),a};return{[Yn]:r,[Gn]:(n,i)=>EE(n,{...e,operationContext:ae(e.operationContext,i.signal,i.requestId)}),[qn]:(n,i)=>yE(n,{...e,operationContext:ae(e.operationContext,i.signal,i.requestId)}),[Qn]:async(n,i)=>{const o=ae(e.operationContext,i.signal,i.requestId);X(o.signal);const s=Ac(n,e.presentation),a=t.then(()=>Nc(n,{...e,operationContext:o},s));return t=a.then(()=>{},()=>{}),$(()=>a,o.signal)}}}const Dc=new WeakMap;function tl(e){const t=e.canonicalIdentity?.miniProgramId?.trim();if(t)return rh(t);const r=e.anonymousStorageScope?.trim();if(r)return`anon_${Xd(r)}`;throw Object.assign(new Error("storage scope 只能在 canonical identity 绑定后使用"),{code:"INVALID_STATE"})}function rl(e){const t=e.coordinationKey??e.storage;let r;const n=()=>r??=Promise.resolve().then(e.resolveScope).catch(c=>{throw r=void 0,c}),i=async(c,d)=>{const u=await n();let l=Dc.get(t);l||(l=new Map,Dc.set(t,l));const f=l.get(u)??Promise.resolve(),m=async()=>(X(c.signal,{preserveReason:!0}),d(u)),h=f.catch(()=>{}).then(()=>e.lock?e.lock(u,m):m());l.set(u,h);try{return await h}finally{l.get(u)===h&&l.delete(u)}},o=async(c,d,u=!1)=>{const l=kt(c,"");if(e.diagnostics)return[...new Set((await e.diagnostics.listRaw(d)).filter(h=>h.key.startsWith(l)&&h.value!=="").map(h=>h.key.slice(l.length)))];const f=await e.storage.getRaw(sn(c),d);if((f===void 0||f==="")&&!u)throw Object.assign(new Error("当前客户端缺少数据索引,且不支持遍历本地数据,暂无法清理"),{code:"STORAGE_INDEX_MISSING"});let m;try{m=f?JSON.parse(f):[]}catch{throw new Error("本地数据索引异常")}if(!Array.isArray(m)||m.length>ma||m.some(h=>typeof h!="string"||!/^[A-Za-z0-9_-]{1,128}$/.test(h)))throw new Error("本地数据索引异常");return[...new Set(m)]},s=async(c,d)=>{if(e.diagnostics){const f=kt(c,"");return(await e.diagnostics.listRaw(d)).filter(m=>m.key.startsWith(f)&&m.value!=="").map(m=>({...m,key:m.key.slice(f.length)}))}const u=[],l=await o(c,d);for(let f=0;f<l.length;f+=16){X(d.signal,{preserveReason:!0});const m=await Promise.all(l.slice(f,f+16).map(async h=>{const g=await e.storage.getRaw(kt(c,h),d);return g!==void 0&&g!==""?{area:"local",key:h,value:g}:void 0}));for(const h of m)h&&u.push(h)}return u},a=c=>{if(!/^[A-Za-z0-9_-]{1,128}$/.test(c))throw Object.assign(new Error("storage key 不合法"),{code:"INVALID_REQUEST"})};return{get(c,d){return a(c),i(d,u=>e.storage.getRaw(kt(u,c),d))},set(c,d,u){return a(c),i(u,async l=>{const f=await o(l,u,!0);if(!f.includes(c)&&f.length>=ma)throw Object.assign(new Error("storage key 数量超出上限"),{code:"STORAGE_QUOTA_EXCEEDED"});if(!e.diagnostics){const m=[...new Set([...f,c])];await e.storage.setRaw(sn(l),JSON.stringify(m),u)}X(u.signal,{preserveReason:!0}),await e.storage.setRaw(kt(l,c),d,u),X(u.signal,{preserveReason:!0})})},list(c){return i(c,d=>s(d,c))},clear(c){return i(c,async d=>{const u=await o(d,c);e.diagnostics||await e.storage.setRaw(sn(d),JSON.stringify(u),c);for(let l=0;l<u.length;l+=16){X(c.signal,{preserveReason:!0});const m=(await Promise.allSettled(u.slice(l,l+16).map(h=>e.storage.setRaw(kt(d,h),"",c)))).find(h=>h.status==="rejected");if(m)throw m.reason}X(c.signal,{preserveReason:!0}),await e.storage.setRaw(sn(d),"[]",c)})}}}function NE(e,t){return typeof navigator<"u"&&navigator.locks?new Promise((r,n)=>{navigator.locks.request(`hb-miniprogram-storage:${e}`,()=>t().then(r,n)).catch(n)}):t()}const DE=128,ME=/^[A-Za-z0-9_-]+$/;function SE(e){const t=e.scopedStorage??rl({storage:e.storage,resolveScope:()=>tl({canonicalIdentity:e.identity.get(),anonymousStorageScope:e.anonymousStorageScope}),diagnostics:e.storageDiagnostics}),r={[Cr]:async n=>{X(e.operationContext.signal);const i=Mc(n,Cr,e.storageLimits?.maxKeyLength),o=await $(()=>t.get(i,e.operationContext),e.operationContext.signal);return{data:Sc(o)}},[Rr]:async n=>{X(e.operationContext.signal);const i=nl(n,"storage.setStorage 参数必须是对象"),o=Mc(i,Rr,e.storageLimits?.maxKeyLength),s=_E(i.data,e.storageLimits?.maxValueBytes);await $(()=>t.set(o,s,e.operationContext),e.operationContext.signal)}};return!e.storageDiagnostics&&!e.scopedStorage?{handlers:r}:{handlers:r,diagnostics:{getSnapshot:async()=>(X(e.operationContext.signal),(await $(()=>t.list(e.operationContext),e.operationContext.signal).catch(i=>{throw i&&typeof i=="object"&&"code"in i&&i.code==="INVALID_STATE"?St("STORAGE_DIAGNOSTICS_NOT_READY","Storage diagnostics 只能在 canonical identity 绑定后使用"):i})).map(i=>{const o=i.value;return{area:i.area,key:i.key,value:Sc(o),serializedValue:o,bytes:il(o)}}).sort((i,o)=>i.key.localeCompare(o.key)))}}}function Mc(e,t,r=DE){const i=nl(e,`${t} 参数必须是对象`).key;if(typeof i!="string")throw St("INVALID_PARAMS",`${t} key 必须是字符串`);if(!i||i.length>r||!ME.test(i))throw St("INVALID_PARAMS",`storage key 仅支持 1-${r} 位字母、数字、下划线和连字符`);return i}function _E(e,t){let r;try{r=JSON.stringify(e)}catch{throw St("INVALID_PARAMS","storage.setStorage data 必须可 JSON 序列化")}if(typeof r!="string")throw St("INVALID_PARAMS","storage.setStorage data 必须可 JSON 序列化");if(t!==void 0&&il(r)>t)throw St("STORAGE_QUOTA_EXCEEDED",`storage.setStorage data 超出 ${t} 字节限制`);return r}function Sc(e){if(!(e===void 0||e===""))try{return JSON.parse(e)}catch{return e}}function nl(e,t){if(typeof e!="object"||e===null||Array.isArray(e))throw St("INVALID_PARAMS",t);return e}function il(e){return new TextEncoder().encode(e).length}function St(e,t){return{code:e,message:t}}const _c=120;function ot(e){throw{code:"INVALID_PARAMS",message:e}}function $s(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ol(e,t,r){const n=Object.keys(e).filter(i=>!t.includes(i));n.length&&ot(`${r} 不支持字段: ${n.join(", ")}`)}function bE(e){if(!$s(e))return ot("ui.showToast 参数必须是对象");if(ol(e,["message","status"],"ui.showToast"),typeof e.message!="string"||!e.message.trim())return ot("ui.showToast message 必须是非空字符串");const t=e.message.trim();if(t.length>_c)return ot(`ui.showToast message 不能超过 ${_c} 字符`);const r=e.status;if(r!==void 0&&r!=="success"&&r!=="error")return ot("ui.showToast status 必须是 success 或 error");const n=r;return{message:t,...n===void 0?{}:{status:n}}}function TE(e){return e===void 0?{dismissible:!1}:$s(e)?(ol(e,["dismissible"],"ui.showLoading"),e.dismissible!==void 0&&typeof e.dismissible!="boolean"?ot("ui.showLoading dismissible 必须是布尔值"):{dismissible:e.dismissible??!1}):ot("ui.showLoading 参数必须是对象")}function OE(e){e!==void 0&&(!$s(e)||Object.keys(e).length)&&ot("ui.hideLoading 不支持参数")}function vE(e){return{[ci]:async(t,r)=>{const n=ae(e.operationContext,r.signal,r.requestId);X(n.signal),await $(()=>e.presentation.showToast(bE(t),n),n.signal)},[di]:async(t,r)=>{const n=ae(e.operationContext,r.signal,r.requestId);X(n.signal),await $(()=>e.presentation.showLoading(TE(t),n),n.signal)},[ui]:async(t,r)=>{const n=ae(e.operationContext,r.signal,r.requestId);X(n.signal),OE(t),await $(()=>e.presentation.hideLoading(n),n.signal)}}}const LE={auth:"optional",channel:"api",failurePresentation:"none",id:"heybox.account.home_v2.get",method:"GET",path:"/account/home_v2/",parse(e){return de(e,"当前用户首页资料接口响应异常")}},CE=3e4;function RE(e,t,r={}){const n=r.ttlMs??CE,i=r.requestPolicyEnabled!==!1,o=r.requestGate?{capability:"user",gate:r.requestGate}:void 0;let s=0,a,c;async function d(){let l;try{l=await Fi(e,LE,void 0,{...t,credentials:"heybox-session",...o?{gate:o}:{}})}catch(f){throw t.signal.aborted?p("RUNTIME_DESTROYED","小程序 Runtime 已终止"):f instanceof ge?p("REQUEST_UNSUPPORTED",f.message):f instanceof $r?p("INVALID_RESPONSE","user home_v2 响应不合法"):f instanceof nr?p("REQUEST_FAILED","user home_v2 请求失败"):f instanceof Wr?i&&(f.status===403||f.status===429)?p("RATE_LIMITED","user home_v2 请求已被网关限流,请稍后重试",{status:f.status,...f.retryAfterMs===void 0?{}:{retryAfterMs:f.retryAfterMs}}):p("REQUEST_FAILED",f.message):kE(f)?f:p("REQUEST_FAILED","user home_v2 请求失败")}return PE(l,"user home_v2")}function u(l){const f=Date.now();if(a?.userId===l&&a.expiresAt>f)return Promise.resolve(a.value);if(c?.userId===l&&c.generation===s)return c.promise;const m=s,h=d().then(g=>(s===m&&(a={userId:l,value:g,expiresAt:Date.now()+n}),g)).finally(()=>{c?.promise===h&&(c=void 0)});return c={userId:l,generation:m,promise:h},h}return{get:u,clear(){s+=1,a=void 0,c=void 0}}}function PE(e,t){if(!Q(e))throw p("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 p(n,r)}if(!Q(e.result))throw p("INVALID_RESPONSE",`${t} result 必须是对象`);return e.result}function kE(e){return Q(e)&&typeof e.code=="string"&&typeof e.message=="string"}const xE={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 de(e,"关注用户接口响应异常")}},UE={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 de(e,"ApiXiaoheiheCnUserMiniprogramRuntimeAuthorFollowStatus 接口响应异常")}},jE={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 de(e,"ApiXiaoheiheCnUserMiniprogramRuntimeAuthorFollowGuidanceBegin 接口响应异常")}},zE={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 de(e,"Steam 游戏库接口响应异常")}};function HE(e,t=Zo){const r=im({version:"2",validate:BE}),n={ttlMs:Number.isFinite(t)?Math.max(0,Math.floor(t)):Zo,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 bc(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 FE(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 BE(e){if(!Q(e)||!Array.isArray(e.gameList)||typeof e.hasMore!="boolean"||!Number.isInteger(e.nextOffset)||Number(e.nextOffset)<0||(Tc(e,"total"),e.isMe!==void 0&&typeof e.isMe!="boolean"))throw Yt();for(const t of e.gameList){if(!Q(t)||!fs(t.appid)||!fs(t.steamAppid)||typeof t.name!="string"||!t.name.trim())throw Yt();for(const r of["image","portraitImage","icon"])VE(t,r);for(const r of["playtimeForever","playtime2Weeks"])Tc(t,r);if(t.tags!==void 0&&(!Array.isArray(t.tags)||t.tags.some(r=>typeof r!="string"||!r.trim())))throw Yt()}return e}function fs(e){return typeof e=="number"&&Number.isFinite(e)}function Tc(e,t){if(e[t]!==void 0&&!fs(e[t]))throw Yt()}function VE(e,t){if(e[t]!==void 0&&typeof e[t]!="string")throw Yt()}function Yt(){return p("INVALID_RESPONSE","Steam 游戏库缓存数据不合法")}const sl=20,GE=100,qE=128,al=0,cl="weeks",QE=100,YE=new Set(["weeks","all","achieved"]);function WE(){return{nickname:"",avatar:""}}function $E(e){const t=RE(e.network,e.operationContext,{requestGate:e.requestGate,requestPolicyEnabled:e.requestPolicyEnabled}),r=e.requestPolicyEnabled!==!1,n=e.cacheManager??du(),i=HE(n,r?e.steamGameListTtlMs:0);let o;const s=new Map;let a=Promise.resolve();function c(M,R){const T=JSON.stringify([M,R]);return(!o||o.key!==T)&&(o={key:T,scope:n.createScope(R,n.createScope(M))}),o.scope}function d(){const M=o;o=void 0,M&&n.invalidateScope(M.scope).catch(()=>{}),s.clear()}const u=Iu({ttlMs:Math.max(0,Math.floor(e.profileTtlMs??Eu))}),l=e.requestGate?{capability:"user",gate:e.requestGate}:void 0;let f,m,h=0,g=!1;const I=e.account.onChange(()=>{h+=1,t.clear(),u.invalidate(),d()}),y=e.authorization.onEvent((M,R)=>{M==="user_info_authorization_change"&&Object.values(R).some(T=>T==="denied")&&(h+=1,t.clear(),u.invalidate(),d(),a=a.then(async()=>{if(g)return;const T=await e.account.getCurrentUserId(e.operationContext);typeof T=="string"&&T.trim()&&await n.invalidateScope(c(_(),T.trim()))}).catch(()=>{}))});function b(){if(g||e.operationContext.signal.aborted)throw p("RUNTIME_DESTROYED","小程序 Runtime 已终止")}function _(){const M=e.identity.get()?.miniProgramId?.trim();if(!M)throw p("INVALID_STATE","用户能力缺少 canonical 小程序身份");return M}async function P(){b(),await a,b();let M;try{M=await e.account.getCurrentUserId(e.operationContext)}catch(R){throw e.operationContext.signal.aborted?p("RUNTIME_DESTROYED","小程序 Runtime 已终止"):Ir(R)?R:p("REQUEST_FAILED","读取小黑盒账号失败")}return typeof M=="string"&&M.trim()?M.trim():void 0}async function j(M,R){const T=await P();if(h!==R||T!==M)throw p("AUTHORIZATION_CONTEXT_CHANGED","用户请求期间账号上下文已变化,请重新操作")}async function U(M,R,T=e.operationContext.signal){try{return await Fi(e.network,M,R,{...e.operationContext,signal:T,credentials:"heybox-session",...l?{gate:l}:{}})}catch(N){throw e.operationContext.signal.aborted?p("RUNTIME_DESTROYED","小程序 Runtime 已终止"):N instanceof ge?p("REQUEST_UNSUPPORTED",N.message):N instanceof $r?p("INVALID_RESPONSE","用户接口响应不合法"):N instanceof nr?p("REQUEST_FAILED","用户请求失败"):N instanceof Wr?r&&(N.status===403||N.status===429)?p("RATE_LIMITED","用户请求已被网关限流,请稍后重试",{status:N.status,...N.retryAfterMs===void 0?{}:{retryAfterMs:N.retryAfterMs}}):p("REQUEST_FAILED",N.message):Ir(N)?N:p("REQUEST_FAILED","用户请求失败")}}async function O(M,R){if(!e.authorizationContext)return{mini_program_id:M};let T;try{T=await $(()=>e.authorizationContext.get({...e.operationContext,signal:R}),R)}catch(N){if(Ir(N))throw N;const A=p("REQUEST_FAILED","读取 Runtime auth context 失败");throw Object.defineProperty(A,"cause",{configurable:!0,value:N}),A}if(!T.token?.trim())throw p("INVALID_STATE","关注作者缺少启动凭据");return{mini_program_id:M,runtime_auth_context_token:T.token}}async function w(){b();const M=_(),R=h,T=await P();if(!T){if(h!==R)throw p("AUTHORIZATION_CONTEXT_CHANGED","查询期间账号已变化");return"notFollowing"}const N=await O(M,e.operationContext.signal);await j(T,R);const A=await U(UE,N);if(await j(T,R),_()!==M)throw p("AUTHORIZATION_CONTEXT_CHANGED","查询期间小程序上下文已变化");return Lc(vc(A))}function S(M,R){if(!M)return Promise.reject(p("USER_GESTURE_REQUIRED","请点击按钮关注作者"));if(R?.aborted)return Promise.reject(p("REQUEST_CANCELLED","关注操作已取消"));if(f)return Promise.reject(p("FOLLOW_IN_PROGRESS","关注确认流程尚未结束"));if(!e.authPresentation?.confirmFollowAuthor)return Promise.reject(p("METHOD_FORBIDDEN","当前宿主不支持关注确认框"));const T=v(R).finally(()=>{f===T&&(f=void 0)});return f=T,T}async function v(M){b();const R=_(),T=new AbortController;m=T;const N=()=>T.abort();e.operationContext.signal.addEventListener("abort",N,{once:!0}),M?.addEventListener("abort",N,{once:!0});let A=()=>{},L=!1;try{try{await $(()=>e.account.ensureAuthenticated({trustedUserGesture:!0,reason:"user_action",signal:T.signal}),T.signal)}catch(re){throw Ir(re)&&["AUTH_CANCELLED","AUTHORIZATION_CANCELLED","HEYBOX_APP_LOGIN_REQUIRED","LOGIN_CANCELLED"].includes(re.code)?p("FOLLOW_CANCELLED","已取消小黑盒登录"):re}b();const k=h;A=e.account.onChange(()=>{L=!0,N()});const x=await $(P,T.signal);if(!x)throw p("FOLLOW_CANCELLED","未完成小黑盒登录");const H=async()=>{if(await $(()=>j(x,k),T.signal),b(),_()!==R)throw p("AUTHORIZATION_CONTEXT_CHANGED","关注期间小程序上下文已变化")};await H();const F=await O(R,T.signal);await H();const V=iw(),q=await $(()=>U(jE,{...F,request_id:V},T.signal),T.signal);await H();const J=vc(q);if(J.status!=="notFollowing")return Lc(J);if(J.rateLimited)throw p("FOLLOW_GUIDANCE_LIMIT_REACHED","今日关注引导次数已达上限");const K=await $(()=>e.authPresentation.confirmFollowAuthor({miniProgramId:R,signal:T.signal}),T.signal);if(await H(),K!=="confirmed")throw p("FOLLOW_CANCELLED","已取消关注作者");const Z=J.authorId,Y=await $(()=>U(xE,{body:{following_id:Z}},T.signal),T.signal);if(await H(),Y.status!=="ok"){const re=["login","relogin","lack_token"].includes(Y.status)?"HEYBOX_APP_LOGIN_REQUIRED":"REQUEST_FAILED";throw p(re,typeof Y.msg=="string"&&Y.msg.trim()?Y.msg.trim():"关注作者失败,请稍后重试")}return"following"}catch(k){throw b(),L?p("AUTHORIZATION_CONTEXT_CHANGED","关注期间账号已变化,请重新操作"):M?.aborted?p("REQUEST_CANCELLED","关注操作已取消"):Ir(k)?k:p("REQUEST_FAILED","关注作者失败,请稍后重试")}finally{A(),e.operationContext.signal.removeEventListener("abort",N),M?.removeEventListener("abort",N),m===T&&(m=void 0)}}async function C(){_();const M=h,R=await P();if(!R)return{isHeyboxAppLoggedIn:!1,authorization:null,userInfo:null};const[T,N]=await Promise.all([e.authorization.getOrCreateLocalIdentity(R),E(R).catch(()=>WE())]);return await j(R,M),{isHeyboxAppLoggedIn:!0,authorization:e.authorization.getAuthorization(),userInfo:{app_user_id:T.appUserId,profile:N,...T.steamId?{steam_id:T.steamId}:{}}}}function E(M){return u.read(M,()=>U(wu,void 0).then(R=>{const T=hs(R,"账号基础信息");if(T.display_username!==void 0&&typeof T.display_username!="string")throw p("INVALID_RESPONSE","账号基础信息 nickname 不合法");if(T.display_avatar!==void 0&&typeof T.display_avatar!="string")throw p("INVALID_RESPONSE","账号基础信息 avatar 不合法");return{nickname:T.display_username??"",avatar:T.display_avatar??""}}))}async function D(M){const R=KE(M),T=_(),N=h,A=await P();if(!A)return d(),{isLogin:!1,isBound:!1,data:null};const L=await t.get(A);await j(A,N);const k=dl(L.steam_id_info);if(Object.keys(k).length===0)return await n.invalidateScope(c(T,A)).catch(()=>{}),await j(A,N),s.delete(JSON.stringify([T,A])),{isLogin:!0,isBound:!1,data:null};const x=JSON.stringify([T,A]),H=c(T,A),F=bc({...R,steamId:void 0},k),V=ul(k.personal_infomation_open??k.personal_information_open),q=JSON.stringify([F??null,V??null]),J=s.get(x);J&&J.identity!==q&&(await n.invalidateScope(H).catch(()=>{}),await j(A,N));const K={identity:q,scope:n.createScope(q,H)};s.set(x,K);const Z=bc(R,k),Y=Z?i.persistent:i.unresolved,re=n.createScope(Z??"unresolved",K.scope),Me=async()=>{if(await j(A,N),_()!==T||s.get(x)?.identity!==q)throw p("AUTHORIZATION_CONTEXT_CHANGED","Steam 游戏库请求期间绑定上下文已变化")},le=await Y.read({scope:re,key:FE({miniProgramId:T,userId:A,effectiveSteamId:Z,personalInformationOpen:V,query:R}),signal:e.operationContext.signal,load:async fe=>{const ie=await U(zE,{userId:A,...R,personalInformationOpen:V},fe);return await Me(),tw(hs(ie,"Steam 游戏库"),R)}}).catch(async fe=>{throw await Me(),fe});return await Me(),{isLogin:!0,isBound:!0,data:le}}return{getFollowStatus:w,requestFollowAuthor:S,getInfo:C,getSteamGameList:D,async invalidateSteamGameListCache(){const M=_(),R=h,T=await P();if(!T)return;const N=c(M,T);await Promise.all([i.persistent.invalidateScope(N),i.unresolved.invalidateScope(N)]),t.clear(),s.delete(JSON.stringify([M,T])),await j(T,R)},dispose(){g||(g=!0,m?.abort(),h+=1,I(),y(),t.clear(),u.dispose(),i.persistent.dispose(),i.unresolved.dispose(),e.cacheManager||n.dispose())}}}function KE(e){if(e==null)return{limit:sl,offset:al,sort:cl,includeHidden:!1};if(!Q(e))throw st("user.getSteamGameList 参数必须是对象");const t=Object.keys(e).find(n=>!["steamId","limit","offset","sort","q","includeHidden"].includes(n));if(t)throw st(`user.getSteamGameList 不支持字段: ${t}`);const r={limit:ZE(e.limit),offset:JE(e.offset),sort:XE(e.sort),includeHidden:ew(e.includeHidden)};if(e.steamId!==void 0){if(typeof e.steamId!="string"||!e.steamId.trim()||e.steamId.trim().length>qE)throw st("user.getSteamGameList steamId 必须是非空字符串");r.steamId=e.steamId.trim()}if(e.q!==void 0){if(typeof e.q!="string")throw st("user.getSteamGameList q 必须是字符串");const n=e.q.trim();n&&(r.q=n.slice(0,QE))}return r}function ZE(e){if(e===void 0)return sl;if(!Number.isInteger(e)||Number(e)<1)throw st("user.getSteamGameList limit 必须是正整数");return Math.min(Number(e),GE)}function JE(e){if(e===void 0)return al;if(!Number.isInteger(e)||Number(e)<0)throw st("user.getSteamGameList offset 必须是非负整数");return Number(e)}function XE(e){if(e===void 0)return cl;if(typeof e!="string"||!YE.has(e))throw st("user.getSteamGameList sort 不支持");return e}function ew(e){if(e===void 0)return!1;if(typeof e!="boolean")throw st("user.getSteamGameList includeHidden 必须是 boolean");return e}function tw(e,t){if(!Array.isArray(e.game_list))throw p("INVALID_RESPONSE","Steam 游戏库 game_list 必须是数组");const r=e.game_list.map(rw).filter(a=>a!==void 0),n=Mi(e.total),i=t.offset+r.length,o={gameList:r,hasMore:r.length>=t.limit,nextOffset:i};n!==void 0&&(o.total=n,o.hasMore=i<n);const s=ul(e.is_me);return s!==void 0&&(o.isMe=s),o}function rw(e){const t=dl(e),r=Mi(t.appid),n=Mi(t.steam_appid)??r,i=Ks(t.name);if(r===void 0||n===void 0||!i)return;const o={appid:r,steamAppid:n,name:i};mo(o,"image",t.image),typeof t.vertical_head_image=="string"&&mo(o,"portraitImage",t.vertical_head_image),mo(o,"icon",t.appicon??t.icon),Oc(o,"playtimeForever",t.playtime_forever),Oc(o,"playtime2Weeks",t.playtime_2weeks);const s=nw(t.external_tags??t.tags);return s.length&&(o.tags=s),o}function hs(e,t){if(!Q(e))throw p("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 p(n,r)}if(!Q(e.result))throw p("INVALID_RESPONSE",`${t} result 必须是对象`);return e.result}function dl(e){return Q(e)?e:{}}function Ks(e){return typeof e=="string"?e.trim():typeof e=="number"||typeof e=="boolean"?String(e):""}function nw(e){return Array.isArray(e)?e.map(Ks).filter(Boolean):[]}function Mi(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"&&e.trim()&&Number.isFinite(Number(e)))return Number(e)}function ul(e){if(e===!0||e===1||e==="1")return!0;if(e===!1||e===0||e==="0")return!1}function mo(e,t,r){const n=Ks(r);n&&Object.assign(e,{[t]:n})}function Oc(e,t,r){const n=Mi(r);n!==void 0&&Object.assign(e,{[t]:n})}function st(e){return p("INVALID_PARAMS",e)}function Ir(e){return Q(e)&&typeof e.code=="string"&&typeof e.message=="string"}function vc(e){const t=hs(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 p("INVALID_RESPONSE","关注状态响应不合法");return{status:t.follow_status===2?"self":t.follow_status===1?"following":"notFollowing",authorId:t.author_id,rateLimited:t.rate_limited}}function Lc(e){return e.status}function iw(){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 ow(e){return{[zn]:async t=>(fn(t,"user.getFollowStatus"),e.user.getFollowStatus()),[Hn]:async(t,r)=>(fn(t,"user.requestFollowAuthor"),e.user.requestFollowAuthor(r.trustedUserGesture,r.signal)),[Fn]:async t=>(fn(t,"user.getInfo"),e.user.getInfo()),[Bn]:async(t,r)=>{fn(t,"user.revokeAuthorization"),await e.authorization.revoke(r.trustedUserGesture)},[Vn]:async t=>e.user.getSteamGameList(t)}}function fn(e,t){if(e!==void 0)throw p("INVALID_PARAMS",`${t} 不接收入参`)}function Cc(e){throw{code:"INVALID_PARAMS",message:e}}function Ar(e,t){const r=Number(e);return Number.isFinite(r)&&r>0?r:t}function ll(e,t){const r=Number(e);return Number.isFinite(r)&&r>=0?r:t}function hn(e,t,r){return Math.min(ll(e,t),r)}async function sw(e){try{return ll(await e.getNavigationBarHeight(),0)}catch{return 0}}function aw(e,t,r,n){const i=hn(e.safeArea?.left,0,t),o=Math.max(i,hn(e.safeArea?.right,t,t)),s=hn(e.safeArea?.top,n,r),a=Math.max(s,hn(e.safeArea?.bottom,r,r));return{left:i,right:o,top:s,bottom:a,width:o-i,height:a-s}}async function Rc(e){const t=e.getViewportMetrics(),r=Ar(t.windowWidth,0),n=Ar(t.windowHeight,0),i=await sw(e);return{pixelRatio:Ar(t.pixelRatio,1),screenWidth:Ar(t.screenWidth,r),screenHeight:Ar(t.screenHeight,n),windowWidth:r,windowHeight:n,statusBarHeight:i,safeArea:aw(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,o,s;const a=()=>{if(n||r.operationContext.signal.aborted||!r.onViewportChange)return;const l=++i;Rc(r.presentation).then(f=>{if(n||r.operationContext.signal.aborted||l!==i)return;const m=JSON.stringify(f);m!==o&&(o=m,r.onViewportChange?.(f))}).catch(()=>{})},c=Cy({...r,onApplied:a}),d=()=>{n||(n=!0,e.operationContext.signal.removeEventListener("abort",d),t.abort(),c.dispose(),s?.())};return e.operationContext.signal.aborted?d():(s=r.presentation.onViewportChange?.(a),e.operationContext.signal.addEventListener("abort",d,{once:!0})),{handlers:{[_t]:async(l,f)=>c.apply(l,f?.signal),[Wn]:async()=>(X(r.operationContext.signal),Rc(r.presentation)),[$n]:async l=>{if(X(r.operationContext.signal),typeof l!="object"||l===null||Array.isArray(l))return Cc("viewport.setNavigationBarStyle 参数必须是对象");const f=l.foregroundStyle;if(f!=="light"&&f!=="dark")return Cc("viewport.setNavigationBarStyle foregroundStyle 必须是 light 或 dark");await $(()=>r.presentation.setNavigationBarStyle(f,e.operationContext),r.operationContext.signal)}},runDisplayRequest:c.runDisplayRequest,applyOrientation:(l,f)=>c.apply({orientation:l.mode,fullscreen:l.hideCapsule},f),notifyChange:()=>{o=void 0,a()},dispose:d}}function dw(e){if(e===void 0)return{};if(!e||typeof e!="object"||Array.isArray(e))throw ee("INVALID_PARAMS","工作区卡片刷新参数必须是对象");const t=e;if(Object.keys(t).some(i=>i!=="gameAppId"&&i!=="cardIds"))throw ee("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 ee("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 ee("INVALID_PARAMS","工作区卡片编号无效");return{...r===void 0?{}:{gameAppId:r},...n===void 0?{}:{cardIds:[...n]}}}function uw(e,t){return{[xn]:async(r,n)=>{const i=ae(t,n.signal,n.requestId);if(X(i.signal),!e)throw ee("CAPABILITY_UNAVAILABLE","当前 Host 不支持工作区卡片");const o=dw(r),s=await $(()=>e.requestRefresh(o,i),i.signal);if(!s||typeof s!="object"||Array.isArray(s)||Object.keys(s).some(a=>a!=="scheduled")||!Number.isSafeInteger(s.scheduled)||s.scheduled<0)throw ee("HOST_INVALID_RESPONSE","工作区卡片刷新回执无效");return{scheduled:s.scheduled}}}}const lw=new Map(ct.map(e=>[e.method,e]));function go(e,t,r){return{code:e,message:t,...r===void 0?{}:{data:r}}}function fw(e){const t=au(e);return r=>t(r.requirement,r.method)}function hw(e,t,r,n){let i;try{i=Promise.resolve(e(t,r))}catch(o){return n.aborted?Promise.resolve({status:"dropped"}):Promise.reject(o)}return n.aborted?(i.catch(()=>{}),Promise.resolve({status:"dropped"})):new Promise((o,s)=>{let a=!1;const c=u=>{a||(a=!0,n.removeEventListener("abort",d),u())},d=()=>c(()=>o({status:"dropped"}));n.addEventListener("abort",d,{once:!0}),i.then(u=>c(()=>o({status:"handled",value:u})),u=>c(()=>s(u)))})}function mw(e){const t=fw(e.runtimePermissions),r=je(e.runtimePermissions);let n=0;return{async dispatch(i,o,s){const a=e.now??gw,c=e.onTrace?a():0,d=e.onTrace?Date.now():0,u=e.onTrace?s.requestId??`runtime_${++n}`:"";e.onTrace&&po(e.onTrace,{callId:u,method:i,startedAt:d,outcome:"started"},()=>c,c);try{if(e.terminalSignal.aborted)throw go("RUNTIME_DESTROYED","小程序 Runtime 已终止");eu(i,e.effectiveCapabilities);const l=lw.get(i);if(!l)throw new Error(`Capability method ${i} 缺少 protocol metadata`);const f=t(l),m=!f.allowed&&r.valid&&r.permissions.companion?.status==="enabled"&&e.allowsCompanionAttachmentAccess?.(i,o)===!0,h=!f.allowed&&r.valid&&r.permissions.gameSaves?.status==="enabled"&&e.allowsGameSaveAccess?.(i,o)===!0;if(!f.allowed&&!m&&!h)throw go(f.code,f.message,f.data);const g=e.handlers[i];if(!g)throw new Error(`Capability method ${i} 缺少 handler`);const I=async _=>{for(const P of e.policies??[]){const j=await P.evaluate({method:i,payload:o,capability:l});if(e.terminalSignal.aborted||_.aborted)throw kc();if(!j.allowed)throw go(j.code,j.message,j.data)}if(e.terminalSignal.aborted||_.aborted)throw kc()},b=await hw(async()=>{if(i===_t){if(!e.runDisplayRequest)throw new Error("viewport.setDisplay 缺少执行 Module");return e.runDisplayRequest(o,s.signal,I)}return await I(e.terminalSignal),g(o,s)},void 0,s,e.terminalSignal);return e.onTrace&&po(e.onTrace,Pc(u,i,o,d,b),a,c),b}catch(l){throw e.onTrace&&po(e.onTrace,Pc(u,i,o,d,{status:"error",error:l}),a,c),l}}}}function gw(){return typeof performance>"u"?Date.now():performance.now()}function po(e,t,r,n){if(!e)return;const i=r()-n,o=Date.now();try{e({...t,phase:"host",timestamp:o,durationMs:Math.max(0,Number.isFinite(i)?i:0)})}catch{}}function Pc(e,t,r,n,i){const o=i.status==="handled"?"success":i.status;return{callId:e,method:t,startedAt:n,outcome:o,...i.status==="error"?{errorCode:pw(i.error)}:{},...yw(t,r,i)}}function pw(e){return typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"?e.code:void 0}function yw(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 o=("method"in t&&typeof t.method=="string"?t.method:"GET").trim().toUpperCase();if(!["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"].includes(o))return{};const s=r.status==="handled"&&fl(r.value)&&typeof r.value.status=="number"?r.value.status:void 0;return{network:{method:o,origin:n.origin,pathname:n.pathname,...s===void 0?{}:{responseStatus:s}}}}catch{return{}}}function fl(e){return typeof e=="object"&&e!==null}function kc(){const e=new Error("The operation was aborted");return e.name="AbortError",e}function Ew(e){const t={signal:e.terminalSignal,...e.miniProgramDetail===void 0?{}:{miniProgramDetail:e.miniProgramDetail}},r=Im(e.requestPolicy);let n;if(e.files)try{n=um(e.files,t)}catch{}const i=du({store:n}),o=e.onRequestPolicyReport??(r.debugReport?ww:void 0),s=r.enabled?pm({...r.gateOptions,...o?{onReport:o}:{}}):void 0,a=new Vs(e.files,e.miniProgramDetail),c=zp({registry:a,picker:e.picker,operationContext:t}),d=Qm({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:s,requestPolicyEnabled:r.enabled});let u,l,f,m,h,g=()=>{},I=()=>{};try{u=cw({operationContext:t,presentation:e.hostPresentation,onDisplayChange:w=>e.eventSink.postEvent("display_change",w),onViewportChange:w=>e.eventSink.postEvent("viewport_change",w)}),f=$E({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:s,requestPolicyEnabled:r.enabled}),g=d.onEvent((w,S)=>e.eventSink.postEvent(w,S)),I=e.hostCompanion?.onSessionEvent?.(w=>{const S=Rp(w);!e.terminalSignal.aborted&&S&&e.eventSink.postEvent(S.type,S.payload)})??(()=>{}),m=bg({authorizationContext:e.authorizationContext,account:e.account,identity:e.identity,network:e.network,operationContext:t,requestGate:s,requestPolicyEnabled:r.enabled}),h=Ep({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:a,requestGate:s,requestPolicyEnabled:r.enabled});const y=SE({storage:e.storage,scopedStorage:e.scopedStorage,storageDiagnostics:e.storageDiagnostics,identity:e.identity,operationContext:t,anonymousStorageScope:e.anonymousStorageScope,storageLimits:e.storageLimits});l=cy({registry:a,media:e.media,operationContext:t});const b=[{name:"gameSaves",handlers:h.handlers},{name:"auth",handlers:eg({authorization:d})},{name:"user",handlers:{...ow({user:f,authorization:d,runtimePermissions:e.runtimePermissions,steamAccount:e.runtimeFeatures?.steamAccount===!0,userDataMode:e.runtimeFeatures?.userDataMode}),...nm({operationContext:t,presentation:e.hostPresentation,miniProgramPresentation:e.miniProgramPresentation})}},{name:"share",handlers:AE({prepareScreenshot:e.prepareScreenshot,prepareLongScreenshot:e.prepareLongScreenshot,environment:e.environment,identity:e.identity,operationContext:t,presentation:e.hostPresentation})},{name:"viewport",handlers:u.handlers},{name:"storage",handlers:y.handlers},{name:"network",handlers:Fy({network:e.network,transfer:e.transfer,fileRegistry:a,operationContext:t,runtimePermissions:e.runtimePermissions,allowedHttpOrigins:e.allowedHttpOrigins,networkPolicy:e.networkPolicy})},{name:"workspaceCards",handlers:uw(e.workspaceCards,t)},{name:"files",handlers:c.files},{name:"file",handlers:c.file},{name:"directory",handlers:c.directory},{name:"media",handlers:l.handlers},{name:"ui",handlers:vE({operationContext:t,presentation:e.hostPresentation})},{name:"device",handlers:Up({operationContext:t,presentation:e.hostPresentation,protocol:e.hostProtocol})},{name:"navigation",handlers:Ry({operationContext:t,presentation:e.hostPresentation,...e.hostPresentation.applyOrientation?{resetDisplay:w=>u.applyOrientation({mode:"portrait",hideCapsule:!1},w)}:{}})},{name:"cloud",handlers:m.handlers},{name:"companion",handlers:Tp({companion:e.hostCompanion,companionPresentation:e.companionPresentation,miniProgramPresentation:e.miniProgramPresentation,operationContext:t,fileRegistry:a})}],_=Iw(b);let P=!1;const j=()=>{P||(P=!0,e.terminalSignal.removeEventListener("abort",j),u?.dispose(),l?.dispose(),m?.dispose(),h?.dispose(),g(),I(),f?.dispose(),i.dispose(),d.dispose(),s?.dispose(),a.dispose())};e.terminalSignal.aborted?j():e.terminalSignal.addEventListener("abort",j,{once:!0});const U=new Set(["file.readText","file.readBytes","file.stat"]),O=(w,S)=>U.has(w)&&fl(S)&&a.isCompanionAttachmentRef(S.target);return{modules:b,handlers:_,runDisplayRequest:u.runDisplayRequest,allowsCompanionAttachmentAccess:O,allowsGameSaveAccess:h.allowsRead,gameSaveDiagnostics:h.diagnostics,applyOrientation:u.applyOrientation,notifyViewportChange:u.notifyChange,...y.diagnostics?{storageDiagnostics:y.diagnostics}:{},...e.files?{sandboxDiagnostics:Wp({registry:a,operationContext:t,runtimePermissions:e.runtimePermissions,capabilities:e.diagnosticCapabilities})}:{},dispose:j}}catch(y){throw u?.dispose(),l?.dispose(),m?.dispose(),h?.dispose(),g(),I(),f?.dispose(),i.dispose(),d.dispose(),s?.dispose(),a.dispose(),y}}function ww(e){try{console.warn("[hb-sdk-runtime] request-policy",e)}catch{}}function Iw(e){const t=new Map(ct.map(i=>[i.method,i.module])),r=new Map;for(const i of e)for(const[o,s]of Object.entries(i.handlers)){const a=o,c=t.get(a);if(!c)throw new Error(`Capability Module ${i.name} 注册了未知 method: ${a}`);if(c!==i.name)throw new Error(`Capability method ${a} 应由 ${c} 拥有,不能注册到 ${i.name}`);if(r.has(a))throw new Error(`Capability method ${a} 存在重复 owner`);if(typeof s!="function")throw new Error(`Capability method ${a} 缺少 handler`);r.set(a,s)}const n=ct.map(i=>i.method).filter(i=>!r.has(i));if(n.length>0)throw new Error(`Capability registry 缺少 method: ${n.join(", ")}`);if(r.size!==ct.length)throw new Error(`Capability registry method 数量不合法: ${r.size}`);return Object.freeze(Object.fromEntries(r))}const Aw="heybox-mini-dev:";function xc(e){try{return Nw(new URL(e))}catch{return!1}}function Nw(e){return e.protocol===Aw}function Dw(e){return e==="localhost"||e==="127.0.0.1"||e==="[::1]"||Mw(e)}function Mw(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 Sw=new Set(["android","ios","ohos","windows","macos","linux","unknown"]);function _w(e,t){const r=[],n=bw(e.environmentInfo,r),i=Mn(n?.appVersion,"host.appVersion",r),o=Ow(n?.operatingSystem,r);return{info:Object.freeze({runtime:Object.freeze({mode:Tw(e.sdkVersionPolicy?.releaseChannel,r)}),host:Object.freeze({appVersion:i}),miniProgram:Object.freeze({id:Mn(t.miniProgramId),version:Mn(t.miniProgramVersion)}),operatingSystem:Object.freeze(o)}),invalidFields:Object.freeze(r)}}function bw(e,t){if(e!=null){if(hl(e))return e;t.push("environmentInfo")}}function Tw(e,t){return e==="public"?"production":e==="preview"||e==="development"?e:(e!=null&&t.push("runtime.mode"),"unknown")}function Ow(e,t){if(e==null)return{name:"unknown",version:null};if(!hl(e))return t.push("operatingSystem"),{name:"unknown",version:null};const r=Sw.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:Mn(e.version,"operatingSystem.version",t)}}function Mn(e,t,r){return e==null?null:typeof e=="string"&&e.trim()?e.trim():(t&&r&&r.push(t),null)}function hl(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const vw="data:image/svg+xml;base64,PHN2ZyBwcmVzZXJ2ZUFzcGVjdFJhdGlvPSJub25lIiBvdmVyZmxvdz0idmlzaWJsZSIgc3R5bGU9ImRpc3BsYXk6IGJsb2NrOyIgd2lkdGg9IjY3IiBoZWlnaHQ9IjIyIiB2aWV3Qm94PSIwIDAgNjcgMjIiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxwYXRoIGlkPSJTdWJ0cmFjdCIgZD0iTTY2IDBDNjYuMzM3MiAwIDY2LjY3MDYgMC4wMTcxODM4IDY3IDAuMDQ2ODc1QzYxLjM5MzYgMC41NTIxODkgNTcgNS4yNjIwMiA1NyAxMUM1NyAxNi43MzggNjEuMzkzNiAyMS40NDY4IDY3IDIxLjk1MjFDNjYuNjcwNiAyMS45ODE4IDY2LjMzNzIgMjIgNjYgMjJIMTFDNC45MjQ4NyAyMiAwIDE3LjA3NTEgMCAxMUMwIDQuOTI0ODcgNC45MjQ4NyAyLjY1NzU2ZS0wNyAxMSAwSDY2Wk04LjI0MzE2IDYuNzM1MzVDOC4yNDMxNiA2LjU5Mzk3IDguMTQyNTggNi41MzU3NiA4LjAxOTUzIDYuNjA2NDVMNi4yMjI2NiA3LjY0MDYyQzYuMTU3ODcgNy42ODIyOCA2LjEwNDE2IDcuNzM5MTcgNi4wNjU0MyA3LjgwNTY2QzYuMDI2NzIgNy44NzIyNyA2LjAwNDEgNy45NDc1MiA2IDguMDI0NDFWMTMuOTY1OEM2LjAwMzcxIDE0LjA0MzQgNi4wMjU4NSAxNC4xMTkxIDYuMDY0NDUgMTQuMTg2NUM2LjEwMzE5IDE0LjI1NCA2LjE1NzQgMTQuMzEyIDYuMjIyNjYgMTQuMzU0NUw5Ljg3MTA5IDE2LjQ1OEM5Ljk5MzQ2IDE2LjUyNzIgMTAuMDkzNiAxNi41ODQyIDEwLjA5NDcgMTYuNTg1OUMxMC4wOTQ3IDE2LjU4NzEgMTAuMTkzNCAxNi42NDUxIDEwLjMxNjQgMTYuNzE1OEwxMi41MDEgMTcuOTY5N0MxMi42MjI4IDE4LjA0MDMgMTIuNzIzNiAxNy45ODIyIDEyLjcyMzYgMTcuODQwOFYxMi4zNjcyQzEyLjcyMyAxMi4yOTk0IDEyLjY5NTcgMTIuMjM0MyAxMi42NDc1IDEyLjE4NjVDMTIuNTk5MiAxMi4xMzg4IDEyLjUzMzggMTIuMTEyMyAxMi40NjU4IDEyLjExMjNIMTAuNzM3M0MxMC42NzAyIDEyLjExMzIgMTAuNjA1OSAxMi4xMzk5IDEwLjU1ODYgMTIuMTg3NUMxMC41MTEzIDEyLjIzNTIgMTAuNDg0NyAxMi4zMDAxIDEwLjQ4NDQgMTIuMzY3MlYxMy44Mzc5QzEwLjQ4NDIgMTMuOTc4OSAxMC4zODQ2IDE0LjAzNjQgMTAuMjYxNyAxMy45NjU4TDguNDY0ODQgMTIuOTM1NUM4LjQwMDI2IDEyLjg5MzUgOC4zNDYxNCAxMi44MzcyIDguMzA3NjIgMTIuNzcwNUM4LjI2OTE5IDEyLjcwNCA4LjI0NzM1IDEyLjYyOTQgOC4yNDMxNiAxMi41NTI3VjYuNzM1MzVaTTI0LjMzNCAxNC4zOTI2QzI0LjMzMzkgMTQuOTk4NSAyNC4yMDU1IDE1LjE4NDYgMjMuNTk4NiAxNS4xOTYzTDIyLjMwMTggMTUuMjU0OUwyMi42NjUgMTYuMjU0OUgyNS4wODY5QzI1LjY3MDUgMTYuMDg0IDI1Ljg3MjEgMTUuNzE5NCAyNS44NzIxIDE0LjgyMzJWNS43ODIyM0wyNC4zMzQgNS43MjM2M1YxNC4zOTI2Wk0zMi4yODIyIDE0LjQ3NTZDMzEuOTQ2IDE1LjA0OTIgMzEuNDY1OSAxNS43NTcxIDMxLjA5OTYgMTYuMjU0OUgzMi42MTkxQzMzLjA2NzMgMTUuNTIxMiAzMy4zNzUxIDE0LjkyOCAzMy41NDg4IDE0LjQ3NTZIMzIuMjgyMlpNMzQuODEwNSAxNS4zOTc1QzM0Ljg3OTEgMTUuNzEwMSAzNC45MzExIDE1Ljk5ODIgMzQuOTczNiAxNi4yNTQ5SDM2LjE4NjVMMzYuMTgxNiAxNi4yMzU0QzM2LjA2NjIgMTUuNzM4OCAzNS44OTg5IDE1LjAxOCAzNS43NDEyIDE0LjQ3NTZIMzQuNTI5M0wzNC44MTA1IDE1LjM5NzVaTTM2Ljk4MTQgMTQuNjUzM0MzNy4wOTg0IDE0Ljg3NyAzNy4yNDExIDE1LjE1MDEgMzcuMzMzIDE1LjQwMjNMMzcuNjM1NyAxNi4yNTQ5SDM5LjA4MDFDMzkuMDMzNiAxNS44MzI1IDM4LjU5NCAxNS4wNTUzIDM4LjIzODMgMTQuNDc1NkgzNi44ODg3QzM2LjkxNjEgMTQuNTI5OCAzNi45NDggMTQuNTg5NCAzNi45ODE0IDE0LjY1MzNaTTM5LjI3MDUgMTQuNDc1NkMzOS44MzAxIDE1LjE4MjEgNDAuMTg2MyAxNS44MDA0IDQwLjQxMzEgMTYuMjU0OUg0MS44MzVDNDEuNzM2NyAxNS42NjU2IDQxLjIyOTIgMTQuOTkzNiA0MC43NzY0IDE0LjQ3NTZIMzkuMjcwNVpNNDMuOTIyOSAxNS4wMDQ5SDQyLjc2NjZWMTUuOTk2MUg1My4xMjVWMTUuMDA0OUg1MS45Njg4VjEyLjQ3NTZINDMuOTIyOVYxNS4wMDQ5Wk0xMC43MDQxIDQuMDMwMjdDMTAuNTgxMSAzLjk1OTU4IDEwLjQ4MDUgNC4wMTc4IDEwLjQ4MDUgNC4xNTkxOFY5LjYyMzA1QzEwLjQ4MDYgOS42OTA3NCAxMC41MDc4IDkuNzU1NzggMTAuNTU1NyA5LjgwMzcxQzEwLjYwMzcgOS44NTE3MSAxMC42NjkzIDkuODc4ODcgMTAuNzM3MyA5Ljg3ODkxSDEyLjQ2NDhDMTIuNDk4NiA5Ljg3OTA1IDEyLjUzMjIgOS44NzIxNyAxMi41NjM1IDkuODU5MzhDMTIuNTk0NCA5Ljg0NjY2IDEyLjYyMjcgOS44MjgyMSAxMi42NDY1IDkuODA0NjlDMTIuNjcwNCA5Ljc4MDg5IDEyLjY5MDIgOS43NTE4NSAxMi43MDMxIDkuNzIwN0MxMi43MTYgOS42ODk3NSAxMi43MjI2IDkuNjU2NTQgMTIuNzIyNyA5LjYyMzA1VjguMTUyMzRDMTIuNzIyNyA4LjAxMSAxMi44MjIzIDcuOTUyODIgMTIuOTQ1MyA4LjAyMzQ0TDE0Ljc0MTIgOS4wNjE1MkMxNC44MDYgOS4xMDM2MiAxNC44NTk3IDkuMTYwNzcgMTQuODk4NCA5LjIyNzU0QzE0LjkzNzEgOS4yOTQzIDE0Ljk1OTYgOS4zNjkyOSAxNC45NjM5IDkuNDQ2MjlWMTUuMjU5OEMxNC45NjQxIDE1LjQwMDcgMTUuMDYzNyAxNS40NTcgMTUuMTg2NSAxNS4zODc3TDE2Ljk4NDQgMTQuMzUwNkMxNy4wNDkgMTQuMzA4NyAxNy4xMDMgMTQuMjUyMSAxNy4xNDE2IDE0LjE4NTVDMTcuMTgwMyAxNC4xMTg3IDE3LjIwMyAxNC4wNDMgMTcuMjA3IDEzLjk2NThWOC4wMjQ0MUMxNy4yMDI5IDcuOTQ3MzYgMTcuMTgwMyA3Ljg3MjQ2IDE3LjE0MTYgNy44MDU2NkMxNy4xMDI5IDcuNzM4ODQgMTcuMDQ5MyA3LjY4MTY0IDE2Ljk4NDQgNy42Mzk2NUwxMS44MjMyIDQuNjY3OTdDMTEuNzAwMiA0LjU5NzI4IDExLjU5NzcgNC41NDEwMiAxMS41OTc3IDQuNTQxMDJDMTEuNTg0NiA0LjUzMDQ3IDExLjQ4NzkgNC40ODIxMyAxMS4zNzIxIDQuNDE1MDRMMTAuNzA0MSA0LjAzMDI3Wk00Ni4yNDcxIDE1LjAwNDlINDUuMDkwOFYxMy4zMzY5SDQ2LjI0NzFWMTUuMDA0OVpNNDguNTI0NCAxNS4wMDQ5SDQ3LjM3OTlWMTMuMzM2OUg0OC41MjQ0VjE1LjAwNDlaTTUwLjgzNTkgMTUuMDA0OUg0OS42NTcyVjEzLjMzNjlINTAuODM1OVYxNS4wMDQ5Wk0zMi4wNjE1IDEwLjM2NTJIMzUuODAwOFYxMC45ODI0SDMxLjk4NjNWMTIuMDkwOEgzNS44MDA4VjEyLjc1NDlIMzEuMjUxVjEzLjgyNzFINDEuNzY1NlYxMi43NTQ5SDM3LjI2MjdWMTIuMDkwOEg0MS4wMjkzVjEwLjk4MjRIMzcuMjYyN1YxMC4zNjUySDM5Ljg1ODRDNDAuNDYzNCAxMC4zNjUyIDQwLjk1NCA5Ljg3NTQzIDQwLjk1NDEgOS4yNzE0OFY2LjAxNjZIMzIuMDYxNVYxMC4zNjUyWk0yMS4yNDQxIDguMzAzNzFDMjAuOTY4NiA5LjU3MTM4IDIwLjcxMzcgMTAuNTAxIDIwLjQ4MDUgMTEuMDkzOEMyMC4yNDcyIDExLjY4NjMgMTkuODEyNiAxMi41MDg2IDE5LjE3NDggMTMuNTYyNUwxOS4xMTUyIDEzLjY2MTFIMjAuNTc5MUwyMC41OTg2IDEzLjYzMzhDMjEuMzE2NiAxMi42MTg4IDIxLjgwNzUgMTEuNzYwNCAyMi4wNjc0IDExLjA1OTZDMjIuMzI1NyAxMC4zNjI4IDIyLjU4MzUgOS40NTMxMSAyMi44NDA4IDguMzMyMDNMMjIuODU4NCA4LjI1MjkzSDIxLjI1NDlMMjEuMjQ0MSA4LjMwMzcxWk0yNy4xOTA0IDguNjk4MjRDMjcuNDE5MiA5LjY1Mjc1IDI3LjY0ODMgMTAuNDQwMiAyNy44Nzc5IDExLjA1OTZDMjguMTM3OCAxMS43NjAzIDI4LjYyNzggMTIuNjE4OSAyOS4zNDU3IDEzLjYzMzhMMjkuMzY1MiAxMy42NjExSDMwLjgyOTFMMzAuNjE0MyAxMy4zMDQ3QzMwLjA2MDQgMTIuMzczNiAyOS42Nzc2IDExLjYzNjggMjkuNDYzOSAxMS4wOTM4QzI5LjIzMDYgMTAuNTAxIDI4Ljk3NTggOS41NzEzOCAyOC43MDAyIDguMzAzNzFMMjguNjg5NSA4LjI1MjkzSDI3LjA4NTlMMjcuMTkwNCA4LjY5ODI0Wk00NC4zNTQ1IDExLjg5MjZINTAuNDc2NkM1MS4wODE1IDExLjg5MjUgNTEuNTcyMSAxMS40MDI3IDUxLjU3MjMgMTAuNzk4OFY5LjM1MDU5SDQ0LjM1NDVWMTEuODkyNlpNNTAuNDI3NyAxMC40MDE0QzUwLjQyNzUgMTAuNzAzMiA1MC4xODIzIDEwLjk0ODIgNDkuODc5OSAxMC45NDgySDQ1LjQ5OVYxMC4yODMySDUwLjQyNzdWMTAuNDAxNFpNMzUuODAwOCA5LjI1NzgxSDMzLjI1MjlWNi45NDgyNEgzNS44MDA4VjkuMjU3ODFaTTM5Ljc2MzcgOC43MTA5NEMzOS43NjM1IDkuMDEyNjYgMzkuNTE4MSA5LjI1NzYgMzkuMjE1OCA5LjI1NzgxSDM3LjI2MjdWNi45NDgyNEgzOS43NjM3VjguNzEwOTRaTTQ3LjQ1NDEgNS41ODU5NEM0Ni4yMTQ0IDYuOTI4NCA0NC41Mzc1IDcuODYyNTcgNDIuNjQ5NCA4LjE2NDA2VjkuMDczMjRDNDMuNDc4NiA4Ljk1Mjc3IDQ0LjY1ODcgOC43NTU5OCA0NS4zNzExIDguNDA2MjVWOC43NDMxNkg1MC41NDM5VjguNDE3OTdDNTEuMTk3OCA4Ljc0NDM0IDUyLjQxMjIgOC45NDExMSA1My4yNzY0IDkuMDczMjRMNTMuMjc3MyA4LjE5NjI5QzUzLjI0OCA4LjE4Njc5IDUzLjIxODYgOC4xNzc1MiA1My4xODk1IDguMTY3OTdDNTEuMzA2IDcuODcyNjcgNDkuNjMxNiA2Ljk0OCA0OC4zODk2IDUuNjE2MjFMNDcuNDU0MSA1LjU4NTk0Wk0zMy42OTkyIDcuMTY3OTdDMzMuODU5OCA4LjIyNTk3IDM0LjQ2NTQgOS4wMjk4NiAzNC40Nzc1IDkuMDQ1OUgzNS40NTEyQzM1LjQ0NDIgOS4wMzEwOCAzNC45MzE2IDcuOTM5OTcgMzQuOTMxNiA3LjE2Nzk3SDMzLjY5OTJaTTM4LjExMTMgNy4xNjc5N0MzOC4xMTEzIDcuOTM3OCAzNy42MDE2IDkuMDI1MTEgMzcuNTkxOCA5LjA0NTlIMzguNTY1NEMzOC41ODE1IDkuMDI0NjUgMzkuMTgzNyA4LjIyMjQ0IDM5LjM0MzggNy4xNjc5N0gzOC4xMTEzWk00Ny45NjM5IDYuNjExMzNDNDguMzI1OSA3LjA0MjU0IDQ4Ljg3NDggNy40NzQwNiA0OS42MTA0IDcuOTA1MjdINDYuMjkzQzQ3LjA1MjEgNy40NjIyNSA0Ny42MDE4IDcuMDMxMDMgNDcuOTYzOSA2LjYxMTMzWiIgZmlsbD0id2hpdGUiLz4KPC9zdmc+Cg==",Lw="data:image/svg+xml;base64,PHN2ZyBwcmVzZXJ2ZUFzcGVjdFJhdGlvPSJub25lIiBvdmVyZmxvdz0idmlzaWJsZSIgc3R5bGU9ImRpc3BsYXk6IGJsb2NrOyIgd2lkdGg9IjEyIiBoZWlnaHQ9IjEyIiB2aWV3Qm94PSIwIDAgMTIgMTIiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxnIGlkPSIxLWNvbW1vbl9zZWFyY2hfbGluZV8yNHgyNCI+CjxnIGlkPSJ1bmlvbiI+CjxwYXRoIGZpbGwtcnVsZT0iZXZlbm9kZCIgY2xpcC1ydWxlPSJldmVub2RkIiBkPSJNNS44NjAxMyAxLjkyNTAxQzMuNzI4NzkgMS45MjUwMSAyLjAwMDAyIDMuNjU0NiAyLjAwMDAyIDUuNzg5MzdDMi4wMDAwMiA3LjkyNDEzIDMuNzI4NzkgOS42NTM3MiA1Ljg2MDEzIDkuNjUzNzJDNy45OTE0NyA5LjY1MzcyIDkuNzIwMjQgNy45MjQxMyA5LjcyMDI0IDUuNzg5MzdDOS43MjAyNCAzLjY1NDYgNy45OTE0NyAxLjkyNTAxIDUuODYwMTMgMS45MjUwMVpNMC44MDAwMjQgNS43ODkzN0MwLjgwMDAyNCAyLjk5Mjk0IDMuMDY0OTcgMC43MjUwMTIgNS44NjAxMyAwLjcyNTAxMkM4LjY1NTI5IDAuNzI1MDEyIDEwLjkyMDIgMi45OTI5NCAxMC45MjAyIDUuNzg5MzdDMTAuOTIwMiA4LjU4NTggOC42NTUyOSAxMC44NTM3IDUuODYwMTMgMTAuODUzN0MzLjA2NDk3IDEwLjg1MzcgMC44MDAwMjQgOC41ODU4IDAuODAwMDI0IDUuNzg5MzdaIiBmaWxsPSJ3aGl0ZSIvPgo8cGF0aCBmaWxsLXJ1bGU9ImV2ZW5vZGQiIGNsaXAtcnVsZT0iZXZlbm9kZCIgZD0iTTkuMDEzMTkgOC45MzQ5N0M5LjI0NzQgOC43MDA1NCA5LjYyNzExIDguNzAwNTQgOS44NjEzMiA4LjkzNDk3TDExLjA1MDggMTAuMTI1NkMxMS4yODUgMTAuMzYgMTEuMjg1IDEwLjc0MDEgMTEuMDUwOCAxMC45NzQ1QzEwLjgxNjYgMTEuMjA4OSAxMC40MzY5IDExLjIwODkgMTAuMjAyNyAxMC45NzQ1TDkuMDEzMTkgOS43ODM5QzguNzc4OTkgOS41NDk0OCA4Ljc3ODk5IDkuMTY5NCA5LjAxMzE5IDguOTM0OTdaIiBmaWxsPSJ3aGl0ZSIvPgo8L2c+CjwvZz4KPC9zdmc+Cg==",Cw="data:image/svg+xml;base64,PHN2ZyBwcmVzZXJ2ZUFzcGVjdFJhdGlvPSJub25lIiBvdmVyZmxvdz0idmlzaWJsZSIgc3R5bGU9ImRpc3BsYXk6IGJsb2NrOyIgd2lkdGg9IjY3IiBoZWlnaHQ9IjIyIiB2aWV3Qm94PSIwIDAgNjcgMjIiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxwYXRoIGlkPSJTdWJ0cmFjdCIgZD0iTTY2IDBDNjYuMzM3MiAwIDY2LjY3MDYgMC4wMTcxODM4IDY3IDAuMDQ2ODc1QzYxLjM5MzYgMC41NTIxODkgNTcgNS4yNjIwMiA1NyAxMUM1NyAxNi43MzggNjEuMzkzNiAyMS40NDY4IDY3IDIxLjk1MjFDNjYuNjcwNiAyMS45ODE4IDY2LjMzNzIgMjIgNjYgMjJIMTFDNC45MjQ4NyAyMiAwIDE3LjA3NTEgMCAxMUMwIDQuOTI0ODcgNC45MjQ4NyAyLjY1NzU2ZS0wNyAxMSAwSDY2Wk04LjI0MzE2IDYuNzM1MzVDOC4yNDMxNiA2LjU5Mzk3IDguMTQyNTggNi41MzU3NiA4LjAxOTUzIDYuNjA2NDVMNi4yMjI2NiA3LjY0MDYyQzYuMTU3ODcgNy42ODIyOCA2LjEwNDE2IDcuNzM5MTcgNi4wNjU0MyA3LjgwNTY2QzYuMDI2NzIgNy44NzIyNyA2LjAwNDEgNy45NDc1MiA2IDguMDI0NDFWMTMuOTY1OEM2LjAwMzcxIDE0LjA0MzQgNi4wMjU4NSAxNC4xMTkxIDYuMDY0NDUgMTQuMTg2NUM2LjEwMzE5IDE0LjI1NCA2LjE1NzQgMTQuMzEyIDYuMjIyNjYgMTQuMzU0NUw5Ljg3MTA5IDE2LjQ1OEM5Ljk5MzQ2IDE2LjUyNzIgMTAuMDkzNiAxNi41ODQyIDEwLjA5NDcgMTYuNTg1OUMxMC4wOTQ3IDE2LjU4NzEgMTAuMTkzNCAxNi42NDUxIDEwLjMxNjQgMTYuNzE1OEwxMi41MDEgMTcuOTY5N0MxMi42MjI4IDE4LjA0MDMgMTIuNzIzNiAxNy45ODIyIDEyLjcyMzYgMTcuODQwOFYxMi4zNjcyQzEyLjcyMyAxMi4yOTk0IDEyLjY5NTcgMTIuMjM0MyAxMi42NDc1IDEyLjE4NjVDMTIuNTk5MiAxMi4xMzg4IDEyLjUzMzggMTIuMTEyMyAxMi40NjU4IDEyLjExMjNIMTAuNzM3M0MxMC42NzAyIDEyLjExMzIgMTAuNjA1OSAxMi4xMzk5IDEwLjU1ODYgMTIuMTg3NUMxMC41MTEzIDEyLjIzNTIgMTAuNDg0NyAxMi4zMDAxIDEwLjQ4NDQgMTIuMzY3MlYxMy44Mzc5QzEwLjQ4NDIgMTMuOTc4OSAxMC4zODQ2IDE0LjAzNjQgMTAuMjYxNyAxMy45NjU4TDguNDY0ODQgMTIuOTM1NUM4LjQwMDI2IDEyLjg5MzUgOC4zNDYxNCAxMi44MzcyIDguMzA3NjIgMTIuNzcwNUM4LjI2OTE5IDEyLjcwNCA4LjI0NzM1IDEyLjYyOTQgOC4yNDMxNiAxMi41NTI3VjYuNzM1MzVaTTI0LjMzNCAxNC4zOTI2QzI0LjMzMzkgMTQuOTk4NSAyNC4yMDU1IDE1LjE4NDYgMjMuNTk4NiAxNS4xOTYzTDIyLjMwMTggMTUuMjU0OUwyMi42NjUgMTYuMjU0OUgyNS4wODY5QzI1LjY3MDUgMTYuMDg0IDI1Ljg3MjEgMTUuNzE5NCAyNS44NzIxIDE0LjgyMzJWNS43ODIyM0wyNC4zMzQgNS43MjM2M1YxNC4zOTI2Wk0zMi4yODIyIDE0LjQ3NTZDMzEuOTQ2IDE1LjA0OTIgMzEuNDY1OSAxNS43NTcxIDMxLjA5OTYgMTYuMjU0OUgzMi42MTkxQzMzLjA2NzMgMTUuNTIxMiAzMy4zNzUxIDE0LjkyOCAzMy41NDg4IDE0LjQ3NTZIMzIuMjgyMlpNMzQuODEwNSAxNS4zOTc1QzM0Ljg3OTEgMTUuNzEwMSAzNC45MzExIDE1Ljk5ODIgMzQuOTczNiAxNi4yNTQ5SDM2LjE4NjVMMzYuMTgxNiAxNi4yMzU0QzM2LjA2NjIgMTUuNzM4OCAzNS44OTg5IDE1LjAxOCAzNS43NDEyIDE0LjQ3NTZIMzQuNTI5M0wzNC44MTA1IDE1LjM5NzVaTTM2Ljk4MTQgMTQuNjUzM0MzNy4wOTg0IDE0Ljg3NyAzNy4yNDExIDE1LjE1MDEgMzcuMzMzIDE1LjQwMjNMMzcuNjM1NyAxNi4yNTQ5SDM5LjA4MDFDMzkuMDMzNiAxNS44MzI1IDM4LjU5NCAxNS4wNTUzIDM4LjIzODMgMTQuNDc1NkgzNi44ODg3QzM2LjkxNjEgMTQuNTI5OCAzNi45NDggMTQuNTg5NCAzNi45ODE0IDE0LjY1MzNaTTM5LjI3MDUgMTQuNDc1NkMzOS44MzAxIDE1LjE4MjEgNDAuMTg2MyAxNS44MDA0IDQwLjQxMzEgMTYuMjU0OUg0MS44MzVDNDEuNzM2NyAxNS42NjU2IDQxLjIyOTIgMTQuOTkzNiA0MC43NzY0IDE0LjQ3NTZIMzkuMjcwNVpNNDMuOTIyOSAxNS4wMDQ5SDQyLjc2NjZWMTUuOTk2MUg1My4xMjVWMTUuMDA0OUg1MS45Njg4VjEyLjQ3NTZINDMuOTIyOVYxNS4wMDQ5Wk0xMC43MDQxIDQuMDMwMjdDMTAuNTgxMSAzLjk1OTU4IDEwLjQ4MDUgNC4wMTc4IDEwLjQ4MDUgNC4xNTkxOFY5LjYyMzA1QzEwLjQ4MDYgOS42OTA3NCAxMC41MDc4IDkuNzU1NzggMTAuNTU1NyA5LjgwMzcxQzEwLjYwMzcgOS44NTE3MSAxMC42NjkzIDkuODc4ODcgMTAuNzM3MyA5Ljg3ODkxSDEyLjQ2NDhDMTIuNDk4NiA5Ljg3OTA1IDEyLjUzMjIgOS44NzIxNyAxMi41NjM1IDkuODU5MzhDMTIuNTk0NCA5Ljg0NjY2IDEyLjYyMjcgOS44MjgyMSAxMi42NDY1IDkuODA0NjlDMTIuNjcwNCA5Ljc4MDg5IDEyLjY5MDIgOS43NTE4NSAxMi43MDMxIDkuNzIwN0MxMi43MTYgOS42ODk3NSAxMi43MjI2IDkuNjU2NTQgMTIuNzIyNyA5LjYyMzA1VjguMTUyMzRDMTIuNzIyNyA4LjAxMSAxMi44MjIzIDcuOTUyODIgMTIuOTQ1MyA4LjAyMzQ0TDE0Ljc0MTIgOS4wNjE1MkMxNC44MDYgOS4xMDM2MiAxNC44NTk3IDkuMTYwNzcgMTQuODk4NCA5LjIyNzU0QzE0LjkzNzEgOS4yOTQzIDE0Ljk1OTYgOS4zNjkyOSAxNC45NjM5IDkuNDQ2MjlWMTUuMjU5OEMxNC45NjQxIDE1LjQwMDcgMTUuMDYzNyAxNS40NTcgMTUuMTg2NSAxNS4zODc3TDE2Ljk4NDQgMTQuMzUwNkMxNy4wNDkgMTQuMzA4NyAxNy4xMDMgMTQuMjUyMSAxNy4xNDE2IDE0LjE4NTVDMTcuMTgwMyAxNC4xMTg3IDE3LjIwMyAxNC4wNDMgMTcuMjA3IDEzLjk2NThWOC4wMjQ0MUMxNy4yMDI5IDcuOTQ3MzYgMTcuMTgwMyA3Ljg3MjQ2IDE3LjE0MTYgNy44MDU2NkMxNy4xMDI5IDcuNzM4ODQgMTcuMDQ5MyA3LjY4MTY0IDE2Ljk4NDQgNy42Mzk2NUwxMS44MjMyIDQuNjY3OTdDMTEuNzAwMiA0LjU5NzI4IDExLjU5NzcgNC41NDEwMiAxMS41OTc3IDQuNTQxMDJDMTEuNTg0NiA0LjUzMDQ3IDExLjQ4NzkgNC40ODIxMyAxMS4zNzIxIDQuNDE1MDRMMTAuNzA0MSA0LjAzMDI3Wk00Ni4yNDcxIDE1LjAwNDlINDUuMDkwOFYxMy4zMzY5SDQ2LjI0NzFWMTUuMDA0OVpNNDguNTI0NCAxNS4wMDQ5SDQ3LjM3OTlWMTMuMzM2OUg0OC41MjQ0VjE1LjAwNDlaTTUwLjgzNTkgMTUuMDA0OUg0OS42NTcyVjEzLjMzNjlINTAuODM1OVYxNS4wMDQ5Wk0zMi4wNjE1IDEwLjM2NTJIMzUuODAwOFYxMC45ODI0SDMxLjk4NjNWMTIuMDkwOEgzNS44MDA4VjEyLjc1NDlIMzEuMjUxVjEzLjgyNzFINDEuNzY1NlYxMi43NTQ5SDM3LjI2MjdWMTIuMDkwOEg0MS4wMjkzVjEwLjk4MjRIMzcuMjYyN1YxMC4zNjUySDM5Ljg1ODRDNDAuNDYzNCAxMC4zNjUyIDQwLjk1NCA5Ljg3NTQzIDQwLjk1NDEgOS4yNzE0OFY2LjAxNjZIMzIuMDYxNVYxMC4zNjUyWk0yMS4yNDQxIDguMzAzNzFDMjAuOTY4NiA5LjU3MTM4IDIwLjcxMzcgMTAuNTAxIDIwLjQ4MDUgMTEuMDkzOEMyMC4yNDcyIDExLjY4NjMgMTkuODEyNiAxMi41MDg2IDE5LjE3NDggMTMuNTYyNUwxOS4xMTUyIDEzLjY2MTFIMjAuNTc5MUwyMC41OTg2IDEzLjYzMzhDMjEuMzE2NiAxMi42MTg4IDIxLjgwNzUgMTEuNzYwNCAyMi4wNjc0IDExLjA1OTZDMjIuMzI1NyAxMC4zNjI4IDIyLjU4MzUgOS40NTMxMSAyMi44NDA4IDguMzMyMDNMMjIuODU4NCA4LjI1MjkzSDIxLjI1NDlMMjEuMjQ0MSA4LjMwMzcxWk0yNy4xOTA0IDguNjk4MjRDMjcuNDE5MiA5LjY1Mjc1IDI3LjY0ODMgMTAuNDQwMiAyNy44Nzc5IDExLjA1OTZDMjguMTM3OCAxMS43NjAzIDI4LjYyNzggMTIuNjE4OSAyOS4zNDU3IDEzLjYzMzhMMjkuMzY1MiAxMy42NjExSDMwLjgyOTFMMzAuNjE0MyAxMy4zMDQ3QzMwLjA2MDQgMTIuMzczNiAyOS42Nzc2IDExLjYzNjggMjkuNDYzOSAxMS4wOTM4QzI5LjIzMDYgMTAuNTAxIDI4Ljk3NTggOS41NzEzOCAyOC43MDAyIDguMzAzNzFMMjguNjg5NSA4LjI1MjkzSDI3LjA4NTlMMjcuMTkwNCA4LjY5ODI0Wk00NC4zNTQ1IDExLjg5MjZINTAuNDc2NkM1MS4wODE1IDExLjg5MjUgNTEuNTcyMSAxMS40MDI3IDUxLjU3MjMgMTAuNzk4OFY5LjM1MDU5SDQ0LjM1NDVWMTEuODkyNlpNNTAuNDI3NyAxMC40MDE0QzUwLjQyNzUgMTAuNzAzMiA1MC4xODIzIDEwLjk0ODIgNDkuODc5OSAxMC45NDgySDQ1LjQ5OVYxMC4yODMySDUwLjQyNzdWMTAuNDAxNFpNMzUuODAwOCA5LjI1NzgxSDMzLjI1MjlWNi45NDgyNEgzNS44MDA4VjkuMjU3ODFaTTM5Ljc2MzcgOC43MTA5NEMzOS43NjM1IDkuMDEyNjYgMzkuNTE4MSA5LjI1NzYgMzkuMjE1OCA5LjI1NzgxSDM3LjI2MjdWNi45NDgyNEgzOS43NjM3VjguNzEwOTRaTTQ3LjQ1NDEgNS41ODU5NEM0Ni4yMTQ0IDYuOTI4NCA0NC41Mzc1IDcuODYyNTcgNDIuNjQ5NCA4LjE2NDA2VjkuMDczMjRDNDMuNDc4NiA4Ljk1Mjc3IDQ0LjY1ODcgOC43NTU5OCA0NS4zNzExIDguNDA2MjVWOC43NDMxNkg1MC41NDM5VjguNDE3OTdDNTEuMTk3OCA4Ljc0NDM0IDUyLjQxMjIgOC45NDExMSA1My4yNzY0IDkuMDczMjRMNTMuMjc3MyA4LjE5NjI5QzUzLjI0OCA4LjE4Njc5IDUzLjIxODYgOC4xNzc1MiA1My4xODk1IDguMTY3OTdDNTEuMzA2IDcuODcyNjcgNDkuNjMxNiA2Ljk0OCA0OC4zODk2IDUuNjE2MjFMNDcuNDU0MSA1LjU4NTk0Wk0zMy42OTkyIDcuMTY3OTdDMzMuODU5OCA4LjIyNTk3IDM0LjQ2NTQgOS4wMjk4NiAzNC40Nzc1IDkuMDQ1OUgzNS40NTEyQzM1LjQ0NDIgOS4wMzEwOCAzNC45MzE2IDcuOTM5OTcgMzQuOTMxNiA3LjE2Nzk3SDMzLjY5OTJaTTM4LjExMTMgNy4xNjc5N0MzOC4xMTEzIDcuOTM3OCAzNy42MDE2IDkuMDI1MTEgMzcuNTkxOCA5LjA0NTlIMzguNTY1NEMzOC41ODE1IDkuMDI0NjUgMzkuMTgzNyA4LjIyMjQ0IDM5LjM0MzggNy4xNjc5N0gzOC4xMTEzWk00Ny45NjM5IDYuNjExMzNDNDguMzI1OSA3LjA0MjU0IDQ4Ljg3NDggNy40NzQwNiA0OS42MTA0IDcuOTA1MjdINDYuMjkzQzQ3LjA1MjEgNy40NjIyNSA0Ny42MDE4IDcuMDMxMDMgNDcuOTYzOSA2LjYxMTMzWiIgZmlsbD0iYmxhY2siLz4KPC9zdmc+Cg==",Rw="data:image/svg+xml;base64,PHN2ZyBwcmVzZXJ2ZUFzcGVjdFJhdGlvPSJub25lIiBvdmVyZmxvdz0idmlzaWJsZSIgc3R5bGU9ImRpc3BsYXk6IGJsb2NrOyIgd2lkdGg9IjEyIiBoZWlnaHQ9IjEyIiB2aWV3Qm94PSIwIDAgMTIgMTIiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxnIGlkPSIxLWNvbW1vbl9zZWFyY2hfbGluZV8yNHgyNCI+CjxnIGlkPSJ1bmlvbiI+CjxwYXRoIGZpbGwtcnVsZT0iZXZlbm9kZCIgY2xpcC1ydWxlPSJldmVub2RkIiBkPSJNNS44NjAxMyAxLjkyNTAxQzMuNzI4NzkgMS45MjUwMSAyLjAwMDAyIDMuNjU0NiAyLjAwMDAyIDUuNzg5MzdDMi4wMDAwMiA3LjkyNDEzIDMuNzI4NzkgOS42NTM3MiA1Ljg2MDEzIDkuNjUzNzJDNy45OTE0NyA5LjY1MzcyIDkuNzIwMjQgNy45MjQxMyA5LjcyMDI0IDUuNzg5MzdDOS43MjAyNCAzLjY1NDYgNy45OTE0NyAxLjkyNTAxIDUuODYwMTMgMS45MjUwMVpNMC44MDAwMjQgNS43ODkzN0MwLjgwMDAyNCAyLjk5Mjk0IDMuMDY0OTcgMC43MjUwMTIgNS44NjAxMyAwLjcyNTAxMkM4LjY1NTI5IDAuNzI1MDEyIDEwLjkyMDIgMi45OTI5NCAxMC45MjAyIDUuNzg5MzdDMTAuOTIwMiA4LjU4NTggOC42NTUyOSAxMC44NTM3IDUuODYwMTMgMTAuODUzN0MzLjA2NDk3IDEwLjg1MzcgMC44MDAwMjQgOC41ODU4IDAuODAwMDI0IDUuNzg5MzdaIiBmaWxsPSJibGFjayIvPgo8cGF0aCBmaWxsLXJ1bGU9ImV2ZW5vZGQiIGNsaXAtcnVsZT0iZXZlbm9kZCIgZD0iTTkuMDEzMTkgOC45MzQ5N0M5LjI0NzQgOC43MDA1NCA5LjYyNzExIDguNzAwNTQgOS44NjEzMiA4LjkzNDk3TDExLjA1MDggMTAuMTI1NkMxMS4yODUgMTAuMzYgMTEuMjg1IDEwLjc0MDEgMTEuMDUwOCAxMC45NzQ1QzEwLjgxNjYgMTEuMjA4OSAxMC40MzY5IDExLjIwODkgMTAuMjAyNyAxMC45NzQ1TDkuMDEzMTkgOS43ODM5QzguNzc4OTkgOS41NDk0OCA4Ljc3ODk5IDkuMTY5NCA5LjAxMzE5IDguOTM0OTdaIiBmaWxsPSJibGFjayIvPgo8L2c+CjwvZz4KPC9zdmc+Cg==";async function Pw(e,t,r,n,i="dark"){X(n);const o=e.defaultView;if(!o||!e.body)throw new Error("截图水印缺少可用的展示窗口");const s=e.createElement("div"),a=i==="light",c=a?"black":"white";s.dataset.miniProgramScreenshotWatermark="",s.setAttribute("aria-hidden","true");const d=Math.min(1,r.width/200,r.height/57);s.style.cssText=`position:absolute;left:${r.left+o.scrollX}px;top:${r.top+o.scrollY+r.height-57*d}px;width:${r.width}px;height:${57*d}px;z-index:2147483647;pointer-events:none;overflow:hidden;`;const u=e.createElement("div");u.style.cssText=`display:flex;flex-direction:column;align-items:center;width:${r.width/d}px;height:57px;transform:scale(${d});transform-origin:top left;font-family:"PingFang SC",sans-serif;`;const l=e.createElement("div");l.style.cssText="display:flex;align-items:center;max-width:calc(100% - 24px);height:22px;flex-shrink:0;";const f=e.createElement("img");f.src=a?Cw:vw,f.style.cssText="width:67px;height:22px;flex-shrink:0;margin-right:-11px;";const m=e.createElement("div");m.style.cssText=`display:flex;align-items:center;gap:2px;min-width:0;height:22px;box-sizing:border-box;border:1.5px solid ${c};border-radius:11px;padding:0 7px 0 6px;`;const h=e.createElement("img");h.src=a?Rw:Lw,h.style.cssText="width:12px;height:12px;flex-shrink:0;";const g=e.createElement("span");g.textContent=t?.trim()||"小程序工坊",g.style.cssText=`color:${c};font-size:11px;font-weight:500;line-height:16px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;`;const I=e.createElement("div");I.textContent="小黑盒工坊小程序",I.style.cssText=`margin-top:6px;color:${a?"rgba(0,0,0,0.4)":"rgba(255,255,255,0.4)"};font-size:11px;font-weight:400;line-height:16px;white-space:nowrap;`,m.append(h,g),l.append(f,m),u.append(l,I),s.append(u),e.body.append(s);const y=()=>{s.remove(),n.removeEventListener("abort",y)};n.addEventListener("abort",y,{once:!0});try{return await $(()=>Promise.all([f.decode(),h.decode()]),n),await $(()=>new Promise(b=>{let _=o.requestAnimationFrame(()=>{_=o.requestAnimationFrame(()=>{n.removeEventListener("abort",P),b()})});const P=()=>o.cancelAnimationFrame(_);n.addEventListener("abort",P,{once:!0})}),n),y}catch(b){throw y(),b}}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)*)?$/,jw=/^[a-f0-9]{64}$/,zw=255,Hw=160,Fw=256;function Bw(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>Fw||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>Hw||!Uw.test(i)))return;const o=r.sanitizedPathnameHash;if(!(o!==void 0&&(typeof o!="string"||!jw.test(o)||i===void 0)))return{effectiveDirective:r.effectiveDirective,violatedDirective:r.effectiveDirective,blockedResourceType:r.blockedResourceType,origin:n,sanitizedPathname:i,sanitizedPathnameHash:o,sdkVersion:r.sdkVersion,timestamp:r.timestamp}}function Vw(e){if(e!==void 0&&!(typeof e!="string"||e.length>zw))try{const t=new URL(e);return["http:","https:"].includes(t.protocol)&&t.origin===e?t.origin:void 0}catch{return}}const Gw=/^(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 qw(e){if(!e?.minimumSdkVersion)throw ee("MINIMUM_SDK_VERSION_UNAVAILABLE","平台最低 SDK 版本配置不可用");const t=Nt(e.minimumSdkVersion),r=e.sdkVersion?Nt(e.sdkVersion):void 0;if(!t)throw ee("MINIMUM_SDK_VERSION_UNAVAILABLE","平台最低 SDK 版本配置不合法");if(e.sdkVersion&&!r)throw ee("SDK_VERSION_INVALID","小程序 SDK 版本不合法");const n=Nt("0.6.0");if(!r){if(Sn(t,n)<0)return{heartbeatEnabled:!1,sdkVersion:void 0};throw ee("SDK_VERSION_INVALID","小程序 SDK 版本缺失")}if((e.releaseChannel??"public")==="public"&&r.prerelease.length>0&&e.allowPublicPrerelease!==!0)throw ee("SDK_VERSION_INVALID","正式小程序不能使用预发布 SDK");if(Sn(r,t)<0)throw ee("SDK_VERSION_TOO_LOW","小程序 SDK 版本低于平台最低要求");return{heartbeatEnabled:Sn(r,Nt("0.6.0-0"))>=0,sdkVersion:e.sdkVersion}}function Qw(e,t){if(typeof t!="string"||!Nt(t))throw ee("SDK_VERSION_INVALID","SDK handshake 版本不合法");if(t!==e)throw ee("SDK_VERSION_MISMATCH","SDK handshake 版本与 Version record 不一致")}function ml(e,t){const r=Nt(e),n=Nt(t);if(!(!r||!n))return Sn(r,n)}function Nt(e){const t=Gw.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 Sn(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],o=t.prerelease[n];if(i===void 0||o===void 0)return i===o?0:i===void 0?-1:1;if(i!==o)return typeof i=="number"&&typeof o=="string"?-1:typeof i=="string"&&typeof o=="number"?1:i<o?-1:1}return 0}const Vi=["android","ios","ohos","windows","macos","linux"],Yw="0.9.0",Ww=Object.freeze(["android","ios","ohos","windows","macos"]),gl="该小程序暂不支持当前平台",$w="PLATFORM_UNSUPPORTED";function Kw(e){return typeof e=="string"&&Vi.includes(e)}function Zw(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 Jw(e){const t=e.manifest;if(!nI(t))return{status:"invalid",reason:"manifest_not_object"};if(!Object.prototype.hasOwnProperty.call(t,"platforms")){const n=jc(e.sdkVersion)??jc(t.sdkVersion);return tI(n)?{status:"invalid",reason:"platforms_missing_after_hard_cutover"}:eI()}const r=pl(t.platforms);return"reason"in r?{status:"invalid",reason:r.reason}:{status:"resolved",declaredPlatforms:r.platforms,effectivePlatforms:r.platforms,platformsDeclared:!0,policy:"explicit"}}function Xw(e){const t=Zw(e.operatingSystemName);if(!t)return Gt("host_operating_system_unknown");const r=e.platformAccess;if(!r)return Gt("platform_access_missing",{platform:t});if(r.source==="compatibility-window")return{status:"allowed",platform:t,effectivePlatforms:Vi,platformsDeclared:!1,policy:"legacy_mobile_default",compatibility:r.reason};if(r.source==="manifest"){const s=Jw({manifest:r.manifest,...r.sdkVersion===void 0?{}:{sdkVersion:r.sdkVersion}});return s.status==="invalid"?Gt("platform_declaration_invalid",{invalidReason:s.reason,platform:t}):Uc(t,s)}if(r.effectivePlatforms===void 0)return Gt("platform_declaration_invalid",{invalidReason:"effective_platforms_missing",platform:t});const n=pl(r.effectivePlatforms);if("reason"in n)return Gt("platform_declaration_invalid",{invalidReason:n.reason,platform:t});const i=typeof r.platformsDeclared=="boolean"?r.platformsDeclared:!0,o=rI(r.platformPolicy)?r.platformPolicy:i?"explicit":"legacy_mobile_default";return Uc(t,{declaredPlatforms:i?n.platforms:[],effectivePlatforms:n.platforms,platformsDeclared:i,policy:o})}function Uc(e,t){return t.effectivePlatforms.includes(e)?{status:"allowed",platform:e,effectivePlatforms:t.effectivePlatforms,platformsDeclared:t.platformsDeclared,policy:t.policy}:Gt("platform_not_supported",{effectivePlatforms:t.effectivePlatforms,platform:e})}function Gt(e,t={}){return{status:"denied",reason:e,message:gl,...t}}function eI(){return{status:"resolved",declaredPlatforms:[],effectivePlatforms:Ww,platformsDeclared:!1,policy:"legacy_mobile_default"}}function pl(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(!Kw(r))return{reason:"platform_unknown_value"};if(t.has(r))return{reason:"platform_duplicate_value"};t.add(r)}return{platforms:Object.freeze(Vi.filter(r=>t.has(r)))}}function tI(e){if(typeof e!="string"||!e.trim())return!1;const t=ml(e.trim(),Yw);return t!==void 0&&t>=0}function jc(e){return typeof e=="string"&&e.trim()?e.trim():void 0}function rI(e){return e==="explicit"||e==="legacy_mobile_default"}function nI(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const iI=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 oI(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:sI(i.pathname),sanitizedPathnameHash:aI(i.pathname)}}catch{return{type:"security_violation",errorCode:e,timestamp:n,sdkVersion:r}}}function sI(e){return(e==="/"?e:e.replace(/\/+$/,"")).split("/").map(r=>r?":segment":"").join("/")}function aI(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]),o=new Uint32Array(64),s=new DataView(n.buffer);for(let a=0;a<r;a+=64){for(let I=0;I<16;I+=1)o[I]=s.getUint32(a+I*4,!1);for(let I=16;I<64;I+=1){const y=o[I-15],b=o[I-2],_=Ve(y,7)^Ve(y,18)^y>>>3,P=Ve(b,17)^Ve(b,19)^b>>>10;o[I]=o[I-16]+_+o[I-7]+P>>>0}let[c,d,u,l,f,m,h,g]=i;for(let I=0;I<64;I+=1){const y=g+(Ve(f,6)^Ve(f,11)^Ve(f,25))+(f&m^~f&h)+iI[I]+o[I]>>>0,b=(Ve(c,2)^Ve(c,13)^Ve(c,22))+(c&d^c&u^d&u);g=h,h=m,m=f,f=l+y>>>0,l=u,u=d,d=c,c=y+b>>>0}[c,d,u,l,f,m,h,g].forEach((I,y)=>{i[y]=i[y]+I>>>0})}return Array.from(i,a=>a.toString(16).padStart(8,"0")).join("")}function Ve(e,t){return e>>>t|e<<32-t}const cI=1e4,dI=1e4,yo=2e3,uI=2,lI="open-with-native-credential-policy",yl="安全提示",El="即将打开未经验证的开发网页。该页面可能由本机或局域网服务提供,请确认来源可信后继续。";class fI{nonce=Aa();runtimeId=Aa();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;unexpectedDocumentLoadTimer;devDocumentDisposer;documentRevalidationPending=!1;documentRevalidationTimer;documentRevalidationGeneration=0;preparedHistoryTraversalGeneration;iframeVisibilityBeforeRevalidation;iframeHiddenForRevalidation=!1;devRuntimePromise;runtimePermissions=void 0;networkPolicy;networkPolicyDisposer;runtimeFeatures;miniProgramPresentation;miniProgramDetail;locationBasePath;anonymousStorageScope;allowedHttpOrigins;environmentInfo;constructor(t){this.options=t,this.iframe=t.iframe;const r=ru(t.ports,{callerCapabilities:t.capabilities,hostCapabilities:t.hostCapabilities});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??cI,this.iframeErrorListener=n=>{this.onIframeError(n)},this.iframeLoadListener=()=>{if(this.awaitingControlledDocumentLoad){if(this.awaitingControlledDocumentLoad=!1,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}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??ee("RUNTIME_DESTROYED","小程序运行时已销毁")):this.stateValue==="failed"?Promise.reject(this.terminalError??ee("STARTUP_ERROR","小程序运行时启动失败")):this.readyContext?Promise.resolve(this.readyContext):this.startPromise?this.startPromise:(MI(),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??ee("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.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.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=Kh(t.runtimePermissions),this.networkPolicy=nu(t.networkPolicy),this.networkPolicy?.enforcement==="restricted"){const s=t.canonicalIdentity?.miniProgramId?.trim();if(!s||!this.options.networkPolicyEnforcement)throw{code:"NETWORK_POLICY_UNSUPPORTED",message:"当前 Host 尚未具备严格网络策略执行能力,请更新 Host 后重新打开"};const a=await Ch(this.options.networkPolicyEnforcement,{policy:this.networkPolicy,miniProgramId:s,launchUrl:t.launchUrl,onInvalidated:()=>this.failRuntime({code:"NETWORK_POLICY_CHANGED",message:"网络权限已变更,请重新打开小程序"})},{signal:this.terminalController.signal});if(this.isInactive()){a();return}this.networkPolicyDisposer=a}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=qw(t.sdkVersionPolicy);const n=_w(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=Xw({operatingSystemName:t.environmentInfo?.operatingSystem?.name,...t.platformAccess===void 0?{}:{platformAccess:t.platformAccess}}),this.platformGateDecision.status==="denied")throw bI(this.platformGateDecision);if(this.miniProgramDetail=TI(t),this.effectiveCapabilities=tu(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),wI(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 o=await this.confirmDevMiniProgramLaunch(i);if(!this.isInactive()){if(!o){await this.closeAfterDevLaunchCancellation();return}if(this.bridgeServer?.setTargetOrigin(AI(i)),this.launchUrl=i,this.options.onDevDocumentReload&&t.sdkVersionPolicy?.releaseChannel==="development"){const s=iu(new URL(i),this.locationBasePath);this.devDocumentDisposer=$h({iframe:this.iframe,launchUrl:i,nonce:this.nonce,locationBasePath:s,onLeaving:()=>{this.prepareForHistoryTraversal()},onResume:()=>{!this.isInactive()&&this.documentRevalidationPending&&this.beginDocumentRevalidation()},onReload:a=>{this.isInactive()||ke(c=>this.options.onDevDocumentReload?.(c,s),a)}})}if(this.miniProgramSrc=Fh(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(s){if(this.isInactive())return;const a=ks(s);this.trace({runtimeId:this.runtimeId,timestamp:Date.now(),type:"error",method:_t,errorCode:a.code,message:`默认展示设置失败,沿用宿主当前布局:${a.message}`})}if(this.isInactive())return}this.awaitingControlledDocumentLoad=!0,this.iframe.src=this.miniProgramSrc,ke(this.options.onLaunch,this.createLaunchContext()),this.armHandshakeTimeout()}}startBridgeServer(){const t={postEvent:(n,i)=>{this.stateValue==="ready"&&(n!=="viewport_change"||this.effectiveCapabilities["viewport.getWindowInfo"])&&(n!=="display_change"||this.effectiveCapabilities[_t])&&this.bridgeServer?.postEvent(n,i)}};this.capabilityGraph=Ew({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,workspaceCards:this.ports.workspaceCards,environment:this.options.environment,identity:this.identityRef,runtimePermissions:this.runtimePermissions,runtimeFeatures:this.runtimeFeatures,networkPolicy:this.networkPolicy,authorizationContext:this.options.authorizationContext,terminalSignal:this.terminalController.signal,eventSink:t,authPresentation:this.options.authPresentation,companionPresentation:this.options.companionPresentation,miniProgramPresentation:this.miniProgramPresentation,prepareLongScreenshot:(n,i)=>Lh(this.iframe,n,i),prepareScreenshot:(n,i,o)=>{const s=this.sdkVersionDecision?.sdkVersion;return!s||(ml(s,"0.9.1")??-1)<0?Promise.resolve(()=>{}):Pw(this.iframe.ownerDocument,this.miniProgramPresentation?.name,n,i,o)},miniProgramDetail:this.miniProgramDetail,anonymousStorageScope:this.anonymousStorageScope,storageLimits:this.options.storageLimits,allowedHttpOrigins:this.allowedHttpOrigins,requestPolicy:this.options.requestPolicy,...this.options.onRequestPolicyReport?{onRequestPolicyReport:this.options.onRequestPolicyReport}:{}});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,policies:this.options.policies,...this.options.onCapabilityTrace?{onTrace:({callId:n,method:i,startedAt:o,timestamp:s,durationMs:a,outcome:c,errorCode:d,network:u})=>{const l={type:"capability",phase:"host",runtimeId:this.runtimeId,callId:n,method:i,startedAt:o,timestamp:s,durationMs:a,outcome:c,...d?{errorCode:d}:{},...this.identity,...u?{network:u}:{}};ke(this.options.onCapabilityTrace,l)}}:{}});this.bridgeServer=new tm({iframe:this.iframe,nonce:this.nonce,dispatcher:r,environmentInfo:this.environmentInfo,...this.options.onDevUploadSession?{onDevUploadSession:n=>{this.isInactive()||ke(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:o})=>{this.trace({runtimeId:this.runtimeId,timestamp:Date.now(),type:"bridge_response",method:n,outcome:i,...o?{errorCode:o}:{}})}}),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(ee("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 EI(t)?t:wl(ee("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 Hh(t,r,{allowPrivateNetwork:xc(r)||zc(r)||await this.isDevRuntime()})}catch(r){throw ee("INVALID_LAUNCH_URL",r instanceof Error?r.message:"小程序链接不合法",r)}}async confirmDevMiniProgramLaunch(t){return await this.shouldConfirmDevMiniProgramLaunch(t)?this.isInactive()?!1:!!await(this.options.confirmDevMiniProgramLaunch??DI)({message:El,title:yl,url:t}):!0}async shouldConfirmDevMiniProgramLaunch(t){if(Da(t)==="production")return!1;const r=this.options.environment.getCurrentHref();return!xc(r)&&!zc(r)}async closeAfterDevLaunchCancellation(){const t=ee("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{Hc(),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(()=>Hc())}async isDevRuntime(){return this.devRuntimePromise??=Promise.resolve().then(()=>this.options.environment.isDevRuntime()).then(Boolean).catch(()=>!1),this.devRuntimePromise}applyIframeDefaults(){this.iframe.setAttribute("allow",xh),this.iframe.setAttribute("referrerpolicy",Uh),this.iframe.setAttribute("sandbox",ou)}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(),ke(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(),ke(this.options.onReady,t)}handleBridgeHandshake(t){const r=this.sdkVersionDecision?.sdkVersion;if(r)try{Qw(r,t?.sdkVersion)}catch(n){return this.failRuntime(n),!1}return!0}armHandshakeTimeout(){this.clearHandshakeTimeout(),!(this.handshakeTimeout<=0)&&(this.handshakeTimeoutTimer=setTimeout(()=>{this.stateValue==="ready"||this.isInactive()||(this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"handshake_timeout"}),this.failRuntime(ee("SDK_HANDSHAKE_TIMEOUT","小程序 SDK 握手超时")))},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>=uI)){this.failRuntime(ee("HEARTBEAT_TIMEOUT","小程序 SDK 心跳超时"));return}const t=`${Date.now().toString(36)}_${++this.probeSequence}`;this.pendingProbeId=t,this.bridgeServer?.postInternalRequest(nn,t,{probeId:t,timestamp:Date.now()}),this.heartbeatTimer=setTimeout(()=>{this.heartbeatTimer=void 0,this.sendLocationProbe()},yo),this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"location_probe",method:nn})}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(nn,t,{probeId:t,timestamp:Date.now()}),this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"location_probe",method:nn})}armDocumentRevalidationTimer(t,r={}){this.clearDocumentRevalidationTimer(),this.hostVisible&&(this.documentRevalidationTimer=setTimeout(()=>{this.documentRevalidationTimer=void 0,!(this.isInactive()||!this.documentRevalidationPending||t!==this.documentRevalidationGeneration)&&this.failRuntime(ee("DOCUMENT_REVALIDATION_TIMEOUT",r.waitingForDocument?"小程序 iframe 目标文档加载超时":"小程序 iframe 文档再验证超时"))},r.waitingForDocument?dI:yo))}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()},yo)),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===Rf){this.handleCspViolation(t.payload);return}if(t.method!==Cf)return;const r=this.sdkVersionDecision?.sdkVersion;if(!r)return;const n=t.payload;if(!n||n.sdkVersion!==r){this.failRuntime(ee("SDK_VERSION_MISMATCH","URL report 的 SDK 版本不一致"));return}if(!(n.probeId!==void 0&&n.probeId!==this.pendingProbeId)){if(typeof n.href!="string"||!su(this.launchUrl,n.href,this.locationBasePath)){typeof n.href=="string"&&this.emitUrlSecurityViolation("URL_OUT_OF_SCOPE",n.href),this.failRuntime(ee("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=Bw(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){ke(this.options.onSecurityViolation,t),this.trace({runtimeId:this.nonce,...t})}emitUrlSecurityViolation(t,r){const n=oI(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(ee("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:kh,launchUrlType:Da(t),networkPolicy:lI})}failRuntime(t){const r=hI(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}),ke(this.options.onError,mI(r)),ke(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,ke(this.options.onStateChange,t))}isInactive(){return this.stateValue==="failed"||this.stateValue==="destroyed"}trace(t){ke(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 hI(e){const t=ks(e);return Si(e)&&"cause"in e&&wl(t,e.cause),t}function wl(e,t){return Object.defineProperty(e,"cause",{configurable:!0,enumerable:!1,value:t}),e}function mI(e){return{code:e.code,message:e.message,...e.data!==void 0?{data:e.data}:{},...e.cause!==void 0?{cause:yI(e.cause)}:{}}}const Eo=(()=>{const e=Object.getOwnPropertyDescriptor(new Error,"stack")?.get,t=Object.getOwnPropertyDescriptor(new Error,"stack")?.get;return typeof e=="function"&&e===t?e:void 0})(),gI=new Set([Error.prototype,TypeError.prototype,RangeError.prototype,ReferenceError.prototype,SyntaxError.prototype,URIError.prototype,EvalError.prototype]);function pI(e,t){const r=Object.getOwnPropertyDescriptor(e,t);if(!r)return;if("value"in r)return r.value;if(t!=="stack"||!Eo||r.get!==Eo)return;const n=Object.getPrototypeOf(e);if(gI.has(n)){for(const i of["name","message"]){const o=Object.getOwnPropertyDescriptor(e,i),s=Object.getOwnPropertyDescriptor(n,i)??Object.getOwnPropertyDescriptor(Error.prototype,i);if(o&&!("value"in o)||s&&!("value"in s))return}return Eo.call(e)}}function yI(e){if(!(!e||typeof e!="object"))try{const t={};for(const r of["name","message","stack"]){const n=pI(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 EI(e){return Si(e)&&typeof e.code=="string"&&typeof e.message=="string"}function Si(e){return!!e&&typeof e=="object"}function ke(e,t){try{e?.(t)}catch{}}function wI(e,t,r){try{e?.(t,r)}catch{}}function zc(e){try{const t=new URL(e);return t.protocol==="http:"&&Dw(t.hostname)}catch{return!1}}function II(e){try{return new URL(e).origin}catch{return}}function AI(e){return jh()?"*":II(e)}function NI(e){return`${yl}
6
-
7
- ${El}
8
-
9
- URL: ${e}`}function DI(e){return typeof window>"u"||typeof window.confirm!="function"?!1:window.confirm(NI(e.url))}function Hc(){typeof window<"u"&&typeof window.close=="function"&&window.close()}function MI(){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:jd,knownMethodCount:ct.length,supportsFileCreate:ct.some(i=>i.method===Pr),system:SI(e?.userAgent,e?.platform),userAgent:e?.userAgent??"",platform:e?.platform??"",language:e?.language??"",hardwareConcurrency:Bt(e?.hardwareConcurrency),maxTouchPoints:Bt(e?.maxTouchPoints),screen:{width:Bt(t?.width),height:Bt(t?.height)},viewport:{width:Bt(r?.innerWidth),height:Bt(r?.innerHeight),devicePixelRatio:_I(r?.devicePixelRatio)}});console.info("[hb-sdk-runtime] environment",n)}function SI(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 Bt(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0?Math.floor(e):0}function _I(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:1}function bI(e){return ee($w,gl,{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 TI(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(),o=e.miniProgramPresentation?.author?.trim();return Object.freeze({miniProgramId:t,...r?{version:r}:{},...n?{name:n}:{},...i?{iconUrl:i}:{},...o?{author:o}:{},...e.sdkVersionPolicy.releaseChannel===void 0?{}:{releaseChannel:e.sdkVersionPolicy.releaseChannel}})}function OI(e){if(!Si(e?.ports)||Array.isArray(e.ports))throw new TypeError("createMiniProgramRuntime 必须显式提供 ports");if(!Si(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 fI(e)}function vI(e={}){return async(t,r,n)=>{if(n.signal.aborted)throw new DOMException("账号标识读取已取消","AbortError");const i=e.indexedDB??globalThis.indexedDB,o=e.crypto??globalThis.crypto;if(!i||!o?.getRandomValues)throw new Error("Host 缺少持久化账号标识能力");const s=await new Promise((a,c)=>{const d=i.open("heybox-mini-program-private-account-v1",1);let u=!1;const l=()=>n.signal.removeEventListener("abort",m),f=h=>{u||(u=!0,l(),c(h))},m=()=>f(new DOMException("账号标识读取已取消","AbortError"));d.onupgradeneeded=()=>{u?d.transaction?.abort():d.result.createObjectStore("accounts")},d.onerror=()=>f(d.error),d.onblocked=()=>f(new Error("账号存储被阻塞")),d.onsuccess=()=>{u?d.result.close():(u=!0,l(),a(d.result))},n.signal.addEventListener("abort",m,{once:!0}),n.signal.aborted&&m()});try{if(n.signal.aborted)throw new DOMException("账号标识读取已取消","AbortError");return await new Promise((a,c)=>{const d=s.transaction("accounts","readwrite"),u=d.objectStore("accounts"),l=JSON.stringify([t,r]);let f;const m=()=>{try{d.abort()}catch{}h(),c(new DOMException("账号标识读取已取消","AbortError"))};n.signal.addEventListener("abort",m,{once:!0});const h=()=>n.signal.removeEventListener("abort",m);d.oncomplete=()=>{h(),a(f)},d.onabort=d.onerror=()=>{h(),c(d.error??new Error("账号存储事务失败"))};const g=u.get(l);g.onsuccess=()=>{try{if(typeof g.result=="string"&&/^ak_[0-9a-f]{64}$/.test(g.result))f=g.result;else{const I=o.getRandomValues(new Uint8Array(32));f=`ak_${Array.from(I,y=>y.toString(16).padStart(2,"0")).join("")}`,u.put(f,l)}}catch{d.abort()}}})}finally{s.close()}}}const LI=/^(?: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,CI=new Set(["origin","referer","user-agent"]);function RI(e,t){return ch({mode:"request-only",request:(r,n={signal:t.signal})=>t.run(n.signal,async i=>{const o={...n,signal:i},s=PI(r),a=await e.authenticatedRequest(s,o);return UI(a)})}).network}function PI(e){const t=kI(e.headers);return{...e,target:{...e.target},...e.params===void 0?{}:{params:{...e.params}},...t===void 0?{headers:void 0}:{headers:t}}}function kI(e){if(e!==void 0)return Object.fromEntries(Object.entries(e).filter(([t])=>!xI(t)))}function xI(e){const t=e.trim().toLowerCase();return CI.has(t)}function UI(e){return{status:e.status,...e.statusText===void 0?{}:{statusText:e.statusText},data:e.data,headers:jI(e.headers)??{}}}function jI(e){if(e!==void 0)return Object.fromEntries(Object.entries(e).filter(([t])=>!zI(t)))}function zI(e){const t=e.trim().toLowerCase();return LI.test(t)||t.startsWith("x-heybox-")||t.startsWith("x-xhh-")}function HI(e,t,r){const n=qI(e.presentation,t);return{account:VI(e,t,r),network:RI(e,t),...e.storage===void 0?{}:{storage:GI(e,t)},...e.storage===void 0?{}:FI(e,t),...n===void 0?{}:{presentation:n},...e.protocol===void 0?{}:{protocol:e.protocol}}}function FI(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 o=0;o<r.storage.length;o+=1){const s=r.storage.key(o);if(s===null)continue;const a=r.storage.getItem(s);a!==null&&i.push({area:r.area,key:s,value:a})}return i})}}}function BI(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 VI(e,t,r){const n=e.account.getAccountKey?.bind(e.account)??vI();return{getAccountKey:(i,o,s)=>t.run(s.signal,a=>n(i,o,{...s,signal:a})),getCurrentUserId:i=>t.run(i.signal,o=>e.account.getCurrentUserId({signal:o})),ensureAuthenticated:i=>t.run(i.signal,o=>e.account.ensureAuthenticated({trustedUserGesture:i.trustedUserGesture,reason:i.reason,signal:o})),onChange:i=>{t.assertActive();const o=e.account.onChange(s=>{t.signal.aborted||i(s)});return r(o)}}}function GI(e,t){const r=e.storage.storage;return{getRaw:(n,i)=>t.run(i.signal,()=>{const o=r.getItem(n);return o===null?void 0:o}),setRaw:(n,i,o)=>t.run(o.signal,()=>{r.setItem(n,i)})}}function qI(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,o=>e.openAppPage(n,{...i,signal:o}))),e.openWindow&&(r.openWindow=(n,i)=>t.run(i.signal,o=>e.openWindow(n,{...i,signal:o}))),e.applyOrientation&&(r.applyOrientation=(n,i)=>t.run(i.signal,o=>e.applyOrientation(n,{...i,signal:o}))),e.onViewportChange&&(r.onViewportChange=n=>{t.assertActive();const i=e.onViewportChange(()=>{t.signal.aborted||n()});let o=!1;const s=()=>{o||(o=!0,t.signal.removeEventListener("abort",s),i())};return t.signal.addEventListener("abort",s,{once:!0}),s}),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,o=>e.setNavigationBarStyle(n,{...i,signal:o}))),e.showShareMenu&&(r.showShareMenu=(n,i)=>t.run(i.signal,o=>e.showShareMenu(n,{...i,signal:o}))),e.setScreenshotChromeHidden&&(r.setScreenshotChromeHidden=(n,i)=>Ih(i)?e.setScreenshotChromeHidden(n,i):t.run(i.signal,o=>e.setScreenshotChromeHidden(n,{...i,signal:o}))),e.captureAndShare&&(r.captureAndShare=(n,i)=>t.run(i.signal,o=>e.captureAndShare(n,{...i,signal:o}))),e.showToast&&(r.showToast=(n,i)=>t.run(i.signal,o=>e.showToast(n,{...i,signal:o}))),e.showLoading&&(r.showLoading=(n,i)=>t.run(i.signal,o=>e.showLoading(n,{...i,signal:o}))),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,o=>e.vibrate(n,{...i,signal:o}))),e.setClipboard&&(r.setClipboard=(n,i)=>t.run(i.signal,o=>e.setClipboard(n,{...i,signal:o}))),Object.keys(r).length===0?void 0:r}function QI(){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 mn(r.reason)},run:async(t,r)=>{const n=t===e.signal||t===void 0?[e.signal]:[e.signal,t],i=n.find(u=>u.aborted);if(i)throw mn(i.reason);const o=new AbortController;let s;const a=new Promise((u,l)=>{s=l}),c=n.map(u=>{const l=()=>{o.signal.aborted||o.abort(u.reason),s(mn(u.reason))};return u.addEventListener("abort",l,{once:!0}),{listener:l,source:u}});let d;try{d=Promise.resolve(r(o.signal))}catch(u){d=Promise.reject(u)}try{const u=await Promise.race([d,a]),l=n.find(f=>f.aborted);if(l)throw mn(l.reason);return u}finally{for(const{listener:u,source:l}of c)l.removeEventListener("abort",u)}}}}function mn(e){return new DOMException("Web Host operation aborted","AbortError")}async function YI(e){const t=QI(),r=new Set;let n=!1;const i=f=>{if(n||t.signal.aborted)return wo(f),()=>{};let m=!0;const h=()=>{m&&(m=!1,r.delete(h),wo(f))};return r.add(h),h},o=()=>s(e.signal.reason),s=f=>{if(!n){n=!0,e.signal.removeEventListener("abort",o),t.abort(f);for(const m of[...r])m();e.onDispose&&wo(e.onDispose)}};e.signal.addEventListener("abort",o,{once:!0}),e.signal.aborted&&s(e.signal.reason);const a=HI(e,t,i);a.storage?.getRaw&&a.storage.setRaw&&(a.scopedStorage=rl({storage:a.storage,diagnostics:a.storageDiagnostics,coordinationKey:e.storage.storage,lock:NE,resolveScope:async()=>tl((await l()).configuration)}));const c=ru(a,{hostCapabilities:e.hostCapabilities}),d=BI(e,t);let u;const l=()=>u??=t.run(void 0,f=>e.resolveLaunch(f));return{platform:"web",ports:a,environment:d,resolveLaunch:l,...e.authPresentation===void 0?{}:{authPresentation:WI(e.authPresentation,t)},hostCapabilities:c.effectiveCapabilities,dispose:s}}function wo(e){try{e()}catch{}}function WI(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}))}}var Vt={},Io,Fc;function $I(){return Fc||(Fc=1,Io=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then}),Io}var Ao={},tt={},Bc;function vt(){if(Bc)return tt;Bc=1;let e;const t=[0,26,44,70,100,134,172,196,242,292,346,404,466,532,581,655,733,815,901,991,1085,1156,1258,1364,1474,1588,1706,1828,1921,2051,2185,2323,2465,2611,2761,2876,3034,3196,3362,3532,3706];return tt.getSymbolSize=function(n){if(!n)throw new Error('"version" cannot be null or undefined');if(n<1||n>40)throw new Error('"version" should be in range from 1 to 40');return n*4+17},tt.getSymbolTotalCodewords=function(n){return t[n]},tt.getBCHDigit=function(r){let n=0;for(;r!==0;)n++,r>>>=1;return n},tt.setToSJISFunction=function(n){if(typeof n!="function")throw new Error('"toSJISFunc" is not a valid function.');e=n},tt.isKanjiModeEnabled=function(){return typeof e<"u"},tt.toSJIS=function(n){return e(n)},tt}var No={},Vc;function Zs(){return Vc||(Vc=1,(function(e){e.L={bit:1},e.M={bit:0},e.Q={bit:3},e.H={bit:2};function t(r){if(typeof r!="string")throw new Error("Param is not a string");switch(r.toLowerCase()){case"l":case"low":return e.L;case"m":case"medium":return e.M;case"q":case"quartile":return e.Q;case"h":case"high":return e.H;default:throw new Error("Unknown EC Level: "+r)}}e.isValid=function(n){return n&&typeof n.bit<"u"&&n.bit>=0&&n.bit<4},e.from=function(n,i){if(e.isValid(n))return n;try{return t(n)}catch{return i}}})(No)),No}var Do,Gc;function KI(){if(Gc)return Do;Gc=1;function e(){this.buffer=[],this.length=0}return e.prototype={get:function(t){const r=Math.floor(t/8);return(this.buffer[r]>>>7-t%8&1)===1},put:function(t,r){for(let n=0;n<r;n++)this.putBit((t>>>r-n-1&1)===1)},getLengthInBits:function(){return this.length},putBit:function(t){const r=Math.floor(this.length/8);this.buffer.length<=r&&this.buffer.push(0),t&&(this.buffer[r]|=128>>>this.length%8),this.length++}},Do=e,Do}var Mo,qc;function ZI(){if(qc)return Mo;qc=1;function e(t){if(!t||t<1)throw new Error("BitMatrix size must be defined and greater than 0");this.size=t,this.data=new Uint8Array(t*t),this.reservedBit=new Uint8Array(t*t)}return e.prototype.set=function(t,r,n,i){const o=t*this.size+r;this.data[o]=n,i&&(this.reservedBit[o]=!0)},e.prototype.get=function(t,r){return this.data[t*this.size+r]},e.prototype.xor=function(t,r,n){this.data[t*this.size+r]^=n},e.prototype.isReserved=function(t,r){return this.reservedBit[t*this.size+r]},Mo=e,Mo}var So={},Qc;function JI(){return Qc||(Qc=1,(function(e){const t=vt().getSymbolSize;e.getRowColCoords=function(n){if(n===1)return[];const i=Math.floor(n/7)+2,o=t(n),s=o===145?26:Math.ceil((o-13)/(2*i-2))*2,a=[o-7];for(let c=1;c<i-1;c++)a[c]=a[c-1]-s;return a.push(6),a.reverse()},e.getPositions=function(n){const i=[],o=e.getRowColCoords(n),s=o.length;for(let a=0;a<s;a++)for(let c=0;c<s;c++)a===0&&c===0||a===0&&c===s-1||a===s-1&&c===0||i.push([o[a],o[c]]);return i}})(So)),So}var _o={},Yc;function XI(){if(Yc)return _o;Yc=1;const e=vt().getSymbolSize,t=7;return _o.getPositions=function(n){const i=e(n);return[[0,0],[i-t,0],[0,i-t]]},_o}var bo={},Wc;function eA(){return Wc||(Wc=1,(function(e){e.Patterns={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7};const t={N1:3,N2:3,N3:40,N4:10};e.isValid=function(i){return i!=null&&i!==""&&!isNaN(i)&&i>=0&&i<=7},e.from=function(i){return e.isValid(i)?parseInt(i,10):void 0},e.getPenaltyN1=function(i){const o=i.size;let s=0,a=0,c=0,d=null,u=null;for(let l=0;l<o;l++){a=c=0,d=u=null;for(let f=0;f<o;f++){let m=i.get(l,f);m===d?a++:(a>=5&&(s+=t.N1+(a-5)),d=m,a=1),m=i.get(f,l),m===u?c++:(c>=5&&(s+=t.N1+(c-5)),u=m,c=1)}a>=5&&(s+=t.N1+(a-5)),c>=5&&(s+=t.N1+(c-5))}return s},e.getPenaltyN2=function(i){const o=i.size;let s=0;for(let a=0;a<o-1;a++)for(let c=0;c<o-1;c++){const d=i.get(a,c)+i.get(a,c+1)+i.get(a+1,c)+i.get(a+1,c+1);(d===4||d===0)&&s++}return s*t.N2},e.getPenaltyN3=function(i){const o=i.size;let s=0,a=0,c=0;for(let d=0;d<o;d++){a=c=0;for(let u=0;u<o;u++)a=a<<1&2047|i.get(d,u),u>=10&&(a===1488||a===93)&&s++,c=c<<1&2047|i.get(u,d),u>=10&&(c===1488||c===93)&&s++}return s*t.N3},e.getPenaltyN4=function(i){let o=0;const s=i.data.length;for(let c=0;c<s;c++)o+=i.data[c];return Math.abs(Math.ceil(o*100/s/5)-10)*t.N4};function r(n,i,o){switch(n){case e.Patterns.PATTERN000:return(i+o)%2===0;case e.Patterns.PATTERN001:return i%2===0;case e.Patterns.PATTERN010:return o%3===0;case e.Patterns.PATTERN011:return(i+o)%3===0;case e.Patterns.PATTERN100:return(Math.floor(i/2)+Math.floor(o/3))%2===0;case e.Patterns.PATTERN101:return i*o%2+i*o%3===0;case e.Patterns.PATTERN110:return(i*o%2+i*o%3)%2===0;case e.Patterns.PATTERN111:return(i*o%3+(i+o)%2)%2===0;default:throw new Error("bad maskPattern:"+n)}}e.applyMask=function(i,o){const s=o.size;for(let a=0;a<s;a++)for(let c=0;c<s;c++)o.isReserved(c,a)||o.xor(c,a,r(i,c,a))},e.getBestMask=function(i,o){const s=Object.keys(e.Patterns).length;let a=0,c=1/0;for(let d=0;d<s;d++){o(d),e.applyMask(d,i);const u=e.getPenaltyN1(i)+e.getPenaltyN2(i)+e.getPenaltyN3(i)+e.getPenaltyN4(i);e.applyMask(d,i),u<c&&(c=u,a=d)}return a}})(bo)),bo}var gn={},$c;function Il(){if($c)return gn;$c=1;const e=Zs(),t=[1,1,1,1,1,1,1,1,1,1,2,2,1,2,2,4,1,2,4,4,2,4,4,4,2,4,6,5,2,4,6,6,2,5,8,8,4,5,8,8,4,5,8,11,4,8,10,11,4,9,12,16,4,9,16,16,6,10,12,18,6,10,17,16,6,11,16,19,6,13,18,21,7,14,21,25,8,16,20,25,8,17,23,25,9,17,23,34,9,18,25,30,10,20,27,32,12,21,29,35,12,23,34,37,12,25,34,40,13,26,35,42,14,28,38,45,15,29,40,48,16,31,43,51,17,33,45,54,18,35,48,57,19,37,51,60,19,38,53,63,20,40,56,66,21,43,59,70,22,45,62,74,24,47,65,77,25,49,68,81],r=[7,10,13,17,10,16,22,28,15,26,36,44,20,36,52,64,26,48,72,88,36,64,96,112,40,72,108,130,48,88,132,156,60,110,160,192,72,130,192,224,80,150,224,264,96,176,260,308,104,198,288,352,120,216,320,384,132,240,360,432,144,280,408,480,168,308,448,532,180,338,504,588,196,364,546,650,224,416,600,700,224,442,644,750,252,476,690,816,270,504,750,900,300,560,810,960,312,588,870,1050,336,644,952,1110,360,700,1020,1200,390,728,1050,1260,420,784,1140,1350,450,812,1200,1440,480,868,1290,1530,510,924,1350,1620,540,980,1440,1710,570,1036,1530,1800,570,1064,1590,1890,600,1120,1680,1980,630,1204,1770,2100,660,1260,1860,2220,720,1316,1950,2310,750,1372,2040,2430];return gn.getBlocksCount=function(i,o){switch(o){case e.L:return t[(i-1)*4+0];case e.M:return t[(i-1)*4+1];case e.Q:return t[(i-1)*4+2];case e.H:return t[(i-1)*4+3];default:return}},gn.getTotalCodewordsCount=function(i,o){switch(o){case e.L:return r[(i-1)*4+0];case e.M:return r[(i-1)*4+1];case e.Q:return r[(i-1)*4+2];case e.H:return r[(i-1)*4+3];default:return}},gn}var To={},Nr={},Kc;function tA(){if(Kc)return Nr;Kc=1;const e=new Uint8Array(512),t=new Uint8Array(256);return(function(){let n=1;for(let i=0;i<255;i++)e[i]=n,t[n]=i,n<<=1,n&256&&(n^=285);for(let i=255;i<512;i++)e[i]=e[i-255]})(),Nr.log=function(n){if(n<1)throw new Error("log("+n+")");return t[n]},Nr.exp=function(n){return e[n]},Nr.mul=function(n,i){return n===0||i===0?0:e[t[n]+t[i]]},Nr}var Zc;function rA(){return Zc||(Zc=1,(function(e){const t=tA();e.mul=function(n,i){const o=new Uint8Array(n.length+i.length-1);for(let s=0;s<n.length;s++)for(let a=0;a<i.length;a++)o[s+a]^=t.mul(n[s],i[a]);return o},e.mod=function(n,i){let o=new Uint8Array(n);for(;o.length-i.length>=0;){const s=o[0];for(let c=0;c<i.length;c++)o[c]^=t.mul(i[c],s);let a=0;for(;a<o.length&&o[a]===0;)a++;o=o.slice(a)}return o},e.generateECPolynomial=function(n){let i=new Uint8Array([1]);for(let o=0;o<n;o++)i=e.mul(i,new Uint8Array([1,t.exp(o)]));return i}})(To)),To}var Oo,Jc;function nA(){if(Jc)return Oo;Jc=1;const e=rA();function t(r){this.genPoly=void 0,this.degree=r,this.degree&&this.initialize(this.degree)}return t.prototype.initialize=function(n){this.degree=n,this.genPoly=e.generateECPolynomial(this.degree)},t.prototype.encode=function(n){if(!this.genPoly)throw new Error("Encoder not initialized");const i=new Uint8Array(n.length+this.degree);i.set(n);const o=e.mod(i,this.genPoly),s=this.degree-o.length;if(s>0){const a=new Uint8Array(this.degree);return a.set(o,s),a}return o},Oo=t,Oo}var vo={},Lo={},Co={},Xc;function Al(){return Xc||(Xc=1,Co.isValid=function(t){return!isNaN(t)&&t>=1&&t<=40}),Co}var Ge={},ed;function Nl(){if(ed)return Ge;ed=1;const e="[0-9]+",t="[A-Z $%*+\\-./:]+";let r="(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+";r=r.replace(/u/g,"\\u");const n="(?:(?![A-Z0-9 $%*+\\-./:]|"+r+`)(?:.|[\r
10
- ]))+`;Ge.KANJI=new RegExp(r,"g"),Ge.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g"),Ge.BYTE=new RegExp(n,"g"),Ge.NUMERIC=new RegExp(e,"g"),Ge.ALPHANUMERIC=new RegExp(t,"g");const i=new RegExp("^"+r+"$"),o=new RegExp("^"+e+"$"),s=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");return Ge.testKanji=function(c){return i.test(c)},Ge.testNumeric=function(c){return o.test(c)},Ge.testAlphanumeric=function(c){return s.test(c)},Ge}var td;function Lt(){return td||(td=1,(function(e){const t=Al(),r=Nl();e.NUMERIC={id:"Numeric",bit:1,ccBits:[10,12,14]},e.ALPHANUMERIC={id:"Alphanumeric",bit:2,ccBits:[9,11,13]},e.BYTE={id:"Byte",bit:4,ccBits:[8,16,16]},e.KANJI={id:"Kanji",bit:8,ccBits:[8,10,12]},e.MIXED={bit:-1},e.getCharCountIndicator=function(o,s){if(!o.ccBits)throw new Error("Invalid mode: "+o);if(!t.isValid(s))throw new Error("Invalid version: "+s);return s>=1&&s<10?o.ccBits[0]:s<27?o.ccBits[1]:o.ccBits[2]},e.getBestModeForData=function(o){return r.testNumeric(o)?e.NUMERIC:r.testAlphanumeric(o)?e.ALPHANUMERIC:r.testKanji(o)?e.KANJI:e.BYTE},e.toString=function(o){if(o&&o.id)return o.id;throw new Error("Invalid mode")},e.isValid=function(o){return o&&o.bit&&o.ccBits};function n(i){if(typeof i!="string")throw new Error("Param is not a string");switch(i.toLowerCase()){case"numeric":return e.NUMERIC;case"alphanumeric":return e.ALPHANUMERIC;case"kanji":return e.KANJI;case"byte":return e.BYTE;default:throw new Error("Unknown mode: "+i)}}e.from=function(o,s){if(e.isValid(o))return o;try{return n(o)}catch{return s}}})(Lo)),Lo}var rd;function iA(){return rd||(rd=1,(function(e){const t=vt(),r=Il(),n=Zs(),i=Lt(),o=Al(),s=7973,a=t.getBCHDigit(s);function c(f,m,h){for(let g=1;g<=40;g++)if(m<=e.getCapacity(g,h,f))return g}function d(f,m){return i.getCharCountIndicator(f,m)+4}function u(f,m){let h=0;return f.forEach(function(g){const I=d(g.mode,m);h+=I+g.getBitsLength()}),h}function l(f,m){for(let h=1;h<=40;h++)if(u(f,h)<=e.getCapacity(h,m,i.MIXED))return h}e.from=function(m,h){return o.isValid(m)?parseInt(m,10):h},e.getCapacity=function(m,h,g){if(!o.isValid(m))throw new Error("Invalid QR Code version");typeof g>"u"&&(g=i.BYTE);const I=t.getSymbolTotalCodewords(m),y=r.getTotalCodewordsCount(m,h),b=(I-y)*8;if(g===i.MIXED)return b;const _=b-d(g,m);switch(g){case i.NUMERIC:return Math.floor(_/10*3);case i.ALPHANUMERIC:return Math.floor(_/11*2);case i.KANJI:return Math.floor(_/13);case i.BYTE:default:return Math.floor(_/8)}},e.getBestVersionForData=function(m,h){let g;const I=n.from(h,n.M);if(Array.isArray(m)){if(m.length>1)return l(m,I);if(m.length===0)return 1;g=m[0]}else g=m;return c(g.mode,g.getLength(),I)},e.getEncodedBits=function(m){if(!o.isValid(m)||m<7)throw new Error("Invalid QR Code version");let h=m<<12;for(;t.getBCHDigit(h)-a>=0;)h^=s<<t.getBCHDigit(h)-a;return m<<12|h}})(vo)),vo}var Ro={},nd;function oA(){if(nd)return Ro;nd=1;const e=vt(),t=1335,r=21522,n=e.getBCHDigit(t);return Ro.getEncodedBits=function(o,s){const a=o.bit<<3|s;let c=a<<10;for(;e.getBCHDigit(c)-n>=0;)c^=t<<e.getBCHDigit(c)-n;return(a<<10|c)^r},Ro}var Po={},ko,id;function sA(){if(id)return ko;id=1;const e=Lt();function t(r){this.mode=e.NUMERIC,this.data=r.toString()}return t.getBitsLength=function(n){return 10*Math.floor(n/3)+(n%3?n%3*3+1:0)},t.prototype.getLength=function(){return this.data.length},t.prototype.getBitsLength=function(){return t.getBitsLength(this.data.length)},t.prototype.write=function(n){let i,o,s;for(i=0;i+3<=this.data.length;i+=3)o=this.data.substr(i,3),s=parseInt(o,10),n.put(s,10);const a=this.data.length-i;a>0&&(o=this.data.substr(i),s=parseInt(o,10),n.put(s,a*3+1))},ko=t,ko}var xo,od;function aA(){if(od)return xo;od=1;const e=Lt(),t=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"," ","$","%","*","+","-",".","/",":"];function r(n){this.mode=e.ALPHANUMERIC,this.data=n}return r.getBitsLength=function(i){return 11*Math.floor(i/2)+6*(i%2)},r.prototype.getLength=function(){return this.data.length},r.prototype.getBitsLength=function(){return r.getBitsLength(this.data.length)},r.prototype.write=function(i){let o;for(o=0;o+2<=this.data.length;o+=2){let s=t.indexOf(this.data[o])*45;s+=t.indexOf(this.data[o+1]),i.put(s,11)}this.data.length%2&&i.put(t.indexOf(this.data[o]),6)},xo=r,xo}var Uo,sd;function cA(){if(sd)return Uo;sd=1;const e=Lt();function t(r){this.mode=e.BYTE,typeof r=="string"?this.data=new TextEncoder().encode(r):this.data=new Uint8Array(r)}return t.getBitsLength=function(n){return n*8},t.prototype.getLength=function(){return this.data.length},t.prototype.getBitsLength=function(){return t.getBitsLength(this.data.length)},t.prototype.write=function(r){for(let n=0,i=this.data.length;n<i;n++)r.put(this.data[n],8)},Uo=t,Uo}var jo,ad;function dA(){if(ad)return jo;ad=1;const e=Lt(),t=vt();function r(n){this.mode=e.KANJI,this.data=n}return r.getBitsLength=function(i){return i*13},r.prototype.getLength=function(){return this.data.length},r.prototype.getBitsLength=function(){return r.getBitsLength(this.data.length)},r.prototype.write=function(n){let i;for(i=0;i<this.data.length;i++){let o=t.toSJIS(this.data[i]);if(o>=33088&&o<=40956)o-=33088;else if(o>=57408&&o<=60351)o-=49472;else throw new Error("Invalid SJIS character: "+this.data[i]+`
11
- Make sure your charset is UTF-8`);o=(o>>>8&255)*192+(o&255),n.put(o,13)}},jo=r,jo}var zo={exports:{}},cd;function uA(){return cd||(cd=1,(function(e){var t={single_source_shortest_paths:function(r,n,i){var o={},s={};s[n]=0;var a=t.PriorityQueue.make();a.push(n,0);for(var c,d,u,l,f,m,h,g,I;!a.empty();){c=a.pop(),d=c.value,l=c.cost,f=r[d]||{};for(u in f)f.hasOwnProperty(u)&&(m=f[u],h=l+m,g=s[u],I=typeof s[u]>"u",(I||g>h)&&(s[u]=h,a.push(u,h),o[u]=d))}if(typeof i<"u"&&typeof s[i]>"u"){var y=["Could not find a path from ",n," to ",i,"."].join("");throw new Error(y)}return o},extract_shortest_path_from_predecessor_list:function(r,n){for(var i=[],o=n;o;)i.push(o),r[o],o=r[o];return i.reverse(),i},find_path:function(r,n,i){var o=t.single_source_shortest_paths(r,n,i);return t.extract_shortest_path_from_predecessor_list(o,i)},PriorityQueue:{make:function(r){var n=t.PriorityQueue,i={},o;r=r||{};for(o in n)n.hasOwnProperty(o)&&(i[o]=n[o]);return i.queue=[],i.sorter=r.sorter||n.default_sorter,i},default_sorter:function(r,n){return r.cost-n.cost},push:function(r,n){var i={value:r,cost:n};this.queue.push(i),this.queue.sort(this.sorter)},pop:function(){return this.queue.shift()},empty:function(){return this.queue.length===0}}};e.exports=t})(zo)),zo.exports}var dd;function lA(){return dd||(dd=1,(function(e){const t=Lt(),r=sA(),n=aA(),i=cA(),o=dA(),s=Nl(),a=vt(),c=uA();function d(y){return unescape(encodeURIComponent(y)).length}function u(y,b,_){const P=[];let j;for(;(j=y.exec(_))!==null;)P.push({data:j[0],index:j.index,mode:b,length:j[0].length});return P}function l(y){const b=u(s.NUMERIC,t.NUMERIC,y),_=u(s.ALPHANUMERIC,t.ALPHANUMERIC,y);let P,j;return a.isKanjiModeEnabled()?(P=u(s.BYTE,t.BYTE,y),j=u(s.KANJI,t.KANJI,y)):(P=u(s.BYTE_KANJI,t.BYTE,y),j=[]),b.concat(_,P,j).sort(function(O,w){return O.index-w.index}).map(function(O){return{data:O.data,mode:O.mode,length:O.length}})}function f(y,b){switch(b){case t.NUMERIC:return r.getBitsLength(y);case t.ALPHANUMERIC:return n.getBitsLength(y);case t.KANJI:return o.getBitsLength(y);case t.BYTE:return i.getBitsLength(y)}}function m(y){return y.reduce(function(b,_){const P=b.length-1>=0?b[b.length-1]:null;return P&&P.mode===_.mode?(b[b.length-1].data+=_.data,b):(b.push(_),b)},[])}function h(y){const b=[];for(let _=0;_<y.length;_++){const P=y[_];switch(P.mode){case t.NUMERIC:b.push([P,{data:P.data,mode:t.ALPHANUMERIC,length:P.length},{data:P.data,mode:t.BYTE,length:P.length}]);break;case t.ALPHANUMERIC:b.push([P,{data:P.data,mode:t.BYTE,length:P.length}]);break;case t.KANJI:b.push([P,{data:P.data,mode:t.BYTE,length:d(P.data)}]);break;case t.BYTE:b.push([{data:P.data,mode:t.BYTE,length:d(P.data)}])}}return b}function g(y,b){const _={},P={start:{}};let j=["start"];for(let U=0;U<y.length;U++){const O=y[U],w=[];for(let S=0;S<O.length;S++){const v=O[S],C=""+U+S;w.push(C),_[C]={node:v,lastCount:0},P[C]={};for(let E=0;E<j.length;E++){const D=j[E];_[D]&&_[D].node.mode===v.mode?(P[D][C]=f(_[D].lastCount+v.length,v.mode)-f(_[D].lastCount,v.mode),_[D].lastCount+=v.length):(_[D]&&(_[D].lastCount=v.length),P[D][C]=f(v.length,v.mode)+4+t.getCharCountIndicator(v.mode,b))}}j=w}for(let U=0;U<j.length;U++)P[j[U]].end=0;return{map:P,table:_}}function I(y,b){let _;const P=t.getBestModeForData(y);if(_=t.from(b,P),_!==t.BYTE&&_.bit<P.bit)throw new Error('"'+y+'" cannot be encoded with mode '+t.toString(_)+`.
12
- Suggested mode is: `+t.toString(P));switch(_===t.KANJI&&!a.isKanjiModeEnabled()&&(_=t.BYTE),_){case t.NUMERIC:return new r(y);case t.ALPHANUMERIC:return new n(y);case t.KANJI:return new o(y);case t.BYTE:return new i(y)}}e.fromArray=function(b){return b.reduce(function(_,P){return typeof P=="string"?_.push(I(P,null)):P.data&&_.push(I(P.data,P.mode)),_},[])},e.fromString=function(b,_){const P=l(b,a.isKanjiModeEnabled()),j=h(P),U=g(j,_),O=c.find_path(U.map,"start","end"),w=[];for(let S=1;S<O.length-1;S++)w.push(U.table[O[S]].node);return e.fromArray(m(w))},e.rawSplit=function(b){return e.fromArray(l(b,a.isKanjiModeEnabled()))}})(Po)),Po}var ud;function fA(){if(ud)return Ao;ud=1;const e=vt(),t=Zs(),r=KI(),n=ZI(),i=JI(),o=XI(),s=eA(),a=Il(),c=nA(),d=iA(),u=oA(),l=Lt(),f=lA();function m(U,O){const w=U.size,S=o.getPositions(O);for(let v=0;v<S.length;v++){const C=S[v][0],E=S[v][1];for(let D=-1;D<=7;D++)if(!(C+D<=-1||w<=C+D))for(let M=-1;M<=7;M++)E+M<=-1||w<=E+M||(D>=0&&D<=6&&(M===0||M===6)||M>=0&&M<=6&&(D===0||D===6)||D>=2&&D<=4&&M>=2&&M<=4?U.set(C+D,E+M,!0,!0):U.set(C+D,E+M,!1,!0))}}function h(U){const O=U.size;for(let w=8;w<O-8;w++){const S=w%2===0;U.set(w,6,S,!0),U.set(6,w,S,!0)}}function g(U,O){const w=i.getPositions(O);for(let S=0;S<w.length;S++){const v=w[S][0],C=w[S][1];for(let E=-2;E<=2;E++)for(let D=-2;D<=2;D++)E===-2||E===2||D===-2||D===2||E===0&&D===0?U.set(v+E,C+D,!0,!0):U.set(v+E,C+D,!1,!0)}}function I(U,O){const w=U.size,S=d.getEncodedBits(O);let v,C,E;for(let D=0;D<18;D++)v=Math.floor(D/3),C=D%3+w-8-3,E=(S>>D&1)===1,U.set(v,C,E,!0),U.set(C,v,E,!0)}function y(U,O,w){const S=U.size,v=u.getEncodedBits(O,w);let C,E;for(C=0;C<15;C++)E=(v>>C&1)===1,C<6?U.set(C,8,E,!0):C<8?U.set(C+1,8,E,!0):U.set(S-15+C,8,E,!0),C<8?U.set(8,S-C-1,E,!0):C<9?U.set(8,15-C-1+1,E,!0):U.set(8,15-C-1,E,!0);U.set(S-8,8,1,!0)}function b(U,O){const w=U.size;let S=-1,v=w-1,C=7,E=0;for(let D=w-1;D>0;D-=2)for(D===6&&D--;;){for(let M=0;M<2;M++)if(!U.isReserved(v,D-M)){let R=!1;E<O.length&&(R=(O[E]>>>C&1)===1),U.set(v,D-M,R),C--,C===-1&&(E++,C=7)}if(v+=S,v<0||w<=v){v-=S,S=-S;break}}}function _(U,O,w){const S=new r;w.forEach(function(M){S.put(M.mode.bit,4),S.put(M.getLength(),l.getCharCountIndicator(M.mode,U)),M.write(S)});const v=e.getSymbolTotalCodewords(U),C=a.getTotalCodewordsCount(U,O),E=(v-C)*8;for(S.getLengthInBits()+4<=E&&S.put(0,4);S.getLengthInBits()%8!==0;)S.putBit(0);const D=(E-S.getLengthInBits())/8;for(let M=0;M<D;M++)S.put(M%2?17:236,8);return P(S,U,O)}function P(U,O,w){const S=e.getSymbolTotalCodewords(O),v=a.getTotalCodewordsCount(O,w),C=S-v,E=a.getBlocksCount(O,w),D=S%E,M=E-D,R=Math.floor(S/E),T=Math.floor(C/E),N=T+1,A=R-T,L=new c(A);let k=0;const x=new Array(E),H=new Array(E);let F=0;const V=new Uint8Array(U.buffer);for(let Y=0;Y<E;Y++){const re=Y<M?T:N;x[Y]=V.slice(k,k+re),H[Y]=L.encode(x[Y]),k+=re,F=Math.max(F,re)}const q=new Uint8Array(S);let J=0,K,Z;for(K=0;K<F;K++)for(Z=0;Z<E;Z++)K<x[Z].length&&(q[J++]=x[Z][K]);for(K=0;K<A;K++)for(Z=0;Z<E;Z++)q[J++]=H[Z][K];return q}function j(U,O,w,S){let v;if(Array.isArray(U))v=f.fromArray(U);else if(typeof U=="string"){let R=O;if(!R){const T=f.rawSplit(U);R=d.getBestVersionForData(T,w)}v=f.fromString(U,R||40)}else throw new Error("Invalid data");const C=d.getBestVersionForData(v,w);if(!C)throw new Error("The amount of data is too big to be stored in a QR Code");if(!O)O=C;else if(O<C)throw new Error(`
13
- The chosen QR Code version cannot contain this amount of data.
14
- Minimum version required to store current data is: `+C+`.
15
- `);const E=_(O,w,v),D=e.getSymbolSize(O),M=new n(D);return m(M,O),h(M),g(M,O),y(M,w,0),O>=7&&I(M,O),b(M,E),isNaN(S)&&(S=s.getBestMask(M,y.bind(null,M,w))),s.applyMask(S,M),y(M,w,S),{modules:M,version:O,errorCorrectionLevel:w,maskPattern:S,segments:v}}return Ao.create=function(O,w){if(typeof O>"u"||O==="")throw new Error("No input text");let S=t.M,v,C;return typeof w<"u"&&(S=t.from(w.errorCorrectionLevel,t.M),v=d.from(w.version),C=s.from(w.maskPattern),w.toSJISFunc&&e.setToSJISFunction(w.toSJISFunc)),j(O,v,S,C)},Ao}var Ho={},Fo={},ld;function Dl(){return ld||(ld=1,(function(e){function t(r){if(typeof r=="number"&&(r=r.toString()),typeof r!="string")throw new Error("Color should be defined as hex string");let n=r.slice().replace("#","").split("");if(n.length<3||n.length===5||n.length>8)throw new Error("Invalid hex color: "+r);(n.length===3||n.length===4)&&(n=Array.prototype.concat.apply([],n.map(function(o){return[o,o]}))),n.length===6&&n.push("F","F");const i=parseInt(n.join(""),16);return{r:i>>24&255,g:i>>16&255,b:i>>8&255,a:i&255,hex:"#"+n.slice(0,6).join("")}}e.getOptions=function(n){n||(n={}),n.color||(n.color={});const i=typeof n.margin>"u"||n.margin===null||n.margin<0?4:n.margin,o=n.width&&n.width>=21?n.width:void 0,s=n.scale||4;return{width:o,scale:o?4:s,margin:i,color:{dark:t(n.color.dark||"#000000ff"),light:t(n.color.light||"#ffffffff")},type:n.type,rendererOpts:n.rendererOpts||{}}},e.getScale=function(n,i){return i.width&&i.width>=n+i.margin*2?i.width/(n+i.margin*2):i.scale},e.getImageWidth=function(n,i){const o=e.getScale(n,i);return Math.floor((n+i.margin*2)*o)},e.qrToImageData=function(n,i,o){const s=i.modules.size,a=i.modules.data,c=e.getScale(s,o),d=Math.floor((s+o.margin*2)*c),u=o.margin*c,l=[o.color.light,o.color.dark];for(let f=0;f<d;f++)for(let m=0;m<d;m++){let h=(f*d+m)*4,g=o.color.light;if(f>=u&&m>=u&&f<d-u&&m<d-u){const I=Math.floor((f-u)/c),y=Math.floor((m-u)/c);g=l[a[I*s+y]?1:0]}n[h++]=g.r,n[h++]=g.g,n[h++]=g.b,n[h]=g.a}}})(Fo)),Fo}var fd;function hA(){return fd||(fd=1,(function(e){const t=Dl();function r(i,o,s){i.clearRect(0,0,o.width,o.height),o.style||(o.style={}),o.height=s,o.width=s,o.style.height=s+"px",o.style.width=s+"px"}function n(){try{return document.createElement("canvas")}catch{throw new Error("You need to specify a canvas element")}}e.render=function(o,s,a){let c=a,d=s;typeof c>"u"&&(!s||!s.getContext)&&(c=s,s=void 0),s||(d=n()),c=t.getOptions(c);const u=t.getImageWidth(o.modules.size,c),l=d.getContext("2d"),f=l.createImageData(u,u);return t.qrToImageData(f.data,o,c),r(l,d,u),l.putImageData(f,0,0),d},e.renderToDataURL=function(o,s,a){let c=a;typeof c>"u"&&(!s||!s.getContext)&&(c=s,s=void 0),c||(c={});const d=e.render(o,s,c),u=c.type||"image/png",l=c.rendererOpts||{};return d.toDataURL(u,l.quality)}})(Ho)),Ho}var Bo={},hd;function mA(){if(hd)return Bo;hd=1;const e=Dl();function t(i,o){const s=i.a/255,a=o+'="'+i.hex+'"';return s<1?a+" "+o+'-opacity="'+s.toFixed(2).slice(1)+'"':a}function r(i,o,s){let a=i+o;return typeof s<"u"&&(a+=" "+s),a}function n(i,o,s){let a="",c=0,d=!1,u=0;for(let l=0;l<i.length;l++){const f=Math.floor(l%o),m=Math.floor(l/o);!f&&!d&&(d=!0),i[l]?(u++,l>0&&f>0&&i[l-1]||(a+=d?r("M",f+s,.5+m+s):r("m",c,0),c=0,d=!1),f+1<o&&i[l+1]||(a+=r("h",u),u=0)):c++}return a}return Bo.render=function(o,s,a){const c=e.getOptions(s),d=o.modules.size,u=o.modules.data,l=d+c.margin*2,f=c.color.light.a?"<path "+t(c.color.light,"fill")+' d="M0 0h'+l+"v"+l+'H0z"/>':"",m="<path "+t(c.color.dark,"stroke")+' d="'+n(u,d,c.margin)+'"/>',h='viewBox="0 0 '+l+" "+l+'"',I='<svg xmlns="http://www.w3.org/2000/svg" '+(c.width?'width="'+c.width+'" height="'+c.width+'" ':"")+h+' shape-rendering="crispEdges">'+f+m+`</svg>
16
- `;return typeof a=="function"&&a(null,I),I},Bo}var md;function gA(){if(md)return Vt;md=1;const e=$I(),t=fA(),r=hA(),n=mA();function i(o,s,a,c,d){const u=[].slice.call(arguments,1),l=u.length,f=typeof u[l-1]=="function";if(!f&&!e())throw new Error("Callback required as last argument");if(f){if(l<2)throw new Error("Too few arguments provided");l===2?(d=a,a=s,s=c=void 0):l===3&&(s.getContext&&typeof d>"u"?(d=c,c=void 0):(d=c,c=a,a=s,s=void 0))}else{if(l<1)throw new Error("Too few arguments provided");return l===1?(a=s,s=c=void 0):l===2&&!s.getContext&&(c=a,a=s,s=void 0),new Promise(function(m,h){try{const g=t.create(a,c);m(o(g,s,c))}catch(g){h(g)}})}try{const m=t.create(a,c);d(null,o(m,s,c))}catch(m){d(m)}}return Vt.create=t.create,Vt.toCanvas=i.bind(null,r.render),Vt.toDataURL=i.bind(null,r.renderToDataURL),Vt.toString=i.bind(null,function(o,s,a){return n.render(o,a)}),Vt}var pA=gA();function yA(e){const t=`hb-game-saves-${crypto.randomUUID()}`,r=c=>`hb-sdk:game-save-cache:${c}`;let n,i;const o=new Promise((c,d)=>{n=c,i=d});let s;const a=new Promise(c=>{s=c});return e.signal.addEventListener("abort",s,{once:!0}),e.signal.aborted&&s(),e.locks.request(r(t),async()=>{let c;try{c=await e.getRoot();const d=await e.locks.request("hb-sdk:game-save-cache:gc",async()=>{e.signal.throwIfAborted();for await(const[u,l]of c)l.kind!=="directory"||!/^hb-game-saves-[a-f0-9-]{36}$/.test(u)||await e.locks.request(r(u),{ifAvailable:!0},async f=>{f&&await gd(c,u)});return e.signal.throwIfAborted(),c.getDirectoryHandle(t,{create:!0})});e.signal.throwIfAborted(),n(d),await a}catch(d){i(d)}finally{e.signal.removeEventListener("abort",s),c&&await gd(c,t).catch(()=>{})}}).catch(i),o.catch(()=>{}),o}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 Vo=8*1024*1024,EA=new Set(["content-length","content-type","content-encoding","transfer-encoding","content-disposition","content-range"]),wA="/__hb_sdk__/game-save-download",Ie=(e,t)=>({code:e,message:t});function IA(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=yA({getRoot:t,locks:r,signal:e.signal}),o=new WeakMap,s=new WeakSet,a=h=>{h.signal.throwIfAborted(),h.lifecycle!=="cleanup"&&e.signal.throwIfAborted()},c=()=>i;function d(h){if(!/^\.hb-game-saves\/[a-zA-Z0-9_-]+\.zip$/.test(h))throw Ie("FILE_ACCESS_DENIED","浏览器仅开放存档私有缓存");return h.slice(15)}async function u(h,g){a(g);const I=d(h);try{return await(await c()).getFileHandle(I)}catch(y){throw y instanceof DOMException&&y.name==="NotFoundError"?Ie("FILE_NOT_FOUND","存档缓存不存在"):y}}function l(h){const g={kind:"file",mode:"readwrite",name:h.split("/").at(-1),async create(I,y){a(y);const b=d(h),_=await c();if(I.exclusive)try{throw await _.getFileHandle(b),Ie("FILE_ALREADY_EXISTS","存档缓存已存在")}catch(P){if(!(P instanceof DOMException&&P.name==="NotFoundError"))throw P}a(y),await _.getFileHandle(b,{create:!0}),a(y)},async remove(I){a(I);const y=d(h);if(i)try{await(await i).removeEntry(y)}catch(b){if(!(b instanceof DOMException&&b.name==="NotFoundError"))throw b}},async read(I){const y=await(await u(h,I)).getFile();if(y.size>Vo)throw Ie("FILE_TOO_LARGE","存档文件超过 8 MiB");const b=new Uint8Array(await y.arrayBuffer());try{return a(I),b}catch(_){throw b.fill(0),_}},async write(){throw Ie("FILE_ACCESS_DENIED","存档缓存仅允许受控下载写入")},async stat(I){const y=await(await u(h,I)).getFile();return a(I),{kind:"file",size:y.size,modifiedAt:y.lastModified}}};return o.set(g,h),g}const f=async()=>{throw Ie("FILE_ACCESS_DENIED","浏览器仅开放存档私有缓存")},m={kind:"directory",mode:"readwrite",name:"",file:l,directory(h){return{...m,name:h,async create(g,I){if(a(I),h!==".hb-game-saves")return f();await c(),a(I)}}},create:f,stat:f,list:f};return{files:{sandbox:m},transfer:{network:{async open(h,g){if(a(g),!Zd(h))throw Ie("METHOD_FORBIDDEN","仅支持受控存档下载");const I=await(e.fetch??fetch)(wA,{method:"POST",credentials:"same-origin",redirect:"error",headers:{"content-type":"application/json","x-hb-sdk-csrf":e.csrfToken()},body:JSON.stringify(h),signal:AbortSignal.any([g.signal,e.signal,AbortSignal.timeout(6e4)])});if(!I.ok){const y=await I.json().catch(()=>({}));throw Ie(y.code==="FILE_TOO_LARGE"?"FILE_TOO_LARGE":"DOWNLOAD_NETWORK_FAILED","存档下载失败")}return s.add(I),{status:I.status,headers:Object.fromEntries(Array.from(I.headers).filter(([y])=>EA.has(y)).map(([y,b])=>[y,[b]])),body:I}},async release(h){s.delete(h),await h.body?.cancel()}},files:{async writeResource(h,g,I,y){let b,_;try{a(y);const P=o.get(h);if(!P||!s.delete(g))throw Ie("FILE_ACCESS_DENIED","下载资源不属于当前存档会话");if(I.mode!=="replace-existing")throw Ie("FILE_ACCESS_DENIED","存档下载目标必须先创建");if(b=await(await u(P,y)).createWritable(),!g.body)throw Ie("DOWNLOAD_NETWORK_FAILED","存档下载没有响应内容");_=g.body.getReader();let U=0;for(;;){a(y);const O=await _.read().catch(w=>{throw a(y),Ie(w instanceof DOMException&&w.name==="TimeoutError"?"DOWNLOAD_TIMEOUT":"DOWNLOAD_NETWORK_FAILED","存档下载流中断")});if(a(y),O.done)break;if(U+=O.value.byteLength,U>Math.min(I.maxBytes??Vo,Vo))throw Ie("FILE_TOO_LARGE","存档文件超过 8 MiB");await b.write(new Uint8Array(O.value)),y.onProgress(U)}if(I.expectedBytes!==void 0&&U!==I.expectedBytes)throw Ie("DOWNLOAD_NETWORK_FAILED","存档下载长度不匹配");return a(y),await b.close(),b=void 0,{committedBytes:U}}catch(P){throw P instanceof DOMException&&P.name==="QuotaExceededError"?Ie("FILE_QUOTA_EXCEEDED","浏览器存储空间不足"):P}finally{await _?.cancel().catch(()=>{}),_||await g.body?.cancel().catch(()=>{}),await b?.abort().catch(()=>{}),s.delete(g)}}}}}}function qe(e,t){throw{code:e,message:t}}function AA(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 o(){if(e.signal.aborted)throw new DOMException("调试会话已结束","AbortError");const a=e.readState();a.userId||(i(),qe("UNAUTHORIZED","请先通过 hb-sdk login 登录小黑盒"));const{signed:c,browser:d}=a,u=eh(c.developmentSnapshot);(c.source!=="remote"||!c.miniProgramId||!c.localDevLaunchToken||!c.expiresAt||c.expiresAt<=t()||!u||!c.developmentSnapshotDigest||!/^[a-f0-9]{64}$/.test(c.developmentSnapshotDigest))&&(i(),qe("INVALID_STATE","开发启动授权尚未就绪,请检查 CLI 登录、项目绑定及开发票据状态")),(d.source!=="remote"||d.miniProgramId!==c.miniProgramId||d.devSessionId!==u.session_id||d.contextRevision!==u.revision||c.devSessionId!==u.session_id||c.contextRevision!==u.revision)&&(i(),qe("AUTHORIZATION_CONTEXT_CHANGED","开发快照正在更新,请稍后重试"));const l={mini_program_id:c.miniProgramId,launch_kind:"remote-dev",version_identity:`dev:${u.session_id}:${u.revision}`,sdk_version:u.sdk_version,local_dev_launch_token:c.localDevLaunchToken,dev_snapshot_digest:c.developmentSnapshotDigest,dev_network_enabled:a.networkEnabled};return{body:l,key:JSON.stringify([a.userId,a.accountRevision,l]),expiresAt:c.expiresAt}}async function s(a,c){const d=c.signal;let u;try{u=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:a.body,timeout:1e4},c)}catch(g){d.throwIfAborted();const I=g&&typeof g=="object"&&"code"in g?String(g.code):"";if(["SESSION_UNAUTHENTICATED","SESSION_INVALIDATED","UNAUTHORIZED"].includes(I)&&qe("UNAUTHORIZED","小黑盒登录已失效,请重新登录"),["REQUEST_CANCELLED","REQUEST_TIMEOUT"].includes(I)||g instanceof DOMException&&["AbortError","TimeoutError"].includes(g.name))throw g;qe("REQUEST_FAILED","获取开发运行授权失败,请稍后重试")}d.throwIfAborted(),await e.refreshAccount(d),d.throwIfAborted(),o().key!==a.key&&qe("AUTHORIZATION_CONTEXT_CHANGED","账号或开发快照已变化,请重试");const l=u.data;(u.status===401||l?.status==="login"||l?.status==="relogin")&&qe("UNAUTHORIZED","小黑盒登录已失效,请重新登录"),(u.status!==200||l?.status!=="ok")&&qe("REQUEST_FAILED","获取开发运行授权失败,请检查开发资格后重试");const f=l.result,m=Number(f?.expires_at)*1e3;(typeof f?.token!="string"||!f.token.trim()||!Number.isSafeInteger(f?.expires_at)||!Number.isSafeInteger(m)||m<=t()||!["legacy","local","server"].includes(String(f.user_data_mode)))&&qe("INVALID_RESPONSE","开发运行授权响应无效");const h={token:f.token,expiresAt:Math.min(m,a.expiresAt),steamAccount:f.steam_account===!0,userDataMode:f.user_data_mode};return r={key:a.key,value:h},h}return{async get(a){const c=AbortSignal.any([a.signal,e.signal]);c.throwIfAborted(),await e.refreshAccount(c),c.throwIfAborted();const d=o();if(r?.key===d.key&&r.value.expiresAt>t()+3e4)return r.value;i();let u=n.get(d.key);if(!u||u.controller.signal.aborted){const f=new AbortController,m=s(d,{...a,signal:AbortSignal.any([f.signal,e.signal])});u={promise:m,controller:f,users:0},n.set(d.key,u);const h=u;m.finally(()=>{n.get(d.key)===h&&n.delete(d.key)}).catch(()=>{})}u.users++;let l;try{const f=await Promise.race([u.promise,new Promise((m,h)=>{l=()=>h(c.reason),c.addEventListener("abort",l,{once:!0}),c.aborted&&l()})]);return c.throwIfAborted(),o().key!==d.key&&qe("AUTHORIZATION_CONTEXT_CHANGED","账号或开发快照已变化,请重试"),f}finally{c.removeEventListener("abort",l),--u.users===0&&u.controller.abort()}}}}const NA="/__hb_sdk__/dev-context";function pd(e,t){return Vr(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,publishedRuntimePermissions:e.publishedRuntimePermissions,warning:typeof e.warning=="string"?e.warning:void 0,declaredPermissions:Vr(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 _r(e,t=Date.now()){if(e.localDevGrant===void 0)return e;const r=Wd(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:Zf({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 DA(e){if(!Vr(e)||!yd(e,["networkRequest"]))return;const t=e.networkRequest;if(!(!Vr(t)||!yd(t,["status","useOfficialDomain"]))&&!(t.status!=="enabled"&&t.status!=="disabled")&&typeof t.useOfficialDomain=="boolean")return{networkRequest:{status:t.status,useOfficialDomain:t.useOfficialDomain}}}const MA={networkRequest:{status:"disabled",useOfficialDomain:!1}};function Gi(e){const t=je(e.localDevGrant?Ps({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}}:bA()}function SA(e,t,r){return r?.localDevGrant?Ps({declaredPermissions:r.declaredPermissions??{},runtimePermissions:e,localDevGrant:r.localDevGrant}).runtimePermissions:Ml(e,t,t.networkRequest.useOfficialDomain)}function _A(e){if(e.source!=="remote")return{schema_version:1,entries:[]};const t=Gi({...e,localDevGrant:void 0});return Ml(e.runtimePermissions,t,!1)}function bA(){return{networkRequest:{...MA.networkRequest}}}function Ml(e,t,r){const n=je(e);if(!n.valid)return{schema_version:1,entries:[]};const i=[];for(const s of Ot){const a=n.permissions[s];a&&i.push(s==="network"?{key:s,status:t.networkRequest.status,config:{useOfficialDomain:r}}:{key:s,status:a.status,config:{}})}const o=Vr(e)&&typeof e.revision=="number"&&Number.isInteger(e.revision)&&e.revision>=0?e.revision:void 0;return{schema_version:1,...o===void 0?{}:{revision:o},entries:i}}function Vr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&Object.getPrototypeOf(e)===Object.prototype}function yd(e,t){return Object.keys(e).length===t.length&&t.every(n=>Object.hasOwn(e,n))}function TA(e){let t,r=!1,n=!1,i;return{invalidate(a){return n?Promise.resolve({ok:!1}):e.shouldSkip?.(a,{draining:i!==void 0})?i??Promise.resolve({ok:!0}):(r=!0,i??=o().finally(()=>{i=void 0}),i)},dispose(){n||(n=!0,r=!1,t?.abort(),t=void 0)}};async function o(){let a={ok:!0};for(;r&&!n;){r=!1;const c=new AbortController;t=c;let d;try{d=await e.fetch(c.signal)}catch(l){a={ok:!1},!n&&!c.signal.aborted&&s(l);continue}finally{t===c&&(t=void 0)}if(n)return{ok:!1};let u;try{u=e.apply(d)}catch(l){a={ok:!1},n||s(l);continue}if(n)return{ok:!1};if(a={ok:!0},!!e.hasChanged(u))try{await e.onChanged(u)}catch(l){a={ok:!1},n||s(l)}}return n?{ok:!1}:a}function s(a){try{e.onError(a)}catch{}}}function OA(e){return TA({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 vA(e){const t=e.minDelayMs??1e3,r=e.maxDelayMs??15e3;let n=t,i=!1,o;return{schedule:s,reset(){n=t,a()},dispose(){i||(i=!0,a())}};function s(){i||e.isDisposed()||(a(),o=e.timers.setTimeout(async()=>{o=void 0;let c;try{c=await e.invalidate()}catch{c={ok:!1}}if(!(i||e.isDisposed())){if(c.ok){n=t,e.connectEvents();return}n=Math.min(n*2,r),s()}},n))}function a(){o!==void 0&&e.timers.clearTimeout(o),o=void 0}}const Go=new WeakMap;function Sl(e){return new Promise((t,r)=>{if(e.signal?.aborted){r(e.signal.reason);return}const{root:n,signal:i}=e;Go.set(n,document.activeElement);const o=[...n.querySelectorAll("button[data-action]")];n.dataset.hostDialog="true",n.style.zIndex="40";const s=()=>[...document.querySelectorAll("[data-host-dialog]")].at(-1);n.setAttribute("role","dialog"),n.setAttribute("aria-modal","true"),n.setAttribute("aria-label",e.title);let a;const c=()=>{i?.removeEventListener("abort",u),document.removeEventListener("keydown",f);const h=s()===n;if(n.remove(),h){const g=s();g&&(g.inert=!1,g.removeAttribute("aria-hidden"));let I=Go.get(n)??null;for(;I instanceof HTMLElement&&!I.isConnected;){const y=I.closest("[data-host-dialog]");I=y?Go.get(y)??null:null}I instanceof HTMLElement&&(!g||g.contains(I))?I.focus():g?.querySelector("button")?.focus()}},d=ef({kind:"dialog",mode:e.mode??"simulated",title:e.title,method:e.method,...e.callId?{callId:e.callId}:{},actions:o.map(h=>h.textContent?.trim()??"")},h=>{c(),a!==void 0?t(a):r(i?.reason??new DOMException(`宿主弹窗已${h}`,"AbortError"))});function u(){d.finish("cancelled")}function l(h){a=h,d.finish(h===e.cancelAction?"cancelled":"confirmed")}function f(h){if(s()!==n||(h.key==="Escape"&&e.cancelAction&&(h.preventDefault(),l(e.cancelAction)),h.key!=="Tab"||o.length===0))return;const g=o[0],I=o.at(-1);h.shiftKey&&document.activeElement===g?(h.preventDefault(),I.focus()):!h.shiftKey&&document.activeElement===I&&(h.preventDefault(),g.focus())}if(!d.active)return;if(i?.aborted){u();return}for(const h of o)h.addEventListener("click",()=>l(h.dataset.action));n.addEventListener("click",h=>{h.target===n&&e.cancelAction&&l(e.cancelAction)}),n.dataset.interactionId=d.interactionId;const m=s();m&&(m.inert=!0,m.setAttribute("aria-hidden","true")),(document.querySelector("#host-overlay-layer")??document.body).appendChild(n),i?.addEventListener("abort",u,{once:!0}),document.addEventListener("keydown",f),o[0]?.focus(),i?.aborted&&u()})}function br(e){return e.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&#039;")}const Ed="hb-sdk-action-dialog-style";async function qi(e){await _l(e)}async function LA(e){return await _l({title:"关注作者",detail:"是否关注当前小程序的作者?",signal:e.signal,method:"user.requestFollowAuthor",mode:"browser",confirmation:!0})?"confirmed":"cancelled"}async function _l(e){xA();const t=document.createElement("div");return t.className="hb-sdk-action-dialog",t.innerHTML=`
17
- <div class="hb-sdk-action-dialog__panel">
18
- <h2>${br(e.title)}</h2>
19
- <pre class="hb-sdk-action-dialog__detail">${br(e.detail)}</pre>
20
- <div class="hb-sdk-action-dialog__actions">
21
- ${e.confirmation?'<button type="button" data-action="cancel">取消</button>':""}
22
- <button type="button" class="primary" data-action="confirm">${e.confirmation?"关注":"确定"}</button>
23
- </div>
24
- </div>`,await Sl({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 CA(e,t){await qi({method:"navigation.openAppPage",title:"打开页面",detail:["protocolType: "+e.protocolType,"path: "+e.path,"params: "+sr(e.params)].join(`
25
- `),signal:t.signal,callId:t.requestId})}async function RA(e,t){await qi({method:"navigation.openAppPage",title:"打开小程序",detail:["miniProgramId: "+e.miniProgramId,"extra: "+sr(e.extra)].join(`
26
- `),signal:t.signal,callId:t.requestId})}async function PA(e,t){await qi({method:"share.showShareMenu",title:"分享",detail:["title: "+e.title,"description: "+e.description,"url: "+e.url,"channel: "+sr(e.channel),"post: "+sr(e.post)].join(`
27
- `),signal:t.signal,callId:t.requestId})}async function kA(e,t){await qi({method:"share.screenshot",title:"截图分享",detail:["rect: "+sr(e.rect),"post: "+sr(e.post)].join(`
28
- `),signal:t.signal,callId:t.requestId})}function sr(e){return JSON.stringify(e,null,2)}function xA(){if(document.getElementById(Ed))return;const e=document.createElement("style");e.id=Ed,e.textContent=`
29
- .hb-sdk-action-dialog {
30
- position: absolute;
31
- inset: 0;
32
- display: grid;
33
- place-items: center;
34
- padding: 24px;
35
- background: rgba(15, 23, 42, 0.45);
36
- }
37
-
38
- .hb-sdk-action-dialog__panel {
39
- width: min(420px, 100%);
40
- border-radius: 12px;
41
- padding: 20px;
42
- background: #fff;
43
- box-shadow: 0 20px 45px rgba(15, 23, 42, 0.2);
44
- }
45
-
46
- .hb-sdk-action-dialog__panel h2 {
47
- margin: 0 0 8px;
48
- font-size: 18px;
49
- }
50
-
51
- .hb-sdk-action-dialog__detail {
52
- margin: 0 0 16px;
53
- max-height: 40vh;
54
- overflow: auto;
55
- color: #1f2933;
56
- font-family: inherit;
57
- font-size: 12px;
58
- line-height: 1.6;
59
- white-space: pre-wrap;
60
- overflow-wrap: anywhere;
61
- word-break: break-word;
62
- }
63
-
64
- .hb-sdk-action-dialog__actions {
65
- display: flex;
66
- justify-content: flex-end;
67
- gap: 8px;
68
- }
69
-
70
- .hb-sdk-action-dialog__actions button {
71
- min-height: 36px;
72
- border: 1px solid #cad5e2;
73
- border-radius: 6px;
74
- padding: 0 12px;
75
- background: #fff;
76
- cursor: pointer;
77
- }
78
-
79
- .hb-sdk-action-dialog__actions .primary {
80
- border-color: #2563eb;
81
- color: #fff;
82
- background: #2563eb;
83
- }
84
- `,document.head.appendChild(e)}const UA={identity:"小程序身份",profile:"昵称和头像",steam_account:"Steam 账号"};async function jA(e){const t=document.createElement("div");return t.className="hb-sdk-auth-dialog",t.innerHTML=`
85
- <div class="hb-sdk-auth-dialog__panel">
86
- <h2>授权请求</h2>
87
- <p class="hb-sdk-auth-dialog__app">${br(e.miniProgram?.name||"当前小程序")} 申请访问:</p>
88
- <ul class="hb-sdk-auth-dialog__scopes">${e.scopes.map(n=>`<li>${br(UA[n]||n)}</li>`).join("")}</ul>
89
- ${e.userProfile?.nickname?`<p class="hb-sdk-auth-dialog__profile">当前账号:${br(e.userProfile.nickname)}</p>`:""}
90
- <div class="hb-sdk-auth-dialog__actions">
91
- <button type="button" data-action="deny">拒绝</button>
92
- <button type="button" class="primary" data-action="allow">允许</button>
93
- </div>
94
- </div>
95
- `,await Sl({root:t,title:"授权请求",method:"auth.authorize",mode:"browser",signal:e.signal,cancelAction:"deny"})==="allow"?{status:"granted",grantedScopes:[...e.scopes]}:{status:"cancelled"}}function zA(e){return{launchUrl:e.launchUrl,...e.locationBasePath!==void 0?{locationBasePath:e.locationBasePath}:{},sdkVersionPolicy:{minimumSdkVersion:"0.5.0",sdkVersion:sa,releaseChannel:"development"},runtimePermissions:e.runtimePermissions,networkPolicy:e.networkPolicy,...e.anonymousStorageScope?{anonymousStorageScope:e.anonymousStorageScope}:{},platformAccess:{source:"manifest",manifest:{platforms:Vi},sdkVersion:sa},environmentInfo:{appVersion:null,operatingSystem:{name:e.operatingSystem??"unknown",version:null}},...e.miniProgramId?{canonicalIdentity:{miniProgramId:e.miniProgramId}}:{}}}const HA=44;function FA(e){const t=()=>e.isCapsuleHidden?.()?0:HA,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:sf,showLoading:of,hideLoading:nf,vibrate:rf,openAppPage:CA,openWindow:RA,showShareMenu:PA,captureAndShare:kA,setScreenshotChromeHidden:tf}}const wd=["launch-only","stdio","full","prepare-fail","prepare-cancel","launch-cancel","os-blocked","normal-exit","crash","output-limit"],pn=[{phase:"downloading",loaded:4,total:12},{phase:"verifying",processed:8,total:12},{phase:"extracting",processed:12,total:12}],Id={"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 BA{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]:[...wd];for(const n of r){const i=this.preparations.get(n);for(const o of i?.operation?.timers??[])this.clearSchedule(o);i?.operation?.reject(ye("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:Id[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:pn[0]),i.operation.promise;let o,s;const a=new Promise((d,u)=>{o=d,s=u}),c={cancelled:!1,listeners:new Set([r.onProgress]),promise:a,reject:s,resolve:o,timers:new Set};{const d={status:{state:"preparing",progress:pn[0]},operation:c};this.preparations.set(n,d),this.diagnostic("prepare.started",n),pn.forEach((u,l)=>{const f=this.schedule(()=>{if(c.timers.delete(f),!c.cancelled){d.status={state:"preparing",progress:u};try{c.listeners.forEach(m=>m(u))}catch(m){c.cancelled=!0;for(const h of c.timers)this.clearSchedule(h);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:m instanceof Error?m.message:String(m)}),c.reject(m);return}if(this.diagnostic("prepare.progress",n,{phase:u.phase}),l===pn.length-1){if(d.operation=void 0,n==="prepare-fail"){d.status={state:"failed",error:{code:"COMPANION_INTEGRITY_FAILED",message:"固定 Fake 完整性校验失败",retryable:!0}},c.reject(ye("COMPANION_INTEGRITY_FAILED","固定 Fake 完整性校验失败")),this.diagnostic("prepare.failed",n,{code:"COMPANION_INTEGRITY_FAILED"});return}d.status={state:"ready",preparedAt:this.now()},c.resolve(this.getInfo(n)),this.diagnostic("prepare.ready",n)}}},l+1);c.timers.add(f)})}return a}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(ye("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(xf,{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 ye("COMPANION_NOT_PREPARED","固定 Fake 尚未准备完成");if(r==="os-blocked")throw ye("COMPANION_OS_BLOCKED","操作系统安全策略已阻止启动");const n=this.sessions.get(r);if(n&&!n.exited)throw ye("COMPANION_LAUNCH_FAILED","固定 Fake Session 已在运行");const i={id:`browser-fake-${++this.nextSessionId}`,alias:r,target:this.getInfo(r).target,capabilities:Id[r],state:"running",controllerGeneration:1},o={snapshot:i,stdinClosed:!1,exited:!1,queuedOutput:[]};return this.sessions.set(r,o),this.diagnostic("session.launched",r,{capabilities:[...i.capabilities],sessionId:i.id}),i.capabilities.includes("stdio")&&this.schedule(()=>{this.queueOutput(o,"stdout",1,`fake:ready
96
- `),this.queueOutput(o,"stderr",1,`fake:diagnostic
97
- `)},20),r==="normal-exit"&&this.schedule(()=>this.requestExit(o,{reason:"exited",exitCode:0}),40),r==="crash"&&this.schedule(()=>this.requestExit(o,{reason:"crashed",exitCode:1}),40),r==="output-limit"&&this.schedule(()=>this.requestExit(o,{reason:"output-limit"}),40),{...i,capabilities:[...i.capabilities]}}write(t){const r=this.readController(t);if(!r.snapshot.capabilities.includes("stdio"))throw ye("COMPANION_PIPE_CLOSED","stdio 未启用");if(r.stdinClosed)throw ye("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 ye("COMPANION_ATTACHMENT_NOT_FOUND","attachments 未启用");if(t.id!=="report")throw ye("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
98
- `);return{kind:"file",name:"browser-fake-report.txt",mode:"read",create:async()=>{throw ye("FILE_ACCESS_DENIED","Attachment 只读")},read:async()=>new Uint8Array(n),write:async()=>{throw ye("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 ye("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(Pf,{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(kf,{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 ye("COMPANION_SESSION_EXITED","固定 Fake Session 不存在");if(r.snapshot.controllerGeneration!==t.controllerGeneration)throw ye("COMPANION_SESSION_OWNERSHIP_LOST","固定 Fake Session 控制权已转移");return r}readAlias(t){if(!wd.includes(t))throw ye("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 VA=Object.freeze({[Oi]:!0,[vi]:!0,[Li]:!0,[Ci]:!0,[Ri]:!0,[Pi]:!0,[ki]:!0,[xi]:!0,[Ui]:!0,[ji]:!0,[zi]:!0,[Hi]:!0,[Ur]:!0,[xr]:!0,[jr]:!0});function GA(e){return new BA(e)}function ye(e,t){return Object.assign(new Error(t),{code:e})}const qA=/^[A-Za-z0-9_-]{22}$/,QA="https://api.xiaoheihe.cn/open_inapp/";function YA(e){const t=typeof e.port=="number"?e.port:Number(e.port);if(!Number.isInteger(t)||t<=0||t>65535)throw new TypeError("Mobile launch redirect port is invalid");if(!qA.test(e.token))throw new TypeError("Mobile launch redirect token is invalid");const r=new URL(`http://${e.host}:${t}/l/${e.token}`);if(r.protocol!=="http:"||r.hostname!==e.host||r.port!==String(t)||r.username||r.password||r.search||r.hash)throw new TypeError("Mobile launch redirect host is invalid");return r.href}function WA(e){const t=new URL(e);if(t.protocol!=="http:"||t.username||t.password)throw new TypeError("Mobile launch redirect URL must be an HTTP URL without credentials");const r=`heybox://${encodeURIComponent(JSON.stringify({protocol_type:"openWindow",full_screen:!0,navigation_bar:{title:""},webview:{url:t.href,pull:!1,refresh:!1}}))}`;return`${QA}#${r}`}function $A(e){const t=je(e.runtimePermissions),r=Ps({declaredPermissions:e.declaredPermissions??{},runtimePermissions:e.runtimePermissions,localDevGrant:e.localDevGrant}),n=[],i=je(e.publishedRuntimePermissions),o=je(r.runtimePermissions);for(const s of Yd){const a=s.key,c={network:"Network",companion:"Companion",appProtocol:"AppProtocol"}[a]??s.name;if(!e.declaredPermissions?.[a]?.enabled)continue;const d=t.valid&&t.permissions[a]?.status==="enabled",u=r.temporaryPermissionKeys.some(l=>l===a);n.push({key:a,label:c,state:s.access==="declaration"?"declared":d?"approved":u?"temporary":"unavailable",facts:{platformApproval:s.access==="declaration"?null:d,temporary:u,effective:o.permissions[a]?.status==="enabled",online:i.valid?i.permissions[a]?.status??"missing":"unknown"},...u?{releaseDifference:"本次使用临时授权,发布后仍需平台批准。"}:i.valid&&!i.permissions[a]?{releaseDifference:"线上快照尚未包含该权限,需发布包含声明的新版本。"}:{},...a==="appProtocol"?{highestRisk:!0}:{},...s.access!=="declaration"&&!d&&!u?{reason:a==="appProtocol"?"最高危险权限:可执行任意协议并绕过其他 SDK 能力权限;当前没有有效临时授权,线上未批准":"没有有效的本地临时授权,线上未批准"}:{}})}if(e.declaredPermissions?.network?.useOfficialDomain){const s=t.valid&&t.permissions.network?.status==="enabled"&&t.permissions.network.config.useOfficialDomain===!0;n.push({key:"network.useOfficialDomain",label:"官方域名",state:s?"approved":"unavailable",...s?{}:{reason:"不支持本地临时授权,获得线上批准后才能使用"}})}return n}function Dt(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 Ad="__hb_sdk_mini_dev_console_installed__",KA=["log","debug","info","warn","error"];function ZA(e,t=console){if(t[Ad])return;let r=!1;for(const n of KA){const i=t[n];if(typeof i!="function")continue;const o=function(...s){try{e(n,s)}catch{}return i.apply(this,s)};try{t[n]=o,r=!0}catch{break}}r&&(t[Ad]=!0)}const ms=1,Nd=64*1024,JA=64,XA=/^[A-Za-z0-9_-]{22}$/;class Te extends TypeError{code;constructor(t,r){super(r),this.name="BrowserDevHostChannelError",this.code=t}}function eN(e,t=!1){const r=rN(e,t);switch(gs(r,"Server message"),nN(r),r.type){case"grant":return Tr(r,["version","type","connectionEpoch","nextClientSequence","nextServerSequence","snapshot"],"grant"),Or(r.connectionEpoch,"connectionEpoch"),Mt(r.nextClientSequence,"nextClientSequence"),Mt(r.nextServerSequence,"nextServerSequence"),Dd(r.snapshot),r;case"event":return Tr(r,["version","type","connectionEpoch","sequence","event","snapshot"],"event"),Or(r.connectionEpoch,"connectionEpoch"),Mt(r.sequence,"sequence"),r.event!=="account.changed"&&r.event!=="status.changed"&&ht("event must be account.changed or status.changed"),Dd(r.snapshot),r;case"heartbeat":return Tr(r,["version","type","connectionEpoch","sequence"],"heartbeat"),Or(r.connectionEpoch,"connectionEpoch"),Mt(r.sequence,"sequence"),r;default:return ht("Unknown server message type")}}function tN(e){const t=e.connectionEpoch;Or(t,"connectionEpoch"),Mt(e.nextSequence,"nextSequence");let r=e.nextSequence;return{get nextSequence(){return r},accept(n){if(Or(n.connectionEpoch,"connectionEpoch"),Mt(n.sequence,"sequence"),n.connectionEpoch!==t)throw new Te("INVALID_SEQUENCE","Connection epoch does not match");if(r===void 0)throw new Te("INVALID_SEQUENCE","Sequence is exhausted");if(n.sequence!==r)throw new Te("INVALID_SEQUENCE",`Expected sequence ${r}`);r=r===Number.MAX_SAFE_INTEGER?void 0:r+1}}}function rN(e,t){if(t)throw new Te("BINARY_FRAME","Binary frames are not supported");if(typeof e!="string")throw new Te("TEXT_FRAME_REQUIRED","Channel frame must be text");if(e.length>Nd)throw new Te("TEXT_FRAME_TOO_LARGE","Channel text frame exceeds 64 KiB");if(new TextEncoder().encode(e).byteLength>Nd)throw new Te("TEXT_FRAME_TOO_LARGE","Channel text frame exceeds 64 KiB");try{return iN(e),JSON.parse(e)}catch(r){throw r instanceof Te?r:new Te("INVALID_JSON","Channel frame must contain strict JSON")}}function Dd(e){gs(e,"snapshot"),Tr(e,["account","permissions"],"snapshot"),gs(e.account,"snapshot.account"),Tr(e.account,["revision"],"snapshot.account"),Mt(e.account.revision,"snapshot.account.revision"),DA(e.permissions)||ht("snapshot.permissions is invalid")}function nN(e){e.version!==ms&&ht("version must be 1")}function gs(e,t){(typeof e!="object"||e===null||Array.isArray(e)||Object.getPrototypeOf(e)!==Object.prototype)&&ht(`${t} must be a plain JSON object`)}function Tr(e,t,r,n=[]){const i=Object.keys(e);(t.some(o=>!Object.hasOwn(e,o))||i.some(o=>!t.includes(o)&&!n.includes(o)))&&ht(`${r} fields are invalid`)}function Mt(e,t){(typeof e!="number"||!Number.isSafeInteger(e)||e<0)&&ht(`${t} must be a non-negative safe integer`)}function Or(e,t){(typeof e!="string"||!XA.test(e))&&ht(`${t} must be a 22-character base64url value`)}function ht(e){throw new Te("INVALID_MESSAGE",e)}function iN(e){new oN(e).scan()}class oN{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>=JA)throw new Te("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 Te("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 Md=[1e3,2e3,4e3,8e3,15e3];function sN(e){const t=new Set,r=e.webSocketFactory??(v=>new WebSocket(v)),n=e.randomValues??(v=>crypto.getRandomValues(v)),i=e.timers??{clearTimeout:v=>window.clearTimeout(v),setTimeout:(v,C)=>window.setTimeout(v,C)},o=e.onlineTarget??(typeof window>"u"?void 0:window),s=e.visibilityTarget??(typeof document>"u"?void 0:document),a=e.isOnline??(()=>typeof navigator>"u"||navigator.onLine!==!1);let c,d,u,l=!1,f=0,m,h=!1,g=!1;const I=new Set,y=(v,C)=>{if(!(!e.onDiagnostic||I.has(v))){I.add(v);try{e.onDiagnostic({phase:v,...C?{code:C}:{}})}catch{}}},b=(v,C,E=!1)=>{if(u&&v.account.revision<u.account.revision)return;const D=u&&JSON.stringify(v)===JSON.stringify(u);if(u=v,!(D&&!E))for(const M of t)M(v,C)},_=()=>{if(l||m!==void 0||c)return;const v=Md[Math.min(f,Md.length-1)];f+=1,m=i.setTimeout(()=>{m=void 0,S()},v)},P=()=>{l||!h||c||(m!==void 0&&(i.clearTimeout(m),m=void 0),S())},j=()=>{a()&&P()},U=()=>{s&&!s.hidden&&P()},O=()=>{g||(g=!0,o?.addEventListener("online",j),s?.addEventListener("visibilitychange",U))},w=()=>{g&&(g=!1,o?.removeEventListener("online",j),s?.removeEventListener("visibilitychange",U))},S=()=>{if(l||c)return;h=!0,O(),m!==void 0&&(i.clearTimeout(m),m=void 0);let v,C;try{v=r(e.url)}catch{y("constructor","WEBSOCKET_CONSTRUCTION_FAILED"),_();return}try{C=cN(n)}catch{y("entropy","NONCE_GENERATION_FAILED");try{v?.close(1011,"channel initialization failed")}catch{}_();return}c=v;let E,D,M;const R=()=>{v.removeEventListener("open",N),v.removeEventListener("message",A),v.removeEventListener("close",L),v.removeEventListener("error",k),d===R&&(d=void 0)},T=()=>{if(c===v){c=void 0,R();try{v.close(1008,"invalid channel state")}catch{}_()}},N=()=>{if(!(l||c!==v))try{v.send(JSON.stringify({version:ms,type:"hello",csrfToken:e.csrfToken,clientNonce:C}))}catch{y("send","HELLO_SEND_FAILED"),T()}},A=x=>{if(l||c!==v)return;if(typeof x.data!="string"){y("parse","TEXT_FRAME_REQUIRED"),T();return}let H;try{H=eN(x.data)}catch(F){y("parse",F instanceof Te?F.code:"INVALID_MESSAGE"),T();return}if(H.type==="grant"){if(M){y("sequence","DUPLICATE_GRANT"),T();return}E=H.connectionEpoch,D=H.nextClientSequence,M=tN({connectionEpoch:E,nextSequence:H.nextServerSequence}),f=0,I.clear(),b(H.snapshot,{type:"grant"});return}if(!M||!E||D===void 0){y("sequence","MESSAGE_BEFORE_GRANT"),T();return}try{M.accept(H)}catch{y("sequence","INVALID_SEQUENCE"),T();return}if(H.type==="heartbeat"){try{v.send(JSON.stringify({version:ms,type:"heartbeat.ack",connectionEpoch:E,sequence:D}))}catch{y("send","HEARTBEAT_ACK_SEND_FAILED"),T()}D=D===Number.MAX_SAFE_INTEGER?void 0:D+1;return}b(H.snapshot,{type:"event",event:H.event},!0)},L=()=>{c===v&&(y("close","SOCKET_CLOSED"),c=void 0,R(),_())},k=()=>{y("open","SOCKET_ERROR"),T()};v.addEventListener("open",N),v.addEventListener("message",A),v.addEventListener("close",L),v.addEventListener("error",k),d=R};return{connect:S,subscribeUpdates(v){return t.add(v),()=>t.delete(v)},dispose(){if(l)return;l=!0,h=!1,w(),m!==void 0&&i.clearTimeout(m),m=void 0;const v=c;c=void 0,d?.(),v?.close(1e3,"client disposed"),t.clear()}}}function aN(e){const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";let r="";for(let n=0;n<e.length;n+=3){const i=e[n]??0,o=e[n+1],s=e[n+2];r+=t[i>>2],r+=t[(i&3)<<4|(o??0)>>4],o!==void 0&&(r+=t[(o&15)<<2|(s??0)>>6]),s!==void 0&&(r+=t[s&63])}return r}function cN(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=aN(t);if(!/^[A-Za-z0-9_-]{22}$/.test(r))throw new TypeError("Channel nonce source returned invalid bytes");return r}let te=!1,Ee;const bl=new AbortController;try{ZA((e,t)=>{Zt(`console.${e}`,{source:"host",message:t.map(r=>AN(r)).join(" ")},Date.now(),e==="log"||e==="debug"?"log":e)})}catch{}const dN="/__hb_sdk_bootstrap__",uN="/__hb_sdk__/mobile-launch-redirect",lN="/__hb_sdk__/network",fN="/session/status",hN="/session/request",mN="/session/events",gN=320,pN=1e3,yN=1e3,EN=15e3,Sd="dark",wN=["windows","macos","linux","unknown"],Tl=new URL(location.href).searchParams,Ol=Tl.get("mini_url"),Oe=Tl.get("ui_preview")==="1",ce={get device(){return En("#device")},get mobileLanSelect(){return En("#mobile-lan-select")},get mobileQrImage(){return En("#mobile-qr-image")},get mobileQrStatus(){return En("#mobile-qr-status")}};if(!Ol&&!Oe)throw ce.device.innerHTML='<div class="error">Missing mini_url query.</div>',new Error("Missing mini_url query.");const vl=Ol??"about:blank",se=await na(),Js=Oe?void 0:await Ue.configure({csrfToken:se.csrfToken??"",diagnosticsToken:se.diagnosticsToken??"",signal:bl.signal,query:QN,onDropped:e=>{B.diagnosticsDropped=e},onOwnershipLost:xl});B.diagnosticTargetId=Js?.targetId??"";B.diagnosticOwnerId=Js?.ownerId??"";B.diagnosticTargetName=Js?.metadata.displayName??"";B.openPlatformBaseUrl=se.openPlatformBaseUrl;B.devReadiness=se.devReadiness;B.miniProgramSupportsDesktop=se.miniProgramSupportsDesktop;B.desktopLaunch.workspaceCardsEnabled=se.workspaceCardsEnabled;Od(se.hostPlatform);vd(se.windowForm);let rt=se.lanAddresses,_n=se.defaultLanAddressId,qt=se.mobileLaunchRedirect,Xs=se.nativeAppLaunchUnavailableReason,vr=se.devSessionId,ps=se.miniProgramManifestAccessToken,bn=se.workspaceCardsEnabled,Tn=se,ea=Wi(se),Le=se.devContext,$t=se.browserDevContext,De=_r($t);Ti();let Gr=Gi(De),Qi=0;const ar=new AbortController;let ta=0,Ke,On=0,nt=0,ut=!1,vn,ys,qo=!1;const cr=wf({apply:If,waitForLayout:async e=>{await kn(),await xd(e),await Ud(e)}});let ra=!1;function Qo(e){if(e.throwIfAborted(),te)throw new At("SESSION_CLOSED","调试台已关闭");if(B.diagnosticOwnershipLost)throw new At("TARGET_OWNERSHIP_LOST","此调试页已失效,请重新打开预览");if(!ra)throw new At("PREVIEW_NOT_READY","调试台正在初始化,请稍后重试");if(Wt)throw new At("SESSION_DISCONNECTED","开发服务已断开,请重新启动 dev")}const Es=Ef({observe:()=>{const e=Qr()?{width:Pn.value.width,height:Pn.value.height}:{width:Ko.value.screenWidth,height:Ko.value.screenHeight};return{preset:B.deviceSelectionId,orientation:Qr()?e.width>=e.height?"landscape":"portrait":B.display.orientation,runtimeStatus:B.runtimeStatus,viewport:e,instanceId:Ee?.mounted?Ee.instanceId:null,browserPixelRatio:window.devicePixelRatio,presentation:Nf()}},async selectPreset(e,t){Qo(t),B.deviceSelectOpen=!1;const r=B.previewMode,n=Ee;Af(e),await kn(),t.throwIfAborted(),B.previewMode!==r&&await _d(n,t)},async applyOrientation(e,t){Qo(t),B.deviceSelectOpen=!1,await cr.applyDisplay({mode:e,hideCapsule:B.display.capsuleHidden},t)},async reload(e){Qo(e),B.deviceSelectOpen=!1;const t=Ee;ft("runtime.restart",{boundary:ta+1}),Ct("manual restart").catch(()=>{}),await _d(t,e)},async waitForLayout(e){await kn(),e.throwIfAborted(),await xd(e),await Ud(e)}}),Ln=_f(),Ll={...Es.bridge,prepareCapture:Ln.prepare,restoreCapture:Ln.restore,cancel(e){Es.bridge.cancel(e),Ln.cancel(e)}};window.__HB_SDK_PREVIEW__=Ll;async function _d(e,t){for(;;){if(t.throwIfAborted(),te)throw new At("SESSION_CLOSED","调试台已关闭");if(Ee!==e&&Ke===void 0){const r=B.runtimeStatus;if(r==="ready"||Oe&&r==="idle")return;if(r==="error")throw new At("RUNTIME_START_FAILED","小程序 Runtime 启动失败,请查看调试日志");if(r==="closed")throw new At("RUNTIME_CLOSED","预览窗口已关闭或最小化,请先恢复窗口")}await new Promise((r,n)=>{const i=()=>{clearTimeout(o),n(t.reason)},o=setTimeout(()=>{t.removeEventListener("abort",i),r()},20);t.addEventListener("abort",i,{once:!0}),t.aborted&&i()})}}let ws,Is,As,Ns,Ds,bd=Date.now(),Wt=!1,Td=Promise.resolve(),Kt=-1,qr=!1,lt,Ms,Ss,Cn,It;const _i=new Set,_s=GA({onDiagnostic:({action:e,alias:t,detail:r})=>ft(`companion.fake.${e}`,{...t?{alias:t}:{},...r})}),dr=OA({applyStatus:e=>Fl(e,!0),fetchStatus:e=>Hl($l(ar.signal,e)),getCanonicalRevision:()=>Kt,onError:WN,reconcile:()=>vN(Qi)}),bs=vA({connectEvents:Bl,invalidate:()=>dr.invalidate(),isDisposed:()=>te,maxDelayMs:EN,minDelayMs:yN,timers:{clearTimeout:e=>window.clearTimeout(e),setTimeout:(e,t)=>window.setTimeout(()=>{e()},t)}});let Yo=0,yn="",Wo=!1,Ts,Os;function Cl(){Oe||te||B.diagnosticOwnershipLost||Ue.poll().finally(()=>{!te&&!B.diagnosticOwnershipLost&&(Os=window.setTimeout(Cl,1e3))})}Cl();await bi(!1);ql();Yl(Ql(se));Oe&&DN();$i();Oe||await Pl();await Ct("initial");Oe||(Bl(),TN());IN();ra=!0;kN();function Rl(){!Oe&&!te&&(Ts=window.setTimeout(()=>{Pl().finally(Rl)},1e3))}Rl();async function Pl(){if(!(Wo||te)){Wo=!0;try{const e=await fetch(`${aa}?targetId=${encodeURIComponent(B.diagnosticTargetId)}&after=${Yo}&limit=500`,{headers:{"x-hb-sdk-csrf":se.csrfToken??""},signal:AbortSignal.any([ar.signal,AbortSignal.timeout(5e3)])});if(!e.ok){B.diagnosticsStale=!0;return}const t=await e.json();if(te)return;if(yn&&t.epoch!==yn){Yo=0,yn=t.epoch;return}yn=t.epoch,B.uploadSessions=t.uploadSessions;const r=await fetch(`${aa}?mode=inspect`,{headers:{"x-hb-sdk-csrf":se.csrfToken??""},signal:AbortSignal.any([ar.signal,AbortSignal.timeout(5e3)])});if(r.ok){const o=await r.json();B.diagnosticInstances=o.instances,B.diagnosticTargets=o.targets,B.diagnosticPrimaryTargetId=o.primaryTargetId;const s=o.targets.find(a=>a.targetId===B.diagnosticTargetId);s&&(B.diagnosticTargetName=s.metadata.displayName),s&&(s.state==="closed"||s.ownerId!==B.diagnosticOwnerId)&&xl()}B.diagnosticsStale=!1,B.diagnosticsGap=B.diagnosticsGap||t.gap===!0;const n=new Map(B.diagnosticTargets.map(o=>[o.targetId,o.metadata.displayName])),i=new Map(B.diagnosticInstances.map(o=>[o.instanceId,n.get(o.targetId)]));for(const o of t.items){const s=af(o);s&&(s.targetName=n.get(o.targetId)??i.get(o.instanceId),s.uploadSessionId=o.uploadSessionId,s.uploadSessionName=t.uploadSessions.find(a=>a.id===o.uploadSessionId)?.name,s.dedupeKey=void 0,cf(s,o.cursor))}Yo=t.nextCursor}catch{B.diagnosticsStale=!0}finally{Wo=!1}}}function IN(){window.addEventListener("beforeunload",$N),window.addEventListener("hb-sdk:refresh-storage",$i),window.addEventListener("hb-sdk:qr-open-change",kl),ws=df(()=>document.querySelector("#host-fullscreen-exit-mount")),Is=rn(()=>B.devicePresetId,()=>cr.notifyViewportChange(),{flush:"post"}),As=rn(()=>B.previewMode,()=>{et("preview mode changed"),Ld(!1),uf(!1),ur("preview mode changed")},{flush:"sync"}),Ns=rn(()=>Pn.value,()=>cr.notifyViewportChange(),{flush:"post"}),Ds=rn(()=>B.desktopWindow.closed,(e,t)=>{if(Qr()){if(e){et("desktop window closed"),B.runtimeStatus="closed";return}t&&B.runtimeStatus==="closed"&&ur("desktop window reopened")}},{flush:"sync"})}function AN(e){if(typeof e=="string")return e;if(e instanceof Error)return(typeof e.stack=="string"?e.stack.split(`
99
- `).slice(0,4).join(`
100
- `):"")||`${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 kl(e){const t=e.detail?.open===!0;t!==ut&&(ut=t,nt+=1,Ki(),t&&(ce.mobileLanSelect.addEventListener("change",NN),Vl(),Jr()))}function NN(){ut&&Jr()}function ur(e){te||Ke!==void 0||(ft("runtime.restart",{boundary:ta+1}),Ke=window.setTimeout(()=>{Ke=void 0,te||Ct(e)},0))}async function Ct(e,t=vl,r){if(te||Wt||B.diagnosticOwnershipLost)return;if(Ke!==void 0&&window.clearTimeout(Ke),Ke=void 0,et(e),Qr()&&B.desktopWindow.closed){B.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(),o=lf(i,c=>{Oe||Ue.event(i,c)}),s={instanceId:i,launchUrl:t,locationBasePath:r,interactions:o,sequence:++ta,state:"starting",iframe:n,terminal:new AbortController,permissions:Jl(Gr),mounted:!1,hadReady:!1,pendingNavigationReload:!1};if(s.iframe.dataset.hbSdkInstanceId=s.instanceId,Ee=s,B.runtimeStatus="loading",jl(),Oe||Ue.send({operation:"register",instanceId:s.instanceId}),await kn(),!Ae(s))return;const a=Xl("#device");if(!a){$o(s,new Error("预览容器尚未挂载"));return}if(Oe){a.innerHTML='<div class="browser-mock-preview"><span class="browser-mock-preview__icon">UI</span><strong>Browser Mock</strong><small>mp_preview</small></div>',B.runtimeStatus="idle";return}a.replaceChildren(s.iframe),s.mounted=!0,Ue.send({operation:"activate",instanceId:s.instanceId});try{const c=await YI(MN(s));if(!Ae(s)){c.dispose();return}s.assembly=c,c.ports.companion=_s.port,c.ports.media=ff({getMode:()=>B.mediaSimulation,signal:s.terminal.signal});const d=IA({signal:s.terminal.signal,csrfToken:()=>se.csrfToken??""}),u=OI({iframe:s.iframe,authorizationContext:AA({signal:s.terminal.signal,refreshAccount:l=>bi(!0,l),request:zl,readState:()=>({signed:Le,browser:De,userId:lt,accountRevision:Kt,networkEnabled:s.permissions.networkRequest.status==="enabled"})}),ports:{...c.ports,...d},environment:c.environment,hostCapabilities:{...c.hostCapabilities,"media.pick":!0,...d?{"gameSaves.getFile":!0,"file.readBytes":!0,"file.readText":!0,"file.stat":!0,"file.exists":!0}:{},...VA},authPresentation:c.authPresentation,companionPresentation:_s.presentation,resolveLaunchConfiguration:async()=>(await c.resolveLaunch()).configuration,dispose:()=>vs(s),onDevDocumentReload:(l,f)=>{Ae(s)&&Ct("development document reloaded",l,f)},onDevUploadSession:l=>{Ae(s)&&(s.uploadSessionId=l,lr(s,{uploadSessionId:l}))},onReady:()=>{Ae(s)&&(s.state="ready",s.hadReady=!0,Cs.value=d?u.diagnostics.gameSaves:void 0,B.runtimeStatus="ready",lr(s),Zt("runtime.ready",{generation:s.sequence},Date.now(),void 0,s.instanceId))},onTrace:l=>bN(s,l),onError:l=>{Ae(s)&&$o(s,l)},onCapabilityTrace:l=>{Zt(l.method,{...l,source:"host"},l.timestamp,void 0,s.instanceId),Ae(s)&&l.method==="storage.setStorage"&&l.outcome==="success"&&$i()}});s.runtime=u,await u.start()}catch(c){if(!Ae(s))return;$o(s,c),Zt("runtime.start.failed",Wl(c,s),Date.now(),"error",s.instanceId),s.terminal.abort(c),s.runtime?.destroy(),s.iframe.remove(),vs(s)}}function xl(){te||B.diagnosticOwnershipLost||(B.diagnosticOwnershipLost=!0,et("预览页面授权已失效"),B.runtimeStatus="closed",ra=!1)}function Ae(e){return Ee===e&&!te&&!e.terminal.signal.aborted&&e.state!=="closed"&&e.state!=="failed"}function lr(e,t={}){Ue.send({operation:"update",instanceId:e.instanceId,state:e.state,...t})}function Ul(e,t){e.mounted&&(e.mounted=!1,Ue.send({operation:"detach",instanceId:e.instanceId,reason:t}))}function vs(e){Ee===e&&(Cs.value=void 0),e.interactions.dispose();const t=e.assembly;e.assembly=void 0,t?.dispose()}function $o(e,t){e.state==="failed"||e.state==="closed"||(e.state="failed",e.interactions.dispose(),lr(e,{error:Wl(t,e),...e.uploadSessionId?{uploadSessionId:e.uploadSessionId}:{}}),Ul(e,"Runtime failed"),Ee===e&&(B.runtimeStatus="error"))}function et(e){const t=Ee;t&&(Ee=void 0,Cs.value=void 0,t.state!=="failed"&&(t.state="closed",lr(t,{reason:e})),Ul(t,e),On+=1,hf(),_s.reset(),t.terminal.abort(new DOMException(e,"AbortError")),t.runtime?.destroy(),t.iframe.remove(),vs(t),cr.reset())}function DN(){ft("runtime.ready",{generation:1}),Cd(Rd("console.info",{source:"app",message:"页面初始化完成"},Date.now(),"info")),ft("user.getInfo",{durationMs:34,outcome:"success"}),ft("network.request",{durationMs:86,network:{method:"GET",origin:"https://api.example.com",pathname:"/demo",responseStatus:200},outcome:"success"})}function MN(e){const t=e.terminal.signal,r=De,n=vr,i=SA(r.runtimePermissions,e.permissions,r),o=Qr();return{signal:t,account:{async getCurrentUserId(){return(await bi(!1,t)).user_id},async ensureAuthenticated({signal:s}){await bi(!1,s)},onChange(s){return _i.add(s),()=>_i.delete(s)}},authenticatedRequest:zl,storage:{area:"local",storage:localStorage},presentation:FA({close:async()=>{Ae(e)&&(et("mini program closed"),jl(),B.runtimeStatus="closed",o&&Ld(!0))},reload:()=>{Ae(e)&&(e.pendingNavigationReload=!0)},onNavigationBarStyleChange:s=>{Ae(e)&&Pd(s)},...o?{getViewportMetrics:()=>{const s=Pn.value;return{windowWidth:s.width,windowHeight:s.height,screenWidth:window.screen.width,screenHeight:window.screen.height,pixelRatio:window.devicePixelRatio,safeArea:{left:0,right:s.width,top:0,bottom:s.height}}},getNavigationBarHeight:()=>Df}:{getDeviceMetrics:()=>Ko.value,applyDisplay:(s,a)=>cr.applyDisplay(s,a),isCapsuleHidden:()=>B.display.capsuleHidden},onViewportChange:s=>cr.onViewportChange(s)}),environment:{getCurrentHref:()=>location.href,isDevRuntime:()=>!0,setDocumentTitle:s=>{document.title=s}},resolveLaunch:async()=>({configuration:zA({launchUrl:e.launchUrl,locationBasePath:e.locationBasePath,runtimePermissions:i,networkPolicy:r.networkPolicy,...r.miniProgramId?{miniProgramId:r.miniProgramId}:n?{anonymousStorageScope:n}:{},operatingSystem:o?B.hostPlatform:mf.value.platform}),hostHints:{launchKind:r.source==="remote"?"dev-session":"anonymous-local-dev"}}),authPresentation:{confirmAuthorization:s=>jA(s),confirmFollowAuthor:s=>LA(s)},protocol:SN(e)}}function Qr(){return B.previewMode==="desktop"}function SN(e){return{async invoke(t){Zt("device.executeProtocol",{outcome:"success",delivery:"mock",protocolType:_N(t)},Date.now(),void 0,e.instanceId)}}}function _N(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 _e(r)&&typeof r.protocol_type=="string"?r.protocol_type:void 0}catch{return}}function jl(){document.documentElement.dataset.navigationBarStyle=Sd,Pd(Sd)}function bN(e,t){Ae(e)&&t.type==="document_validation"&&typeof t.documentVerifying=="boolean"&&lr(e,{documentVerifying:t.documentVerifying}),te||Ue.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(gf({...t,generation:e.sequence})),...t.errorCode?{errorCode:t.errorCode}:{}}),e.runtimeId!==t.runtimeId&&(e.runtimeId=t.runtimeId,lr(e,{runtimeId:t.runtimeId})),Ae(e)&&e.pendingNavigationReload&&t.type==="bridge_response"&&t.method==="navigation.reload"&&t.outcome==="success"&&(e.pendingNavigationReload=!1,ur("navigation.reload"))}async function zl(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 Yi(n?lN:hN,{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,bodyEncoding:e.bodyEncoding,timeout:e.timeout}),signal:t.signal});!n&&i.status===401&&dr.invalidate();const o=await i.json();if(!i.ok)throw o;return o}async function bi(e,t){const r=Qi,n=await Hl($l(ar.signal,t));return Kl(r)?Fl(n,e).status:Ls()}async function Hl(e){return await(await fetch(fN,{cache:"no-store",credentials:"same-origin",redirect:"error",signal:e})).json()}function Fl(e,t){if(!Number.isSafeInteger(e.revision)||e.revision<Kt)return{changed:!1,status:Ls()};const r=e.authenticated?e.user_id:void 0,n=e.authenticated?me(e.nickname):void 0,i=e.authenticated?me(e.avatar):void 0,o=e.revision!==Kt||e.authenticated!==qr||r!==lt||n!==Ms||i!==Ss;return Kt=e.revision,qr=e.authenticated,lt=r,Ms=n,Ss=i,ql(),t&&o&&_i.forEach(s=>s(lt)),{changed:o,status:Ls()}}function Ls(){return{authenticated:qr,revision:Kt,...qr&&lt?{user_id:lt}:{}}}function TN(){if(!(!se.csrfToken||te))try{const e=new URL("/__hb_sdk__/channel",location.href);e.protocol=e.protocol==="https:"?"wss:":"ws:",It=sN({csrfToken:se.csrfToken,onDiagnostic:t=>ft("channel.diagnostic",t),url:e.toString()}),It.subscribeUpdates((t,r)=>ON(t,r)),It.connect()}catch{It?.dispose(),It=void 0}}function ON(e,t){dr.invalidate(e.account.revision),JN(Gr,e.permissions)?t.type==="event"&&t.event==="status.changed"&&Ct("status changed"):(Gr=Jl(e.permissions),LN())}function Bl(){if(Cn?.close(),Cn=void 0,!lt||te)return;const e=new EventSource(mN);Cn=e,e.addEventListener("account-invalidated",()=>{dr.invalidate()}),e.addEventListener("account-revision",()=>{dr.invalidate()}),e.onopen=()=>{bs.reset()},e.onerror=()=>{e.close(),bs.schedule()}}async function vN(e){Kl(e)&&await Ct("account revision changed")}async function LN(){te||(await Ct("permission changed"),!te&&await Jr())}async function na(){const e=await fetch(dN,{cache:"no-store",credentials:"same-origin",redirect:"error",signal:AbortSignal.timeout(5e3)});if(!e.ok)throw new Error("Browser Dev Host bootstrap request failed");const t=await e.json();if(!_e(t))throw new Error("Browser Dev Host bootstrap is invalid");const r=Zl(t.mobileLaunchRedirect);if(Object.hasOwn(t,"mobileLaunchRedirect")&&t.mobileLaunchRedirect!==void 0&&!r)throw new fr;return{openPlatformBaseUrl:typeof t.openPlatformBaseUrl=="string"?t.openPlatformBaseUrl:void 0,devReadiness:PN(t.devReadiness),csrfToken:typeof t.csrfToken=="string"?t.csrfToken:void 0,diagnosticsToken:typeof t.diagnosticsToken=="string"?t.diagnosticsToken:void 0,defaultLanAddressId:typeof t.defaultLanAddressId=="string"?t.defaultLanAddressId:void 0,devSessionId:typeof t.devSessionId=="string"&&/^[a-f0-9]{32}$/.test(t.devSessionId)?t.devSessionId:void 0,devContext:pd(t.devContext,t.runtimePermissions),browserDevContext:pd(t.browserDevContext??t.devContext,t.runtimePermissions),lanAddresses:Array.isArray(t.lanAddresses)?t.lanAddresses.filter(ZN):[],loginAvailable:t.loginAvailable===!0,miniProgram:GN(t.miniProgram),miniProgramSupportsDesktop:t.miniProgramSupportsDesktop===!0,workspaceCardsEnabled:t.workspaceCardsEnabled===!0,mobileLaunchRedirect:r,nativeAppLaunchUnavailableReason:typeof t.nativeAppLaunchUnavailableReason=="string"?t.nativeAppLaunchUnavailableReason:void 0,miniProgramManifestAccessToken:typeof t.miniProgramManifestAccessToken=="string"?t.miniProgramManifestAccessToken:void 0,windowForm:RN(t.windowForm),hostPlatform:CN(t.hostPlatform)}}function CN(e){return wN.includes(e)?e:"unknown"}function RN(e){if(!_e(e))return;const t=s=>typeof s=="number"&&Number.isFinite(s)&&s>0?s:void 0,r=t(e.defaultWidth),n=t(e.defaultHeight),i=t(e.minWidth),o=t(e.minHeight);return{...r===void 0?{}:{defaultWidth:r},...n===void 0?{}:{defaultHeight:n},...i===void 0?{}:{minWidth:i},...o===void 0?{}:{minHeight:o},...typeof e.resizable=="boolean"?{resizable:e.resizable}:{}}}function PN(e){if(!_e(e))return;const t=s=>{if(!(!_e(s)||!["ready","pending","blocked","not-configured"].includes(String(s.state))))return{state:s.state,...typeof s.reason=="string"?{reason:s.reason.slice(0,240)}:{}}},r=t(e.browser),n=t(e.mobile),i=t(e.companion);if(!r||!n||!i||!_e(e.companion))return;const o=e.companion;return{browser:r,mobile:n,companion:{...i,...typeof o.digest=="string"&&/^[a-f0-9]{64}$/.test(o.digest)?{digest:o.digest}:{},artifacts:Array.isArray(o.artifacts)?o.artifacts.filter(s=>_e(s)&&typeof s.alias=="string"&&/^[a-z][a-z0-9-]{0,31}$/.test(s.alias)&&["windows-x64","macos-arm64"].includes(String(s.target))).map(({alias:s,target:a})=>({alias:s,target:a})):[]}}}async function Yi(e,t){const r=new Headers(t.headers);return r.set("content-type","application/json"),se.csrfToken&&r.set("x-hb-sdk-csrf",se.csrfToken),fetch(e,{...t,headers:r,cache:"no-store",credentials:"same-origin",redirect:"error"})}function kN(){ia(),Oe||(ys=window.setInterval(()=>{VN()},pN))}function Vl(e=ce.mobileLanSelect.options.length>0?ce.mobileLanSelect.value:void 0){ce.mobileLanSelect.replaceChildren();for(const t of rt){const r=document.createElement("option");r.value=t.id,r.textContent=`${t.name} · ${t.address}`,ce.mobileLanSelect.appendChild(r)}e&&rt.some(({id:t})=>t===e)?ce.mobileLanSelect.value=e:_n&&rt.some(({id:t})=>t===_n)?ce.mobileLanSelect.value=_n:rt[0]&&(ce.mobileLanSelect.value=rt[0].id),ce.mobileLanSelect.disabled=rt.length===0}async function Jr(){if(te)return;const e=++nt;if(Ki(),Le.source!=="remote"||!Le.localDevLaunchToken||Le.expiresAt!==void 0&&Le.expiresAt<=Date.now()){ce.mobileQrImage.removeAttribute("src"),ce.mobileQrStatus.textContent=Xs||"需要有效的本地调试启动票";return}const t=KN();if(!t?.mobileAppQrPayload){ce.mobileQrImage.removeAttribute("src"),ce.mobileQrStatus.textContent="未发现可用的局域网地址";return}ce.mobileQrStatus.textContent="正在生成二维码...";try{const r=await HN(t);if(e!==nt||te)return;const n=await xN(r.address,r.expiresAt);if(e!==nt||te)return;const i=await pA.toDataURL(n.payload,{width:gN,margin:1});if(e!==nt||te)return;ce.mobileQrImage.src=i,ce.mobileQrStatus.textContent=`${r.address.name} · ${r.address.address}`,BN(n.expiresAt,e)}catch(r){if(e!==nt||te)return;if(r instanceof fr){Rn();return}ce.mobileQrImage.removeAttribute("src"),ce.mobileQrStatus.textContent=oa(r)}}async function xN(e,t){const r=e.mobileAppQrPayload;if(!r)throw new Error("Mobile 启动配置不可用");const n=await UN(e,r);if(!n)return{expiresAt:t,payload:r};try{return{expiresAt:Math.min(t,n.expiresAt),payload:WA(YA({host:e.address,port:location.port,token:n.token}))}}catch{throw new fr}}async function UN(e,t){if(qt?.addressId===e.id)return qt;if(!qt)return;const r=await Yi(uN,{method:"POST",body:JSON.stringify({address_id:e.id,payload:t,previous_token:qt.token})});if(!r.ok)throw new fr;const n=await r.json(),i=_e(n)?Zl({addressId:n.address_id,expiresAt:n.expires_at,token:n.token}):void 0;if(!i||i.addressId!==e.id)throw new fr;return qt=i,Tn={...Tn,mobileLaunchRedirect:i},ea=Wi(Tn),i}async function jN(e){const t=await na(),r=zN(t,e),n=r?.mobileAppQrPayload;if(!r||!n)throw new Error("Mobile 启动配置不可用");return Gl(t),{...r,mobileAppQrPayload:n}}function zN(e,t){return e.lanAddresses.find(({id:r})=>r===t)??e.lanAddresses.find(({id:r})=>r===e.defaultLanAddressId)??e.lanAddresses[0]}function Gl(e){const t=Dt(De);B.devReadiness=e.devReadiness,B.miniProgramSupportsDesktop=e.miniProgramSupportsDesktop,Od(e.hostPlatform),vd(e.windowForm),bn=e.workspaceCardsEnabled,Tn=e,ea=Wi(e),Le=e.devContext,$t=e.browserDevContext,De=_r($t),Gr=Gi(De),Ti(),rt=e.lanAddresses,_n=e.defaultLanAddressId,qt=e.mobileLaunchRedirect,Xs=e.nativeAppLaunchUnavailableReason,vr=e.devSessionId,ps=e.miniProgramManifestAccessToken,Yl(Ql(e)),ut&&Vl(),ia(),t!==Dt(De)&&(et("local permission context changed"),ur("local permission context changed"))}function Ti(){B.localPermissions=$A(De),B.devContextWarning=De.source==="anonymous"?"未连接线上上下文":De.warning?"本地上下文受限,请检查 CLI 状态":""}function ia(){let e;try{e=pf(vl)}catch{}const t=Le.miniProgramId?.trim().toLowerCase();let r=Xs?.trim()??"";!r&&(Le.source!=="remote"||!t)&&(r="请先绑定可管理的小程序"),!r&&!Le.localDevLaunchToken?.trim()&&(r="正在等待有效的本地调试启动票"),!r&&bn&&!vr&&(r="本地调试会话尚未就绪"),!r&&Le.expiresAt!==void 0&&Le.expiresAt<=Date.now()&&(r="本地调试启动票已过期"),!r&&!e&&(r="未发现可用的本机调试地址"),kd({...e?{address:e}:{},...t?{miniProgramId:t}:{},...bn&&vr?{devSessionId:vr}:{},...ps?{miniProgramManifestToken:ps}:{},workspaceCardsEnabled:bn,ready:r==="",...r?{unavailableReason:r}:{}})}class fr extends Error{}async function HN(e){const t=Td.then(()=>FN(e));return Td=t.then(()=>{},()=>{}),t}async function FN(e){const t=new URL(e.appUrl),r=new URL(NA,location.origin),n=await Yi(r.pathname,{method:"POST",body:JSON.stringify({mini_url_origin:t.origin,runtime_permissions:_A(Le)})}),i=await n.json();if(!n.ok||!_e(i)||typeof i.token!="string"||typeof i.expires_at!="number")throw new Error("创建 Mobile Dev Session 失败");return{address:await jN(e.id),expiresAt:i.expires_at}}function BN(e,t){vn=window.setTimeout(()=>{!te&&ut&&t===nt&&Jr()},Math.max(1e3,e-Date.now()-3e4))}async function VN(){if(!(qo||te)){qo=!0;try{const e=await na();bd=Date.now();const t=Wt;Wt=!1;const r=Wi(e);if(!t&&r===ea&&Dt(_r(e.browserDevContext))===Dt(De)){$t=e.browserDevContext,De=_r($t),Ti();return}Gl(e),t&&ur("CLI dev session reconnected"),ut&&Jr()}catch(e){e instanceof fr&&Rn();const t=_r($t);Dt(t)!==Dt(De)&&(De=t,Gr=Gi(De),Ti(),et("local permission context expired"),ur("local permission context expired"),ia(),ut&&Rn()),Date.now()-bd>=3e4&&!Wt&&(Wt=!0,et("CLI dev session disconnected"),Xl("#device")?.replaceChildren(),B.runtimeStatus="closed",B.localPermissions=[],B.devContextWarning="调试会话已断开",kd({ready:!1,unavailableReason:"调试会话已断开"}),B.devReadiness={browser:{state:"blocked",reason:"调试会话已断开,等待 CLI 恢复"},mobile:{state:"blocked",reason:"调试会话已断开"},companion:{state:"blocked",reason:"调试会话已断开"}},ut&&Rn())}finally{qo=!1}}}function Rn(){nt+=1,Ki(),ce.mobileQrImage.removeAttribute("src"),ce.mobileQrStatus.textContent="Mobile 短链接配置无效"}function Wi(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:{permissionContext:Dt(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 ql(){if(!qr){B.account={authenticated:!1,avatar:"",nickname:"未登录"};return}B.account={authenticated:!0,avatar:Ss??"",nickname:Ms||lt||"已登录"}}function Ql(e){if(e.miniProgram?.miniProgramId)return e.miniProgram;const t=e.devContext.miniProgramId?.trim();return t?{miniProgramId:t}:e.miniProgram??null}function Yl(e){if(!!!e?.miniProgramId||!e){B.miniProgram={bound:!1,id:"",iconUrl:"",name:"未绑定小程序",detail:"本地调试"};return}B.miniProgram={bound:!0,id:e.miniProgramId,iconUrl:e.iconUrl??"",name:e.name||e.miniProgramId,detail:[e.miniProgramId,e.version].filter(Boolean).join(" · ")}}function GN(e){if(e===null)return null;if(!_e(e))return;const t=me(e.miniProgramId)??me(e.mini_program_id);if(t)return{miniProgramId:t,...me(e.name)?{name:me(e.name)}:{},...me(e.iconUrl)??me(e.icon_url)?{iconUrl:me(e.iconUrl)??me(e.icon_url)}:{},...me(e.status)?{status:me(e.status)}:{},...me(e.version)?{version:me(e.version)}:{},...me(e.developerName)??me(e.developer_name)?{developerName:me(e.developerName)??me(e.developer_name)}:{}}}function me(e){return typeof e=="string"&&e.trim()?e.trim():void 0}async function $i(){const e=++On,t=Ee?.instanceId;if(!t){B.storage=[],B.storageError="";return}try{const r=await Yi(yf,{method:"POST",body:JSON.stringify({instanceId:t,resource:"storage"})}),n=await r.json();if(te||e!==On||t!==Ee?.instanceId)return;if(!r.ok||n.code)throw new Error(n.error??"Storage 诊断查询失败");B.storage=n.value,B.storageError=""}catch(r){if(te||e!==On||t!==Ee?.instanceId)return;B.storage=[],B.storageError=oa(r)}}function Wl(e,t=Ee){const r=(c,d)=>{if(!(!c||typeof c!="object"))try{return Object.getOwnPropertyDescriptor(c,d)?.value}catch{return}},n=(c,d)=>{const u=r(c,d);return typeof u=="string"?u.slice(0,8192):void 0},i=r(e,"cause"),o=n(e,"stack")??n(i,"stack"),s=n(e,"name")??n(i,"name"),a=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",...s?{name:s}:{},...o?{stack:o}:{},...a?{cause:a}:{}}}function Zt(e,t,r=Date.now(),n,i){qN(Rd(e,t,r,n==="debug"?"log":n),i)}function qN(e,t){if(te)return;if(Oe){Cd(e);return}const r=_e(e.detail)?e.detail:{};Ue.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}:{},..._e(r.network)?{network:r.network}:{}})}async function QN(e){const t=Ee;if(!t||e.instanceId!==t.instanceId||!Ae(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([ar.signal,t.terminal.signal,AbortSignal.timeout(Math.max(1,e.deadline-Date.now()))]);let o,s;try{s=await Promise.race([n.getSnapshot(),new Promise((a,c)=>{o=()=>c(i.reason),i.addEventListener("abort",o,{once:!0}),i.aborted&&o()})])}catch{return{code:Date.now()>=e.deadline?"timeout":"closed",error:"实例查询已结束或超过期限"}}finally{o&&i.removeEventListener("abort",o)}return!Ae(t)||r!==t.runtime||e.instanceId!==t.instanceId?{code:"closed",error:"查询期间实例已结束"}:{value:s}}function YN(e,t){ft("host.message",{message:e,status:t})}function WN(e){te||YN(oa(e),"error")}function ft(e,t){Zt(e,t)}function $N(){Ue.close(),Ts!==void 0&&window.clearTimeout(Ts),Os!==void 0&&window.clearTimeout(Os),!te&&(te=!0,Ln.dispose(),Es.dispose(),window.__HB_SDK_PREVIEW__===Ll&&delete window.__HB_SDK_PREVIEW__,window.removeEventListener("hb-sdk:refresh-storage",$i),window.removeEventListener("hb-sdk:qr-open-change",kl),Qi+=1,ar.abort(new DOMException("Browser Dev Host disposed","AbortError")),dr.dispose(),et("Browser Dev Host disposed"),Ue.send({operation:"close-target",reason:"Browser Dev Host disposed"}),window.setTimeout(()=>bl.abort(),2e3),Cn?.close(),It?.dispose(),It=void 0,bs.dispose(),Ke!==void 0&&window.clearTimeout(Ke),Ke=void 0,Ki(),ys!==void 0&&window.clearInterval(ys),_i.clear(),ws?.(),ws=void 0,Is?.(),Is=void 0,As?.(),As=void 0,Ns?.(),Ns=void 0,Ds?.(),Ds=void 0)}function Ki(){vn!==void 0&&window.clearTimeout(vn),vn=void 0}function $l(e,t){return t?AbortSignal.any([e,t]):e}function Kl(e){return!te&&e===Qi}function KN(){return rt.find(({id:e})=>e===ce.mobileLanSelect.value)}function ZN(e){return _e(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 Zl(e){if(!(!_e(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 Jl(e){return{networkRequest:{...e.networkRequest}}}function JN(e,t){return e.networkRequest.status===t.networkRequest.status&&e.networkRequest.useOfficialDomain===t.networkRequest.useOfficialDomain}function oa(e){return e instanceof Error&&e.message?e.message:"操作失败"}function _e(e){return Object.prototype.toString.call(e)==="[object Object]"}function En(e){const t=document.querySelector(e);if(!t)throw new Error(`Missing Browser Dev Host element: ${e}`);return t}function Xl(e){return document.querySelector(e)??void 0}