@heybox/hb-sdk 0.9.8-alpha.2 → 0.9.8-alpha.3

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 (28) hide show
  1. package/CHANGELOG.md +4 -0
  2. package/dist/cli-chunks/{artifact-DpPkKB0p.cjs → artifact-C4JTa7D5.cjs} +3 -3
  3. package/dist/cli-chunks/{build-HnEZU7vh.cjs → build-wK5IcYmp.cjs} +5 -5
  4. package/dist/cli-chunks/{create-CoQZAi2o.cjs → create-D1DAg4er.cjs} +1 -1
  5. package/dist/cli-chunks/{dev-context-rMlSIJDh.cjs → dev-context-4ZGqANND.cjs} +2 -2
  6. package/dist/cli-chunks/{dev-DxvriNGb.cjs → dev-zh_Wb9WZ.cjs} +27 -19
  7. package/dist/cli-chunks/{doctor-BM6HYc6Q.cjs → doctor-Br31MP94.cjs} +1 -1
  8. package/dist/cli-chunks/{games-BdBtXI0v.cjs → games-B5bUkOCp.cjs} +1 -1
  9. package/dist/cli-chunks/{index-D0s71o42.cjs → index-B8tKOZ1w.cjs} +17 -17
  10. package/dist/cli-chunks/{index-B3G8sxcs.cjs → index-CkPh8IQn.cjs} +1 -1
  11. package/dist/cli-chunks/{index.esm-7M7Fm5fI.cjs → index.esm-DOvuMPDE.cjs} +6 -6
  12. package/dist/cli-chunks/{login-utKL8hNg.cjs → login-BGxsC07i.cjs} +1 -1
  13. package/dist/cli-chunks/{project-vite-BGZ0nd6-.cjs → project-vite-DU7Wp4o5.cjs} +1 -1
  14. package/dist/cli-chunks/{remote-CgYHLC8e.cjs → remote-HX0wMZ6W.cjs} +9 -7
  15. package/dist/cli-chunks/{runtime-permission-env-DcWIfDXK.cjs → runtime-permission-env-CAnNV2Lw.cjs} +23 -10
  16. package/dist/cli-chunks/{skill-BXKBDPnA.cjs → skill-B6KtNum4.cjs} +2 -2
  17. package/dist/cli-chunks/{version-BeddnZpt.cjs → version-DIhLu9jy.cjs} +1 -1
  18. package/dist/cli.cjs +1 -1
  19. package/dist/devtools/browser-dev-host/assets/{browser-dev-host-zYzCEWEd.js → browser-dev-host-5lgAW5KL.js} +12 -12
  20. package/dist/devtools/browser-dev-host/assets/{desktop-app-launch-CaciTQhd.js → desktop-app-launch-B4cpTP3G.js} +1 -1
  21. package/dist/devtools/browser-dev-host/assets/{index-CLEAsVY-.js → index-DxL85blk.js} +3 -3
  22. package/dist/devtools/browser-dev-host/index.html +2 -2
  23. package/dist/index.cjs.js +1 -1
  24. package/dist/index.esm.js +1 -1
  25. package/dist/vite.cjs.js +34 -9
  26. package/dist/vite.esm.js +34 -9
  27. package/package.json +7 -7
  28. package/skill/skill.json +4 -4
@@ -1,19 +1,19 @@
1
- import{m as Yh,H as wc,aV as Wh,bv as Zh,a2 as Kh,bc as Jh,bd as Xh,n as ct,bF as q,b5 as al,l as cl,aH as em,e as Ic,aM as tm,ay as rm,k as nm,aI as im,bz as Qr,aT as pn,aS as Gs,aU as ii,aZ as dl,a$ as om,f as wi,v as sm,al as Ii,Y as Pa,aL as am,j as $s,ap as qs,h as cm,b9 as ul,aD as dm,G as um,aX as ll,S as lm,z as fm,aA as hm,y as mm,b6 as gm,bx as fl,bw as hl,b1 as pm,g as Qs,aC as ym,b as Yt,c as Em}from"./desktop-app-launch-CaciTQhd.js";function wm(){return{targetId:"ui-preview-target",ownerId:"ui-preview-owner",adapterId:"browser-dev-host",kind:"browser",capabilities:{storage:!0,presentation:!0,sandboxList:!0,sandboxRead:!0},state:"attached",currentInstanceId:"ui-preview-instance",cdpTargetId:"ui-preview-browser-target",metadata:{displayName:"UI 预览(模拟)",browser:"Chrome",os:"macOS"},updatedAt:Date.now(),stale:!1}}function Im(){return[{key:"network",label:"网络请求",state:"approved",facts:{platformApproval:!0,temporary:!1,effective:!0,online:"enabled"}},{key:"companion",label:"桌面辅助应用",state:"temporary",facts:{platformApproval:!1,temporary:!0,effective:!0,online:"disabled"},releaseDifference:"发布前需要获得平台批准。"},{key:"network.useOfficialDomain",label:"官方域名",state:"unavailable",facts:{platformApproval:!1,temporary:!1,effective:!1,online:"disabled"},reason:"不支持本地临时授权,获得平台批准后才能使用。"}]}const Hn={device:'[data-preview-target="device"]',screen:'[data-preview-target="screen"]',app:"#device iframe",workbench:'[data-testid="workbench-root"]'},Ac=15e3,Am=32*1024*1024,_c="data-hb-preview-capture-device",$o="data-hb-preview-capture-ancestor",Dc="data-hb-preview-capture-surface",Nc=64,_m=1024;function Dm(e={}){const t=e.document??globalThis.document,r=t.defaultView,n=e.leaseMs??Ac;if(!Number.isFinite(n)||n<=0||n>Ac)throw Ve("INVALID_CAPTURE_LEASE","截图租约无效");let i;function o(d,u,f){d.attributes.push({element:u,name:f,previous:u.getAttribute(f)}),u.setAttribute(f,d.token)}function s(d){const u=i;if(!u||u.token!==d)return!1;const f=a(u),l=!!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:h,name:m,previous:E}of u.attributes)h.getAttribute(m)===d&&(E===null?h.removeAttribute(m):h.setAttribute(m,E));return u.overlay.remove(),l&&(r.scrollX!==u.scroll.x||r.scrollY!==u.scroll.y)&&r.scrollTo(u.scroll.x,u.scroll.y),f}function a(d){const{viewport:u,target:f,rect:l}=d;if(!f?.isConnected||!l||Date.now()>=d.expiresAt||r.innerWidth!==u.width||r.innerHeight!==u.height||r.devicePixelRatio!==u.devicePixelRatio)return!1;const h=f.getBoundingClientRect();return["left","top","width","height"].every(m=>Math.abs(h[m]-l[m])<.01)}async function c(d,u){if(u?.throwIfAborted(),!Number.isFinite(d.deadlineAt)||Date.now()>=d.deadlineAt)throw Ve("PREVIEW_TIMEOUT","截图操作已超时");if(d.scope==="workbench"||!Object.hasOwn(Hn,d.scope))throw Ve("INVALID_CAPTURE_SCOPE","设备像素截图仅支持 device、screen 或 app");if(!d.operationId||d.operationId.length>128)throw Ve("INVALID_OPERATION","截图操作标识无效");if(!d.previewImage.startsWith("data:image/png;base64,")||d.previewImage.length>Am)throw Ve("INVALID_CAPTURE_IMAGE","共享窗口冻结图无效或过大");if(i)throw Ve("PREVIEW_BUSY","已有设备截图正在执行");const f=t.querySelectorAll(Hn.device);if(f.length!==1)throw Ve("DEVICE_NOT_UNIQUE","设备画面不唯一或尚未创建");const l=f[0],h=d.scope==="device"?l:t.querySelector(Hn[d.scope]);if(!h||h!==l&&!l.contains(h))throw Ve("CAPTURE_TARGET_UNAVAILABLE","截图内容尚未创建");const m=l.getBoundingClientRect();if(!(m.width>0&&m.height>0))throw Ve("CAPTURE_TARGET_UNAVAILABLE","设备画面当前不可见");const E=t.createElement("img");E.alt="",E.setAttribute("aria-hidden","true"),E.setAttribute("data-hb-preview-capture-freeze",""),E.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;`,E.addEventListener("wheel",z=>z.preventDefault(),{passive:!1}),E.addEventListener("touchmove",z=>z.preventDefault(),{passive:!1});const _=Math.min(Date.now()+n,d.deadlineAt),w={operationId:d.operationId,token:r.crypto.randomUUID(),overlay:E,attributes:[],scroll:{x:r.scrollX,y:r.scrollY},viewport:{width:r.innerWidth,height:r.innerHeight,devicePixelRatio:r.devicePixelRatio},expiresAt:_};i=w,w.timer=setTimeout(()=>s(w.token),Math.max(0,_-Date.now()));const S=()=>s(w.token);u?.addEventListener("abort",S,{once:!0}),w.removeAbort=()=>u?.removeEventListener("abort",S);const p=()=>{const{viewport:z}=w;(r.innerWidth!==z.width||r.innerHeight!==z.height||r.devicePixelRatio!==z.devicePixelRatio)&&s(w.token)};r.addEventListener("resize",p),w.removeResize=()=>r.removeEventListener("resize",p);const M=()=>{if(u?.throwIfAborted(),i!==w||Date.now()>=_)throw Ve("CAPTURE_EXPIRED","截图布局租约已结束,请重新截图")};try{E.src=d.previewImage,await E.decode(),M();const z=w.token,A=`[${_c}="${z}"]`,D=r.getComputedStyle(l),I=new r.DOMMatrixReadOnly(D.transform==="none"?void 0:D.transform),v=Math.atan2(I.b,I.a),T=l.querySelector(".desktop-window__surface"),x=T?T.offsetWidth:Number.parseFloat(D.width),N=T?T.offsetHeight:Number.parseFloat(D.height),b=D.backgroundColor,O=r.getComputedStyle(t.body).backgroundColor,j=ye=>!ye||ye==="transparent"||ye==="rgba(0, 0, 0, 0)",U=j(b)?j(O)?"#fff":O:b;if(!(x>0&&N>0))throw Ve("CAPTURE_TARGET_UNAVAILABLE","设备布局尺寸无效");M(),t.body.append(E),o(w,l,_c),T&&o(w,T,Dc);for(let ye=l.parentElement;ye;ye=ye.parentElement)o(w,ye,$o);const L=t.createElement("style");w.style=L;const C=`
1
+ import{m as Yh,H as wc,aV as Wh,bv as Zh,a2 as Kh,bc as Jh,bd as Xh,n as ct,bF as q,b5 as al,l as cl,aH as em,e as Ic,aM as tm,ay as rm,k as nm,aI as im,bz as Qr,aT as pn,aS as Gs,aU as ii,aZ as dl,a$ as om,f as wi,v as sm,al as Ii,Y as ka,aL as am,j as $s,ap as qs,h as cm,b9 as ul,aD as dm,G as um,aX as ll,S as lm,z as fm,aA as hm,y as mm,b6 as gm,bx as fl,bw as hl,b1 as pm,g as Qs,aC as ym,b as Yt,c as Em}from"./desktop-app-launch-B4cpTP3G.js";function wm(){return{targetId:"ui-preview-target",ownerId:"ui-preview-owner",adapterId:"browser-dev-host",kind:"browser",capabilities:{storage:!0,presentation:!0,sandboxList:!0,sandboxRead:!0},state:"attached",currentInstanceId:"ui-preview-instance",cdpTargetId:"ui-preview-browser-target",metadata:{displayName:"UI 预览(模拟)",browser:"Chrome",os:"macOS"},updatedAt:Date.now(),stale:!1}}function Im(){return[{key:"network",label:"网络请求",state:"approved",facts:{platformApproval:!0,temporary:!1,effective:!0,online:"enabled"}},{key:"companion",label:"桌面辅助应用",state:"temporary",facts:{platformApproval:!1,temporary:!0,effective:!0,online:"disabled"},releaseDifference:"发布前需要获得平台批准。"},{key:"network.useOfficialDomain",label:"官方域名",state:"unavailable",facts:{platformApproval:!1,temporary:!1,effective:!1,online:"disabled"},reason:"不支持本地临时授权,获得平台批准后才能使用。"}]}const Hn={device:'[data-preview-target="device"]',screen:'[data-preview-target="screen"]',app:"#device iframe",workbench:'[data-testid="workbench-root"]'},Ac=15e3,Am=32*1024*1024,_c="data-hb-preview-capture-device",$o="data-hb-preview-capture-ancestor",Dc="data-hb-preview-capture-surface",Nc=64,_m=1024;function Dm(e={}){const t=e.document??globalThis.document,r=t.defaultView,n=e.leaseMs??Ac;if(!Number.isFinite(n)||n<=0||n>Ac)throw Ve("INVALID_CAPTURE_LEASE","截图租约无效");let i;function o(d,u,f){d.attributes.push({element:u,name:f,previous:u.getAttribute(f)}),u.setAttribute(f,d.token)}function s(d){const u=i;if(!u||u.token!==d)return!1;const f=a(u),l=!!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:h,name:m,previous:E}of u.attributes)h.getAttribute(m)===d&&(E===null?h.removeAttribute(m):h.setAttribute(m,E));return u.overlay.remove(),l&&(r.scrollX!==u.scroll.x||r.scrollY!==u.scroll.y)&&r.scrollTo(u.scroll.x,u.scroll.y),f}function a(d){const{viewport:u,target:f,rect:l}=d;if(!f?.isConnected||!l||Date.now()>=d.expiresAt||r.innerWidth!==u.width||r.innerHeight!==u.height||r.devicePixelRatio!==u.devicePixelRatio)return!1;const h=f.getBoundingClientRect();return["left","top","width","height"].every(m=>Math.abs(h[m]-l[m])<.01)}async function c(d,u){if(u?.throwIfAborted(),!Number.isFinite(d.deadlineAt)||Date.now()>=d.deadlineAt)throw Ve("PREVIEW_TIMEOUT","截图操作已超时");if(d.scope==="workbench"||!Object.hasOwn(Hn,d.scope))throw Ve("INVALID_CAPTURE_SCOPE","设备像素截图仅支持 device、screen 或 app");if(!d.operationId||d.operationId.length>128)throw Ve("INVALID_OPERATION","截图操作标识无效");if(!d.previewImage.startsWith("data:image/png;base64,")||d.previewImage.length>Am)throw Ve("INVALID_CAPTURE_IMAGE","共享窗口冻结图无效或过大");if(i)throw Ve("PREVIEW_BUSY","已有设备截图正在执行");const f=t.querySelectorAll(Hn.device);if(f.length!==1)throw Ve("DEVICE_NOT_UNIQUE","设备画面不唯一或尚未创建");const l=f[0],h=d.scope==="device"?l:t.querySelector(Hn[d.scope]);if(!h||h!==l&&!l.contains(h))throw Ve("CAPTURE_TARGET_UNAVAILABLE","截图内容尚未创建");const m=l.getBoundingClientRect();if(!(m.width>0&&m.height>0))throw Ve("CAPTURE_TARGET_UNAVAILABLE","设备画面当前不可见");const E=t.createElement("img");E.alt="",E.setAttribute("aria-hidden","true"),E.setAttribute("data-hb-preview-capture-freeze",""),E.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;`,E.addEventListener("wheel",z=>z.preventDefault(),{passive:!1}),E.addEventListener("touchmove",z=>z.preventDefault(),{passive:!1});const _=Math.min(Date.now()+n,d.deadlineAt),w={operationId:d.operationId,token:r.crypto.randomUUID(),overlay:E,attributes:[],scroll:{x:r.scrollX,y:r.scrollY},viewport:{width:r.innerWidth,height:r.innerHeight,devicePixelRatio:r.devicePixelRatio},expiresAt:_};i=w,w.timer=setTimeout(()=>s(w.token),Math.max(0,_-Date.now()));const S=()=>s(w.token);u?.addEventListener("abort",S,{once:!0}),w.removeAbort=()=>u?.removeEventListener("abort",S);const p=()=>{const{viewport:z}=w;(r.innerWidth!==z.width||r.innerHeight!==z.height||r.devicePixelRatio!==z.devicePixelRatio)&&s(w.token)};r.addEventListener("resize",p),w.removeResize=()=>r.removeEventListener("resize",p);const M=()=>{if(u?.throwIfAborted(),i!==w||Date.now()>=_)throw Ve("CAPTURE_EXPIRED","截图布局租约已结束,请重新截图")};try{E.src=d.previewImage,await E.decode(),M();const z=w.token,A=`[${_c}="${z}"]`,D=r.getComputedStyle(l),I=new r.DOMMatrixReadOnly(D.transform==="none"?void 0:D.transform),v=Math.atan2(I.b,I.a),T=l.querySelector(".desktop-window__surface"),x=T?T.offsetWidth:Number.parseFloat(D.width),N=T?T.offsetHeight:Number.parseFloat(D.height),b=D.backgroundColor,O=r.getComputedStyle(t.body).backgroundColor,j=ye=>!ye||ye==="transparent"||ye==="rgba(0, 0, 0, 0)",U=j(b)?j(O)?"#fff":O:b;if(!(x>0&&N>0))throw Ve("CAPTURE_TARGET_UNAVAILABLE","设备布局尺寸无效");M(),t.body.append(E),o(w,l,_c),T&&o(w,T,Dc);for(let ye=l.parentElement;ye;ye=ye.parentElement)o(w,ye,$o);const L=t.createElement("style");w.style=L;const C=`
2
2
  [${$o}="${z}"] {overflow:visible!important;scrollbar-width:none!important;}
3
3
  [${$o}="${z}"]::-webkit-scrollbar {display:none!important;}
4
4
  [${Dc}="${z}"] {transform:none!important;transition:none!important;}
5
- `,H=(ye,Oe,Me=0,Pe=0)=>`${A} {position:absolute!important;left:${ye}px!important;top:${Oe}px!important;width:${x}px!important;height:${N}px!important;transform:translate(${Me}px,${Pe}px) rotate(${v}rad)!important;transition:none!important;z-index:2147483646!important;background-color:${U}!important;}`;L.textContent=C+H(0,0),M(),t.head.append(L);const F=l.getBoundingClientRect(),$=t.querySelector(Hn.app),K=$&&l.contains($)?$.getBoundingClientRect():void 0,g=K&&K.width>0&&K.height>0?K:void 0,P=g?Math.floor(r.innerWidth-1-(g.left-F.left)):r.innerWidth+64,B=g?Math.floor(r.innerHeight-1-(g.top-F.top)):32,Q=P-F.left,X=B-F.top;M(),L.textContent=C+H(Q,X);const ne=l.getBoundingClientRect();L.textContent=C+H(Q,X,P-ne.left,B-ne.top),M();const ie=h.getBoundingClientRect(),ue=Math.floor(lr(ie.left+r.scrollX)),Ee=Math.floor(lr(ie.top+r.scrollY)),me={x:ue,y:Ee,width:Math.ceil(lr(ie.right+r.scrollX))-ue,height:Math.ceil(lr(ie.bottom+r.scrollY))-Ee};if(!(me.width>0&&me.height>0)||me.x<0||me.y<0)throw Ve("CAPTURE_LAYOUT_INVALID","无法建立完整设备截图布局");if(g&&$){const ye=$.getBoundingClientRect();if(!(ye.left<r.innerWidth&&ye.top<r.innerHeight&&ye.right>0&&ye.bottom>0))throw Ve("CAPTURE_LAYOUT_INVALID","无法保持 iframe 的最小绘制区域");const Oe=l.getBoundingClientRect(),Me=Math.floor(lr(Oe.left))-1,Pe=Math.floor(lr(Oe.top))-1,ze=r.innerWidth-Me,Ft=r.innerHeight-Pe;if(Me<0||Pe<0||ze<=0||Ft<=0||ze>Nc||Ft>Nc||ze*Ft>_m)throw Ve("CAPTURE_LAYOUT_INVALID","无法在有界角部保持完整设备绘制,请改用 --scale css");E.style.clipPath=`polygon(0 0,100% 0,100% ${Pe}px,${Me}px ${Pe}px,${Me}px 100%,0 100%)`,E.setAttribute("data-hb-preview-capture-corner",JSON.stringify({x:Me,y:Pe,width:ze,height:Ft}))}const ge=t.createElement("div");if(ge.setAttribute("aria-hidden","true"),ge.style.cssText=`position:absolute;left:${me.x+me.width+2}px;top:${me.y+me.height+2}px;width:1px;height:1px;pointer-events:none;opacity:0;`,w.bounds=ge,M(),t.body.append(ge),w.target=h,w.rect=ie,await Nm(r,u),M(),!a(w))throw Ve("CAPTURE_LAYOUT_INVALID","截图准备期间布局发生变化,请重新截图");w.observer=new r.ResizeObserver(()=>{i===w&&!a(w)&&s(w.token)});for(const{element:ye}of w.attributes)w.observer.observe(ye);return{token:z,clip:me,devicePixelRatio:r.devicePixelRatio,expiresAt:_}}catch(z){throw s(w.token),z}}return{prepare:c,restore:s,cancel:d=>i?.operationId!==d?!1:(s(i.token),!0),dispose:()=>{i&&s(i.token)}}}function Nm(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 Ve(e,t){return Object.assign(new Error(t),{name:"PreviewError",code:e})}function lr(e){const t=Math.round(e);return Math.abs(e-t)<.001?t:e}const Ca="user.games.getOverview",Ai="user.data.query",un="user.data.sync",_i="user.data.file",La="user.dataPermission.request",Ua="user.dataPermission.get",xa="user.dataPermission.set",za="user.dataPermission.openSettings",ja="user.dataPermission.revokeSession",ml=[Ca,Ai,un,_i,La,Ua,xa,za,ja],Di="workspaceCards.requestRefresh",Ni="auth.getAccountState",Mi="auth.login",Si="user.getFollowStatus",bi="user.requestFollowAuthor",Mm="gameSaves.list",Sm="gameSaves.sync",bm="gameSaves.getFile",Tm="gameSaves.readParsedData",Ti="user.getInfo",vi="user.revokeAuthorization",Oi="user.getSteamGameList",yn="user.showAppreciation",Ri="share.copyLink",ki="share.showShareMenu",Pi="share.screenshot",Ci="share.screenshotLong",nr="viewport.setDisplay",Li="viewport.getWindowInfo",Ui="viewport.setNavigationBarStyle",En="storage.getStorage",wn="storage.setStorage",xi="network.request",zi="network.download",ji="network.upload",Bi="files.pickFiles",Hi="files.pickDirectory",Fi="files.saveFile",In="file.create",An="file.remove",Vi="file.exists",_n="file.readText",Gi="file.writeText",Dn="file.readBytes",$i="file.writeBytes",Nn="file.stat",qi="directory.create",Mn="directory.remove",Qi="directory.exists",Yi="directory.list",Sn="media.pick",Wi="ui.showToast",Zi="ui.showLoading",Ki="ui.hideLoading",Ji="device.vibrate",Xi="device.setClipboard",eo="device.executeProtocol",to="navigation.close",ro="navigation.reload",no="navigation.openAppPage",bt="cloud.leaderboard.submit",at="cloud.leaderboard.getList",xt="cloud.leaderboard.getCurrentUserEntry",ir="cloud.leaderboard.deleteCurrentUserEntry",wt="cloud.leaderboard.getInfo",vr="cloud.storage.getStorage",Or="cloud.storage.setStorage",Rr="cloud.storage.removeItem",or="cloud.storage.getKeys",wo="companion.getInfo",Io="companion.getPreparationStatus",Ao="companion.prepare",_o="companion.cancelPreparation",Do="companion.getActiveSession",No="companion.launch",Mo="companion.session.write",So="companion.session.closeStdin",bo="companion.session.terminate",To="companion.session.ackOutput",vo="companion.openAttachment",Oo="companion.showNotification",zt=[...[Mm,Sm,bm,Tm].map(e=>({method:e,module:"gameSaves",capability:e,requirement:{kind:"all",permissions:["gameSaves"]},risk:"high"})),...ml.map(e=>({method:e,module:"userGameData",capability:e,requirement:{kind:"all",permissions:["user_game_data"]},risk:"high"})),{method:Di,module:"workspaceCards",capability:Di,requirement:{kind:"all",permissions:["workspaceCards"]},risk:"high"},{method:Ni,module:"auth",capability:Ni,requirement:{kind:"none"},risk:"low"},{method:Mi,module:"auth",capability:Mi,requirement:{kind:"all",permissions:["userInfo"]},risk:"medium"},{method:Si,module:"user",capability:Si,requirement:{kind:"none"},risk:"low"},{method:bi,module:"user",capability:bi,requirement:{kind:"none"},risk:"high"},{method:Ti,module:"user",capability:Ti,requirement:{kind:"all",permissions:["userInfo"]},risk:"medium"},{method:vi,module:"user",capability:vi,requirement:{kind:"none"},risk:"high"},{method:Oi,module:"user",capability:Oi,requirement:{kind:"all",permissions:["steamLibrary"]},risk:"high"},{method:yn,module:"user",capability:yn,requirement:{kind:"none"},risk:"medium"},{method:Ri,module:"share",capability:Ri,requirement:{kind:"all",permissions:["share"]},risk:"medium"},{method:ki,module:"share",capability:ki,requirement:{kind:"all",permissions:["share"]},risk:"low"},{method:Pi,module:"share",capability:Pi,requirement:{kind:"all",permissions:["share"]},risk:"medium"},{method:Ci,module:"share",capability:Ci,requirement:{kind:"all",permissions:["share"]},risk:"medium"},{method:Li,module:"viewport",capability:Li,requirement:{kind:"none"},risk:"low"},{method:Ui,module:"viewport",capability:Ui,requirement:{kind:"none"},risk:"low"},{method:nr,module:"viewport",capability:nr,requirement:{kind:"none"},risk:"low"},{method:En,module:"storage",capability:En,requirement:{kind:"all",permissions:["storage"]},risk:"low"},{method:wn,module:"storage",capability:wn,requirement:{kind:"all",permissions:["storage"]},risk:"medium"},{method:xi,module:"network",capability:xi,requirement:{kind:"all",permissions:["network"]},risk:"high"},{method:zi,module:"network",capability:zi,requirement:{kind:"all",permissions:["network","filesystem"]},risk:"high"},{method:ji,module:"network",capability:ji,requirement:{kind:"all",permissions:["network","filesystem"]},risk:"high"},{method:Bi,module:"files",capability:Bi,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Hi,module:"files",capability:Hi,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Fi,module:"files",capability:Fi,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:In,module:"file",capability:In,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:An,module:"file",capability:An,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Vi,module:"file",capability:Vi,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:_n,module:"file",capability:_n,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Gi,module:"file",capability:Gi,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Dn,module:"file",capability:Dn,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:$i,module:"file",capability:$i,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Nn,module:"file",capability:Nn,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:qi,module:"directory",capability:qi,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Mn,module:"directory",capability:Mn,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Qi,module:"directory",capability:Qi,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Yi,module:"directory",capability:Yi,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Sn,module:"media",capability:Sn,requirement:{kind:"all",permissions:["media"]},risk:"high"},{method:Wi,module:"ui",capability:Wi,requirement:{kind:"none"},risk:"low"},{method:Zi,module:"ui",capability:Zi,requirement:{kind:"none"},risk:"low"},{method:Ki,module:"ui",capability:Ki,requirement:{kind:"none"},risk:"low"},{method:Ji,module:"device",capability:Ji,requirement:{kind:"none"},risk:"low"},{method:Xi,module:"device",capability:Xi,requirement:{kind:"all",permissions:["clipboard"]},risk:"medium"},{method:eo,module:"device",capability:eo,requirement:{kind:"all",permissions:["appProtocol"]},risk:"high"},{method:to,module:"navigation",capability:to,requirement:{kind:"none"},risk:"medium"},{method:ro,module:"navigation",capability:ro,requirement:{kind:"none"},risk:"medium"},{method:no,module:"navigation",capability:no,requirement:{kind:"none"},risk:"medium"},{method:bt,module:"cloud",capability:bt,requirement:{kind:"all",permissions:["leaderboard"]},risk:"medium"},{method:at,module:"cloud",capability:at,requirement:{kind:"all",permissions:["leaderboard"]},risk:"low"},{method:xt,module:"cloud",capability:xt,requirement:{kind:"all",permissions:["leaderboard"]},risk:"medium"},{method:ir,module:"cloud",capability:ir,requirement:{kind:"all",permissions:["leaderboard"]},risk:"medium"},{method:wt,module:"cloud",capability:wt,requirement:{kind:"all",permissions:["leaderboard"]},risk:"low"},{method:vr,module:"cloud",capability:vr,requirement:{kind:"all",permissions:["cloud_storage"]},risk:"low"},{method:Or,module:"cloud",capability:Or,requirement:{kind:"all",permissions:["cloud_storage"]},risk:"medium"},{method:Rr,module:"cloud",capability:Rr,requirement:{kind:"all",permissions:["cloud_storage"]},risk:"medium"},{method:or,module:"cloud",capability:or,requirement:{kind:"all",permissions:["cloud_storage"]},risk:"low"},...[wo,Io,Ao,_o,Do,No,Mo,So,bo,To,vo,Oo].map(e=>({method:e,module:"companion",capability:e,requirement:{kind:"all",permissions:["companion"]},risk:"high"}))],$t="heybox:miniprogram",gl=2,pl="hb_mini_bridge_nonce",yl="sdk.handshake",Fn="runtime.location.probe",vm="sdk.location.report",Om="sdk.csp.violation",El="operation.progress",Rm="companion.session.output",km="companion.session.exit",Pm="companion.session.ownershipLost";function Cm(e){return!ut(e)||e.namespace!==$t||e.version!==1&&e.version!==2||!ke(e.nonce)?!1:e.type==="handshake"?ke(e.id)&&e.method===yl&&e.error===void 0&&Fm(e.payload):e.type==="request"?ke(e.id)&&ke(e.method)&&e.error===void 0:e.type==="response"?ke(e.id)&&(e.method===void 0||ke(e.method))&&(e.error===void 0||Vm(e.error)):e.type==="event"?!ke(e.method)||e.error!==void 0?!1:e.method===El?e.version===2&&ke(e.id)&&Hm(e.payload):e.id===void 0||ke(e.id):e.type==="cancel"?e.version===2&&ke(e.id)&&e.method===void 0&&e.payload===void 0&&e.error===void 0:!1}function Ba(e){return typeof e!="string"||!e||e.startsWith("/")||e.endsWith("/")||/[\\\u0000-\u001f\u007f]/.test(e)?!1:e.split("/").every(t=>!!t&&t!=="."&&t!=="..")}function wl(e){return ut(e)?e.kind==="sandbox"?rt(e,["kind"]):e.kind==="directory"&&ke(e.handleId)&&rt(e,["kind","handleId"]):!1}function er(e){return!ut(e)||e.kind!=="file"?!1:ke(e.handleId)?rt(e,["kind","handleId"]):wl(e.root)&&Ba(e.relativePath)&&rt(e,["kind","root","relativePath"])}function Il(e){return!ut(e)||e.kind!=="directory"?!1:ke(e.handleId)?rt(e,["kind","handleId"]):wl(e.root)&&(e.relativePath==="."||Ba(e.relativePath))&&rt(e,["kind","root","relativePath"])}function Lm(e){return ut(e)&&e.kind==="file"&&ke(e.name)&&Gm(e.mode)&&er(e.ref)&&rt(e,["kind","name","mode","ref"])}const Al=20,Mc=["type","mimeType","size","width","height","previewUrl","file"];function Um(e){return e===void 0?!0:!(!ut(e)||!rt(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&&(!$m(e.maxCount,1,Al)||e.source==="camera"&&e.maxCount!==1))}function _l(e){if(!ut(e)||e.type!=="image"&&e.type!=="video")return!1;const t=e.type==="video";return!rt(e,t?[...Mc,"durationMs"]:Mc)||!ke(e.mimeType)||!Ct(e.size)||!Sc(e.width)||!Sc(e.height)||!ke(e.previewUrl)||!zm(e.file)?!1:t?Ct(e.durationMs):!0}function xm(e){if(!Array.isArray(e)||e.length<1||e.length>Al)return!1;for(let t=0;t<e.length;t+=1)if(!Object.prototype.hasOwnProperty.call(e,t)||!_l(e[t]))return!1;return!0}function zm(e){return!Lm(e)||e.mode!=="read"?!1:e.ref.kind==="file"&&"handleId"in e.ref&&ke(e.ref.handleId)}function Dl(e){return e instanceof Uint8Array&&e.buffer instanceof ArrayBuffer}function jm(e){return!ut(e)||!Ct(e.loaded)||typeof e.lengthComputable!="boolean"||!rt(e,["loaded","total","lengthComputable"])?!1:e.lengthComputable?Ct(e.total)&&e.loaded<=e.total:e.total===void 0}function Bm(e){return ut(e)?e.phase==="downloading"?Ct(e.loaded)&&(e.total===void 0||Ct(e.total)&&e.loaded<=e.total)&&rt(e,["phase","loaded","total"]):e.phase!=="verifying"&&e.phase!=="extracting"?!1:Ct(e.processed)&&Ct(e.total)&&e.processed<=e.total&&rt(e,["phase","processed","total"]):!1}function Hm(e){return jm(e)||Bm(e)}function Fm(e){return ut(e)&&ke(e.href)&&typeof e.userAgent=="string"&&ke(e.sdkVersion)}function Vm(e){return ut(e)&&ke(e.code)&&typeof e.message=="string"}function Gm(e){return e==="read"||e==="readwrite"}function Ct(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function Sc(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>0}function $m(e,t,r){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=t&&e<=r}function ke(e){return typeof e=="string"&&e.length>0}function rt(e,t){const r=new Set(t);return Object.keys(e).every(n=>r.has(n))}function ut(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const Nl={ark:"明日方舟",black_myth_wukong:"黑神话悟空",task_bar_hero:"任务栏英雄",phantom_blade_zero:"影之刃零"},Ml=Object.keys(Nl),tr=[{key:"game.ark.profile",game:"ark",family:"profile",name:"明日方舟角色与养成资料",disclosureRevision:1,queries:{get:{schema:"ark.profile",version:1}},sync:!1,file:!1},{key:"game.ark.gacha",game:"ark",family:"gacha",name:"明日方舟抽卡记录与分析",disclosureRevision:1,queries:{get:{schema:"ark.gacha-analysis",version:1},list:{schema:"ark.gacha-record-page",version:1,page:{defaultSize:50,maxSize:100}}},sync:!1,file:!1},{key:"game.black_myth_wukong.save_analysis",game:"black_myth_wukong",family:"save_analysis",name:"黑神话悟空存档解析结果",disclosureRevision:1,queries:{get:{schema:"black_myth_wukong.save",version:1}},sync:!0,file:!1},{key:"game.black_myth_wukong.save_files",game:"black_myth_wukong",family:"save_files",name:"黑神话悟空云存档文件",disclosureRevision:1,queries:{list:{schema:"save-file-page",version:1}},sync:!0,file:!0},{key:"game.task_bar_hero.save_analysis",game:"task_bar_hero",family:"save_analysis",name:"任务栏英雄存档解析结果",disclosureRevision:1,queries:{get:{schema:"task_bar_hero.save",version:1}},sync:!0,file:!1},{key:"game.task_bar_hero.save_files",game:"task_bar_hero",family:"save_files",name:"任务栏英雄云存档文件",disclosureRevision:1,queries:{list:{schema:"save-file-page",version:1}},sync:!0,file:!0},{key:"game.phantom_blade_zero.save_analysis",game:"phantom_blade_zero",family:"save_analysis",name:"影之刃零存档解析结果",disclosureRevision:1,queries:{get:{schema:"phantom_blade_zero.save",version:1}},sync:!0,file:!1},{key:"game.phantom_blade_zero.save_files",game:"phantom_blade_zero",family:"save_files",name:"影之刃零云存档文件",disclosureRevision:1,queries:{list:{schema:"save-file-page",version:1}},sync:!0,file:!0}],Wt=tr.map(e=>e.key),qm=new Set(Wt),Qm=new Set(Ml);function Pt(e){return qm.has(e)}function bc(e){return Qm.has(e)}function Ha(e){const t=tr.find(i=>i.key===e);if(!t)return;const r=t.queries,n=Object.keys(r);return t.sync&&n.push("sync"),t.file&&n.push("file"),{key:t.key,game:t.game,name:t.name,family:t.family,disclosureRevision:t.disclosureRevision,queries:r,operations:n}}const Ym="同步时,原始存档将上传至小黑盒;向小程序提供原始文件仍需单独许可。",sr=["userInfo","steamLibrary","share","storage","cloud_storage","gameSaves","filesystem","media","clipboard","leaderboard","network","companion","appProtocol","workspaceCards","user_game_data"],Fa=[{key:"gameSaves",name:"游戏存档",description:"已废弃,将在 SDK 0.10.0 移除;新接入使用 user.games。",access:"declaration",risk:"high",config:{},methods:["gameSaves.list","gameSaves.sync","gameSaves.getFile","gameSaves.readParsedData"],conditions:["SDK < 0.10.0-0 保留兼容入口,保留原合同,不增加本版逐资源确认;需要有效 Steam 登录和宿主支持。"]},{key:"userInfo",name:"用户信息",description:"登录小程序并读取当前用户的授权信息。",access:"declaration",risk:"medium",config:{},methods:["auth.login","user.getInfo"],conditions:["继续执行黑盒登录、用户授权和可信手势规则。"]},{key:"steamLibrary",name:"Steam 游戏库",description:"读取当前用户授权的 Steam 游戏库。",access:"declaration",risk:"high",config:{},methods:["user.getSteamGameList"],conditions:["继续执行账号绑定和数据可用性规则。"]},{key:"share",name:"分享",description:"使用小程序分享、分享菜单和截图能力。",access:"declaration",risk:"medium",config:{},methods:["share.copyLink","share.showShareMenu","share.screenshot","share.screenshotLong"],conditions:["继续执行分享参数校验和 Host 支持检查。"]},{key:"storage",name:"键值存储",description:"读写按小程序隔离的简单键值数据。",access:"declaration",risk:"medium",config:{},methods:["storage.getStorage","storage.setStorage"],conditions:["仅用于简单键值存储,不包含文件系统。"]},{key:"cloud_storage",name:"云端存储",description:"读写按小程序和当前登录用户隔离的云端键值数据。",access:"declaration",risk:"medium",config:{},methods:["cloud.storage.getStorage","cloud.storage.setStorage","cloud.storage.removeItem","cloud.storage.getKeys"],conditions:["云端存储按登录用户隔离并受容量配额限制。"]},{key:"filesystem",name:"文件系统",description:"访问小程序沙盒文件和用户选择的外部文件。",access:"declaration",risk:"high",config:{},methods:["network.download","network.upload","files.pickFiles","files.pickDirectory","files.saveFile","file.create","file.remove","file.exists","file.readText","file.writeText","file.readBytes","file.writeBytes","file.stat","directory.create","directory.remove","directory.exists","directory.list"],conditions:["外部文件继续要求有效的用户选择、会话句柄和匹配的读写模式。"]},{key:"media",name:"媒体",description:"通过系统图库或相机选择图片、视频。",access:"declaration",risk:"high",config:{},methods:["media.pick"],conditions:["图库授权范围仅限本次用户选择的媒体,不包含任意文件或沙盒访问权;继续执行可信手势、Host 能力与会话资源规则。"]},{key:"clipboard",name:"剪贴板",description:"向系统剪贴板写入文本。",access:"declaration",risk:"medium",config:{},methods:["device.setClipboard"],conditions:["继续执行文本长度和 Host 支持限制。"]},{key:"leaderboard",name:"排行榜",description:"读写小程序云排行榜。",access:"declaration",risk:"medium",config:{},methods:["cloud.leaderboard.submit","cloud.leaderboard.getList","cloud.leaderboard.getCurrentUserEntry","cloud.leaderboard.deleteCurrentUserEntry","cloud.leaderboard.getInfo"],conditions:["排行榜必须已创建,用户和资源规则保持不变。"]},{key:"network",name:"网络",description:"通过 network 模块请求或下载外部资源。",access:"platform-approval",risk:"high",config:{useOfficialDomain:{type:"boolean",required:!1,default:!1,description:"是否申请访问小黑盒官方域名。"}},methods:["network.request","network.download","network.upload"],conditions:["声明后仍需平台批准,并继续执行网络安全策略。"]},{key:"companion",name:"桌面辅助应用",description:"下载、准备并运行随当前小程序版本发布的受管桌面程序。",access:"platform-approval",risk:"high",config:{},methods:["companion.getInfo","companion.getPreparationStatus","companion.prepare","companion.cancelPreparation","companion.getActiveSession","companion.launch","companion.session.write","companion.session.closeStdin","companion.session.terminate","companion.session.ackOutput","companion.openAttachment","companion.showNotification"],conditions:["声明后仍需平台批准,并继续执行可信用户手势、Host 能力和当前版本 Manifest 校验。"]},{key:"appProtocol",name:"应用协议执行",description:"执行任意小黑盒客户端协议。",access:"platform-approval",risk:"high",config:{},methods:["device.executeProtocol"],conditions:["最高危险权限:批准后该入口可执行任意协议,并绕过其他 SDK 能力权限及专用授权流程。"]},{key:"workspaceCards",name:"工作区卡片",description:"在已绑定游戏的桌面工作区展示受审核卡片。",access:"platform-approval",risk:"high",config:{},methods:["workspaceCards.requestRefresh"],conditions:["需平台批准、Host 支持与有效执行租约;不隐式授予网络或存储权限。"]},{key:"user_game_data",name:"游戏资料",description:"在精确资源声明范围内读取当前用户的游戏资料:明日方舟角色/养成与抽卡,以及黑神话悟空、任务栏英雄、影之刃零的云存档解析结果与文件。",access:"declaration",risk:"high",config:{resources:{type:"resource-map",required:!0,items:Wt,description:"精确资源声明对象;每项必须填写 1~30 个 Unicode 码点的 purpose,不接受通配符或未开放资源。"}},methods:ml,conditions:["逐项声明资源与用途,读取前需用户许可;未取得许可不查询个人来源。","文件与解析结果分别许可;本次许可仅当前实例有效,持久许可保存在本机。","同步会将原存档上传至小黑盒,向小程序交付原文件仍需 `save_files` 许可。","平台取数不授予小程序 `network` 权限;已交付的数据副本无法撤回。"]}];new Set(sr);const Wm=30;function Zm(e){if(typeof e!="string")throw new Error("purpose 必须是字符串");const t=e.trim(),r=Array.from(t);if(r.length<1||r.length>Wm)throw new Error("purpose 去除首尾空白后必须为 1~30 个 Unicode 码点");if(r.some(n=>{const i=n.codePointAt(0);return i>=55296&&i<=57343}))throw new Error("purpose 包含非法 Unicode 字符");return t}function bn(e){return Sl(e,!1)}function Km(e){return Sl(e,!0)}function Sl(e,t){if(!Tc(e))throw new Error("resources 必须是资源声明对象;每项资源必须填写 purpose");const r={};for(const n of Object.keys(e).sort()){const i=e[n];if(!Tc(i)||Object.keys(i).length!==1||!Object.prototype.hasOwnProperty.call(i,"purpose"))throw new Error(`resources.${n} 必须且只能包含 purpose`);let o;try{o=Zm(i.purpose)}catch(s){throw new Error(`resources.${n}: ${s.message}`)}if(!Pt(n)){if(t&&/^game\.[a-z0-9_]+\.[a-z0-9_.]+$/.test(n))continue;throw new Error(`resources 包含未开放资源:${n}`)}r[n]={purpose:o}}return r}function Jm(e){return Wt.filter(t=>Object.prototype.hasOwnProperty.call(e,t))}function Tc(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function bl(e,t,r,n){return JSON.stringify(["user-game-data-purpose-v1",e,t,r,n])}const Xm=new Set(sr);function eg(e){return Xm.has(e)}function qe(e){if(!Yr(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(!Yr(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),!!eg(o)){if(o==="network"){const s=n.config;if(!Yr(s)||typeof s.useOfficialDomain!="boolean")return{valid:!1,permissions:{}};r[o]={key:o,status:n.status,config:{useOfficialDomain:s.useOfficialDomain}};continue}if(o==="user_game_data"){const s=n.config;if(!Yr(s))return{valid:!1,permissions:{}};try{const a=Km(s.resources);r[o]={key:o,status:n.status,config:{resources:a}}}catch{return{valid:!1,permissions:{}}}continue}if(n.config!==null&&n.config!==void 0&&(!Yr(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 Yr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const oi=["network","companion","appProtocol"];function Tl(e){if(!Wr(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>oi.length)return{valid:!1};const t=[],r=new Set;for(const n of e.entries){if(!Wr(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(!Wr(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(!Wr(n.config,[]))return{valid:!1};t.push({key:"companion",status:"enabled",config:{}})}else if(n.key==="appProtocol"){if(!Wr(n.config,[]))return{valid:!1};t.push({key:"appProtocol",status:"enabled",config:{}})}else return{valid:!1}}return t.sort((n,i)=>oi.indexOf(n.key)-oi.indexOf(i.key)),{valid:!0,grant:{schema_version:1,revision:e.revision,entries:t}}}function tg(e){if(!Number.isSafeInteger(e.revision)||e.revision<0)throw new Error("本地调试权限 revision 必须是非负安全整数");const t=qe(e.runtimePermissions),r=new Set(e.eligiblePermissionKeys??["network","appProtocol"]),n=[];for(const i of oi)!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 Va(e){const t=qe(e.runtimePermissions),r=Tl(e.localDevGrant),n=t.valid?t.permissions:{};for(const s of sr)e.declaredPermissions[s]?.enabled!==!0?delete n[s]:Fa.some(a=>a.key===s&&a.access==="declaration")?n[s]={key:s,status:"enabled",config:rg(s,e.declaredPermissions)}: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=vl(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:sr.flatMap(s=>n[s]?[n[s]]:[])},temporaryPermissionKeys:i,grantValid:r.valid}}function rg(e,t){const r=Fa.find(i=>i.key===e);if(!r)return{};const n={};for(const[i,o]of Object.entries(r.config))o.type==="resource-map"&&(n[i]=i==="resources"?bn(t[e]?.resources):{});return n}function vl(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Wr(e,t){return vl(e)&&Object.keys(e).length===t.length&&t.every(r=>Object.prototype.hasOwnProperty.call(e,r))}const kr=["identity","profile","steam_account"],ng=/^[a-z][a-z0-9-]{0,31}$/,Ol=["COMPANION_UNSUPPORTED","COMPANION_PREVIEW_UNSUPPORTED","COMPANION_NOT_DECLARED","COMPANION_TARGET_UNSUPPORTED","COMPANION_NOT_PREPARED","COMPANION_PREPARATION_CANCELLED","COMPANION_DOWNLOAD_FAILED","COMPANION_DESCRIPTOR_UNAVAILABLE","COMPANION_ARCHIVE_INVALID","COMPANION_INTEGRITY_FAILED","COMPANION_ENTRYPOINT_INVALID","COMPANION_USER_CANCELLED","COMPANION_ELEVATION_DENIED","COMPANION_OS_BLOCKED","COMPANION_LAUNCH_FAILED","COMPANION_SESSION_VERSION_MISMATCH","COMPANION_SESSION_OWNERSHIP_LOST","COMPANION_SESSION_EXITED","COMPANION_PIPE_CLOSED","COMPANION_OUTPUT_LIMIT","COMPANION_PROCESS_CRASHED","COMPANION_ATTACHMENT_NOT_FOUND","COMPANION_NOTIFICATION_UNAVAILABLE","COMPANION_TERMINATE_FAILED"];var vc;function _e(e,t,r){function n(a,c){if(a._zod||Object.defineProperty(a,"_zod",{value:{def:c,constr:s,traits:new Set},enumerable:!1}),a._zod.traits.has(e))return;a._zod.traits.add(e),t(a,c);const d=s.prototype,u=Object.keys(d);for(let f=0;f<u.length;f++){const l=u[f];l in a||(a[l]=d[l].bind(a))}}const i=r?.Parent??Object;class o extends i{}Object.defineProperty(o,"name",{value:e});function s(a){var c;const d=r?.Parent?new o:this;n(d,a),(c=d._zod).deferred??(c.deferred=[]);for(const u of d._zod.deferred)u();return d}return Object.defineProperty(s,"init",{value:n}),Object.defineProperty(s,Symbol.hasInstance,{value:a=>r?.Parent&&a instanceof r.Parent?!0:a?._zod?.traits?.has(e)}),Object.defineProperty(s,"name",{value:e}),s}class ln extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}(vc=globalThis).__zod_globalConfig??(vc.__zod_globalConfig={});const Oc=globalThis.__zod_globalConfig;function Gr(e){return e&&Object.assign(Oc,e),Oc}function ig(e,t){return typeof t=="bigint"?t.toString():t}function og(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function Rl(e){const t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}const Rc=Symbol("evaluating");function Qe(e,t,r){let n;Object.defineProperty(e,t,{get(){if(n!==Rc)return n===void 0&&(n=Rc,n=r()),n},set(i){Object.defineProperty(e,t,{value:i})},configurable:!0})}const kl="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function sg(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function kc(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function ag(e,t,r){const n=new e._zod.constr(t??e._zod.def);return(!t||r?.parent)&&(n._zod.parent=e),n}function it(e){return{}}function cg(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}const dg={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function sn(e,t=0){if(e.aborted===!0)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue!==!0)return!0;return!1}function ug(e,t=0){if(e.aborted===!0)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue===!1)return!0;return!1}function Pl(e,t){return t.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(e),r})}function Vn(e){return typeof e=="string"?e:e?.message}function Cn(e,t,r){const n=e.message?e.message:Vn(e.inst?._zod.def?.error?.(e))??Vn(t?.error?.(e))??Vn(r.customError?.(e))??Vn(r.localeError?.(e))??"Invalid input",{inst:i,continue:o,input:s,...a}=e;return a.path??(a.path=[]),a.message=n,t?.reportInput&&(a.input=s),a}const Cl=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,ig,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},lg=_e("$ZodError",Cl),Ro=_e("$ZodError",Cl,{Parent:Error}),fg=e=>(t,r,n,i)=>{const o=n?{...n,async:!1}:{async:!1},s=t._zod.run({value:r,issues:[]},o);if(s instanceof Promise)throw new ln;if(s.issues.length){const a=new(i?.Err??e)(s.issues.map(c=>Cn(c,o,Gr())));throw kl(a,i?.callee),a}return s.value},hg=fg(Ro),mg=e=>async(t,r,n,i)=>{const o=n?{...n,async:!0}:{async:!0};let s=t._zod.run({value:r,issues:[]},o);if(s instanceof Promise&&(s=await s),s.issues.length){const a=new(i?.Err??e)(s.issues.map(c=>Cn(c,o,Gr())));throw kl(a,i?.callee),a}return s.value},gg=mg(Ro),pg=e=>(t,r,n)=>{const i=n?{...n,async:!1}:{async:!1},o=t._zod.run({value:r,issues:[]},i);if(o instanceof Promise)throw new ln;return o.issues.length?{success:!1,error:new(e??lg)(o.issues.map(s=>Cn(s,i,Gr())))}:{success:!0,data:o.value}},Ll=pg(Ro),yg=e=>async(t,r,n)=>{const i=n?{...n,async:!0}:{async:!0};let o=t._zod.run({value:r,issues:[]},i);return o instanceof Promise&&(o=await o),o.issues.length?{success:!1,error:new e(o.issues.map(s=>Cn(s,i,Gr())))}:{success:!0,data:o.value}},Ul=yg(Ro),Eg=e=>{const t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},wg=/^-?\d+$/,Ig=/^-?\d+(?:\.\d+)?$/,Ag=/^null$/i,ko=_e("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),xl={number:"number",bigint:"bigint",object:"date"},_g=_e("$ZodCheckLessThan",(e,t)=>{ko.init(e,t);const r=xl[typeof t.value];e._zod.onattach.push(n=>{const i=n._zod.bag,o=(t.inclusive?i.maximum:i.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<o&&(t.inclusive?i.maximum=t.value:i.exclusiveMaximum=t.value)}),e._zod.check=n=>{(t.inclusive?n.value<=t.value:n.value<t.value)||n.issues.push({origin:r,code:"too_big",maximum:typeof t.value=="object"?t.value.getTime():t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Dg=_e("$ZodCheckGreaterThan",(e,t)=>{ko.init(e,t);const r=xl[typeof t.value];e._zod.onattach.push(n=>{const i=n._zod.bag,o=(t.inclusive?i.minimum:i.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>o&&(t.inclusive?i.minimum=t.value:i.exclusiveMinimum=t.value)}),e._zod.check=n=>{(t.inclusive?n.value>=t.value:n.value>t.value)||n.issues.push({origin:r,code:"too_small",minimum:typeof t.value=="object"?t.value.getTime():t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Ng=_e("$ZodCheckNumberFormat",(e,t)=>{ko.init(e,t),t.format=t.format||"float64";const r=t.format?.includes("int"),n=r?"int":"number",[i,o]=dg[t.format];e._zod.onattach.push(s=>{const a=s._zod.bag;a.format=t.format,a.minimum=i,a.maximum=o,r&&(a.pattern=wg)}),e._zod.check=s=>{const a=s.value;if(r){if(!Number.isInteger(a)){s.issues.push({expected:n,format:t.format,code:"invalid_type",continue:!1,input:a,inst:e});return}if(!Number.isSafeInteger(a)){a>0?s.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,inclusive:!0,continue:!t.abort}):s.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,inclusive:!0,continue:!t.abort});return}}a<i&&s.issues.push({origin:"number",input:a,code:"too_small",minimum:i,inclusive:!0,inst:e,continue:!t.abort}),a>o&&s.issues.push({origin:"number",input:a,code:"too_big",maximum:o,inclusive:!0,inst:e,continue:!t.abort})}}),Mg=_e("$ZodCheckStringFormat",(e,t)=>{var r,n;ko.init(e,t),e._zod.onattach.push(i=>{const o=i._zod.bag;o.format=t.format,t.pattern&&(o.patterns??(o.patterns=new Set),o.patterns.add(t.pattern))}),t.pattern?(r=e._zod).check??(r.check=i=>{t.pattern.lastIndex=0,!t.pattern.test(i.value)&&i.issues.push({origin:"string",code:"invalid_format",format:t.format,input:i.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(n=e._zod).check??(n.check=()=>{})}),Sg=_e("$ZodCheckRegex",(e,t)=>{Mg.init(e,t),e._zod.check=r=>{t.pattern.lastIndex=0,!t.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),bg={major:4,minor:4,patch:3},lt=_e("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=bg;const n=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&n.unshift(e);for(const i of n)for(const o of i._zod.onattach)o(e);if(n.length===0)(r=e._zod).deferred??(r.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{const i=(s,a,c)=>{let d=sn(s),u;for(const f of a){if(f._zod.def.when){if(ug(s)||!f._zod.def.when(s))continue}else if(d)continue;const l=s.issues.length,h=f._zod.check(s);if(h instanceof Promise&&c?.async===!1)throw new ln;if(u||h instanceof Promise)u=(u??Promise.resolve()).then(async()=>{await h,s.issues.length!==l&&(d||(d=sn(s,l)))});else{if(s.issues.length===l)continue;d||(d=sn(s,l))}}return u?u.then(()=>s):s},o=(s,a,c)=>{if(sn(s))return s.aborted=!0,s;const d=i(a,n,c);if(d instanceof Promise){if(c.async===!1)throw new ln;return d.then(u=>e._zod.parse(u,c))}return e._zod.parse(d,c)};e._zod.run=(s,a)=>{if(a.skipChecks)return e._zod.parse(s,a);if(a.direction==="backward"){const d=e._zod.parse({value:s.value,issues:[]},{...a,skipChecks:!0});return d instanceof Promise?d.then(u=>o(u,s,a)):o(d,s,a)}const c=e._zod.parse(s,a);if(c instanceof Promise){if(a.async===!1)throw new ln;return c.then(d=>i(d,n,a))}return i(c,n,a)}}Qe(e,"~standard",()=>({validate:i=>{try{const o=Ll(e,i);return o.success?{value:o.data}:{issues:o.error?.issues}}catch{return Ul(e,i).then(s=>s.success?{value:s.data}:{issues:s.error?.issues})}},vendor:"zod",version:1}))}),Tg=_e("$ZodString",(e,t)=>{lt.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??Eg(e._zod.bag),e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=String(r.value)}catch{}return typeof r.value=="string"||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:e}),r}}),zl=_e("$ZodNumber",(e,t)=>{lt.init(e,t),e._zod.pattern=e._zod.bag.pattern??Ig,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=Number(r.value)}catch{}const i=r.value;if(typeof i=="number"&&!Number.isNaN(i)&&Number.isFinite(i))return r;const o=typeof i=="number"?Number.isNaN(i)?"NaN":Number.isFinite(i)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:i,inst:e,...o?{received:o}:{}}),r}}),vg=_e("$ZodNumberFormat",(e,t)=>{Ng.init(e,t),zl.init(e,t)}),Og=_e("$ZodNull",(e,t)=>{lt.init(e,t),e._zod.pattern=Ag,e._zod.values=new Set([null]),e._zod.parse=(r,n)=>{const i=r.value;return i===null||r.issues.push({expected:"null",code:"invalid_type",input:i,inst:e}),r}}),Rg=_e("$ZodNever",(e,t)=>{lt.init(e,t),e._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:e}),r)});function Pc(e,t,r){e.issues.length&&t.issues.push(...Pl(r,e.issues)),t.value[r]=e.value}const kg=_e("$ZodArray",(e,t)=>{lt.init(e,t),e._zod.parse=(r,n)=>{const i=r.value;if(!Array.isArray(i))return r.issues.push({expected:"array",code:"invalid_type",input:i,inst:e}),r;r.value=Array(i.length);const o=[];for(let s=0;s<i.length;s++){const a=i[s],c=t.element._zod.run({value:a,issues:[]},n);c instanceof Promise?o.push(c.then(d=>Pc(d,r,s))):Pc(c,r,s)}return o.length?Promise.all(o).then(()=>r):r}});function io(e,t,r,n,i,o){const s=r in n;if(e.issues.length){if(i&&o&&!s)return;t.issues.push(...Pl(r,e.issues))}if(!s&&!i){e.issues.length||t.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[r]});return}e.value===void 0?s&&(t.value[r]=void 0):t.value[r]=e.value}function Pg(e){const t=Object.keys(e.shape);for(const n of t)if(!e.shape?.[n]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${n}": expected a Zod schema`);const r=cg(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(r)}}function Cg(e,t,r,n,i,o){const s=[],a=i.keySet,c=i.catchall._zod,d=c.def.type,u=c.optin==="optional",f=c.optout==="optional";for(const l in t){if(l==="__proto__"||a.has(l))continue;if(d==="never"){s.push(l);continue}const h=c.run({value:t[l],issues:[]},n);h instanceof Promise?e.push(h.then(m=>io(m,r,l,t,u,f))):io(h,r,l,t,u,f)}return s.length&&r.issues.push({code:"unrecognized_keys",keys:s,input:t,inst:o}),e.length?Promise.all(e).then(()=>r):r}const Lg=_e("$ZodObject",(e,t)=>{if(lt.init(e,t),!Object.getOwnPropertyDescriptor(t,"shape")?.get){const a=t.shape;Object.defineProperty(t,"shape",{get:()=>{const c={...a};return Object.defineProperty(t,"shape",{value:c}),c}})}const n=og(()=>Pg(t));Qe(e._zod,"propValues",()=>{const a=t.shape,c={};for(const d in a){const u=a[d]._zod;if(u.values){c[d]??(c[d]=new Set);for(const f of u.values)c[d].add(f)}}return c});const i=sg,o=t.catchall;let s;e._zod.parse=(a,c)=>{s??(s=n.value);const d=a.value;if(!i(d))return a.issues.push({expected:"object",code:"invalid_type",input:d,inst:e}),a;a.value={};const u=[],f=s.shape;for(const l of s.keys){const h=f[l],m=h._zod.optin==="optional",E=h._zod.optout==="optional",_=h._zod.run({value:d[l],issues:[]},c);_ instanceof Promise?u.push(_.then(w=>io(w,a,l,d,m,E))):io(_,a,l,d,m,E)}return o?Cg(u,d,a,c,n.value,e):u.length?Promise.all(u).then(()=>a):a}});function Cc(e,t,r,n){for(const o of e)if(o.issues.length===0)return t.value=o.value,t;const i=e.filter(o=>!sn(o));return i.length===1?(t.value=i[0].value,i[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:e.map(o=>o.issues.map(s=>Cn(s,n,Gr())))}),t)}const Ug=_e("$ZodUnion",(e,t)=>{lt.init(e,t),Qe(e._zod,"optin",()=>t.options.some(n=>n._zod.optin==="optional")?"optional":void 0),Qe(e._zod,"optout",()=>t.options.some(n=>n._zod.optout==="optional")?"optional":void 0),Qe(e._zod,"values",()=>{if(t.options.every(n=>n._zod.values))return new Set(t.options.flatMap(n=>Array.from(n._zod.values)))}),Qe(e._zod,"pattern",()=>{if(t.options.every(n=>n._zod.pattern)){const n=t.options.map(i=>i._zod.pattern);return new RegExp(`^(${n.map(i=>Rl(i.source)).join("|")})$`)}});const r=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(n,i)=>{if(r)return r(n,i);let o=!1;const s=[];for(const a of t.options){const c=a._zod.run({value:n.value,issues:[]},i);if(c instanceof Promise)s.push(c),o=!0;else{if(c.issues.length===0)return c;s.push(c)}}return o?Promise.all(s).then(a=>Cc(a,n,e,i)):Cc(s,n,e,i)}}),xg=_e("$ZodLiteral",(e,t)=>{if(lt.init(e,t),t.values.length===0)throw new Error("Cannot create literal schema with no valid values");const r=new Set(t.values);e._zod.values=r,e._zod.pattern=new RegExp(`^(${t.values.map(n=>typeof n=="string"?kc(n):n?kc(n.toString()):String(n)).join("|")})$`),e._zod.parse=(n,i)=>{const o=n.value;return r.has(o)||n.issues.push({code:"invalid_value",values:t.values,input:o,inst:e}),n}});function Lc(e,t){return t===void 0&&(e.issues.length||e.fallback)?{issues:[],value:void 0}:e}const zg=_e("$ZodOptional",(e,t)=>{lt.init(e,t),e._zod.optin="optional",e._zod.optout="optional",Qe(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),Qe(e._zod,"pattern",()=>{const r=t.innerType._zod.pattern;return r?new RegExp(`^(${Rl(r.source)})?$`):void 0}),e._zod.parse=(r,n)=>{if(t.innerType._zod.optin==="optional"){const i=r.value,o=t.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>Lc(s,i)):Lc(o,i)}return r.value===void 0?r:t.innerType._zod.run(r,n)}}),jg=_e("$ZodLazy",(e,t)=>{lt.init(e,t),Qe(e._zod,"innerType",()=>{const r=t;return r._cachedInner||(r._cachedInner=t.getter()),r._cachedInner}),Qe(e._zod,"pattern",()=>e._zod.innerType?._zod?.pattern),Qe(e._zod,"propValues",()=>e._zod.innerType?._zod?.propValues),Qe(e._zod,"optin",()=>e._zod.innerType?._zod?.optin??void 0),Qe(e._zod,"optout",()=>e._zod.innerType?._zod?.optout??void 0),e._zod.parse=(r,n)=>e._zod.innerType._zod.run(r,n)});function Bg(e,t){return new e({type:"string",...it()})}function Hg(e,t){return new e({type:"number",checks:[],...it()})}function Fg(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...it()})}function Vg(e,t){return new e({type:"null",...it()})}function Gg(e,t){return new e({type:"never",...it()})}function se(e,t){return new _g({check:"less_than",...it(),value:e,inclusive:!0})}function ae(e,t){return new Dg({check:"greater_than",...it(),value:e,inclusive:!0})}function ce(e,t){return new Sg({check:"string_format",format:"regex",...it(),pattern:e})}Gr({jitless:!0});function jl(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 sr){const n=e.declared_permissions[r];if(n){if(typeof n.enabled!="boolean")throw new Error("开发权限声明无效");if(r==="network"){t[r]={enabled:n.enabled,useOfficialDomain:n.useOfficialDomain===!0};continue}if(r==="user_game_data"){t[r]={enabled:n.enabled,resources:bn(n.resources)};continue}t[r]={enabled:n.enabled}}}if(Object.keys(e.declared_permissions).some(r=>!sr.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 $g(e){if(!(typeof e!="string"||e.length>16384))try{const t=JSON.parse(e);return jl(t)===e?t:void 0}catch{return}}const Dt=_e("ZodMiniType",(e,t)=>{if(!e._zod)throw new Error("Uninitialized schema in ZodMiniType.");lt.init(e,t),e.def=t,e.type=t.type,e.parse=(r,n)=>hg(e,r,n,{callee:e.parse}),e.safeParse=(r,n)=>Ll(e,r,n),e.parseAsync=async(r,n)=>gg(e,r,n,{callee:e.parseAsync}),e.safeParseAsync=async(r,n)=>Ul(e,r,n),e.check=(...r)=>e.clone({...t,checks:[...t.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]},{parent:!0}),e.with=e.check,e.clone=(r,n)=>ag(e,r,n),e.brand=()=>e,e.register=((r,n)=>(r.add(e,n),e)),e.apply=r=>r(e)}),qg=_e("ZodMiniString",(e,t)=>{Tg.init(e,t),Dt.init(e,t)});function k(e){return Bg(qg)}const Bl=_e("ZodMiniNumber",(e,t)=>{zl.init(e,t),Dt.init(e,t)});function V(e){return Hg(Bl)}const Qg=_e("ZodMiniNumberFormat",(e,t)=>{vg.init(e,t),Bl.init(e,t)});function de(e){return Fg(Qg)}const Yg=_e("ZodMiniNull",(e,t)=>{Og.init(e,t),Dt.init(e,t)});function te(e){return Vg(Yg)}const Wg=_e("ZodMiniNever",(e,t)=>{Rg.init(e,t),Dt.init(e,t)});function Zg(e){return Gg(Wg)}const Kg=_e("ZodMiniArray",(e,t)=>{kg.init(e,t),Dt.init(e,t)});function J(e,t){return new Kg({type:"array",element:e,...it()})}const Jg=_e("ZodMiniObject",(e,t)=>{Lg.init(e,t),Dt.init(e,t),Qe(e,"shape",()=>t.shape)});function oe(e,t){return new Jg({type:"object",shape:e,catchall:Zg(),...it()})}const Xg=_e("ZodMiniUnion",(e,t)=>{Ug.init(e,t),Dt.init(e,t)});function R(e,t){return new Xg({type:"union",options:e,...it()})}const ep=_e("ZodMiniLiteral",(e,t)=>{xg.init(e,t),Dt.init(e,t)});function le(e,t){return new ep({type:"literal",values:Array.isArray(e)?e:[e],...it()})}const tp=_e("ZodMiniOptional",(e,t)=>{zg.init(e,t),Dt.init(e,t)});function G(e){return new tp({type:"optional",innerType:e})}const rp=_e("ZodMiniLazy",(e,t)=>{jg.init(e,t),Dt.init(e,t)});function Y(e){return new rp({type:"lazy",getter:e})}const W={ArkProfile:oe({uid:k(),name:k(),level:V(),avatar:G(Y(()=>W.ArkPlayerAvatar)),characterCount:V(),totalCharacterCount:V(),mainStageProgress:k(),rogueLevel:V(),campaignFullKillCount:V(),tag:k(),observedAt:G(R([k(),V()])),lastOnlineTs:G(R([k(),V()])),registerTs:G(R([k(),V()])),changeTime:G(R([k(),V()])),operators:G(J(Y(()=>W.ArkOperator)))}),ArkPlayerAvatar:oe({url:k(),type:k(),id:k()}),ArkOperator:oe({characterId:k(),name:k(),profession:k(),evolvePhase:V(),potentialRank:V()}),ArkGachaAnalysis:oe({uid:k(),year:V(),total:V(),srCount:V(),upCount:V(),missCount:V(),careerEvaluation:k(),careerIsLucky:R([le(!1),le(!0)]),pools:J(Y(()=>W.ArkGachaPoolStat)),records:J(Y(()=>W.ArkGachaAnalysisRecord)),luckyLottery:J(V())}),ArkGachaPoolStat:oe({poolId:k(),totalCost:V(),ssrCount:V(),ssrCost:V(),records:J(Y(()=>W.ArkGachaAnalysisRecord))}),ArkGachaAnalysisRecord:oe({name:k(),timestamp:R([de().check(ae(-9007199254740991),se(9007199254740991)),k().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),diff:V(),negativeDiff:V(),tag:k(),missUp:R([le(!1),le(!0)])}),GachaRecord:oe({id:k(),name:k(),pool:k(),rarity:V(),timestamp:R([de().check(ae(-9007199254740991),se(9007199254740991)),k().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))])}),BlackMythWukongSave:oe({level:G(V()),newGamePlusCount:G(V()),gameTotalTime:G(V()),playerDeathCount:G(V()),totalMoney:G(k()),meditationList:G(R([te(),J(V())])),monsterCollectionList:G(R([te(),J(V())])),returnPointList:G(R([te(),J(V())])),activatedWeaponIdList:G(R([te(),J(k())])),activatedEquipIdList:G(R([te(),J(V())])),magicArtifactList:G(R([te(),J(V())])),soulSkillIdList:G(R([te(),J(V())])),huluIdLits:G(R([te(),J(V())])),wineIdList:G(R([te(),J(V())])),wineIdPartnerList:G(R([te(),J(V())])),cropIdList:G(R([te(),J(V())])),recipeIdList:G(R([te(),J(V())])),wearedWaeponId:G(k()),wearedMagicArtifact:G(V()),wearedSoulSkill:G(V()),wearedHead:G(V()),wearedUpware:G(V()),wearedArm:G(V()),wearedFoot:G(V()),wearedHulu:G(V()),wearedAccessoryList:G(R([te(),J(V())])),spellQishu:G(R([te(),J(V())])),spellShenfa:G(R([te(),J(V())])),spellHaomao:G(R([te(),J(V())])),spellBianshen:G(R([te(),J(V())])),bossRushBossgroup:G(Y(()=>W.BlackMythWukongBossRushData)),bossRushRefight:G(Y(()=>W.BlackMythWukongBossRefightData))}),BlackMythWukongBossRushData:oe({bossGroups:G(R([te(),J(Y(()=>W.BlackMythWukongBossRushRecord))]))}),BlackMythWukongBossRushRecord:oe({bossGroupId:G(V()),isPassed:G(R([le(!1),le(!0)])),bestRecords:G(R([te(),J(Y(()=>W.BlackMythWukongBattleRecord))])),encounterBossIndex:G(V()),battleCount:G(V())}),BlackMythWukongBattleRecord:oe({battleId:G(k()),battleData:G(Y(()=>W.BlackMythWukongBattleData))}),BlackMythWukongBattleData:oe({totalTime:G(V()),score:G(V()),debuffList:G(R([te(),J(V())])),targetId:G(V()),archiveTime:G(k()),roleBase:G(Y(()=>W.BlackMythWukongRoleBase)),battleStyleInfo:G(Y(()=>W.BlackMythWukongBattleStyleInfo)),damageInfo:G(Y(()=>W.BlackMythWukongDamageInfo))}),BlackMythWukongRoleBase:oe({level:G(V()),atk:G(V()),hpMax:G(V()),staminaMax:G(V()),mpMax:G(V())}),BlackMythWukongBattleStyleInfo:oe({spellList:G(R([te(),J(Y(()=>W.BlackMythWukongCast))])),fabaoInfo:G(Y(()=>W.BlackMythWukongCast)),soulInfo:G(Y(()=>W.BlackMythWukongCast)),itemCount:G(V()),wineCount:G(V()),rollCount:G(V()),defuseCount:G(V()),fourPeCount:G(V())}),BlackMythWukongCast:oe({castId:G(V()),castCount:G(V())}),BlackMythWukongDamageInfo:oe({totalDamage:G(R([k(),V()])),hightestDamage:G(R([k(),V()])),criticalDmgRate:G(V()),totalBeDamaged:G(R([k(),V()])),criticalDmgTotal:G(R([k(),V()])),elemDotDmgTotal:G(R([k(),V()])),elemDotDmgRate:G(V())}),BlackMythWukongBossRefightData:oe({bossList:G(R([te(),J(Y(()=>W.BlackMythWukongBossRefightRecord))]))}),BlackMythWukongBossRefightRecord:oe({bossId:G(V()),passedMaxLevel:G(V()),lastChallengeLevel:G(V()),bestRecords:G(R([te(),J(Y(()=>W.BlackMythWukongBattleRecord))])),refightStatisticsList:G(R([te(),J(Y(()=>W.BlackMythWukongRefightStatistic))]))}),BlackMythWukongRefightStatistic:oe({challengeLevel:G(V()),battleCount:G(V())}),TaskBarHeroSave:oe({update_time:R([de().check(ae(-9007199254740991),se(9007199254740991)),k().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),game_version:k(),account_version:k(),play_time:V(),last_saved_time:k(),common:Y(()=>W.TaskBarHeroCommon),summary:Y(()=>W.TaskBarHeroSummary),heroes:R([te(),J(Y(()=>W.TaskBarHeroHero))]),rune_save_data:R([te(),J(Y(()=>W.TaskBarHeroRune))]),pets:R([te(),J(Y(()=>W.TaskBarHeroPet))]),attributes:R([te(),J(Y(()=>W.TaskBarHeroAttribute))]),inventory_slots:R([te(),J(Y(()=>W.TaskBarHeroItemSlot))]),stash_slots:R([te(),J(Y(()=>W.TaskBarHeroItemSlot))]),item_instances:R([te(),J(Y(()=>W.TaskBarHeroItemInstance))]),values:Y(()=>W.TaskBarHeroValueSummary)}),TaskBarHeroCommon:oe({max_completed_stage:R([de().check(ae(-9007199254740991),se(9007199254740991)),k().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),current_stage_key:R([de().check(ae(-9007199254740991),se(9007199254740991)),k().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),current_stage_wave:R([de().check(ae(-9007199254740991),se(9007199254740991)),k().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),arranged_hero_keys:R([te(),J(R([de().check(ae(-9007199254740991),se(9007199254740991)),k().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]))]),arranged_pet_key:R([de().check(ae(-9007199254740991),se(9007199254740991)),k().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))])}),TaskBarHeroSummary:oe({max_hero_level:R([de().check(ae(-9007199254740991),se(9007199254740991)),k().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),learned_rune_count:R([de().check(ae(-9007199254740991),se(9007199254740991)),k().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),unlocked_hero:R([de().check(ae(-9007199254740991),se(9007199254740991)),k().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),total_hero:R([de().check(ae(-9007199254740991),se(9007199254740991)),k().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),item_count:R([de().check(ae(-9007199254740991),se(9007199254740991)),k().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),inventory_slots:R([de().check(ae(-9007199254740991),se(9007199254740991)),k().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),stash_slots:R([de().check(ae(-9007199254740991),se(9007199254740991)),k().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))])}),TaskBarHeroHero:oe({hero_key:R([de().check(ae(-9007199254740991),se(9007199254740991)),k().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),hero_level:R([de().check(ae(-9007199254740991),se(9007199254740991)),k().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),is_unlock:R([le(!1),le(!0)]),hero_exp:V(),ability_point:R([de().check(ae(-9007199254740991),se(9007199254740991)),k().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),allocated_hero_ability_point:R([de().check(ae(-9007199254740991),se(9007199254740991)),k().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),equipped_item_ids:R([te(),J(k())]),equipped_skill_keys:R([te(),J(R([de().check(ae(-9007199254740991),se(9007199254740991)),k().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]))]),unlocked_attribute_group_keys:R([te(),J(R([de().check(ae(-9007199254740991),se(9007199254740991)),k().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]))])}),TaskBarHeroRune:oe({rune_key:R([de().check(ae(-9007199254740991),se(9007199254740991)),k().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),level:R([de().check(ae(-9007199254740991),se(9007199254740991)),k().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))])}),TaskBarHeroPet:oe({pet_key:R([de().check(ae(-9007199254740991),se(9007199254740991)),k().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),is_unlock:R([le(!1),le(!0)])}),TaskBarHeroAttribute:oe({key:R([de().check(ae(-9007199254740991),se(9007199254740991)),k().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),level:R([de().check(ae(-9007199254740991),se(9007199254740991)),k().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))])}),TaskBarHeroItemSlot:oe({index:R([de().check(ae(-9007199254740991),se(9007199254740991)),k().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),item_unique_id:k(),is_unlock:R([le(!1),le(!0)]),is_unlocked_by_rune:R([le(!1),le(!0)])}),TaskBarHeroItemInstance:oe({item_key:R([de().check(ae(-9007199254740991),se(9007199254740991)),k().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),unique_id:k(),is_chaotic:R([le(!1),le(!0)]),is_blocked:R([le(!1),le(!0)]),is_server_pending_item:R([le(!1),le(!0)]),enchant_count:R([te(),J(R([de().check(ae(-9007199254740991),se(9007199254740991)),k().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]))]),enchant_data:R([te(),J(Y(()=>W.TaskBarHeroEnchantData))]),item_get_source_type:R([de().check(ae(-9007199254740991),se(9007199254740991)),k().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),decoration_applied_total_count:R([de().check(ae(-9007199254740991),se(9007199254740991)),k().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),engraving_applied_total_count:R([de().check(ae(-9007199254740991),se(9007199254740991)),k().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),inscription_applied_total_count:R([de().check(ae(-9007199254740991),se(9007199254740991)),k().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))])}),TaskBarHeroEnchantData:oe({stat_mod_key:R([de().check(ae(-9007199254740991),se(9007199254740991)),k().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),tier:R([de().check(ae(-9007199254740991),se(9007199254740991)),k().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),value:V(),recipe_type:R([de().check(ae(-9007199254740991),se(9007199254740991)),k().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),mod_type:R([de().check(ae(-9007199254740991),se(9007199254740991)),k().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),material_key:R([de().check(ae(-9007199254740991),se(9007199254740991)),k().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),stat_type:R([de().check(ae(-9007199254740991),se(9007199254740991)),k().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))])}),TaskBarHeroValueSummary:oe({market_value:R([de().check(ae(-9007199254740991),se(9007199254740991)),k().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),price_state:k(),currency:k()}),PhantomBladeZeroSave:oe({defaultSlot:k(),slots:J(Y(()=>W.PhantomBladeZeroSaveSlot))}),PhantomBladeZeroSaveSlot:oe({slot:k(),head:Y(()=>W.PhantomBladeZeroSlotHead),firstClear:Y(()=>W.PhantomBladeZeroSlotFirstClear),progress:Y(()=>W.PhantomBladeZeroSlotProgress),combat:Y(()=>W.PhantomBladeZeroSlotCombat),achievements:Y(()=>W.PhantomBladeZeroSlotAchievementSummary),bosses:Y(()=>W.PhantomBladeZeroSlotBossSummary),collectibles:Y(()=>W.PhantomBladeZeroSlotCollectibles),quest_details:R([te(),Y(()=>W.PhantomBladeZeroQuestDetails)]),inventory_details:R([te(),J(Y(()=>W.PhantomBladeZeroInventoryItem))]),detail:Y(()=>W.PhantomBladeZeroSlotDetail)}),PhantomBladeZeroSlotHead:oe({saveTime:k(),currentLevel:k(),cycle:k(),difficulty:Y(()=>W.PhantomBladeZeroSlotDifficulty)}),PhantomBladeZeroSlotDifficulty:oe({raw:V(),name:k()}),PhantomBladeZeroSlotFirstClear:oe({clearDate:Y(()=>W.PhantomBladeZeroUnavailableValue),cycles:R([te(),J(Y(()=>W.PhantomBladeZeroClearanceRecord))])}),PhantomBladeZeroUnavailableValue:oe({value:te(),reason:k()}),PhantomBladeZeroClearanceRecord:oe({Cycle:G(R([te(),V()])),Ending:V(),Difficulty:V(),GameTime:R([de().check(ae(-9007199254740991),se(9007199254740991)),k().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),Completion:V(),DiedTimes:R([de().check(ae(-9007199254740991),se(9007199254740991)),k().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))])}),PhantomBladeZeroSlotProgress:oe({playTimeSeconds:R([de().check(ae(-9007199254740991),se(9007199254740991)),k().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),playTime:k(),lastLaunch:Y(()=>W.PhantomBladeZeroUnavailableValue),narrativePercentage:V(),chapter:k(),remainingDays:R([de().check(ae(-9007199254740991),se(9007199254740991)),k().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))])}),PhantomBladeZeroSlotCombat:oe({loadout:G(Y(()=>W.PhantomBladeZeroSlotLoadout)),totalDeaths:R([de().check(ae(-9007199254740991),se(9007199254740991)),k().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),cycleDeaths:R([de().check(ae(-9007199254740991),se(9007199254740991)),k().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),bossKillTotal:R([de().check(ae(-9007199254740991),se(9007199254740991)),k().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),currentMainWeapon:G(R([te(),Y(()=>W.PhantomBladeZeroNamedItem)])),mainWeapon:Y(()=>W.PhantomBladeZeroCollectionCount),currentShaqi:G(R([te(),Y(()=>W.PhantomBladeZeroNamedItem)])),shaqi:Y(()=>W.PhantomBladeZeroCollectionCount)}),PhantomBladeZeroSlotLoadout:oe({states:G(R([te(),J(Y(()=>W.PhantomBladeZeroLoadoutState))])),main_weapons:R([te(),J(k())]),shaqi_weapons:R([te(),J(k())]),accessory_ids:R([te(),J(k())]),top_medicine:k(),bottom_medicine:k(),current_weapon_index:V(),current_shaqi_weapon_index:V()}),PhantomBladeZeroLoadoutState:oe({category:k(),id:k(),level:G(V()),soul_forged:G(R([le(!1),le(!0)])),reincarnation_count:G(V())}),PhantomBladeZeroNamedItem:oe({id:k(),name:k()}),PhantomBladeZeroCollectionCount:oe({unknown:G(R([k(),V()])),done:R([de().check(ae(-9007199254740991),se(9007199254740991)),k().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),total:R([de().check(ae(-9007199254740991),se(9007199254740991)),k().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))])}),PhantomBladeZeroSlotAchievementSummary:oe({unlocked:R([de().check(ae(-9007199254740991),se(9007199254740991)),k().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),total:R([de().check(ae(-9007199254740991),se(9007199254740991)),k().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),reason:k()}),PhantomBladeZeroSlotBossSummary:oe({groups:R([te(),J(Y(()=>W.PhantomBladeZeroBossGroup))])}),PhantomBladeZeroBossGroup:oe({map:k(),mapName:k(),count:R([de().check(ae(-9007199254740991),se(9007199254740991)),k().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),bosses:R([te(),J(Y(()=>W.PhantomBladeZeroBoss))])}),PhantomBladeZeroBoss:oe({id:k(),classPath:k(),map:k(),mapName:k(),encountered:R([le(!1),le(!0)]),killed:R([le(!1),le(!0)]),kill:R([de().check(ae(-9007199254740991),se(9007199254740991)),k().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),attempt:R([de().check(ae(-9007199254740991),se(9007199254740991)),k().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),bestTimeMs:R([de().check(ae(-9007199254740991),se(9007199254740991)),k().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),records:R([te(),J(Y(()=>W.PhantomBladeZeroBossRecord))])}),PhantomBladeZeroBossRecord:oe({cycle:k(),diff:k(),diffName:k(),kill:R([de().check(ae(-9007199254740991),se(9007199254740991)),k().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),attempt:R([de().check(ae(-9007199254740991),se(9007199254740991)),k().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),bestTimeMs:R([de().check(ae(-9007199254740991),se(9007199254740991)),k().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))])}),PhantomBladeZeroSlotCollectibles:oe({overall:Y(()=>W.PhantomBladeZeroCollectionSummary),craneBellCount:R([de().check(ae(-9007199254740991),se(9007199254740991)),k().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),byBigMap:R([te(),J(Y(()=>W.PhantomBladeZeroBigMapProgress))]),currentChapter:Y(()=>W.PhantomBladeZeroChapterProgress)}),PhantomBladeZeroCollectionSummary:oe({bell:Y(()=>W.PhantomBladeZeroCollectionCount),weapon:Y(()=>W.PhantomBladeZeroCollectionCount),shaqi:Y(()=>W.PhantomBladeZeroCollectionCount),accessory:Y(()=>W.PhantomBladeZeroCollectionCount),medicine:Y(()=>W.PhantomBladeZeroCollectionCount),challenge:Y(()=>W.PhantomBladeZeroCollectionCount),hupo:Y(()=>W.PhantomBladeZeroCollectionCount),heishi:Y(()=>W.PhantomBladeZeroCollectionCount),flower:Y(()=>W.PhantomBladeZeroCollectionCount)}),PhantomBladeZeroBigMapProgress:oe({unknown:G(R([k(),V()])),mapID:k(),name:k(),pct:V(),done:R([de().check(ae(-9007199254740991),se(9007199254740991)),k().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),total:R([de().check(ae(-9007199254740991),se(9007199254740991)),k().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),subMaps:R([te(),J(k())])}),PhantomBladeZeroChapterProgress:oe({unknown:G(R([k(),V()])),mapID:k(),pct:V(),done:R([de().check(ae(-9007199254740991),se(9007199254740991)),k().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),total:R([de().check(ae(-9007199254740991),se(9007199254740991)),k().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),reason:k()}),PhantomBladeZeroQuestDetails:oe({CurrentMainQuestPath:k(),CurrentTutorialQuestPath:k(),TrackedQuestPath:k(),TrackedBranchID:k(),TrackedTaskPointID:k(),ManualTrackingOptOut:R([le(!1),le(!0)]),NarrativeSavedQuests:R([te(),J(Y(()=>W.PhantomBladeZeroQuest))])}),PhantomBladeZeroQuest:oe({QuestClass:k(),QuestCompletion:k(),QuestBranches:R([te(),J(Y(()=>W.PhantomBladeZeroQuestBranch))]),CompletedBranches:R([te(),J(k())]),ReachedStateNames:R([te(),J(k())])}),PhantomBladeZeroQuestBranch:oe({BranchID:k(),TasksProgress:R([te(),J(R([de().check(ae(-9007199254740991),se(9007199254740991)),k().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]))]),BranchType:k()}),PhantomBladeZeroInventoryItem:oe({id:k(),amount:R([de().check(ae(-9007199254740991),se(9007199254740991)),k().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))])}),PhantomBladeZeroSlotDetail:oe({bell:R([te(),J(Y(()=>W.PhantomBladeZeroBellDetail))]),weapon:R([te(),J(Y(()=>W.PhantomBladeZeroItemDetail))]),shaqi:R([te(),J(Y(()=>W.PhantomBladeZeroItemDetail))]),accessory:R([te(),J(Y(()=>W.PhantomBladeZeroItemDetail))]),medicine:R([te(),J(Y(()=>W.PhantomBladeZeroItemDetail))]),challenge:R([te(),J(Y(()=>W.PhantomBladeZeroChallengeDetail))]),hupo:R([te(),J(Y(()=>W.PhantomBladeZeroWorldItemDetail))]),heishi:R([te(),J(Y(()=>W.PhantomBladeZeroWorldItemDetail))]),flower:R([te(),J(Y(()=>W.PhantomBladeZeroItemDetail))]),achievements:R([te(),J(Y(()=>W.PhantomBladeZeroAchievementDetail))])}),PhantomBladeZeroBellDetail:oe({unknown:G(R([le(!1),le(!0)])),id:k(),done:R([le(!1),le(!0)]),equip:R([le(!1),le(!0)])}),PhantomBladeZeroItemDetail:oe({level:G(V()),soul_forged:G(R([le(!1),le(!0)])),reincarnation_count:G(V()),unknown:G(R([le(!1),le(!0)])),id:k(),name:k(),done:R([le(!1),le(!0)]),equip:R([le(!1),le(!0)]),locs:R([te(),J(Y(()=>W.PhantomBladeZeroLocation))])}),PhantomBladeZeroLocation:oe({map:k(),mapName:k(),x:V(),y:V(),z:V()}),PhantomBladeZeroChallengeDetail:oe({key:G(k()),unknown:G(R([le(!1),le(!0)])),index:R([de().check(ae(-9007199254740991),se(9007199254740991)),k().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),guids:R([te(),J(k())]),done:R([le(!1),le(!0)]),locs:R([te(),J(Y(()=>W.PhantomBladeZeroLocation))])}),PhantomBladeZeroWorldItemDetail:oe({key:G(k()),unknown:G(R([le(!1),le(!0)])),id:k(),saveGuid:k(),mobDomain:k(),done:R([le(!1),le(!0)]),locs:R([te(),J(Y(()=>W.PhantomBladeZeroLocation))])}),PhantomBladeZeroAchievementDetail:oe({id:k(),name:k(),desc:k(),grade:k(),hidden:R([le(!1),le(!0)]),done:R([le(!1),le(!0)])}),UserGameDataSaveFilePage:oe({items:J(Y(()=>W.UserGameDataSaveInfo)),hasMore:le(!1)}),UserGameDataSaveInfo:oe({saveId:k(),createdAt:k(),files:J(Y(()=>W.UserGameDataSaveFileInfo))}),UserGameDataSaveFileInfo:oe({fileId:k(),name:k(),sizeBytes:V(),modifiedAt:k()})},np=new Map([["ark.profile",Y(()=>W.ArkProfile)],["ark.gacha-analysis",Y(()=>W.ArkGachaAnalysis)],["ark.gacha-record-page",oe({items:J(Y(()=>W.GachaRecord)),nextCursor:G(k()),hasMore:R([le(!1),le(!0)]),total:G(V())})],["black_myth_wukong.save",Y(()=>W.BlackMythWukongSave)],["task_bar_hero.save",Y(()=>W.TaskBarHeroSave)],["phantom_blade_zero.save",Y(()=>W.PhantomBladeZeroSave)],["save-file-page",Y(()=>W.UserGameDataSaveFilePage)]]);function ip(e,t){return np.get(e)?.safeParse(t).success??!1}zt.map(e=>e.method);function si(){const e=new Error("The operation was aborted");return e.name="AbortError",e}function pe(e,t={}){if(e.aborted)throw t.preserveReason?e.reason===void 0?new DOMException("存储操作已取消","AbortError"):e.reason:si()}function Hl(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 Fl="METHOD_FORBIDDEN";function tt(e){const t=new Error(`小程序能力已禁用: ${e}`);return t.name="MethodForbiddenError",t.code=Fl,t}class Le 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 op=/^[A-Za-z0-9_-]{1,64}$/,Uc=1e3;function Vl(e){return op.test(e)?e:dp(e)}function sp(e){return`id_${Vl(e.trim())}`}function fr(e,t){return`hb_miniprogram_${e}_${t}`}function Gn(e){return`hb_miniprogram_keys_${e}`}const ap="hb_user_game_data_consent_";function cp(e){return`${ap}${e}`}function dp(e){let t=2166136261;for(let r=0;r<e.length;r+=1)t^=e.charCodeAt(r),t=Math.imul(t,16777619);return(t>>>0).toString(36)}const up=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 Ga(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 _=0;_<16;_+=1)o[_]=s.getUint32(a+_*4,!1);for(let _=16;_<64;_+=1){const w=o[_-15],S=o[_-2],p=ft(w,7)^ft(w,18)^w>>>3,M=ft(S,17)^ft(S,19)^S>>>10;o[_]=o[_-16]+p+o[_-7]+M>>>0}let[c,d,u,f,l,h,m,E]=i;for(let _=0;_<64;_+=1){const w=E+(ft(l,6)^ft(l,11)^ft(l,25))+(l&h^~l&m)+up[_]+o[_]>>>0,S=(ft(c,2)^ft(c,13)^ft(c,22))+(c&d^c&u^d&u);E=m,m=h,h=l,l=f+w>>>0,f=u,u=d,d=c,c=w+S>>>0}[c,d,u,f,l,h,m,E].forEach((_,w)=>{i[w]=i[w]+_>>>0})}return Array.from(i,a=>a.toString(16).padStart(8,"0")).join("")}function ft(e,t){return e>>>t|e<<32-t}const lp=Object.freeze({upload:"你允许读取的数据可能会被上传至开发者服务器。",no_network:"此小程序未获准将你允许读取的数据上传至开发者服务器。"});function fp(e){if(e===void 0||e==="")return;let t;try{t=JSON.parse(e)}catch{return}if(typeof t!="object"||t===null||Array.isArray(t))return;const r=t;if(r.schema_version!==1||typeof r.records!="object"||r.records===null||Array.isArray(r.records))return;const n={};for(const[i,o]of Object.entries(r.records)){if(typeof o!="object"||o===null||Array.isArray(o))return;const s=o;if(s.decision!=="ask"&&s.decision!=="allow"&&s.decision!=="deny"||typeof s.revision!="number"||!Number.isSafeInteger(s.revision)||s.revision<1||s.consentFingerprint!==void 0&&!gp(s.consentFingerprint))return;n[i]={decision:s.decision,revision:s.revision,...s.decision==="allow"&&s.consentFingerprint!==void 0?{consentFingerprint:s.consentFingerprint}:{}}}return{schema_version:1,records:n}}function hp(e){return Ga(`${e.miniProgramId}\0${e.userId}\0${e.environment}`).slice(0,32)}function mp(e){const t=e.miniProgramId?.trim(),r=e.userId?.trim(),n=e.environment?.trim();if(!t||!r||!n)throw Object.assign(new Error("无法确定用户数据许可作用域"),{code:"INVALID_STATE"});return Object.freeze({miniProgramId:t,userId:r,environment:n})}function gp(e){return typeof e=="string"&&/^[0-9a-f]{64}$/.test(e)}function we(e,t,r){return{code:e,message:t,data:r}}function $a(e){return pp(e)?{code:e.code,message:e.message,data:e.data}:e instanceof Error?we("RUNTIME_ERROR",e.message):we("UNKNOWN_ERROR","小程序运行时异常",e)}function pp(e){return!!e&&typeof e=="object"&&typeof e.code=="string"&&typeof e.message=="string"}const qt=["account.getCurrentUserId","account.onChange","storage.getRaw","storage.setRaw"],qo=[...qt,"network.request"],xc={"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"],[Di]:["workspaceCards.requestRefresh"],[Ni]:["account.getCurrentUserId","account.getAccountKey","account.onChange"],[Mi]:["account.getCurrentUserId","account.ensureAuthenticated","account.onChange","network.request"],[Si]:["account.getCurrentUserId","account.onChange","network.request"],[bi]:["account.getCurrentUserId","account.ensureAuthenticated","account.onChange","network.request"],[Ti]:["account.getCurrentUserId","account.onChange","network.request"],[vi]:["account.getCurrentUserId","account.onChange","network.request"],[Oi]:["account.getCurrentUserId","account.onChange","network.request"],[Ri]:["presentation.setClipboard"],[ki]:["presentation.showShareMenu"],[Pi]:["presentation.getViewportMetrics","presentation.captureAndShare"],[Ci]:["presentation.getViewportMetrics","presentation.captureAndShare"],[nr]:["presentation.applyOrientation"],[Li]:["presentation.getViewportMetrics","presentation.getNavigationBarHeight"],[Ui]:["presentation.setNavigationBarStyle"],[En]:["storage.getRaw"],[wn]:["storage.setRaw"],[xi]:["network.request"],[zi]:["network.stream","files.transfer","files.access"],[ji]:["network.upload","files.access"],[Bi]:["files.external"],[Hi]:["files.external"],[Fi]:["files.save"],[In]:["files.access"],[An]:["files.removeFile"],[Vi]:["files.access"],[_n]:["files.access"],[Gi]:["files.access"],[Dn]:["files.access"],[$i]:["files.access"],[Nn]:["files.access"],[qi]:["files.access"],[Mn]:["files.removeDirectory"],[Qi]:["files.access"],[Yi]:["files.access"],[Sn]:["media.pick"],[yn]:["presentation.showAppreciation"],[Wi]:["presentation.showToast"],[Zi]:["presentation.showLoading"],[Ki]:["presentation.hideLoading"],[Ji]:["presentation.vibrate"],[Xi]:["presentation.setClipboard"],[eo]:["protocol.invoke"],[to]:["presentation.close"],[ro]:["presentation.reload"],[no]:["presentation.openAppPage"],[bt]:["account.getCurrentUserId","account.onChange","network.request"],[at]:["account.onChange","network.request"],[xt]:["account.getCurrentUserId","account.onChange","network.request"],[ir]:["account.getCurrentUserId","account.onChange","network.request"],[wt]:["account.onChange","network.request"],[vr]:["account.getCurrentUserId","account.onChange","network.request"],[Or]:["account.getCurrentUserId","account.onChange","network.request"],[Rr]:["account.getCurrentUserId","account.onChange","network.request"],[or]:["account.getCurrentUserId","account.onChange","network.request"],[wo]:["companion.getInfo"],[Io]:["companion.getPreparationStatus"],[Ao]:["companion.getInfo","companion.getPreparationStatus","companion.prepare"],[_o]:["companion.cancelPreparation"],[Do]:["companion.getActiveSession"],[No]:["companion.getInfo","companion.launch"],[Mo]:["companion.session.write"],[So]:["companion.session.closeStdin"],[bo]:["companion.session.terminate"],[To]:["companion.session.ackOutput"],[vo]:["companion.openAttachment"],[Oo]:["companion.showNotification"],[Ca]:qt,[Ai]:qo,[un]:qo,[_i]:[...qo,"files.sandbox","files.removeFile","network.stream","files.transfer"],[La]:[...qt,"presentation.confirmDataPermission"],[Ua]:qt,[xa]:qt,[za]:[...qt,"presentation.openDataPermissions"],[ja]:qt},yp=new Set([yn]);function Gl(e,t){if(t[e]!==!0)throw yp.has(e)?we("REQUEST_UNSUPPORTED","当前宿主不支持该能力"):tt(e)}const Ep=32*1024*1024,wp=/^application\/(?:[a-z0-9!#$&^_.+-]+\+)?json(?:\s*;|$)/i;function Ip(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:Ep},i);return Ap(o,a)}catch(a){throw s=a,a}finally{try{await r.release(o.body)}catch(a){if(s===void 0)throw a}}}}}}function Ap(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:_p(t,Np(e,"content-type"))}}function _p(e,t){Dp(t);let r;try{r=new TextDecoder("utf-8",{fatal:!0}).decode(e)}catch(n){throw new Le("Host network response 不是合法 UTF-8 文本",{cause:n})}if(r.charCodeAt(0)===65279&&(r=r.slice(1)),!t||!wp.test(t)||r==="")return r;try{return JSON.parse(r)}catch{return r}}function Dp(e){if(!e)return;const t=/(?:^|;)\s*charset\s*=\s*["']?([^;"'\s]+)/i.exec(e)?.[1];if(t&&!/^utf-?8$/i.test(t))throw new Le(`Host network response 不支持 charset=${t}`)}function Np(e,t){return Object.entries(e.headers).find(([r])=>r.toLowerCase()===t)?.[1]?.[0]}function Z(e){return typeof e=="function"}function zc(e){return(...t)=>{throw tt(e)}}function Ce(e){return async(...t)=>{throw tt(e)}}const Mp=(e,t)=>{},Sp=()=>()=>{};function bp(e){const t={request:Z(e.network?.request)?e.network.request.bind(e.network):Ce("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):Ce("account.getCurrentUserId"),ensureAuthenticated:Z(e.account?.ensureAuthenticated)?e.account.ensureAuthenticated.bind(e.account):Ce("account.ensureAuthenticated"),onChange:Z(e.account?.onChange)?e.account.onChange.bind(e.account):Sp},n={...e.storage?.withLock?{withLock:e.storage.withLock.bind(e.storage)}:{},getRaw:Z(e.storage?.getRaw)?e.storage.getRaw.bind(e.storage):Ce("storage.getRaw"),setRaw:Z(e.storage?.setRaw)?e.storage.setRaw.bind(e.storage):Ce("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):Ce("presentation.close"),reload:Z(e.presentation?.reload)?e.presentation.reload.bind(e.presentation):Ce("presentation.reload"),openAppPage:Z(e.presentation?.openAppPage)?e.presentation.openAppPage.bind(e.presentation):Ce("presentation.openAppPage"),openWindow:Z(e.presentation?.openWindow)?e.presentation.openWindow.bind(e.presentation):Ce("presentation.openWindow"),getViewportMetrics:Z(e.presentation?.getViewportMetrics)?e.presentation.getViewportMetrics.bind(e.presentation):zc("presentation.getViewportMetrics"),getNavigationBarHeight:Z(e.presentation?.getNavigationBarHeight)?e.presentation.getNavigationBarHeight.bind(e.presentation):zc("presentation.getNavigationBarHeight"),setNavigationBarStyle:Z(e.presentation?.setNavigationBarStyle)?e.presentation.setNavigationBarStyle.bind(e.presentation):Ce("presentation.setNavigationBarStyle"),showShareMenu:Z(e.presentation?.showShareMenu)?e.presentation.showShareMenu.bind(e.presentation):Ce("presentation.showShareMenu"),setScreenshotChromeHidden:Z(e.presentation?.setScreenshotChromeHidden)?e.presentation.setScreenshotChromeHidden.bind(e.presentation):Mp,supportsLongScreenshot:e.presentation?.supportsLongScreenshot===!0,captureAndShare:Z(e.presentation?.captureAndShare)?e.presentation.captureAndShare.bind(e.presentation):Ce("presentation.captureAndShare"),showAppreciation:Z(e.presentation?.showAppreciation)?e.presentation.showAppreciation.bind(e.presentation):async()=>{throw we("REQUEST_UNSUPPORTED","当前宿主不支持赞赏码")},showToast:Z(e.presentation?.showToast)?e.presentation.showToast.bind(e.presentation):Ce("presentation.showToast"),showLoading:Z(e.presentation?.showLoading)?e.presentation.showLoading.bind(e.presentation):Ce("presentation.showLoading"),hideLoading:Z(e.presentation?.hideLoading)?e.presentation.hideLoading.bind(e.presentation):Ce("presentation.hideLoading"),vibrate:Z(e.presentation?.vibrate)?e.presentation.vibrate.bind(e.presentation):Ce("presentation.vibrate"),setClipboard:Z(e.presentation?.setClipboard)?e.presentation.setClipboard.bind(e.presentation):Ce("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):Ce(`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):Ce("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 Tp(e,t={}){const r=vp(e.files?.sandbox),n=Z(e.picker?.pickFiles)&&Z(e.picker?.pickDirectory),i=Z(e.picker?.saveFile),o=r||n||i||Z(e.companion?.openAttachment),s=r?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":r,"files.external":n,"files.save":i,"files.access":o,"files.removeFile":Z(s?.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),"presentation.confirmDataPermission":t.hasUserDataPresentation===!0,"presentation.openDataPermissions":t.hasUserDataSettings===!0}}function vp(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 jc(e,t){return t?.[e]!==!1}function Op(e){return e==="network.download"||e.startsWith("files.")||e.startsWith("file.")||e.startsWith("directory.")||e.startsWith("media.")||e.startsWith("companion.")}function $l(e,t={}){const r={};for(const n of Object.keys(xc)){const o=xc[n].every(a=>e[a]),s=!Op(n)||!!t.miniProgramDetail?.miniProgramId.trim();r[n]=jc(n,t.callerCapabilities)&&jc(n,t.hostCapabilities)&&o&&s}return r}function ql(e={},t={}){const r=Tp(e,t),n=$l(r,t);return{ports:bp(e),primitiveAvailability:r,availablePrimitives:r,effectiveCapabilities:n}}function Se(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]):Rp(e.signal,t);return{...e,signal:n,...r===void 0?{}:{requestId:r}}}function Rp(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 kp(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 Pp=4,Cp=["xiaoheihe.cn","max-c.com","debugmode.cn","maxjia.com"],Lp=new Set(["connection","content-length","host","origin","referer","keep-alive","proxy-connection","te","trailer","transfer-encoding","upgrade","x-heybox-runtime-auth-context-token"]),Up=["/user_miniprogram/runtime/auth","/user_miniprogram/openapi/v1"],xp=["/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 zp(e,t){const r=Hp(e);return r===null||Bc(r,Up)?!0:t&&Bc(r,xp)}function jp(e){const t=e.hostname.toLowerCase().replace(/\.$/,"");return Cp.some(r=>t===r||t.endsWith(`.${r}`))}function Bp(e){const t=e.trim().toLowerCase();return t.startsWith("x-hb-sdk-")||t.startsWith("sec-")||Lp.has(t)||/^(?:x-heybox|x-xhh)-(?:access-token|auth|authorization|pkey|session|token)$/.test(t)}function Hp(e){let t=e;for(let r=0;r<Pp;r+=1){let n;try{n=decodeURIComponent(t)}catch{return null}if(n===t)return Hc(t);t=n}try{if(decodeURIComponent(t)!==t)return null}catch{return null}return Hc(t)}function Bc(e,t){return t.some(r=>e===r||e.startsWith(`${r}/`))}function Hc(e){const t=[];for(const r of e.replace(/\\/g,"/").split("/"))!r||r==="."||(r===".."?t.pop():t.push(r));return`/${t.join("/")}`}function Fp(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 Ql(e){if(e==null)return;if(typeof e!="object"||Array.isArray(e))throw Qo("网络策略格式无效");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 Qo("网络策略格式无效");const n=new Set;for(const i of r){const o=Fp(i&&typeof i=="object"?i.domain:void 0);if(!o)throw Qo("网络策略包含无效域名");n.add(o)}return Object.freeze({revision:t.revision,enforcement:t.enforcement,entries:Object.freeze([...n].sort().map(i=>Object.freeze({domain:i})))})}function Qo(e){return Object.assign(new TypeError(e),{code:"NETWORK_POLICY_INVALID"})}function Fc(e){return e instanceof Le?{code:"REQUEST_UNSUPPORTED",message:e.message}:e}function fe(e,t,r={}){if(t.aborted&&!r.invokeWhenAborted)return Promise.reject(si());let n;try{n=e()}catch(i){return Promise.reject(Fc(i))}return t.aborted?(Promise.resolve(n).catch(()=>{}),Promise.reject(si())):new Promise((i,o)=>{let s=!1;const a=d=>{s||(s=!0,t.removeEventListener("abort",c),d())},c=()=>a(()=>o(si()));t.addEventListener("abort",c,{once:!0}),Promise.resolve(n).then(d=>a(()=>i(d)),d=>a(()=>o(Fc(d))))})}async function Vp(e,t,r){pe(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 fe(()=>new Promise(f=>i.requestAnimationFrame(()=>i.requestAnimationFrame(()=>f()))),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 f=e.parentElement;f;f=f.parentElement){const l=i.getComputedStyle(f),h=f.getBoundingClientRect();if(["hidden","clip","scroll","auto"].includes(l.overflowY)&&(u.top+t.top<h.top-1||u.top+t.top+t.height>h.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 Gp(e,t,r,n=1e4){const i=new AbortController;return new Promise((o,s)=>{let a=!1;const c=f=>{a||(a=!0,clearTimeout(u),r.signal.removeEventListener("abort",d),i.abort(f),s(f))},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(f=>{if(typeof f!="function"){c({code:"NETWORK_POLICY_UNSUPPORTED",message:"Host 未完成严格网络策略初始化"});return}if(a){try{f()}catch{}return}a=!0,clearTimeout(u),o(()=>{r.signal.removeEventListener("abort",d),i.abort(),f()})},c)})}function Yl(e,t){return $p(t)??qp(e.pathname)}function $p(e){if(!e)return;const t=new URL(e,"https://mini-program.invalid").pathname;return t.endsWith("/")?t:`${t}/`}function qp(e){const t=/^(\/u\/[^/]+\/[^/]+\/)/.exec(e)?.[1];if(t)return t;const r=e.lastIndexOf("/");return r>=0?e.slice(0,r+1):"/"}const Qp=1,Wl="allow-scripts allow-same-origin",Yp="",Wp="no-referrer";function Zp(e=Wl){return!e.split(/\s+/).includes("allow-same-origin")}function Vc(){return window.crypto?.randomUUID?window.crypto.randomUUID():`${Date.now().toString(36)}_${Math.random().toString(36).slice(2)}`}const Kp=new Set(["javascript:","data:","blob:","file:"]),Gc="xiaoheihe.cn";function Jp(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(Kp.has(i.protocol)||!["http:","https:"].includes(i.protocol))throw new Error("不支持的小程序链接协议");if(!ey(i,t,r))throw new Error("小程序链接必须属于 https://*.xiaoheihe.cn 或本地调试地址");return i.toString()}function Xp(e,t){const r=new URL(e);return r.searchParams.set(pl,t),r.toString()}function Zl(e,t,r){try{const n=new URL(e),i=new URL(t);if(n.origin!==i.origin)return!1;const o=Yl(n,r);return i.pathname.startsWith(o)}catch{return!1}}function $c(e){const t=new URL(e);return qa(t)?"loopback":Qa(t)?"lan":"production"}function ey(e,t,r){return ty(e)||qa(e)||Qa(e)&&ny(t,r)}function ty(e){return e.protocol==="https:"&&sy(e.hostname)}function qa(e){return e.protocol==="http:"&&ry(e.hostname)}function ry(e){return e==="localhost"||e==="127.0.0.1"||e==="[::1]"}function Qa(e){return e.protocol==="http:"&&iy(e.hostname)}function ny(e,t){if(t.allowPrivateNetwork)return!0;try{const r=new URL(e);return qa(r)||Qa(r)}catch{return!1}}function iy(e){const t=oy(e);return t?t[0]===10||t[0]===172&&t[1]>=16&&t[1]<=31||t[0]===192&&t[1]===168:!1}function oy(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 sy(e){return e===Gc||e.endsWith(`.${Gc}`)}function ay(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||!Zl(e.launchUrl,a.href,e.locationBasePath))return;const c=new URL(a.href);if(!(c.username||c.password||c.searchParams.get(pl)!==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 Kl(e){const t=qe(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 cy(e){const t=qe(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 dy(){try{return{activeElement:globalThis.document?.activeElement??null,userActivation:globalThis.navigator?.userActivation}}catch{return{activeElement:null}}}const uy=1e3;function ly(e,t=dy()){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<=uy}const fy="runtime.gate.probe",Jl=new Set(zt.map(e=>e.method));class hy{iframe;nonce;onReady;getWorkspaceCardLaunchContext;onHandshake;onDuplicateHandshake;onInternalEvent;onResponsePosted;onDevUploadSession;handleMessage;handleUserInteraction;dispatcher;environmentInfo;started=!1;destroyed=!1;handshaken=!1;bridgeVersion=gl;targetOrigin;lastUserInteractionAt;operations=new Map;constructor(t){this.iframe=t.iframe,this.nonce=t.nonce,this.onReady=t.onReady,this.getWorkspaceCardLaunchContext=t.getWorkspaceCardLaunchContext,this.onHandshake=t.onHandshake,this.onDuplicateHandshake=t.onDuplicateHandshake,this.onInternalEvent=t.onInternalEvent,this.onResponsePosted=t.onResponsePosted,this.onDevUploadSession=t.onDevUploadSession,this.handleMessage=this.onMessage.bind(this),this.handleUserInteraction=this.onUserInteraction.bind(this),this.dispatcher=t.dispatcher,this.environmentInfo=t.environmentInfo,this.targetOrigin=t.targetOrigin||"*"}get protocolVersion(){return this.handshaken?this.bridgeVersion:void 0}start(){if(!(this.started||this.destroyed)){this.started=!0,window.addEventListener("message",this.handleMessage);for(const t of["pointerdown","touchend","mousedown","keydown"])window.addEventListener(t,this.handleUserInteraction,!0)}}setTargetOrigin(t){this.targetOrigin=t||"*"}destroy(){if(this.destroyed)return;const t=this.started;this.destroyed=!0,this.started=!1,this.handshaken=!1;try{t&&this.postMessage({namespace:$t,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:$t,version:this.bridgeVersion,nonce:this.nonce,type:"event",method:t,payload:r})}postInternalRequest(t,r,n){this.destroyed||this.postMessage({namespace:$t,version:this.bridgeVersion,nonce:this.nonce,type:"request",id:r,method:t,payload:n})}postProgress(t,r){this.bridgeVersion===2&&this.postMessage({namespace:$t,version:2,nonce:this.nonce,type:"event",id:t,method:El,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=ly(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&&Cm(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:$t,version:this.bridgeVersion,nonce:this.nonce,type:"response",id:t.id,method:yl,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===fy){this.postResponse(t,{ready:!0});return}if(!this.handshaken){this.postResponse(t,void 0,we("BRIDGE_NOT_READY","小程序 SDK 尚未完成握手"));return}if(!Jl.has(t.method)){this.postResponse(t,void 0,we("METHOD_NOT_FOUND",`未开放小程序能力: ${t.method}`));return}if(this.operations.has(t.id)){this.postResponse(t,void 0,we("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=$a(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:$t,version:t.version,nonce:this.nonce,type:"response",id:t.id,method:t.method,payload:r,error:n})||!my(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 my(e){return typeof e=="string"&&Jl.has(e)}function y(e,t,r){return r===void 0?{code:e,message:t}:{code:e,message:t,data:r}}function re(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ya(){const e=globalThis.crypto;if(!e||typeof e.getRandomValues!="function")throw y("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 y("FILE_IO_FAILED","无法生成安全文件标识")}}function Xl(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):Ys,remove:o?s=>e.remove(s):tf,read:s=>e.read(s),...typeof e.readPrefix=="function"?{readPrefix:(s,a)=>e.readPrefix(s,a)}:{},write:i?(s,a)=>e.write(s,a):Ys,stat:s=>e.stat(s)})}function ef(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=>Xl(e.file(a),n,{allowRemove:o}),directory:a=>ef(e.directory(a),n,{allowRemove:o}),create:i?(a,c)=>e.create(a,c):Ys,remove:s?(a,c)=>e.remove(a,c):tf,stat:a=>e.stat(a),list:(a,c)=>e.list(a,c)})}function Ys(){return Promise.reject(y("FILE_ACCESS_DENIED","当前文件授权只允许读取"))}function tf(){return Promise.reject(y("FILE_ACCESS_DENIED","外部文件授权不允许删除"))}const gy=new Set(["REQUEST_CANCELLED","REQUEST_TIMEOUT","RUNTIME_DESTROYED","USER_DATA_PERMISSION_STORAGE_UNAVAILABLE","USER_DATA_PERMISSION_STATE_INVALID","USER_DATA_SOURCE_NOT_LINKED","USER_DATA_SOURCE_LOGIN_REQUIRED","USER_GAME_DATA_UNAVAILABLE","USER_GAME_DATA_INVALID_RESPONSE","METHOD_FORBIDDEN","FILE_PICKER_CANCELLED","FILE_ACCESS_REVOKED","FILE_ACCESS_DENIED","FILE_NOT_FOUND","DIRECTORY_NOT_FOUND","FILE_ALREADY_EXISTS","DIRECTORY_ALREADY_EXISTS","FILE_TYPE_MISMATCH","FILE_TOO_LARGE","FILE_QUOTA_EXCEEDED","FILE_ENCODING_INVALID","DIRECTORY_LIST_LIMIT_EXCEEDED","DIRECTORY_NOT_EMPTY","FILE_IO_FAILED"]),py={REQUEST_CANCELLED:"文件操作已取消",REQUEST_TIMEOUT:"文件操作超时",RUNTIME_DESTROYED:"小程序已关闭",USER_DATA_PERMISSION_STORAGE_UNAVAILABLE:"无法读取本地用户数据许可",USER_DATA_PERMISSION_STATE_INVALID:"本地用户数据许可状态异常,已停止访问",USER_DATA_SOURCE_NOT_LINKED:"请先在小黑盒关联对应游戏账号",USER_DATA_SOURCE_LOGIN_REQUIRED:"请先在小黑盒更新游戏来源登录",USER_GAME_DATA_UNAVAILABLE:"游戏资料暂不可用,请稍后重试",USER_GAME_DATA_INVALID_RESPONSE:"游戏资料响应异常,请稍后重试",METHOD_FORBIDDEN:"当前 Host 未开放该文件能力",FILE_PICKER_CANCELLED:"已取消文件选择",FILE_ACCESS_REVOKED:"文件授权已失效",FILE_ACCESS_DENIED:"当前文件授权不允许此操作",FILE_NOT_FOUND:"文件不存在",DIRECTORY_NOT_FOUND:"目录不存在",FILE_ALREADY_EXISTS:"文件已存在",DIRECTORY_ALREADY_EXISTS:"目录已存在",FILE_TYPE_MISMATCH:"文件类型不匹配",FILE_TOO_LARGE:"文件超过大小限制",FILE_QUOTA_EXCEEDED:"文件配额已用尽",FILE_ENCODING_INVALID:"文件编码不合法",DIRECTORY_LIST_LIMIT_EXCEEDED:"目录项数量超过限制",DIRECTORY_NOT_EMPTY:"目录不为空",FILE_IO_FAILED:"文件操作失败"};function Pr(e){const t=Wa(e),r=t&&gy.has(t)?y(t,py[t]??"文件操作失败"):y("FILE_IO_FAILED","文件操作失败");return Object.defineProperty(r,"cause",{value:e,enumerable:!1}),r}function Nt(e){try{return e()}catch(t){throw Pr(t)}}function Wa(e){try{if(!re(e))return;const t=Object.getOwnPropertyDescriptor(e,"code");return t&&"value"in t&&typeof t.value=="string"?t.value:void 0}catch{return}}const qc=1024;class Za{constructor(t,r){this.files=t,this.miniProgramDetail=r}handles=new Map;disposed=!1;createTransferScope(){return this.assertCanonicalDetail(),new Za(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 $n(i.handle,{kind:"file",handleId:o})}registerFiles(t,r="external",n,i){this.assertCanonicalDetail();const o=Nt(()=>{if(!Array.isArray(t))throw y("FILE_IO_FAILED","Host 返回了无效文件选择结果");const a=t.length;if(i!==void 0&&a>i)throw y("FILE_IO_FAILED","Host 返回了过多文件选择结果");if(this.handles.size+a>qc)throw y("FILE_QUOTA_EXCEEDED","当前会话的文件授权句柄已达上限");const c=[];for(let d=0;d<a;d+=1){if(!Object.prototype.hasOwnProperty.call(t,d))throw y("FILE_IO_FAILED","Host 返回了稀疏文件选择结果");c.push(this.prepareFile(t[d],r,n))}return c}),s=this.registerMany(o);return o.map((a,c)=>$n(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 Yc(i.handle,{kind:"directory",handleId:o})}resolveFile(t){return this.resolveFileEntry(t).handle}resolveDirectory(t){return this.resolveDirectoryEntry(t).handle}isCompanionAttachmentRef(t){return!er(t)||!("handleId"in t)?!1:this.handles.get(t.handleId)?.origin==="companion-attachment"}isGameSaveRef(t){return!er(t)||!("handleId"in t)?!1:this.handles.get(t.handleId)?.origin==="game-save"}isUserDataDownloadRef(t){return!er(t)||!("handleId"in t)?!1:this.handles.get(t.handleId)?.origin==="download"}resolveFileEntry(t){this.assertCanonicalDetail();const r=Ey(t);if("handleId"in r){const s=this.readDirect(r.handleId,"file");return{ref:r,...s}}const n=this.resolveRoot(r.root),i=Tn(r.relativePath);Yo(n.origin,i);const o=this.prepareFile(Nt(()=>n.hostHandle.file(i)),n.origin,n.handle.mode);return{ref:r,...o}}resolveDirectoryEntry(t){this.assertCanonicalDetail();const r=wy(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==="."?".":Tn(r.relativePath);Yo(n.origin,i);const o=this.prepareDirectory(i==="."?n.hostHandle:Nt(()=>n.hostHandle.directory(i)),n.origin,n.handle.mode,!0);return{ref:r,...o}}describeFile(t,r){return Zc(t),$n(t,r)}describeListedEntries(t,r,n){return this.assertCanonicalDetail(),Nt(()=>{if(!Array.isArray(r))throw y("FILE_IO_FAILED","Host 返回了无效目录列表");const i=r.length;if(i>n)throw y("DIRECTORY_LIST_LIMIT_EXCEEDED","目录项数量超过限制");const o=[];for(let s=0;s<i;s+=1){if(!Object.prototype.hasOwnProperty.call(r,s))throw y("FILE_IO_FAILED","Host 返回了稀疏目录列表");const a=r[s];t.origin==="sandbox"&&re(a)&&typeof a.name=="string"&&rf(a.name)||o.push(this.describeListedEntry(t,a))}return this.assertCanonicalDetail(),o})}describeListedEntry(t,r){return Nt(()=>{if(re(r)&&r.kind==="file"){const n=this.prepareFile(r,t.origin,t.handle.mode);return $n(n.handle,Qc(t.ref,n.handle.name))}if(re(r)&&r.kind==="directory"){const n=this.prepareDirectory(r,t.origin,t.handle.mode);return Yc(n.handle,yy(t.ref,n.handle.name))}throw y("FILE_IO_FAILED","Host 返回了无效目录项")})}deriveFile(t,r){this.assertCanonicalDetail();const n=Ln(r);Yo(t.origin,n);const i=this.prepareFile(Nt(()=>t.hostHandle.file(n)),t.origin,t.handle.mode);return{ref:Qc(t.ref,n),...i}}assertSandboxOrigin(t){if(t.origin!=="sandbox")throw y("FILE_ACCESS_DENIED","外部文件授权不允许删除")}prepareFile(t,r,n){return Nt(()=>{Zc(t);const i=n??t.mode;return Wc(t.mode,i),{handle:Xl(t,i,{allowRemove:r==="sandbox"}),hostHandle:t,origin:r}})}prepareDirectory(t,r,n,i=!1){return Nt(()=>{_y(t,i);const o=n??t.mode;return Wc(t.mode,o),{handle:ef(t,o,{allowRemove:r==="sandbox"}),hostHandle:t,origin:r}})}registerMany(t){if(this.assertCanonicalDetail(),this.handles.size+t.length>qc)throw y("FILE_QUOTA_EXCEEDED","当前会话的文件授权句柄已达上限");const r=new Set,n=t.map(()=>{for(let i=0;i<8;i+=1){const o=Ya();if(!this.handles.has(o)&&!r.has(o))return r.add(o),o}throw y("FILE_IO_FAILED","无法创建文件授权句柄")});return t.forEach((i,o)=>this.handles.set(n[o],i)),n}readDirect(t,r){if(!Iy(t))throw y("FILE_ACCESS_REVOKED","文件授权句柄无效");const n=this.handles.get(t);if(!n)throw y("FILE_ACCESS_REVOKED","文件授权已失效");if(n.handle.kind!==r||n.hostHandle.kind!==r)throw y("FILE_TYPE_MISMATCH","文件句柄类型不匹配");return n}resolveRoot(t){if(this.assertCanonicalDetail(),t.kind==="sandbox"){if(!this.files)throw tt("files.sandbox");return this.prepareDirectory(Nt(()=>this.files.sandbox),"sandbox",void 0,!0)}return this.readDirect(t.handleId,"directory")}assertCanonicalDetail(){if(this.disposed)throw y("FILE_ACCESS_REVOKED","文件授权已失效");if(!this.miniProgramDetail?.miniProgramId.trim())throw tt("files")}}function Tn(e){if(!Ba(e))throw y("INVALID_PARAMS","relativePath 不是规范逻辑路径");return e}function Yo(e,t){if(e==="sandbox"&&rf(t))throw y("FILE_ACCESS_DENIED","Runtime 私有缓存不能通过沙箱路径访问")}function rf(e){return e.split("/").some(t=>t.replace(/[. ]+$/,"").toLowerCase()===".hb-game-saves")}function Ln(e,t="文件名"){const r=Tn(e);if(r.includes("/"))throw y("INVALID_PARAMS",`${t} 只能是 basename`);return r}function Qc(e,t){return"handleId"in e?{kind:"file",root:{kind:"directory",handleId:e.handleId},relativePath:t}:{kind:"file",root:e.root,relativePath:Tn(e.relativePath==="."?t:`${e.relativePath}/${t}`)}}function yy(e,t){return"handleId"in e?{kind:"directory",root:{kind:"directory",handleId:e.handleId},relativePath:t}:{kind:"directory",root:e.root,relativePath:Tn(e.relativePath==="."?t:`${e.relativePath}/${t}`)}}function $n(e,t){return{kind:"file",name:e.name,mode:e.mode,ref:t}}function Yc(e,t){return{kind:"directory",name:e.name,mode:e.mode,ref:t}}function Wc(e,t){if(t==="readwrite"&&e!=="readwrite")throw y("FILE_ACCESS_DENIED","Host 未授予请求的文件写权限")}function Ey(e){return er(e)||nf(),e}function wy(e){return Il(e)||nf(),e}function nf(){throw y("INVALID_PARAMS","文件引用不合法")}function Iy(e){return/^[0-9a-f]{32}$/.test(e)}function Ay(e){return re(e)&&e.kind==="file"&&typeof e.name=="string"&&(e.mode==="read"||e.mode==="readwrite")&&typeof e.create=="function"&&typeof e.read=="function"&&typeof e.write=="function"&&typeof e.stat=="function"}function Zc(e){if(!Ay(e))throw y("FILE_IO_FAILED","Host 返回了无效 File handle");Ln(e.name,"Host File name")}function _y(e,t=!1){if(!re(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 y("FILE_IO_FAILED","Host 返回了无效 Directory handle");if(!t&&e.name.length===0)throw y("FILE_IO_FAILED","Host Directory name 不能为空");e.name&&Ln(e.name,"Host Directory name")}const Dy=new Set(["content-length","content-encoding","transfer-encoding","content-disposition","content-range","content-type"]),Ny=new Set(["content-length","content-encoding","content-disposition","content-range","content-type"]),My=new Set(["range","if-range","a-im"]),Sy=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"]),by=/^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\..*)?$/i,qn={initial:0,target:1,open:2,validate:3,transfer:4,committed:5,completed:6};class Ty{constructor(t){this.signal=t}phase="initial";transition(t){if(qn[t]<=qn[this.phase])throw y("FILE_IO_FAILED","下载状态转换不合法");this.phase=t}throwIfCancelled(){if(qn[this.phase]<qn.committed&&this.signal.aborted)throw af()}normalizeHostError(t,r){return this.throwIfCancelled(),Ja(t,r,this.signal)}}async function of(e,t,r){const n=r.transfer,i=r.fileRegistry;if(!n||!i)throw tt("network.download");const o=Se(r.operationContext,t.signal),s=new Ty(o.signal);s.transition("target"),s.throwIfCancelled();let a;try{a=await ky(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=Cy(c);Ly(c,u);const f=Uy(c.status,u);if(e.maxBytes!==void 0&&f.expectedBytes!==void 0&&f.expectedBytes>e.maxBytes)throw y("FILE_TOO_LARGE","下载响应超过 maxBytes");s.throwIfCancelled();const l=Py(e,a,u,i);let h=0;const m=Oy(f.expectedBytes,e.maxBytes);Zo(t,Wo(0,f));const E={...o,onProgress(S){!Number.isSafeInteger(S)||S<h||m!==void 0&&S>m||(h=S,Zo(t,Wo(h,f)))}};s.transition("transfer"),d=!0;let _;try{_=await n.files.writeResource(l.hostHandle,c.body,{mode:l.mode,...e.maxBytes===void 0?{}:{maxBytes:e.maxBytes},...f.expectedBytes===void 0?{}:{expectedBytes:f.expectedBytes}},E)}catch(S){throw s.normalizeHostError(S,"transfer")}s.transition("committed"),h=vy(_,f,h,e.maxBytes),Zo(t,Wo(h,f));const w=i.describeFile(l.handle,l.ref);return s.transition("completed"),w}finally{d||Ry(n.network,c.body)}}function vy(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 Oy(e,t){return e===void 0?t:t===void 0?e:Math.min(e,t)}function Ry(e,t){try{Promise.resolve(e.release(t)).catch(()=>{})}catch{}}async function ky(e,t,r){if(e.targetKind==="file"){const i=t.resolveFileEntry(e.to);return Ws(i.handle.mode),await Vy(i.handle,r),{kind:"file",...i}}const n=t.resolveDirectoryEntry(e.to);return Ws(n.handle.mode),await Gy(n.handle,r),{kind:"directory",...n}}function Py(e,t,r,n){if(t.kind==="file")return{ref:t.ref,handle:t.handle,hostHandle:t.hostHandle,mode:"replace-existing"};const i=zy(e,r),o=n.deriveFile(t,i);return Ws(o.handle.mode),{...o,mode:e.overwrite===!0?"upsert":"create-exclusive"}}function Cy(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 y("DOWNLOAD_NETWORK_FAILED","Host 返回了无效 stream response");if(!re(e.headers))throw y("DOWNLOAD_NETWORK_FAILED","Host 返回了无效 stream headers");const t={};for(const[r,n]of Object.entries(e.headers)){if(r!==r.toLowerCase()||!Dy.has(r)||!Array.isArray(n)||n.length===0)throw y("DOWNLOAD_NETWORK_FAILED","Host 返回了不安全 stream header");if(n.some(i=>typeof i!="string"||/[\r\n]/.test(i)))throw y("DOWNLOAD_NETWORK_FAILED","Host 返回了无效 stream header value");t[r]=[...n]}return t}function Ly(e,t){if(e.status<200||e.status>=300||e.status===206||e.status===226)throw y("DOWNLOAD_HTTP_STATUS",`下载请求失败: HTTP ${e.status}`,{status:e.status,...e.statusText===void 0?{}:{statusText:e.statusText},headers:Fy(t,Ny)});if((t["content-range"]?.length??0)>0)throw y("DOWNLOAD_NETWORK_FAILED","下载响应包含 Content-Range")}function Uy(e,t){const r=t["content-length"]??[],n=t["transfer-encoding"]??[];if(r.length>0&&n.length>0)throw y("DOWNLOAD_NETWORK_FAILED","下载响应同时包含 Transfer-Encoding 与 Content-Length");if((e===204||e===205)&&r.some(d=>d!=="0"))throw y("DOWNLOAD_NETWORK_FAILED","无内容响应声明了非零 Content-Length");if((e===204||e===205)&&n.length>0)throw y("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=xy(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 xy(e){return!e||e.length===0?!0:e.length===1&&e[0].trim().toLowerCase()==="identity"}function Wo(e,t){return{loaded:e,...t.total===void 0?{}:{total:t.total},lengthComputable:t.lengthComputable}}function Zo(e,t){try{e.postProgress(t)}catch{}}function zy(e,t){const r=t["content-disposition"]??[];for(const i of r){const o=jy(i);if(o&&ai(o))return o}for(const i of r){const o=By(i);if(o&&ai(o))return o}if(e.suggestedName!==void 0)return Ka(e.suggestedName);const n=Hy(e.url);return n&&ai(n)?n:"download.bin"}function jy(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 By(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 Hy(e){const t=e.pathname.split("/").pop();if(t)try{return decodeURIComponent(t)}catch{return}}function Ka(e){try{Ln(e,"suggestedName")}catch{throw y("INVALID_PARAMS","suggestedName 不是安全 basename")}if(!ai(e))throw y("INVALID_PARAMS","suggestedName 不是安全 basename");return e}function ai(e){return!(!e||e==="."||e===".."||Array.from(e).length>255||/[\\/<>:"|?*\u0000-\u001f\u007f]/.test(e)||/[. ]$/.test(e)||by.test(e))}function Fy(e,t){return Object.fromEntries(Object.entries(e).filter(([r])=>t.has(r)).map(([r,n])=>[r,n.join(", ")]))}async function Vy(e,t){try{const r=await e.stat(t);if(!r||r.kind!=="file")throw sf()}catch(r){throw Ja(r,"file",t.signal)}}async function Gy(e,t){try{const r=await e.stat(t);if(!r||r.kind!=="directory")throw sf()}catch(r){throw Ja(r,"file",t.signal)}}function Ws(e){if(e!=="readwrite")throw y("FILE_ACCESS_DENIED","下载目标只允许读取")}const $y={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 Ja(e,t,r){if(r.aborted)return af();const n=qy(e);if(n&&Sy.has(n)){const o=y(n,$y[n]??"下载失败");return Object.defineProperty(o,"cause",{value:e,enumerable:!1}),o}if(e instanceof Error&&e.name==="AbortError")return t==="network"||t==="transfer"?y("DOWNLOAD_TIMEOUT","下载网络请求超时"):y("FILE_IO_FAILED","下载文件写入失败");const i=t==="network"?y("DOWNLOAD_NETWORK_FAILED","下载网络请求失败"):y("FILE_IO_FAILED","下载文件写入失败");return Object.defineProperty(i,"cause",{value:e,enumerable:!1}),i}function qy(e){return re(e)&&typeof e.code=="string"?e.code:void 0}function sf(){return y("FILE_TYPE_MISMATCH","下载目标类型不匹配")}function af(){return y("DOWNLOAD_CANCELLED","下载已取消")}function Qy(e){if(!e)return;const t=Object.keys(e).find(r=>My.has(r.trim().toLowerCase()));if(t)throw y("INVALID_PARAMS",`network.download 不允许设置请求头: ${t}`)}const Kc=8*1024*1024,Yy=32*1024*1024;function Xa(e){const t=new Map;let r=0;const n={signal:new AbortController().signal,lifecycle:"cleanup"},i=a=>a.remove(n).catch(()=>{}),o=async a=>{const c=t.get(a);c&&(t.delete(a),r-=c.size,await i(c.target))};e.signal.addEventListener("abort",()=>{for(const a of t.keys())o(a)},{once:!0});const s=a=>{if(e.signal.aborted||a.signal.aborted)throw y("DOWNLOAD_CANCELLED","存档下载已取消")};return{release:o,sizeOf:a=>t.get(a)?.size,async download(a,c,d){const u=a.file;if(!u||typeof u.file_id!="string"||typeof u.name!="string"||typeof u.size_bytes!="number"||!Number.isSafeInteger(u.size_bytes)||u.size_bytes<0||typeof a.download_url!="string"||typeof a.expires_at!="number"||!Number.isSafeInteger(a.expires_at))throw y("INVALID_RESPONSE","存档下载描述无效");if(u.size_bytes>Kc)throw y("FILE_TOO_LARGE","存档文件超过 8 MiB");const f={source:"runtime-private",credentials:"omit",route:"game-save",redirectPolicy:"error",method:"GET",target:{kind:"absolute-url",url:a.download_url},timeout:6e4};if(!Hl(f)||new URL(a.download_url).pathname!==`/cloud_archive/${u.file_id}.zip`||a.expires_at<=Date.now())throw y("INVALID_RESPONSE","存档下载地址无效");s(d);const l=Math.min(Kc,Yy-r);if(l<=0)throw y("FILE_QUOTA_EXCEEDED","当前会话存档缓存已达上限");const h=e.files.sandbox.file(`.hb-game-saves/${Ya()}.zip`);if(!h.remove)throw y("REQUEST_UNSUPPORTED","宿主不支持私有存档清理");r+=l;let m=!1;try{await e.files.sandbox.directory(".hb-game-saves").create({recursive:!0,exclusive:!1},d),await h.create({recursive:!0,exclusive:!0},d);const E=e.registry.createTransferScope();try{const p=E.registerFile(h,"game-save","readwrite");await of({request:f,url:new URL(a.download_url),to:p.ref,targetKind:"file",maxBytes:l},{...d,trustedUserGesture:!1,postEvent:()=>{},postProgress:()=>{}},{transfer:e.transfer,fileRegistry:E,operationContext:d})}finally{E.dispose()}s(d);const _=(await h.stat(d)).size;if(!Number.isSafeInteger(_)||_<0||_>l)throw y("FILE_TOO_LARGE","存档实际大小超过限额");await c(d),s(d);const w=async()=>{throw y("FILE_ACCESS_DENIED","存档文件只读")},S={kind:"file",mode:"read",name:u.name,create:w,write:w,async read(p){s(p),await c(p);const M=await h.read(p);try{if(s(p),await c(p),M.byteLength!==_)throw y("INVALID_RESPONSE","私有存档副本长度不匹配");return M}catch(z){throw M.fill(0),z}},async stat(p){return s(p),await c(p),await h.stat(p),s(p),await c(p),{kind:"file",size:_,...typeof u.modified_at=="number"&&Number.isSafeInteger(u.modified_at)?{modifiedAt:u.modified_at}:{}}}};return r-=l-_,t.set(S,{target:h,size:_}),m=!0,S}finally{m||(r-=l,await i(h))}}}}const Wy=/^(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 Zy(e){if(!e?.minimumSdkVersion)throw we("MINIMUM_SDK_VERSION_UNAVAILABLE","平台最低 SDK 版本配置不可用");const t=Zt(e.minimumSdkVersion),r=e.sdkVersion?Zt(e.sdkVersion):void 0;if(!t)throw we("MINIMUM_SDK_VERSION_UNAVAILABLE","平台最低 SDK 版本配置不合法");if(e.sdkVersion&&!r)throw we("SDK_VERSION_INVALID","小程序 SDK 版本不合法");const n=Zt("0.6.0");if(!r){if(ci(t,n)<0)return{heartbeatEnabled:!1,sdkVersion:void 0};throw we("SDK_VERSION_INVALID","小程序 SDK 版本缺失")}if((e.releaseChannel??"public")==="public"&&r.prerelease.length>0&&e.allowPublicPrerelease!==!0)throw we("SDK_VERSION_INVALID","正式小程序不能使用预发布 SDK");if(ci(r,t)<0)throw we("SDK_VERSION_TOO_LOW","小程序 SDK 版本低于平台最低要求");return{heartbeatEnabled:ci(r,Zt("0.6.0-0"))>=0,sdkVersion:e.sdkVersion}}function Ky(e,t){if(typeof t!="string"||!Zt(t))throw we("SDK_VERSION_INVALID","SDK handshake 版本不合法");if(t!==e)throw we("SDK_VERSION_MISMATCH","SDK handshake 版本与 Version record 不一致")}function ec(e,t){const r=Zt(e),n=Zt(t);if(!(!r||!n))return ci(r,n)}function Zt(e){const t=Wy.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 ci(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}function Jy(e){return{[yn]:async(t,r)=>{const n=Se(e.operationContext,r.signal);if(pe(n.signal),t!==void 0)throw y("INVALID_PARAMS","user.showAppreciation 不支持参数");if(!r.trustedUserGesture)throw y("USER_GESTURE_REQUIRED","请通过点击打开赞赏码");const i=e.miniProgramPresentation;if(!i?.name||!i.author)throw y("INVALID_STATE","缺少小程序名称或开发者信息,无法展示赞赏码");const o=e.presentation.showAppreciation;if(!o)throw y("REQUEST_UNSUPPORTED","当前宿主不支持赞赏码");await fe(()=>o({name:i.name,author:i.author},n),n.signal)}}}function hr(){const e=new Error("Runtime cache read cancelled");return e.name="AbortError",e}function Jc(e,t){return e.length===t.length&&e.every((r,n)=>r===t[n])}function cf(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(E,_){try{e.onEvent&&Promise.resolve(e.onEvent({namespace:E,type:_})).catch(()=>{})}catch{}}function u(E){const _=r.get(E);if(!_)throw new Error("Unknown runtime cache scope");return _}function f(E,_){return E.flatMap((w,S)=>{const p=JSON.stringify(E.slice(0,S+1));return[JSON.stringify([p]),JSON.stringify([p,_])]})}function l(E,_){return JSON.stringify(f(E,_).map(w=>n.get(w)??0))}async function h(E,_){const w=u(E),S=JSON.stringify([JSON.stringify(w),..._?[_]:[]]),p=(n.get(S)??0)+1;n.set(S,p),i.add(S);for(const M of a)M(w,_);if(!e.store){i.delete(S),d(_??"*","invalidation");return}try{await e.store.invalidate(w,_)}catch(M){throw d(_??"*","storage_error"),M}n.get(S)===p&&i.delete(S),d(_??"*","invalidation")}function m(E){if(c)throw new Error("Runtime cache manager disposed");const _=o.get(E.namespace);if(_){if(_.sourceCodec!==E.codec||_.definition.codec.version!==E.codec.version||JSON.stringify(_.definition.policy)!==JSON.stringify(E.policy))throw new Error("Conflicting runtime cache namespace");return _.cache}if(!E.namespace||!E.codec.version)throw new Error("Invalid runtime cache definition");const w=Object.freeze({...E.policy}),S=Object.freeze({version:E.codec.version,encode:E.codec.encode.bind(E.codec),decode:E.codec.decode.bind(E.codec),validate:E.codec.validate.bind(E.codec),clone:E.codec.clone.bind(E.codec)}),p=E.namespace;for(const L of[w.ttlMs,w.memoryMaxEntries,w.diskMaxEntries,w.diskMaxBytes,w.maxEntryBytes])if(!Number.isFinite(L)||L<0)throw new Error("Invalid runtime cache policy");const M=new Map,z=new Map,A=new Map;let D=!1;function I(L,C,H){if(c||D||L.aborted||l(C,p)!==H)throw hr()}function v(L){return w.ttlMs>0&&w.persistence==="memory-and-disk"&&!!e.store&&!f(L,p).some(C=>i.has(C))}function T(L,C,H){const F=t();return L.envelopeVersion===1&&JSON.stringify(L.address)===JSON.stringify(C)&&Jc(L.revisions,H)&&L.payload.byteLength<=w.maxEntryBytes&&Number.isFinite(L.cachedAt)&&Number.isFinite(L.expiresAt)&&L.cachedAt<=F&&L.cachedAt>=0&&L.expiresAt>L.cachedAt&&Math.min(L.expiresAt,L.cachedAt+w.ttlMs)>F}function x(L,C,H,F,$){if(!(w.ttlMs<=0||w.memoryMaxEntries<1)){for(const[K,g]of M)Math.min(g.entry.expiresAt,g.entry.cachedAt+w.ttlMs)<=t()&&M.delete(K);for(M.delete(L);M.size>=Math.floor(w.memoryMaxEntries);){const K=M.keys().next();if(K.done)break;M.delete(K.value)}M.set(L,{entry:C,value:H,epoch:F,persistent:$})}}async function N(L,C,H,F){const $={namespace:p,codecVersion:S.version,scopeIds:C,key:L.key},K=JSON.stringify($);let g=[],P=v(C);if(P)try{g=await e.store.readRevisions(C,p)}catch{P=!1,d(p,"storage_error")}I(F.signal,C,H);async function B(){if(!P)return!0;try{return Jc(g,await e.store.readRevisions(C,p))}catch{return P=!1,d(p,"storage_error"),!1}}const Q=M.get(K);if(w.ttlMs>0&&Q&&Q.epoch===H&&T(Q.entry,$,g)&&Q.persistent===P&&await B())return I(F.signal,C,H),d(p,"memory_hit"),Q.value;if(M.delete(K),P){let ie,ue;try{ie=await e.store.read($,w.maxEntryBytes),ie&&T(ie,$,g)?ue=S.decode(ie.payload):ie=void 0}catch{ie=void 0,d(p,"storage_error")}if(I(F.signal,C,H),ie&&await B())return I(F.signal,C,H),x(K,ie,ue,H,!0),d(p,"disk_hit"),ue}d(p,"miss");const X=S.validate(await L.load(F.signal));I(F.signal,C,H);const ne=S.clone(X);if(!await B()&&P)throw hr();if(I(F.signal,C,H),w.ttlMs>0){const ie=t();let ue;try{ue=S.encode(ne)}catch{return ne}const Ee={envelopeVersion:1,address:$,revisions:P?g:[],cachedAt:ie,expiresAt:ie+w.ttlMs,payload:ue};if(P&&ue.byteLength<=w.maxEntryBytes){let me=!0,ge=!1;try{me=await e.store.publish(Ee,w),ge=me}catch{d(p,"storage_error")}if(I(F.signal,C,H),!me)throw hr();ge&&d(p,"published")}I(F.signal,C,H),x(K,Ee,ne,H,P)}return ne}async function b(L){if(c||D||L.signal?.aborted)return Promise.reject(hr());const C=u(L.scope),H=l(C,p);let F;if(v(C)){const P=new AbortController;A.set(P,C);const B=()=>P.abort();L.signal?.addEventListener("abort",B,{once:!0});let Q=()=>{};try{F=await Promise.race([e.store.readRevisions(C,p),new Promise((X,ne)=>{const ie=()=>ne(hr());P.signal.addEventListener("abort",ie,{once:!0}),Q=()=>P.signal.removeEventListener("abort",ie)})])}catch{P.signal.aborted||d(p,"storage_error")}finally{Q(),A.delete(P),L.signal?.removeEventListener("abort",B)}}I(L.signal??new AbortController().signal,C,H);const $=JSON.stringify([C,L.key,H,F]);let K=z.get($);if(K?.controller.signal.aborted&&(K=void 0),!K){const P=new AbortController;K={ids:C,controller:P,waiters:0,promise:Promise.resolve(void 0)};const B=K;B.promise=N(L,C,H,P).finally(()=>{z.get($)===B&&z.delete($)}),z.set($,B)}const g=K;return g.waiters+=1,new Promise((P,B)=>{let Q=!1;function X(ie){Q||(Q=!0,L.signal?.removeEventListener("abort",ne),g.controller.signal.removeEventListener("abort",ne),g.waiters-=1,g.waiters===0&&g.controller.abort(),ie())}function ne(){X(()=>B(hr()))}L.signal?.addEventListener("abort",ne,{once:!0}),g.controller.signal.addEventListener("abort",ne,{once:!0}),g.promise.then(ie=>X(()=>{try{I(L.signal??new AbortController().signal,C,H),P(S.clone(ie))}catch(ue){B(ue)}}),ie=>X(()=>B(ie)))})}function O(L,C){if(C&&C!==p)return;const H=F=>L.every(($,K)=>F[K]===$);for(const[F,$]of M)H($.entry.address.scopeIds)&&M.delete(F);for(const[F,$]of z)H($.ids)&&($.controller.abort(),z.delete(F));for(const[F,$]of A)H($)&&F.abort()}function j(){if(!D){D=!0,M.clear();for(const L of A.keys())L.abort();A.clear();for(const L of z.values())L.controller.abort();z.clear(),s.delete(j),a.delete(O),o.get(p)?.cache===U&&o.delete(p)}}const U={read:b,invalidateScope:L=>h(L,p),dispose:j};return s.add(j),a.add(O),o.set(p,{definition:{namespace:p,codec:S,policy:w},sourceCodec:E.codec,cache:U}),U}return{createScope(E,_){if(c||!E)throw new Error("Invalid runtime cache scope");const w=Object.freeze({});return r.set(w,[..._?u(_):[],E]),w},register:m,invalidateScope:E=>h(E),dispose(){if(!c){c=!0;for(const E of[...s])E();o.clear(),n.clear(),i.clear()}}}}function Xy(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 eE=".hb-runtime-cache-v1",tE=1e3,Ko=64*1024,mr=1e3,rE=2048,Zr=32*1024*1024,nE=1024,di=new TextEncoder,Xc=new TextDecoder("utf-8",{fatal:!0});function Kr(){return Object.assign(new Error("缓存文件操作已取消"),{name:"AbortError"})}async function Qn(e){const t=await globalThis.crypto.subtle.digest("SHA-256",di.encode(JSON.stringify(e)));return Array.from(new Uint8Array(t),r=>r.toString(16).padStart(2,"0")).join("")}function ht(e,t){return JSON.stringify(e)===JSON.stringify(t)}function ed(){return Array.from(globalThis.crypto.getRandomValues(new Uint8Array(16)),e=>e.toString(16).padStart(2,"0")).join("")}function iE(e){return!!e&&typeof e=="object"&&["METHOD_FORBIDDEN","NOT_SUPPORTED","UNSUPPORTED_OPERATION","ENOSYS","ENOTSUP","EOPNOTSUPP"].includes(String(e.code))}function td(e,t){if(t.some(r=>typeof e[r]!="function"))throw Object.assign(new Error("Host 文件原语不完整,关闭磁盘缓存"),{code:"METHOD_FORBIDDEN"})}function oE(e,t){const r=e.sandbox.directory(eE),n=r.directory("revisions"),i=r.directory("entries");for(const N of[r,n,i,i.directory("capability-check")])td(N,["directory","file","create","stat","list","remove"]),td(N.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(N){d=N,o.abort(),t.signal.removeEventListener("abort",s)}function f(N){if(iE(N))throw u(N),N}function l(){if(d)throw d;if(a.signal.aborted)throw Kr()}function h(N,b=a.signal){const O=c.then(()=>{if(b.aborted)throw d??Kr();return l(),N()},()=>{if(b.aborted)throw d??Kr();return l(),N()}).catch(C=>{throw f(C),C});if(c=O.catch(()=>{}),b.aborted)return Promise.reject(d??Kr());let j=()=>{};const U=new Promise((C,H)=>{const F=()=>H(d??Kr());b.addEventListener("abort",F,{once:!0}),j=()=>b.removeEventListener("abort",F)}),L=setTimeout(()=>{u(Object.assign(new Error("缓存文件操作超时,已降级为内存缓存"),{code:"CACHE_STORAGE_TIMEOUT"}))},tE);return Promise.race([O,U]).finally(()=>{clearTimeout(L),j()})}async function m(){l(),await n.create({recursive:!0,exclusive:!1},a),l(),await i.create({recursive:!0,exclusive:!1},a),l()}async function E(N,b){const O=n.file(`${await Qn([N,b??null])}.revision`);await w(O);let j=!1;try{await O.create({recursive:!1,exclusive:!0},a),j=!0}catch(C){f(C),l()}if(j){const C=ed();return await O.write(di.encode(C),a),l(),C}const U=await O.stat(a);if(U.size<1||U.size>128)throw new Error("缓存 revision 文件损坏");const L=Xc.decode(await O.read(a));if(!/^(?:[0-9a-f]{32}|[0-9a-f-]{36})$/.test(L))throw new Error("缓存 revision 文件损坏");return l(),L}async function _(N){const b=await N.list({limit:mr},a);if(b.length>=mr)throw new Error("缓存目录超过治理上限");return b}async function w(N){try{await N.stat(a);return}catch(O){if(!Yn(O))throw O}if((await _(n)).length>=mr-1)throw new Error("缓存 metadata 超过治理上限")}async function S(N,b){await m();const O=[];for(let j=0;j<N.length;j+=1){const U=N.slice(0,j+1);O.push(await E(U),await E(U,b))}return O}async function p(N){return r.directory(`entries/${await Qn([N.namespace,N.codecVersion,N.scopeIds])}`)}async function M(N){return(await p(N)).file(`${await Qn(N.key)}.cache`)}async function z(N,b){const O=await N.stat(a);if(O.size<5||O.size>b+Ko+4)throw new Error("缓存条目超过大小限制");const j=await N.read(a);if(l(),j.length!==O.size)throw new Error("缓存条目读取不完整");const U=new DataView(j.buffer,j.byteOffset,j.byteLength).getUint32(0);if(U<1||U>Ko||U+4>j.length)throw new Error("缓存信封损坏");const L=JSON.parse(Xc.decode(j.subarray(4,U+4))),C=j.slice(U+4);if(L.envelopeVersion!==1||!L.address||!Array.isArray(L.address.scopeIds)||!L.address.scopeIds.every(H=>typeof H=="string")||typeof L.address.namespace!="string"||typeof L.address.codecVersion!="string"||typeof L.address.key!="string"||!Array.isArray(L.revisions)||L.revisions.length!==L.address.scopeIds.length*2||!L.revisions.every(H=>typeof H=="string"&&H.length>0)||!Number.isSafeInteger(L.cachedAt)||!Number.isSafeInteger(L.expiresAt)||L.cachedAt<0||L.expiresAt<=L.cachedAt||L.payloadBytes!==C.length||C.length>b)throw new Error("缓存信封损坏");return{envelopeVersion:1,address:L.address,revisions:L.revisions,cachedAt:L.cachedAt,expiresAt:L.expiresAt,payload:C}}async function A(N){if(!N.remove)throw new Error("Host 不支持缓存文件删除");await N.remove(a)}async function D(N){try{if((await N.file.stat(a)).size!==N.size)return!1;const b=await z(N.file,Zr);return!ht(b.address,N.entry.address)||!ht(b.revisions,N.entry.revisions)||b.cachedAt!==N.entry.cachedAt||b.expiresAt!==N.entry.expiresAt||!ht(await I(b.payload),await I(N.entry.payload))?!1:(await A(N.file),!0)}catch(b){if(Yn(b))return!0;throw b}}async function I(N){const b=await globalThis.crypto.subtle.digest("SHA-256",N);return Array.from(new Uint8Array(b),O=>O.toString(16).padStart(2,"0")).join("")}async function v(){const N=await _(n);let b=0;for(const L of N)if(L.kind==="file"&&(b+=(await L.stat(a)).size,b>Zr))throw new Error("缓存扫描超过字节上限");const O=[];let j=0,U=b;for(const L of await _(i)){if(L.kind!=="directory")throw new Error("缓存目录结构损坏");for(const C of await _(L)){if(C.kind!=="file"||++j>rE)throw new Error("缓存文件超过治理上限");const H=(await C.stat(a)).size;if(U+=H,U>Zr)throw new Error("缓存扫描超过字节上限");try{const F=await z(C,Zr);O.push({file:C,entry:F,size:(await C.stat(a)).size,bucketName:L.name})}catch(F){f(F),l(),Yn(F)||await A(C)}}}return{entries:O,metadataBytes:b}}async function T(){for(const N of await _(i))if(N.kind==="directory"&&N.remove&&(await _(N)).length===0)try{await N.remove({recursive:!1},a)}catch(b){f(b),l()}}function x(N){const{payload:b,...O}=N,j=di.encode(JSON.stringify({...O,payloadBytes:b.length}));if(j.length>Ko)throw new Error("缓存信封过大");const U=new Uint8Array(4+j.length+b.length);return new DataView(U.buffer).setUint32(0,j.length),U.set(j,4),U.set(b,j.length+4),U}return{readRevisions:(N,b)=>h(()=>S(N,b)),read:(N,b)=>h(async()=>{l();const O=await M(N);let j;try{j=await z(O,b)}catch(U){if(l(),Yn(U))return;throw U}if(!(!ht(j.address,N)||j.expiresAt<=Date.now())&&ht(j.revisions,await S(N.scopeIds,N.namespace)))return j}),publish:(N,b)=>h(async()=>{l();const{address:O}=N;if(!ht(N.revisions,await S(O.scopeIds,O.namespace)))return!1;const j=x(N);if(N.payload.length>b.maxEntryBytes||j.length>b.diskMaxBytes||b.diskMaxEntries<1)throw new Error("缓存条目超出容量预算");await m();const U=await p(O),L=await M(O),C=await v(),H=[],F=new Map;for(const g of C.entries){if(g.bucketName===U.name&&g.file.name===L.name)continue;const P=JSON.stringify([g.entry.address.scopeIds,g.entry.address.namespace]);let B=F.get(P);if(B||(B=await S(g.entry.address.scopeIds,g.entry.address.namespace),F.set(P,B)),g.entry.expiresAt<=Date.now()||!ht(g.entry.revisions,B)){if(!await D(g))throw new Error("缓存治理期间条目已变化")}else H.push(g)}H.sort((g,P)=>g.entry.cachedAt-P.entry.cachedAt);function $(){const g=H.filter(P=>P.bucketName===U.name);return H.length+1>nE||j.length+C.metadataBytes+H.reduce((P,B)=>P+B.size,0)>Zr||g.length+1>Math.min(b.diskMaxEntries,mr-1)||j.length+g.reduce((P,B)=>P+B.size,0)>b.diskMaxBytes}for(;$();){const g=H.filter(Q=>Q.bucketName===U.name),B=g.length+1>Math.min(b.diskMaxEntries,mr-1)||j.length+g.reduce((Q,X)=>Q+X.size,0)>b.diskMaxBytes?g[0]:H[0];if(!B||!await D(B))throw new Error("缓存容量不足或条目已变化");H.splice(H.indexOf(B),1)}await T();const K=await _(i);if(!K.some(g=>g.name===U.name)&&K.length>=mr-1)throw new Error("缓存目录超过治理上限");if(await U.create({recursive:!0,exclusive:!1},a),!ht(N.revisions,await S(O.scopeIds,O.namespace)))return!1;try{await L.create({recursive:!1,exclusive:!0},a)}catch(g){f(g),await L.stat(a)}return await L.write(j,a),l(),ht(N.revisions,await S(O.scopeIds,O.namespace))}),invalidate:(N,b)=>h(async()=>{await m();const O=n.file(`${await Qn([N,b??null])}.revision`);await w(O);try{await O.create({recursive:!1,exclusive:!0},a)}catch(j){f(j),await O.stat(a)}await O.write(di.encode(ed()),a),l();try{const{entries:j}=await v();for(const U of j){if(b!==void 0&&U.entry.address.namespace!==b||!N.every((C,H)=>U.entry.address.scopeIds[H]===C))continue;const L=await S(U.entry.address.scopeIds,U.entry.address.namespace);ht(U.entry.revisions,L)||await D(U)}await T()}catch(j){f(j),l()}})}}function Yn(e){return!!e&&typeof e=="object"&&["FILE_NOT_FOUND","ENOENT","NOT_FOUND"].includes(String(e.code))}const sE="RATE_LIMITED_BY_RUNTIME",aE="RATE_LIMITED",df=20,uf=40,lf=150,ff=20,hf=1e4,mf=45e3,gf=1,cE=300*1e3,dE=64;function gr(e,t){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:t}function uE(e,t){return typeof e=="number"&&Number.isFinite(e)&&e>=0?Math.floor(e):t}function lE(e={}){const t=e.now??Date.now,r=uE(e.coalesceWindowMs,lf),n=e.budget===!1?void 0:{ratePerSecond:Math.max(.001,gr(e.budget?.ratePerSecond,df)),burst:Math.max(1,Math.floor(gr(e.budget?.burst,uf)))},i=e.loopDetection===!1?void 0:{maxCalls:Math.max(1,Math.floor(gr(e.loopDetection?.maxCalls,ff))),windowMs:Math.max(1,Math.floor(gr(e.loopDetection?.windowMs,hf)))},o=e.circuitBreaker===!1?void 0:{failureThreshold:Math.max(1,Math.floor(gr(e.circuitBreaker?.failureThreshold,gf))),openMs:Math.max(1,Math.floor(gr(e.circuitBreaker?.openMs,mf)))},s=new Map,a=new Map,c=new Set,d=new Map,u=n?{tokens:n.burst,updatedAt:t()}:{tokens:0,updatedAt:0},f={coalesced:0,budgetRejected:0,loopRejected:0,circuitOpened:0,circuitRejected:0};let l=!1;function h(D){try{e.onReport?.(D)}catch{}}function m(D,I){if(!i)return{exceeded:!1,count:0};const v=a.get(D)??[],T=I-i.windowMs;let x=0;for(;x<v.length&&v[x]<=T;)x+=1;x>0&&v.splice(0,x);const N=v.length>=i.maxCalls;return N||(v.push(I),v.length>i.maxCalls+1&&v.splice(0,v.length-(i.maxCalls+1))),a.set(D,v),{exceeded:N,count:v.length}}function E(D){if(!n)return!0;const I=Math.max(0,D-u.updatedAt)/1e3;return u.tokens=Math.min(n.burst,u.tokens+I*n.ratePerSecond),u.updatedAt=D,u.tokens<1?!1:(u.tokens-=1,!0)}function _(D){if(!n)return 0;const I=Math.max(0,D-u.updatedAt)/1e3,v=Math.min(n.burst,u.tokens+I*n.ratePerSecond);return Math.max(0,Math.ceil((1-v)/n.ratePerSecond*1e3))}function w(D,I,v,T,x){if(!o)return;const N=d.get(I),b=(N?.open?0:N?.failures??0)+1;if(b<o.failureThreshold){d.set(I,{open:!1,openedAt:0,openMs:0,failures:b});return}const O=Math.min(Math.max(o.openMs,T),cE);d.set(I,{open:!0,openedAt:x,openMs:O,failures:b}),f.circuitOpened+=1,h({type:"circuit_opened",capability:D,endpointId:I,status:v,openMs:O,timestamp:x})}function S(D){const I=d.get(D);I&&!I.open&&d.delete(D)}function p(D){for(const[I,v]of s)!v.pending&&v.expiresAt<=D&&s.delete(I);for(;s.size>=dE;){const I=[...s].find(([,v])=>!v.pending);if(!I)break;s.delete(I[0])}}function M(D,I){if(D===void 0)return;const v=s.get(D);v?.promise===I&&(v.pending=!1)}function z(D,I){if(D===void 0)return;s.get(D)?.promise===I&&s.delete(D)}async function A(D){if(l)return D.load();const I=t();if(o){const N=d.get(D.endpointId);if(N?.open){const b=N.openedAt+N.openMs-I;if(b>0)throw f.circuitRejected+=1,h({type:"circuit_rejected",capability:D.capability,endpointId:D.endpointId,retryAfterMs:b,timestamp:I}),mE("上游已被网关限流,Runtime 熔断中,请稍后重试",{origin:"circuit",reason:"circuit_open",endpointId:D.endpointId,retryAfterMs:b});d.delete(D.endpointId)}}const v=m(D.endpointId,I);v.exceeded&&i?c.has(D.endpointId)||(c.add(D.endpointId),h({type:"loop_detected",capability:D.capability,endpointId:D.endpointId,count:v.count,windowMs:i.windowMs,timestamp:I})):c.delete(D.endpointId);const T=r>0?D.coalesceKey:void 0;if(T!==void 0){const N=s.get(T);if(N&&(N.pending||N.expiresAt>I))return f.coalesced+=1,h({type:"coalesced",capability:D.capability,endpointId:D.endpointId,timestamp:I}),N.promise;N&&s.delete(T)}if(v.exceeded&&i)throw f.loopRejected+=1,rd("检测到同一 endpoint 的高频循环调用,本次请求已在 Runtime 本地拒绝",{origin:"loop",reason:"loop",capability:D.capability,endpointId:D.endpointId,count:v.count,windowMs:i.windowMs});if(!E(I)){f.budgetRejected+=1;const N=_(I);throw h({type:"budget_exhausted",capability:D.capability,endpointId:D.endpointId,retryAfterMs:N,timestamp:I}),rd("请求过于频繁,已触发 Runtime 本地配额限制",{origin:"budget",reason:"budget",capability:D.capability,endpointId:D.endpointId,retryAfterMs:N})}T!==void 0&&p(I);const x=D.load().then(N=>(M(T,x),S(D.endpointId),N),N=>{z(T,x);const b=fE(N);throw b!==void 0&&w(D.capability,D.endpointId,b,hE(N),I),N});return T!==void 0&&s.set(T,{endpointId:D.endpointId,promise:x,expiresAt:I+r,pending:!0}),x}return{execute:A,invalidateCoalescing(D){if(D===void 0){s.clear();return}for(const[I,v]of s)D.includes(v.endpointId)&&s.delete(I)},snapshot(){return{...f,openCircuits:[...d.entries()].filter(([,D])=>D.open).map(([D])=>D)}},dispose(){l||(l=!0,s.clear(),a.clear(),c.clear(),d.clear())}}}function fE(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 hE(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 rd(e,t){return{code:sE,message:e,data:t}}function mE(e,t){return{code:aE,message:e,data:t}}const pf=3e4,yf=6e4,Zs=1440*60*1e3;function gE(e){const t=e!==!1&&(e?.enabled??!0),r=e===!1?void 0:e;return{enabled:t,debugReport:t&&r?.debugReport===!0,identityTtlMs:t?Math.max(0,Math.floor(r?.identityTtlMs??pf)):0,profileTtlMs:t?Math.max(0,Math.floor(r?.profileTtlMs??yf)):0,steamGameListTtlMs:t?pE(r?.steamGameListTtlMs):0,gateOptions:{budget:r?.budget??{ratePerSecond:df,burst:uf},coalesceWindowMs:r?.coalesceWindowMs??lf,loopDetection:r?.loopDetection??{maxCalls:ff,windowMs:hf},circuitBreaker:r?.circuitBreaker??{failureThreshold:gf,openMs:mf}}}}function pE(e){return e===void 0||!Number.isFinite(e)?Zs:Math.max(0,Math.floor(e))}function yE(e){return typeof e=="object"&&e!==null}function Te(e,t){const r=e.data;if(!yE(r)||typeof r.status!="string")throw new Error(t);return r}const Ef={auth:"optional",channel:"api",id:"heybox.account.user_base_info.envelope.get",method:"GET",path:"/account/get_user_base_info"},EE={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 Te(e,"工坊小程序详情加载失败")}};function Un(e){const t=e.runtimeAuthContextToken?.trim();return{mini_program_id:e.miniProgramId,...t?{runtime_auth_context_token:t}:{}}}function wE(e){return{challenge:e.challenge,expiresIn:e.expires_in,requestedScopes:e.requested_scopes||[],displayedScopes:e.displayed_scopes||[],consentUiVersion:e.consent_ui_version}}function IE(e){const t=Te(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=wE(r.consent_challenge)),{...t,result:n}}const AE={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=>({...Un(e.runtimeContext),challenge:e.challenge}),parse:e=>Te(e,"小程序授权取消接口响应异常")},_E={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=>Un(e.runtimeContext),parse:e=>Te(e,"小程序授权撤销接口响应异常")},DE={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=>Un(e.runtimeContext),parse(e){const t=Te(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}:{}}}}},NE={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=>({...Un(e.runtimeContext),...e.scopes?.length?{scopes:e.scopes.join(",")}:{}}),parse:e=>IE(e)},ME={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=>({...Un(e.runtimeContext),challenge:e.challenge,...e.selectedScopes.length?{selected_scopes:e.selectedScopes.join(",")}:{}}),parse(e){const t=Te(e,"小程序登录确认接口响应异常");return{...t,result:{code:t.result.code,expiresIn:t.result.expires_in,scopes:t.result.scopes}}}},SE=64;function wf(e){const t=e.ttlMs,r=Math.max(1,Math.floor(e.maxEntries??SE)),n=e.now??Date.now,i=new Map,o=new Map;let s=0,a=!1;function c(f){for(const[l,h]of i)h.expiresAt<=f&&i.delete(l)}function d(f,l,h){if(a||t<=0||h!==s)return;const m=n();for(c(m),i.delete(f);i.size>=r;){const E=i.keys().next();if(E.done)break;i.delete(E.value)}i.set(f,{expiresAt:m+t,value:l})}function u(f,l){if(a)return l();if(t>0){const _=i.get(f);if(_&&_.expiresAt>n())return Promise.resolve(_.value);_&&i.delete(f)}const h=o.get(f);if(h)return h;const m=s,E=l().then(_=>(d(f,_,m),_)).finally(()=>{o.get(f)===E&&o.delete(f)});return o.set(f,E),E}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 bE(e,t){return t?e?"server":"local":"legacy"}function TE(e,t){if(e==="local")throw y("SERVER_API_REQUIRED",`${t} 需要 effective network 启用后才能使用`)}const vE=["baseURL","errorMode","jsonParseMode","observability","queryEncoding","responseType","security"],OE=new Set(["auth","body","bodyEncoding","channel","failurePresentation","headers","id","method","parse","path","query","timeout"]),RE=/authorization|cookie|pkey|password|secret|token/i,If=/authorization|cookie|pkey|token|password|secret/i;function mt(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function kE(e){for(const t of Object.keys(e))if(!OE.has(t))throw new Le(`endpoint 字段不受 hb-sdk-runtime private mapper 支持: ${t}`);for(const t of vE)if(Object.prototype.hasOwnProperty.call(e,t)&&mt(e,t)!==void 0)throw new Le(`endpoint 字段不受 hb-sdk-runtime private mapper 支持: ${t}`);if(mt(e,"bodyEncoding")!==void 0&&mt(e,"bodyEncoding")!=="json"&&mt(e,"bodyEncoding")!=="form")throw new Le("endpoint bodyEncoding 不受 HostNetworkPort 支持");if(mt(e,"failurePresentation")!==void 0&&mt(e,"failurePresentation")!=="none")throw new Le("endpoint failurePresentation 必须为 none");if(mt(e,"auth")!==void 0&&mt(e,"auth")!=="none"&&mt(e,"auth")!=="optional"&&mt(e,"auth")!=="required")throw new Le("endpoint auth 必须为 none、optional 或 required")}function oo(e){if(Array.isArray(e))return e.map(oo);if(!e||typeof e!="object")return e;const t=e,r={};for(const[n,i]of Object.entries(t))RE.test(n)||(r[n]=oo(i));return r}function nd(e){if(!e)return;const t={};for(const[r,n]of Object.entries(e))If.test(r)||(t[r]=n);return t}function PE(e){if(!e)return;const t=Object.keys(e).find(r=>If.test(r));if(t)throw new Le(`endpoint 禁止声明 credential-bearing header: ${t}`)}class xn 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 id=1440*60*1e3,CE=/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun)\b/i;function LE(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,id):void 0}if(!CE.test(n))return;const i=Date.parse(n);if(!Number.isFinite(i))return;const o=i-t();return o>0?Math.min(o,id):void 0}function UE(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 Af(e,t){Object.defineProperty(e,"cause",{configurable:!1,enumerable:!1,value:t,writable:!1})}class Cr extends Error{code="INTERNAL_ENDPOINT_REQUEST_FAILED";endpointId;constructor(t){super(`内部 endpoint 请求执行失败: ${t.endpointId}`),this.name="InternalEndpointRequestError",this.endpointId=t.endpointId,Af(this,t.cause),Object.setPrototypeOf(this,new.target.prototype)}}class zn extends Error{code="INTERNAL_ENDPOINT_PARSE_FAILED";endpointId;constructor(t){super(`内部 endpoint 响应解析失败: ${t.endpointId}`),this.name="InternalEndpointParseError",this.endpointId=t.endpointId,Af(this,t.cause),Object.setPrototypeOf(this,new.target.prototype)}}function xE(e,t,r,n,i,o,s,a){return{config:{auth:e.auth,body:oo(i),bodyEncoding:e.bodyEncoding,channel:e.channel,credentials:s.credentials,headers:nd(o),method:e.method,metadata:{endpointId:e.id},query:oo(n),timeout:e.timeout,url:r},data:a.data,headers:nd(a.headers)||{},status:a.status,statusText:a.statusText}}async function Po(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(kE(t),typeof t.id!="string"||!t.id)throw new Le("endpoint id 必须为非空字符串");if(!["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"].includes(t.method))throw new Le("endpoint method 不受 HostNetworkPort 支持");const i=typeof t.path=="function"?await t.path(r):t.path;if(typeof i!="string"||!i)throw new Le("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;PE(a);const c=async()=>{let f;try{f=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(h){throw h instanceof Le?h:new Cr({endpointId:t.id,cause:h})}if(f.status<200||f.status>=300)throw new xn({endpointId:t.id,status:f.status,responseData:f.data,retryAfterMs:LE(f.headers)});const l=xE(t,r,i,o,s,a,n,f);if(t.parse)try{return await t.parse(l,r)}catch(h){throw new zn({endpointId:t.id,cause:h})}return l.data},d=n.gate;if(!d)return c();const u=UE(t,o,s,n.credentials);return d.gate.execute({capability:d.capability,endpointId:t.id,...u===void 0?{}:{coalesceKey:u},load:c})}const zE=new Set(["MINIPROGRAM_UNAVAILABLE","RUNTIME_CONTEXT_INVALID","CAPABILITY_NOT_GRANTED","AUTHORIZATION_CONTEXT_CHANGED","SERVER_API_REQUIRED","AUTHORIZATION_CANCELLED"]),jE=new Set(kr),tc="steam_account",_f=new Set(kr.filter(e=>e!==tc)),BE=1e3;function HE(e){const t=new Set,r=wf({ttlMs:Math.max(0,Math.floor(e.identityTtlMs??pf))}),n=new Set;let i=0,o=!1,s=Promise.resolve(),a;const c=e.steamAccount===!0,d=e.userDataMode??bE(e.networkEnabled===!0,c),u=e.requestPolicyEnabled!==!1,f=e.requestGate?{capability:"auth",gate:e.requestGate}:void 0;async function l(){if(!c&&!e.authorizationContext)return{};if(!e.authorizationContext)throw y("METHOD_FORBIDDEN","新能力版本缺少 Runtime auth context Port");let C;try{C=await e.authorizationContext.get(e.operationContext)}catch(F){throw Js(F)?Jo(F.code,F.message,F):Jo("REQUEST_FAILED","读取 Runtime auth context 失败",F)}if(C.steamAccount!==c||C.userDataMode!==d)throw y("AUTHORIZATION_CONTEXT_CHANGED","Runtime auth context 已变化,请重新打开小程序");const H=C.token.trim();if(!H)throw y("REQUEST_FAILED","Runtime auth context 为空");return{runtimeAuthContextToken:H}}const h=e.account.onChange(C=>{if(m(),E("heybox_app_login_change",C?{isHeyboxAppLoggedIn:!0}:{isHeyboxAppLoggedIn:!1,accountKey:null}),C&&e.account.getAccountKey){const H=i;z().then(F=>{!o&&i===H&&E("heybox_app_login_change",F)}).catch(()=>{})}});function m(){i+=1,a?.abort(),r.invalidate(),e.requestGate?.invalidateCoalescing(),n.clear()}function E(C,H){C==="user_info_authorization_change"&&QE(H)&&r.invalidate();for(const F of t)try{F(C,H)}catch{}}function _(){const C=e.identity.get()?.miniProgramId?.trim();if(!C)throw y("INVALID_STATE","当前能力缺少 canonical 小程序身份");return C}function w(){if(o||e.operationContext.signal.aborted)throw y("RUNTIME_DESTROYED","小程序 Runtime 已终止")}async function S(){w();let C;try{C=await e.account.getCurrentUserId(e.operationContext)}catch(H){throw cd(H,e.operationContext.signal,"读取小黑盒账号失败")}return typeof C=="string"&&C.trim()?C.trim():void 0}async function p(C,H){const F=await S();if(i!==H||F!==C)throw y("AUTHORIZATION_CONTEXT_CHANGED","授权期间账号上下文已变化,请重新操作")}async function M(C,H,F=_()){if(!e.account.getAccountKey)throw y("METHOD_FORBIDDEN","Host 不支持持久化账号比较");let $;try{$=await e.account.getAccountKey(F,C,e.operationContext)}catch{throw w(),y("REQUEST_FAILED","读取本地账号标识失败")}if(await p(C,H),_()!==F)throw y("AUTHORIZATION_CONTEXT_CHANGED","读取期间小程序上下文已变化");if(typeof $!="string"||!$.trim())throw y("INVALID_RESPONSE","Host 返回了无效的账号标识");return $}async function z(){const C=_(),H=i,F=await S();if(w(),i!==H)throw y("AUTHORIZATION_CONTEXT_CHANGED","读取期间账号上下文已变化");return F?{isHeyboxAppLoggedIn:!0,accountKey:await M(F,H,C)}:{isHeyboxAppLoggedIn:!1,accountKey:null}}async function A(C){w();try{await e.account.ensureAuthenticated({trustedUserGesture:C,reason:"runtime_auth",signal:e.operationContext.signal})}catch(F){throw cd(F,e.operationContext.signal,"小黑盒登录失败")}const H=await S();if(!H)throw y("HEYBOX_APP_LOGIN_REQUIRED","请先登录小黑盒");return H}async function D(C,H,F=e.operationContext.signal){try{if(F.aborted)throw Ks();return await qE(Po(e.network,C,H,{...e.operationContext,credentials:"heybox-session",signal:F,...f?{gate:f}:{}}),F)}catch($){throw e.operationContext.signal.aborted?y("RUNTIME_DESTROYED","小程序 Runtime 已终止"):$ instanceof Le?y("REQUEST_UNSUPPORTED",$.message):$ instanceof zn?y("INVALID_RESPONSE","授权接口响应不合法"):$ instanceof Cr?y("REQUEST_FAILED","授权请求失败"):$ instanceof xn?u&&($.status===403||$.status===429)?y("RATE_LIMITED","授权请求已被网关限流,请稍后重试",{status:$.status,...$.retryAfterMs===void 0?{}:{retryAfterMs:$.retryAfterMs}}):y("REQUEST_FAILED",$.message):Js($)?$:y("REQUEST_FAILED","授权请求失败")}}async function I(C,H){await D(AE,{runtimeContext:{miniProgramId:C,...await l()},challenge:H}).catch(()=>{})}function v(C){const H=async()=>{const $=sd(e.operationContext.signal);a=$;try{return await C($.signal)}finally{a===$&&(a=void 0),$.abort()}},F=s.then(H,H);return s=F.then(()=>{},()=>{}),F}async function T(C,H,F,$,K){if(!F)throw await I(C,H.challenge),y("USER_GESTURE_REQUIRED","展示授权确认需要用户手势");if(!e.authPresentation)throw await I(C,H.challenge),y("AUTHORIZATION_PRESENTATION_UNAVAILABLE","授权确认界面不可用");return v(async g=>{await p($,K);const P=await x(C,H.displayedScopes,g);await p($,K);let B;try{B=await e.authPresentation.confirmAuthorization({miniProgramId:C,scopes:H.displayedScopes,...P,signal:g})}catch(X){throw e.operationContext.signal.aborted?y("RUNTIME_DESTROYED","小程序 Runtime 已终止"):(await p($,K),await I(C,H.challenge),Jo("REQUEST_FAILED","授权确认界面执行失败",X))}if(await p($,K),B.status!=="granted")throw await I(C,H.challenge),y("AUTHORIZATION_CANCELLED","用户取消授权");const Q=GE(B.grantedScopes,H.displayedScopes,c);if(!Q.includes("identity"))throw await I(C,H.challenge),y("AUTHORIZATION_CANCELLED","用户拒绝授权");return Q})}async function x(C,H,F){const $=sd(F),K=setTimeout(()=>$.abort(),BE);try{const g=$E(e.miniProgramPresentation),[P,B]=await Promise.all([g?Promise.resolve(g):N(C,$.signal),H.includes("profile")?b($.signal):Promise.resolve(void 0)]);return{...P?{miniProgram:P}:{},...B?{userProfile:B}:{}}}finally{clearTimeout(K),$.abort()}}async function N(C,H){try{const F=e.identity.get()?.version?.trim(),$=await D(EE,{mini_program_id:C,...F?{miniprogram_version:F}:{}},H),K=pr($,"小程序公开资料"),g=Nr(K.name),P=Nr(K.icon_url);return g||P?{...g?{name:g}:{},...P?{avatarUrl:P}:{}}:void 0}catch{return}}async function b(C){try{const H=await D(Ef,void 0,C),F=pr(H,"账号基础信息"),$=Nr(F.display_username),K=Nr(F.display_avatar);return $||K?{...$?{nickname:$}:{},...K?{avatar:K}:{}}:void 0}catch{return}}async function O(C,H){if(TE(d,"auth.login"),!c&&C.includes(tc))throw y("INVALID_PARAMS","auth.login 参数不合法");const F=_(),$=await A(H),K=i,g=await D(NE,{runtimeContext:{miniProgramId:F,...await l()},scopes:C});await p($,K);const P=pr(g,"小程序登录"),B=ad(P,"loginCode"),Q=ad(P,"consentChallenge");if(B===Q)throw y("INVALID_RESPONSE","小程序登录 begin 必须返回 exact oneof");let X;if(B)X=od(P.loginCode,c);else{const ie=FE(P.consentChallenge,c),ue=await T(F,ie,H,$,K);await p($,K);const Ee=await D(ME,{runtimeContext:{miniProgramId:F,...await l()},challenge:ie.challenge,selectedScopes:ue});if(await p($,K),X=od(pr(Ee,"小程序登录确认"),c),X.scopes.some(me=>!ue.includes(me)))throw y("INVALID_RESPONSE","小程序登录确认返回了未选择的 scope")}n.clear();for(const ie of X.scopes)n.add(ie);r.invalidate();const ne=e.account.getAccountKey?await M($,K,F):void 0;return E("heybox_app_login_change",{isHeyboxAppLoggedIn:!0,...ne===void 0?{}:{accountKey:ne}}),E("user_info_authorization_change",Xo(n,c)),{...X,...ne===void 0?{}:{accountKey:ne}}}async function j(C,H){const F=i,$=await D(DE,{runtimeContext:{miniProgramId:H,...await l()}});await p(C,F);const K=VE(pr($,"用户本地身份"),c);for(const g of c?kr:_f)n.add(g);return E("user_info_authorization_change",Xo(n,c)),K}function U(C){w();const H=_(),F=`${C}\0${H}\0${i}\0${c}`;return r.read(F,()=>j(C,H))}async function L(C){if(!C)throw y("USER_GESTURE_REQUIRED","撤销授权需要用户手势");const H=_(),F=i,$=await S();if(!$)throw y("HEYBOX_APP_LOGIN_REQUIRED","请先登录小黑盒");const K=await D(_E,{runtimeContext:{miniProgramId:H,...await l()}});await p($,F),pr(K,"用户授权撤销"),m(),E("user_info_authorization_change",{identity:"denied",profile:"denied",...c?{steam_account:"denied"}:{}})}return{getAccountState:z,login:O,async confirmGameSaves(C){if(!C)throw y("USER_GESTURE_REQUIRED","读取游戏存档需要点击按钮授权");if(!e.authPresentation)throw y("AUTHORIZATION_PRESENTATION_UNAVAILABLE","授权确认界面不可用");const H=_(),F=await A(C),$=i;await v(async K=>{await p(F,$);const g=await x(H,["identity"],K),P=await e.authPresentation.confirmAuthorization({miniProgramId:H,scopes:["identity","game_saves"],...g,signal:K});if(await p(F,$),P.status!=="granted"||!P.grantedScopes.includes("game_saves")||!P.grantedScopes.includes("identity"))throw y("AUTHORIZATION_CANCELLED","用户取消存档授权")})},getOrCreateLocalIdentity:U,invalidateLocalIdentity(){r.invalidate()},getAuthorization:()=>Xo(n,c),revoke:L,onEvent(C){return t.add(C),()=>t.delete(C)},dispose(){o||(o=!0,m(),r.dispose(),h(),t.clear())}}}function Jo(e,t,r){const n=y(e,t);return Object.defineProperty(n,"cause",{configurable:!0,enumerable:!1,value:r}),n}function pr(e,t){if(!re(e))throw y("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":zE.has(r)?r:"REQUEST_FAILED";throw y(n,r)}if(!re(e.result))throw y("INVALID_RESPONSE",`${t} result 必须是对象`);return e.result}function od(e,t){if(!re(e))throw y("INVALID_RESPONSE","login code 必须是对象");const r=so(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 y("INVALID_RESPONSE","login code 响应不合法");return{code:e.code,expiresIn:Number(e.expiresIn),scopes:r}}function FE(e,t){if(!re(e))throw y("INVALID_RESPONSE","授权 challenge 必须是对象");const r=so(e.requestedScopes,"challenge requestedScopes",t),n=so(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 y("INVALID_RESPONSE","授权 challenge 响应不合法");return{challenge:e.challenge.trim(),requestedScopes:r,displayedScopes:n}}function VE(e,t){if(!re(e)||typeof e.appUserId!="string"||!e.appUserId.trim())throw y("INVALID_RESPONSE","本地身份 appUserId 必须是非空字符串");const r=e.appUserId.trim();if(!t)return{appUserId:r};if(e.steamId!==void 0&&typeof e.steamId!="string")throw y("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 GE(e,t,r){const n=so(e,"授权选择 scopes",r);if(n.some(i=>!t.includes(i)))throw y("INVALID_RESPONSE","授权选择包含未展示的 scope");return n}function Nr(e){return typeof e=="string"&&e.trim()?e.trim():void 0}function $E(e){const t=Nr(e?.name),r=Nr(e?.avatarUrl);return t||r?{...t?{name:t}:{},...r?{avatarUrl:r}:{}}:void 0}function sd(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 qE(e,t){return t.aborted?Promise.reject(Ks()):new Promise((r,n)=>{let i=!1;const o=a=>{i||(i=!0,t.removeEventListener("abort",s),a())},s=()=>o(()=>n(Ks()));t.addEventListener("abort",s,{once:!0}),e.then(a=>o(()=>r(a)),a=>o(()=>n(a)))})}function Ks(){const e=new Error("The operation was aborted");return e.name="AbortError",e}function so(e,t,r){const n=r?jE:_f;if(!Array.isArray(e)||e.some(i=>typeof i!="string"||!n.has(i))||new Set(e).size!==e.length)throw y("INVALID_RESPONSE",`${t} 不合法`);return[...e]}function Xo(e,t){const r=t?kr:kr.filter(n=>n!==tc);return Object.fromEntries(r.map(n=>[n,e.has(n)?"granted":"not_requested"]))}function ad(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function QE(e){return re(e)?Object.values(e).some(t=>t==="denied"):!1}function Js(e){return re(e)&&typeof e.code=="string"&&typeof e.message=="string"}function cd(e,t,r){return t.aborted?y("RUNTIME_DESTROYED","小程序 Runtime 已终止"):Js(e)?e:y("REQUEST_FAILED",r)}const YE=new Set(kr);function WE(e){return{[Ni]:async t=>{if(t!==void 0)throw y("INVALID_PARAMS","auth.getAccountState 不接受参数");return e.authorization.getAccountState()},[Mi]:async(t,r)=>e.authorization.login(ZE(t),r.trustedUserGesture)}}function ZE(e){if(e===void 0)return["identity"];if(!re(e)||Object.keys(e).some(t=>t!=="scopes"))throw dd();if(e.scopes===void 0)return["identity"];if(!Array.isArray(e.scopes)||e.scopes.some(t=>typeof t!="string"||!YE.has(t))||new Set(e.scopes).size!==e.scopes.length)throw dd();return[...e.scopes]}function dd(){return y("INVALID_PARAMS","auth.login 参数不合法")}const KE={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 Te(e,"排行榜记录删除接口响应异常")}},JE={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 Te(e,"当前排行榜记录接口响应异常")}},XE={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 Te(e,"排行榜信息接口响应异常")}},ew={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 Te(e,"排行榜列表接口响应异常")}},tw={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 Te(e,"排行榜提交接口响应异常")}},rw={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 Co(e,t,r){e.assertUsable();const n={request:async(i,o)=>(e.assertUsable(),e.network.request(i,o))};try{return await fe(()=>Po(n,t,r,{...e.operationContext,credentials:"heybox-session",...e.gate?{gate:e.gate}:{}}),e.operationContext.signal)}catch(i){if(uo(i)||an(i,"REQUEST_UNSUPPORTED")||an(i,"RATE_LIMITED")||an(i,"RATE_LIMITED_BY_RUNTIME"))throw i;if(i instanceof Le)throw ee("REQUEST_UNSUPPORTED",`当前 Host 不支持该${e.subject}请求`);if(i instanceof Cr&&an(i.cause,"INVALID_STATE"))throw i.cause;if(i instanceof xn){if(e.requestPolicyEnabled!==!1&&(i.status===403||i.status===429))throw ee("RATE_LIMITED",`${e.subject}请求已被网关限流,请稍后重试`,{status:i.status,...i.retryAfterMs===void 0?{}:{retryAfterMs:i.retryAfterMs}});if(i.status===401||i.status===403)throw ee("UNAUTHORIZED","当前用户未登录");const o=nw(i.responseData);if(Ie(o)&&typeof o.status=="string"&&o.status!=="ok"){const s=Ie(o.result)?Mt(o.result.error_code):void 0;if(o.status==="login"||o.status==="relogin"||ao(o.result)||ao(o)||s&&/^[A-Z][A-Z0-9_]+$/.test(s))throw Df(o,e.subject)}throw ee("HTTP_ERROR",`${e.subject}请求失败(HTTP ${i.status})`,{status:i.status})}throw i instanceof Cr?co(e.subject):i instanceof zn?Ne(i.cause instanceof Error?i.cause.message:`${e.subject}响应不合法`):Ne(i instanceof Error?i.message:`${e.subject}响应不合法`)}}function st(e,t,r){if(!Ie(e)||typeof e.status!="string")throw Ne(`${t} 响应必须是标准信封`);if(e.status!=="ok")throw Df(e,r);if(!Object.prototype.hasOwnProperty.call(e,"result")||e.result===void 0||e.result===null)throw Ne(`${t} 响应缺少 result`);return e.result}function Lo(e,t){try{return e.onChange(t)}catch(r){if(an(r,Fl))return()=>{};throw r}}function Df(e,t){if(e.status==="login"||e.status==="relogin")throw ee("UNAUTHORIZED",Mt(e.msg)||"当前用户未登录");if(Ie(e.result)){const i=Mt(e.result.error_code);if(i&&/^[A-Z][A-Z0-9_]+$/.test(i))throw ee(i,Mt(e.result.message)||Mt(e.msg)||`${t}请求失败`)}const r=ao(e.result)??ao(e),n=Mt(r?.user_message)||Mt(e.msg)||Mt(r?.developer_message)||`${t}请求失败`;throw r?ee(iw(r),n,{status:e.status,sbe:r}):ee("HEYBOX_API_ERROR",n,{status:e.status})}function nw(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return}}function ao(e){return Ie(e)&&Ie(e.sbe)?e.sbe:void 0}function iw(e){const t=Mt(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 rw[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 Ie(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Mt(e){return typeof e=="string"&&e.trim()?e.trim():void 0}function an(e,t){return Ie(e)&&e.code===t}function ee(e,t,r){return r===void 0?{code:e,message:t}:{code:e,message:t,data:r}}function Ne(e){return ee("INVALID_RESPONSE",e)}function co(e){return ee("REQUEST_FAILED",`${e}请求失败`)}function uo(e){return e instanceof Error&&e.name==="AbortError"}const ow="default",Vt="排行榜",sw=/^[A-Za-z0-9_-]{1,64}$/,aw=300*1e3,cw=250,dw=3;class uw{constructor(t){this.options=t,this.requestGateContext=t.requestGate?{capability:"cloud",gate:t.requestGate}:void 0,this.unsubscribeAccountChange=Lo(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(tw,{miniProgramId:n,...t});this.assertAccountGeneration(r);const o=st(i,bt,Vt);return this.invalidateMutableReads(this.createBucketKey(n,t.key)),es(o,bt)}getList(t){this.assertUsable();const r=this.readMiniProgramId(),n=this.createBucketKey(r,t.key),i=Jr("list",t.limit,t.cursor??null);return this.read(n,"list",i,async()=>{const o=await this.request(ew,{miniProgramId:r,...t}),s=st(o,at,Vt);if(!Ie(s)||!Array.isArray(s.entries)||typeof s.has_more!="boolean")throw Ne(`${at} 返回值不合法`);if(s.cursor!==void 0&&s.cursor!==null&&typeof s.cursor!="string")throw Ne(`${at} 返回的 cursor 必须是字符串`);return{entries:s.entries.map(a=>es(a,at)),...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=Jr("current",i);return this.read(o,"current",s,async()=>{const a=await this.request(JE,{miniProgramId:n,...t}),c=st(a,xt,Vt);if(!Ie(c))throw Ne(`${xt} 返回值必须是对象`);return c.entry===void 0||c.entry===null?void 0:es(c.entry,xt)})}async deleteCurrentUserEntry(t){this.assertUsable();const r=this.accountGeneration,n=this.readMiniProgramId();await this.requireCurrentUser(r);const i=await this.request(KE,{miniProgramId:n,...t});this.assertAccountGeneration(r);const o=st(i,ir,Vt);if(this.invalidateMutableReads(this.createBucketKey(n,t.key)),!Ie(o)||typeof o.deleted!="boolean")throw Ne(`${ir} 返回的 deleted 必须是布尔值`);return{deleted:o.deleted}}getInfo(t){this.assertUsable();const r=this.readMiniProgramId(),n=this.createBucketKey(r,t.key);return this.read(n,"info",Jr("info"),async()=>{const i=await this.request(XE,{miniProgramId:r,...t}),o=st(i,wt,Vt);if(!Ie(o)||typeof o.key!="string"||!sw.test(o.key))throw Ne(`${wt} 返回的 key 不合法`);if(t.key!==void 0&&o.key!==t.key)throw Ne(`${wt} 返回的 key 与请求不一致`);if(o.order!=="asc"&&o.order!=="desc")throw Ne(`${wt} 返回的 order 必须是 asc 或 desc`);if(typeof o.rank_limit!="number"||!Number.isInteger(o.rank_limit)||o.rank_limit<0)throw Ne(`${wt} 返回的 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=Jr(t,n),d=this.inflight.get(c);if(d)return d.promise;const u=this.accountGeneration,f=o?.generation,l=i().then(h=>(this.assertAccountGeneration(u),o&&s&&o.generation===f&&(r==="list"?s.size>=cw&&s.delete(s.keys().next().value):s.clear(),s.set(n,{expiresAt:Date.now()+aw,value:h})),h)).finally(()=>{this.inflight.get(c)?.promise===l&&this.inflight.delete(c),o&&this.removeEmptyBucket(t,o)});return this.inflight.set(c,{bucketKey:t,promise:l}),l}getOrCreateBucket(t){const r=this.buckets.get(t);if(r)return r;if(this.pruneExpiredBuckets(),this.buckets.size>=dw)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)ud(n,t),this.isBucketEmpty(r,n)&&this.buckets.delete(r)}removeEmptyBucket(t,r){ud(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 fe(()=>this.options.account.getCurrentUserId(this.options.operationContext),this.options.operationContext.signal)}catch(n){throw uo(n)?n:co(Vt)}if(this.assertAccountGeneration(t),typeof r!="string"||!r.trim())throw ee("UNAUTHORIZED","当前用户未登录");return r.trim()}readMiniProgramId(){const t=this.options.identity.get()?.miniProgramId.trim();if(!t)throw ee("INVALID_STATE","canonical mini-program identity 尚未绑定");return t}createBucketKey(t,r){return Jr(t,r??ow)}assertAccountGeneration(t){if(this.assertUsable(),t!==this.accountGeneration)throw ee("UNAUTHORIZED","登录状态已变化,请重试")}request(t,r){return Co({network:this.options.network,operationContext:this.options.operationContext,...this.requestGateContext?{gate:this.requestGateContext}:{},...this.options.requestPolicyEnabled===void 0?{}:{requestPolicyEnabled:this.options.requestPolicyEnabled},subject:Vt,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(pe(this.options.operationContext.signal),this.disposed)throw ee("INVALID_STATE","Cloud capability 已释放")}}function lw(e){return new uw(e)}function es(e,t){if(!Ie(e))throw Ne(`${t} 返回的 entry 必须是对象`);if(typeof e.ranked!="boolean")throw Ne(`${t} 返回的 ranked 必须是布尔值`);if(typeof e.rank!="number"||!Number.isInteger(e.rank)||(e.ranked?e.rank<=0:e.rank!==0))throw Ne(`${t} 返回的 rank/ranked 不合法`);if(typeof e.app_user_id!="string"||!e.app_user_id.trim())throw Ne(`${t} 返回的 appUserId 必须是非空字符串`);if(typeof e.score!="number"||!Number.isFinite(e.score))throw Ne(`${t} 返回的 score 必须是有限数字`);if(!Ie(e.extra))throw Ne(`${t} 返回的 extra 必须是对象`);if(typeof e.created_at!="number"||!Number.isFinite(e.created_at)||typeof e.updated_at!="number"||!Number.isFinite(e.updated_at))throw Ne(`${t} 返回的时间字段必须是有限数字`);return{appUserId:e.app_user_id,createdAt:e.created_at,extra:e.extra,rank:e.rank,ranked:e.ranked,score:e.score,updatedAt:e.updated_at}}function ud(e,t){for(const r of Object.values(e.caches))for(const[n,i]of r)i.expiresAt<=t&&r.delete(n)}function Jr(...e){return JSON.stringify(e)}const fw={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 Te(e,"云端存储删除接口响应异常")}},ld={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 Te(e,"云端存储读取接口响应异常")}},fd={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 Te(e,"云端存储 key 列表接口响应异常")}},hw={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 Te(e,"云端存储写入接口响应异常")}},Gt="云端存储",mw=3e4,gw=128,pw=500;class yw{constructor(t){this.options=t,this.requestGateContext=t.requestGate?{capability:"cloud.storage",gate:t.requestGate}:void 0,this.unsubscribeAccountChange=Lo(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=st(await this.request(fd,{}),or,Gt);if(this.assertAccountGeneration(t),!Ie(r)||r.keys!==void 0&&(!Array.isArray(r.keys)||!r.keys.every(i=>typeof i=="string")))throw Ne("cloud.storage.getKeys 返回的 keys 必须是字符串数组");const n=new Set(r.keys??[]);for(const i of this.unfinished)i.kind==="set"?n.add(i.key):n.delete(i.key);return[...n]}async enqueue(t,r,n){this.assertUsable(),this.readMiniProgramId();const i=this.accountGeneration;return await this.requireCurrentUser(i),this.assertAccountGeneration(i),t==="set"&&this.blockedKeys.has(r)?Promise.reject(this.blockedKeys.get(r)):new Promise((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"?pw: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=st(await this.request(fw,{key:t}),Rr,Gt);if(this.assertAccountGeneration(r.generation),!Ie(i)||i.deleted!==void 0&&typeof i.deleted!="boolean")throw Ne("删除结果不合法");this.writeCache(t,{value:"",found:!1,version:0,revision:""}),this.blockedKeys.delete(t)}else{const i=await this.readStored(t,r.generation,!0);if(this.assertAccountGeneration(r.generation),!Number.isSafeInteger(i.version+1))throw Ne("云存储版本超出安全整数范围");const o=st(await this.request(hw,{key:t,value:r.value,expectedVersion:i.version,expectedRevision:i.revision}),Or,Gt);if(this.assertAccountGeneration(r.generation),!Ie(o)||o.success!==!0)throw Ne("云存储写入结果不合法");const s=hd({...o,found:!0,value:r.value});if(s.version!==i.version+1||i.found&&s.revision!==i.revision)throw Ne("写入版本凭证不匹配");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(ld,{key:t}).then(c=>{this.assertAccountGeneration(r);const d=hd(st(c,vr,Gt));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>=gw&&this.cache.delete(this.cache.keys().next().value),this.cache.set(t,{expiresAt:Date.now()+mw,value:r})}invalidateRead(t){this.keyGenerations.set(t,(this.keyGenerations.get(t)??0)+1),this.inflight.delete(t),this.options.requestGate?.invalidateCoalescing([ld.id,fd.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(ee("INVALID_STATE","Cloud capability 已释放")))}invalidateForAccountChange(){this.purge(ee("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 fe(()=>this.options.account.getCurrentUserId(this.options.operationContext),this.options.operationContext.signal)}catch(o){throw uo(o)?o:co(Gt)}if(this.assertAccountGeneration(t),this.hasAccountObservation&&(n?.trim()||void 0)!==this.observedUserId)throw this.invalidateForAccountChange(),ee("UNAUTHORIZED","登录状态已变化,请重试");const i=JSON.stringify([r,n]);if(this.boundScope!==void 0&&this.boundScope!==i)throw this.invalidateForAccountChange(),ee("UNAUTHORIZED","登录状态已变化,请重试");if(typeof n!="string"||!n.trim())throw ee("UNAUTHORIZED","当前用户未登录");return this.boundScope=i,this.boundUserId=n.trim(),n}readMiniProgramId(){const t=this.options.identity.get()?.miniProgramId.trim();if(!t)throw ee("INVALID_STATE","canonical mini-program identity 尚未绑定");return t}assertAccountGeneration(t){if(this.assertUsable(),t!==this.accountGeneration)throw ee("UNAUTHORIZED","登录状态已变化,请重试")}async request(t,r){const n=this.accountGeneration;if(this.assertUsable(),!this.options.authorizationContext)throw ee("METHOD_FORBIDDEN","云端存储缺少受信运行上下文");let i;try{i=await fe(()=>this.options.authorizationContext.get(this.options.operationContext),this.options.operationContext.signal)}catch(s){throw uo(s)?s:co(Gt)}this.assertAccountGeneration(n);const o=i.token.trim();if(!o||i.expiresAt<=Date.now())throw ee("UNAUTHORIZED","小程序运行上下文无效,请重新打开");return Co({network:this.options.network,operationContext:this.options.operationContext,...this.requestGateContext?{gate:this.requestGateContext}:{},...this.options.requestPolicyEnabled===void 0?{}:{requestPolicyEnabled:this.options.requestPolicyEnabled},subject:Gt,assertUsable:()=>this.assertAccountGeneration(n)},t,{...r,runtimeAuthContextToken:o})}assertUsable(){if(pe(this.options.operationContext.signal),this.disposed)throw ee("INVALID_STATE","Cloud capability 已释放")}}function Ew(e){return new yw(e)}function hd(e){if(!Ie(e))throw Ne("云存储读取结果必须是对象");const t=e.found??!1,r=e.value??"",n=e.version??0,i=e.revision??"";if(typeof t!="boolean"||typeof r!="string"||typeof n!="number"||!Number.isSafeInteger(n)||n<0||typeof i!="string")throw Ne("云存储读取结果不合法");if(t&&(n===0||!/^[0-9a-f]{24}$/.test(i)||/^0+$/.test(i)))throw Ne("云存储版本凭证不合法");return t?{value:r,found:t,version:n,revision:i}:{value:"",found:!1,version:0,revision:""}}const ww=/^[A-Za-z0-9_-]{1,64}$/,md=20,Iw=100,gd=2048,Aw=/^[A-Za-z0-9_-]{1,128}$/,pd=16*1024;function _w(e){const t=lw(e),r=Ew(e);return{handlers:{[bt]:async i=>t.submit(Dw(i)),[at]:async i=>t.getList(Nw(i)),[xt]:async i=>t.getCurrentUserEntry(ts(i,xt)),[ir]:async i=>t.deleteCurrentUserEntry(ts(i,ir)),[wt]:async i=>t.getInfo(ts(i,wt)),[vr]:async i=>r.getItem(yd(i,vr)),[Or]:async i=>{const{key:o,value:s}=Mw(i);return r.setItem(o,s)},[Rr]:async i=>r.removeItem(yd(i,Rr)),[or]:async i=>(bw(i),r.getKeys())},dispose:()=>{t.dispose(),r.dispose()}}}function Dw(e){const t=$r(e,bt,!1);if(qr(t,["key","score","extra"],bt),typeof t.score!="number"||!Number.isFinite(t.score)||Math.abs(t.score)>Number.MAX_SAFE_INTEGER)throw Ye("INVALID_PARAMS","cloud.leaderboard.submit score 必须是有限安全数字");return{...rc(t.key,bt),score:t.score,...t.extra===void 0?{}:{extra:Tw(t.extra)}}}function Nw(e){if(e===void 0)return{limit:md};const t=$r(e,at,!0);qr(t,["key","limit","cursor"],at);const r=t.limit===void 0?md:t.limit;if(typeof r!="number"||!Number.isInteger(r)||r<=0||r>Iw)throw Ye("INVALID_PARAMS","cloud.leaderboard.getList limit 必须是 1-100 的整数");if(t.cursor!==void 0&&typeof t.cursor!="string")throw Ye("INVALID_PARAMS","cloud.leaderboard.getList cursor 必须是字符串");return{...rc(t.key,at),limit:r,...t.cursor===void 0?{}:{cursor:t.cursor}}}function ts(e,t){if(e===void 0)return{};const r=$r(e,t,!0);return qr(r,["key"],t),rc(r.key,t)}function yd(e,t){const r=$r(e,t,!1);return qr(r,["key"],t),Nf(r.key,t)}function Mw(e){const t=Or,r=$r(e,t,!1);qr(r,["key","value"],t);const n=Nf(r.key,t);if(typeof r.value!="string")throw Ye("INVALID_PARAMS",`${t} value 必须是字符串`);if(Sw(r.value))throw Ye("INVALID_PARAMS",`${t} value 不能包含不成对的代理字符`);if(new TextEncoder().encode(r.value).length>pd)throw Ye("INVALID_PARAMS",`${t} value 不能超过 ${pd} 字节`);return{key:n,value:r.value}}function Sw(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 bw(e){const t=$r(e,or,!0);qr(t,[],or)}function Nf(e,t){if(typeof e!="string"||!Aw.test(e))throw Ye("INVALID_PARAMS",`${t} key 仅支持 1–128 位英文字母、数字、下划线和连字符`);return e}function $r(e,t,r){if(e===void 0&&r)return{};if(!Mf(e))throw Ye("INVALID_PARAMS",`${t} 参数必须是对象`);return e}function qr(e,t,r){const n=Object.keys(e).find(i=>!t.includes(i));if(n)throw Ye("INVALID_PARAMS",`${r} 不支持参数 ${n}`)}function rc(e,t){if(e===void 0)return{};if(typeof e!="string"||!ww.test(e))throw Ye("INVALID_PARAMS",`${t} key 仅支持 1-64 位字母、数字、下划线和连字符`);return{key:e}}function Tw(e){if(!Mf(e))throw Ye("INVALID_PARAMS","cloud.leaderboard.submit extra 必须是对象");let t;try{t=JSON.stringify(e)}catch{throw Ye("INVALID_PARAMS","cloud.leaderboard.submit extra 必须可序列化")}if(typeof t!="string")throw Ye("INVALID_PARAMS","cloud.leaderboard.submit extra 必须可序列化");if(new TextEncoder().encode(t).length>gd)throw Ye("INVALID_PARAMS",`cloud.leaderboard.submit extra 不能超过 ${gd} 字节`);return e}function Mf(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ye(e,t){return{code:e,message:t}}const vw={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 Te(e,"游戏存档接口响应异常")}},Ow=new Map([["2358720","blackMythWukong"],["3678970","taskbarHero"],["4115450","phantomBladeZero"],["1245620","eldenRing"],["413150","stardewValley"],["2246340","monsterHunterWilds"],["3167020","duckov"],["3489700","stellarBlade"],["2001120","splitFiction"]]);function Xs(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=>Xs(r,t+1)):Ie(e)&&Object.values(e).every(r=>Xs(r,t+1))}function Rw(e,t){const r=Ow.get(t);if(!r||Ie(e)&&e.status==="unsupported")return{status:"unsupported"};if(Ie(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 ee(String(e.error_code),"账号或授权已变化");if(e.status==="ready"&&Ie(e.data)&&Xs(e.data))return{status:"ready",data:e.data}}return{status:"failed",error:{code:"STRUCTURED_DATA_UNAVAILABLE",message:"结构化数据暂时无法读取,请稍后重试"}}}function Sf(e){const t=new Map,r=new Map,n=c=>c.resource?`hb_runtime_game_save_resource_sync_v1_${[c.miniProgramId,c.userId,c.resource].map(encodeURIComponent).join(":")}`:`hb_runtime_game_save_sync_v1_${[c.miniProgramId,c.userId,c.gameId].map(encodeURIComponent).join(":")}`;async function i(c,d,u){const f=n(c),l=r.get(f)??Promise.resolve();let h;const m=new Promise(_=>{h=_}),E=l.then(()=>m);r.set(f,E);try{return await fe(()=>l,d.signal),pe(d.signal),e?.withLock?await e.withLock(f,u):await u()}finally{h(),r.get(f)===E&&E.then(()=>{r.get(f)===E&&r.delete(f)})}}async function o(c,d,u=!1){const f=n(c);if(!u&&t.has(f)||!e)return t.get(f);try{const l=await fe(()=>e.getRaw(f,d),d.signal);if(!l)return;const h=JSON.parse(l);if(!h||typeof h!="object")return;const m=h;return m.version!==1||m.miniProgramId!==c.miniProgramId||m.userId!==c.userId||m.gameId!==c.gameId||(c.resource?m.resource!==c.resource:typeof m.accountId!="string"||!/^[1-9][0-9]{0,19}$/.test(m.accountId))||typeof m.taskId!="string"||(c.resource?m.taskId.length<1||m.taskId.length>128:!/^[1-9][0-9]{0,19}$/.test(m.taskId))?void 0:(u||t.set(f,m),m)}catch(l){if(pe(d.signal),u)throw l;return t.get(f)}}async function s(c,d,u){pe(u.signal);const f=n(c),l=d?{...c,version:1,taskId:d}:void 0;if(t.set(f,l),!!e)try{await fe(()=>e.setRaw(f,l?JSON.stringify(l):"",u),u.signal)}catch{pe(u.signal)}}async function a(c,d,u){await i(c,u,async()=>{const f=n(c),l=t.get(f),h=l?.taskId===d&&l.accountId===c.accountId;let m;try{m=await o(c,u,!0)}catch{pe(u.signal),h&&t.set(f,void 0);return}m?.taskId===d&&m.accountId===c.accountId?(await s(c,void 0,u),l&&!h&&t.set(f,l)):h&&t.set(f,m)})}return{run:i,async get(c,d){const u=await o(c,d);if(u&&u.accountId!==c.accountId){t.delete(n(c));return}return u?.taskId},set:s,remove:a,clear(c){for(const d of t.values())d&&a(d,d.taskId,c).catch(()=>{})}}}const kw=2e3,Pw=5*6e4;function Cw(e){const t=Sf(e.storage);let r=0,n=!1,i;const o=e.fileDownloads??(e.files&&e.transfer?Xa({files:e.files,transfer:e.transfer,registry:e.fileRegistry,signal:e.operationContext.signal}):void 0),s=new Set,a=new Map,c={...e.operationContext,lifecycle:"cleanup",signal:new AbortController().signal},d=I=>o?.release(I)??Promise.resolve(),u=new Set;let f=new AbortController,l;const h=()=>{f.abort(),f=new AbortController,l=void 0},m=(I=!0)=>{I&&t.clear(c),r++,h();for(const v of u)v.abort();for(const v of s)d(v).catch(()=>{});s.clear(),a.clear()},E=Lo(e.account,I=>{i&&I!==i&&(m(),i=void 0)}),_=e.authorization.onEvent(()=>m());function w(I,v,T,x){if(S(T),x.signal.aborted||!I.account_id||!e.presentation?.showSteamLoginRequired)return;const N=`${I.account_id}:${I.game_id}:${I.task_id??"sync"}`;if(l!==N){l=N;try{e.presentation.showSteamLoginRequired({userId:v,accountId:I.account_id},Se(e.operationContext,f.signal))}catch{}}}function S(I){if(n||e.operationContext.signal.aborted)throw ee("RUNTIME_DESTROYED","小程序已关闭");if(I!==r)throw ee("AUTHORIZATION_CONTEXT_CHANGED","账号或授权已变化")}async function p(I,v,T){if(S(v),await e.account.getCurrentUserId(T)!==I)throw m(),ee("AUTHORIZATION_CONTEXT_CHANGED","账号已变化");S(v)}async function M(I,v,T,x){if(await p(v,T,x),!e.authorizationContext)throw ee("METHOD_FORBIDDEN","宿主不支持存档授权上下文");const N=await e.authorizationContext.get(x);if(!N.token||N.expiresAt<=Date.now())throw ee("UNAUTHORIZED","小程序运行上下文已过期");const b=await Co({network:e.network,operationContext:x,subject:"游戏存档",assertUsable:()=>S(T),...e.requestGate?{gate:{capability:"gameSaves",gate:e.requestGate}}:{},requestPolicyEnabled:e.requestPolicyEnabled},vw,{...I,runtime_auth_context_token:N.token});if(await p(v,T,x),b.status==="failed"&&Ie(b.result)&&b.result.error_code==="RECENT_SAVE_AVAILABLE")throw ee("RECENT_SAVE_AVAILABLE",typeof b.msg=="string"&&b.msg?b.msg:"已有近期存档,请直接查询使用");const O=st(b,I.action,"游戏存档");if(!Ie(O))throw ee("INVALID_RESPONSE","存档响应不合法");return O}async function z(I,v,T){const x=Lw(I,v),N=r;if(S(N),I==="file"&&(!e.transfer||!e.files))throw ee("METHOD_FORBIDDEN","宿主不支持存档文件读取");const b=new AbortController;u.add(b);let O=!1;const j=I==="sync"?setTimeout(()=>{O=!0,b.abort()},Pw):void 0,U=Se(Se(e.operationContext,T.signal),b.signal);try{const L=await e.account.getCurrentUserId(U);if(!L)throw ee("UNAUTHORIZED","请先登录小黑盒");if(i&&i!==L)throw m(),ee("AUTHORIZATION_CONTEXT_CHANGED","账号已变化");if(i=L,I==="sync"||I==="parsed"){if(I==="sync"&&h(),!x.account_id){const K=await M({action:"check",game_id:x.game_id},L,N,U);x.account_id=vn(K.account_id)}if(I==="sync")return await A(x,L,N,U)}const C=await M({action:I,...x},L,N,U);if(I==="list")return Uw(C);if(I==="parsed")return Rw(C.parsed_data,x.game_id);if(bf(C.file).fileId!==x.file_id)throw ee("INVALID_RESPONSE","文件标识不匹配");if(!o)throw ee("REQUEST_UNSUPPORTED","宿主不支持存档下载");const F=await o.download(C,async K=>{try{S(N),await M({action:"check",game_id:x.game_id,account_id:x.account_id},L,N,K)}catch(g){const P=Ie(g)?String(g.code):"";throw["RUNTIME_DESTROYED","AUTHORIZATION_CONTEXT_CHANGED","STEAM_ACCOUNT_CHANGED","GAME_SAVES_AUTHORIZATION_REQUIRED","UNAUTHORIZED"].includes(P)?(m(),ee("FILE_ACCESS_REVOKED","游戏存档授权已失效")):g}},U);let $=!1;try{if(await p(L,N,U),S(N),U.signal.aborted)throw ee("DOWNLOAD_CANCELLED","存档下载已取消");const K=e.fileRegistry.registerFile(F,"game-save","read");return s.add(F),a.set(Ya(),{file:F,sizeBytes:o.sizeOf(F)}),$=!0,K}finally{$||await o.release(F)}}catch(L){throw O?ee("REQUEST_TIMEOUT","等待同步超时,任务可能仍在执行,请稍后查询存档列表"):L}finally{j!==void 0&&clearTimeout(j),u.delete(b)}}async function A(I,v,T,x){const N=e.identity.get()?.miniProgramId;if(!N)throw ee("INVALID_STATE","小程序身份尚未确认");const b={miniProgramId:N,userId:v,gameId:I.game_id,accountId:I.account_id},O=U=>M({action:"status",...I,task_id:U},v,T,x);let j;try{const U=await t.run(b,x,async()=>{await p(v,T,x);const C=await t.get(b,x);if(C){j=C;try{return{taskId:C,status:await O(C)}}catch(F){if(!Ie(F)||!["SYNC_TASK_NOT_FOUND","SYNC_TASK_CHANGED"].includes(String(F.code)))throw F;await t.set(b,void 0,x),j=void 0}}const H=await M({action:"sync",...I},v,T,x);return j=vn(H.task_id),await t.set(b,j,x),await p(v,T,x),{taskId:j,status:void 0}});j=U.taskId;let L=U.status;for(;;){if(S(T),x.signal.aborted)throw ee("REQUEST_CANCELLED","已停止等待存档同步");if(L??=await O(j),L.state==="succeeded"||L.state==="failed"){if(await t.remove(b,j,x),await p(v,T,x),L.state==="succeeded")return{state:"succeeded"};throw ee(L.error_code?lo(L.error_code):"SYNC_FAILED",L.message?lo(L.message):"存档同步失败")}if(L.state!=="syncing"&&L.state!=="uploading")throw ee("INVALID_RESPONSE","同步状态不合法");L=void 0,await xw(kw,x.signal)}}catch(U){if(Ie(U)){const L=String(U.code);L==="STEAM_LOGIN_REQUIRED"&&w({...I,task_id:j},v,T,x),j&&["SYNC_TASK_NOT_FOUND","SYNC_TASK_CHANGED","STEAM_ACCOUNT_CHANGED","STEAM_ACCOUNT_REQUIRED","GAME_SAVES_AUTHORIZATION_REQUIRED","AUTHORIZATION_CONTEXT_CHANGED","UNAUTHORIZED"].includes(L)&&await t.remove(b,j,c)}throw U}}return{handlers:{"gameSaves.list":(I,v)=>z("list",I,v),"gameSaves.sync":(I,v)=>z("sync",I,v),"gameSaves.readParsedData":(I,v)=>z("parsed",I,v),"gameSaves.getFile":(I,v)=>z("file",I,v)},diagnostics:{async getSnapshot(){const I=r;return i&&await p(i,I,e.operationContext),S(I),Array.from(a,([v,T])=>({id:v,name:T.file.name,sizeBytes:T.sizeBytes}))},async readFile(I,v){const T=r;S(T);const x=a.get(I);if(!x)throw ee("FILE_ACCESS_REVOKED","存档文件已失效,请重新下载");const N=Se(e.operationContext,v);N.signal.throwIfAborted();const b=await x.file.read(N);try{return N.signal.throwIfAborted(),S(T),{name:x.file.name,bytes:b}}catch(O){throw b.fill(0),O}}},allowsRead(I,v){return["file.readBytes","file.readText","file.stat","file.exists"].includes(I)&&Ie(v)&&e.fileRegistry.isGameSaveRef(v.target)},dispose(){n||(n=!0,m(!1),E(),_())}}}function Lw(e,t){const r=e==="file"?["gameId","accountId","saveId","fileId"]:["gameId","accountId"];if(!Ie(t)||Object.keys(t).some(i=>!r.includes(i)))throw ee("INVALID_PARAMS","存档参数不合法");const n=cn(t.gameId);if(Number(n)>2147483647)throw ee("INVALID_PARAMS","Steam AppID 超出范围");return{game_id:n,...e==="file"||t.accountId!==void 0?{account_id:cn(t.accountId)}:{},...e==="file"?{save_id:cn(t.saveId),file_id:cn(t.fileId)}:{}}}function cn(e){if(typeof e!="string"||!/^[1-9][0-9]{0,19}$/.test(e))throw ee("INVALID_PARAMS","存档标识必须为十进制字符串");return e}function vn(e){try{return cn(e)}catch{throw ee("INVALID_RESPONSE","服务端存档标识无效")}}function lo(e){if(typeof e!="string")throw ee("INVALID_RESPONSE","服务端存档字段无效");return e}function ea(e){if(typeof e!="number"||!Number.isSafeInteger(e)||e<0)throw ee("INVALID_RESPONSE","服务端存档数值无效");return e}function bf(e){if(!Ie(e))throw ee("INVALID_RESPONSE","存档文件信息无效");return{fileId:vn(e.file_id),name:lo(e.name),originalPath:lo(e.original_path),sizeBytes:ea(e.size_bytes),modifiedAt:ea(e.modified_at)}}function Uw(e){if(!Array.isArray(e.saves)||e.saves.length>500)throw ee("INVALID_RESPONSE","存档列表无效");return{accountId:vn(e.account_id),saves:e.saves.map(t=>{if(!Ie(t)||!Array.isArray(t.files)||t.files.length>200)throw ee("INVALID_RESPONSE","存档文件列表无效");return{saveId:vn(t.save_id),createdAt:ea(t.created_at),files:t.files.map(bf)}})}}function xw(e,t){return new Promise((r,n)=>{const i=()=>{clearTimeout(o),t.removeEventListener("abort",i),n(ee("REQUEST_CANCELLED","已停止等待存档同步"))},o=setTimeout(()=>{t.removeEventListener("abort",i),r()},Math.max(0,e));t.addEventListener("abort",i,{once:!0}),t.aborted&&i()})}const zw=new Set(["stdio","attachments","notifications"]),Tf=new Set(["windows-x64","macos-arm64"]),jw=new Set(["unsigned","valid","invalid","unknown"]),Bw=/^[a-f0-9]{64}$/,Hw=new Set(["exited","terminated","crashed","host-shutdown","permission-revoked","output-limit"]),Fw=new Set(Ol),Vw=new Set([...Ol,"PERMISSION_DENIED","USER_GESTURE_REQUIRED"]),vf=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 Gw(e){const t=async(n,i,o,s)=>{const a=$w(n);try{Et(i.signal);const c=await o(a,{...e.operationContext,signal:i.signal});return Et(i.signal),c}catch(c){throw ra(c,s)}},r=async(n,i,o)=>{if(!o.trustedUserGesture)throw y("USER_GESTURE_REQUIRED","当前操作需要新的可信用户手势");if(!e.companionPresentation)throw y("COMPANION_UNSUPPORTED","Host 未提供 Companion 可信授权界面");const s={...e.operationContext,signal:o.signal},a=await e.companion.getInfo(i,s).then(d=>qw(d,i)).catch(d=>{throw ra(d)});Et(o.signal);const c=await e.companionPresentation.confirmCompanionOperation({action:n,companion:a,miniProgram:e.miniProgramPresentation,signal:o.signal});if(Et(o.signal),c.status!=="granted")throw y("COMPANION_USER_CANCELLED","用户取消了 Companion 操作")};return{[wo]:(n,i)=>t(n,i,async(o,s)=>ta(await e.companion.getInfo(o,s),o)),[Io]:(n,i)=>t(n,i,async(o,s)=>Ed(await e.companion.getPreparationStatus(o,s))),[Ao]:(n,i)=>t(n,i,async(o,s)=>{const a=Ed(await e.companion.getPreparationStatus(o,s));return Et(i.signal),a.state!=="ready"&&a.state!=="preparing"&&await r("prepare",o,i),Et(i.signal),ta(await e.companion.prepare(o,{...s,onProgress:c=>i.postProgress(Rf(c))}),o)},"COMPANION_PREPARATION_CANCELLED"),[_o]:(n,i)=>t(n,i,(o,s)=>e.companion.cancelPreparation(o,s)),[Do]:(n,i)=>t(n,i,async(o,s)=>wd(await e.companion.getActiveSession(o,s),o)),[No]:(n,i)=>t(n,i,async(o,s)=>{const a=wd(await e.companion.getActiveSession(o,s),o);return Et(i.signal),a||(await r("launch",o,i),Et(i.signal),kf(await e.companion.launch(o,s),o))}),[Mo]:(n,i)=>yr(n,i,e,"write"),[So]:(n,i)=>yr(n,i,e,"closeStdin"),[bo]:(n,i)=>yr(n,i,e,"terminate"),[To]:(n,i)=>yr(n,i,e,"ackOutput"),[vo]:async(n,i)=>{const o=await yr(n,i,e,"openAttachment");return e.fileRegistry.registerFile(o,"companion-attachment","read")},[Oo]:(n,i)=>yr(n,i,e,"showNotification")}}function $w(e){if(!re(e)||typeof e.alias!="string"||!ng.test(e.alias))throw y("INVALID_PARAMS","Companion alias 不合法");return e.alias}function Et(e){if(e.aborted)throw Object.assign(new Error("Companion 操作已取消"),{name:"AbortError"})}async function yr(e,t,r,n){if(!re(e)||typeof e.sessionId!="string"||!e.sessionId||!Number.isSafeInteger(e.controllerGeneration)||Number(e.controllerGeneration)<0)throw y("INVALID_PARAMS","Companion Session controller 不合法");try{Et(t.signal);const i=await r.companion[n](Qw(e,n),{...r.operationContext,signal:t.signal});return Et(t.signal),i}catch(i){throw ra(i)}}function dt(){throw y("COMPANION_HOST_FAILED","Companion Host 返回了无效数据")}function Of(e){return!Array.isArray(e)||e.some(t=>!zw.has(t))?dt():Object.freeze([...new Set(e)])}function ta(e,t){return!re(e)||typeof e.alias!="string"||typeof e.displayName!="string"||t!==void 0&&e.alias!==t||!Tf.has(String(e.target))||!Number.isSafeInteger(e.archiveBytes)||Number(e.archiveBytes)<0||!jw.has(String(e.signatureStatus))||e.source!==void 0&&e.source!=="local-dev"&&e.source!=="preview"&&e.source!=="released"?dt():Object.freeze({alias:e.alias,displayName:e.displayName,target:e.target,capabilities:Of(e.capabilities),archiveBytes:e.archiveBytes,signatureStatus:e.signatureStatus,...e.source===void 0?{}:{source:e.source}})}function qw(e,t){const r=ta(e,t);return!re(e)||e.sha256===void 0?r:typeof e.sha256!="string"||!Bw.test(e.sha256)?dt():Object.freeze({...r,sha256:e.sha256})}function Rf(e){return re(e)?e.phase==="downloading"&&Number.isSafeInteger(e.loaded)&&Number(e.loaded)>=0&&(e.total===void 0||Number.isSafeInteger(e.total)&&Number(e.total)>=Number(e.loaded))?Object.freeze({phase:"downloading",loaded:e.loaded,...e.total===void 0?{}:{total:e.total}}):(e.phase==="verifying"||e.phase==="extracting")&&Number.isSafeInteger(e.processed)&&Number.isSafeInteger(e.total)&&Number(e.processed)>=0&&Number(e.total)>=Number(e.processed)?Object.freeze({phase:e.phase,processed:e.processed,total:e.total}):dt():dt()}function Ed(e){return re(e)?e.state==="not-prepared"?Object.freeze({state:"not-prepared"}):e.state==="preparing"?Object.freeze({state:"preparing",progress:Rf(e.progress)}):e.state==="ready"&&Number.isSafeInteger(e.preparedAt)&&Number(e.preparedAt)>=0?Object.freeze({state:"ready",preparedAt:e.preparedAt}):e.state==="failed"&&re(e.error)&&typeof e.error.code=="string"&&Fw.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:vf[e.error.code]??"Companion 操作失败",retryable:e.error.retryable})}):dt():dt()}function kf(e,t){return!re(e)||typeof e.id!="string"||!e.id||typeof e.alias!="string"||t!==void 0&&e.alias!==t||!Tf.has(String(e.target))||e.state!=="running"||!Number.isSafeInteger(e.controllerGeneration)||Number(e.controllerGeneration)<0?dt():Object.freeze({id:e.id,alias:e.alias,target:e.target,capabilities:Of(e.capabilities),state:"running",controllerGeneration:e.controllerGeneration})}function wd(e,t){return e===void 0?void 0:kf(e,t)}function Qw(e,t){const r=e,n={sessionId:r.sessionId,controllerGeneration:r.controllerGeneration};if(t==="write"){if(!Dl(r.data))throw y("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 y("INVALID_PARAMS","Companion output ack 不合法");return{...n,stream:r.stream,sequence:r.sequence}}if(t==="openAttachment"){if(typeof r.id!="string"||!r.id)throw y("INVALID_PARAMS","Companion Attachment ID 不合法");return{...n,id:r.id}}if(t==="showNotification"){if(!["completed","failed","stopped","attention"].includes(String(r.category)))throw y("INVALID_PARAMS","Companion notification category 不合法");return{...n,category:r.category}}return n}function Yw(e){return!re(e)||!Hw.has(String(e.reason))?dt():e.reason==="exited"?Number.isSafeInteger(e.exitCode)?Object.freeze({reason:"exited",exitCode:e.exitCode}):dt():e.exitCode!==void 0&&!Number.isSafeInteger(e.exitCode)?dt():Object.freeze({reason:e.reason,...e.exitCode===void 0?{}:{exitCode:e.exitCode}})}function Ww(e){if(!re(e)||!re(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||!Dl(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:Yw(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 ra(e,t){return re(e)&&typeof e.code=="string"&&Vw.has(e.code)?y(e.code,vf[e.code]??"Companion 操作失败",e.code==="COMPANION_DESCRIPTOR_UNAVAILABLE"?{retryable:!0}:typeof e.retryable=="boolean"?{retryable:e.retryable}:void 0):t&&re(e)&&e.name==="AbortError"?y(t,"Companion 准备已取消"):y("COMPANION_HOST_FAILED","Companion Host 操作失败")}const Id=5e3,Ad=1e4;function $e(e){throw{code:"INVALID_PARAMS",message:e}}function nc(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Pf(e,t,r){const n=Object.keys(e).filter(i=>!t.includes(i));n.length&&$e(`${r} 不支持字段: ${n.join(", ")}`)}function Zw(e){if(e===void 0)return{intensity:"light",delay:0};if(!nc(e))return $e("device.vibrate 参数必须是对象");Pf(e,["intensity","delay"],"device.vibrate");const t=e.intensity??"light";if(t!=="light"&&t!=="medium"&&t!=="heavy")return $e("device.vibrate intensity 必须是 light、medium 或 heavy");const r=t,n=e.delay??0;return typeof n!="number"||!Number.isInteger(n)||n<0||n>Id?$e(`device.vibrate delay 必须是 0-${Id} 的整数毫秒`):{intensity:r,delay:n}}function Kw(e){return nc(e)?(Pf(e,["text"],"device.setClipboard"),typeof e.text!="string"||!e.text.trim()?$e("device.setClipboard text 必须是非空字符串"):e.text.length>Ad?$e(`device.setClipboard text 不能超过 ${Ad} 字符`):{text:e.text}):$e("device.setClipboard 参数必须是对象")}function Jw(e){return typeof e=="string"?e.trim()?e:$e("device.executeProtocol 协议字符串不能为空"):nc(e)?typeof e.protocol_type!="string"||!e.protocol_type.trim()?$e("device.executeProtocol 协议对象必须包含非空字符串 protocol_type"):(na(e,new Set),e):$e("device.executeProtocol 参数必须是协议字符串或协议对象")}function na(e,t){if(e===null)return;switch(typeof e){case"string":case"boolean":return;case"number":Number.isFinite(e)||$e("device.executeProtocol 协议对象不能包含非有限数字");return;case"undefined":$e("device.executeProtocol 协议对象不能包含 undefined");return;case"function":case"symbol":case"bigint":$e(`device.executeProtocol 协议对象只能包含 JSON 数据,不能包含 ${typeof e}`);return}const r=e;if(t.has(r)&&$e("device.executeProtocol 协议对象不能包含循环引用"),t.add(r),Array.isArray(r)){for(const i of r)na(i,t);t.delete(r);return}const n=Object.getPrototypeOf(r);n!==Object.prototype&&n!==null&&$e("device.executeProtocol 协议对象只能包含普通 JSON 对象,不能包含类实例或特殊对象");for(const i of Object.values(r))na(i,t);t.delete(r)}function Xw(e){return{[Ji]:async(t,r)=>{const n=Se(e.operationContext,r.signal,r.requestId);pe(n.signal),await fe(()=>e.presentation.vibrate(Zw(t),n),n.signal)},[Xi]:async(t,r)=>{const n=Se(e.operationContext,r.signal,r.requestId);pe(n.signal),await fe(()=>e.presentation.setClipboard(Kw(t),n),n.signal)},[eo]:async(t,r)=>{const n=Se(e.operationContext,r.signal,r.requestId);pe(n.signal);const i=Jw(t);await fe(()=>e.protocol.invoke(i,n),n.signal)}}}const _d=1e3,eI=new Set(["FILE_NOT_FOUND","DIRECTORY_NOT_FOUND","FILE_TYPE_MISMATCH"]);function tI(e){const t=r=>Se(e.operationContext,r.signal);return{files:{[Bi]:async(r,n)=>{rs(n);const i=ns(e.picker),o=rI(r),s=await Ze(()=>i.pickFiles(o,t(n)));return e.registry.registerFiles(s,"external",o.mode,o.multiple?void 0:1)},[Hi]:async(r,n)=>{rs(n);const i=ns(e.picker),o=nI(r),s=await Ze(()=>i.pickDirectory(o,t(n)));return e.registry.registerDirectory(s,"external",o.mode)},[Fi]:async(r,n)=>{rs(n);const i=ns(e.picker),o=iI(r).suggestedName,s=t(n);if(!i.saveFile)throw tt("files.saveFile");const a=await Ze(()=>i.saveFile({suggestedName:o},s));return e.registry.registerFile(a,"external","readwrite")}},file:{[In]:async(r,n)=>{const i=Xe(r,["recursive","exclusive"]),o=e.registry.resolveFile(i.target);Er(o.mode),await Ze(()=>o.create(Dd(i),t(n)))},[An]:async(r,n)=>{const i=Xe(r),o=e.registry.resolveFileEntry(i.target);if(e.registry.assertSandboxOrigin(o),Er(o.handle.mode),!o.handle.remove)throw tt(An);await Ze(()=>o.handle.remove(t(n)))},[Vi]:async(r,n)=>{const i=Xe(r);return Nd(async()=>{const o=await e.registry.resolveFile(i.target).stat(t(n));if(!re(o)||o.kind!=="file")throw Sd()})},[_n]:async(r,n)=>{const i=Xe(r),o=Md(await Ze(()=>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 y("FILE_ENCODING_INVALID","文件不是合法 UTF-8 文本")}},[Gi]:async(r,n)=>{const i=Xe(r,["content"]);typeof i.content!="string"&&nt("content 必须是字符串");const o=e.registry.resolveFile(i.target);Er(o.mode),await Ze(()=>o.write(new TextEncoder().encode(i.content),t(n)))},[Dn]:async(r,n)=>{const i=Xe(r),o=await Ze(()=>e.registry.resolveFile(i.target).read(t(n)));return Md(o)},[$i]:async(r,n)=>{const i=Xe(r,["content"]),o=e.registry.resolveFile(i.target);Er(o.mode),await Ze(()=>o.write(sI(i.content),t(n)))},[Nn]:async(r,n)=>{const i=Xe(r),o=await Ze(()=>e.registry.resolveFile(i.target).stat(t(n)));return aI(o)}},directory:{[qi]:async(r,n)=>{const i=Xe(r,["recursive","exclusive"]),o=e.registry.resolveDirectory(i.target);Er(o.mode),await Ze(()=>o.create(Dd(i),t(n)))},[Mn]:async(r,n)=>{const i=Xe(r,["recursive"]);if(re(i.target)&&i.target.relativePath===".")throw y("FILE_ACCESS_DENIED","不能删除根目录");const o=e.registry.resolveDirectoryEntry(i.target);if(e.registry.assertSandboxOrigin(o),Er(o.handle.mode),!o.handle.remove)throw tt(Mn);await Ze(()=>o.handle.remove({recursive:i.recursive===void 0?!1:fo(i.recursive,"recursive")},t(n)))},[Qi]:async(r,n)=>{const i=Xe(r);return Nd(async()=>{const o=await e.registry.resolveDirectory(i.target).stat(t(n));if(!re(o)||o.kind!=="directory")throw Sd()})},[Yi]:async(r,n)=>{const i=Xe(r,["limit"]),o=oI(i.limit),s=e.registry.resolveDirectoryEntry(i.target),a=await Ze(()=>s.handle.list({limit:o},t(n)));return e.registry.describeListedEntries(s,a,o)}}}}function rI(e){if(e===void 0)return{mode:"read",multiple:!1};re(e)||nt("pickFiles 参数必须是对象"),Uo(e,["mode","accept","multiple"]);const t=Cf(e.mode,"read"),r=e.multiple===void 0?!1:fo(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)))&&nt("accept 必须是规范扩展名数组"),n=[...new Set(e.accept)]),{mode:t,multiple:r,...n===void 0?{}:{accept:n}}}function nI(e){return e===void 0?{mode:"read"}:(re(e)||nt("pickDirectory 参数必须是对象"),Uo(e,["mode"]),{mode:Cf(e.mode,"read")})}function iI(e){return re(e)||nt("saveFile 参数必须是对象"),Uo(e,["suggestedName"]),{suggestedName:Ln(e.suggestedName,"suggestedName")}}function Xe(e,t=[]){return(!re(e)||!Object.prototype.hasOwnProperty.call(e,"target"))&&nt("文件操作参数必须包含 target"),Uo(e,["target",...t]),e}function Dd(e){return{recursive:e.recursive===void 0?!1:fo(e.recursive,"recursive"),exclusive:e.exclusive===void 0?!1:fo(e.exclusive,"exclusive")}}function Cf(e,t){return e===void 0?t:(e!=="read"&&e!=="readwrite"&&nt("mode 必须是 read 或 readwrite"),e)}function fo(e,t){return typeof e!="boolean"&&nt(`${t} 必须是布尔值`),e}function oI(e){if(e===void 0)return _d;if((!Number.isSafeInteger(e)||e<=0)&&nt("limit 必须是正整数"),e>_d)throw y("DIRECTORY_LIST_LIMIT_EXCEEDED","目录项限制超过 Host 上限");return e}function Uo(e,t){const r=Object.keys(e).filter(n=>!t.includes(n));r.length&&nt(`不支持字段: ${r.join(", ")}`)}function Er(e){if(e!=="readwrite")throw y("FILE_ACCESS_DENIED","当前文件授权只允许读取")}function rs(e){if(!e.trustedUserGesture)throw y("USER_GESTURE_REQUIRED","当前操作需要可信用户手势")}function ns(e){if(!e)throw tt("files.external");return e}async function Nd(e){try{return await e(),!0}catch(t){if(eI.has(Wa(t)??""))return!1;throw Pr(t)}}async function Ze(e){try{return await e()}catch(t){throw Pr(t)}}function sI(e){return e instanceof Uint8Array||nt("content 必须是 Uint8Array"),typeof SharedArrayBuffer<"u"&&e.buffer instanceof SharedArrayBuffer&&nt("不支持 SharedArrayBuffer-backed Uint8Array"),new Uint8Array(e)}function Md(e){if(!(e instanceof Uint8Array))throw y("FILE_IO_FAILED","Host 返回了无效字节数据");return new Uint8Array(e)}function Sd(){return y("FILE_TYPE_MISMATCH","文件句柄类型不匹配")}function aI(e){if(!re(e)||e.kind!=="file"||!cI(e.size))throw y("FILE_IO_FAILED","Host 返回了无效 FileStat");for(const t of["modifiedAt","createdAt"])if(e[t]!==void 0&&!dI(e[t]))throw y("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 cI(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function dI(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0}function nt(e){throw y("INVALID_PARAMS",e)}const bd=16*1024,Td=200;function uI(e){const t=Kl(e.runtimePermissions);function r(n,i){e.capabilities&&Gl(i,e.capabilities);const o=t({kind:"all",permissions:["filesystem"]},i);if(!o.allowed)throw y(o.code,o.message);const s=Se(e.operationContext,n);return ia(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 vd(()=>s.handle.list({limit:Td},o),o);return e.registry.describeListedEntries(s,a,Td).map(({name:c,kind:d})=>({name:c,kind:d}))},async read(n,i={}){const o=i.maxBytes??bd;if(!Number.isSafeInteger(o)||o<1||o>bd)throw y("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 y("DIAGNOSTICS_UNSUPPORTED","当前 Host 不支持有界文件诊断读取");const c=await vd(()=>a.readPrefix({maxBytes:o},s),s);if(!c||!(c.bytes instanceof Uint8Array)||c.bytes.byteLength>o||typeof c.truncated!="boolean")throw y("FILE_IO_FAILED","Host 返回了无效的有界读取结果");return{bytes:new Uint8Array(c.bytes),truncated:c.truncated}}}}function ia(e){if(e.signal.aborted)throw y("FILE_ACCESS_REVOKED","诊断文件查询已取消或实例已结束")}async function vd(e,t){let r;try{const n=await Promise.race([e(),new Promise((i,o)=>{r=()=>o(y("FILE_ACCESS_REVOKED","诊断文件查询已取消或实例已结束")),t.signal.addEventListener("abort",r,{once:!0}),t.signal.aborted&&r()})]);return ia(t),n}catch(n){throw t.signal.aborted&&ia(t),Pr(n)}finally{r&&t.signal.removeEventListener("abort",r)}}const lI=new Set(["METHOD_FORBIDDEN","MEDIA_PICKER_CANCELLED","MEDIA_SYSTEM_PERMISSION_DENIED","MEDIA_PREPARE_FAILED","MEDIA_PREVIEW_UNAVAILABLE","REQUEST_UNSUPPORTED","USER_GESTURE_REQUIRED"]),is={METHOD_FORBIDDEN:"当前 Host 未开放媒体选择能力",MEDIA_PICKER_CANCELLED:"用户取消了媒体选择",MEDIA_SYSTEM_PERMISSION_DENIED:"系统未授予相机或相册权限",MEDIA_PREPARE_FAILED:"媒体准备失败,未保留部分结果",MEDIA_PREVIEW_UNAVAILABLE:"当前 Host 无法提供受控媒体预览",REQUEST_UNSUPPORTED:"当前 Host 不支持该媒体请求形态",USER_GESTURE_REQUIRED:"当前操作需要可信用户手势"};function fI(e){if(e instanceof Le)return y("REQUEST_UNSUPPORTED",is.REQUEST_UNSUPPORTED);const t=Lf(e);return t!==void 0&&lI.has(t)?y(t,is[t]??"媒体操作失败"):y("MEDIA_PREPARE_FAILED",is.MEDIA_PREPARE_FAILED)}function Lf(e){try{if(!re(e))return;const t=Object.getOwnPropertyDescriptor(e,"code");return t&&"value"in t&&typeof t.value=="string"?t.value:void 0}catch{return}}const hI=["source","mediaType","maxCount"],ui=Object.freeze({source:"album",mediaType:"all",maxCount:1});function mI(e){if(e===void 0)return ui;if(!Um(e))throw y("INVALID_PARAMS",pI(e));return gI(e)}function gI(e){return Object.freeze({source:e.source??ui.source,mediaType:e.mediaType??ui.mediaType,maxCount:e.maxCount??ui.maxCount})}function pI(e){if(!re(e))return"media.pick 参数必须是对象";const t=Object.keys(e).filter(r=>!hI.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 yI=new Set(["METHOD_FORBIDDEN","FILE_QUOTA_EXCEEDED","FILE_ACCESS_REVOKED","FILE_ACCESS_DENIED"]),EI={kind:"file",name:"media-probe",mode:"read",ref:{kind:"file",handleId:"media-probe"}};class wI{constructor(t,r,n){this.registry=t,this.media=r,this.operationContext=n}committed=new Set;disposed=!1;commit(t,r){const n=II(t,r);let i=[];try{i=this.registerBatch(n,r.maxCount);const o=n.map((s,a)=>_I(s,i[a]));if(!xm(o))throw It("Host 返回的媒体结果未通过协议校验");for(const s of n)this.committed.add(s);return o}catch(o){throw this.registry.revokeFiles(i.map(DI).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=Lf(n);throw i!==void 0&&yI.has(i)?n:It("Host 返回的媒体文件资源无法登记为只读句柄")}}releaseItems(t,r){if(t.length!==0)try{const n=this.media.release(t,r);Promise.resolve(n).catch(()=>{})}catch{}}}function Od(e,t){if(e.signal.aborted)throw y("RUNTIME_DESTROYED","小程序 Runtime 已终止");if(t.aborted)throw y("REQUEST_CANCELLED","media.pick 已取消")}function II(e,t){if(!Array.isArray(e))throw It("Host 返回了无效媒体选择结果");const r=e.length;if(r===0)throw It("Host 未返回任何媒体项;用户取消不得作为空数组成功");if(r>t.maxCount)throw It("Host 返回的媒体项超过本次 maxCount");if(t.source==="camera"&&r!==1)throw It("相机必须恰好返回 1 项");for(let n=0;n<r;n+=1){if(!Object.prototype.hasOwnProperty.call(e,n))throw It("Host 返回了稀疏媒体结果");AI(e[n],n)}return e}function AI(e,t){if(!re(e))throw It(`第 ${t+1} 项不是对象`);if(!_l({...e,file:EI}))throw It(`第 ${t+1} 项不符合 media.pick 媒体项契约`);if(!re(e.file))throw It(`第 ${t+1} 项缺少文件句柄`)}function _I(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 DI(e){return"handleId"in e.ref?e.ref.handleId:void 0}function It(e){return y("MEDIA_PREPARE_FAILED",e)}function NI(e){const t=e.media?new wI(e.registry,e.media,e.operationContext):void 0;return{handlers:{[Sn]:async(n,i)=>{const o=mI(n);SI(i);const s=e.media,a=t;if(!s||typeof s.pick!="function"||!a)throw tt(Sn);const c=Se(e.operationContext,i.signal);Od(e.operationContext,i.signal);const d=await MI(s,o,c,e.operationContext,i.signal);Od(e.operationContext,i.signal);try{return a.commit(d,o)}catch(u){throw a.releaseBatch(d,c),u}}},dispose(){t?.dispose()}}}async function MI(e,t,r,n,i){try{return await fe(()=>e.pick(t,r),r.signal)}catch(o){throw n.signal.aborted?y("RUNTIME_DESTROYED","小程序 Runtime 已终止"):i.aborted?y("REQUEST_CANCELLED","media.pick 已取消"):fI(o)}}function SI(e){if(!e.trustedUserGesture)throw y("USER_GESTURE_REQUIRED","当前操作需要可信用户手势")}const Wn=4294967296;function bI(e){const t=new TI;return t.write(e),t.finish()}class TI{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<Wn?(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=vI(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<Wn)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/Wn),this.view.setUint32(this.offset+4,t),this.offset+=8}writeInt64(t){this.ensureCapacity(8),this.view.setUint32(this.offset,Math.floor(t/Wn)),this.view.setUint32(this.offset+4,t),this.offset+=8}}function vI(e){const t=new Uint8Array(OI(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 OI(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 Uf(e){oa(e);const t=bI(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 oa(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)oa(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");oa(s,t+1,r)}r.delete(e)}const RI=["pc","console","mobile"],kI=["game","wiki"];function ho(e){throw{code:"INVALID_PARAMS",message:e}}function PI(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function jt(e,t){return typeof e!="string"||!e.trim()?ho(t):e.trim()}function Rd(e,t,r){return typeof e!="string"||!t.includes(e)?ho(r):e}function CI(e){const t={target:"game_detail",appId:jt(e.appId,"navigation.openAppPage appId 必须是非空字符串"),gameType:Rd(e.gameType,RI,"navigation.openAppPage gameType 必须是 pc、console 或 mobile")};return e.page!==void 0&&(t.page=Rd(e.page,kI,"navigation.openAppPage page 必须是 game 或 wiki")),e.hSrc!==void 0&&(t.hSrc=jt(e.hSrc,"navigation.openAppPage hSrc 必须是非空字符串")),e.skuId!==void 0&&(t.skuId=jt(e.skuId,"navigation.openAppPage skuId 必须是非空字符串")),t}function LI(e){return{target:"user_detail",userId:jt(e.userId,"navigation.openAppPage userId 必须是非空字符串")}}function UI(e){const t={target:"post_detail",linkId:jt(e.linkId,"navigation.openAppPage linkId 必须是非空字符串")};return e.rootCommentId!==void 0&&(t.rootCommentId=jt(e.rootCommentId,"navigation.openAppPage rootCommentId 必须是非空字符串")),e.commentId!==void 0&&(t.commentId=jt(e.commentId,"navigation.openAppPage commentId 必须是非空字符串")),t}function xI(e){const t={target:"mini_program",miniProgramId:jt(e.miniProgramId,"navigation.openAppPage miniProgramId 必须是非空字符串")};return e.extra!==void 0&&(t.extra=e.extra),t}function zI(e){return PI(e)?e.target==="game_detail"?CI(e):e.target==="user_detail"?LI(e):e.target==="post_detail"?UI(e):e.target==="mini_program"?xI(e):ho("navigation.openAppPage target 不支持"):ho("navigation.openAppPage options 必须是对象")}function jI(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 BI(e){return{protocolType:"openRouterPath",path:"/user_home",params:{userid:e.userId}}}function HI(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 FI(e){const t=e;return t.target==="game_detail"?jI(t):t.target==="user_detail"?BI(t):HI(t)}const VI="data:image/svg+xml;base64,PHN2ZyBwcmVzZXJ2ZUFzcGVjdFJhdGlvPSJub25lIiBvdmVyZmxvdz0idmlzaWJsZSIgc3R5bGU9ImRpc3BsYXk6IGJsb2NrOyIgd2lkdGg9IjIwIiBoZWlnaHQ9IjIwIiB2aWV3Qm94PSIwIDAgMjAgMjAiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxnIGlkPSJJY29uIj4KPHBhdGggaWQ9IlVuaW9uIiBkPSJNNS4wMzMzOCAxLjI5Mjg5QzUuNDIzOSAwLjkwMjM2OSA2LjA1NzI0IDAuOTAyMzY5IDYuNDQ3NzYgMS4yOTI4OUM2LjgzODI3IDEuNjgzNDIgNi44MzgyOCAyLjMxNjc2IDYuNDQ3NzYgMi43MDcyN0w1LjIzODQ2IDMuOTE2NThIMTEuNjY2N0MxNS40NDA1IDMuOTE2NzEgMTguNTAwMSA2Ljk3NjIgMTguNTAwMSAxMC43NTAxQzE4LjUgMTQuNTIzOCAxNS40NDA0IDE3LjU4MzQgMTEuNjY2NyAxNy41ODM1SDMuMzMzMzVDMi43ODExMiAxNy41ODM1IDIuMzMzMjcgMTcuMTM1NiAyLjMzMzE5IDE2LjU4MzRDMi4zMzMxOSAxNi4wMzExIDIuNzgxMDcgMTUuNTgzMiAzLjMzMzM1IDE1LjU4MzJIMTEuNjY2N0MxNC4zMzU5IDE1LjU4MzEgMTYuNDk5NyAxMy40MTkzIDE2LjQ5OTggMTAuNzUwMUMxNi40OTk4IDguMDgwNzYgMTQuMzM1OSA1LjkxNzAzIDExLjY2NjcgNS45MTY5SDQuNTkwNjdMNi40NDc3NiA3Ljc3NDhDNi44MzgyMSA4LjE2NTMzIDYuODM4MjYgOC43OTg2OCA2LjQ0Nzc2IDkuMTg5MThDNi4wNTcyNCA5LjU3OTQ1IDUuNDIzODMgOS41Nzk1NiA1LjAzMzM4IDkuMTg5MThMMS43OTI4MyA1Ljk0NzgyQzEuNDAyMzEgNS41NTczIDEuNDAyMzEgNC45MjM5NiAxLjc5MjgzIDQuNTMzNDRMNS4wMzMzOCAxLjI5Mjg5WiIgZmlsbD0id2hpdGUiLz4KPC9nPgo8L3N2Zz4K",GI="data-hb-sdk-fullscreen-exit",$I=3e3,qI=2e3,kd="var(--white-70a,rgba(255,255,255,.7))",Pd="0 0 var(--space-8,8px) var(--white-20a,rgba(255,255,255,.2))";function QI(e){if(typeof document>"u"||!document.body)return;const t=document.createElement("button");t.type="button",t.setAttribute(GI,""),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 ${kd}`,`box-shadow:${Pd}`,"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=VI,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 f(){o||(t.style.width=u())}function l(){d?.cancel(),d=void 0}function h(_=qI){clearTimeout(c),c=setTimeout(()=>{l(),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")},_)}function m(){l(),o=!0,t.style.width="48px",t.style.opacity="1",t.style.borderColor=kd,t.style.boxShadow=Pd,n.style.visibility="",i.style.display="",t.setAttribute("aria-label","退出全屏"),t.setAttribute("aria-expanded","true"),h()}async function E(){if(!(s||a)){if(!o){m();return}a=!0,clearTimeout(c),l();try{await e()}catch{}finally{a=!1,s||m()}}}return t.addEventListener("click",E),window.addEventListener("resize",f),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"})),h($I),{dispose(){s=!0,clearTimeout(c),l(),t.removeEventListener("click",E),window.removeEventListener("resize",f),t.remove()}}}const xf=1e4;function zf(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()},xf);return{signal:r.signal,async run(s){try{return await fe(s,r.signal)}catch(a){throw n??a}},dispose(){clearTimeout(o),e.removeEventListener("abort",i),t?.removeEventListener("abort",i)}}}function Cd(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 os(e,t){return e.mode===t.mode&&e.hideCapsule===t.hideCapsule}function Xr(){return{code:"REQUEST_CANCELLED",message:"方向设置已取消"}}function YI(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(m){if(!m.hideCapsule){c();return}a??=QI(()=>h.apply({orientation:"portrait",fullscreen:!1},void 0,"user"))}e.operationContext.signal.addEventListener("abort",c,{once:!0});function u(m,E){if(n===m){if(n=void 0,clearTimeout(m.timer),e.operationContext.signal.removeEventListener("abort",f),"error"in E)m.controller.abort();else if(i={options:m.options,result:E.result},o=m.options,d(m.options),e.onApplied?.(m.options),E.result.supported&&!os(s,m.options)){s={...m.options};try{e.onDisplayChange?.({orientation:s.mode,fullscreen:s.hideCapsule,source:m.source})}catch{}}for(const _ of m.subscribers)_.dispose(),"error"in E?_.reject(E.error):_.resolve(E.result);m.subscribers.clear()}}function f(){n&&u(n,{error:Xr()})}function l(m,E){return new Promise((_,w)=>{const S=()=>{m.subscribers.delete(p),p.dispose(),w(Xr()),m.subscribers.size===0&&u(m,{error:Xr()})},p={resolve:_,reject:w,dispose:()=>E?.removeEventListener("abort",S)};m.subscribers.add(p),E?.addEventListener("abort",S,{once:!0}),E?.aborted&&S()})}const h={async runDisplayRequest(m,E,_){const w=++t,S=zf(E,e.operationContext.signal);try{return await S.run(async()=>{if(await _(S.signal),S.signal.aborted)throw Xr();if(Cd(m),w<r)throw{code:"ORIENTATION_SUPERSEDED",message:"方向设置已被后续设置替换"};return r=w,h.apply(m,S.signal)})}finally{S.dispose()}},async apply(m,E,_="api"){if(pe(e.operationContext.signal),E?.aborted)throw Xr();const w=Cd(m),S=n?.options??o,p={mode:w.orientation??S.mode,hideCapsule:w.fullscreen??S.hideCapsule};p.mode==="landscape"&&(p.hideCapsule=!0);const M=e.presentation.applyOrientation;if(!M)throw{code:"METHOD_FORBIDDEN",message:"当前宿主暂不支持方向控制"};if(n&&os(n.options,p))return l(n,E);if(n&&u(n,{error:{code:"ORIENTATION_SUPERSEDED",message:"方向设置已被后续设置替换"}}),i&&os(i.options,p))return i.result;i=void 0;const z={options:p,source:_,controller:new AbortController,subscribers:new Set};n=z;const A=l(z,E);return e.operationContext.signal.addEventListener("abort",f,{once:!0}),E||(z.timer=setTimeout(()=>{u(z,{error:{code:"ORIENTATION_TIMEOUT",message:"方向切换超时"}})},xf)),fe(()=>M.call(e.presentation,p,{...e.operationContext,signal:z.controller.signal}),z.controller.signal).then(D=>u(z,{result:D??{supported:!0}}),D=>u(z,{error:D})),A},dispose(){e.operationContext.signal.removeEventListener("abort",c),c()}};return h}function jf(e){throw{code:"INVALID_PARAMS",message:e}}function Ld(e,t){e!==void 0&&(typeof e!="object"||e===null||Array.isArray(e)||Object.keys(e).length)&&jf(`${t} 不支持参数`)}function WI(e){return{[to]:async(t,r)=>{const n=Se(e.operationContext,r.signal,r.requestId);pe(n.signal),Ld(t,"navigation.close"),await fe(()=>e.presentation.close(n),n.signal)},[ro]:async(t,r)=>{const n=Se(e.operationContext,r.signal,r.requestId);pe(n.signal),Ld(t,"navigation.reload"),await fe(()=>e.presentation.reload(n),n.signal)},[no]:async(t,r)=>{const n=Se(e.operationContext,r.signal,r.requestId);pe(n.signal);const i=zI(t);if(i.target==="mini_program"){let o;if(i.extra!==void 0)try{o=Uf(i.extra)}catch{jf("navigation.openAppPage extra 必须是符合限制的 JSON-compatible 数据")}const s=e.resetDisplay;if(s){const a=zf(n.signal);try{await a.run(()=>s(a.signal))}finally{a.dispose()}}pe(n.signal),await fe(()=>e.presentation.openWindow({miniProgramId:i.miniProgramId,...o===void 0?{}:{extra:o}},n),n.signal);return}await fe(()=>e.presentation.openAppPage(FI(i),n),n.signal)}}}const Ud={UPLOAD_CANCELLED:"上传已取消",UPLOAD_TIMEOUT:"上传空闲超时",UPLOAD_NETWORK_FAILED:"上传网络失败",FILE_CHANGED:"上传源文件已变化",METHOD_FORBIDDEN:"当前 Host 未开放上传能力"};async function ZI(e,t,r){const n=r.transfer?.upload,i=r.fileRegistry;if(!n||!i)throw tt("network.upload");const o=Se(r.operationContext,t.signal),s=()=>{if(o.signal.aborted)throw y("UPLOAD_CANCELLED","上传已取消")};s();let a,c;try{a=i.resolveFileEntry(e.from).hostHandle,c=await a.stat(o)}catch(l){throw s(),Pr(l)}if(s(),c.kind!=="file"||!Number.isSafeInteger(c.size)||c.size<0)throw y("FILE_IO_FAILED","上传源文件状态无效");if(e.maxBytes!==void 0&&c.size>e.maxBytes)throw y("FILE_TOO_LARGE","文件超过大小限制");let d=0,u=!1;const f=l=>{u||o.signal.aborted||!Number.isSafeInteger(l)||l<d||l>c.size||(d=l,t.postProgress({loaded:d,total:c.size,lengthComputable:!0}))};try{const{from:l,...h}=e,m=await n.upload(a,{...h,expectedBytes:c.size,...e.format==="multipart"?{fileName:e.fileName??a.name}:{}},{...o,onProgress:f});if(u=!0,!Number.isSafeInteger(m.uploadedBytes)||m.uploadedBytes<d||m.uploadedBytes>c.size)throw y("UPLOAD_NETWORK_FAILED","Host 返回的上传字节数无效");if(m.status>=200&&m.status<300&&m.uploadedBytes!==c.size)throw y("FILE_CHANGED","上传源文件已变化");return t.postProgress({loaded:m.uploadedBytes,total:c.size,lengthComputable:!0}),m}catch(l){u=!0;const h=Wa(l);throw h&&Ud[h]?y(h,Ud[h]):o.signal.aborted?y("UPLOAD_CANCELLED","上传已取消"):h?.startsWith("FILE_")||h?.startsWith("DIRECTORY_")?Pr(l):y("UPLOAD_NETWORK_FAILED","上传网络失败")}}const ic="withCredentials",KI=new Set(["url","method","params","data","headers","timeout",ic]),JI=new Set(["url","to","params","headers","timeout","suggestedName","overwrite","maxBytes",ic]),XI=new Set(["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"]),xd=3e4,sa=2*1024*1024,eA=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,Bf=/[\u0000-\u0008\u000A-\u001F\u007F]/,tA=/^(?:authorization|authentication-info|proxy-authentication-info|cookie|set-cookie|set-cookie2|pkey|x-pkey|x-access-token|x-auth-token)$/i,rA="network.request 不支持 multipart/form-data,请使用专用上传能力";function nA(e){const t=iA(e.runtimePermissions);t.networkPolicy=Ql(e.networkPolicy);const r=EA(e.allowedHttpOrigins);return{[ji]:async(n,i)=>{const o=sA(n,{permission:t,allowedHttpOrigins:r}),s=await ZI(o,i,e),{uploadedBytes:a,...c}=s;return jd(c)},[zi]:async(n,i)=>{const o=aA(n,{permission:t,allowedHttpOrigins:r});return of(o,i,{transfer:e.transfer,fileRegistry:e.fileRegistry,operationContext:e.operationContext})},[xi]:async(n,i)=>{const o=Se(e.operationContext,i?.signal);pe(o.signal);const s=oA(n,{permission:t,allowedHttpOrigins:r});let a;try{a=await fe(()=>e.network.request(s,o),o.signal)}catch(c){throw IA(c)?c:AA(c,"REQUEST_UNSUPPORTED")?he("REQUEST_UNSUPPORTED","当前 Host 不支持该网络请求"):he("REQUEST_FAILED","网络请求失败")}return jd(a)}}}function iA(e){const t=qe(e),r=t.permissions.network;return{enabled:t.valid&&r?.status==="enabled",useOfficialDomain:t.valid&&r?.status==="enabled"&&r.config.useOfficialDomain===!0}}function oA(e,t){const r=Lr(e,"network.request 参数必须是对象"),n=Object.keys(r).filter(c=>!KI.has(c));if(n.length>0)throw he("INVALID_PARAMS",`network.request 不支持字段: ${n.join(", ")}`);Hf(r,"network.request");const i=oc(r,t,"network.request"),o=dA(r.method),s=r.data;s!==void 0&&fA(s),mA(i.headers,s);const a=gA(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 sA(e,t){const r=Lr(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 he("INVALID_PARAMS","network.upload 包含不支持的字段");const i=oc(r,t,"network.upload");if(i.official)throw he("PERMISSION_DENIED","上传暂不支持官方域名");if(i.timeout!==void 0&&i.timeout<=0)throw he("INVALID_PARAMS","上传 timeout 必须是有限正数");if(!er(r.from))throw he("INVALID_PARAMS","from 必须是有效 File ref");if(r.maxBytes!==void 0&&(!Number.isSafeInteger(r.maxBytes)||r.maxBytes<=0))throw he("INVALID_PARAMS","maxBytes 必须是正的 safe integer");if(r.format!=="raw"&&r.format!=="multipart")throw he("INVALID_PARAMS","format 必须是 raw 或 multipart");const o=r.method??(r.format==="raw"?"PUT":"POST");if(o!=="POST"&&(r.format!=="raw"||o!=="PUT"))throw he("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 he("INVALID_PARAMS","raw 不接受 multipart 字段");return s}if(Object.keys(i.headers??{}).some(u=>u.toLowerCase()==="content-type"))throw he("INVALID_PARAMS","multipart Content-Type 由 Host 生成");const a=zd(r.fieldName),c=r.fields===void 0?void 0:Lr(r.fields,"fields 必须是字符串字典");for(const[u,f]of Object.entries(c??{}))if(zd(u),typeof f!="string"||u===a)throw he("INVALID_PARAMS","fields 必须是字符串且不得与文件字段重名");if(r.fileName!==void 0&&typeof r.fileName!="string")throw he("INVALID_PARAMS","fileName 必须是字符串");if(r.contentType!==void 0&&(typeof r.contentType!="string"||Bf.test(r.contentType)||!/^[^\s/;]+\/[^\s;]+(?:;[^\r\n]*)?$/.test(r.contentType)))throw he("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>sa)throw he("INVALID_PARAMS","multipart 元数据超过 2 MiB");return{...s,fieldName:a,...c===void 0?{}:{fields:{...c}},...r.fileName===void 0?{}:{fileName:Ka(r.fileName)},contentType:r.contentType??"application/octet-stream"}}function zd(e){if(typeof e!="string"||!e||/[\u0000-\u001F\u007F"\\]/.test(e))throw he("INVALID_PARAMS","multipart 字段名必须是非空且无控制字符的字符串");return e}function aA(e,t){const r=Lr(e,"network.download 参数必须是对象"),n=Object.keys(r).filter(c=>!JI.has(c));if(n.length>0)throw he("INVALID_PARAMS",`network.download 不支持字段: ${n.join(", ")}`);Hf(r,"network.download");const i=oc(r,t,"network.download");if(i.timeout!==void 0&&i.timeout<=0)throw he("INVALID_PARAMS","network.download timeout 必须是有限正数");Qy(i.headers);const o=er(r.to),s=Il(r.to);if(!o&&!s)throw he("INVALID_PARAMS","network.download to 必须是有效 File/Directory ref");if(o&&(r.suggestedName!==void 0||r.overwrite!==void 0))throw he("INVALID_PARAMS","File 下载目标不接受 suggestedName/overwrite");let a;if(r.suggestedName!==void 0){if(typeof r.suggestedName!="string")throw he("INVALID_PARAMS","suggestedName 必须是字符串");a=Ka(r.suggestedName)}if(r.overwrite!==void 0&&typeof r.overwrite!="boolean")throw he("INVALID_PARAMS","overwrite 必须是布尔值");if(r.maxBytes!==void 0&&(!Number.isSafeInteger(r.maxBytes)||r.maxBytes<=0))throw he("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 oc(e,t,r){const n=cA(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 he("PERMISSION_DENIED",`${r} 目标不在平台批准的域名清单中`);const s=jp(n);if(s&&!t.permission.useOfficialDomain)throw he("PERMISSION_DENIED","当前小程序暂不支持访问官方域名");if(zp(n.pathname,s))throw he("PERMISSION_DENIED",`${r} 不允许访问 Runtime 或账号敏感接口`);return{url:n,official:s,params:e.params===void 0?void 0:{...Lr(e.params,`${r} params 必须是对象`)},headers:e.headers===void 0?void 0:uA(e.headers,r),timeout:lA(e.timeout,r)}}function cA(e,t,r="network.request"){if(typeof e!="string"||!e.trim())throw he("INVALID_PARAMS",`${r} url 必须是 HTTP(S) URL`);let n;try{n=new URL(e)}catch{throw he("INVALID_PARAMS",`${r} url 必须是 HTTP(S) URL`)}if(n.protocol!=="http:"&&n.protocol!=="https:")throw he("INVALID_PARAMS",`${r} url 必须是 HTTP(S) URL`);if(n.username||n.password)throw he("INVALID_PARAMS",`${r} url 不允许包含用户信息`);if(n.protocol==="http:"&&!t.has(n.origin))throw he("PERMISSION_DENIED",`${r} 生产环境只允许 HTTPS`);return n}function dA(e){if(e===void 0)return;if(typeof e!="string"||!e.trim())throw he("INVALID_PARAMS","network.request method 必须是字符串");const t=e.trim().toUpperCase();if(!XI.has(t))throw he("INVALID_PARAMS","network.request method 不合法");return t}function uA(e,t="network.request"){const r=Lr(e,`${t} headers 必须是 Record<string, string>`),n={};for(const[i,o]of Object.entries(r)){const s=i.trim();if(!s||s!==i||!eA.test(s)||typeof o!="string"||Bf.test(o))throw he("INVALID_PARAMS",`${t} headers 必须是 Record<string, string>`);if(Bp(s))throw he("INVALID_PARAMS",`${t} 不允许设置敏感请求头: ${i}`);n[s]=o}return n}function Hf(e,t){const r=e[ic];if(r!==void 0&&typeof r!="boolean")throw he("INVALID_PARAMS",`${t} 旧版凭据字段必须是布尔值`)}function lA(e,t="network.request"){if(e!==void 0){if(typeof e!="number"||!Number.isFinite(e)||e<0)throw he("INVALID_PARAMS",`${t} timeout 必须是非负数字`);if(t==="network.request"&&e>xd)throw he("INVALID_PARAMS",`${t} timeout 不能超过 ${xd}ms`);return e}}function fA(e){if(typeof Blob<"u"&&e instanceof Blob||typeof FormData<"u"&&e instanceof FormData)throw he("INVALID_PARAMS","network.request data 不支持 File、Blob 或 FormData,请使用专用上传能力");if(hA(e)>sa)throw he("INVALID_PARAMS",`network.request data 不能超过 ${sa} 字节`)}function hA(e){if(typeof e=="string")return ss(e);if(e instanceof ArrayBuffer||ArrayBuffer.isView(e))return e.byteLength;if(typeof URLSearchParams<"u"&&e instanceof URLSearchParams)return ss(e.toString());try{const t=JSON.stringify(e);return t?ss(t):0}catch{throw he("INVALID_PARAMS","network.request data 必须可序列化")}}function mA(e,t){const r=Ff(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 he("INVALID_PARAMS",rA)}function gA(e,t,r){if(t===void 0)return;const n=Ff(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)||yA(t))?"form":pA(t)?"json":void 0}function Ff(e){return e?Object.entries(e).find(([r])=>r.trim().toLowerCase()==="content-type")?.[1].toLowerCase():void 0}function pA(e){return e===null||typeof e=="boolean"||typeof e=="number"||typeof e=="object"&&!ArrayBuffer.isView(e)&&!(e instanceof ArrayBuffer)}function yA(e){if(typeof e!="object"||e===null)return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function EA(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&&wA(n.hostname)&&t.add(n.origin)}catch{}return t}function wA(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 jd(e){return Object.keys(e.headers).some(Bd)?{...e,headers:Object.fromEntries(Object.entries(e.headers).filter(([t])=>!Bd(t)))}:e}function Bd(e){const t=e.trim().toLowerCase();return tA.test(t)||t.startsWith("x-heybox-")||t.startsWith("x-xhh-")}function IA(e){return e instanceof Error&&e.name==="AbortError"}function AA(e,t){return typeof e=="object"&&e!==null&&"code"in e&&e.code===t}function Lr(e,t){if(typeof e!="object"||e===null||Array.isArray(e))throw he("INVALID_PARAMS",t);return e}function ss(e){return new TextEncoder().encode(e).length}function he(e,t){return{code:e,message:t}}function _A(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function DA(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 NA(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=DA(i);o?r.has(o)||(r.add(o),n.push(o)):t.push("post.topicIds 每项必须是正整数或非空字符串")}return{invalidMessages:t,values:n}}function MA(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 Vf(e,t){if(e==null)return{};if(!_A(e))return{invalidMessage:`${t.method} post 必须是对象或 null`};const r=NA(e.topicIds),n=MA(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 SA(e){try{return new URL(e).protocol==="heybox-mini-dev:"}catch{return!1}}async function bA(e){try{if(SA(e.getCurrentHref()))return!0}catch{}try{return!!await e.isDevRuntime()}catch{return!1}}function xe(e){throw{code:"INVALID_PARAMS",message:e}}function jn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function aa(e,t){return typeof e!="string"||!e.trim()?xe(t):e}function TA(e,t){const r=aa(e,t);try{const n=new URL(r);return n.protocol!=="http:"&&n.protocol!=="https:"?xe(t):r}catch{return xe(t)}}function vA(e){return e==="wechatSession"||e==="wechatTimeline"||e==="qqFriend"||e==="qzone"||e==="weibo"}function Gf(e,t,r){const n=e.identity.get(),i=n?.miniProgramId.trim();if(!i)return xe(`${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 xe(`${t} 缺少有效的小程序分享地址`)}}function OA(e,t){if(!jn(e))return xe("share.showShareMenu 参数必须是对象");if(Object.prototype.hasOwnProperty.call(e,"url"))return xe("share.showShareMenu 不支持自定义 url");const r=e.channel;if(r!==void 0&&!vA(r))return xe("share.showShareMenu channel 不合法");const n=$f(e.extra,"share.showShareMenu");return{title:aa(e.title,"share.showShareMenu title 必须是非空字符串"),description:aa(e.desc,"share.showShareMenu desc 必须是非空字符串"),url:Gf(t,"share.showShareMenu",n),...e.imageUrl===void 0?{}:{imageUrl:TA(e.imageUrl,"share.showShareMenu imageUrl 必须是 HTTP(S) URL")},...r===void 0?{}:{channel:r}}}function $f(e,t){if(e!==void 0)try{return Uf(e)}catch{return xe(`${t} extra 必须是符合限制的 JSON-compatible 数据`)}}async function qf(e,t){return e.invalidMessage&&await fe(()=>bA(t.environment),t.operationContext.signal)?xe(e.invalidMessage):e.post}function Hd(e,t){const r=Number(e);return Number.isFinite(r)&&r>0?r:t}function RA(e){const t=e.getViewportMetrics();return{left:0,top:0,width:Hd(t.windowWidth,0),height:Hd(t.windowHeight,0)}}function ca(e,t){const r=Number(e);return!Number.isFinite(r)||r<0?xe(t):r}function Fd(e,t){const r=Number(e);return!Number.isFinite(r)||r<=0?xe(t):r}function kA(e){return jn(e)?{left:ca(e.left,"share.screenshot rect.left 必须是非负数字"),top:ca(e.top,"share.screenshot rect.top 必须是非负数字"),width:Fd(e.width,"share.screenshot rect.width 必须是正数"),height:Fd(e.height,"share.screenshot rect.height 必须是正数")}:xe("share.screenshot rect 必须是对象")}function Vd(e,t){if(e!=null&&!jn(e))return xe("share.screenshot 参数必须是对象");const r=e??{};return r.saveToAlbum!==void 0&&typeof r.saveToAlbum!="boolean"?xe("share.screenshot saveToAlbum 必须是布尔值"):r.watermarkTheme!==void 0&&r.watermarkTheme!=="light"&&r.watermarkTheme!=="dark"?xe("share.screenshot watermarkTheme 必须是 light 或 dark"):{watermarkTheme:r.watermarkTheme??"dark",rect:r.rect===void 0?RA(t):kA(r.rect),...r.delay===void 0?{}:{delay:ca(r.delay,"share.screenshot delay 必须是非负数字")},...r.saveToAlbum===void 0?{}:{saveToAlbum:r.saveToAlbum}}}async function PA(e,t){pe(t.operationContext.signal);const r=OA(e,t);let n=Vf(e.post,{maxTopicIds:1,method:"share.showShareMenu"});r.channel&&n.post&&(n={invalidMessage:n.invalidMessage||"share.showShareMenu channel 与 post 不能同时使用"});const i=await qf(n,t);return fe(()=>t.presentation.showShareMenu({...r,post:i},t.operationContext),t.operationContext.signal)}async function CA(e,t){if(pe(t.operationContext.signal),e!==void 0&&!jn(e))return xe("share.copyLink 参数必须是对象");const r=$f(e?.extra,"share.copyLink"),n=Gf(t,"share.copyLink",r);return await fe(()=>t.presentation.setClipboard({text:n},t.operationContext),t.operationContext.signal),n}async function Gd(e,t,r,n=!1){pe(t.operationContext.signal);const i=Vf(jn(e)?e.post:void 0,{method:"share.screenshot"}),o=await qf(i,t),s=t.identity.get()?.miniProgramId.trim()||void 0,a=LA(),{watermarkTheme:c,...d}=r;let u=!1,f,l,h;try{if(n&&(!t.presentation.supportsLongScreenshot||!t.prepareLongScreenshot))throw{code:"REQUEST_UNSUPPORTED",message:"当前宿主不支持 DOM 长图,请更新宿主"};if(u=!0,await fe(()=>t.presentation.setScreenshotChromeHidden(!0,t.operationContext),t.operationContext.signal),n){const _=await t.prepareLongScreenshot(r.rect,t.operationContext.signal);f=_.restore,d.rect=_.rect}l=await t.prepareScreenshot?.(d.rect,t.operationContext.signal,c),h={status:"fulfilled",value:await fe(()=>t.presentation.captureAndShare({...d,...n?{longContent:!0}:{},post:o,...s?{sourceMiniProgramId:s}:{}},t.operationContext),t.operationContext.signal)}}catch(E){h={status:"rejected",error:E}}finally{try{l?.()}finally{f?.()}}const m=u?await UA(t.presentation,a,t.operationContext.signal):void 0;if(h.status==="rejected")throw h.error;if(m)throw m;return h.value}function LA(){return{lifecycle:"cleanup",signal:new AbortController().signal}}async function UA(e,t,r){let n;try{n=Promise.resolve(e.setScreenshotChromeHidden(!1,t))}catch{return}try{await fe(()=>n,r,{invokeWhenAborted:!0})}catch(i){if(r.aborted)return i}}function xA(e){let t=Promise.resolve();const r=async(n,i)=>{const o=Se(e.operationContext,i.signal,i.requestId),s=Vd(n,e.presentation);(s.rect.top+s.rect.height>1e4||s.rect.left+s.rect.width>2048||s.rect.width*s.rect.height>4e6)&&xe("长图尺寸超出限制");const a=t.then(()=>Gd(n,{...e,operationContext:o},s,!0));return t=a.then(()=>{},()=>{}),a};return{[Ci]:r,[Ri]:(n,i)=>CA(n,{...e,operationContext:Se(e.operationContext,i.signal,i.requestId)}),[ki]:(n,i)=>PA(n,{...e,operationContext:Se(e.operationContext,i.signal,i.requestId)}),[Pi]:async(n,i)=>{const o=Se(e.operationContext,i.signal,i.requestId);pe(o.signal);const s=Vd(n,e.presentation),a=t.then(()=>Gd(n,{...e,operationContext:o},s));return t=a.then(()=>{},()=>{}),fe(()=>a,o.signal)}}}const $d=new WeakMap,Zn=new Map;function Qf(e){const t=e.canonicalIdentity?.miniProgramId?.trim();if(t)return sp(t);const r=e.anonymousStorageScope?.trim();if(r)return`anon_${Vl(r)}`;throw Object.assign(new Error("storage scope 只能在 canonical identity 绑定后使用"),{code:"INVALID_STATE"})}function Yf(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 f=$d.get(t);f||(f=new Map,$d.set(t,f));const l=f.get(u)??Promise.resolve(),h=async()=>(pe(c.signal,{preserveReason:!0}),d(u)),m=l.catch(()=>{}).then(()=>e.lock?e.lock(u,h):h());f.set(u,m);try{return await m}finally{f.get(u)===m&&f.delete(u)}},o=async(c,d,u=!1)=>{const f=fr(c,"");if(e.diagnostics)return[...new Set((await e.diagnostics.listRaw(d)).filter(m=>m.key.startsWith(f)&&m.value!=="").map(m=>m.key.slice(f.length)))];const l=await e.storage.getRaw(Gn(c),d);if((l===void 0||l==="")&&!u)throw Object.assign(new Error("当前客户端缺少数据索引,且不支持遍历本地数据,暂无法清理"),{code:"STORAGE_INDEX_MISSING"});let h;try{h=l?JSON.parse(l):[]}catch{throw new Error("本地数据索引异常")}if(!Array.isArray(h)||h.length>Uc||h.some(m=>typeof m!="string"||!/^[A-Za-z0-9_-]{1,128}$/.test(m)))throw new Error("本地数据索引异常");return[...new Set(h)]},s=async(c,d)=>{if(e.diagnostics){const l=fr(c,"");return(await e.diagnostics.listRaw(d)).filter(h=>h.key.startsWith(l)&&h.value!=="").map(h=>({...h,key:h.key.slice(l.length)}))}const u=[],f=await o(c,d);for(let l=0;l<f.length;l+=16){pe(d.signal,{preserveReason:!0});const h=await Promise.all(f.slice(l,l+16).map(async m=>{const E=await e.storage.getRaw(fr(c,m),d);return E!==void 0&&E!==""?{area:"local",key:m,value:E}:void 0}));for(const m of h)m&&u.push(m)}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(fr(u,c),d))},set(c,d,u){return a(c),i(u,async f=>{const l=await o(f,u,!0);if(!l.includes(c)&&l.length>=Uc)throw Object.assign(new Error("storage key 数量超出上限"),{code:"STORAGE_QUOTA_EXCEEDED"});if(!e.diagnostics){const h=[...new Set([...l,c])];await e.storage.setRaw(Gn(f),JSON.stringify(h),u)}pe(u.signal,{preserveReason:!0}),await e.storage.setRaw(fr(f,c),d,u),pe(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(Gn(d),JSON.stringify(u),c);for(let f=0;f<u.length;f+=16){pe(c.signal,{preserveReason:!0});const h=(await Promise.allSettled(u.slice(f,f+16).map(m=>e.storage.setRaw(fr(d,m),"",c)))).find(m=>m.status==="rejected");if(h)throw h.reason}pe(c.signal,{preserveReason:!0}),await e.storage.setRaw(Gn(d),"[]",c)})}}}function Wf(e,t){if(typeof navigator<"u"&&navigator.locks)return new Promise((n,i)=>{navigator.locks.request(`hb-miniprogram-storage:${e}`,()=>t().then(n,i)).catch(i)});const r=(Zn.get(e)??Promise.resolve()).catch(()=>{}).then(t);return Zn.set(e,r),r.finally(()=>{Zn.get(e)===r&&Zn.delete(e)})}const zA=128,jA=/^[A-Za-z0-9_-]+$/;function BA(e){const t=e.scopedStorage??Yf({storage:e.storage,resolveScope:()=>Qf({canonicalIdentity:e.identity.get(),anonymousStorageScope:e.anonymousStorageScope}),diagnostics:e.storageDiagnostics}),r={[En]:async n=>{pe(e.operationContext.signal);const i=qd(n,En,e.storageLimits?.maxKeyLength),o=await fe(()=>t.get(i,e.operationContext),e.operationContext.signal);return{data:Qd(o)}},[wn]:async n=>{pe(e.operationContext.signal);const i=Zf(n,"storage.setStorage 参数必须是对象"),o=qd(i,wn,e.storageLimits?.maxKeyLength),s=HA(i.data,e.storageLimits?.maxValueBytes);await fe(()=>t.set(o,s,e.operationContext),e.operationContext.signal)}};return!e.storageDiagnostics&&!e.scopedStorage?{handlers:r}:{handlers:r,diagnostics:{getSnapshot:async()=>(pe(e.operationContext.signal),(await fe(()=>t.list(e.operationContext),e.operationContext.signal).catch(i=>{throw i&&typeof i=="object"&&"code"in i&&i.code==="INVALID_STATE"?rr("STORAGE_DIAGNOSTICS_NOT_READY","Storage diagnostics 只能在 canonical identity 绑定后使用"):i})).map(i=>{const o=i.value;return{area:i.area,key:i.key,value:Qd(o),serializedValue:o,bytes:Kf(o)}}).sort((i,o)=>i.key.localeCompare(o.key)))}}}function qd(e,t,r=zA){const i=Zf(e,`${t} 参数必须是对象`).key;if(typeof i!="string")throw rr("INVALID_PARAMS",`${t} key 必须是字符串`);if(!i||i.length>r||!jA.test(i))throw rr("INVALID_PARAMS",`storage key 仅支持 1-${r} 位字母、数字、下划线和连字符`);return i}function HA(e,t){let r;try{r=JSON.stringify(e)}catch{throw rr("INVALID_PARAMS","storage.setStorage data 必须可 JSON 序列化")}if(typeof r!="string")throw rr("INVALID_PARAMS","storage.setStorage data 必须可 JSON 序列化");if(t!==void 0&&Kf(r)>t)throw rr("STORAGE_QUOTA_EXCEEDED",`storage.setStorage data 超出 ${t} 字节限制`);return r}function Qd(e){if(!(e===void 0||e===""))try{return JSON.parse(e)}catch{return e}}function Zf(e,t){if(typeof e!="object"||e===null||Array.isArray(e))throw rr("INVALID_PARAMS",t);return e}function Kf(e){return new TextEncoder().encode(e).length}function rr(e,t){return{code:e,message:t}}const Yd=120;function Lt(e){throw{code:"INVALID_PARAMS",message:e}}function sc(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Jf(e,t,r){const n=Object.keys(e).filter(i=>!t.includes(i));n.length&&Lt(`${r} 不支持字段: ${n.join(", ")}`)}function FA(e){if(!sc(e))return Lt("ui.showToast 参数必须是对象");if(Jf(e,["message","status"],"ui.showToast"),typeof e.message!="string"||!e.message.trim())return Lt("ui.showToast message 必须是非空字符串");const t=e.message.trim();if(t.length>Yd)return Lt(`ui.showToast message 不能超过 ${Yd} 字符`);const r=e.status;if(r!==void 0&&r!=="success"&&r!=="error")return Lt("ui.showToast status 必须是 success 或 error");const n=r;return{message:t,...n===void 0?{}:{status:n}}}function VA(e){return e===void 0?{dismissible:!1}:sc(e)?(Jf(e,["dismissible"],"ui.showLoading"),e.dismissible!==void 0&&typeof e.dismissible!="boolean"?Lt("ui.showLoading dismissible 必须是布尔值"):{dismissible:e.dismissible??!1}):Lt("ui.showLoading 参数必须是对象")}function GA(e){e!==void 0&&(!sc(e)||Object.keys(e).length)&&Lt("ui.hideLoading 不支持参数")}function $A(e){return{[Wi]:async(t,r)=>{const n=Se(e.operationContext,r.signal,r.requestId);pe(n.signal),await fe(()=>e.presentation.showToast(FA(t),n),n.signal)},[Zi]:async(t,r)=>{const n=Se(e.operationContext,r.signal,r.requestId);pe(n.signal),await fe(()=>e.presentation.showLoading(VA(t),n),n.signal)},[Ki]:async(t,r)=>{const n=Se(e.operationContext,r.signal,r.requestId);pe(n.signal),GA(t),await fe(()=>e.presentation.hideLoading(n),n.signal)}}}const qA={auth:"optional",channel:"api",failurePresentation:"none",id:"heybox.account.home_v2.get",method:"GET",path:"/account/home_v2/",parse(e){return Te(e,"当前用户首页资料接口响应异常")}},QA=3e4;function YA(e,t,r={}){const n=r.ttlMs??QA,i=r.requestPolicyEnabled!==!1,o=r.requestGate?{capability:"user",gate:r.requestGate}:void 0;let s=0,a,c;async function d(){let f;try{f=await Po(e,qA,void 0,{...t,credentials:"heybox-session",...o?{gate:o}:{}})}catch(l){throw t.signal.aborted?y("RUNTIME_DESTROYED","小程序 Runtime 已终止"):l instanceof Le?y("REQUEST_UNSUPPORTED",l.message):l instanceof zn?y("INVALID_RESPONSE","user home_v2 响应不合法"):l instanceof Cr?y("REQUEST_FAILED","user home_v2 请求失败"):l instanceof xn?i&&(l.status===403||l.status===429)?y("RATE_LIMITED","user home_v2 请求已被网关限流,请稍后重试",{status:l.status,...l.retryAfterMs===void 0?{}:{retryAfterMs:l.retryAfterMs}}):y("REQUEST_FAILED",l.message):ZA(l)?l:y("REQUEST_FAILED","user home_v2 请求失败")}return WA(f,"user home_v2")}function u(f){const l=Date.now();if(a?.userId===f&&a.expiresAt>l)return Promise.resolve(a.value);if(c?.userId===f&&c.generation===s)return c.promise;const h=s,m=d().then(E=>(s===h&&(a={userId:f,value:E,expiresAt:Date.now()+n}),E)).finally(()=>{c?.promise===m&&(c=void 0)});return c={userId:f,generation:h,promise:m},m}return{get:u,clear(){s+=1,a=void 0,c=void 0}}}function WA(e,t){if(!re(e))throw y("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 y(n,r)}if(!re(e.result))throw y("INVALID_RESPONSE",`${t} result 必须是对象`);return e.result}function ZA(e){return re(e)&&typeof e.code=="string"&&typeof e.message=="string"}const KA={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 Te(e,"关注用户接口响应异常")}},JA={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 Te(e,"ApiXiaoheiheCnUserMiniprogramRuntimeAuthorFollowStatus 接口响应异常")}},XA={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 Te(e,"ApiXiaoheiheCnUserMiniprogramRuntimeAuthorFollowGuidanceBegin 接口响应异常")}},e_={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 Te(e,"Steam 游戏库接口响应异常")}};function t_(e,t=Zs){const r=Xy({version:"2",validate:n_}),n={ttlMs:Number.isFinite(t)?Math.max(0,Math.floor(t)):Zs,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 Wd(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 r_(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 n_(e){if(!re(e)||!Array.isArray(e.gameList)||typeof e.hasMore!="boolean"||!Number.isInteger(e.nextOffset)||Number(e.nextOffset)<0||(Zd(e,"total"),e.isMe!==void 0&&typeof e.isMe!="boolean"))throw Mr();for(const t of e.gameList){if(!re(t)||!da(t.appid)||!da(t.steamAppid)||typeof t.name!="string"||!t.name.trim())throw Mr();for(const r of["image","portraitImage","icon"])i_(t,r);for(const r of["playtimeForever","playtime2Weeks"])Zd(t,r);if(t.tags!==void 0&&(!Array.isArray(t.tags)||t.tags.some(r=>typeof r!="string"||!r.trim())))throw Mr()}return e}function da(e){return typeof e=="number"&&Number.isFinite(e)}function Zd(e,t){if(e[t]!==void 0&&!da(e[t]))throw Mr()}function i_(e,t){if(e[t]!==void 0&&typeof e[t]!="string")throw Mr()}function Mr(){return y("INVALID_RESPONSE","Steam 游戏库缓存数据不合法")}const Xf=20,o_=100,s_=128,eh=0,th="weeks",a_=100,c_=new Set(["weeks","all","achieved"]);function d_(){return{nickname:"",avatar:""}}function u_(e){const t=YA(e.network,e.operationContext,{requestGate:e.requestGate,requestPolicyEnabled:e.requestPolicyEnabled}),r=e.requestPolicyEnabled!==!1,n=e.cacheManager??cf(),i=t_(n,r?e.steamGameListTtlMs:0);let o;const s=new Map;let a=Promise.resolve();function c(O,j){const U=JSON.stringify([O,j]);return(!o||o.key!==U)&&(o={key:U,scope:n.createScope(j,n.createScope(O))}),o.scope}function d(){const O=o;o=void 0,O&&n.invalidateScope(O.scope).catch(()=>{}),s.clear()}const u=wf({ttlMs:Math.max(0,Math.floor(e.profileTtlMs??yf))}),f=e.requestGate?{capability:"user",gate:e.requestGate}:void 0;let l,h,m=0,E=!1;const _=e.account.onChange(()=>{m+=1,t.clear(),u.invalidate(),d()}),w=e.authorization.onEvent((O,j)=>{O==="user_info_authorization_change"&&Object.values(j).some(U=>U==="denied")&&(m+=1,t.clear(),u.invalidate(),d(),a=a.then(async()=>{if(E)return;const U=await e.account.getCurrentUserId(e.operationContext);typeof U=="string"&&U.trim()&&await n.invalidateScope(c(p(),U.trim()))}).catch(()=>{}))});function S(){if(E||e.operationContext.signal.aborted)throw y("RUNTIME_DESTROYED","小程序 Runtime 已终止")}function p(){const O=e.identity.get()?.miniProgramId?.trim();if(!O)throw y("INVALID_STATE","用户能力缺少 canonical 小程序身份");return O}async function M(){S(),await a,S();let O;try{O=await e.account.getCurrentUserId(e.operationContext)}catch(j){throw e.operationContext.signal.aborted?y("RUNTIME_DESTROYED","小程序 Runtime 已终止"):en(j)?j:y("REQUEST_FAILED","读取小黑盒账号失败")}return typeof O=="string"&&O.trim()?O.trim():void 0}async function z(O,j){const U=await M();if(m!==j||U!==O)throw y("AUTHORIZATION_CONTEXT_CHANGED","用户请求期间账号上下文已变化,请重新操作")}async function A(O,j,U=e.operationContext.signal){try{return await Po(e.network,O,j,{...e.operationContext,signal:U,credentials:"heybox-session",...f?{gate:f}:{}})}catch(L){throw e.operationContext.signal.aborted?y("RUNTIME_DESTROYED","小程序 Runtime 已终止"):L instanceof Le?y("REQUEST_UNSUPPORTED",L.message):L instanceof zn?y("INVALID_RESPONSE","用户接口响应不合法"):L instanceof Cr?y("REQUEST_FAILED","用户请求失败"):L instanceof xn?r&&(L.status===403||L.status===429)?y("RATE_LIMITED","用户请求已被网关限流,请稍后重试",{status:L.status,...L.retryAfterMs===void 0?{}:{retryAfterMs:L.retryAfterMs}}):y("REQUEST_FAILED",L.message):en(L)?L:y("REQUEST_FAILED","用户请求失败")}}async function D(O,j){if(!e.authorizationContext)return{mini_program_id:O};let U;try{U=await fe(()=>e.authorizationContext.get({...e.operationContext,signal:j}),j)}catch(L){if(en(L))throw L;const C=y("REQUEST_FAILED","读取 Runtime auth context 失败");throw Object.defineProperty(C,"cause",{configurable:!0,value:L}),C}if(!U.token?.trim())throw y("INVALID_STATE","关注作者缺少启动凭据");return{mini_program_id:O,runtime_auth_context_token:U.token}}async function I(){S();const O=p(),j=m,U=await M();if(!U){if(m!==j)throw y("AUTHORIZATION_CONTEXT_CHANGED","查询期间账号已变化");return"notFollowing"}const L=await D(O,e.operationContext.signal);await z(U,j);const C=await A(JA,L);if(await z(U,j),p()!==O)throw y("AUTHORIZATION_CONTEXT_CHANGED","查询期间小程序上下文已变化");return Xd(Jd(C))}function v(O,j){if(!O)return Promise.reject(y("USER_GESTURE_REQUIRED","请点击按钮关注作者"));if(j?.aborted)return Promise.reject(y("REQUEST_CANCELLED","关注操作已取消"));if(l)return Promise.reject(y("FOLLOW_IN_PROGRESS","关注确认流程尚未结束"));if(!e.authPresentation?.confirmFollowAuthor)return Promise.reject(y("METHOD_FORBIDDEN","当前宿主不支持关注确认框"));const U=T(j).finally(()=>{l===U&&(l=void 0)});return l=U,U}async function T(O){S();const j=p(),U=new AbortController;h=U;const L=()=>U.abort();e.operationContext.signal.addEventListener("abort",L,{once:!0}),O?.addEventListener("abort",L,{once:!0});let C=()=>{},H=!1;try{try{await fe(()=>e.account.ensureAuthenticated({trustedUserGesture:!0,reason:"user_action",signal:U.signal}),U.signal)}catch(ue){throw en(ue)&&["AUTH_CANCELLED","AUTHORIZATION_CANCELLED","HEYBOX_APP_LOGIN_REQUIRED","LOGIN_CANCELLED"].includes(ue.code)?y("FOLLOW_CANCELLED","已取消小黑盒登录"):ue}S();const F=m;C=e.account.onChange(()=>{H=!0,L()});const $=await fe(M,U.signal);if(!$)throw y("FOLLOW_CANCELLED","未完成小黑盒登录");const K=async()=>{if(await fe(()=>z($,F),U.signal),S(),p()!==j)throw y("AUTHORIZATION_CONTEXT_CHANGED","关注期间小程序上下文已变化")};await K();const g=await D(j,U.signal);await K();const P=w_(),B=await fe(()=>A(XA,{...g,request_id:P},U.signal),U.signal);await K();const Q=Jd(B);if(Q.status!=="notFollowing")return Xd(Q);if(Q.rateLimited)throw y("FOLLOW_GUIDANCE_LIMIT_REACHED","今日关注引导次数已达上限");const X=await fe(()=>e.authPresentation.confirmFollowAuthor({miniProgramId:j,signal:U.signal}),U.signal);if(await K(),X!=="confirmed")throw y("FOLLOW_CANCELLED","已取消关注作者");const ne=Q.authorId,ie=await fe(()=>A(KA,{body:{following_id:ne}},U.signal),U.signal);if(await K(),ie.status!=="ok"){const ue=["login","relogin","lack_token"].includes(ie.status)?"HEYBOX_APP_LOGIN_REQUIRED":"REQUEST_FAILED";throw y(ue,typeof ie.msg=="string"&&ie.msg.trim()?ie.msg.trim():"关注作者失败,请稍后重试")}return"following"}catch(F){throw S(),H?y("AUTHORIZATION_CONTEXT_CHANGED","关注期间账号已变化,请重新操作"):O?.aborted?y("REQUEST_CANCELLED","关注操作已取消"):en(F)?F:y("REQUEST_FAILED","关注作者失败,请稍后重试")}finally{C(),e.operationContext.signal.removeEventListener("abort",L),O?.removeEventListener("abort",L),h===U&&(h=void 0)}}async function x(){p();const O=m,j=await M();if(!j)return{isHeyboxAppLoggedIn:!1,authorization:null,userInfo:null};const[U,L]=await Promise.all([e.authorization.getOrCreateLocalIdentity(j),N(j).catch(()=>d_())]);return await z(j,O),{isHeyboxAppLoggedIn:!0,authorization:e.authorization.getAuthorization(),userInfo:{app_user_id:U.appUserId,profile:L,...U.steamId?{steam_id:U.steamId}:{}}}}function N(O){return u.read(O,()=>A(Ef,void 0).then(j=>{const U=ua(j,"账号基础信息");if(U.display_username!==void 0&&typeof U.display_username!="string")throw y("INVALID_RESPONSE","账号基础信息 nickname 不合法");if(U.display_avatar!==void 0&&typeof U.display_avatar!="string")throw y("INVALID_RESPONSE","账号基础信息 avatar 不合法");return{nickname:U.display_username??"",avatar:U.display_avatar??""}}))}async function b(O){const j=l_(O),U=p(),L=m,C=await M();if(!C)return d(),{isLogin:!1,isBound:!1,data:null};const H=await t.get(C);await z(C,L);const F=rh(H.steam_id_info);if(Object.keys(F).length===0)return await n.invalidateScope(c(U,C)).catch(()=>{}),await z(C,L),s.delete(JSON.stringify([U,C])),{isLogin:!0,isBound:!1,data:null};const $=JSON.stringify([U,C]),K=c(U,C),g=Wd({...j,steamId:void 0},F),P=nh(F.personal_infomation_open??F.personal_information_open),B=JSON.stringify([g??null,P??null]),Q=s.get($);Q&&Q.identity!==B&&(await n.invalidateScope(K).catch(()=>{}),await z(C,L));const X={identity:B,scope:n.createScope(B,K)};s.set($,X);const ne=Wd(j,F),ie=ne?i.persistent:i.unresolved,ue=n.createScope(ne??"unresolved",X.scope),Ee=async()=>{if(await z(C,L),p()!==U||s.get($)?.identity!==B)throw y("AUTHORIZATION_CONTEXT_CHANGED","Steam 游戏库请求期间绑定上下文已变化")},me=await ie.read({scope:ue,key:r_({miniProgramId:U,userId:C,effectiveSteamId:ne,personalInformationOpen:P,query:j}),signal:e.operationContext.signal,load:async ge=>{const ye=await A(e_,{userId:C,...j,personalInformationOpen:P},ge);return await Ee(),p_(ua(ye,"Steam 游戏库"),j)}}).catch(async ge=>{throw await Ee(),ge});return await Ee(),{isLogin:!0,isBound:!0,data:me}}return{getFollowStatus:I,requestFollowAuthor:v,getInfo:x,getSteamGameList:b,async invalidateSteamGameListCache(){const O=p(),j=m,U=await M();if(!U)return;const L=c(O,U);await Promise.all([i.persistent.invalidateScope(L),i.unresolved.invalidateScope(L)]),t.clear(),s.delete(JSON.stringify([O,U])),await z(U,j)},dispose(){E||(E=!0,h?.abort(),m+=1,_(),w(),t.clear(),u.dispose(),i.persistent.dispose(),i.unresolved.dispose(),e.cacheManager||n.dispose())}}}function l_(e){if(e==null)return{limit:Xf,offset:eh,sort:th,includeHidden:!1};if(!re(e))throw Ut("user.getSteamGameList 参数必须是对象");const t=Object.keys(e).find(n=>!["steamId","limit","offset","sort","q","includeHidden"].includes(n));if(t)throw Ut(`user.getSteamGameList 不支持字段: ${t}`);const r={limit:f_(e.limit),offset:h_(e.offset),sort:m_(e.sort),includeHidden:g_(e.includeHidden)};if(e.steamId!==void 0){if(typeof e.steamId!="string"||!e.steamId.trim()||e.steamId.trim().length>s_)throw Ut("user.getSteamGameList steamId 必须是非空字符串");r.steamId=e.steamId.trim()}if(e.q!==void 0){if(typeof e.q!="string")throw Ut("user.getSteamGameList q 必须是字符串");const n=e.q.trim();n&&(r.q=n.slice(0,a_))}return r}function f_(e){if(e===void 0)return Xf;if(!Number.isInteger(e)||Number(e)<1)throw Ut("user.getSteamGameList limit 必须是正整数");return Math.min(Number(e),o_)}function h_(e){if(e===void 0)return eh;if(!Number.isInteger(e)||Number(e)<0)throw Ut("user.getSteamGameList offset 必须是非负整数");return Number(e)}function m_(e){if(e===void 0)return th;if(typeof e!="string"||!c_.has(e))throw Ut("user.getSteamGameList sort 不支持");return e}function g_(e){if(e===void 0)return!1;if(typeof e!="boolean")throw Ut("user.getSteamGameList includeHidden 必须是 boolean");return e}function p_(e,t){if(!Array.isArray(e.game_list))throw y("INVALID_RESPONSE","Steam 游戏库 game_list 必须是数组");const r=e.game_list.map(y_).filter(a=>a!==void 0),n=mo(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=nh(e.is_me);return s!==void 0&&(o.isMe=s),o}function y_(e){const t=rh(e),r=mo(t.appid),n=mo(t.steam_appid)??r,i=ac(t.name);if(r===void 0||n===void 0||!i)return;const o={appid:r,steamAppid:n,name:i};as(o,"image",t.image),typeof t.vertical_head_image=="string"&&as(o,"portraitImage",t.vertical_head_image),as(o,"icon",t.appicon??t.icon),Kd(o,"playtimeForever",t.playtime_forever),Kd(o,"playtime2Weeks",t.playtime_2weeks);const s=E_(t.external_tags??t.tags);return s.length&&(o.tags=s),o}function ua(e,t){if(!re(e))throw y("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 y(n,r)}if(!re(e.result))throw y("INVALID_RESPONSE",`${t} result 必须是对象`);return e.result}function rh(e){return re(e)?e:{}}function ac(e){return typeof e=="string"?e.trim():typeof e=="number"||typeof e=="boolean"?String(e):""}function E_(e){return Array.isArray(e)?e.map(ac).filter(Boolean):[]}function mo(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"&&e.trim()&&Number.isFinite(Number(e)))return Number(e)}function nh(e){if(e===!0||e===1||e==="1")return!0;if(e===!1||e===0||e==="0")return!1}function as(e,t,r){const n=ac(r);n&&Object.assign(e,{[t]:n})}function Kd(e,t,r){const n=mo(r);n!==void 0&&Object.assign(e,{[t]:n})}function Ut(e){return y("INVALID_PARAMS",e)}function en(e){return re(e)&&typeof e.code=="string"&&typeof e.message=="string"}function Jd(e){const t=ua(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 y("INVALID_RESPONSE","关注状态响应不合法");return{status:t.follow_status===2?"self":t.follow_status===1?"following":"notFollowing",authorId:t.author_id,rateLimited:t.rate_limited}}function Xd(e){return e.status}function w_(){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 I_(e){return{[Si]:async t=>(Kn(t,"user.getFollowStatus"),e.user.getFollowStatus()),[bi]:async(t,r)=>(Kn(t,"user.requestFollowAuthor"),e.user.requestFollowAuthor(r.trustedUserGesture,r.signal)),[Ti]:async t=>(Kn(t,"user.getInfo"),e.user.getInfo()),[vi]:async(t,r)=>{Kn(t,"user.revokeAuthorization"),await e.authorization.revoke(r.trustedUserGesture)},[Oi]:async t=>e.user.getSteamGameList(t)}}function Kn(e,t){if(e!==void 0)throw y("INVALID_PARAMS",`${t} 不接收入参`)}function A_(){return y("USER_DATA_PERMISSION_STATE_INVALID","本地用户数据许可状态异常,已停止访问")}function eu(e){return y("USER_DATA_PERMISSION_SAVE_FAILED","本次运行已停止访问,设置未保存,请重试",e===void 0?void 0:{reason:e instanceof Error?e.message:String(e)})}function __(e){const t=e.managedResources??Wt,r=typeof e.storage.withLock=="function"||typeof navigator<"u"&&!!navigator.locks,n=e.hash??Ga,i=new Map,o=new Set;let s=!1;function a(){if(s)throw y("RUNTIME_DESTROYED","小程序 Runtime 已终止")}function c(p,M){if(e.storage.withLock)return e.storage.withLock(u(p),M);if(typeof navigator<"u"&&navigator.locks)return Wf(u(p),M);throw y("REQUEST_UNSUPPORTED","当前宿主不支持跨实例保存资料许可")}function d(p){return mp({miniProgramId:e.resolveMiniProgramId(),userId:p,environment:e.resolveEnvironment()})}function u(p){return cp(hp(d(p)))}function f(p,M){return e.purposeOf?n(bl(p,e.revisionOf(p),M,e.purposeOf(p))):n(`${p}\0${e.revisionOf(p)}\0${M}`)}function l(p,M){return`${p}\0${M}`}async function h(p,M){let z;try{z=await e.storage.getRaw(u(p),M)}catch(D){throw a(),M.signal.aborted?y("REQUEST_CANCELLED","许可操作已取消"):y("USER_DATA_PERMISSION_STORAGE_UNAVAILABLE","无法读取本地用户数据许可",{reason:D instanceof Error?D.message:String(D)})}if(a(),M.signal.aborted)throw y("REQUEST_CANCELLED","许可操作已取消");const A=z===void 0||z===""?void 0:fp(z);if(z!==void 0&&z!==""&&A===void 0)throw A_();return A??{schema_version:1,records:{}}}async function m(p,M,z){if(a(),z.signal.aborted)throw y("REQUEST_CANCELLED","许可操作已取消");await e.storage.setRaw(u(p),JSON.stringify(M),z)}function E(p){return p?.revision??0}function _(p,M,z){const A=new Set(z.declared??[]),D=new Set(t);for(const T of Object.keys(M.records))Pt(T)&&D.add(T);for(const T of i.keys())T.startsWith(`${p}\0`)&&D.add(T.slice(p.length+1));const v=[...D].sort((T,x)=>{const N=Wt.indexOf(T),b=Wt.indexOf(x);return(N<0?Number.MAX_SAFE_INTEGER:N)-(b<0?Number.MAX_SAFE_INTEGER:b)}).map(T=>{const x=M.records[T],N=E(x),b=z.egressTier===void 0?void 0:f(T,z.egressTier),O=i.get(l(p,T)),j=O!==void 0&&O.revision===N&&(b===void 0||O.consentFingerprint===b);return{resource:T,name:Ha(T)?.name??T,purposeText:e.purposeOf?.(T)??"",scopeFingerprint:b??"",declared:A.has(T),available:A.has(T),decision:x?.decision??"ask",revision:N,...x?.decision==="allow"&&x.consentFingerprint?{consentFingerprint:x.consentFingerprint}:{},sessionAllowed:j,allowed:!o.has(l(p,T))&&A.has(T)&&x?.decision!=="deny"&&(j||r&&x?.decision==="allow"&&b!==void 0&&x.consentFingerprint===b)}});return Object.freeze({schema_version:1,canPersist:r,resources:Object.freeze(v),...z.egressTier===void 0?{}:{egressTier:z.egressTier}})}function w(p,M,z,A){const D=M.records[z],I=l(p,z);if(o.has(I))return{status:"denied",reason:"tightening"};if(D?.decision==="deny")return{status:"denied",reason:"deny"};const v=f(z,A);if(r&&D?.decision==="allow"&&D.consentFingerprint===v)return{status:"allowed",source:"persistent"};const T=i.get(I);return T&&T.revision===E(D)&&T.consentFingerprint===v?{status:"allowed",source:"session"}:{status:"ask"}}function S(p){if(typeof p!="string"||!Wt.includes(p))throw y("INVALID_PARAMS","用户数据资源标识不合法")}return{canPersist:r,async read(p,M,z={}){a();const A=await h(p,M);return _(p,A,z)},async evaluate(p,M,z){a(),S(M.resource);const A=await h(p,z);return w(p,A,M.resource,M.egressTier)},async decide(p,M){a(),S(p.resource);const z=async()=>{a();const A=await h(p.userId,M);if(a(),M.signal.aborted)throw y("REQUEST_CANCELLED","许可操作已取消");const D=A.records[p.resource],I=E(D);if(p.expectedRevision!==void 0&&I!==p.expectedRevision)throw y("AUTHORIZATION_CONTEXT_CHANGED","资料许可已变化,请重新确认");const v=l(p.userId,p.resource),T=f(p.resource,p.egressTier);if(p.expectedFingerprint!==void 0&&p.expectedFingerprint!==T)throw y("AUTHORIZATION_CONTEXT_CHANGED","资料披露范围已变化,请重新确认");if(p.scope==="session"){if(p.decision!=="allow")throw y("INVALID_PARAMS","本次许可只支持允许");return i.set(v,Object.freeze({revision:I,consentFingerprint:T})),_(p.userId,A,{egressTier:p.egressTier})}const x=I+1,N=p.decision==="allow"?{decision:"allow",revision:x,consentFingerprint:T}:{decision:p.decision,revision:x},b={schema_version:1,records:{...A.records,[p.resource]:N}};p.decision!=="allow"&&(o.add(v),i.delete(v));try{await m(p.userId,b,M)}catch(O){throw eu(O)}return o.delete(v),i.delete(v),_(p.userId,b,{egressTier:p.egressTier})};return p.scope==="session"?z():c(p.userId,z)},async revokeSession(p,M){a(),p.resource!==void 0&&S(p.resource);for(const A of[...i.keys()])A.startsWith(`${p.userId}\0`)&&(p.resource===void 0||A===l(p.userId,p.resource))&&i.delete(A);const z=await h(p.userId,M);return _(p.userId,z,{})},async reset(p,M){return a(),c(p.userId,async()=>{a();const z=await h(p.userId,M);if(a(),M.signal.aborted)throw y("REQUEST_CANCELLED","许可操作已取消");const A=new Set(t);for(const v of Object.keys(z.records))A.add(v);for(const v of i.keys())v.startsWith(`${p.userId}\0`)&&A.add(v.slice(p.userId.length+1));for(const v of A)o.add(l(p.userId,v));for(const v of[...i.keys()])v.startsWith(`${p.userId}\0`)&&i.delete(v);const D={...z.records};for(const v of A)D[v]={decision:"ask",revision:(D[v]?.revision??0)+1};const I={schema_version:1,records:D};try{await m(p.userId,I,M)}catch(v){throw eu(v)}for(const v of A)o.delete(l(p.userId,v));return _(p.userId,I,{})})},dispose(){s||(s=!0,i.clear(),o.clear())}}}const xo={auth:"none",channel:"api",method:"POST",bodyEncoding:"form",failurePresentation:"none",parse(e){return Te(e,"游戏资料接口响应异常")}};function zo(e){return{runtime_auth_context_token:e.runtime_auth_context_token,resource:e.resource,disclosure_revision:e.disclosure_revision}}const D_={...xo,id:"heybox.user_miniprogram.runtime.user_game_data.query.post",path:"/user_miniprogram/runtime/user_game_data/query",body(e){return{...zo(e),operation:e.operation,schema_version:e.schema_version,...e.cursor===void 0?{}:{cursor:e.cursor},...e.limit===void 0?{}:{limit:e.limit}}}},N_={...xo,id:"heybox.user_miniprogram.runtime.user_game_data.sync.post",path:"/user_miniprogram/runtime/user_game_data/sync",body:zo},tu={...xo,id:"heybox.user_miniprogram.runtime.user_game_data.sync_status.post",path:"/user_miniprogram/runtime/user_game_data/sync_status",body(e){return{...zo(e),task_id:e.task_id}}},M_={...xo,id:"heybox.user_miniprogram.runtime.user_game_data.file.post",path:"/user_miniprogram/runtime/user_game_data/file",body(e){return{...zo(e),save_id:e.save_id,file_id:e.file_id}}};function S_(e){const t=Sf(e.storage),r=e.fileDownloads??(e.files&&e.transfer?Xa({files:e.files,transfer:e.transfer,registry:e.registry,signal:e.signal}):void 0),n=new Set,i=d=>{if(e.signal.aborted||d.signal.aborted)throw ee("REQUEST_CANCELLED","资料请求已取消")};async function o(d,u){if(i(u),!e.authorizationContext)throw ee("REQUEST_UNSUPPORTED","宿主缺少受信运行上下文");const f=await e.authorizationContext.get(u);if(!f.token||!Number.isFinite(f.expiresAt)||f.expiresAt<=Date.now())throw ee("UNAUTHORIZED","受信运行上下文已过期");return{runtime_auth_context_token:f.token,resource:d.key,disclosure_revision:d.disclosureRevision}}async function s(d,u,f){i(f);const l=await Co({network:e.network,operationContext:f,subject:"游戏资料",assertUsable:()=>i(f),requestPolicyEnabled:e.requestPolicyEnabled,...e.requestGate?{gate:{capability:"userGameData",gate:e.requestGate}}:{}},d,u),h=st(l,"user.data","游戏资料");if(!Ie(h))throw ee("INVALID_RESPONSE","游戏资料响应无效");return i(f),h}const a=d=>{const u=Ha(d);if(!u)throw ee("REQUEST_UNSUPPORTED","未开放资料资源");return u};async function c(d){n.delete(d),await r?.release(d)}return{releaseFile:c,invalidate(){for(const d of n)r?.release(d);n.clear()},async query(d,u){const f=a(d.resource),l=f.queries[d.operation];if(!l)throw ee("REQUEST_UNSUPPORTED","未开放资料操作");const h=await s(D_,{...await o(f,u),operation:d.operation,schema_version:l.version,...d.cursor===void 0?{}:{cursor:d.cursor},...d.limit===void 0?{}:{limit:d.limit}},u);if(h.resource!==d.resource||h.operation!==d.operation||h.schema_version!==l.version||h.disclosure_revision!==f.disclosureRevision)throw ee("INVALID_RESPONSE","游戏资料合同不匹配");if(h.status==="ready"){if(!ip(l.schema,h.data))throw ee("INVALID_RESPONSE","游戏资料正文不匹配公开 schema");return{status:"ready",data:h.data,meta:{},schemaVersion:l.version}}if(h.status==="empty"&&(h.reason==="no_data"||h.reason==="not_ready")&&typeof h.message=="string")return{status:"empty",reason:h.reason,message:h.message,meta:{},schemaVersion:l.version};throw ee("INVALID_RESPONSE","游戏资料状态无效")},async sync(d,u,f){const l=a(d.resource);if(!l.operations.includes("sync"))throw ee("REQUEST_UNSUPPORTED","资源不支持同步");const h=await o(l,u),m=new AbortController,E=()=>m.abort();u.signal.addEventListener("abort",E,{once:!0}),u.signal.aborted&&E();let _=!1;const w=setTimeout(()=>{_=!0,E()},5*6e4),S={...u,signal:m.signal},p={...f,gameId:l.game,resource:d.resource};let M;try{const z=await t.run(p,S,async()=>{const D=await t.get(p,S);if(D)return M=D,{id:D,status:await s(tu,{...await o(l,S),task_id:D},S)};const I=await s(N_,h,S);if(typeof I.task_id!="string"||!I.task_id||I.task_id.length>128)throw ee("INVALID_RESPONSE","同步任务缺失");return await t.set(p,I.task_id,S),{id:I.task_id,status:I}});let A=z.status;for(M=z.id;;){if(i(S),A.state==="succeeded")return await t.remove(p,M,S),{status:"succeeded"};if(A.state==="failed")throw await t.remove(p,M,S),ee(typeof A.error_code=="string"?A.error_code:"SYNC_FAILED","存档同步失败");if(A.state!=="syncing"&&A.state!=="uploading")throw ee("INVALID_RESPONSE","同步状态无效");if(await b_(S.signal),A=await s(tu,{...await o(l,S),task_id:M},S),A.task_id!==M)throw ee("INVALID_RESPONSE","同步任务不匹配")}}catch(z){throw M&&Ie(z)&&["SYNC_TASK_NOT_FOUND","SYNC_TASK_CHANGED","STEAM_ACCOUNT_CHANGED"].includes(String(z.code))&&await t.remove(p,M,S),_?ee("REQUEST_TIMEOUT","等待同步超时,后台任务可能仍在执行"):z}finally{clearTimeout(w),u.signal.removeEventListener("abort",E)}},async file(d,u,f){const l=a(d.resource);if(!l.operations.includes("file")||!r)throw ee("REQUEST_UNSUPPORTED","宿主不支持资料文件下载");const h=async E=>{await f(E);const _=await s(M_,{...await o(l,E),save_id:d.saveId,file_id:d.fileId},E);if(!Ie(_.file)||_.file.file_id!==d.fileId)throw ee("INVALID_RESPONSE","文件标识不匹配");return await f(E),_},m=await r.download(await h(u),async E=>{await h(E)},u);try{return i(u),await f(u),i(u),n.add(m),m}catch(E){throw await c(m),E}}}}function b_(e){return new Promise((t,r)=>{const n=()=>{clearTimeout(i),e.removeEventListener("abort",n),r(ee("REQUEST_CANCELLED","已停止等待同步"))},i=setTimeout(()=>{e.removeEventListener("abort",n),t()},2e3);e.addEventListener("abort",n,{once:!0}),e.aborted&&n()})}const tn=["event_id","miniProgramId","environment","host_platform","host_version","sdk_version","runtime_version","egress_tier","resource","call_id","flow_id"],T_=Object.freeze({user_game_data_permission_show:new Set([...tn,"entry","reason"]),user_game_data_permission_result:new Set([...tn,"choice","apply_result"]),user_game_data_permission_manage:new Set([...tn,"operation","apply_result","succeeded_count","failed_count"]),user_game_data_action:new Set([...tn,"stage","action_type","outcome","duration_ms"]),user_game_data_access_result:new Set([...tn,"api","trigger","status","error_code","failure_stage","duration_ms","cache_hit","sample_rate","overview_status_counts"])}),ru=10*6e4,v_=256;function O_(e){const t=e.now??Date.now,r=e.random??Math.random,n=e.createId??C_,i=k_(e.sampleRate),o=new Map,s=new Map,a=new Map;let c=!1,d=0,u=0,f=0,l=0;const h={get emitted(){return d},get failed(){return u},get skipped(){return f},get deduplicated(){return l}};function m(A){return`${A}${n()}`}function E(){const A=t();for(const[D,I]of o)A-I.createdAt<=ru||(o.delete(D),s.get(I.key)===D&&s.delete(I.key));for(const[D,I]of a){if(A-I<=ru&&a.size<=v_)break;a.delete(D)}}function _(A){const D=o.get(A);D!==void 0&&(o.delete(A),s.get(D.key)===A&&s.delete(D.key))}function w(A){_(A),a.delete(A),a.set(A,t())}function S(A,D){const I=T_[A],v={};for(const[T,x]of Object.entries(D))x===void 0||!I.has(T)||(v[T]=x);return Object.freeze(v)}function p(A){const D={event_id:m("evt_"),miniProgramId:wr(()=>e.resolveMiniProgramId())??"unknown",environment:R_(wr(()=>e.resolveEnvironment())),host_platform:wr(e.resolveHostPlatform)??"unknown",host_version:wr(e.resolveHostVersion)??"unknown",sdk_version:wr(e.resolveSdkVersion)??"unknown",runtime_version:wr(e.resolveRuntimeVersion)??"unknown",egress_tier:P_(e)};return A.resource!==void 0&&(D.resource=A.resource),A.callId!==void 0&&(D.call_id=A.callId),A.flowId!==void 0&&(D.flow_id=A.flowId),D}function M(A,D){if(c){f+=1;return}try{if(e.sink===void 0){f+=1;return}e.sink.postEvent(A,S(A,D)),d+=1}catch{u+=1}}function z(A,D){if(A===void 0)return!1;const I=o.get(A);return I===void 0?!1:D==="start"&&I.started||D==="shown"&&I.shown||D==="decided"&&I.decided?!0:(D==="start"&&(I.started=!0),D==="shown"&&(I.shown=!0),D==="decided"&&(I.decided=!0),!1)}return{diagnostics:h,createCallId(){return m("call_")},beginFlow(A){E();const D=`${A.resource??""}\0${A.actionType}`,I=s.get(D);if(I!==void 0&&o.has(I))return I;const v=m("flow_");return o.set(v,{key:D,createdAt:t(),started:!1,shown:!1,decided:!1}),s.set(D,v),v},permissionShow(A){if(z(A.flowId,"shown")){l+=1;return}M("user_game_data_permission_show",{...p(A),entry:A.entry,reason:A.reason})},permissionResult(A){if(z(A.flowId,"decided")){l+=1;return}M("user_game_data_permission_result",{...p(A),choice:A.choice,apply_result:A.applyResult})},permissionManage(A){M("user_game_data_permission_manage",{...p(A),operation:A.operation,apply_result:A.applyResult,...A.succeededCount===void 0?{}:{succeeded_count:A.succeededCount},...A.failedCount===void 0?{}:{failed_count:A.failedCount}})},action(A){if(A.stage==="start"&&z(A.flowId,"start")){l+=1;return}if(A.stage==="finish"){if(A.flowId!==void 0&&a.has(A.flowId)){l+=1;return}A.flowId!==void 0&&w(A.flowId)}M("user_game_data_action",{...p(A),stage:A.stage,action_type:A.actionType,...A.outcome===void 0?{}:{outcome:A.outcome},...A.durationMs===void 0?{}:{duration_ms:Math.max(0,Math.round(A.durationMs))}})},access(A){if(i<=0){f+=1;return}if(i<1&&r()>=i){f+=1;return}M("user_game_data_access_result",{...p(A),api:A.api,trigger:A.trigger,status:A.status,duration_ms:Math.max(0,Math.round(A.durationMs)),sample_rate:i,...A.errorCode===void 0?{}:{error_code:A.errorCode},...A.failureStage===void 0?{}:{failure_stage:A.failureStage},...A.cacheHit===void 0?{}:{cache_hit:A.cacheHit},...A.overviewStatusCounts===void 0?{}:{overview_status_counts:A.overviewStatusCounts}})},dispose(){c||(c=!0,o.clear(),s.clear(),a.clear())}}}function R_(e){switch(e){case"public":case"production":return"production";case"preview":return"preview";case"development":case"dev":case"local":return"development";case"mock":return"mock";default:return"unknown"}}function k_(e){return e===void 0||!Number.isFinite(e)?1:e<=0?0:e>=1?1:e}function wr(e){if(e!==void 0)try{const t=e();if(typeof t!="string")return;const r=t.trim();return r===""?void 0:r}catch{return}}function P_(e){try{return e.resolveEgressTier()==="upload"?"upload":"no_network"}catch{return"no_network"}}function C_(){const e=globalThis.crypto;if(typeof e?.randomUUID=="function")return e.randomUUID();const t=new Uint8Array(16);if(typeof globalThis.crypto?.getRandomValues=="function")globalThis.crypto.getRandomValues(t);else for(let r=0;r<t.length;r+=1)t[r]=Math.floor(Math.random()*256);return Array.from(t,r=>r.toString(16).padStart(2,"0")).join("")}function gt(e){const t=qe(e);return t.valid?t.permissions.network?.status==="enabled"||t.permissions.companion?.status==="enabled"?"upload":"no_network":"upload"}function L_(e){let t=!1,r=0,n,i=!1;const o=new Map,s=new Map,a=new Set,c=new Map,d=e.now??Date.now,u=g=>w()[g]?.purpose??"",f=g=>{const P=Ha(g);if(!P)throw y("REQUEST_UNSUPPORTED","未开放的资料资源");return P},l=g=>bl(g,f(g).disclosureRevision,gt(e.runtimePermissions),u(g)),h=()=>__({storage:e.storage,resolveMiniProgramId:()=>e.identity.get()?.miniProgramId,resolveEnvironment:()=>e.environment,revisionOf:g=>f(g).disclosureRevision,purposeOf:u,...e.hash?{hash:e.hash}:{}});let m=h();const E=O_({resolveMiniProgramId:()=>e.identity.get()?.miniProgramId,resolveEnvironment:()=>e.environment,resolveEgressTier:()=>gt(e.runtimePermissions),...e.telemetry??{}}),_=S_({network:e.network,authorizationContext:e.authorizationContext,files:e.files,transfer:e.transfer,storage:e.storage,registry:e.fileRegistry,fileDownloads:e.fileDownloads,requestGate:e.requestGate,requestPolicyEnabled:e.requestPolicyEnabled,signal:e.operationContext.signal});function w(){const g=qe(e.runtimePermissions),P=g.valid?g.permissions.user_game_data:void 0;return P?.status==="enabled"?bn(P.config.resources):{}}function S(g){if(t||e.operationContext.signal.aborted)throw y("RUNTIME_DESTROYED","小程序已关闭");if(g?.signal.aborted)throw y("REQUEST_CANCELLED","资料请求已取消")}function p(g){for(const[P,B]of o)B!==void 0&&(g===void 0||B===g)&&P.abort()}function M(g){for(const[P,B]of s)(g===void 0||P===g)&&(B.abort(),s.delete(P))}function z(){r++,M();for(const g of o.keys())g.abort();for(const g of a)e.fileRegistry.revokeFiles([g]);a.clear(),c.clear(),_.invalidate()}const A=Lo(e.account,g=>{if(i&&n===g)return;const P=n;i=!0,n=g,P!==void 0&&(z(),m.dispose(),m=h())}),D=()=>z();e.operationContext.signal.addEventListener("abort",D,{once:!0});async function I(g,P){S(g);const B=new AbortController,Q=()=>B.abort();o.set(B,void 0),g.signal.addEventListener("abort",Q,{once:!0}),g.signal.aborted&&Q();const X={...e.operationContext,...g,signal:B.signal};try{const ne=await P(X);return S(X),ne}catch(ne){throw re(ne)&&ne.name==="AbortError"?y("REQUEST_CANCELLED","资料操作已取消"):ne}finally{g.signal.removeEventListener("abort",Q),o.delete(B)}}function v(g){const P=f(g);if(!u(P.key))throw y("USER_DATA_RESOURCE_NOT_DECLARED","小程序未声明这项游戏资料",{resource:P.key});return P}async function T(g){S(g);const P=await e.account.getCurrentUserId(g);if(S(g),!i)i=!0,n=P;else if(n!==P){const B=n;n=P,B!==void 0&&(z(),m.dispose(),m=h(),S(g))}return P}function x(g,P){const B={login_required:"请先登录小黑盒",permission_required:"尚未允许读取这项资料",permission_denied:"已拒绝读取这项资料",source_not_linked:"请先在小黑盒关联对应游戏账号",source_login_required:"请先在小黑盒更新游戏来源登录"},Q=P==="login_required"?{type:"user_login",label:"登录并授权"}:P==="permission_required"?{type:"permission",label:"允许读取"}:P==="permission_denied"&&e.presentation?.openDataPermissions?{type:"manage",label:"管理数据权限"}:void 0;return{status:"blocked",resource:g,reason:P,message:B[P],...Q?{interaction:Q}:{}}}async function N(g,P){v(g);const B=await T(P);if(!B)return x(g,"login_required");const Q=await m.evaluate(B,{resource:g,egressTier:gt(e.runtimePermissions)},P);return S(P),Q.status==="allowed"?{userId:B}:x(g,Q.status==="denied"?"permission_denied":"permission_required")}async function b(g,P,B,Q,X){if(S(X),r!==B||await T(X)!==P||l(g)!==Q)throw y("AUTHORIZATION_CONTEXT_CHANGED","账号或资料范围已变化");return N(g,X)}function O(g,P){if(!re(g)||typeof g.resource!="string")throw y("INVALID_PARAMS","资料请求无效");if(!Pt(g.resource))throw y("REQUEST_UNSUPPORTED","当前宿主尚未开放该资料资源");const B=P==="query"?["resource","operation","schemaVersion","cursor","limit"]:["resource","saveId","fileId"];if(Object.keys(g).some(X=>!B.includes(X)))throw y("INVALID_PARAMS","资料请求包含未知参数");const Q=v(g.resource);if(P==="query"){if(g.operation!=="get"&&g.operation!=="list")throw y("INVALID_PARAMS","资料查询操作无效");const X=Q.queries[g.operation];if(!X)throw y("REQUEST_UNSUPPORTED","资源不支持该查询");if(g.schemaVersion!==X.version)throw y("REQUEST_UNSUPPORTED","SDK 与宿主正文合同版本不匹配");if(g.operation!=="list"&&(g.cursor!==void 0||g.limit!==void 0))throw y("INVALID_PARAMS","单份查询不能分页");if(g.cursor!==void 0&&(typeof g.cursor!="string"||!g.cursor||g.cursor.length>32768))throw y("INVALID_PARAMS","分页游标无效");if(!X.page&&(g.cursor!==void 0||g.limit!==void 0))throw y("INVALID_PARAMS","该列表不支持分页");if(g.limit!==void 0&&(typeof g.limit!="number"||!Number.isInteger(g.limit)||g.limit<1||g.limit>(X.page?.maxSize??100)))throw y("INVALID_PARAMS","分页数量无效")}else if(!Q.operations.includes(P))throw y("REQUEST_UNSUPPORTED","资源不支持该操作");if(P==="file"&&(typeof g.saveId!="string"||!g.saveId||typeof g.fileId!="string"||!g.fileId))throw y("INVALID_PARAMS","资料文件标识无效");return P==="query"?{resource:g.resource,operation:g.operation,schemaVersion:g.schemaVersion,...g.cursor===void 0?{}:{cursor:g.cursor},...g.limit===void 0?{}:{limit:g.limit}}:{resource:g.resource,saveId:g.saveId,fileId:g.fileId}}async function j(g,P,B,Q){const X=d(),ne=r,ie=l(P.resource);for(const ue of o.keys())ue.signal===B.signal&&o.set(ue,P.resource);try{const ue=await N(P.resource,B);if("status"in ue)return E.access({resource:P.resource,api:g,trigger:"initial",status:"blocked",durationMs:d()-X}),ue;let Ee;try{Ee=await Q()}catch(ge){const ye=re(ge)?ge.code:void 0;if(ye==="USER_DATA_SOURCE_NOT_LINKED"||ye==="USER_DATA_SOURCE_LOGIN_REQUIRED")return E.access({resource:P.resource,api:g,trigger:"initial",status:"blocked",durationMs:d()-X}),x(P.resource,ye==="USER_DATA_SOURCE_NOT_LINKED"?"source_not_linked":"source_login_required");throw ge}const me=await b(P.resource,ue.userId,ne,ie,B);return"status"in me?(E.access({resource:P.resource,api:g,trigger:"initial",status:"blocked",durationMs:d()-X}),me):(E.access({resource:P.resource,api:g,trigger:"initial",status:re(Ee)&&Ee.status==="empty"?"empty":g===un?"succeeded":"ready",durationMs:d()-X}),Ee)}catch(ue){throw E.access({resource:P.resource,api:g,trigger:"initial",status:"error",durationMs:d()-X,errorCode:re(ue)?String(ue.code):"REQUEST_FAILED"}),ue}}async function U(g){const P=await T(g);if(!P)throw y("UNAUTHORIZED","请先登录小黑盒");return m.read(P,g,{declared:Object.keys(w()),egressTier:gt(e.runtimePermissions)})}async function L(g,P){const B=v(g);let Q=await T(P);if(Q||(await e.account.ensureAuthenticated({trustedUserGesture:!0,reason:"user_action",signal:P.signal}),Q=await T(P)),!Q)return{status:"cancelled"};let X=await m.evaluate(Q,{resource:g,egressTier:gt(e.runtimePermissions)},P);if(X.status==="allowed")return{status:"allowed"};if(X.status==="denied"){if(e.presentation?.openDataPermissions){const Me=r,Pe=l(g),ze=await e.presentation.openDataPermissions({resource:g,miniProgramName:e.miniProgramPresentation?.name,signal:P.signal});if(!("status"in await b(g,Q,Me,Pe,P)))return{status:"allowed"};if(!ze)return{status:"cancelled"}}return X=await m.evaluate(Q,{resource:g,egressTier:gt(e.runtimePermissions)},P),{status:X.status==="allowed"?"allowed":"denied"}}if(!e.presentation?.confirmDataPermission)throw y("REQUEST_UNSUPPORTED","当前宿主不支持资料许可弹窗");M(g);const ne=new AbortController;s.set(g,ne);const ie=()=>ne.abort();P.signal.addEventListener("abort",ie,{once:!0}),P.signal.aborted&&ie();const ue={...P,signal:ne.signal},Ee=r,me=l(g),ge=m,ye=E.beginFlow({resource:g,actionType:"permission"});let Oe="error";try{const Pe=(await ge.read(Q,ue,{egressTier:gt(e.runtimePermissions)})).resources.find(Ft=>Ft.resource===g);E.action({resource:g,flowId:ye,stage:"start",actionType:"permission"}),E.permissionShow({resource:g,flowId:ye,entry:"other",reason:Pe?.decision==="allow"?"scope_changed":"first"});const ze=await fe(()=>e.presentation.confirmDataPermission({miniProgramName:e.miniProgramPresentation?.name,resource:g,scopeText:`此黑盒账号关联的${B.name}${B.operations.includes("sync")?`。${Ym}`:""}`,purposeText:u(g),egress:gt(e.runtimePermissions),canPersist:ge.canPersist,signal:ne.signal}),ne.signal);if(S(ue),r!==Ee||await T(ue)!==Q||l(g)!==me)throw y("AUTHORIZATION_CONTEXT_CHANGED","资料许可范围已变化");return ze.decision==="cancelled"?(Oe="cancelled",E.permissionResult({resource:g,flowId:ye,choice:"cancel",applyResult:"cancelled"}),{status:"cancelled"}):(await ge.decide({userId:Q,resource:g,decision:ze.decision==="deny"?"deny":"allow",scope:ze.decision==="session"?"session":"persistent",egressTier:gt(e.runtimePermissions),expectedRevision:Pe?.revision??0,expectedFingerprint:Pe?.scopeFingerprint},ue),ze.decision==="deny"&&p(g),Oe=ze.decision==="deny"?"unresolved":"resolved",E.permissionResult({resource:g,flowId:ye,choice:ze.decision,applyResult:"applied"}),{status:ze.decision==="deny"?"denied":"allowed"})}catch(Me){throw Oe=ue.signal.aborted?"cancelled":"error",E.permissionResult({resource:g,flowId:ye,choice:"cancel",applyResult:ue.signal.aborted?"cancelled":"error"}),Me}finally{E.action({resource:g,flowId:ye,stage:"finish",actionType:"permission",outcome:Oe}),P.signal.removeEventListener("abort",ie),s.get(g)===ne&&s.delete(g)}}async function C(g,P,B,Q,X,ne){P==="allow"?v(g):f(g);const ie=await T(Q);if(!ie)throw y("UNAUTHORIZED","请先登录小黑盒");try{await m.decide({userId:ie,resource:g,decision:P,scope:B,expectedRevision:X,expectedFingerprint:ne,egressTier:gt(e.runtimePermissions)},Q)}catch(ue){throw re(ue)&&ue.code==="USER_DATA_PERMISSION_SAVE_FAILED"&&p(g),ue}return M(g),P!=="allow"&&p(g),U(Q)}async function H(g,P,B){try{const Q=await B();return E.permissionManage({operation:g,resource:P,applyResult:"applied"}),Q}catch(Q){throw E.permissionManage({operation:g,resource:P,applyResult:re(Q)&&Q.code==="USER_DATA_PERMISSION_SAVE_FAILED"?"save_failed":"error"}),Q}}async function F(g,P){M(g),p(g);const B=await T(P);if(!B)throw y("UNAUTHORIZED","请先登录小黑盒");return H("revoke",g,async()=>(await m.revokeSession({userId:B,resource:g},P),U(P)))}function $(){let g;const P=B=>I(e.operationContext,async Q=>{const X=await T(Q);if(!X)throw y("UNAUTHORIZED","请先登录小黑盒");if(g&&(g.userId!==X||g.generation!==r))throw y("AUTHORIZATION_CONTEXT_CHANGED","管理页面所属账号已变化,请重新打开");return g??={userId:X,generation:r},B(Q)});return{getSnapshot:()=>P(U),setDecision:B=>P(Q=>H("modify",B.resource,()=>C(B.resource,B.decision,B.scope,Q,B.expectedRevision,B.expectedFingerprint))),revokeSession:B=>P(Q=>F(B?.resource,Q)),resetAll:()=>P(async B=>{M(),p();const Q=await T(B);return H("reset",void 0,async()=>(await m.reset({userId:Q},B),U(B)))})}}return{handlers:{[Ca]:async(g,P)=>I(P,async B=>{if(g!==void 0&&(!re(g)||Object.keys(g).some(ne=>ne!=="game")||g.game!==void 0&&typeof g.game!="string"))throw y("INVALID_PARAMS","概览参数无效");if(re(g)&&typeof g.game=="string"&&!bc(g.game))throw y("REQUEST_UNSUPPORTED","当前宿主尚未开放该游戏");const Q=Object.keys(w()),X=re(g)?g.game:void 0;return Ml.filter(ne=>X===void 0||ne===X).map(ne=>({game:ne,name:Nl[ne],resources:tr.filter(ie=>ie.game===ne&&Q.includes(ie.key)).map(ie=>({resource:ie.key,name:ie.name,status:"not_checked",statusText:"尚未检查"}))})).filter(ne=>ne.resources.length>0)}),[Ai]:async(g,P)=>I(P,B=>{const Q=O(g,"query");return j(Ai,Q,B,()=>_.query(Q,B))}),[un]:async(g,P)=>I(P,async B=>{if(!re(g)||Object.keys(g).length!==1||typeof g.game!="string"||!bc(g.game))throw y("INVALID_PARAMS","同步需要指定已开放的游戏");const Q={game:g.game};if(!tr.some(Ee=>Ee.game===Q.game&&Ee.sync))throw y("REQUEST_UNSUPPORTED","该游戏不支持存档同步");const X=tr.filter(Ee=>Ee.game===Q.game&&Ee.sync&&u(Ee.key));if(X.length===0)throw y("USER_DATA_RESOURCE_NOT_DECLARED","小程序未声明可同步的资料");let ne,ie;for(const Ee of X){const me=await N(Ee.key,B);if(!("status"in me)){ne=Ee.key;break}(!ie||ie.reason==="permission_denied")&&(ie=me)}if(!ne)return ie;const ue={resource:ne};return j(un,ue,B,async()=>{const Ee=await T(B),me=`${Ee}\0${ue.resource}`;let ge=c.get(me);if(!ge){const ye=new AbortController;o.set(ye,ue.resource);const Oe={controller:ye,waiters:0,settled:!1,promise:Promise.resolve(void 0)};Oe.promise=_.sync(ue,{...e.operationContext,signal:ye.signal},{userId:Ee,miniProgramId:e.identity.get()?.miniProgramId??""}).finally(()=>{Oe.settled=!0,o.delete(ye),c.get(me)===Oe&&c.delete(me)}),Oe.promise.catch(()=>{}),c.set(me,Oe),ge=Oe}ge.waiters++;try{return await fe(()=>ge.promise,B.signal)}finally{ge.waiters--,ge.waiters===0&&!ge.settled&&ge.controller.abort()}})}),[_i]:async(g,P)=>I(P,async B=>{const Q=O(g,"file"),X=await T(B),ne=r,ie=l(Q.resource),ue=async me=>{try{const ge=await b(Q.resource,X,ne,ie,me);if("status"in ge)throw y("FILE_ACCESS_REVOKED","文件授权已撤销",{reason:ge.reason})}catch(ge){throw re(ge)&&["AUTHORIZATION_CONTEXT_CHANGED","USER_DATA_RESOURCE_NOT_DECLARED"].includes(String(ge.code))?y("FILE_ACCESS_REVOKED","文件授权已失效",{causeCode:ge.code}):ge}};let Ee;try{const me=await j(_i,Q,B,async()=>(Ee=await _.file(Q,B,ue),{handle:Ee}));if(re(me)&&me.status==="blocked"){const Me=String(me.reason);throw y(Me==="source_not_linked"?"USER_DATA_SOURCE_NOT_LINKED":Me==="source_login_required"?"USER_DATA_SOURCE_LOGIN_REQUIRED":Me==="login_required"?"UNAUTHORIZED":"PERMISSION_DENIED",String(me.message),{reason:Me})}const ge=me.handle,ye={...ge,read:async Me=>{await ue(Me);const Pe=await ge.read(Me);try{return await ue(Me),Pe}catch(ze){throw Pe.fill(0),ze}},stat:async Me=>{await ue(Me);const Pe=await ge.stat(Me);return await ue(Me),Pe}},Oe=e.fileRegistry.registerFile(ye,"download","read");return"handleId"in Oe.ref&&a.add(Oe.ref.handleId),Oe}catch(me){throw Ee&&await _.releaseFile(Ee),me}}),[La]:async(g,P)=>{if(!P.trustedUserGesture)throw y("USER_GESTURE_REQUIRED","许可操作需要点击");return I(P,B=>{if(!re(g)||Object.keys(g).length!==1||typeof g.resource!="string"||!Pt(g.resource))throw y("INVALID_PARAMS","许可资源无效");return L(g.resource,B)})},[Ua]:async(g,P)=>I(P,U),[xa]:async(g,P)=>{if(!P.trustedUserGesture)throw y("USER_GESTURE_REQUIRED","修改许可需要点击");if(!re(g)||typeof g.resource!="string"||!Pt(g.resource)||g.decision!=="deny"||g.scope!=="persistent"||Object.keys(g).some(B=>!["resource","decision","scope"].includes(B)))throw y("INVALID_PARAMS","允许许可只能由可信弹窗确认");return I(P,B=>C(g.resource,g.decision,"persistent",B))},[za]:async(g,P)=>{if(!P.trustedUserGesture)throw y("USER_GESTURE_REQUIRED","管理资料许可需要点击");if(!e.presentation?.openDataPermissions)throw y("REQUEST_UNSUPPORTED","宿主未提供资料管理界面");if(g!==void 0&&(!re(g)||Object.keys(g).some(B=>B!=="resource")||g.resource!==void 0&&(typeof g.resource!="string"||!Pt(g.resource))))throw y("INVALID_PARAMS","管理资源无效");return I(P,async B=>(await e.presentation.openDataPermissions({resource:re(g)?g.resource:void 0,miniProgramName:e.miniProgramPresentation?.name,signal:B.signal}),U(B)))},[ja]:async(g,P)=>{if(!P.trustedUserGesture)throw y("USER_GESTURE_REQUIRED","撤销许可需要点击");if(g!==void 0&&(!re(g)||Object.keys(g).some(B=>B!=="resource")||g.resource!==void 0&&(typeof g.resource!="string"||!Pt(g.resource))))throw y("INVALID_PARAMS","撤销资源无效");return I(P,B=>F(re(g)?g.resource:void 0,B))}},get permissionBridge(){return $()},diagnostics:{telemetry:E.diagnostics},dispose(){t||(t=!0,z(),A(),e.operationContext.signal.removeEventListener("abort",D),m.dispose(),E.dispose())}}}function nu(e){throw{code:"INVALID_PARAMS",message:e}}function rn(e,t){const r=Number(e);return Number.isFinite(r)&&r>0?r:t}function ih(e,t){const r=Number(e);return Number.isFinite(r)&&r>=0?r:t}function Jn(e,t,r){return Math.min(ih(e,t),r)}async function U_(e){try{return ih(await e.getNavigationBarHeight(),0)}catch{return 0}}function x_(e,t,r,n){const i=Jn(e.safeArea?.left,0,t),o=Math.max(i,Jn(e.safeArea?.right,t,t)),s=Jn(e.safeArea?.top,n,r),a=Math.max(s,Jn(e.safeArea?.bottom,r,r));return{left:i,right:o,top:s,bottom:a,width:o-i,height:a-s}}async function iu(e){const t=e.getViewportMetrics(),r=rn(t.windowWidth,0),n=rn(t.windowHeight,0),i=await U_(e);return{pixelRatio:rn(t.pixelRatio,1),screenWidth:rn(t.screenWidth,r),screenHeight:rn(t.screenHeight,n),windowWidth:r,windowHeight:n,statusBarHeight:i,safeArea:x_(t,r,n,i),screenTop:i}}function z_(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 f=++i;iu(r.presentation).then(l=>{if(n||r.operationContext.signal.aborted||f!==i)return;const h=JSON.stringify(l);h!==o&&(o=h,r.onViewportChange?.(l))}).catch(()=>{})},c=YI({...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:{[nr]:async(f,l)=>c.apply(f,l?.signal),[Li]:async()=>(pe(r.operationContext.signal),iu(r.presentation)),[Ui]:async f=>{if(pe(r.operationContext.signal),typeof f!="object"||f===null||Array.isArray(f))return nu("viewport.setNavigationBarStyle 参数必须是对象");const l=f.foregroundStyle;if(l!=="light"&&l!=="dark")return nu("viewport.setNavigationBarStyle foregroundStyle 必须是 light 或 dark");await fe(()=>r.presentation.setNavigationBarStyle(l,e.operationContext),r.operationContext.signal)}},runDisplayRequest:c.runDisplayRequest,applyOrientation:(f,l)=>c.apply({orientation:f.mode,fullscreen:f.hideCapsule},l),notifyChange:()=>{o=void 0,a()},dispose:d}}function j_(e){if(e===void 0)return{};if(!e||typeof e!="object"||Array.isArray(e))throw we("INVALID_PARAMS","工作区卡片刷新参数必须是对象");const t=e;if(Object.keys(t).some(i=>i!=="gameAppId"&&i!=="cardIds"))throw we("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 we("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 we("INVALID_PARAMS","工作区卡片编号无效");return{...r===void 0?{}:{gameAppId:r},...n===void 0?{}:{cardIds:[...n]}}}function B_(e,t){return{[Di]:async(r,n)=>{const i=Se(t,n.signal,n.requestId);if(pe(i.signal),!e)throw we("CAPABILITY_UNAVAILABLE","当前 Host 不支持工作区卡片");const o=j_(r),s=await fe(()=>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 we("HOST_INVALID_RESPONSE","工作区卡片刷新回执无效");return{scheduled:s.scheduled}}}}const H_=new Map(zt.map(e=>[e.method,e]));function cs(e,t,r){return{code:e,message:t,...r===void 0?{}:{data:r}}}function F_(e){const t=Kl(e);return r=>t(r.requirement,r.method)}function V_(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 G_(e){const t=F_(e.runtimePermissions),r=qe(e.runtimePermissions);let n=0;return{async dispatch(i,o,s){const a=e.now??$_,c=e.onTrace?a():0,d=e.onTrace?Date.now():0,u=e.onTrace?s.requestId??`runtime_${++n}`:"";e.onTrace&&ds(e.onTrace,{callId:u,method:i,startedAt:d,outcome:"started"},()=>c,c);try{if(e.terminalSignal.aborted)throw cs("RUNTIME_DESTROYED","小程序 Runtime 已终止");Gl(i,e.effectiveCapabilities);const f=H_.get(i);if(!f)throw new Error(`Capability method ${i} 缺少 protocol metadata`);const l=t(f),h=!l.allowed&&r.valid&&r.permissions.companion?.status==="enabled"&&e.allowsCompanionAttachmentAccess?.(i,o)===!0,m=!l.allowed&&r.valid&&r.permissions.gameSaves?.status==="enabled"&&e.allowsGameSaveAccess?.(i,o)===!0,E=!l.allowed&&r.valid&&r.permissions.user_game_data?.status==="enabled"&&e.allowsUserGameDataFileAccess?.(i,o)===!0;if(!l.allowed&&!h&&!m&&!E)throw cs(l.code,l.message,l.data);const _=e.handlers[i];if(!_)throw new Error(`Capability method ${i} 缺少 handler`);const w=async M=>{for(const z of e.policies??[]){const A=await z.evaluate({method:i,payload:o,capability:f});if(e.terminalSignal.aborted||M.aborted)throw su();if(!A.allowed)throw cs(A.code,A.message,A.data)}if(e.terminalSignal.aborted||M.aborted)throw su()},p=await V_(async()=>{if(i===nr){if(!e.runDisplayRequest)throw new Error("viewport.setDisplay 缺少执行 Module");return e.runDisplayRequest(o,s.signal,w)}return await w(e.terminalSignal),_(o,s)},void 0,s,e.terminalSignal);return e.onTrace&&ds(e.onTrace,ou(u,i,o,d,p),a,c),p}catch(f){throw e.onTrace&&ds(e.onTrace,ou(u,i,o,d,{status:"error",error:f}),a,c),f}}}}function $_(){return typeof performance>"u"?Date.now():performance.now()}function ds(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 ou(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:q_(i.error)}:{},...Q_(t,r,i)}}function q_(e){return typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"?e.code:void 0}function Q_(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"&&la(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 la(e){return typeof e=="object"&&e!==null}function su(){const e=new Error("The operation was aborted");return e.name="AbortError",e}function Y_(e){const t={signal:e.terminalSignal,...e.miniProgramDetail===void 0?{}:{miniProgramDetail:e.miniProgramDetail}},r=gE(e.requestPolicy);let n;if(e.files)try{n=oE(e.files,t)}catch{}const i=cf({store:n}),o=e.onRequestPolicyReport??(r.debugReport?W_:void 0),s=r.enabled?lE({...r.gateOptions,...o?{onReport:o}:{}}):void 0,a=new Za(e.files,e.miniProgramDetail),c=tI({registry:a,picker:e.picker,operationContext:t}),d=HE({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,f,l,h,m,E,_=()=>{},w=()=>{};try{u=z_({operationContext:t,presentation:e.hostPresentation,onDisplayChange:b=>e.eventSink.postEvent("display_change",b),onViewportChange:b=>e.eventSink.postEvent("viewport_change",b)}),l=u_({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}),_=d.onEvent((b,O)=>e.eventSink.postEvent(b,O)),w=e.hostCompanion?.onSessionEvent?.(b=>{const O=Ww(b);!e.terminalSignal.aborted&&O&&e.eventSink.postEvent(O.type,O.payload)})??(()=>{}),h=_w({authorizationContext:e.authorizationContext,account:e.account,identity:e.identity,network:e.network,operationContext:t,requestGate:s,requestPolicyEnabled:r.enabled});const S=e.files&&e.transfer?Xa({files:e.files,transfer:e.transfer,registry:a,signal:t.signal}):void 0,p=L_({identity:e.identity,account:e.account,storage:e.storage,network:e.network,authorizationContext:e.authorizationContext,files:e.files,transfer:e.transfer,fileDownloads:S,requestGate:s,requestPolicyEnabled:r.enabled,fileRegistry:a,...e.userDataPresentation===void 0?{}:{presentation:e.userDataPresentation},...e.miniProgramPresentation===void 0?{}:{miniProgramPresentation:e.miniProgramPresentation},runtimePermissions:e.runtimePermissions,environment:e.miniProgramDetail?.releaseChannel,operationContext:t,...e.onUserDataTelemetry===void 0?{}:{telemetry:{sink:{postEvent(b,O){e.onUserDataTelemetry?.({name:b,payload:O})}}}}});E=p,m=Cw({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,fileDownloads:S,requestGate:s,requestPolicyEnabled:r.enabled});const M=BA({storage:e.storage,scopedStorage:e.scopedStorage,storageDiagnostics:e.storageDiagnostics,identity:e.identity,operationContext:t,anonymousStorageScope:e.anonymousStorageScope,storageLimits:e.storageLimits});f=NI({registry:a,media:e.media,operationContext:t});const z=[{name:"gameSaves",handlers:Object.fromEntries(Object.entries(m.handlers).map(([b,O])=>[b,async(j,U)=>{const L=e.verifiedSdkVersion,C=L?ec(L,"0.10.0-0"):void 0;if(C===void 0||C>=0)throw y("REQUEST_UNSUPPORTED","当前 SDK 不支持旧游戏存档入口,请使用 user.games.get(...).saves");return O(j,U)}]))},{name:"auth",handlers:WE({authorization:d})},{name:"user",handlers:{...I_({user:l,authorization:d,runtimePermissions:e.runtimePermissions,steamAccount:e.runtimeFeatures?.steamAccount===!0,userDataMode:e.runtimeFeatures?.userDataMode}),...Jy({operationContext:t,presentation:e.hostPresentation,miniProgramPresentation:e.miniProgramPresentation})}},{name:"share",handlers:xA({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:M.handlers},{name:"network",handlers:nA({network:e.network,transfer:e.transfer,fileRegistry:a,operationContext:t,runtimePermissions:e.runtimePermissions,allowedHttpOrigins:e.allowedHttpOrigins,networkPolicy:e.networkPolicy})},{name:"workspaceCards",handlers:B_(e.workspaceCards,t)},{name:"files",handlers:c.files},{name:"file",handlers:c.file},{name:"directory",handlers:c.directory},{name:"media",handlers:f.handlers},{name:"ui",handlers:$A({operationContext:t,presentation:e.hostPresentation})},{name:"device",handlers:Xw({operationContext:t,presentation:e.hostPresentation,protocol:e.hostProtocol})},{name:"navigation",handlers:WI({operationContext:t,presentation:e.hostPresentation,...e.hostPresentation.applyOrientation?{resetDisplay:b=>u.applyOrientation({mode:"portrait",hideCapsule:!1},b)}:{}})},{name:"cloud",handlers:h.handlers},{name:"userGameData",handlers:E.handlers},{name:"companion",handlers:Gw({companion:e.hostCompanion,companionPresentation:e.companionPresentation,miniProgramPresentation:e.miniProgramPresentation,operationContext:t,fileRegistry:a})}],A=Z_(z);let D=!1;const I=()=>{D||(D=!0,e.terminalSignal.removeEventListener("abort",I),u?.dispose(),f?.dispose(),h?.dispose(),m?.dispose(),E?.dispose(),_(),w(),l?.dispose(),i.dispose(),d.dispose(),s?.dispose(),a.dispose())};e.terminalSignal.aborted?I():e.terminalSignal.addEventListener("abort",I,{once:!0});const v=new Set(["file.readText","file.readBytes","file.stat"]),T=(b,O)=>v.has(b)&&la(O)&&a.isCompanionAttachmentRef(O.target),x=new Set(["file.readText","file.readBytes","file.stat","file.exists"]),N=(b,O)=>x.has(b)&&la(O)&&a.isUserDataDownloadRef(O.target);return{get permissionBridge(){return p.permissionBridge},modules:z,handlers:A,runDisplayRequest:u.runDisplayRequest,allowsCompanionAttachmentAccess:T,allowsGameSaveAccess:m.allowsRead,allowsUserGameDataFileAccess:N,gameSaveDiagnostics:m.diagnostics,applyOrientation:u.applyOrientation,notifyViewportChange:u.notifyChange,...M.diagnostics?{storageDiagnostics:M.diagnostics}:{},...e.files?{sandboxDiagnostics:uI({registry:a,operationContext:t,runtimePermissions:e.runtimePermissions,capabilities:e.diagnosticCapabilities})}:{},dispose:I}}catch(S){throw u?.dispose(),f?.dispose(),h?.dispose(),m?.dispose(),E?.dispose(),_(),w(),l?.dispose(),i.dispose(),d.dispose(),s?.dispose(),a.dispose(),S}}function W_(e){try{console.warn("[hb-sdk-runtime] request-policy",e)}catch{}}function Z_(e){const t=new Map(zt.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=zt.map(i=>i.method).filter(i=>!r.has(i));if(n.length>0)throw new Error(`Capability registry 缺少 method: ${n.join(", ")}`);if(r.size!==zt.length)throw new Error(`Capability registry method 数量不合法: ${r.size}`);return Object.freeze(Object.fromEntries(r))}const K_="heybox-mini-dev:";function au(e){try{return J_(new URL(e))}catch{return!1}}function J_(e){return e.protocol===K_}function X_(e){return e==="localhost"||e==="127.0.0.1"||e==="[::1]"||eD(e)}function eD(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 tD=new Set(["android","ios","ohos","windows","macos","linux","unknown"]);function rD(e,t){const r=[],n=nD(e.environmentInfo,r),i=li(n?.appVersion,"host.appVersion",r),o=oD(n?.operatingSystem,r);return{info:Object.freeze({runtime:Object.freeze({mode:iD(e.sdkVersionPolicy?.releaseChannel,r)}),host:Object.freeze({appVersion:i}),miniProgram:Object.freeze({id:li(t.miniProgramId),version:li(t.miniProgramVersion)}),operatingSystem:Object.freeze(o)}),invalidFields:Object.freeze(r)}}function nD(e,t){if(e!=null){if(oh(e))return e;t.push("environmentInfo")}}function iD(e,t){return e==="public"?"production":e==="preview"||e==="development"?e:(e!=null&&t.push("runtime.mode"),"unknown")}function oD(e,t){if(e==null)return{name:"unknown",version:null};if(!oh(e))return t.push("operatingSystem"),{name:"unknown",version:null};const r=tD.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:li(e.version,"operatingSystem.version",t)}}function li(e,t,r){return e==null?null:typeof e=="string"&&e.trim()?e.trim():(t&&r&&r.push(t),null)}function oh(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const sD="data:image/svg+xml;base64,PHN2ZyBwcmVzZXJ2ZUFzcGVjdFJhdGlvPSJub25lIiBvdmVyZmxvdz0idmlzaWJsZSIgc3R5bGU9ImRpc3BsYXk6IGJsb2NrOyIgd2lkdGg9IjY3IiBoZWlnaHQ9IjIyIiB2aWV3Qm94PSIwIDAgNjcgMjIiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxwYXRoIGlkPSJTdWJ0cmFjdCIgZD0iTTY2IDBDNjYuMzM3MiAwIDY2LjY3MDYgMC4wMTcxODM4IDY3IDAuMDQ2ODc1QzYxLjM5MzYgMC41NTIxODkgNTcgNS4yNjIwMiA1NyAxMUM1NyAxNi43MzggNjEuMzkzNiAyMS40NDY4IDY3IDIxLjk1MjFDNjYuNjcwNiAyMS45ODE4IDY2LjMzNzIgMjIgNjYgMjJIMTFDNC45MjQ4NyAyMiAwIDE3LjA3NTEgMCAxMUMwIDQuOTI0ODcgNC45MjQ4NyAyLjY1NzU2ZS0wNyAxMSAwSDY2Wk04LjI0MzE2IDYuNzM1MzVDOC4yNDMxNiA2LjU5Mzk3IDguMTQyNTggNi41MzU3NiA4LjAxOTUzIDYuNjA2NDVMNi4yMjI2NiA3LjY0MDYyQzYuMTU3ODcgNy42ODIyOCA2LjEwNDE2IDcuNzM5MTcgNi4wNjU0MyA3LjgwNTY2QzYuMDI2NzIgNy44NzIyNyA2LjAwNDEgNy45NDc1MiA2IDguMDI0NDFWMTMuOTY1OEM2LjAwMzcxIDE0LjA0MzQgNi4wMjU4NSAxNC4xMTkxIDYuMDY0NDUgMTQuMTg2NUM2LjEwMzE5IDE0LjI1NCA2LjE1NzQgMTQuMzEyIDYuMjIyNjYgMTQuMzU0NUw5Ljg3MTA5IDE2LjQ1OEM5Ljk5MzQ2IDE2LjUyNzIgMTAuMDkzNiAxNi41ODQyIDEwLjA5NDcgMTYuNTg1OUMxMC4wOTQ3IDE2LjU4NzEgMTAuMTkzNCAxNi42NDUxIDEwLjMxNjQgMTYuNzE1OEwxMi41MDEgMTcuOTY5N0MxMi42MjI4IDE4LjA0MDMgMTIuNzIzNiAxNy45ODIyIDEyLjcyMzYgMTcuODQwOFYxMi4zNjcyQzEyLjcyMyAxMi4yOTk0IDEyLjY5NTcgMTIuMjM0MyAxMi42NDc1IDEyLjE4NjVDMTIuNTk5MiAxMi4xMzg4IDEyLjUzMzggMTIuMTEyMyAxMi40NjU4IDEyLjExMjNIMTAuNzM3M0MxMC42NzAyIDEyLjExMzIgMTAuNjA1OSAxMi4xMzk5IDEwLjU1ODYgMTIuMTg3NUMxMC41MTEzIDEyLjIzNTIgMTAuNDg0NyAxMi4zMDAxIDEwLjQ4NDQgMTIuMzY3MlYxMy44Mzc5QzEwLjQ4NDIgMTMuOTc4OSAxMC4zODQ2IDE0LjAzNjQgMTAuMjYxNyAxMy45NjU4TDguNDY0ODQgMTIuOTM1NUM4LjQwMDI2IDEyLjg5MzUgOC4zNDYxNCAxMi44MzcyIDguMzA3NjIgMTIuNzcwNUM4LjI2OTE5IDEyLjcwNCA4LjI0NzM1IDEyLjYyOTQgOC4yNDMxNiAxMi41NTI3VjYuNzM1MzVaTTI0LjMzNCAxNC4zOTI2QzI0LjMzMzkgMTQuOTk4NSAyNC4yMDU1IDE1LjE4NDYgMjMuNTk4NiAxNS4xOTYzTDIyLjMwMTggMTUuMjU0OUwyMi42NjUgMTYuMjU0OUgyNS4wODY5QzI1LjY3MDUgMTYuMDg0IDI1Ljg3MjEgMTUuNzE5NCAyNS44NzIxIDE0LjgyMzJWNS43ODIyM0wyNC4zMzQgNS43MjM2M1YxNC4zOTI2Wk0zMi4yODIyIDE0LjQ3NTZDMzEuOTQ2IDE1LjA0OTIgMzEuNDY1OSAxNS43NTcxIDMxLjA5OTYgMTYuMjU0OUgzMi42MTkxQzMzLjA2NzMgMTUuNTIxMiAzMy4zNzUxIDE0LjkyOCAzMy41NDg4IDE0LjQ3NTZIMzIuMjgyMlpNMzQuODEwNSAxNS4zOTc1QzM0Ljg3OTEgMTUuNzEwMSAzNC45MzExIDE1Ljk5ODIgMzQuOTczNiAxNi4yNTQ5SDM2LjE4NjVMMzYuMTgxNiAxNi4yMzU0QzM2LjA2NjIgMTUuNzM4OCAzNS44OTg5IDE1LjAxOCAzNS43NDEyIDE0LjQ3NTZIMzQuNTI5M0wzNC44MTA1IDE1LjM5NzVaTTM2Ljk4MTQgMTQuNjUzM0MzNy4wOTg0IDE0Ljg3NyAzNy4yNDExIDE1LjE1MDEgMzcuMzMzIDE1LjQwMjNMMzcuNjM1NyAxNi4yNTQ5SDM5LjA4MDFDMzkuMDMzNiAxNS44MzI1IDM4LjU5NCAxNS4wNTUzIDM4LjIzODMgMTQuNDc1NkgzNi44ODg3QzM2LjkxNjEgMTQuNTI5OCAzNi45NDggMTQuNTg5NCAzNi45ODE0IDE0LjY1MzNaTTM5LjI3MDUgMTQuNDc1NkMzOS44MzAxIDE1LjE4MjEgNDAuMTg2MyAxNS44MDA0IDQwLjQxMzEgMTYuMjU0OUg0MS44MzVDNDEuNzM2NyAxNS42NjU2IDQxLjIyOTIgMTQuOTkzNiA0MC43NzY0IDE0LjQ3NTZIMzkuMjcwNVpNNDMuOTIyOSAxNS4wMDQ5SDQyLjc2NjZWMTUuOTk2MUg1My4xMjVWMTUuMDA0OUg1MS45Njg4VjEyLjQ3NTZINDMuOTIyOVYxNS4wMDQ5Wk0xMC43MDQxIDQuMDMwMjdDMTAuNTgxMSAzLjk1OTU4IDEwLjQ4MDUgNC4wMTc4IDEwLjQ4MDUgNC4xNTkxOFY5LjYyMzA1QzEwLjQ4MDYgOS42OTA3NCAxMC41MDc4IDkuNzU1NzggMTAuNTU1NyA5LjgwMzcxQzEwLjYwMzcgOS44NTE3MSAxMC42NjkzIDkuODc4ODcgMTAuNzM3MyA5Ljg3ODkxSDEyLjQ2NDhDMTIuNDk4NiA5Ljg3OTA1IDEyLjUzMjIgOS44NzIxNyAxMi41NjM1IDkuODU5MzhDMTIuNTk0NCA5Ljg0NjY2IDEyLjYyMjcgOS44MjgyMSAxMi42NDY1IDkuODA0NjlDMTIuNjcwNCA5Ljc4MDg5IDEyLjY5MDIgOS43NTE4NSAxMi43MDMxIDkuNzIwN0MxMi43MTYgOS42ODk3NSAxMi43MjI2IDkuNjU2NTQgMTIuNzIyNyA5LjYyMzA1VjguMTUyMzRDMTIuNzIyNyA4LjAxMSAxMi44MjIzIDcuOTUyODIgMTIuOTQ1MyA4LjAyMzQ0TDE0Ljc0MTIgOS4wNjE1MkMxNC44MDYgOS4xMDM2MiAxNC44NTk3IDkuMTYwNzcgMTQuODk4NCA5LjIyNzU0QzE0LjkzNzEgOS4yOTQzIDE0Ljk1OTYgOS4zNjkyOSAxNC45NjM5IDkuNDQ2MjlWMTUuMjU5OEMxNC45NjQxIDE1LjQwMDcgMTUuMDYzNyAxNS40NTcgMTUuMTg2NSAxNS4zODc3TDE2Ljk4NDQgMTQuMzUwNkMxNy4wNDkgMTQuMzA4NyAxNy4xMDMgMTQuMjUyMSAxNy4xNDE2IDE0LjE4NTVDMTcuMTgwMyAxNC4xMTg3IDE3LjIwMyAxNC4wNDMgMTcuMjA3IDEzLjk2NThWOC4wMjQ0MUMxNy4yMDI5IDcuOTQ3MzYgMTcuMTgwMyA3Ljg3MjQ2IDE3LjE0MTYgNy44MDU2NkMxNy4xMDI5IDcuNzM4ODQgMTcuMDQ5MyA3LjY4MTY0IDE2Ljk4NDQgNy42Mzk2NUwxMS44MjMyIDQuNjY3OTdDMTEuNzAwMiA0LjU5NzI4IDExLjU5NzcgNC41NDEwMiAxMS41OTc3IDQuNTQxMDJDMTEuNTg0NiA0LjUzMDQ3IDExLjQ4NzkgNC40ODIxMyAxMS4zNzIxIDQuNDE1MDRMMTAuNzA0MSA0LjAzMDI3Wk00Ni4yNDcxIDE1LjAwNDlINDUuMDkwOFYxMy4zMzY5SDQ2LjI0NzFWMTUuMDA0OVpNNDguNTI0NCAxNS4wMDQ5SDQ3LjM3OTlWMTMuMzM2OUg0OC41MjQ0VjE1LjAwNDlaTTUwLjgzNTkgMTUuMDA0OUg0OS42NTcyVjEzLjMzNjlINTAuODM1OVYxNS4wMDQ5Wk0zMi4wNjE1IDEwLjM2NTJIMzUuODAwOFYxMC45ODI0SDMxLjk4NjNWMTIuMDkwOEgzNS44MDA4VjEyLjc1NDlIMzEuMjUxVjEzLjgyNzFINDEuNzY1NlYxMi43NTQ5SDM3LjI2MjdWMTIuMDkwOEg0MS4wMjkzVjEwLjk4MjRIMzcuMjYyN1YxMC4zNjUySDM5Ljg1ODRDNDAuNDYzNCAxMC4zNjUyIDQwLjk1NCA5Ljg3NTQzIDQwLjk1NDEgOS4yNzE0OFY2LjAxNjZIMzIuMDYxNVYxMC4zNjUyWk0yMS4yNDQxIDguMzAzNzFDMjAuOTY4NiA5LjU3MTM4IDIwLjcxMzcgMTAuNTAxIDIwLjQ4MDUgMTEuMDkzOEMyMC4yNDcyIDExLjY4NjMgMTkuODEyNiAxMi41MDg2IDE5LjE3NDggMTMuNTYyNUwxOS4xMTUyIDEzLjY2MTFIMjAuNTc5MUwyMC41OTg2IDEzLjYzMzhDMjEuMzE2NiAxMi42MTg4IDIxLjgwNzUgMTEuNzYwNCAyMi4wNjc0IDExLjA1OTZDMjIuMzI1NyAxMC4zNjI4IDIyLjU4MzUgOS40NTMxMSAyMi44NDA4IDguMzMyMDNMMjIuODU4NCA4LjI1MjkzSDIxLjI1NDlMMjEuMjQ0MSA4LjMwMzcxWk0yNy4xOTA0IDguNjk4MjRDMjcuNDE5MiA5LjY1Mjc1IDI3LjY0ODMgMTAuNDQwMiAyNy44Nzc5IDExLjA1OTZDMjguMTM3OCAxMS43NjAzIDI4LjYyNzggMTIuNjE4OSAyOS4zNDU3IDEzLjYzMzhMMjkuMzY1MiAxMy42NjExSDMwLjgyOTFMMzAuNjE0MyAxMy4zMDQ3QzMwLjA2MDQgMTIuMzczNiAyOS42Nzc2IDExLjYzNjggMjkuNDYzOSAxMS4wOTM4QzI5LjIzMDYgMTAuNTAxIDI4Ljk3NTggOS41NzEzOCAyOC43MDAyIDguMzAzNzFMMjguNjg5NSA4LjI1MjkzSDI3LjA4NTlMMjcuMTkwNCA4LjY5ODI0Wk00NC4zNTQ1IDExLjg5MjZINTAuNDc2NkM1MS4wODE1IDExLjg5MjUgNTEuNTcyMSAxMS40MDI3IDUxLjU3MjMgMTAuNzk4OFY5LjM1MDU5SDQ0LjM1NDVWMTEuODkyNlpNNTAuNDI3NyAxMC40MDE0QzUwLjQyNzUgMTAuNzAzMiA1MC4xODIzIDEwLjk0ODIgNDkuODc5OSAxMC45NDgySDQ1LjQ5OVYxMC4yODMySDUwLjQyNzdWMTAuNDAxNFpNMzUuODAwOCA5LjI1NzgxSDMzLjI1MjlWNi45NDgyNEgzNS44MDA4VjkuMjU3ODFaTTM5Ljc2MzcgOC43MTA5NEMzOS43NjM1IDkuMDEyNjYgMzkuNTE4MSA5LjI1NzYgMzkuMjE1OCA5LjI1NzgxSDM3LjI2MjdWNi45NDgyNEgzOS43NjM3VjguNzEwOTRaTTQ3LjQ1NDEgNS41ODU5NEM0Ni4yMTQ0IDYuOTI4NCA0NC41Mzc1IDcuODYyNTcgNDIuNjQ5NCA4LjE2NDA2VjkuMDczMjRDNDMuNDc4NiA4Ljk1Mjc3IDQ0LjY1ODcgOC43NTU5OCA0NS4zNzExIDguNDA2MjVWOC43NDMxNkg1MC41NDM5VjguNDE3OTdDNTEuMTk3OCA4Ljc0NDM0IDUyLjQxMjIgOC45NDExMSA1My4yNzY0IDkuMDczMjRMNTMuMjc3MyA4LjE5NjI5QzUzLjI0OCA4LjE4Njc5IDUzLjIxODYgOC4xNzc1MiA1My4xODk1IDguMTY3OTdDNTEuMzA2IDcuODcyNjcgNDkuNjMxNiA2Ljk0OCA0OC4zODk2IDUuNjE2MjFMNDcuNDU0MSA1LjU4NTk0Wk0zMy42OTkyIDcuMTY3OTdDMzMuODU5OCA4LjIyNTk3IDM0LjQ2NTQgOS4wMjk4NiAzNC40Nzc1IDkuMDQ1OUgzNS40NTEyQzM1LjQ0NDIgOS4wMzEwOCAzNC45MzE2IDcuOTM5OTcgMzQuOTMxNiA3LjE2Nzk3SDMzLjY5OTJaTTM4LjExMTMgNy4xNjc5N0MzOC4xMTEzIDcuOTM3OCAzNy42MDE2IDkuMDI1MTEgMzcuNTkxOCA5LjA0NTlIMzguNTY1NEMzOC41ODE1IDkuMDI0NjUgMzkuMTgzNyA4LjIyMjQ0IDM5LjM0MzggNy4xNjc5N0gzOC4xMTEzWk00Ny45NjM5IDYuNjExMzNDNDguMzI1OSA3LjA0MjU0IDQ4Ljg3NDggNy40NzQwNiA0OS42MTA0IDcuOTA1MjdINDYuMjkzQzQ3LjA1MjEgNy40NjIyNSA0Ny42MDE4IDcuMDMxMDMgNDcuOTYzOSA2LjYxMTMzWiIgZmlsbD0id2hpdGUiLz4KPC9zdmc+Cg==",aD="data:image/svg+xml;base64,PHN2ZyBwcmVzZXJ2ZUFzcGVjdFJhdGlvPSJub25lIiBvdmVyZmxvdz0idmlzaWJsZSIgc3R5bGU9ImRpc3BsYXk6IGJsb2NrOyIgd2lkdGg9IjEyIiBoZWlnaHQ9IjEyIiB2aWV3Qm94PSIwIDAgMTIgMTIiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxnIGlkPSIxLWNvbW1vbl9zZWFyY2hfbGluZV8yNHgyNCI+CjxnIGlkPSJ1bmlvbiI+CjxwYXRoIGZpbGwtcnVsZT0iZXZlbm9kZCIgY2xpcC1ydWxlPSJldmVub2RkIiBkPSJNNS44NjAxMyAxLjkyNTAxQzMuNzI4NzkgMS45MjUwMSAyLjAwMDAyIDMuNjU0NiAyLjAwMDAyIDUuNzg5MzdDMi4wMDAwMiA3LjkyNDEzIDMuNzI4NzkgOS42NTM3MiA1Ljg2MDEzIDkuNjUzNzJDNy45OTE0NyA5LjY1MzcyIDkuNzIwMjQgNy45MjQxMyA5LjcyMDI0IDUuNzg5MzdDOS43MjAyNCAzLjY1NDYgNy45OTE0NyAxLjkyNTAxIDUuODYwMTMgMS45MjUwMVpNMC44MDAwMjQgNS43ODkzN0MwLjgwMDAyNCAyLjk5Mjk0IDMuMDY0OTcgMC43MjUwMTIgNS44NjAxMyAwLjcyNTAxMkM4LjY1NTI5IDAuNzI1MDEyIDEwLjkyMDIgMi45OTI5NCAxMC45MjAyIDUuNzg5MzdDMTAuOTIwMiA4LjU4NTggOC42NTUyOSAxMC44NTM3IDUuODYwMTMgMTAuODUzN0MzLjA2NDk3IDEwLjg1MzcgMC44MDAwMjQgOC41ODU4IDAuODAwMDI0IDUuNzg5MzdaIiBmaWxsPSJ3aGl0ZSIvPgo8cGF0aCBmaWxsLXJ1bGU9ImV2ZW5vZGQiIGNsaXAtcnVsZT0iZXZlbm9kZCIgZD0iTTkuMDEzMTkgOC45MzQ5N0M5LjI0NzQgOC43MDA1NCA5LjYyNzExIDguNzAwNTQgOS44NjEzMiA4LjkzNDk3TDExLjA1MDggMTAuMTI1NkMxMS4yODUgMTAuMzYgMTEuMjg1IDEwLjc0MDEgMTEuMDUwOCAxMC45NzQ1QzEwLjgxNjYgMTEuMjA4OSAxMC40MzY5IDExLjIwODkgMTAuMjAyNyAxMC45NzQ1TDkuMDEzMTkgOS43ODM5QzguNzc4OTkgOS41NDk0OCA4Ljc3ODk5IDkuMTY5NCA5LjAxMzE5IDguOTM0OTdaIiBmaWxsPSJ3aGl0ZSIvPgo8L2c+CjwvZz4KPC9zdmc+Cg==",cD="data:image/svg+xml;base64,PHN2ZyBwcmVzZXJ2ZUFzcGVjdFJhdGlvPSJub25lIiBvdmVyZmxvdz0idmlzaWJsZSIgc3R5bGU9ImRpc3BsYXk6IGJsb2NrOyIgd2lkdGg9IjY3IiBoZWlnaHQ9IjIyIiB2aWV3Qm94PSIwIDAgNjcgMjIiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxwYXRoIGlkPSJTdWJ0cmFjdCIgZD0iTTY2IDBDNjYuMzM3MiAwIDY2LjY3MDYgMC4wMTcxODM4IDY3IDAuMDQ2ODc1QzYxLjM5MzYgMC41NTIxODkgNTcgNS4yNjIwMiA1NyAxMUM1NyAxNi43MzggNjEuMzkzNiAyMS40NDY4IDY3IDIxLjk1MjFDNjYuNjcwNiAyMS45ODE4IDY2LjMzNzIgMjIgNjYgMjJIMTFDNC45MjQ4NyAyMiAwIDE3LjA3NTEgMCAxMUMwIDQuOTI0ODcgNC45MjQ4NyAyLjY1NzU2ZS0wNyAxMSAwSDY2Wk04LjI0MzE2IDYuNzM1MzVDOC4yNDMxNiA2LjU5Mzk3IDguMTQyNTggNi41MzU3NiA4LjAxOTUzIDYuNjA2NDVMNi4yMjI2NiA3LjY0MDYyQzYuMTU3ODcgNy42ODIyOCA2LjEwNDE2IDcuNzM5MTcgNi4wNjU0MyA3LjgwNTY2QzYuMDI2NzIgNy44NzIyNyA2LjAwNDEgNy45NDc1MiA2IDguMDI0NDFWMTMuOTY1OEM2LjAwMzcxIDE0LjA0MzQgNi4wMjU4NSAxNC4xMTkxIDYuMDY0NDUgMTQuMTg2NUM2LjEwMzE5IDE0LjI1NCA2LjE1NzQgMTQuMzEyIDYuMjIyNjYgMTQuMzU0NUw5Ljg3MTA5IDE2LjQ1OEM5Ljk5MzQ2IDE2LjUyNzIgMTAuMDkzNiAxNi41ODQyIDEwLjA5NDcgMTYuNTg1OUMxMC4wOTQ3IDE2LjU4NzEgMTAuMTkzNCAxNi42NDUxIDEwLjMxNjQgMTYuNzE1OEwxMi41MDEgMTcuOTY5N0MxMi42MjI4IDE4LjA0MDMgMTIuNzIzNiAxNy45ODIyIDEyLjcyMzYgMTcuODQwOFYxMi4zNjcyQzEyLjcyMyAxMi4yOTk0IDEyLjY5NTcgMTIuMjM0MyAxMi42NDc1IDEyLjE4NjVDMTIuNTk5MiAxMi4xMzg4IDEyLjUzMzggMTIuMTEyMyAxMi40NjU4IDEyLjExMjNIMTAuNzM3M0MxMC42NzAyIDEyLjExMzIgMTAuNjA1OSAxMi4xMzk5IDEwLjU1ODYgMTIuMTg3NUMxMC41MTEzIDEyLjIzNTIgMTAuNDg0NyAxMi4zMDAxIDEwLjQ4NDQgMTIuMzY3MlYxMy44Mzc5QzEwLjQ4NDIgMTMuOTc4OSAxMC4zODQ2IDE0LjAzNjQgMTAuMjYxNyAxMy45NjU4TDguNDY0ODQgMTIuOTM1NUM4LjQwMDI2IDEyLjg5MzUgOC4zNDYxNCAxMi44MzcyIDguMzA3NjIgMTIuNzcwNUM4LjI2OTE5IDEyLjcwNCA4LjI0NzM1IDEyLjYyOTQgOC4yNDMxNiAxMi41NTI3VjYuNzM1MzVaTTI0LjMzNCAxNC4zOTI2QzI0LjMzMzkgMTQuOTk4NSAyNC4yMDU1IDE1LjE4NDYgMjMuNTk4NiAxNS4xOTYzTDIyLjMwMTggMTUuMjU0OUwyMi42NjUgMTYuMjU0OUgyNS4wODY5QzI1LjY3MDUgMTYuMDg0IDI1Ljg3MjEgMTUuNzE5NCAyNS44NzIxIDE0LjgyMzJWNS43ODIyM0wyNC4zMzQgNS43MjM2M1YxNC4zOTI2Wk0zMi4yODIyIDE0LjQ3NTZDMzEuOTQ2IDE1LjA0OTIgMzEuNDY1OSAxNS43NTcxIDMxLjA5OTYgMTYuMjU0OUgzMi42MTkxQzMzLjA2NzMgMTUuNTIxMiAzMy4zNzUxIDE0LjkyOCAzMy41NDg4IDE0LjQ3NTZIMzIuMjgyMlpNMzQuODEwNSAxNS4zOTc1QzM0Ljg3OTEgMTUuNzEwMSAzNC45MzExIDE1Ljk5ODIgMzQuOTczNiAxNi4yNTQ5SDM2LjE4NjVMMzYuMTgxNiAxNi4yMzU0QzM2LjA2NjIgMTUuNzM4OCAzNS44OTg5IDE1LjAxOCAzNS43NDEyIDE0LjQ3NTZIMzQuNTI5M0wzNC44MTA1IDE1LjM5NzVaTTM2Ljk4MTQgMTQuNjUzM0MzNy4wOTg0IDE0Ljg3NyAzNy4yNDExIDE1LjE1MDEgMzcuMzMzIDE1LjQwMjNMMzcuNjM1NyAxNi4yNTQ5SDM5LjA4MDFDMzkuMDMzNiAxNS44MzI1IDM4LjU5NCAxNS4wNTUzIDM4LjIzODMgMTQuNDc1NkgzNi44ODg3QzM2LjkxNjEgMTQuNTI5OCAzNi45NDggMTQuNTg5NCAzNi45ODE0IDE0LjY1MzNaTTM5LjI3MDUgMTQuNDc1NkMzOS44MzAxIDE1LjE4MjEgNDAuMTg2MyAxNS44MDA0IDQwLjQxMzEgMTYuMjU0OUg0MS44MzVDNDEuNzM2NyAxNS42NjU2IDQxLjIyOTIgMTQuOTkzNiA0MC43NzY0IDE0LjQ3NTZIMzkuMjcwNVpNNDMuOTIyOSAxNS4wMDQ5SDQyLjc2NjZWMTUuOTk2MUg1My4xMjVWMTUuMDA0OUg1MS45Njg4VjEyLjQ3NTZINDMuOTIyOVYxNS4wMDQ5Wk0xMC43MDQxIDQuMDMwMjdDMTAuNTgxMSAzLjk1OTU4IDEwLjQ4MDUgNC4wMTc4IDEwLjQ4MDUgNC4xNTkxOFY5LjYyMzA1QzEwLjQ4MDYgOS42OTA3NCAxMC41MDc4IDkuNzU1NzggMTAuNTU1NyA5LjgwMzcxQzEwLjYwMzcgOS44NTE3MSAxMC42NjkzIDkuODc4ODcgMTAuNzM3MyA5Ljg3ODkxSDEyLjQ2NDhDMTIuNDk4NiA5Ljg3OTA1IDEyLjUzMjIgOS44NzIxNyAxMi41NjM1IDkuODU5MzhDMTIuNTk0NCA5Ljg0NjY2IDEyLjYyMjcgOS44MjgyMSAxMi42NDY1IDkuODA0NjlDMTIuNjcwNCA5Ljc4MDg5IDEyLjY5MDIgOS43NTE4NSAxMi43MDMxIDkuNzIwN0MxMi43MTYgOS42ODk3NSAxMi43MjI2IDkuNjU2NTQgMTIuNzIyNyA5LjYyMzA1VjguMTUyMzRDMTIuNzIyNyA4LjAxMSAxMi44MjIzIDcuOTUyODIgMTIuOTQ1MyA4LjAyMzQ0TDE0Ljc0MTIgOS4wNjE1MkMxNC44MDYgOS4xMDM2MiAxNC44NTk3IDkuMTYwNzcgMTQuODk4NCA5LjIyNzU0QzE0LjkzNzEgOS4yOTQzIDE0Ljk1OTYgOS4zNjkyOSAxNC45NjM5IDkuNDQ2MjlWMTUuMjU5OEMxNC45NjQxIDE1LjQwMDcgMTUuMDYzNyAxNS40NTcgMTUuMTg2NSAxNS4zODc3TDE2Ljk4NDQgMTQuMzUwNkMxNy4wNDkgMTQuMzA4NyAxNy4xMDMgMTQuMjUyMSAxNy4xNDE2IDE0LjE4NTVDMTcuMTgwMyAxNC4xMTg3IDE3LjIwMyAxNC4wNDMgMTcuMjA3IDEzLjk2NThWOC4wMjQ0MUMxNy4yMDI5IDcuOTQ3MzYgMTcuMTgwMyA3Ljg3MjQ2IDE3LjE0MTYgNy44MDU2NkMxNy4xMDI5IDcuNzM4ODQgMTcuMDQ5MyA3LjY4MTY0IDE2Ljk4NDQgNy42Mzk2NUwxMS44MjMyIDQuNjY3OTdDMTEuNzAwMiA0LjU5NzI4IDExLjU5NzcgNC41NDEwMiAxMS41OTc3IDQuNTQxMDJDMTEuNTg0NiA0LjUzMDQ3IDExLjQ4NzkgNC40ODIxMyAxMS4zNzIxIDQuNDE1MDRMMTAuNzA0MSA0LjAzMDI3Wk00Ni4yNDcxIDE1LjAwNDlINDUuMDkwOFYxMy4zMzY5SDQ2LjI0NzFWMTUuMDA0OVpNNDguNTI0NCAxNS4wMDQ5SDQ3LjM3OTlWMTMuMzM2OUg0OC41MjQ0VjE1LjAwNDlaTTUwLjgzNTkgMTUuMDA0OUg0OS42NTcyVjEzLjMzNjlINTAuODM1OVYxNS4wMDQ5Wk0zMi4wNjE1IDEwLjM2NTJIMzUuODAwOFYxMC45ODI0SDMxLjk4NjNWMTIuMDkwOEgzNS44MDA4VjEyLjc1NDlIMzEuMjUxVjEzLjgyNzFINDEuNzY1NlYxMi43NTQ5SDM3LjI2MjdWMTIuMDkwOEg0MS4wMjkzVjEwLjk4MjRIMzcuMjYyN1YxMC4zNjUySDM5Ljg1ODRDNDAuNDYzNCAxMC4zNjUyIDQwLjk1NCA5Ljg3NTQzIDQwLjk1NDEgOS4yNzE0OFY2LjAxNjZIMzIuMDYxNVYxMC4zNjUyWk0yMS4yNDQxIDguMzAzNzFDMjAuOTY4NiA5LjU3MTM4IDIwLjcxMzcgMTAuNTAxIDIwLjQ4MDUgMTEuMDkzOEMyMC4yNDcyIDExLjY4NjMgMTkuODEyNiAxMi41MDg2IDE5LjE3NDggMTMuNTYyNUwxOS4xMTUyIDEzLjY2MTFIMjAuNTc5MUwyMC41OTg2IDEzLjYzMzhDMjEuMzE2NiAxMi42MTg4IDIxLjgwNzUgMTEuNzYwNCAyMi4wNjc0IDExLjA1OTZDMjIuMzI1NyAxMC4zNjI4IDIyLjU4MzUgOS40NTMxMSAyMi44NDA4IDguMzMyMDNMMjIuODU4NCA4LjI1MjkzSDIxLjI1NDlMMjEuMjQ0MSA4LjMwMzcxWk0yNy4xOTA0IDguNjk4MjRDMjcuNDE5MiA5LjY1Mjc1IDI3LjY0ODMgMTAuNDQwMiAyNy44Nzc5IDExLjA1OTZDMjguMTM3OCAxMS43NjAzIDI4LjYyNzggMTIuNjE4OSAyOS4zNDU3IDEzLjYzMzhMMjkuMzY1MiAxMy42NjExSDMwLjgyOTFMMzAuNjE0MyAxMy4zMDQ3QzMwLjA2MDQgMTIuMzczNiAyOS42Nzc2IDExLjYzNjggMjkuNDYzOSAxMS4wOTM4QzI5LjIzMDYgMTAuNTAxIDI4Ljk3NTggOS41NzEzOCAyOC43MDAyIDguMzAzNzFMMjguNjg5NSA4LjI1MjkzSDI3LjA4NTlMMjcuMTkwNCA4LjY5ODI0Wk00NC4zNTQ1IDExLjg5MjZINTAuNDc2NkM1MS4wODE1IDExLjg5MjUgNTEuNTcyMSAxMS40MDI3IDUxLjU3MjMgMTAuNzk4OFY5LjM1MDU5SDQ0LjM1NDVWMTEuODkyNlpNNTAuNDI3NyAxMC40MDE0QzUwLjQyNzUgMTAuNzAzMiA1MC4xODIzIDEwLjk0ODIgNDkuODc5OSAxMC45NDgySDQ1LjQ5OVYxMC4yODMySDUwLjQyNzdWMTAuNDAxNFpNMzUuODAwOCA5LjI1NzgxSDMzLjI1MjlWNi45NDgyNEgzNS44MDA4VjkuMjU3ODFaTTM5Ljc2MzcgOC43MTA5NEMzOS43NjM1IDkuMDEyNjYgMzkuNTE4MSA5LjI1NzYgMzkuMjE1OCA5LjI1NzgxSDM3LjI2MjdWNi45NDgyNEgzOS43NjM3VjguNzEwOTRaTTQ3LjQ1NDEgNS41ODU5NEM0Ni4yMTQ0IDYuOTI4NCA0NC41Mzc1IDcuODYyNTcgNDIuNjQ5NCA4LjE2NDA2VjkuMDczMjRDNDMuNDc4NiA4Ljk1Mjc3IDQ0LjY1ODcgOC43NTU5OCA0NS4zNzExIDguNDA2MjVWOC43NDMxNkg1MC41NDM5VjguNDE3OTdDNTEuMTk3OCA4Ljc0NDM0IDUyLjQxMjIgOC45NDExMSA1My4yNzY0IDkuMDczMjRMNTMuMjc3MyA4LjE5NjI5QzUzLjI0OCA4LjE4Njc5IDUzLjIxODYgOC4xNzc1MiA1My4xODk1IDguMTY3OTdDNTEuMzA2IDcuODcyNjcgNDkuNjMxNiA2Ljk0OCA0OC4zODk2IDUuNjE2MjFMNDcuNDU0MSA1LjU4NTk0Wk0zMy42OTkyIDcuMTY3OTdDMzMuODU5OCA4LjIyNTk3IDM0LjQ2NTQgOS4wMjk4NiAzNC40Nzc1IDkuMDQ1OUgzNS40NTEyQzM1LjQ0NDIgOS4wMzEwOCAzNC45MzE2IDcuOTM5OTcgMzQuOTMxNiA3LjE2Nzk3SDMzLjY5OTJaTTM4LjExMTMgNy4xNjc5N0MzOC4xMTEzIDcuOTM3OCAzNy42MDE2IDkuMDI1MTEgMzcuNTkxOCA5LjA0NTlIMzguNTY1NEMzOC41ODE1IDkuMDI0NjUgMzkuMTgzNyA4LjIyMjQ0IDM5LjM0MzggNy4xNjc5N0gzOC4xMTEzWk00Ny45NjM5IDYuNjExMzNDNDguMzI1OSA3LjA0MjU0IDQ4Ljg3NDggNy40NzQwNiA0OS42MTA0IDcuOTA1MjdINDYuMjkzQzQ3LjA1MjEgNy40NjIyNSA0Ny42MDE4IDcuMDMxMDMgNDcuOTYzOSA2LjYxMTMzWiIgZmlsbD0iYmxhY2siLz4KPC9zdmc+Cg==",dD="data:image/svg+xml;base64,PHN2ZyBwcmVzZXJ2ZUFzcGVjdFJhdGlvPSJub25lIiBvdmVyZmxvdz0idmlzaWJsZSIgc3R5bGU9ImRpc3BsYXk6IGJsb2NrOyIgd2lkdGg9IjEyIiBoZWlnaHQ9IjEyIiB2aWV3Qm94PSIwIDAgMTIgMTIiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxnIGlkPSIxLWNvbW1vbl9zZWFyY2hfbGluZV8yNHgyNCI+CjxnIGlkPSJ1bmlvbiI+CjxwYXRoIGZpbGwtcnVsZT0iZXZlbm9kZCIgY2xpcC1ydWxlPSJldmVub2RkIiBkPSJNNS44NjAxMyAxLjkyNTAxQzMuNzI4NzkgMS45MjUwMSAyLjAwMDAyIDMuNjU0NiAyLjAwMDAyIDUuNzg5MzdDMi4wMDAwMiA3LjkyNDEzIDMuNzI4NzkgOS42NTM3MiA1Ljg2MDEzIDkuNjUzNzJDNy45OTE0NyA5LjY1MzcyIDkuNzIwMjQgNy45MjQxMyA5LjcyMDI0IDUuNzg5MzdDOS43MjAyNCAzLjY1NDYgNy45OTE0NyAxLjkyNTAxIDUuODYwMTMgMS45MjUwMVpNMC44MDAwMjQgNS43ODkzN0MwLjgwMDAyNCAyLjk5Mjk0IDMuMDY0OTcgMC43MjUwMTIgNS44NjAxMyAwLjcyNTAxMkM4LjY1NTI5IDAuNzI1MDEyIDEwLjkyMDIgMi45OTI5NCAxMC45MjAyIDUuNzg5MzdDMTAuOTIwMiA4LjU4NTggOC42NTUyOSAxMC44NTM3IDUuODYwMTMgMTAuODUzN0MzLjA2NDk3IDEwLjg1MzcgMC44MDAwMjQgOC41ODU4IDAuODAwMDI0IDUuNzg5MzdaIiBmaWxsPSJibGFjayIvPgo8cGF0aCBmaWxsLXJ1bGU9ImV2ZW5vZGQiIGNsaXAtcnVsZT0iZXZlbm9kZCIgZD0iTTkuMDEzMTkgOC45MzQ5N0M5LjI0NzQgOC43MDA1NCA5LjYyNzExIDguNzAwNTQgOS44NjEzMiA4LjkzNDk3TDExLjA1MDggMTAuMTI1NkMxMS4yODUgMTAuMzYgMTEuMjg1IDEwLjc0MDEgMTEuMDUwOCAxMC45NzQ1QzEwLjgxNjYgMTEuMjA4OSAxMC40MzY5IDExLjIwODkgMTAuMjAyNyAxMC45NzQ1TDkuMDEzMTkgOS43ODM5QzguNzc4OTkgOS41NDk0OCA4Ljc3ODk5IDkuMTY5NCA5LjAxMzE5IDguOTM0OTdaIiBmaWxsPSJibGFjayIvPgo8L2c+CjwvZz4KPC9zdmc+Cg==";async function uD(e,t,r,n,i="dark"){pe(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 f=e.createElement("div");f.style.cssText="display:flex;align-items:center;max-width:calc(100% - 24px);height:22px;flex-shrink:0;";const l=e.createElement("img");l.src=a?cD:sD,l.style.cssText="width:67px;height:22px;flex-shrink:0;margin-right:-11px;";const h=e.createElement("div");h.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 m=e.createElement("img");m.src=a?dD:aD,m.style.cssText="width:12px;height:12px;flex-shrink:0;";const E=e.createElement("span");E.textContent=t?.trim()||"小程序工坊",E.style.cssText=`color:${c};font-size:11px;font-weight:500;line-height:16px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;`;const _=e.createElement("div");_.textContent="小黑盒工坊小程序",_.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;`,h.append(m,E),f.append(l,h),u.append(f,_),s.append(u),e.body.append(s);const w=()=>{s.remove(),n.removeEventListener("abort",w)};n.addEventListener("abort",w,{once:!0});try{return await fe(()=>Promise.all([l.decode(),m.decode()]),n),await fe(()=>new Promise(S=>{let p=o.requestAnimationFrame(()=>{p=o.requestAnimationFrame(()=>{n.removeEventListener("abort",M),S()})});const M=()=>o.cancelAnimationFrame(p);n.addEventListener("abort",M,{once:!0})}),n),w}catch(S){throw w(),S}}const lD=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"]),fD=new Set(["url","inline","eval","unknown"]),hD=/^\/(?:\:segment(?:\/\:segment)*)?$/,mD=/^[a-f0-9]{64}$/,gD=255,pD=160,yD=256;function ED(e,t){const r=e;if(!r||typeof r.sdkVersion!="string"||r.sdkVersion!==t||typeof r.effectiveDirective!="string"||!lD.has(r.effectiveDirective)||typeof r.violatedDirective!="string"||r.violatedDirective.length>yD||r.violatedDirective.split(/\s/,1)[0]!==r.effectiveDirective||!["enforce","report"].includes(r.disposition??"")||typeof r.blockedResourceType!="string"||!fD.has(r.blockedResourceType)||typeof r.timestamp!="number"||!Number.isFinite(r.timestamp)||r.timestamp<0)return;const n=wD(r.blockedOrigin);if(r.blockedOrigin!==void 0&&!n)return;const i=r.redactedPathname;if(i!==void 0&&(typeof i!="string"||i.length>pD||!hD.test(i)))return;const o=r.sanitizedPathnameHash;if(!(o!==void 0&&(typeof o!="string"||!mD.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 wD(e){if(e!==void 0&&!(typeof e!="string"||e.length>gD))try{const t=new URL(e);return["http:","https:"].includes(t.protocol)&&t.origin===e?t.origin:void 0}catch{return}}const jo=["android","ios","ohos","windows","macos","linux"],ID="0.9.0",AD=Object.freeze(["android","ios","ohos","windows","macos"]),sh="该小程序暂不支持当前平台",_D="PLATFORM_UNSUPPORTED";function DD(e){return typeof e=="string"&&jo.includes(e)}function ND(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 MD(e){const t=e.manifest;if(!OD(t))return{status:"invalid",reason:"manifest_not_object"};if(!Object.prototype.hasOwnProperty.call(t,"platforms")){const n=du(e.sdkVersion)??du(t.sdkVersion);return TD(n)?{status:"invalid",reason:"platforms_missing_after_hard_cutover"}:bD()}const r=ah(t.platforms);return"reason"in r?{status:"invalid",reason:r.reason}:{status:"resolved",declaredPlatforms:r.platforms,effectivePlatforms:r.platforms,platformsDeclared:!0,policy:"explicit"}}function SD(e){const t=ND(e.operatingSystemName);if(!t)return _r("host_operating_system_unknown");const r=e.platformAccess;if(!r)return _r("platform_access_missing",{platform:t});if(r.source==="compatibility-window")return{status:"allowed",platform:t,effectivePlatforms:jo,platformsDeclared:!1,policy:"legacy_mobile_default",compatibility:r.reason};if(r.source==="manifest"){const s=MD({manifest:r.manifest,...r.sdkVersion===void 0?{}:{sdkVersion:r.sdkVersion}});return s.status==="invalid"?_r("platform_declaration_invalid",{invalidReason:s.reason,platform:t}):cu(t,s)}if(r.effectivePlatforms===void 0)return _r("platform_declaration_invalid",{invalidReason:"effective_platforms_missing",platform:t});const n=ah(r.effectivePlatforms);if("reason"in n)return _r("platform_declaration_invalid",{invalidReason:n.reason,platform:t});const i=typeof r.platformsDeclared=="boolean"?r.platformsDeclared:!0,o=vD(r.platformPolicy)?r.platformPolicy:i?"explicit":"legacy_mobile_default";return cu(t,{declaredPlatforms:i?n.platforms:[],effectivePlatforms:n.platforms,platformsDeclared:i,policy:o})}function cu(e,t){return t.effectivePlatforms.includes(e)?{status:"allowed",platform:e,effectivePlatforms:t.effectivePlatforms,platformsDeclared:t.platformsDeclared,policy:t.policy}:_r("platform_not_supported",{effectivePlatforms:t.effectivePlatforms,platform:e})}function _r(e,t={}){return{status:"denied",reason:e,message:sh,...t}}function bD(){return{status:"resolved",declaredPlatforms:[],effectivePlatforms:AD,platformsDeclared:!1,policy:"legacy_mobile_default"}}function ah(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(!DD(r))return{reason:"platform_unknown_value"};if(t.has(r))return{reason:"platform_duplicate_value"};t.add(r)}return{platforms:Object.freeze(jo.filter(r=>t.has(r)))}}function TD(e){if(typeof e!="string"||!e.trim())return!1;const t=ec(e.trim(),ID);return t!==void 0&&t>=0}function du(e){return typeof e=="string"&&e.trim()?e.trim():void 0}function vD(e){return e==="explicit"||e==="legacy_mobile_default"}function OD(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function RD(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:kD(i.pathname),sanitizedPathnameHash:Ga(i.pathname)}}catch{return{type:"security_violation",errorCode:e,timestamp:n,sdkVersion:r}}}function kD(e){return(e==="/"?e:e.replace(/\/+$/,"")).split("/").map(r=>r?":segment":"").join("/")}const PD=1e4,CD=1e4,us=2e3,LD=2,UD="open-with-native-credential-policy",ch="安全提示",dh="即将打开未经验证的开发网页。该页面可能由本机或局域网服务提供,请确认来源可信后继续。";class xD{nonce=Vc();runtimeId=Vc();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=ql(t.ports,{callerCapabilities:t.capabilities,hostCapabilities:t.hostCapabilities,hasUserDataPresentation:t.userDataPresentation!==void 0,hasUserDataSettings:t.userDataPresentation?.openDataPermissions!==void 0});this.ports=r.ports,this.primitiveAvailability=r.primitiveAvailability,this.effectiveCapabilities=r.effectiveCapabilities,this.identity={},this.identityRef={get:()=>{const n=this.identity.miniProgramId?.trim();if(n)return{miniProgramId:n,...this.identity.miniProgramVersion?{version:this.identity.miniProgramVersion}:{}}}},this.handshakeTimeout=t.handshakeTimeout??PD,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}getDataPermissionBridge(){return this.capabilityGraph?.permissionBridge}get diagnostics(){const t=this.capabilityGraph?.storageDiagnostics,r=this.capabilityGraph?.sandboxDiagnostics,n=this.capabilityGraph?.gameSaveDiagnostics;return{...t?{storage:t}:{},...r?{sandbox:r}:{},...n?{gameSaves:n}:{}}}start(){return this.stateValue==="destroyed"?Promise.reject(this.terminalError??we("RUNTIME_DESTROYED","小程序运行时已销毁")):this.stateValue==="failed"?Promise.reject(this.terminalError??we("STARTUP_ERROR","小程序运行时启动失败")):this.readyContext?Promise.resolve(this.readyContext):this.startPromise?this.startPromise:(WD(),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??we("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=cy(t.runtimePermissions),this.networkPolicy=Ql(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 Gp(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=Zy(t.sdkVersionPolicy);const n=rD(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=SD({operatingSystemName:t.environmentInfo?.operatingSystem?.name,...t.platformAccess===void 0?{}:{platformAccess:t.platformAccess}}),this.platformGateDecision.status==="denied")throw JD(this.platformGateDecision);if(this.miniProgramDetail=XD(t),this.effectiveCapabilities=$l(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),GD(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(qD(i)),this.launchUrl=i,this.options.onDevDocumentReload&&t.sdkVersionPolicy?.releaseChannel==="development"){const s=Yl(new URL(i),this.locationBasePath);this.devDocumentDisposer=ay({iframe:this.iframe,launchUrl:i,nonce:this.nonce,locationBasePath:s,onLeaving:()=>{this.prepareForHistoryTraversal()},onResume:()=>{!this.isInactive()&&this.documentRevalidationPending&&this.beginDocumentRevalidation()},onReload:a=>{this.isInactive()||ot(c=>this.options.onDevDocumentReload?.(c,s),a)}})}if(this.miniProgramSrc=Xp(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=$a(s);this.trace({runtimeId:this.runtimeId,timestamp:Date.now(),type:"error",method:nr,errorCode:a.code,message:`默认展示设置失败,沿用宿主当前布局:${a.message}`})}if(this.isInactive())return}this.awaitingControlledDocumentLoad=!0,this.iframe.src=this.miniProgramSrc,ot(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[nr])&&this.bridgeServer?.postEvent(n,i)}};this.capabilityGraph=Y_({verifiedSdkVersion:this.sdkVersionDecision?.sdkVersion,diagnosticCapabilities:this.effectiveCapabilities,account:this.ports.account,network:this.ports.network,files:this.ports.files,picker:this.ports.picker,media:this.ports.media,transfer:this.ports.transfer,storage:this.ports.storage,scopedStorage:this.ports.scopedStorage,storageDiagnostics:this.ports.storageDiagnostics,hostPresentation:this.ports.presentation,hostCompanion:this.ports.companion,hostProtocol:this.ports.protocol,...this.options.userDataPresentation===void 0?{}:{userDataPresentation:this.options.userDataPresentation},...this.options.onUserDataTelemetry===void 0?{}:{onUserDataTelemetry:this.options.onUserDataTelemetry},workspaceCards:this.ports.workspaceCards,environment:this.options.environment,identity:this.identityRef,runtimePermissions:this.runtimePermissions,runtimeFeatures:this.runtimeFeatures,networkPolicy:this.networkPolicy,authorizationContext:this.options.authorizationContext,terminalSignal:this.terminalController.signal,eventSink:t,authPresentation:this.options.authPresentation,companionPresentation:this.options.companionPresentation,miniProgramPresentation:this.miniProgramPresentation,prepareLongScreenshot:(n,i)=>Vp(this.iframe,n,i),prepareScreenshot:(n,i,o)=>{const s=this.sdkVersionDecision?.sdkVersion;return!s||(ec(s,"0.9.1")??-1)<0?Promise.resolve(()=>{}):uD(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=G_({handlers:this.capabilityGraph.handlers,runDisplayRequest:this.capabilityGraph.runDisplayRequest,effectiveCapabilities:this.effectiveCapabilities,runtimePermissions:this.runtimePermissions,terminalSignal:this.terminalController.signal,allowsCompanionAttachmentAccess:this.capabilityGraph.allowsCompanionAttachmentAccess,allowsGameSaveAccess:this.capabilityGraph.allowsGameSaveAccess,allowsUserGameDataFileAccess:this.capabilityGraph.allowsUserGameDataFileAccess,policies:this.options.policies,...this.options.onCapabilityTrace?{onTrace:({callId:n,method:i,startedAt:o,timestamp:s,durationMs:a,outcome:c,errorCode:d,network:u})=>{const f={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}:{}};ot(this.options.onCapabilityTrace,f)}}:{}});this.bridgeServer=new hy({iframe:this.iframe,nonce:this.nonce,dispatcher:r,environmentInfo:this.environmentInfo,...this.options.onDevUploadSession?{onDevUploadSession:n=>{this.isInactive()||ot(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(we("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 VD(t)?t:uh(we("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 Jp(t,r,{allowPrivateNetwork:au(r)||uu(r)||await this.isDevRuntime()})}catch(r){throw we("INVALID_LAUNCH_URL",r instanceof Error?r.message:"小程序链接不合法",r)}}async confirmDevMiniProgramLaunch(t){return await this.shouldConfirmDevMiniProgramLaunch(t)?this.isInactive()?!1:!!await(this.options.confirmDevMiniProgramLaunch??YD)({message:dh,title:ch,url:t}):!0}async shouldConfirmDevMiniProgramLaunch(t){if($c(t)==="production")return!1;const r=this.options.environment.getCurrentHref();return!au(r)&&!uu(r)}async closeAfterDevLaunchCancellation(){const t=we("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{lu(),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(()=>lu())}async isDevRuntime(){return this.devRuntimePromise??=Promise.resolve().then(()=>this.options.environment.isDevRuntime()).then(Boolean).catch(()=>!1),this.devRuntimePromise}applyIframeDefaults(){this.iframe.setAttribute("allow",Yp),this.iframe.setAttribute("referrerpolicy",Wp),this.iframe.setAttribute("sandbox",Wl)}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(),ot(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(),ot(this.options.onReady,t)}handleBridgeHandshake(t){const r=this.sdkVersionDecision?.sdkVersion;if(r)try{Ky(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(we("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>=LD)){this.failRuntime(we("HEARTBEAT_TIMEOUT","小程序 SDK 心跳超时"));return}const t=`${Date.now().toString(36)}_${++this.probeSequence}`;this.pendingProbeId=t,this.bridgeServer?.postInternalRequest(Fn,t,{probeId:t,timestamp:Date.now()}),this.heartbeatTimer=setTimeout(()=>{this.heartbeatTimer=void 0,this.sendLocationProbe()},us),this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"location_probe",method:Fn})}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(Fn,t,{probeId:t,timestamp:Date.now()}),this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"location_probe",method:Fn})}armDocumentRevalidationTimer(t,r={}){this.clearDocumentRevalidationTimer(),this.hostVisible&&(this.documentRevalidationTimer=setTimeout(()=>{this.documentRevalidationTimer=void 0,!(this.isInactive()||!this.documentRevalidationPending||t!==this.documentRevalidationGeneration)&&this.failRuntime(we("DOCUMENT_REVALIDATION_TIMEOUT",r.waitingForDocument?"小程序 iframe 目标文档加载超时":"小程序 iframe 文档再验证超时"))},r.waitingForDocument?CD:us))}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()},us)),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===Om){this.handleCspViolation(t.payload);return}if(t.method!==vm)return;const r=this.sdkVersionDecision?.sdkVersion;if(!r)return;const n=t.payload;if(!n||n.sdkVersion!==r){this.failRuntime(we("SDK_VERSION_MISMATCH","URL report 的 SDK 版本不一致"));return}if(!(n.probeId!==void 0&&n.probeId!==this.pendingProbeId)){if(typeof n.href!="string"||!Zl(this.launchUrl,n.href,this.locationBasePath)){typeof n.href=="string"&&this.emitUrlSecurityViolation("URL_OUT_OF_SCOPE",n.href),this.failRuntime(we("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=ED(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){ot(this.options.onSecurityViolation,t),this.trace({runtimeId:this.nonce,...t})}emitUrlSecurityViolation(t,r){const n=RD(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(we("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:Qp,launchUrlType:$c(t),networkPolicy:UD})}failRuntime(t){const r=zD(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}),ot(this.options.onError,jD(r)),ot(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,ot(this.options.onStateChange,t))}isInactive(){return this.stateValue==="failed"||this.stateValue==="destroyed"}trace(t){ot(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 zD(e){const t=$a(e);return go(e)&&"cause"in e&&uh(t,e.cause),t}function uh(e,t){return Object.defineProperty(e,"cause",{configurable:!0,enumerable:!1,value:t}),e}function jD(e){return{code:e.code,message:e.message,...e.data!==void 0?{data:e.data}:{},...e.cause!==void 0?{cause:FD(e.cause)}:{}}}const ls=(()=>{const e=Object.getOwnPropertyDescriptor(new Error,"stack")?.get,t=Object.getOwnPropertyDescriptor(new Error,"stack")?.get;return typeof e=="function"&&e===t?e:void 0})(),BD=new Set([Error.prototype,TypeError.prototype,RangeError.prototype,ReferenceError.prototype,SyntaxError.prototype,URIError.prototype,EvalError.prototype]);function HD(e,t){const r=Object.getOwnPropertyDescriptor(e,t);if(!r)return;if("value"in r)return r.value;if(t!=="stack"||!ls||r.get!==ls)return;const n=Object.getPrototypeOf(e);if(BD.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 ls.call(e)}}function FD(e){if(!(!e||typeof e!="object"))try{const t={};for(const r of["name","message","stack"]){const n=HD(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 VD(e){return go(e)&&typeof e.code=="string"&&typeof e.message=="string"}function go(e){return!!e&&typeof e=="object"}function ot(e,t){try{e?.(t)}catch{}}function GD(e,t,r){try{e?.(t,r)}catch{}}function uu(e){try{const t=new URL(e);return t.protocol==="http:"&&X_(t.hostname)}catch{return!1}}function $D(e){try{return new URL(e).origin}catch{return}}function qD(e){return Zp()?"*":$D(e)}function QD(e){return`${ch}
5
+ `,H=(ye,Oe,Me=0,ke=0)=>`${A} {position:absolute!important;left:${ye}px!important;top:${Oe}px!important;width:${x}px!important;height:${N}px!important;transform:translate(${Me}px,${ke}px) rotate(${v}rad)!important;transition:none!important;z-index:2147483646!important;background-color:${U}!important;}`;L.textContent=C+H(0,0),M(),t.head.append(L);const F=l.getBoundingClientRect(),$=t.querySelector(Hn.app),K=$&&l.contains($)?$.getBoundingClientRect():void 0,g=K&&K.width>0&&K.height>0?K:void 0,k=g?Math.floor(r.innerWidth-1-(g.left-F.left)):r.innerWidth+64,B=g?Math.floor(r.innerHeight-1-(g.top-F.top)):32,Q=k-F.left,X=B-F.top;M(),L.textContent=C+H(Q,X);const ne=l.getBoundingClientRect();L.textContent=C+H(Q,X,k-ne.left,B-ne.top),M();const ie=h.getBoundingClientRect(),ue=Math.floor(lr(ie.left+r.scrollX)),Ee=Math.floor(lr(ie.top+r.scrollY)),me={x:ue,y:Ee,width:Math.ceil(lr(ie.right+r.scrollX))-ue,height:Math.ceil(lr(ie.bottom+r.scrollY))-Ee};if(!(me.width>0&&me.height>0)||me.x<0||me.y<0)throw Ve("CAPTURE_LAYOUT_INVALID","无法建立完整设备截图布局");if(g&&$){const ye=$.getBoundingClientRect();if(!(ye.left<r.innerWidth&&ye.top<r.innerHeight&&ye.right>0&&ye.bottom>0))throw Ve("CAPTURE_LAYOUT_INVALID","无法保持 iframe 的最小绘制区域");const Oe=l.getBoundingClientRect(),Me=Math.floor(lr(Oe.left))-1,ke=Math.floor(lr(Oe.top))-1,ze=r.innerWidth-Me,Ft=r.innerHeight-ke;if(Me<0||ke<0||ze<=0||Ft<=0||ze>Nc||Ft>Nc||ze*Ft>_m)throw Ve("CAPTURE_LAYOUT_INVALID","无法在有界角部保持完整设备绘制,请改用 --scale css");E.style.clipPath=`polygon(0 0,100% 0,100% ${ke}px,${Me}px ${ke}px,${Me}px 100%,0 100%)`,E.setAttribute("data-hb-preview-capture-corner",JSON.stringify({x:Me,y:ke,width:ze,height:Ft}))}const ge=t.createElement("div");if(ge.setAttribute("aria-hidden","true"),ge.style.cssText=`position:absolute;left:${me.x+me.width+2}px;top:${me.y+me.height+2}px;width:1px;height:1px;pointer-events:none;opacity:0;`,w.bounds=ge,M(),t.body.append(ge),w.target=h,w.rect=ie,await Nm(r,u),M(),!a(w))throw Ve("CAPTURE_LAYOUT_INVALID","截图准备期间布局发生变化,请重新截图");w.observer=new r.ResizeObserver(()=>{i===w&&!a(w)&&s(w.token)});for(const{element:ye}of w.attributes)w.observer.observe(ye);return{token:z,clip:me,devicePixelRatio:r.devicePixelRatio,expiresAt:_}}catch(z){throw s(w.token),z}}return{prepare:c,restore:s,cancel:d=>i?.operationId!==d?!1:(s(i.token),!0),dispose:()=>{i&&s(i.token)}}}function Nm(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 Ve(e,t){return Object.assign(new Error(t),{name:"PreviewError",code:e})}function lr(e){const t=Math.round(e);return Math.abs(e-t)<.001?t:e}const Ca="user.games.getOverview",Ai="user.data.query",un="user.data.sync",_i="user.data.file",La="user.dataPermission.request",Ua="user.dataPermission.get",xa="user.dataPermission.set",za="user.dataPermission.openSettings",ja="user.dataPermission.revokeSession",ml=[Ca,Ai,un,_i,La,Ua,xa,za,ja],Di="workspaceCards.requestRefresh",Ni="auth.getAccountState",Mi="auth.login",Si="user.getFollowStatus",bi="user.requestFollowAuthor",Mm="gameSaves.list",Sm="gameSaves.sync",bm="gameSaves.getFile",Tm="gameSaves.readParsedData",Ti="user.getInfo",vi="user.revokeAuthorization",Oi="user.getSteamGameList",yn="user.showAppreciation",Ri="share.copyLink",Pi="share.showShareMenu",ki="share.screenshot",Ci="share.screenshotLong",nr="viewport.setDisplay",Li="viewport.getWindowInfo",Ui="viewport.setNavigationBarStyle",En="storage.getStorage",wn="storage.setStorage",xi="network.request",zi="network.download",ji="network.upload",Bi="files.pickFiles",Hi="files.pickDirectory",Fi="files.saveFile",In="file.create",An="file.remove",Vi="file.exists",_n="file.readText",Gi="file.writeText",Dn="file.readBytes",$i="file.writeBytes",Nn="file.stat",qi="directory.create",Mn="directory.remove",Qi="directory.exists",Yi="directory.list",Sn="media.pick",Wi="ui.showToast",Zi="ui.showLoading",Ki="ui.hideLoading",Ji="device.vibrate",Xi="device.setClipboard",eo="device.executeProtocol",to="navigation.close",ro="navigation.reload",no="navigation.openAppPage",bt="cloud.leaderboard.submit",at="cloud.leaderboard.getList",xt="cloud.leaderboard.getCurrentUserEntry",ir="cloud.leaderboard.deleteCurrentUserEntry",wt="cloud.leaderboard.getInfo",vr="cloud.storage.getStorage",Or="cloud.storage.setStorage",Rr="cloud.storage.removeItem",or="cloud.storage.getKeys",wo="companion.getInfo",Io="companion.getPreparationStatus",Ao="companion.prepare",_o="companion.cancelPreparation",Do="companion.getActiveSession",No="companion.launch",Mo="companion.session.write",So="companion.session.closeStdin",bo="companion.session.terminate",To="companion.session.ackOutput",vo="companion.openAttachment",Oo="companion.showNotification",zt=[...[Mm,Sm,bm,Tm].map(e=>({method:e,module:"gameSaves",capability:e,requirement:{kind:"all",permissions:["gameSaves"]},risk:"high"})),...ml.map(e=>({method:e,module:"userGameData",capability:e,requirement:{kind:"all",permissions:["user_game_data"]},risk:"high"})),{method:Di,module:"workspaceCards",capability:Di,requirement:{kind:"all",permissions:["workspaceCards"]},risk:"high"},{method:Ni,module:"auth",capability:Ni,requirement:{kind:"none"},risk:"low"},{method:Mi,module:"auth",capability:Mi,requirement:{kind:"all",permissions:["userInfo"]},risk:"medium"},{method:Si,module:"user",capability:Si,requirement:{kind:"none"},risk:"low"},{method:bi,module:"user",capability:bi,requirement:{kind:"none"},risk:"high"},{method:Ti,module:"user",capability:Ti,requirement:{kind:"all",permissions:["userInfo"]},risk:"medium"},{method:vi,module:"user",capability:vi,requirement:{kind:"none"},risk:"high"},{method:Oi,module:"user",capability:Oi,requirement:{kind:"all",permissions:["steamLibrary"]},risk:"high"},{method:yn,module:"user",capability:yn,requirement:{kind:"none"},risk:"medium"},{method:Ri,module:"share",capability:Ri,requirement:{kind:"all",permissions:["share"]},risk:"medium"},{method:Pi,module:"share",capability:Pi,requirement:{kind:"all",permissions:["share"]},risk:"low"},{method:ki,module:"share",capability:ki,requirement:{kind:"all",permissions:["share"]},risk:"medium"},{method:Ci,module:"share",capability:Ci,requirement:{kind:"all",permissions:["share"]},risk:"medium"},{method:Li,module:"viewport",capability:Li,requirement:{kind:"none"},risk:"low"},{method:Ui,module:"viewport",capability:Ui,requirement:{kind:"none"},risk:"low"},{method:nr,module:"viewport",capability:nr,requirement:{kind:"none"},risk:"low"},{method:En,module:"storage",capability:En,requirement:{kind:"all",permissions:["storage"]},risk:"low"},{method:wn,module:"storage",capability:wn,requirement:{kind:"all",permissions:["storage"]},risk:"medium"},{method:xi,module:"network",capability:xi,requirement:{kind:"all",permissions:["network"]},risk:"high"},{method:zi,module:"network",capability:zi,requirement:{kind:"all",permissions:["network","filesystem"]},risk:"high"},{method:ji,module:"network",capability:ji,requirement:{kind:"all",permissions:["network","filesystem"]},risk:"high"},{method:Bi,module:"files",capability:Bi,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Hi,module:"files",capability:Hi,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Fi,module:"files",capability:Fi,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:In,module:"file",capability:In,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:An,module:"file",capability:An,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Vi,module:"file",capability:Vi,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:_n,module:"file",capability:_n,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Gi,module:"file",capability:Gi,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Dn,module:"file",capability:Dn,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:$i,module:"file",capability:$i,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Nn,module:"file",capability:Nn,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:qi,module:"directory",capability:qi,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Mn,module:"directory",capability:Mn,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Qi,module:"directory",capability:Qi,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Yi,module:"directory",capability:Yi,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Sn,module:"media",capability:Sn,requirement:{kind:"all",permissions:["media"]},risk:"high"},{method:Wi,module:"ui",capability:Wi,requirement:{kind:"none"},risk:"low"},{method:Zi,module:"ui",capability:Zi,requirement:{kind:"none"},risk:"low"},{method:Ki,module:"ui",capability:Ki,requirement:{kind:"none"},risk:"low"},{method:Ji,module:"device",capability:Ji,requirement:{kind:"none"},risk:"low"},{method:Xi,module:"device",capability:Xi,requirement:{kind:"all",permissions:["clipboard"]},risk:"medium"},{method:eo,module:"device",capability:eo,requirement:{kind:"all",permissions:["appProtocol"]},risk:"high"},{method:to,module:"navigation",capability:to,requirement:{kind:"none"},risk:"medium"},{method:ro,module:"navigation",capability:ro,requirement:{kind:"none"},risk:"medium"},{method:no,module:"navigation",capability:no,requirement:{kind:"none"},risk:"medium"},{method:bt,module:"cloud",capability:bt,requirement:{kind:"all",permissions:["leaderboard"]},risk:"medium"},{method:at,module:"cloud",capability:at,requirement:{kind:"all",permissions:["leaderboard"]},risk:"low"},{method:xt,module:"cloud",capability:xt,requirement:{kind:"all",permissions:["leaderboard"]},risk:"medium"},{method:ir,module:"cloud",capability:ir,requirement:{kind:"all",permissions:["leaderboard"]},risk:"medium"},{method:wt,module:"cloud",capability:wt,requirement:{kind:"all",permissions:["leaderboard"]},risk:"low"},{method:vr,module:"cloud",capability:vr,requirement:{kind:"all",permissions:["cloud_storage"]},risk:"low"},{method:Or,module:"cloud",capability:Or,requirement:{kind:"all",permissions:["cloud_storage"]},risk:"medium"},{method:Rr,module:"cloud",capability:Rr,requirement:{kind:"all",permissions:["cloud_storage"]},risk:"medium"},{method:or,module:"cloud",capability:or,requirement:{kind:"all",permissions:["cloud_storage"]},risk:"low"},...[wo,Io,Ao,_o,Do,No,Mo,So,bo,To,vo,Oo].map(e=>({method:e,module:"companion",capability:e,requirement:{kind:"all",permissions:["companion"]},risk:"high"}))],$t="heybox:miniprogram",gl=2,pl="hb_mini_bridge_nonce",yl="sdk.handshake",Fn="runtime.location.probe",vm="sdk.location.report",Om="sdk.csp.violation",El="operation.progress",Rm="companion.session.output",Pm="companion.session.exit",km="companion.session.ownershipLost";function Cm(e){return!ut(e)||e.namespace!==$t||e.version!==1&&e.version!==2||!Pe(e.nonce)?!1:e.type==="handshake"?Pe(e.id)&&e.method===yl&&e.error===void 0&&Fm(e.payload):e.type==="request"?Pe(e.id)&&Pe(e.method)&&e.error===void 0:e.type==="response"?Pe(e.id)&&(e.method===void 0||Pe(e.method))&&(e.error===void 0||Vm(e.error)):e.type==="event"?!Pe(e.method)||e.error!==void 0?!1:e.method===El?e.version===2&&Pe(e.id)&&Hm(e.payload):e.id===void 0||Pe(e.id):e.type==="cancel"?e.version===2&&Pe(e.id)&&e.method===void 0&&e.payload===void 0&&e.error===void 0:!1}function Ba(e){return typeof e!="string"||!e||e.startsWith("/")||e.endsWith("/")||/[\\\u0000-\u001f\u007f]/.test(e)?!1:e.split("/").every(t=>!!t&&t!=="."&&t!=="..")}function wl(e){return ut(e)?e.kind==="sandbox"?rt(e,["kind"]):e.kind==="directory"&&Pe(e.handleId)&&rt(e,["kind","handleId"]):!1}function er(e){return!ut(e)||e.kind!=="file"?!1:Pe(e.handleId)?rt(e,["kind","handleId"]):wl(e.root)&&Ba(e.relativePath)&&rt(e,["kind","root","relativePath"])}function Il(e){return!ut(e)||e.kind!=="directory"?!1:Pe(e.handleId)?rt(e,["kind","handleId"]):wl(e.root)&&(e.relativePath==="."||Ba(e.relativePath))&&rt(e,["kind","root","relativePath"])}function Lm(e){return ut(e)&&e.kind==="file"&&Pe(e.name)&&Gm(e.mode)&&er(e.ref)&&rt(e,["kind","name","mode","ref"])}const Al=20,Mc=["type","mimeType","size","width","height","previewUrl","file"];function Um(e){return e===void 0?!0:!(!ut(e)||!rt(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&&(!$m(e.maxCount,1,Al)||e.source==="camera"&&e.maxCount!==1))}function _l(e){if(!ut(e)||e.type!=="image"&&e.type!=="video")return!1;const t=e.type==="video";return!rt(e,t?[...Mc,"durationMs"]:Mc)||!Pe(e.mimeType)||!Ct(e.size)||!Sc(e.width)||!Sc(e.height)||!Pe(e.previewUrl)||!zm(e.file)?!1:t?Ct(e.durationMs):!0}function xm(e){if(!Array.isArray(e)||e.length<1||e.length>Al)return!1;for(let t=0;t<e.length;t+=1)if(!Object.prototype.hasOwnProperty.call(e,t)||!_l(e[t]))return!1;return!0}function zm(e){return!Lm(e)||e.mode!=="read"?!1:e.ref.kind==="file"&&"handleId"in e.ref&&Pe(e.ref.handleId)}function Dl(e){return e instanceof Uint8Array&&e.buffer instanceof ArrayBuffer}function jm(e){return!ut(e)||!Ct(e.loaded)||typeof e.lengthComputable!="boolean"||!rt(e,["loaded","total","lengthComputable"])?!1:e.lengthComputable?Ct(e.total)&&e.loaded<=e.total:e.total===void 0}function Bm(e){return ut(e)?e.phase==="downloading"?Ct(e.loaded)&&(e.total===void 0||Ct(e.total)&&e.loaded<=e.total)&&rt(e,["phase","loaded","total"]):e.phase!=="verifying"&&e.phase!=="extracting"?!1:Ct(e.processed)&&Ct(e.total)&&e.processed<=e.total&&rt(e,["phase","processed","total"]):!1}function Hm(e){return jm(e)||Bm(e)}function Fm(e){return ut(e)&&Pe(e.href)&&typeof e.userAgent=="string"&&Pe(e.sdkVersion)}function Vm(e){return ut(e)&&Pe(e.code)&&typeof e.message=="string"}function Gm(e){return e==="read"||e==="readwrite"}function Ct(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function Sc(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>0}function $m(e,t,r){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=t&&e<=r}function Pe(e){return typeof e=="string"&&e.length>0}function rt(e,t){const r=new Set(t);return Object.keys(e).every(n=>r.has(n))}function ut(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const Nl={ark:"明日方舟",black_myth_wukong:"黑神话悟空",task_bar_hero:"任务栏英雄",phantom_blade_zero:"影之刃零"},Ml=Object.keys(Nl),tr=[{key:"game.ark.profile",game:"ark",family:"profile",name:"明日方舟角色与养成资料",disclosureRevision:1,queries:{get:{schema:"ark.profile",version:1}},sync:!1,file:!1},{key:"game.ark.gacha",game:"ark",family:"gacha",name:"明日方舟抽卡记录与分析",disclosureRevision:1,queries:{get:{schema:"ark.gacha-analysis",version:1},list:{schema:"ark.gacha-record-page",version:1,page:{defaultSize:50,maxSize:100}}},sync:!1,file:!1},{key:"game.black_myth_wukong.save_analysis",game:"black_myth_wukong",family:"save_analysis",name:"黑神话悟空存档解析结果",disclosureRevision:1,queries:{get:{schema:"black_myth_wukong.save",version:1}},sync:!0,file:!1},{key:"game.black_myth_wukong.save_files",game:"black_myth_wukong",family:"save_files",name:"黑神话悟空云存档文件",disclosureRevision:1,queries:{list:{schema:"save-file-page",version:1}},sync:!0,file:!0},{key:"game.task_bar_hero.save_analysis",game:"task_bar_hero",family:"save_analysis",name:"任务栏英雄存档解析结果",disclosureRevision:1,queries:{get:{schema:"task_bar_hero.save",version:1}},sync:!0,file:!1},{key:"game.task_bar_hero.save_files",game:"task_bar_hero",family:"save_files",name:"任务栏英雄云存档文件",disclosureRevision:1,queries:{list:{schema:"save-file-page",version:1}},sync:!0,file:!0},{key:"game.phantom_blade_zero.save_analysis",game:"phantom_blade_zero",family:"save_analysis",name:"影之刃零存档解析结果",disclosureRevision:1,queries:{get:{schema:"phantom_blade_zero.save",version:1}},sync:!0,file:!1},{key:"game.phantom_blade_zero.save_files",game:"phantom_blade_zero",family:"save_files",name:"影之刃零云存档文件",disclosureRevision:1,queries:{list:{schema:"save-file-page",version:1}},sync:!0,file:!0}],Wt=tr.map(e=>e.key),qm=new Set(Wt),Qm=new Set(Ml);function kt(e){return qm.has(e)}function bc(e){return Qm.has(e)}function Ha(e){const t=tr.find(i=>i.key===e);if(!t)return;const r=t.queries,n=Object.keys(r);return t.sync&&n.push("sync"),t.file&&n.push("file"),{key:t.key,game:t.game,name:t.name,family:t.family,disclosureRevision:t.disclosureRevision,queries:r,operations:n}}const Ym="同步时,原始存档将上传至小黑盒;向小程序提供原始文件仍需单独许可。",sr=["userInfo","steamLibrary","share","storage","cloud_storage","gameSaves","filesystem","media","clipboard","leaderboard","network","companion","appProtocol","workspaceCards","user_game_data"],Fa=[{key:"gameSaves",name:"游戏存档",description:"已废弃,将在 SDK 0.10.0 移除;新接入使用 user.games。",access:"declaration",risk:"high",config:{},methods:["gameSaves.list","gameSaves.sync","gameSaves.getFile","gameSaves.readParsedData"],conditions:["SDK < 0.10.0-0 保留兼容入口,保留原合同,不增加本版逐资源确认;需要有效 Steam 登录和宿主支持。"]},{key:"userInfo",name:"用户信息",description:"登录小程序并读取当前用户的授权信息。",access:"declaration",risk:"medium",config:{},methods:["auth.login","user.getInfo"],conditions:["继续执行黑盒登录、用户授权和可信手势规则。"]},{key:"steamLibrary",name:"Steam 游戏库",description:"读取当前用户授权的 Steam 游戏库。",access:"declaration",risk:"high",config:{},methods:["user.getSteamGameList"],conditions:["继续执行账号绑定和数据可用性规则。"]},{key:"share",name:"分享",description:"使用小程序分享、分享菜单和截图能力。",access:"declaration",risk:"medium",config:{},methods:["share.copyLink","share.showShareMenu","share.screenshot","share.screenshotLong"],conditions:["继续执行分享参数校验和 Host 支持检查。"]},{key:"storage",name:"键值存储",description:"读写按小程序隔离的简单键值数据。",access:"declaration",risk:"medium",config:{},methods:["storage.getStorage","storage.setStorage"],conditions:["仅用于简单键值存储,不包含文件系统。"]},{key:"cloud_storage",name:"云端存储",description:"读写按小程序和当前登录用户隔离的云端键值数据。",access:"declaration",risk:"medium",config:{},methods:["cloud.storage.getStorage","cloud.storage.setStorage","cloud.storage.removeItem","cloud.storage.getKeys"],conditions:["云端存储按登录用户隔离并受容量配额限制。"]},{key:"filesystem",name:"文件系统",description:"访问小程序沙盒文件和用户选择的外部文件。",access:"declaration",risk:"high",config:{},methods:["network.download","network.upload","files.pickFiles","files.pickDirectory","files.saveFile","file.create","file.remove","file.exists","file.readText","file.writeText","file.readBytes","file.writeBytes","file.stat","directory.create","directory.remove","directory.exists","directory.list"],conditions:["外部文件继续要求有效的用户选择、会话句柄和匹配的读写模式。"]},{key:"media",name:"媒体",description:"通过系统图库或相机选择图片、视频。",access:"declaration",risk:"high",config:{},methods:["media.pick"],conditions:["图库授权范围仅限本次用户选择的媒体,不包含任意文件或沙盒访问权;继续执行可信手势、Host 能力与会话资源规则。"]},{key:"clipboard",name:"剪贴板",description:"向系统剪贴板写入文本。",access:"declaration",risk:"medium",config:{},methods:["device.setClipboard"],conditions:["继续执行文本长度和 Host 支持限制。"]},{key:"leaderboard",name:"排行榜",description:"读写小程序云排行榜。",access:"declaration",risk:"medium",config:{},methods:["cloud.leaderboard.submit","cloud.leaderboard.getList","cloud.leaderboard.getCurrentUserEntry","cloud.leaderboard.deleteCurrentUserEntry","cloud.leaderboard.getInfo"],conditions:["排行榜必须已创建,用户和资源规则保持不变。"]},{key:"network",name:"网络",description:"通过 network 模块请求或下载外部资源。",access:"platform-approval",risk:"high",config:{useOfficialDomain:{type:"boolean",required:!1,default:!1,description:"是否申请访问小黑盒官方域名。"}},methods:["network.request","network.download","network.upload"],conditions:["声明后仍需平台批准,并继续执行网络安全策略。"]},{key:"companion",name:"桌面辅助应用",description:"下载、准备并运行随当前小程序版本发布的受管桌面程序。",access:"platform-approval",risk:"high",config:{},methods:["companion.getInfo","companion.getPreparationStatus","companion.prepare","companion.cancelPreparation","companion.getActiveSession","companion.launch","companion.session.write","companion.session.closeStdin","companion.session.terminate","companion.session.ackOutput","companion.openAttachment","companion.showNotification"],conditions:["声明后仍需平台批准,并继续执行可信用户手势、Host 能力和当前版本 Manifest 校验。"]},{key:"appProtocol",name:"应用协议执行",description:"执行任意小黑盒客户端协议。",access:"platform-approval",risk:"high",config:{},methods:["device.executeProtocol"],conditions:["最高危险权限:批准后该入口可执行任意协议,并绕过其他 SDK 能力权限及专用授权流程。"]},{key:"workspaceCards",name:"工作区卡片",description:"在已绑定游戏的桌面工作区展示受审核卡片。",access:"platform-approval",risk:"high",config:{},methods:["workspaceCards.requestRefresh"],conditions:["需平台批准、Host 支持与有效执行租约;不隐式授予网络或存储权限。"]},{key:"user_game_data",name:"游戏资料",description:"在精确资源声明范围内读取当前用户的游戏资料:明日方舟角色/养成与抽卡,以及黑神话悟空、任务栏英雄、影之刃零的云存档解析结果与文件。",access:"declaration",risk:"high",config:{resources:{type:"resource-map",required:!0,items:Wt,description:"精确资源声明对象;每项必须填写 1~30 个 Unicode 码点的 purpose,不接受通配符或未开放资源。"}},methods:ml,conditions:["逐项声明资源与用途,读取前需用户许可;未取得许可不查询个人来源。","文件与解析结果分别许可;本次许可仅当前实例有效,持久许可保存在本机。","同步会将原存档上传至小黑盒,向小程序交付原文件仍需 `save_files` 许可。","平台取数不授予小程序 `network` 权限;已交付的数据副本无法撤回。"]}];new Set(sr);const Wm=30;function Zm(e){if(typeof e!="string")throw new Error("purpose 必须是字符串");const t=e.trim(),r=Array.from(t);if(r.length<1||r.length>Wm)throw new Error("purpose 去除首尾空白后必须为 1~30 个 Unicode 码点");if(r.some(n=>{const i=n.codePointAt(0);return i>=55296&&i<=57343}))throw new Error("purpose 包含非法 Unicode 字符");return t}function bn(e){return Sl(e,!1)}function Km(e){return Sl(e,!0)}function Sl(e,t){if(!Tc(e))throw new Error("resources 必须是资源声明对象;每项资源必须填写 purpose");const r={};for(const n of Object.keys(e).sort()){const i=e[n];if(!Tc(i)||Object.keys(i).length!==1||!Object.prototype.hasOwnProperty.call(i,"purpose"))throw new Error(`resources.${n} 必须且只能包含 purpose`);let o;try{o=Zm(i.purpose)}catch(s){throw new Error(`resources.${n}: ${s.message}`)}if(!kt(n)){if(t&&/^game\.[a-z0-9_]+\.[a-z0-9_.]+$/.test(n))continue;throw new Error(`resources 包含未开放资源:${n}`)}r[n]={purpose:o}}return r}function Jm(e){return Wt.filter(t=>Object.prototype.hasOwnProperty.call(e,t))}function Tc(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function bl(e,t,r,n){return JSON.stringify(["user-game-data-purpose-v1",e,t,r,n])}const Xm=new Set(sr);function eg(e){return Xm.has(e)}function qe(e){if(!Yr(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(!Yr(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),!!eg(o)){if(o==="network"){const s=n.config;if(!Yr(s)||typeof s.useOfficialDomain!="boolean")return{valid:!1,permissions:{}};r[o]={key:o,status:n.status,config:{useOfficialDomain:s.useOfficialDomain}};continue}if(o==="user_game_data"){const s=n.config;if(!Yr(s))return{valid:!1,permissions:{}};try{const a=Km(s.resources);r[o]={key:o,status:n.status,config:{resources:a}}}catch{return{valid:!1,permissions:{}}}continue}if(n.config!==null&&n.config!==void 0&&(!Yr(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 Yr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const oi=["network","companion","appProtocol"];function Tl(e){if(!Wr(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>oi.length)return{valid:!1};const t=[],r=new Set;for(const n of e.entries){if(!Wr(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(!Wr(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(!Wr(n.config,[]))return{valid:!1};t.push({key:"companion",status:"enabled",config:{}})}else if(n.key==="appProtocol"){if(!Wr(n.config,[]))return{valid:!1};t.push({key:"appProtocol",status:"enabled",config:{}})}else return{valid:!1}}return t.sort((n,i)=>oi.indexOf(n.key)-oi.indexOf(i.key)),{valid:!0,grant:{schema_version:1,revision:e.revision,entries:t}}}function tg(e){if(!Number.isSafeInteger(e.revision)||e.revision<0)throw new Error("本地调试权限 revision 必须是非负安全整数");const t=qe(e.runtimePermissions),r=new Set(e.eligiblePermissionKeys??["network","appProtocol"]),n=[];for(const i of oi)!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 Va(e){const t=qe(e.runtimePermissions),r=Tl(e.localDevGrant),n=t.valid?t.permissions:{};for(const s of sr)e.declaredPermissions[s]?.enabled!==!0?delete n[s]:Fa.some(a=>a.key===s&&a.access==="declaration")?n[s]={key:s,status:"enabled",config:rg(s,e.declaredPermissions)}: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=vl(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:sr.flatMap(s=>n[s]?[n[s]]:[])},temporaryPermissionKeys:i,grantValid:r.valid}}function rg(e,t){const r=Fa.find(i=>i.key===e);if(!r)return{};const n={};for(const[i,o]of Object.entries(r.config))o.type==="resource-map"&&(n[i]=i==="resources"?bn(t[e]?.resources):{});return n}function vl(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Wr(e,t){return vl(e)&&Object.keys(e).length===t.length&&t.every(r=>Object.prototype.hasOwnProperty.call(e,r))}const Pr=["identity","profile","steam_account"],ng=/^[a-z][a-z0-9-]{0,31}$/,Ol=["COMPANION_UNSUPPORTED","COMPANION_PREVIEW_UNSUPPORTED","COMPANION_NOT_DECLARED","COMPANION_TARGET_UNSUPPORTED","COMPANION_NOT_PREPARED","COMPANION_PREPARATION_CANCELLED","COMPANION_DOWNLOAD_FAILED","COMPANION_DESCRIPTOR_UNAVAILABLE","COMPANION_ARCHIVE_INVALID","COMPANION_INTEGRITY_FAILED","COMPANION_ENTRYPOINT_INVALID","COMPANION_USER_CANCELLED","COMPANION_ELEVATION_DENIED","COMPANION_OS_BLOCKED","COMPANION_LAUNCH_FAILED","COMPANION_SESSION_VERSION_MISMATCH","COMPANION_SESSION_OWNERSHIP_LOST","COMPANION_SESSION_EXITED","COMPANION_PIPE_CLOSED","COMPANION_OUTPUT_LIMIT","COMPANION_PROCESS_CRASHED","COMPANION_ATTACHMENT_NOT_FOUND","COMPANION_NOTIFICATION_UNAVAILABLE","COMPANION_TERMINATE_FAILED"];var vc;function _e(e,t,r){function n(a,c){if(a._zod||Object.defineProperty(a,"_zod",{value:{def:c,constr:s,traits:new Set},enumerable:!1}),a._zod.traits.has(e))return;a._zod.traits.add(e),t(a,c);const d=s.prototype,u=Object.keys(d);for(let f=0;f<u.length;f++){const l=u[f];l in a||(a[l]=d[l].bind(a))}}const i=r?.Parent??Object;class o extends i{}Object.defineProperty(o,"name",{value:e});function s(a){var c;const d=r?.Parent?new o:this;n(d,a),(c=d._zod).deferred??(c.deferred=[]);for(const u of d._zod.deferred)u();return d}return Object.defineProperty(s,"init",{value:n}),Object.defineProperty(s,Symbol.hasInstance,{value:a=>r?.Parent&&a instanceof r.Parent?!0:a?._zod?.traits?.has(e)}),Object.defineProperty(s,"name",{value:e}),s}class ln extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}(vc=globalThis).__zod_globalConfig??(vc.__zod_globalConfig={});const Oc=globalThis.__zod_globalConfig;function Gr(e){return e&&Object.assign(Oc,e),Oc}function ig(e,t){return typeof t=="bigint"?t.toString():t}function og(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function Rl(e){const t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}const Rc=Symbol("evaluating");function Qe(e,t,r){let n;Object.defineProperty(e,t,{get(){if(n!==Rc)return n===void 0&&(n=Rc,n=r()),n},set(i){Object.defineProperty(e,t,{value:i})},configurable:!0})}const Pl="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function sg(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Pc(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function ag(e,t,r){const n=new e._zod.constr(t??e._zod.def);return(!t||r?.parent)&&(n._zod.parent=e),n}function it(e){return{}}function cg(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}const dg={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function sn(e,t=0){if(e.aborted===!0)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue!==!0)return!0;return!1}function ug(e,t=0){if(e.aborted===!0)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue===!1)return!0;return!1}function kl(e,t){return t.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(e),r})}function Vn(e){return typeof e=="string"?e:e?.message}function Cn(e,t,r){const n=e.message?e.message:Vn(e.inst?._zod.def?.error?.(e))??Vn(t?.error?.(e))??Vn(r.customError?.(e))??Vn(r.localeError?.(e))??"Invalid input",{inst:i,continue:o,input:s,...a}=e;return a.path??(a.path=[]),a.message=n,t?.reportInput&&(a.input=s),a}const Cl=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,ig,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},lg=_e("$ZodError",Cl),Ro=_e("$ZodError",Cl,{Parent:Error}),fg=e=>(t,r,n,i)=>{const o=n?{...n,async:!1}:{async:!1},s=t._zod.run({value:r,issues:[]},o);if(s instanceof Promise)throw new ln;if(s.issues.length){const a=new(i?.Err??e)(s.issues.map(c=>Cn(c,o,Gr())));throw Pl(a,i?.callee),a}return s.value},hg=fg(Ro),mg=e=>async(t,r,n,i)=>{const o=n?{...n,async:!0}:{async:!0};let s=t._zod.run({value:r,issues:[]},o);if(s instanceof Promise&&(s=await s),s.issues.length){const a=new(i?.Err??e)(s.issues.map(c=>Cn(c,o,Gr())));throw Pl(a,i?.callee),a}return s.value},gg=mg(Ro),pg=e=>(t,r,n)=>{const i=n?{...n,async:!1}:{async:!1},o=t._zod.run({value:r,issues:[]},i);if(o instanceof Promise)throw new ln;return o.issues.length?{success:!1,error:new(e??lg)(o.issues.map(s=>Cn(s,i,Gr())))}:{success:!0,data:o.value}},Ll=pg(Ro),yg=e=>async(t,r,n)=>{const i=n?{...n,async:!0}:{async:!0};let o=t._zod.run({value:r,issues:[]},i);return o instanceof Promise&&(o=await o),o.issues.length?{success:!1,error:new e(o.issues.map(s=>Cn(s,i,Gr())))}:{success:!0,data:o.value}},Ul=yg(Ro),Eg=e=>{const t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},wg=/^-?\d+$/,Ig=/^-?\d+(?:\.\d+)?$/,Ag=/^null$/i,Po=_e("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),xl={number:"number",bigint:"bigint",object:"date"},_g=_e("$ZodCheckLessThan",(e,t)=>{Po.init(e,t);const r=xl[typeof t.value];e._zod.onattach.push(n=>{const i=n._zod.bag,o=(t.inclusive?i.maximum:i.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<o&&(t.inclusive?i.maximum=t.value:i.exclusiveMaximum=t.value)}),e._zod.check=n=>{(t.inclusive?n.value<=t.value:n.value<t.value)||n.issues.push({origin:r,code:"too_big",maximum:typeof t.value=="object"?t.value.getTime():t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Dg=_e("$ZodCheckGreaterThan",(e,t)=>{Po.init(e,t);const r=xl[typeof t.value];e._zod.onattach.push(n=>{const i=n._zod.bag,o=(t.inclusive?i.minimum:i.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>o&&(t.inclusive?i.minimum=t.value:i.exclusiveMinimum=t.value)}),e._zod.check=n=>{(t.inclusive?n.value>=t.value:n.value>t.value)||n.issues.push({origin:r,code:"too_small",minimum:typeof t.value=="object"?t.value.getTime():t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Ng=_e("$ZodCheckNumberFormat",(e,t)=>{Po.init(e,t),t.format=t.format||"float64";const r=t.format?.includes("int"),n=r?"int":"number",[i,o]=dg[t.format];e._zod.onattach.push(s=>{const a=s._zod.bag;a.format=t.format,a.minimum=i,a.maximum=o,r&&(a.pattern=wg)}),e._zod.check=s=>{const a=s.value;if(r){if(!Number.isInteger(a)){s.issues.push({expected:n,format:t.format,code:"invalid_type",continue:!1,input:a,inst:e});return}if(!Number.isSafeInteger(a)){a>0?s.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,inclusive:!0,continue:!t.abort}):s.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,inclusive:!0,continue:!t.abort});return}}a<i&&s.issues.push({origin:"number",input:a,code:"too_small",minimum:i,inclusive:!0,inst:e,continue:!t.abort}),a>o&&s.issues.push({origin:"number",input:a,code:"too_big",maximum:o,inclusive:!0,inst:e,continue:!t.abort})}}),Mg=_e("$ZodCheckStringFormat",(e,t)=>{var r,n;Po.init(e,t),e._zod.onattach.push(i=>{const o=i._zod.bag;o.format=t.format,t.pattern&&(o.patterns??(o.patterns=new Set),o.patterns.add(t.pattern))}),t.pattern?(r=e._zod).check??(r.check=i=>{t.pattern.lastIndex=0,!t.pattern.test(i.value)&&i.issues.push({origin:"string",code:"invalid_format",format:t.format,input:i.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(n=e._zod).check??(n.check=()=>{})}),Sg=_e("$ZodCheckRegex",(e,t)=>{Mg.init(e,t),e._zod.check=r=>{t.pattern.lastIndex=0,!t.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),bg={major:4,minor:4,patch:3},lt=_e("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=bg;const n=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&n.unshift(e);for(const i of n)for(const o of i._zod.onattach)o(e);if(n.length===0)(r=e._zod).deferred??(r.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{const i=(s,a,c)=>{let d=sn(s),u;for(const f of a){if(f._zod.def.when){if(ug(s)||!f._zod.def.when(s))continue}else if(d)continue;const l=s.issues.length,h=f._zod.check(s);if(h instanceof Promise&&c?.async===!1)throw new ln;if(u||h instanceof Promise)u=(u??Promise.resolve()).then(async()=>{await h,s.issues.length!==l&&(d||(d=sn(s,l)))});else{if(s.issues.length===l)continue;d||(d=sn(s,l))}}return u?u.then(()=>s):s},o=(s,a,c)=>{if(sn(s))return s.aborted=!0,s;const d=i(a,n,c);if(d instanceof Promise){if(c.async===!1)throw new ln;return d.then(u=>e._zod.parse(u,c))}return e._zod.parse(d,c)};e._zod.run=(s,a)=>{if(a.skipChecks)return e._zod.parse(s,a);if(a.direction==="backward"){const d=e._zod.parse({value:s.value,issues:[]},{...a,skipChecks:!0});return d instanceof Promise?d.then(u=>o(u,s,a)):o(d,s,a)}const c=e._zod.parse(s,a);if(c instanceof Promise){if(a.async===!1)throw new ln;return c.then(d=>i(d,n,a))}return i(c,n,a)}}Qe(e,"~standard",()=>({validate:i=>{try{const o=Ll(e,i);return o.success?{value:o.data}:{issues:o.error?.issues}}catch{return Ul(e,i).then(s=>s.success?{value:s.data}:{issues:s.error?.issues})}},vendor:"zod",version:1}))}),Tg=_e("$ZodString",(e,t)=>{lt.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??Eg(e._zod.bag),e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=String(r.value)}catch{}return typeof r.value=="string"||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:e}),r}}),zl=_e("$ZodNumber",(e,t)=>{lt.init(e,t),e._zod.pattern=e._zod.bag.pattern??Ig,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=Number(r.value)}catch{}const i=r.value;if(typeof i=="number"&&!Number.isNaN(i)&&Number.isFinite(i))return r;const o=typeof i=="number"?Number.isNaN(i)?"NaN":Number.isFinite(i)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:i,inst:e,...o?{received:o}:{}}),r}}),vg=_e("$ZodNumberFormat",(e,t)=>{Ng.init(e,t),zl.init(e,t)}),Og=_e("$ZodNull",(e,t)=>{lt.init(e,t),e._zod.pattern=Ag,e._zod.values=new Set([null]),e._zod.parse=(r,n)=>{const i=r.value;return i===null||r.issues.push({expected:"null",code:"invalid_type",input:i,inst:e}),r}}),Rg=_e("$ZodNever",(e,t)=>{lt.init(e,t),e._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:e}),r)});function kc(e,t,r){e.issues.length&&t.issues.push(...kl(r,e.issues)),t.value[r]=e.value}const Pg=_e("$ZodArray",(e,t)=>{lt.init(e,t),e._zod.parse=(r,n)=>{const i=r.value;if(!Array.isArray(i))return r.issues.push({expected:"array",code:"invalid_type",input:i,inst:e}),r;r.value=Array(i.length);const o=[];for(let s=0;s<i.length;s++){const a=i[s],c=t.element._zod.run({value:a,issues:[]},n);c instanceof Promise?o.push(c.then(d=>kc(d,r,s))):kc(c,r,s)}return o.length?Promise.all(o).then(()=>r):r}});function io(e,t,r,n,i,o){const s=r in n;if(e.issues.length){if(i&&o&&!s)return;t.issues.push(...kl(r,e.issues))}if(!s&&!i){e.issues.length||t.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[r]});return}e.value===void 0?s&&(t.value[r]=void 0):t.value[r]=e.value}function kg(e){const t=Object.keys(e.shape);for(const n of t)if(!e.shape?.[n]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${n}": expected a Zod schema`);const r=cg(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(r)}}function Cg(e,t,r,n,i,o){const s=[],a=i.keySet,c=i.catchall._zod,d=c.def.type,u=c.optin==="optional",f=c.optout==="optional";for(const l in t){if(l==="__proto__"||a.has(l))continue;if(d==="never"){s.push(l);continue}const h=c.run({value:t[l],issues:[]},n);h instanceof Promise?e.push(h.then(m=>io(m,r,l,t,u,f))):io(h,r,l,t,u,f)}return s.length&&r.issues.push({code:"unrecognized_keys",keys:s,input:t,inst:o}),e.length?Promise.all(e).then(()=>r):r}const Lg=_e("$ZodObject",(e,t)=>{if(lt.init(e,t),!Object.getOwnPropertyDescriptor(t,"shape")?.get){const a=t.shape;Object.defineProperty(t,"shape",{get:()=>{const c={...a};return Object.defineProperty(t,"shape",{value:c}),c}})}const n=og(()=>kg(t));Qe(e._zod,"propValues",()=>{const a=t.shape,c={};for(const d in a){const u=a[d]._zod;if(u.values){c[d]??(c[d]=new Set);for(const f of u.values)c[d].add(f)}}return c});const i=sg,o=t.catchall;let s;e._zod.parse=(a,c)=>{s??(s=n.value);const d=a.value;if(!i(d))return a.issues.push({expected:"object",code:"invalid_type",input:d,inst:e}),a;a.value={};const u=[],f=s.shape;for(const l of s.keys){const h=f[l],m=h._zod.optin==="optional",E=h._zod.optout==="optional",_=h._zod.run({value:d[l],issues:[]},c);_ instanceof Promise?u.push(_.then(w=>io(w,a,l,d,m,E))):io(_,a,l,d,m,E)}return o?Cg(u,d,a,c,n.value,e):u.length?Promise.all(u).then(()=>a):a}});function Cc(e,t,r,n){for(const o of e)if(o.issues.length===0)return t.value=o.value,t;const i=e.filter(o=>!sn(o));return i.length===1?(t.value=i[0].value,i[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:e.map(o=>o.issues.map(s=>Cn(s,n,Gr())))}),t)}const Ug=_e("$ZodUnion",(e,t)=>{lt.init(e,t),Qe(e._zod,"optin",()=>t.options.some(n=>n._zod.optin==="optional")?"optional":void 0),Qe(e._zod,"optout",()=>t.options.some(n=>n._zod.optout==="optional")?"optional":void 0),Qe(e._zod,"values",()=>{if(t.options.every(n=>n._zod.values))return new Set(t.options.flatMap(n=>Array.from(n._zod.values)))}),Qe(e._zod,"pattern",()=>{if(t.options.every(n=>n._zod.pattern)){const n=t.options.map(i=>i._zod.pattern);return new RegExp(`^(${n.map(i=>Rl(i.source)).join("|")})$`)}});const r=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(n,i)=>{if(r)return r(n,i);let o=!1;const s=[];for(const a of t.options){const c=a._zod.run({value:n.value,issues:[]},i);if(c instanceof Promise)s.push(c),o=!0;else{if(c.issues.length===0)return c;s.push(c)}}return o?Promise.all(s).then(a=>Cc(a,n,e,i)):Cc(s,n,e,i)}}),xg=_e("$ZodLiteral",(e,t)=>{if(lt.init(e,t),t.values.length===0)throw new Error("Cannot create literal schema with no valid values");const r=new Set(t.values);e._zod.values=r,e._zod.pattern=new RegExp(`^(${t.values.map(n=>typeof n=="string"?Pc(n):n?Pc(n.toString()):String(n)).join("|")})$`),e._zod.parse=(n,i)=>{const o=n.value;return r.has(o)||n.issues.push({code:"invalid_value",values:t.values,input:o,inst:e}),n}});function Lc(e,t){return t===void 0&&(e.issues.length||e.fallback)?{issues:[],value:void 0}:e}const zg=_e("$ZodOptional",(e,t)=>{lt.init(e,t),e._zod.optin="optional",e._zod.optout="optional",Qe(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),Qe(e._zod,"pattern",()=>{const r=t.innerType._zod.pattern;return r?new RegExp(`^(${Rl(r.source)})?$`):void 0}),e._zod.parse=(r,n)=>{if(t.innerType._zod.optin==="optional"){const i=r.value,o=t.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>Lc(s,i)):Lc(o,i)}return r.value===void 0?r:t.innerType._zod.run(r,n)}}),jg=_e("$ZodLazy",(e,t)=>{lt.init(e,t),Qe(e._zod,"innerType",()=>{const r=t;return r._cachedInner||(r._cachedInner=t.getter()),r._cachedInner}),Qe(e._zod,"pattern",()=>e._zod.innerType?._zod?.pattern),Qe(e._zod,"propValues",()=>e._zod.innerType?._zod?.propValues),Qe(e._zod,"optin",()=>e._zod.innerType?._zod?.optin??void 0),Qe(e._zod,"optout",()=>e._zod.innerType?._zod?.optout??void 0),e._zod.parse=(r,n)=>e._zod.innerType._zod.run(r,n)});function Bg(e,t){return new e({type:"string",...it()})}function Hg(e,t){return new e({type:"number",checks:[],...it()})}function Fg(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...it()})}function Vg(e,t){return new e({type:"null",...it()})}function Gg(e,t){return new e({type:"never",...it()})}function se(e,t){return new _g({check:"less_than",...it(),value:e,inclusive:!0})}function ae(e,t){return new Dg({check:"greater_than",...it(),value:e,inclusive:!0})}function ce(e,t){return new Sg({check:"string_format",format:"regex",...it(),pattern:e})}Gr({jitless:!0});function jl(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 sr){const n=e.declared_permissions[r];if(n){if(typeof n.enabled!="boolean")throw new Error("开发权限声明无效");if(r==="network"){t[r]={enabled:n.enabled,useOfficialDomain:n.useOfficialDomain===!0};continue}if(r==="user_game_data"){t[r]={enabled:n.enabled,resources:bn(n.resources)};continue}t[r]={enabled:n.enabled}}}if(Object.keys(e.declared_permissions).some(r=>!sr.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 $g(e){if(!(typeof e!="string"||e.length>16384))try{const t=JSON.parse(e);return jl(t)===e?t:void 0}catch{return}}const Dt=_e("ZodMiniType",(e,t)=>{if(!e._zod)throw new Error("Uninitialized schema in ZodMiniType.");lt.init(e,t),e.def=t,e.type=t.type,e.parse=(r,n)=>hg(e,r,n,{callee:e.parse}),e.safeParse=(r,n)=>Ll(e,r,n),e.parseAsync=async(r,n)=>gg(e,r,n,{callee:e.parseAsync}),e.safeParseAsync=async(r,n)=>Ul(e,r,n),e.check=(...r)=>e.clone({...t,checks:[...t.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]},{parent:!0}),e.with=e.check,e.clone=(r,n)=>ag(e,r,n),e.brand=()=>e,e.register=((r,n)=>(r.add(e,n),e)),e.apply=r=>r(e)}),qg=_e("ZodMiniString",(e,t)=>{Tg.init(e,t),Dt.init(e,t)});function P(e){return Bg(qg)}const Bl=_e("ZodMiniNumber",(e,t)=>{zl.init(e,t),Dt.init(e,t)});function V(e){return Hg(Bl)}const Qg=_e("ZodMiniNumberFormat",(e,t)=>{vg.init(e,t),Bl.init(e,t)});function de(e){return Fg(Qg)}const Yg=_e("ZodMiniNull",(e,t)=>{Og.init(e,t),Dt.init(e,t)});function te(e){return Vg(Yg)}const Wg=_e("ZodMiniNever",(e,t)=>{Rg.init(e,t),Dt.init(e,t)});function Zg(e){return Gg(Wg)}const Kg=_e("ZodMiniArray",(e,t)=>{Pg.init(e,t),Dt.init(e,t)});function J(e,t){return new Kg({type:"array",element:e,...it()})}const Jg=_e("ZodMiniObject",(e,t)=>{Lg.init(e,t),Dt.init(e,t),Qe(e,"shape",()=>t.shape)});function oe(e,t){return new Jg({type:"object",shape:e,catchall:Zg(),...it()})}const Xg=_e("ZodMiniUnion",(e,t)=>{Ug.init(e,t),Dt.init(e,t)});function R(e,t){return new Xg({type:"union",options:e,...it()})}const ep=_e("ZodMiniLiteral",(e,t)=>{xg.init(e,t),Dt.init(e,t)});function le(e,t){return new ep({type:"literal",values:Array.isArray(e)?e:[e],...it()})}const tp=_e("ZodMiniOptional",(e,t)=>{zg.init(e,t),Dt.init(e,t)});function G(e){return new tp({type:"optional",innerType:e})}const rp=_e("ZodMiniLazy",(e,t)=>{jg.init(e,t),Dt.init(e,t)});function Y(e){return new rp({type:"lazy",getter:e})}const W={ArkProfile:oe({uid:P(),name:P(),level:V(),avatar:G(Y(()=>W.ArkPlayerAvatar)),characterCount:V(),totalCharacterCount:V(),mainStageProgress:P(),rogueLevel:V(),campaignFullKillCount:V(),tag:P(),observedAt:G(R([P(),V()])),lastOnlineTs:G(R([P(),V()])),registerTs:G(R([P(),V()])),changeTime:G(R([P(),V()])),operators:G(J(Y(()=>W.ArkOperator)))}),ArkPlayerAvatar:oe({url:P(),type:P(),id:P()}),ArkOperator:oe({characterId:P(),name:P(),profession:P(),evolvePhase:V(),potentialRank:V()}),ArkGachaAnalysis:oe({uid:P(),year:V(),total:V(),srCount:V(),upCount:V(),missCount:V(),careerEvaluation:P(),careerIsLucky:R([le(!1),le(!0)]),pools:J(Y(()=>W.ArkGachaPoolStat)),records:J(Y(()=>W.ArkGachaAnalysisRecord)),luckyLottery:J(V())}),ArkGachaPoolStat:oe({poolId:P(),totalCost:V(),ssrCount:V(),ssrCost:V(),records:J(Y(()=>W.ArkGachaAnalysisRecord))}),ArkGachaAnalysisRecord:oe({name:P(),timestamp:R([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),diff:V(),negativeDiff:V(),tag:P(),missUp:R([le(!1),le(!0)])}),GachaRecord:oe({id:P(),name:P(),pool:P(),rarity:V(),timestamp:R([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))])}),BlackMythWukongSave:oe({level:G(V()),newGamePlusCount:G(V()),gameTotalTime:G(V()),playerDeathCount:G(V()),totalMoney:G(P()),meditationList:G(R([te(),J(V())])),monsterCollectionList:G(R([te(),J(V())])),returnPointList:G(R([te(),J(V())])),activatedWeaponIdList:G(R([te(),J(P())])),activatedEquipIdList:G(R([te(),J(V())])),magicArtifactList:G(R([te(),J(V())])),soulSkillIdList:G(R([te(),J(V())])),huluIdLits:G(R([te(),J(V())])),wineIdList:G(R([te(),J(V())])),wineIdPartnerList:G(R([te(),J(V())])),cropIdList:G(R([te(),J(V())])),recipeIdList:G(R([te(),J(V())])),wearedWaeponId:G(P()),wearedMagicArtifact:G(V()),wearedSoulSkill:G(V()),wearedHead:G(V()),wearedUpware:G(V()),wearedArm:G(V()),wearedFoot:G(V()),wearedHulu:G(V()),wearedAccessoryList:G(R([te(),J(V())])),spellQishu:G(R([te(),J(V())])),spellShenfa:G(R([te(),J(V())])),spellHaomao:G(R([te(),J(V())])),spellBianshen:G(R([te(),J(V())])),bossRushBossgroup:G(Y(()=>W.BlackMythWukongBossRushData)),bossRushRefight:G(Y(()=>W.BlackMythWukongBossRefightData))}),BlackMythWukongBossRushData:oe({bossGroups:G(R([te(),J(Y(()=>W.BlackMythWukongBossRushRecord))]))}),BlackMythWukongBossRushRecord:oe({bossGroupId:G(V()),isPassed:G(R([le(!1),le(!0)])),bestRecords:G(R([te(),J(Y(()=>W.BlackMythWukongBattleRecord))])),encounterBossIndex:G(V()),battleCount:G(V())}),BlackMythWukongBattleRecord:oe({battleId:G(P()),battleData:G(Y(()=>W.BlackMythWukongBattleData))}),BlackMythWukongBattleData:oe({totalTime:G(V()),score:G(V()),debuffList:G(R([te(),J(V())])),targetId:G(V()),archiveTime:G(P()),roleBase:G(Y(()=>W.BlackMythWukongRoleBase)),battleStyleInfo:G(Y(()=>W.BlackMythWukongBattleStyleInfo)),damageInfo:G(Y(()=>W.BlackMythWukongDamageInfo))}),BlackMythWukongRoleBase:oe({level:G(V()),atk:G(V()),hpMax:G(V()),staminaMax:G(V()),mpMax:G(V())}),BlackMythWukongBattleStyleInfo:oe({spellList:G(R([te(),J(Y(()=>W.BlackMythWukongCast))])),fabaoInfo:G(Y(()=>W.BlackMythWukongCast)),soulInfo:G(Y(()=>W.BlackMythWukongCast)),itemCount:G(V()),wineCount:G(V()),rollCount:G(V()),defuseCount:G(V()),fourPeCount:G(V())}),BlackMythWukongCast:oe({castId:G(V()),castCount:G(V())}),BlackMythWukongDamageInfo:oe({totalDamage:G(R([P(),V()])),hightestDamage:G(R([P(),V()])),criticalDmgRate:G(V()),totalBeDamaged:G(R([P(),V()])),criticalDmgTotal:G(R([P(),V()])),elemDotDmgTotal:G(R([P(),V()])),elemDotDmgRate:G(V())}),BlackMythWukongBossRefightData:oe({bossList:G(R([te(),J(Y(()=>W.BlackMythWukongBossRefightRecord))]))}),BlackMythWukongBossRefightRecord:oe({bossId:G(V()),passedMaxLevel:G(V()),lastChallengeLevel:G(V()),bestRecords:G(R([te(),J(Y(()=>W.BlackMythWukongBattleRecord))])),refightStatisticsList:G(R([te(),J(Y(()=>W.BlackMythWukongRefightStatistic))]))}),BlackMythWukongRefightStatistic:oe({challengeLevel:G(V()),battleCount:G(V())}),TaskBarHeroSave:oe({update_time:R([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),game_version:P(),account_version:P(),play_time:V(),last_saved_time:P(),common:Y(()=>W.TaskBarHeroCommon),summary:Y(()=>W.TaskBarHeroSummary),heroes:R([te(),J(Y(()=>W.TaskBarHeroHero))]),rune_save_data:R([te(),J(Y(()=>W.TaskBarHeroRune))]),pets:R([te(),J(Y(()=>W.TaskBarHeroPet))]),attributes:R([te(),J(Y(()=>W.TaskBarHeroAttribute))]),inventory_slots:R([te(),J(Y(()=>W.TaskBarHeroItemSlot))]),stash_slots:R([te(),J(Y(()=>W.TaskBarHeroItemSlot))]),item_instances:R([te(),J(Y(()=>W.TaskBarHeroItemInstance))]),values:Y(()=>W.TaskBarHeroValueSummary)}),TaskBarHeroCommon:oe({max_completed_stage:R([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),current_stage_key:R([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),current_stage_wave:R([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),arranged_hero_keys:R([te(),J(R([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]))]),arranged_pet_key:R([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))])}),TaskBarHeroSummary:oe({max_hero_level:R([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),learned_rune_count:R([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),unlocked_hero:R([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),total_hero:R([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),item_count:R([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),inventory_slots:R([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),stash_slots:R([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))])}),TaskBarHeroHero:oe({hero_key:R([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),hero_level:R([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),is_unlock:R([le(!1),le(!0)]),hero_exp:V(),ability_point:R([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),allocated_hero_ability_point:R([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),equipped_item_ids:R([te(),J(P())]),equipped_skill_keys:R([te(),J(R([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]))]),unlocked_attribute_group_keys:R([te(),J(R([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]))])}),TaskBarHeroRune:oe({rune_key:R([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),level:R([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))])}),TaskBarHeroPet:oe({pet_key:R([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),is_unlock:R([le(!1),le(!0)])}),TaskBarHeroAttribute:oe({key:R([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),level:R([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))])}),TaskBarHeroItemSlot:oe({index:R([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),item_unique_id:P(),is_unlock:R([le(!1),le(!0)]),is_unlocked_by_rune:R([le(!1),le(!0)])}),TaskBarHeroItemInstance:oe({item_key:R([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),unique_id:P(),is_chaotic:R([le(!1),le(!0)]),is_blocked:R([le(!1),le(!0)]),is_server_pending_item:R([le(!1),le(!0)]),enchant_count:R([te(),J(R([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]))]),enchant_data:R([te(),J(Y(()=>W.TaskBarHeroEnchantData))]),item_get_source_type:R([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),decoration_applied_total_count:R([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),engraving_applied_total_count:R([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),inscription_applied_total_count:R([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))])}),TaskBarHeroEnchantData:oe({stat_mod_key:R([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),tier:R([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),value:V(),recipe_type:R([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),mod_type:R([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),material_key:R([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),stat_type:R([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))])}),TaskBarHeroValueSummary:oe({market_value:R([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),price_state:P(),currency:P()}),PhantomBladeZeroSave:oe({defaultSlot:P(),slots:J(Y(()=>W.PhantomBladeZeroSaveSlot))}),PhantomBladeZeroSaveSlot:oe({slot:P(),head:Y(()=>W.PhantomBladeZeroSlotHead),firstClear:Y(()=>W.PhantomBladeZeroSlotFirstClear),progress:Y(()=>W.PhantomBladeZeroSlotProgress),combat:Y(()=>W.PhantomBladeZeroSlotCombat),achievements:Y(()=>W.PhantomBladeZeroSlotAchievementSummary),bosses:Y(()=>W.PhantomBladeZeroSlotBossSummary),collectibles:Y(()=>W.PhantomBladeZeroSlotCollectibles),quest_details:R([te(),Y(()=>W.PhantomBladeZeroQuestDetails)]),inventory_details:R([te(),J(Y(()=>W.PhantomBladeZeroInventoryItem))]),detail:Y(()=>W.PhantomBladeZeroSlotDetail)}),PhantomBladeZeroSlotHead:oe({saveTime:P(),currentLevel:P(),cycle:P(),difficulty:Y(()=>W.PhantomBladeZeroSlotDifficulty)}),PhantomBladeZeroSlotDifficulty:oe({raw:V(),name:P()}),PhantomBladeZeroSlotFirstClear:oe({clearDate:Y(()=>W.PhantomBladeZeroUnavailableValue),cycles:R([te(),J(Y(()=>W.PhantomBladeZeroClearanceRecord))])}),PhantomBladeZeroUnavailableValue:oe({value:te(),reason:P()}),PhantomBladeZeroClearanceRecord:oe({Cycle:G(R([te(),V()])),Ending:V(),Difficulty:V(),GameTime:R([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),Completion:V(),DiedTimes:R([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))])}),PhantomBladeZeroSlotProgress:oe({playTimeSeconds:R([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),playTime:P(),lastLaunch:Y(()=>W.PhantomBladeZeroUnavailableValue),narrativePercentage:V(),chapter:P(),remainingDays:R([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))])}),PhantomBladeZeroSlotCombat:oe({loadout:G(Y(()=>W.PhantomBladeZeroSlotLoadout)),totalDeaths:R([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),cycleDeaths:R([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),bossKillTotal:R([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),currentMainWeapon:G(R([te(),Y(()=>W.PhantomBladeZeroNamedItem)])),mainWeapon:Y(()=>W.PhantomBladeZeroCollectionCount),currentShaqi:G(R([te(),Y(()=>W.PhantomBladeZeroNamedItem)])),shaqi:Y(()=>W.PhantomBladeZeroCollectionCount)}),PhantomBladeZeroSlotLoadout:oe({states:G(R([te(),J(Y(()=>W.PhantomBladeZeroLoadoutState))])),main_weapons:R([te(),J(P())]),shaqi_weapons:R([te(),J(P())]),accessory_ids:R([te(),J(P())]),top_medicine:P(),bottom_medicine:P(),current_weapon_index:V(),current_shaqi_weapon_index:V()}),PhantomBladeZeroLoadoutState:oe({category:P(),id:P(),level:G(V()),soul_forged:G(R([le(!1),le(!0)])),reincarnation_count:G(V())}),PhantomBladeZeroNamedItem:oe({id:P(),name:P()}),PhantomBladeZeroCollectionCount:oe({unknown:G(R([P(),V()])),done:R([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),total:R([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))])}),PhantomBladeZeroSlotAchievementSummary:oe({unlocked:R([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),total:R([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),reason:P()}),PhantomBladeZeroSlotBossSummary:oe({groups:R([te(),J(Y(()=>W.PhantomBladeZeroBossGroup))])}),PhantomBladeZeroBossGroup:oe({map:P(),mapName:P(),count:R([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),bosses:R([te(),J(Y(()=>W.PhantomBladeZeroBoss))])}),PhantomBladeZeroBoss:oe({id:P(),classPath:P(),map:P(),mapName:P(),encountered:R([le(!1),le(!0)]),killed:R([le(!1),le(!0)]),kill:R([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),attempt:R([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),bestTimeMs:R([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),records:R([te(),J(Y(()=>W.PhantomBladeZeroBossRecord))])}),PhantomBladeZeroBossRecord:oe({cycle:P(),diff:P(),diffName:P(),kill:R([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),attempt:R([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),bestTimeMs:R([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))])}),PhantomBladeZeroSlotCollectibles:oe({overall:Y(()=>W.PhantomBladeZeroCollectionSummary),craneBellCount:R([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),byBigMap:R([te(),J(Y(()=>W.PhantomBladeZeroBigMapProgress))]),currentChapter:Y(()=>W.PhantomBladeZeroChapterProgress)}),PhantomBladeZeroCollectionSummary:oe({bell:Y(()=>W.PhantomBladeZeroCollectionCount),weapon:Y(()=>W.PhantomBladeZeroCollectionCount),shaqi:Y(()=>W.PhantomBladeZeroCollectionCount),accessory:Y(()=>W.PhantomBladeZeroCollectionCount),medicine:Y(()=>W.PhantomBladeZeroCollectionCount),challenge:Y(()=>W.PhantomBladeZeroCollectionCount),hupo:Y(()=>W.PhantomBladeZeroCollectionCount),heishi:Y(()=>W.PhantomBladeZeroCollectionCount),flower:Y(()=>W.PhantomBladeZeroCollectionCount)}),PhantomBladeZeroBigMapProgress:oe({unknown:G(R([P(),V()])),mapID:P(),name:P(),pct:V(),done:R([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),total:R([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),subMaps:R([te(),J(P())])}),PhantomBladeZeroChapterProgress:oe({unknown:G(R([P(),V()])),mapID:P(),pct:V(),done:R([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),total:R([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),reason:P()}),PhantomBladeZeroQuestDetails:oe({CurrentMainQuestPath:P(),CurrentTutorialQuestPath:P(),TrackedQuestPath:P(),TrackedBranchID:P(),TrackedTaskPointID:P(),ManualTrackingOptOut:R([le(!1),le(!0)]),NarrativeSavedQuests:R([te(),J(Y(()=>W.PhantomBladeZeroQuest))])}),PhantomBladeZeroQuest:oe({QuestClass:P(),QuestCompletion:P(),QuestBranches:R([te(),J(Y(()=>W.PhantomBladeZeroQuestBranch))]),CompletedBranches:R([te(),J(P())]),ReachedStateNames:R([te(),J(P())])}),PhantomBladeZeroQuestBranch:oe({BranchID:P(),TasksProgress:R([te(),J(R([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]))]),BranchType:P()}),PhantomBladeZeroInventoryItem:oe({id:P(),amount:R([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))])}),PhantomBladeZeroSlotDetail:oe({bell:R([te(),J(Y(()=>W.PhantomBladeZeroBellDetail))]),weapon:R([te(),J(Y(()=>W.PhantomBladeZeroItemDetail))]),shaqi:R([te(),J(Y(()=>W.PhantomBladeZeroItemDetail))]),accessory:R([te(),J(Y(()=>W.PhantomBladeZeroItemDetail))]),medicine:R([te(),J(Y(()=>W.PhantomBladeZeroItemDetail))]),challenge:R([te(),J(Y(()=>W.PhantomBladeZeroChallengeDetail))]),hupo:R([te(),J(Y(()=>W.PhantomBladeZeroWorldItemDetail))]),heishi:R([te(),J(Y(()=>W.PhantomBladeZeroWorldItemDetail))]),flower:R([te(),J(Y(()=>W.PhantomBladeZeroItemDetail))]),achievements:R([te(),J(Y(()=>W.PhantomBladeZeroAchievementDetail))])}),PhantomBladeZeroBellDetail:oe({unknown:G(R([le(!1),le(!0)])),id:P(),done:R([le(!1),le(!0)]),equip:R([le(!1),le(!0)])}),PhantomBladeZeroItemDetail:oe({level:G(V()),soul_forged:G(R([le(!1),le(!0)])),reincarnation_count:G(V()),unknown:G(R([le(!1),le(!0)])),id:P(),name:P(),done:R([le(!1),le(!0)]),equip:R([le(!1),le(!0)]),locs:R([te(),J(Y(()=>W.PhantomBladeZeroLocation))])}),PhantomBladeZeroLocation:oe({map:P(),mapName:P(),x:V(),y:V(),z:V()}),PhantomBladeZeroChallengeDetail:oe({key:G(P()),unknown:G(R([le(!1),le(!0)])),index:R([de().check(ae(-9007199254740991),se(9007199254740991)),P().check(ce(new RegExp("^-?(0|[1-9][0-9]*)$")))]),guids:R([te(),J(P())]),done:R([le(!1),le(!0)]),locs:R([te(),J(Y(()=>W.PhantomBladeZeroLocation))])}),PhantomBladeZeroWorldItemDetail:oe({key:G(P()),unknown:G(R([le(!1),le(!0)])),id:P(),saveGuid:P(),mobDomain:P(),done:R([le(!1),le(!0)]),locs:R([te(),J(Y(()=>W.PhantomBladeZeroLocation))])}),PhantomBladeZeroAchievementDetail:oe({id:P(),name:P(),desc:P(),grade:P(),hidden:R([le(!1),le(!0)]),done:R([le(!1),le(!0)])}),UserGameDataSaveFilePage:oe({items:J(Y(()=>W.UserGameDataSaveInfo)),hasMore:le(!1)}),UserGameDataSaveInfo:oe({saveId:P(),createdAt:P(),files:J(Y(()=>W.UserGameDataSaveFileInfo))}),UserGameDataSaveFileInfo:oe({fileId:P(),name:P(),sizeBytes:V(),modifiedAt:P()})},np=new Map([["ark.profile",Y(()=>W.ArkProfile)],["ark.gacha-analysis",Y(()=>W.ArkGachaAnalysis)],["ark.gacha-record-page",oe({items:J(Y(()=>W.GachaRecord)),nextCursor:G(P()),hasMore:R([le(!1),le(!0)]),total:G(V())})],["black_myth_wukong.save",Y(()=>W.BlackMythWukongSave)],["task_bar_hero.save",Y(()=>W.TaskBarHeroSave)],["phantom_blade_zero.save",Y(()=>W.PhantomBladeZeroSave)],["save-file-page",Y(()=>W.UserGameDataSaveFilePage)]]);function ip(e,t){return np.get(e)?.safeParse(t).success??!1}zt.map(e=>e.method);function si(){const e=new Error("The operation was aborted");return e.name="AbortError",e}function pe(e,t={}){if(e.aborted)throw t.preserveReason?e.reason===void 0?new DOMException("存储操作已取消","AbortError"):e.reason:si()}function Hl(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 Fl="METHOD_FORBIDDEN";function tt(e){const t=new Error(`小程序能力已禁用: ${e}`);return t.name="MethodForbiddenError",t.code=Fl,t}class Le 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 op=/^[A-Za-z0-9_-]{1,64}$/,Uc=1e3;function Vl(e){return op.test(e)?e:dp(e)}function sp(e){return`id_${Vl(e.trim())}`}function fr(e,t){return`hb_miniprogram_${e}_${t}`}function Gn(e){return`hb_miniprogram_keys_${e}`}const ap="hb_user_game_data_consent_";function cp(e){return`${ap}${e}`}function dp(e){let t=2166136261;for(let r=0;r<e.length;r+=1)t^=e.charCodeAt(r),t=Math.imul(t,16777619);return(t>>>0).toString(36)}const up=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 Ga(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 _=0;_<16;_+=1)o[_]=s.getUint32(a+_*4,!1);for(let _=16;_<64;_+=1){const w=o[_-15],S=o[_-2],p=ft(w,7)^ft(w,18)^w>>>3,M=ft(S,17)^ft(S,19)^S>>>10;o[_]=o[_-16]+p+o[_-7]+M>>>0}let[c,d,u,f,l,h,m,E]=i;for(let _=0;_<64;_+=1){const w=E+(ft(l,6)^ft(l,11)^ft(l,25))+(l&h^~l&m)+up[_]+o[_]>>>0,S=(ft(c,2)^ft(c,13)^ft(c,22))+(c&d^c&u^d&u);E=m,m=h,h=l,l=f+w>>>0,f=u,u=d,d=c,c=w+S>>>0}[c,d,u,f,l,h,m,E].forEach((_,w)=>{i[w]=i[w]+_>>>0})}return Array.from(i,a=>a.toString(16).padStart(8,"0")).join("")}function ft(e,t){return e>>>t|e<<32-t}const lp=Object.freeze({upload:"你允许读取的数据可能会被上传至开发者服务器。",no_network:"此小程序未获准将你允许读取的数据上传至开发者服务器。"});function fp(e){if(e===void 0||e==="")return;let t;try{t=JSON.parse(e)}catch{return}if(typeof t!="object"||t===null||Array.isArray(t))return;const r=t;if(r.schema_version!==1||typeof r.records!="object"||r.records===null||Array.isArray(r.records))return;const n={};for(const[i,o]of Object.entries(r.records)){if(typeof o!="object"||o===null||Array.isArray(o))return;const s=o;if(s.decision!=="ask"&&s.decision!=="allow"&&s.decision!=="deny"||typeof s.revision!="number"||!Number.isSafeInteger(s.revision)||s.revision<1||s.consentFingerprint!==void 0&&!gp(s.consentFingerprint))return;n[i]={decision:s.decision,revision:s.revision,...s.decision==="allow"&&s.consentFingerprint!==void 0?{consentFingerprint:s.consentFingerprint}:{}}}return{schema_version:1,records:n}}function hp(e){return Ga(`${e.miniProgramId}\0${e.userId}\0${e.environment}`).slice(0,32)}function mp(e){const t=e.miniProgramId?.trim(),r=e.userId?.trim(),n=e.environment?.trim();if(!t||!r||!n)throw Object.assign(new Error("无法确定用户数据许可作用域"),{code:"INVALID_STATE"});return Object.freeze({miniProgramId:t,userId:r,environment:n})}function gp(e){return typeof e=="string"&&/^[0-9a-f]{64}$/.test(e)}function we(e,t,r){return{code:e,message:t,data:r}}function $a(e){return pp(e)?{code:e.code,message:e.message,data:e.data}:e instanceof Error?we("RUNTIME_ERROR",e.message):we("UNKNOWN_ERROR","小程序运行时异常",e)}function pp(e){return!!e&&typeof e=="object"&&typeof e.code=="string"&&typeof e.message=="string"}const qt=["account.getCurrentUserId","account.onChange","storage.getRaw","storage.setRaw"],qo=[...qt,"network.request"],xc={"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"],[Di]:["workspaceCards.requestRefresh"],[Ni]:["account.getCurrentUserId","account.getAccountKey","account.onChange"],[Mi]:["account.getCurrentUserId","account.ensureAuthenticated","account.onChange","network.request"],[Si]:["account.getCurrentUserId","account.onChange","network.request"],[bi]:["account.getCurrentUserId","account.ensureAuthenticated","account.onChange","network.request"],[Ti]:["account.getCurrentUserId","account.onChange","network.request"],[vi]:["account.getCurrentUserId","account.onChange","network.request"],[Oi]:["account.getCurrentUserId","account.onChange","network.request"],[Ri]:["presentation.setClipboard"],[Pi]:["presentation.showShareMenu"],[ki]:["presentation.getViewportMetrics","presentation.captureAndShare"],[Ci]:["presentation.getViewportMetrics","presentation.captureAndShare"],[nr]:["presentation.applyOrientation"],[Li]:["presentation.getViewportMetrics","presentation.getNavigationBarHeight"],[Ui]:["presentation.setNavigationBarStyle"],[En]:["storage.getRaw"],[wn]:["storage.setRaw"],[xi]:["network.request"],[zi]:["network.stream","files.transfer","files.access"],[ji]:["network.upload","files.access"],[Bi]:["files.external"],[Hi]:["files.external"],[Fi]:["files.save"],[In]:["files.access"],[An]:["files.removeFile"],[Vi]:["files.access"],[_n]:["files.access"],[Gi]:["files.access"],[Dn]:["files.access"],[$i]:["files.access"],[Nn]:["files.access"],[qi]:["files.access"],[Mn]:["files.removeDirectory"],[Qi]:["files.access"],[Yi]:["files.access"],[Sn]:["media.pick"],[yn]:["presentation.showAppreciation"],[Wi]:["presentation.showToast"],[Zi]:["presentation.showLoading"],[Ki]:["presentation.hideLoading"],[Ji]:["presentation.vibrate"],[Xi]:["presentation.setClipboard"],[eo]:["protocol.invoke"],[to]:["presentation.close"],[ro]:["presentation.reload"],[no]:["presentation.openAppPage"],[bt]:["account.getCurrentUserId","account.onChange","network.request"],[at]:["account.onChange","network.request"],[xt]:["account.getCurrentUserId","account.onChange","network.request"],[ir]:["account.getCurrentUserId","account.onChange","network.request"],[wt]:["account.onChange","network.request"],[vr]:["account.getCurrentUserId","account.onChange","network.request"],[Or]:["account.getCurrentUserId","account.onChange","network.request"],[Rr]:["account.getCurrentUserId","account.onChange","network.request"],[or]:["account.getCurrentUserId","account.onChange","network.request"],[wo]:["companion.getInfo"],[Io]:["companion.getPreparationStatus"],[Ao]:["companion.getInfo","companion.getPreparationStatus","companion.prepare"],[_o]:["companion.cancelPreparation"],[Do]:["companion.getActiveSession"],[No]:["companion.getInfo","companion.launch"],[Mo]:["companion.session.write"],[So]:["companion.session.closeStdin"],[bo]:["companion.session.terminate"],[To]:["companion.session.ackOutput"],[vo]:["companion.openAttachment"],[Oo]:["companion.showNotification"],[Ca]:qt,[Ai]:qo,[un]:qo,[_i]:[...qo,"files.sandbox","files.removeFile","network.stream","files.transfer"],[La]:[...qt,"presentation.confirmDataPermission"],[Ua]:qt,[xa]:qt,[za]:[...qt,"presentation.openDataPermissions"],[ja]:qt},yp=new Set([yn]);function Gl(e,t){if(t[e]!==!0)throw yp.has(e)?we("REQUEST_UNSUPPORTED","当前宿主不支持该能力"):tt(e)}const Ep=32*1024*1024,wp=/^application\/(?:[a-z0-9!#$&^_.+-]+\+)?json(?:\s*;|$)/i;function Ip(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:Ep},i);return Ap(o,a)}catch(a){throw s=a,a}finally{try{await r.release(o.body)}catch(a){if(s===void 0)throw a}}}}}}function Ap(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:_p(t,Np(e,"content-type"))}}function _p(e,t){Dp(t);let r;try{r=new TextDecoder("utf-8",{fatal:!0}).decode(e)}catch(n){throw new Le("Host network response 不是合法 UTF-8 文本",{cause:n})}if(r.charCodeAt(0)===65279&&(r=r.slice(1)),!t||!wp.test(t)||r==="")return r;try{return JSON.parse(r)}catch{return r}}function Dp(e){if(!e)return;const t=/(?:^|;)\s*charset\s*=\s*["']?([^;"'\s]+)/i.exec(e)?.[1];if(t&&!/^utf-?8$/i.test(t))throw new Le(`Host network response 不支持 charset=${t}`)}function Np(e,t){return Object.entries(e.headers).find(([r])=>r.toLowerCase()===t)?.[1]?.[0]}function Z(e){return typeof e=="function"}function zc(e){return(...t)=>{throw tt(e)}}function Ce(e){return async(...t)=>{throw tt(e)}}const Mp=(e,t)=>{},Sp=()=>()=>{};function bp(e){const t={request:Z(e.network?.request)?e.network.request.bind(e.network):Ce("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):Ce("account.getCurrentUserId"),ensureAuthenticated:Z(e.account?.ensureAuthenticated)?e.account.ensureAuthenticated.bind(e.account):Ce("account.ensureAuthenticated"),onChange:Z(e.account?.onChange)?e.account.onChange.bind(e.account):Sp},n={...e.storage?.withLock?{withLock:e.storage.withLock.bind(e.storage)}:{},getRaw:Z(e.storage?.getRaw)?e.storage.getRaw.bind(e.storage):Ce("storage.getRaw"),setRaw:Z(e.storage?.setRaw)?e.storage.setRaw.bind(e.storage):Ce("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):Ce("presentation.close"),reload:Z(e.presentation?.reload)?e.presentation.reload.bind(e.presentation):Ce("presentation.reload"),openAppPage:Z(e.presentation?.openAppPage)?e.presentation.openAppPage.bind(e.presentation):Ce("presentation.openAppPage"),openWindow:Z(e.presentation?.openWindow)?e.presentation.openWindow.bind(e.presentation):Ce("presentation.openWindow"),getViewportMetrics:Z(e.presentation?.getViewportMetrics)?e.presentation.getViewportMetrics.bind(e.presentation):zc("presentation.getViewportMetrics"),getNavigationBarHeight:Z(e.presentation?.getNavigationBarHeight)?e.presentation.getNavigationBarHeight.bind(e.presentation):zc("presentation.getNavigationBarHeight"),setNavigationBarStyle:Z(e.presentation?.setNavigationBarStyle)?e.presentation.setNavigationBarStyle.bind(e.presentation):Ce("presentation.setNavigationBarStyle"),showShareMenu:Z(e.presentation?.showShareMenu)?e.presentation.showShareMenu.bind(e.presentation):Ce("presentation.showShareMenu"),setScreenshotChromeHidden:Z(e.presentation?.setScreenshotChromeHidden)?e.presentation.setScreenshotChromeHidden.bind(e.presentation):Mp,supportsLongScreenshot:e.presentation?.supportsLongScreenshot===!0,captureAndShare:Z(e.presentation?.captureAndShare)?e.presentation.captureAndShare.bind(e.presentation):Ce("presentation.captureAndShare"),showAppreciation:Z(e.presentation?.showAppreciation)?e.presentation.showAppreciation.bind(e.presentation):async()=>{throw we("REQUEST_UNSUPPORTED","当前宿主不支持赞赏码")},showToast:Z(e.presentation?.showToast)?e.presentation.showToast.bind(e.presentation):Ce("presentation.showToast"),showLoading:Z(e.presentation?.showLoading)?e.presentation.showLoading.bind(e.presentation):Ce("presentation.showLoading"),hideLoading:Z(e.presentation?.hideLoading)?e.presentation.hideLoading.bind(e.presentation):Ce("presentation.hideLoading"),vibrate:Z(e.presentation?.vibrate)?e.presentation.vibrate.bind(e.presentation):Ce("presentation.vibrate"),setClipboard:Z(e.presentation?.setClipboard)?e.presentation.setClipboard.bind(e.presentation):Ce("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):Ce(`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):Ce("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 Tp(e,t={}){const r=vp(e.files?.sandbox),n=Z(e.picker?.pickFiles)&&Z(e.picker?.pickDirectory),i=Z(e.picker?.saveFile),o=r||n||i||Z(e.companion?.openAttachment),s=r?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":r,"files.external":n,"files.save":i,"files.access":o,"files.removeFile":Z(s?.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),"presentation.confirmDataPermission":t.hasUserDataPresentation===!0,"presentation.openDataPermissions":t.hasUserDataSettings===!0}}function vp(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 jc(e,t){return t?.[e]!==!1}function Op(e){return e==="network.download"||e.startsWith("files.")||e.startsWith("file.")||e.startsWith("directory.")||e.startsWith("media.")||e.startsWith("companion.")}function $l(e,t={}){const r={};for(const n of Object.keys(xc)){const o=xc[n].every(a=>e[a]),s=!Op(n)||!!t.miniProgramDetail?.miniProgramId.trim();r[n]=jc(n,t.callerCapabilities)&&jc(n,t.hostCapabilities)&&o&&s}return r}function ql(e={},t={}){const r=Tp(e,t),n=$l(r,t);return{ports:bp(e),primitiveAvailability:r,availablePrimitives:r,effectiveCapabilities:n}}function Se(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]):Rp(e.signal,t);return{...e,signal:n,...r===void 0?{}:{requestId:r}}}function Rp(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 Pp(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 kp=4,Cp=["xiaoheihe.cn","max-c.com","debugmode.cn","maxjia.com"],Lp=new Set(["connection","content-length","host","origin","referer","keep-alive","proxy-connection","te","trailer","transfer-encoding","upgrade","x-heybox-runtime-auth-context-token"]),Up=["/user_miniprogram/runtime/auth","/user_miniprogram/openapi/v1"],xp=["/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 zp(e,t){const r=Hp(e);return r===null||Bc(r,Up)?!0:t&&Bc(r,xp)}function jp(e){const t=e.hostname.toLowerCase().replace(/\.$/,"");return Cp.some(r=>t===r||t.endsWith(`.${r}`))}function Bp(e){const t=e.trim().toLowerCase();return t.startsWith("x-hb-sdk-")||t.startsWith("sec-")||Lp.has(t)||/^(?:x-heybox|x-xhh)-(?:access-token|auth|authorization|pkey|session|token)$/.test(t)}function Hp(e){let t=e;for(let r=0;r<kp;r+=1){let n;try{n=decodeURIComponent(t)}catch{return null}if(n===t)return Hc(t);t=n}try{if(decodeURIComponent(t)!==t)return null}catch{return null}return Hc(t)}function Bc(e,t){return t.some(r=>e===r||e.startsWith(`${r}/`))}function Hc(e){const t=[];for(const r of e.replace(/\\/g,"/").split("/"))!r||r==="."||(r===".."?t.pop():t.push(r));return`/${t.join("/")}`}function Fp(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 Ql(e){if(e==null)return;if(typeof e!="object"||Array.isArray(e))throw Qo("网络策略格式无效");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 Qo("网络策略格式无效");const n=new Set;for(const i of r){const o=Fp(i&&typeof i=="object"?i.domain:void 0);if(!o)throw Qo("网络策略包含无效域名");n.add(o)}return Object.freeze({revision:t.revision,enforcement:t.enforcement,entries:Object.freeze([...n].sort().map(i=>Object.freeze({domain:i})))})}function Qo(e){return Object.assign(new TypeError(e),{code:"NETWORK_POLICY_INVALID"})}function Fc(e){return e instanceof Le?{code:"REQUEST_UNSUPPORTED",message:e.message}:e}function fe(e,t,r={}){if(t.aborted&&!r.invokeWhenAborted)return Promise.reject(si());let n;try{n=e()}catch(i){return Promise.reject(Fc(i))}return t.aborted?(Promise.resolve(n).catch(()=>{}),Promise.reject(si())):new Promise((i,o)=>{let s=!1;const a=d=>{s||(s=!0,t.removeEventListener("abort",c),d())},c=()=>a(()=>o(si()));t.addEventListener("abort",c,{once:!0}),Promise.resolve(n).then(d=>a(()=>i(d)),d=>a(()=>o(Fc(d))))})}async function Vp(e,t,r){pe(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 fe(()=>new Promise(f=>i.requestAnimationFrame(()=>i.requestAnimationFrame(()=>f()))),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 f=e.parentElement;f;f=f.parentElement){const l=i.getComputedStyle(f),h=f.getBoundingClientRect();if(["hidden","clip","scroll","auto"].includes(l.overflowY)&&(u.top+t.top<h.top-1||u.top+t.top+t.height>h.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 Gp(e,t,r,n=1e4){const i=new AbortController;return new Promise((o,s)=>{let a=!1;const c=f=>{a||(a=!0,clearTimeout(u),r.signal.removeEventListener("abort",d),i.abort(f),s(f))},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(f=>{if(typeof f!="function"){c({code:"NETWORK_POLICY_UNSUPPORTED",message:"Host 未完成严格网络策略初始化"});return}if(a){try{f()}catch{}return}a=!0,clearTimeout(u),o(()=>{r.signal.removeEventListener("abort",d),i.abort(),f()})},c)})}function Yl(e,t){return $p(t)??qp(e.pathname)}function $p(e){if(!e)return;const t=new URL(e,"https://mini-program.invalid").pathname;return t.endsWith("/")?t:`${t}/`}function qp(e){const t=/^(\/u\/[^/]+\/[^/]+\/)/.exec(e)?.[1];if(t)return t;const r=e.lastIndexOf("/");return r>=0?e.slice(0,r+1):"/"}const Qp=1,Wl="allow-scripts allow-same-origin",Yp="",Wp="no-referrer";function Zp(e=Wl){return!e.split(/\s+/).includes("allow-same-origin")}function Vc(){return window.crypto?.randomUUID?window.crypto.randomUUID():`${Date.now().toString(36)}_${Math.random().toString(36).slice(2)}`}const Kp=new Set(["javascript:","data:","blob:","file:"]),Gc="xiaoheihe.cn";function Jp(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(Kp.has(i.protocol)||!["http:","https:"].includes(i.protocol))throw new Error("不支持的小程序链接协议");if(!ey(i,t,r))throw new Error("小程序链接必须属于 https://*.xiaoheihe.cn 或本地调试地址");return i.toString()}function Xp(e,t){const r=new URL(e);return r.searchParams.set(pl,t),r.toString()}function Zl(e,t,r){try{const n=new URL(e),i=new URL(t);if(n.origin!==i.origin)return!1;const o=Yl(n,r);return i.pathname.startsWith(o)}catch{return!1}}function $c(e){const t=new URL(e);return qa(t)?"loopback":Qa(t)?"lan":"production"}function ey(e,t,r){return ty(e)||qa(e)||Qa(e)&&ny(t,r)}function ty(e){return e.protocol==="https:"&&sy(e.hostname)}function qa(e){return e.protocol==="http:"&&ry(e.hostname)}function ry(e){return e==="localhost"||e==="127.0.0.1"||e==="[::1]"}function Qa(e){return e.protocol==="http:"&&iy(e.hostname)}function ny(e,t){if(t.allowPrivateNetwork)return!0;try{const r=new URL(e);return qa(r)||Qa(r)}catch{return!1}}function iy(e){const t=oy(e);return t?t[0]===10||t[0]===172&&t[1]>=16&&t[1]<=31||t[0]===192&&t[1]===168:!1}function oy(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 sy(e){return e===Gc||e.endsWith(`.${Gc}`)}function ay(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||!Zl(e.launchUrl,a.href,e.locationBasePath))return;const c=new URL(a.href);if(!(c.username||c.password||c.searchParams.get(pl)!==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 Kl(e){const t=qe(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 cy(e){const t=qe(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 dy(){try{return{activeElement:globalThis.document?.activeElement??null,userActivation:globalThis.navigator?.userActivation}}catch{return{activeElement:null}}}const uy=1e3;function ly(e,t=dy()){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<=uy}const fy="runtime.gate.probe",Jl=new Set(zt.map(e=>e.method));class hy{iframe;nonce;onReady;getWorkspaceCardLaunchContext;onHandshake;onDuplicateHandshake;onInternalEvent;onResponsePosted;onDevUploadSession;handleMessage;handleUserInteraction;dispatcher;environmentInfo;started=!1;destroyed=!1;handshaken=!1;bridgeVersion=gl;targetOrigin;lastUserInteractionAt;operations=new Map;constructor(t){this.iframe=t.iframe,this.nonce=t.nonce,this.onReady=t.onReady,this.getWorkspaceCardLaunchContext=t.getWorkspaceCardLaunchContext,this.onHandshake=t.onHandshake,this.onDuplicateHandshake=t.onDuplicateHandshake,this.onInternalEvent=t.onInternalEvent,this.onResponsePosted=t.onResponsePosted,this.onDevUploadSession=t.onDevUploadSession,this.handleMessage=this.onMessage.bind(this),this.handleUserInteraction=this.onUserInteraction.bind(this),this.dispatcher=t.dispatcher,this.environmentInfo=t.environmentInfo,this.targetOrigin=t.targetOrigin||"*"}get protocolVersion(){return this.handshaken?this.bridgeVersion:void 0}start(){if(!(this.started||this.destroyed)){this.started=!0,window.addEventListener("message",this.handleMessage);for(const t of["pointerdown","touchend","mousedown","keydown"])window.addEventListener(t,this.handleUserInteraction,!0)}}setTargetOrigin(t){this.targetOrigin=t||"*"}destroy(){if(this.destroyed)return;const t=this.started;this.destroyed=!0,this.started=!1,this.handshaken=!1;try{t&&this.postMessage({namespace:$t,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:$t,version:this.bridgeVersion,nonce:this.nonce,type:"event",method:t,payload:r})}postInternalRequest(t,r,n){this.destroyed||this.postMessage({namespace:$t,version:this.bridgeVersion,nonce:this.nonce,type:"request",id:r,method:t,payload:n})}postProgress(t,r){this.bridgeVersion===2&&this.postMessage({namespace:$t,version:2,nonce:this.nonce,type:"event",id:t,method:El,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=ly(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&&Cm(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:$t,version:this.bridgeVersion,nonce:this.nonce,type:"response",id:t.id,method:yl,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===fy){this.postResponse(t,{ready:!0});return}if(!this.handshaken){this.postResponse(t,void 0,we("BRIDGE_NOT_READY","小程序 SDK 尚未完成握手"));return}if(!Jl.has(t.method)){this.postResponse(t,void 0,we("METHOD_NOT_FOUND",`未开放小程序能力: ${t.method}`));return}if(this.operations.has(t.id)){this.postResponse(t,void 0,we("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=$a(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:$t,version:t.version,nonce:this.nonce,type:"response",id:t.id,method:t.method,payload:r,error:n})||!my(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 my(e){return typeof e=="string"&&Jl.has(e)}function y(e,t,r){return r===void 0?{code:e,message:t}:{code:e,message:t,data:r}}function re(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ya(){const e=globalThis.crypto;if(!e||typeof e.getRandomValues!="function")throw y("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 y("FILE_IO_FAILED","无法生成安全文件标识")}}function Xl(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):Ys,remove:o?s=>e.remove(s):tf,read:s=>e.read(s),...typeof e.readPrefix=="function"?{readPrefix:(s,a)=>e.readPrefix(s,a)}:{},write:i?(s,a)=>e.write(s,a):Ys,stat:s=>e.stat(s)})}function ef(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=>Xl(e.file(a),n,{allowRemove:o}),directory:a=>ef(e.directory(a),n,{allowRemove:o}),create:i?(a,c)=>e.create(a,c):Ys,remove:s?(a,c)=>e.remove(a,c):tf,stat:a=>e.stat(a),list:(a,c)=>e.list(a,c)})}function Ys(){return Promise.reject(y("FILE_ACCESS_DENIED","当前文件授权只允许读取"))}function tf(){return Promise.reject(y("FILE_ACCESS_DENIED","外部文件授权不允许删除"))}const gy=new Set(["REQUEST_CANCELLED","REQUEST_TIMEOUT","RUNTIME_DESTROYED","USER_DATA_PERMISSION_STORAGE_UNAVAILABLE","USER_DATA_PERMISSION_STATE_INVALID","USER_DATA_SOURCE_NOT_LINKED","USER_DATA_SOURCE_LOGIN_REQUIRED","USER_GAME_DATA_UNAVAILABLE","USER_GAME_DATA_INVALID_RESPONSE","METHOD_FORBIDDEN","FILE_PICKER_CANCELLED","FILE_ACCESS_REVOKED","FILE_ACCESS_DENIED","FILE_NOT_FOUND","DIRECTORY_NOT_FOUND","FILE_ALREADY_EXISTS","DIRECTORY_ALREADY_EXISTS","FILE_TYPE_MISMATCH","FILE_TOO_LARGE","FILE_QUOTA_EXCEEDED","FILE_ENCODING_INVALID","DIRECTORY_LIST_LIMIT_EXCEEDED","DIRECTORY_NOT_EMPTY","FILE_IO_FAILED"]),py={REQUEST_CANCELLED:"文件操作已取消",REQUEST_TIMEOUT:"文件操作超时",RUNTIME_DESTROYED:"小程序已关闭",USER_DATA_PERMISSION_STORAGE_UNAVAILABLE:"无法读取本地用户数据许可",USER_DATA_PERMISSION_STATE_INVALID:"本地用户数据许可状态异常,已停止访问",USER_DATA_SOURCE_NOT_LINKED:"请先在小黑盒关联对应游戏账号",USER_DATA_SOURCE_LOGIN_REQUIRED:"请先在小黑盒更新游戏来源登录",USER_GAME_DATA_UNAVAILABLE:"游戏资料暂不可用,请稍后重试",USER_GAME_DATA_INVALID_RESPONSE:"游戏资料响应异常,请稍后重试",METHOD_FORBIDDEN:"当前 Host 未开放该文件能力",FILE_PICKER_CANCELLED:"已取消文件选择",FILE_ACCESS_REVOKED:"文件授权已失效",FILE_ACCESS_DENIED:"当前文件授权不允许此操作",FILE_NOT_FOUND:"文件不存在",DIRECTORY_NOT_FOUND:"目录不存在",FILE_ALREADY_EXISTS:"文件已存在",DIRECTORY_ALREADY_EXISTS:"目录已存在",FILE_TYPE_MISMATCH:"文件类型不匹配",FILE_TOO_LARGE:"文件超过大小限制",FILE_QUOTA_EXCEEDED:"文件配额已用尽",FILE_ENCODING_INVALID:"文件编码不合法",DIRECTORY_LIST_LIMIT_EXCEEDED:"目录项数量超过限制",DIRECTORY_NOT_EMPTY:"目录不为空",FILE_IO_FAILED:"文件操作失败"};function kr(e){const t=Wa(e),r=t&&gy.has(t)?y(t,py[t]??"文件操作失败"):y("FILE_IO_FAILED","文件操作失败");return Object.defineProperty(r,"cause",{value:e,enumerable:!1}),r}function Nt(e){try{return e()}catch(t){throw kr(t)}}function Wa(e){try{if(!re(e))return;const t=Object.getOwnPropertyDescriptor(e,"code");return t&&"value"in t&&typeof t.value=="string"?t.value:void 0}catch{return}}const qc=1024;class Za{constructor(t,r){this.files=t,this.miniProgramDetail=r}handles=new Map;disposed=!1;createTransferScope(){return this.assertCanonicalDetail(),new Za(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 $n(i.handle,{kind:"file",handleId:o})}registerFiles(t,r="external",n,i){this.assertCanonicalDetail();const o=Nt(()=>{if(!Array.isArray(t))throw y("FILE_IO_FAILED","Host 返回了无效文件选择结果");const a=t.length;if(i!==void 0&&a>i)throw y("FILE_IO_FAILED","Host 返回了过多文件选择结果");if(this.handles.size+a>qc)throw y("FILE_QUOTA_EXCEEDED","当前会话的文件授权句柄已达上限");const c=[];for(let d=0;d<a;d+=1){if(!Object.prototype.hasOwnProperty.call(t,d))throw y("FILE_IO_FAILED","Host 返回了稀疏文件选择结果");c.push(this.prepareFile(t[d],r,n))}return c}),s=this.registerMany(o);return o.map((a,c)=>$n(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 Yc(i.handle,{kind:"directory",handleId:o})}resolveFile(t){return this.resolveFileEntry(t).handle}resolveDirectory(t){return this.resolveDirectoryEntry(t).handle}isCompanionAttachmentRef(t){return!er(t)||!("handleId"in t)?!1:this.handles.get(t.handleId)?.origin==="companion-attachment"}isGameSaveRef(t){return!er(t)||!("handleId"in t)?!1:this.handles.get(t.handleId)?.origin==="game-save"}isUserDataDownloadRef(t){return!er(t)||!("handleId"in t)?!1:this.handles.get(t.handleId)?.origin==="download"}resolveFileEntry(t){this.assertCanonicalDetail();const r=Ey(t);if("handleId"in r){const s=this.readDirect(r.handleId,"file");return{ref:r,...s}}const n=this.resolveRoot(r.root),i=Tn(r.relativePath);Yo(n.origin,i);const o=this.prepareFile(Nt(()=>n.hostHandle.file(i)),n.origin,n.handle.mode);return{ref:r,...o}}resolveDirectoryEntry(t){this.assertCanonicalDetail();const r=wy(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==="."?".":Tn(r.relativePath);Yo(n.origin,i);const o=this.prepareDirectory(i==="."?n.hostHandle:Nt(()=>n.hostHandle.directory(i)),n.origin,n.handle.mode,!0);return{ref:r,...o}}describeFile(t,r){return Zc(t),$n(t,r)}describeListedEntries(t,r,n){return this.assertCanonicalDetail(),Nt(()=>{if(!Array.isArray(r))throw y("FILE_IO_FAILED","Host 返回了无效目录列表");const i=r.length;if(i>n)throw y("DIRECTORY_LIST_LIMIT_EXCEEDED","目录项数量超过限制");const o=[];for(let s=0;s<i;s+=1){if(!Object.prototype.hasOwnProperty.call(r,s))throw y("FILE_IO_FAILED","Host 返回了稀疏目录列表");const a=r[s];t.origin==="sandbox"&&re(a)&&typeof a.name=="string"&&rf(a.name)||o.push(this.describeListedEntry(t,a))}return this.assertCanonicalDetail(),o})}describeListedEntry(t,r){return Nt(()=>{if(re(r)&&r.kind==="file"){const n=this.prepareFile(r,t.origin,t.handle.mode);return $n(n.handle,Qc(t.ref,n.handle.name))}if(re(r)&&r.kind==="directory"){const n=this.prepareDirectory(r,t.origin,t.handle.mode);return Yc(n.handle,yy(t.ref,n.handle.name))}throw y("FILE_IO_FAILED","Host 返回了无效目录项")})}deriveFile(t,r){this.assertCanonicalDetail();const n=Ln(r);Yo(t.origin,n);const i=this.prepareFile(Nt(()=>t.hostHandle.file(n)),t.origin,t.handle.mode);return{ref:Qc(t.ref,n),...i}}assertSandboxOrigin(t){if(t.origin!=="sandbox")throw y("FILE_ACCESS_DENIED","外部文件授权不允许删除")}prepareFile(t,r,n){return Nt(()=>{Zc(t);const i=n??t.mode;return Wc(t.mode,i),{handle:Xl(t,i,{allowRemove:r==="sandbox"}),hostHandle:t,origin:r}})}prepareDirectory(t,r,n,i=!1){return Nt(()=>{_y(t,i);const o=n??t.mode;return Wc(t.mode,o),{handle:ef(t,o,{allowRemove:r==="sandbox"}),hostHandle:t,origin:r}})}registerMany(t){if(this.assertCanonicalDetail(),this.handles.size+t.length>qc)throw y("FILE_QUOTA_EXCEEDED","当前会话的文件授权句柄已达上限");const r=new Set,n=t.map(()=>{for(let i=0;i<8;i+=1){const o=Ya();if(!this.handles.has(o)&&!r.has(o))return r.add(o),o}throw y("FILE_IO_FAILED","无法创建文件授权句柄")});return t.forEach((i,o)=>this.handles.set(n[o],i)),n}readDirect(t,r){if(!Iy(t))throw y("FILE_ACCESS_REVOKED","文件授权句柄无效");const n=this.handles.get(t);if(!n)throw y("FILE_ACCESS_REVOKED","文件授权已失效");if(n.handle.kind!==r||n.hostHandle.kind!==r)throw y("FILE_TYPE_MISMATCH","文件句柄类型不匹配");return n}resolveRoot(t){if(this.assertCanonicalDetail(),t.kind==="sandbox"){if(!this.files)throw tt("files.sandbox");return this.prepareDirectory(Nt(()=>this.files.sandbox),"sandbox",void 0,!0)}return this.readDirect(t.handleId,"directory")}assertCanonicalDetail(){if(this.disposed)throw y("FILE_ACCESS_REVOKED","文件授权已失效");if(!this.miniProgramDetail?.miniProgramId.trim())throw tt("files")}}function Tn(e){if(!Ba(e))throw y("INVALID_PARAMS","relativePath 不是规范逻辑路径");return e}function Yo(e,t){if(e==="sandbox"&&rf(t))throw y("FILE_ACCESS_DENIED","Runtime 私有缓存不能通过沙箱路径访问")}function rf(e){return e.split("/").some(t=>t.replace(/[. ]+$/,"").toLowerCase()===".hb-game-saves")}function Ln(e,t="文件名"){const r=Tn(e);if(r.includes("/"))throw y("INVALID_PARAMS",`${t} 只能是 basename`);return r}function Qc(e,t){return"handleId"in e?{kind:"file",root:{kind:"directory",handleId:e.handleId},relativePath:t}:{kind:"file",root:e.root,relativePath:Tn(e.relativePath==="."?t:`${e.relativePath}/${t}`)}}function yy(e,t){return"handleId"in e?{kind:"directory",root:{kind:"directory",handleId:e.handleId},relativePath:t}:{kind:"directory",root:e.root,relativePath:Tn(e.relativePath==="."?t:`${e.relativePath}/${t}`)}}function $n(e,t){return{kind:"file",name:e.name,mode:e.mode,ref:t}}function Yc(e,t){return{kind:"directory",name:e.name,mode:e.mode,ref:t}}function Wc(e,t){if(t==="readwrite"&&e!=="readwrite")throw y("FILE_ACCESS_DENIED","Host 未授予请求的文件写权限")}function Ey(e){return er(e)||nf(),e}function wy(e){return Il(e)||nf(),e}function nf(){throw y("INVALID_PARAMS","文件引用不合法")}function Iy(e){return/^[0-9a-f]{32}$/.test(e)}function Ay(e){return re(e)&&e.kind==="file"&&typeof e.name=="string"&&(e.mode==="read"||e.mode==="readwrite")&&typeof e.create=="function"&&typeof e.read=="function"&&typeof e.write=="function"&&typeof e.stat=="function"}function Zc(e){if(!Ay(e))throw y("FILE_IO_FAILED","Host 返回了无效 File handle");Ln(e.name,"Host File name")}function _y(e,t=!1){if(!re(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 y("FILE_IO_FAILED","Host 返回了无效 Directory handle");if(!t&&e.name.length===0)throw y("FILE_IO_FAILED","Host Directory name 不能为空");e.name&&Ln(e.name,"Host Directory name")}const Dy=new Set(["content-length","content-encoding","transfer-encoding","content-disposition","content-range","content-type"]),Ny=new Set(["content-length","content-encoding","content-disposition","content-range","content-type"]),My=new Set(["range","if-range","a-im"]),Sy=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"]),by=/^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\..*)?$/i,qn={initial:0,target:1,open:2,validate:3,transfer:4,committed:5,completed:6};class Ty{constructor(t){this.signal=t}phase="initial";transition(t){if(qn[t]<=qn[this.phase])throw y("FILE_IO_FAILED","下载状态转换不合法");this.phase=t}throwIfCancelled(){if(qn[this.phase]<qn.committed&&this.signal.aborted)throw af()}normalizeHostError(t,r){return this.throwIfCancelled(),Ja(t,r,this.signal)}}async function of(e,t,r){const n=r.transfer,i=r.fileRegistry;if(!n||!i)throw tt("network.download");const o=Se(r.operationContext,t.signal),s=new Ty(o.signal);s.transition("target"),s.throwIfCancelled();let a;try{a=await Py(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=Cy(c);Ly(c,u);const f=Uy(c.status,u);if(e.maxBytes!==void 0&&f.expectedBytes!==void 0&&f.expectedBytes>e.maxBytes)throw y("FILE_TOO_LARGE","下载响应超过 maxBytes");s.throwIfCancelled();const l=ky(e,a,u,i);let h=0;const m=Oy(f.expectedBytes,e.maxBytes);Zo(t,Wo(0,f));const E={...o,onProgress(S){!Number.isSafeInteger(S)||S<h||m!==void 0&&S>m||(h=S,Zo(t,Wo(h,f)))}};s.transition("transfer"),d=!0;let _;try{_=await n.files.writeResource(l.hostHandle,c.body,{mode:l.mode,...e.maxBytes===void 0?{}:{maxBytes:e.maxBytes},...f.expectedBytes===void 0?{}:{expectedBytes:f.expectedBytes}},E)}catch(S){throw s.normalizeHostError(S,"transfer")}s.transition("committed"),h=vy(_,f,h,e.maxBytes),Zo(t,Wo(h,f));const w=i.describeFile(l.handle,l.ref);return s.transition("completed"),w}finally{d||Ry(n.network,c.body)}}function vy(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 Oy(e,t){return e===void 0?t:t===void 0?e:Math.min(e,t)}function Ry(e,t){try{Promise.resolve(e.release(t)).catch(()=>{})}catch{}}async function Py(e,t,r){if(e.targetKind==="file"){const i=t.resolveFileEntry(e.to);return Ws(i.handle.mode),await Vy(i.handle,r),{kind:"file",...i}}const n=t.resolveDirectoryEntry(e.to);return Ws(n.handle.mode),await Gy(n.handle,r),{kind:"directory",...n}}function ky(e,t,r,n){if(t.kind==="file")return{ref:t.ref,handle:t.handle,hostHandle:t.hostHandle,mode:"replace-existing"};const i=zy(e,r),o=n.deriveFile(t,i);return Ws(o.handle.mode),{...o,mode:e.overwrite===!0?"upsert":"create-exclusive"}}function Cy(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 y("DOWNLOAD_NETWORK_FAILED","Host 返回了无效 stream response");if(!re(e.headers))throw y("DOWNLOAD_NETWORK_FAILED","Host 返回了无效 stream headers");const t={};for(const[r,n]of Object.entries(e.headers)){if(r!==r.toLowerCase()||!Dy.has(r)||!Array.isArray(n)||n.length===0)throw y("DOWNLOAD_NETWORK_FAILED","Host 返回了不安全 stream header");if(n.some(i=>typeof i!="string"||/[\r\n]/.test(i)))throw y("DOWNLOAD_NETWORK_FAILED","Host 返回了无效 stream header value");t[r]=[...n]}return t}function Ly(e,t){if(e.status<200||e.status>=300||e.status===206||e.status===226)throw y("DOWNLOAD_HTTP_STATUS",`下载请求失败: HTTP ${e.status}`,{status:e.status,...e.statusText===void 0?{}:{statusText:e.statusText},headers:Fy(t,Ny)});if((t["content-range"]?.length??0)>0)throw y("DOWNLOAD_NETWORK_FAILED","下载响应包含 Content-Range")}function Uy(e,t){const r=t["content-length"]??[],n=t["transfer-encoding"]??[];if(r.length>0&&n.length>0)throw y("DOWNLOAD_NETWORK_FAILED","下载响应同时包含 Transfer-Encoding 与 Content-Length");if((e===204||e===205)&&r.some(d=>d!=="0"))throw y("DOWNLOAD_NETWORK_FAILED","无内容响应声明了非零 Content-Length");if((e===204||e===205)&&n.length>0)throw y("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=xy(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 xy(e){return!e||e.length===0?!0:e.length===1&&e[0].trim().toLowerCase()==="identity"}function Wo(e,t){return{loaded:e,...t.total===void 0?{}:{total:t.total},lengthComputable:t.lengthComputable}}function Zo(e,t){try{e.postProgress(t)}catch{}}function zy(e,t){const r=t["content-disposition"]??[];for(const i of r){const o=jy(i);if(o&&ai(o))return o}for(const i of r){const o=By(i);if(o&&ai(o))return o}if(e.suggestedName!==void 0)return Ka(e.suggestedName);const n=Hy(e.url);return n&&ai(n)?n:"download.bin"}function jy(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 By(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 Hy(e){const t=e.pathname.split("/").pop();if(t)try{return decodeURIComponent(t)}catch{return}}function Ka(e){try{Ln(e,"suggestedName")}catch{throw y("INVALID_PARAMS","suggestedName 不是安全 basename")}if(!ai(e))throw y("INVALID_PARAMS","suggestedName 不是安全 basename");return e}function ai(e){return!(!e||e==="."||e===".."||Array.from(e).length>255||/[\\/<>:"|?*\u0000-\u001f\u007f]/.test(e)||/[. ]$/.test(e)||by.test(e))}function Fy(e,t){return Object.fromEntries(Object.entries(e).filter(([r])=>t.has(r)).map(([r,n])=>[r,n.join(", ")]))}async function Vy(e,t){try{const r=await e.stat(t);if(!r||r.kind!=="file")throw sf()}catch(r){throw Ja(r,"file",t.signal)}}async function Gy(e,t){try{const r=await e.stat(t);if(!r||r.kind!=="directory")throw sf()}catch(r){throw Ja(r,"file",t.signal)}}function Ws(e){if(e!=="readwrite")throw y("FILE_ACCESS_DENIED","下载目标只允许读取")}const $y={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 Ja(e,t,r){if(r.aborted)return af();const n=qy(e);if(n&&Sy.has(n)){const o=y(n,$y[n]??"下载失败");return Object.defineProperty(o,"cause",{value:e,enumerable:!1}),o}if(e instanceof Error&&e.name==="AbortError")return t==="network"||t==="transfer"?y("DOWNLOAD_TIMEOUT","下载网络请求超时"):y("FILE_IO_FAILED","下载文件写入失败");const i=t==="network"?y("DOWNLOAD_NETWORK_FAILED","下载网络请求失败"):y("FILE_IO_FAILED","下载文件写入失败");return Object.defineProperty(i,"cause",{value:e,enumerable:!1}),i}function qy(e){return re(e)&&typeof e.code=="string"?e.code:void 0}function sf(){return y("FILE_TYPE_MISMATCH","下载目标类型不匹配")}function af(){return y("DOWNLOAD_CANCELLED","下载已取消")}function Qy(e){if(!e)return;const t=Object.keys(e).find(r=>My.has(r.trim().toLowerCase()));if(t)throw y("INVALID_PARAMS",`network.download 不允许设置请求头: ${t}`)}const Kc=8*1024*1024,Yy=32*1024*1024;function Xa(e){const t=new Map;let r=0;const n={signal:new AbortController().signal,lifecycle:"cleanup"},i=a=>a.remove(n).catch(()=>{}),o=async a=>{const c=t.get(a);c&&(t.delete(a),r-=c.size,await i(c.target))};e.signal.addEventListener("abort",()=>{for(const a of t.keys())o(a)},{once:!0});const s=a=>{if(e.signal.aborted||a.signal.aborted)throw y("DOWNLOAD_CANCELLED","存档下载已取消")};return{release:o,sizeOf:a=>t.get(a)?.size,async download(a,c,d){const u=a.file;if(!u||typeof u.file_id!="string"||typeof u.name!="string"||typeof u.size_bytes!="number"||!Number.isSafeInteger(u.size_bytes)||u.size_bytes<0||typeof a.download_url!="string"||typeof a.expires_at!="number"||!Number.isSafeInteger(a.expires_at))throw y("INVALID_RESPONSE","存档下载描述无效");if(u.size_bytes>Kc)throw y("FILE_TOO_LARGE","存档文件超过 8 MiB");const f={source:"runtime-private",credentials:"omit",route:"game-save",redirectPolicy:"error",method:"GET",target:{kind:"absolute-url",url:a.download_url},timeout:6e4};if(!Hl(f)||new URL(a.download_url).pathname!==`/cloud_archive/${u.file_id}.zip`||a.expires_at<=Date.now())throw y("INVALID_RESPONSE","存档下载地址无效");s(d);const l=Math.min(Kc,Yy-r);if(l<=0)throw y("FILE_QUOTA_EXCEEDED","当前会话存档缓存已达上限");const h=e.files.sandbox.file(`.hb-game-saves/${Ya()}.zip`);if(!h.remove)throw y("REQUEST_UNSUPPORTED","宿主不支持私有存档清理");r+=l;let m=!1;try{await e.files.sandbox.directory(".hb-game-saves").create({recursive:!0,exclusive:!1},d),await h.create({recursive:!0,exclusive:!0},d);const E=e.registry.createTransferScope();try{const p=E.registerFile(h,"game-save","readwrite");await of({request:f,url:new URL(a.download_url),to:p.ref,targetKind:"file",maxBytes:l},{...d,trustedUserGesture:!1,postEvent:()=>{},postProgress:()=>{}},{transfer:e.transfer,fileRegistry:E,operationContext:d})}finally{E.dispose()}s(d);const _=(await h.stat(d)).size;if(!Number.isSafeInteger(_)||_<0||_>l)throw y("FILE_TOO_LARGE","存档实际大小超过限额");await c(d),s(d);const w=async()=>{throw y("FILE_ACCESS_DENIED","存档文件只读")},S={kind:"file",mode:"read",name:u.name,create:w,write:w,async read(p){s(p),await c(p);const M=await h.read(p);try{if(s(p),await c(p),M.byteLength!==_)throw y("INVALID_RESPONSE","私有存档副本长度不匹配");return M}catch(z){throw M.fill(0),z}},async stat(p){return s(p),await c(p),await h.stat(p),s(p),await c(p),{kind:"file",size:_,...typeof u.modified_at=="number"&&Number.isSafeInteger(u.modified_at)?{modifiedAt:u.modified_at}:{}}}};return r-=l-_,t.set(S,{target:h,size:_}),m=!0,S}finally{m||(r-=l,await i(h))}}}}const Wy=/^(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 Zy(e){if(!e?.minimumSdkVersion)throw we("MINIMUM_SDK_VERSION_UNAVAILABLE","平台最低 SDK 版本配置不可用");const t=Zt(e.minimumSdkVersion),r=e.sdkVersion?Zt(e.sdkVersion):void 0;if(!t)throw we("MINIMUM_SDK_VERSION_UNAVAILABLE","平台最低 SDK 版本配置不合法");if(e.sdkVersion&&!r)throw we("SDK_VERSION_INVALID","小程序 SDK 版本不合法");const n=Zt("0.6.0");if(!r){if(ci(t,n)<0)return{heartbeatEnabled:!1,sdkVersion:void 0};throw we("SDK_VERSION_INVALID","小程序 SDK 版本缺失")}if((e.releaseChannel??"public")==="public"&&r.prerelease.length>0&&e.allowPublicPrerelease!==!0)throw we("SDK_VERSION_INVALID","正式小程序不能使用预发布 SDK");if(ci(r,t)<0)throw we("SDK_VERSION_TOO_LOW","小程序 SDK 版本低于平台最低要求");return{heartbeatEnabled:ci(r,Zt("0.6.0-0"))>=0,sdkVersion:e.sdkVersion}}function Ky(e,t){if(typeof t!="string"||!Zt(t))throw we("SDK_VERSION_INVALID","SDK handshake 版本不合法");if(t!==e)throw we("SDK_VERSION_MISMATCH","SDK handshake 版本与 Version record 不一致")}function ec(e,t){const r=Zt(e),n=Zt(t);if(!(!r||!n))return ci(r,n)}function Zt(e){const t=Wy.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 ci(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}function Jy(e){return{[yn]:async(t,r)=>{const n=Se(e.operationContext,r.signal);if(pe(n.signal),t!==void 0)throw y("INVALID_PARAMS","user.showAppreciation 不支持参数");if(!r.trustedUserGesture)throw y("USER_GESTURE_REQUIRED","请通过点击打开赞赏码");const i=e.miniProgramPresentation;if(!i?.name||!i.author)throw y("INVALID_STATE","缺少小程序名称或开发者信息,无法展示赞赏码");const o=e.presentation.showAppreciation;if(!o)throw y("REQUEST_UNSUPPORTED","当前宿主不支持赞赏码");await fe(()=>o({name:i.name,author:i.author},n),n.signal)}}}function hr(){const e=new Error("Runtime cache read cancelled");return e.name="AbortError",e}function Jc(e,t){return e.length===t.length&&e.every((r,n)=>r===t[n])}function cf(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(E,_){try{e.onEvent&&Promise.resolve(e.onEvent({namespace:E,type:_})).catch(()=>{})}catch{}}function u(E){const _=r.get(E);if(!_)throw new Error("Unknown runtime cache scope");return _}function f(E,_){return E.flatMap((w,S)=>{const p=JSON.stringify(E.slice(0,S+1));return[JSON.stringify([p]),JSON.stringify([p,_])]})}function l(E,_){return JSON.stringify(f(E,_).map(w=>n.get(w)??0))}async function h(E,_){const w=u(E),S=JSON.stringify([JSON.stringify(w),..._?[_]:[]]),p=(n.get(S)??0)+1;n.set(S,p),i.add(S);for(const M of a)M(w,_);if(!e.store){i.delete(S),d(_??"*","invalidation");return}try{await e.store.invalidate(w,_)}catch(M){throw d(_??"*","storage_error"),M}n.get(S)===p&&i.delete(S),d(_??"*","invalidation")}function m(E){if(c)throw new Error("Runtime cache manager disposed");const _=o.get(E.namespace);if(_){if(_.sourceCodec!==E.codec||_.definition.codec.version!==E.codec.version||JSON.stringify(_.definition.policy)!==JSON.stringify(E.policy))throw new Error("Conflicting runtime cache namespace");return _.cache}if(!E.namespace||!E.codec.version)throw new Error("Invalid runtime cache definition");const w=Object.freeze({...E.policy}),S=Object.freeze({version:E.codec.version,encode:E.codec.encode.bind(E.codec),decode:E.codec.decode.bind(E.codec),validate:E.codec.validate.bind(E.codec),clone:E.codec.clone.bind(E.codec)}),p=E.namespace;for(const L of[w.ttlMs,w.memoryMaxEntries,w.diskMaxEntries,w.diskMaxBytes,w.maxEntryBytes])if(!Number.isFinite(L)||L<0)throw new Error("Invalid runtime cache policy");const M=new Map,z=new Map,A=new Map;let D=!1;function I(L,C,H){if(c||D||L.aborted||l(C,p)!==H)throw hr()}function v(L){return w.ttlMs>0&&w.persistence==="memory-and-disk"&&!!e.store&&!f(L,p).some(C=>i.has(C))}function T(L,C,H){const F=t();return L.envelopeVersion===1&&JSON.stringify(L.address)===JSON.stringify(C)&&Jc(L.revisions,H)&&L.payload.byteLength<=w.maxEntryBytes&&Number.isFinite(L.cachedAt)&&Number.isFinite(L.expiresAt)&&L.cachedAt<=F&&L.cachedAt>=0&&L.expiresAt>L.cachedAt&&Math.min(L.expiresAt,L.cachedAt+w.ttlMs)>F}function x(L,C,H,F,$){if(!(w.ttlMs<=0||w.memoryMaxEntries<1)){for(const[K,g]of M)Math.min(g.entry.expiresAt,g.entry.cachedAt+w.ttlMs)<=t()&&M.delete(K);for(M.delete(L);M.size>=Math.floor(w.memoryMaxEntries);){const K=M.keys().next();if(K.done)break;M.delete(K.value)}M.set(L,{entry:C,value:H,epoch:F,persistent:$})}}async function N(L,C,H,F){const $={namespace:p,codecVersion:S.version,scopeIds:C,key:L.key},K=JSON.stringify($);let g=[],k=v(C);if(k)try{g=await e.store.readRevisions(C,p)}catch{k=!1,d(p,"storage_error")}I(F.signal,C,H);async function B(){if(!k)return!0;try{return Jc(g,await e.store.readRevisions(C,p))}catch{return k=!1,d(p,"storage_error"),!1}}const Q=M.get(K);if(w.ttlMs>0&&Q&&Q.epoch===H&&T(Q.entry,$,g)&&Q.persistent===k&&await B())return I(F.signal,C,H),d(p,"memory_hit"),Q.value;if(M.delete(K),k){let ie,ue;try{ie=await e.store.read($,w.maxEntryBytes),ie&&T(ie,$,g)?ue=S.decode(ie.payload):ie=void 0}catch{ie=void 0,d(p,"storage_error")}if(I(F.signal,C,H),ie&&await B())return I(F.signal,C,H),x(K,ie,ue,H,!0),d(p,"disk_hit"),ue}d(p,"miss");const X=S.validate(await L.load(F.signal));I(F.signal,C,H);const ne=S.clone(X);if(!await B()&&k)throw hr();if(I(F.signal,C,H),w.ttlMs>0){const ie=t();let ue;try{ue=S.encode(ne)}catch{return ne}const Ee={envelopeVersion:1,address:$,revisions:k?g:[],cachedAt:ie,expiresAt:ie+w.ttlMs,payload:ue};if(k&&ue.byteLength<=w.maxEntryBytes){let me=!0,ge=!1;try{me=await e.store.publish(Ee,w),ge=me}catch{d(p,"storage_error")}if(I(F.signal,C,H),!me)throw hr();ge&&d(p,"published")}I(F.signal,C,H),x(K,Ee,ne,H,k)}return ne}async function b(L){if(c||D||L.signal?.aborted)return Promise.reject(hr());const C=u(L.scope),H=l(C,p);let F;if(v(C)){const k=new AbortController;A.set(k,C);const B=()=>k.abort();L.signal?.addEventListener("abort",B,{once:!0});let Q=()=>{};try{F=await Promise.race([e.store.readRevisions(C,p),new Promise((X,ne)=>{const ie=()=>ne(hr());k.signal.addEventListener("abort",ie,{once:!0}),Q=()=>k.signal.removeEventListener("abort",ie)})])}catch{k.signal.aborted||d(p,"storage_error")}finally{Q(),A.delete(k),L.signal?.removeEventListener("abort",B)}}I(L.signal??new AbortController().signal,C,H);const $=JSON.stringify([C,L.key,H,F]);let K=z.get($);if(K?.controller.signal.aborted&&(K=void 0),!K){const k=new AbortController;K={ids:C,controller:k,waiters:0,promise:Promise.resolve(void 0)};const B=K;B.promise=N(L,C,H,k).finally(()=>{z.get($)===B&&z.delete($)}),z.set($,B)}const g=K;return g.waiters+=1,new Promise((k,B)=>{let Q=!1;function X(ie){Q||(Q=!0,L.signal?.removeEventListener("abort",ne),g.controller.signal.removeEventListener("abort",ne),g.waiters-=1,g.waiters===0&&g.controller.abort(),ie())}function ne(){X(()=>B(hr()))}L.signal?.addEventListener("abort",ne,{once:!0}),g.controller.signal.addEventListener("abort",ne,{once:!0}),g.promise.then(ie=>X(()=>{try{I(L.signal??new AbortController().signal,C,H),k(S.clone(ie))}catch(ue){B(ue)}}),ie=>X(()=>B(ie)))})}function O(L,C){if(C&&C!==p)return;const H=F=>L.every(($,K)=>F[K]===$);for(const[F,$]of M)H($.entry.address.scopeIds)&&M.delete(F);for(const[F,$]of z)H($.ids)&&($.controller.abort(),z.delete(F));for(const[F,$]of A)H($)&&F.abort()}function j(){if(!D){D=!0,M.clear();for(const L of A.keys())L.abort();A.clear();for(const L of z.values())L.controller.abort();z.clear(),s.delete(j),a.delete(O),o.get(p)?.cache===U&&o.delete(p)}}const U={read:b,invalidateScope:L=>h(L,p),dispose:j};return s.add(j),a.add(O),o.set(p,{definition:{namespace:p,codec:S,policy:w},sourceCodec:E.codec,cache:U}),U}return{createScope(E,_){if(c||!E)throw new Error("Invalid runtime cache scope");const w=Object.freeze({});return r.set(w,[..._?u(_):[],E]),w},register:m,invalidateScope:E=>h(E),dispose(){if(!c){c=!0;for(const E of[...s])E();o.clear(),n.clear(),i.clear()}}}}function Xy(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 eE=".hb-runtime-cache-v1",tE=1e3,Ko=64*1024,mr=1e3,rE=2048,Zr=32*1024*1024,nE=1024,di=new TextEncoder,Xc=new TextDecoder("utf-8",{fatal:!0});function Kr(){return Object.assign(new Error("缓存文件操作已取消"),{name:"AbortError"})}async function Qn(e){const t=await globalThis.crypto.subtle.digest("SHA-256",di.encode(JSON.stringify(e)));return Array.from(new Uint8Array(t),r=>r.toString(16).padStart(2,"0")).join("")}function ht(e,t){return JSON.stringify(e)===JSON.stringify(t)}function ed(){return Array.from(globalThis.crypto.getRandomValues(new Uint8Array(16)),e=>e.toString(16).padStart(2,"0")).join("")}function iE(e){return!!e&&typeof e=="object"&&["METHOD_FORBIDDEN","NOT_SUPPORTED","UNSUPPORTED_OPERATION","ENOSYS","ENOTSUP","EOPNOTSUPP"].includes(String(e.code))}function td(e,t){if(t.some(r=>typeof e[r]!="function"))throw Object.assign(new Error("Host 文件原语不完整,关闭磁盘缓存"),{code:"METHOD_FORBIDDEN"})}function oE(e,t){const r=e.sandbox.directory(eE),n=r.directory("revisions"),i=r.directory("entries");for(const N of[r,n,i,i.directory("capability-check")])td(N,["directory","file","create","stat","list","remove"]),td(N.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(N){d=N,o.abort(),t.signal.removeEventListener("abort",s)}function f(N){if(iE(N))throw u(N),N}function l(){if(d)throw d;if(a.signal.aborted)throw Kr()}function h(N,b=a.signal){const O=c.then(()=>{if(b.aborted)throw d??Kr();return l(),N()},()=>{if(b.aborted)throw d??Kr();return l(),N()}).catch(C=>{throw f(C),C});if(c=O.catch(()=>{}),b.aborted)return Promise.reject(d??Kr());let j=()=>{};const U=new Promise((C,H)=>{const F=()=>H(d??Kr());b.addEventListener("abort",F,{once:!0}),j=()=>b.removeEventListener("abort",F)}),L=setTimeout(()=>{u(Object.assign(new Error("缓存文件操作超时,已降级为内存缓存"),{code:"CACHE_STORAGE_TIMEOUT"}))},tE);return Promise.race([O,U]).finally(()=>{clearTimeout(L),j()})}async function m(){l(),await n.create({recursive:!0,exclusive:!1},a),l(),await i.create({recursive:!0,exclusive:!1},a),l()}async function E(N,b){const O=n.file(`${await Qn([N,b??null])}.revision`);await w(O);let j=!1;try{await O.create({recursive:!1,exclusive:!0},a),j=!0}catch(C){f(C),l()}if(j){const C=ed();return await O.write(di.encode(C),a),l(),C}const U=await O.stat(a);if(U.size<1||U.size>128)throw new Error("缓存 revision 文件损坏");const L=Xc.decode(await O.read(a));if(!/^(?:[0-9a-f]{32}|[0-9a-f-]{36})$/.test(L))throw new Error("缓存 revision 文件损坏");return l(),L}async function _(N){const b=await N.list({limit:mr},a);if(b.length>=mr)throw new Error("缓存目录超过治理上限");return b}async function w(N){try{await N.stat(a);return}catch(O){if(!Yn(O))throw O}if((await _(n)).length>=mr-1)throw new Error("缓存 metadata 超过治理上限")}async function S(N,b){await m();const O=[];for(let j=0;j<N.length;j+=1){const U=N.slice(0,j+1);O.push(await E(U),await E(U,b))}return O}async function p(N){return r.directory(`entries/${await Qn([N.namespace,N.codecVersion,N.scopeIds])}`)}async function M(N){return(await p(N)).file(`${await Qn(N.key)}.cache`)}async function z(N,b){const O=await N.stat(a);if(O.size<5||O.size>b+Ko+4)throw new Error("缓存条目超过大小限制");const j=await N.read(a);if(l(),j.length!==O.size)throw new Error("缓存条目读取不完整");const U=new DataView(j.buffer,j.byteOffset,j.byteLength).getUint32(0);if(U<1||U>Ko||U+4>j.length)throw new Error("缓存信封损坏");const L=JSON.parse(Xc.decode(j.subarray(4,U+4))),C=j.slice(U+4);if(L.envelopeVersion!==1||!L.address||!Array.isArray(L.address.scopeIds)||!L.address.scopeIds.every(H=>typeof H=="string")||typeof L.address.namespace!="string"||typeof L.address.codecVersion!="string"||typeof L.address.key!="string"||!Array.isArray(L.revisions)||L.revisions.length!==L.address.scopeIds.length*2||!L.revisions.every(H=>typeof H=="string"&&H.length>0)||!Number.isSafeInteger(L.cachedAt)||!Number.isSafeInteger(L.expiresAt)||L.cachedAt<0||L.expiresAt<=L.cachedAt||L.payloadBytes!==C.length||C.length>b)throw new Error("缓存信封损坏");return{envelopeVersion:1,address:L.address,revisions:L.revisions,cachedAt:L.cachedAt,expiresAt:L.expiresAt,payload:C}}async function A(N){if(!N.remove)throw new Error("Host 不支持缓存文件删除");await N.remove(a)}async function D(N){try{if((await N.file.stat(a)).size!==N.size)return!1;const b=await z(N.file,Zr);return!ht(b.address,N.entry.address)||!ht(b.revisions,N.entry.revisions)||b.cachedAt!==N.entry.cachedAt||b.expiresAt!==N.entry.expiresAt||!ht(await I(b.payload),await I(N.entry.payload))?!1:(await A(N.file),!0)}catch(b){if(Yn(b))return!0;throw b}}async function I(N){const b=await globalThis.crypto.subtle.digest("SHA-256",N);return Array.from(new Uint8Array(b),O=>O.toString(16).padStart(2,"0")).join("")}async function v(){const N=await _(n);let b=0;for(const L of N)if(L.kind==="file"&&(b+=(await L.stat(a)).size,b>Zr))throw new Error("缓存扫描超过字节上限");const O=[];let j=0,U=b;for(const L of await _(i)){if(L.kind!=="directory")throw new Error("缓存目录结构损坏");for(const C of await _(L)){if(C.kind!=="file"||++j>rE)throw new Error("缓存文件超过治理上限");const H=(await C.stat(a)).size;if(U+=H,U>Zr)throw new Error("缓存扫描超过字节上限");try{const F=await z(C,Zr);O.push({file:C,entry:F,size:(await C.stat(a)).size,bucketName:L.name})}catch(F){f(F),l(),Yn(F)||await A(C)}}}return{entries:O,metadataBytes:b}}async function T(){for(const N of await _(i))if(N.kind==="directory"&&N.remove&&(await _(N)).length===0)try{await N.remove({recursive:!1},a)}catch(b){f(b),l()}}function x(N){const{payload:b,...O}=N,j=di.encode(JSON.stringify({...O,payloadBytes:b.length}));if(j.length>Ko)throw new Error("缓存信封过大");const U=new Uint8Array(4+j.length+b.length);return new DataView(U.buffer).setUint32(0,j.length),U.set(j,4),U.set(b,j.length+4),U}return{readRevisions:(N,b)=>h(()=>S(N,b)),read:(N,b)=>h(async()=>{l();const O=await M(N);let j;try{j=await z(O,b)}catch(U){if(l(),Yn(U))return;throw U}if(!(!ht(j.address,N)||j.expiresAt<=Date.now())&&ht(j.revisions,await S(N.scopeIds,N.namespace)))return j}),publish:(N,b)=>h(async()=>{l();const{address:O}=N;if(!ht(N.revisions,await S(O.scopeIds,O.namespace)))return!1;const j=x(N);if(N.payload.length>b.maxEntryBytes||j.length>b.diskMaxBytes||b.diskMaxEntries<1)throw new Error("缓存条目超出容量预算");await m();const U=await p(O),L=await M(O),C=await v(),H=[],F=new Map;for(const g of C.entries){if(g.bucketName===U.name&&g.file.name===L.name)continue;const k=JSON.stringify([g.entry.address.scopeIds,g.entry.address.namespace]);let B=F.get(k);if(B||(B=await S(g.entry.address.scopeIds,g.entry.address.namespace),F.set(k,B)),g.entry.expiresAt<=Date.now()||!ht(g.entry.revisions,B)){if(!await D(g))throw new Error("缓存治理期间条目已变化")}else H.push(g)}H.sort((g,k)=>g.entry.cachedAt-k.entry.cachedAt);function $(){const g=H.filter(k=>k.bucketName===U.name);return H.length+1>nE||j.length+C.metadataBytes+H.reduce((k,B)=>k+B.size,0)>Zr||g.length+1>Math.min(b.diskMaxEntries,mr-1)||j.length+g.reduce((k,B)=>k+B.size,0)>b.diskMaxBytes}for(;$();){const g=H.filter(Q=>Q.bucketName===U.name),B=g.length+1>Math.min(b.diskMaxEntries,mr-1)||j.length+g.reduce((Q,X)=>Q+X.size,0)>b.diskMaxBytes?g[0]:H[0];if(!B||!await D(B))throw new Error("缓存容量不足或条目已变化");H.splice(H.indexOf(B),1)}await T();const K=await _(i);if(!K.some(g=>g.name===U.name)&&K.length>=mr-1)throw new Error("缓存目录超过治理上限");if(await U.create({recursive:!0,exclusive:!1},a),!ht(N.revisions,await S(O.scopeIds,O.namespace)))return!1;try{await L.create({recursive:!1,exclusive:!0},a)}catch(g){f(g),await L.stat(a)}return await L.write(j,a),l(),ht(N.revisions,await S(O.scopeIds,O.namespace))}),invalidate:(N,b)=>h(async()=>{await m();const O=n.file(`${await Qn([N,b??null])}.revision`);await w(O);try{await O.create({recursive:!1,exclusive:!0},a)}catch(j){f(j),await O.stat(a)}await O.write(di.encode(ed()),a),l();try{const{entries:j}=await v();for(const U of j){if(b!==void 0&&U.entry.address.namespace!==b||!N.every((C,H)=>U.entry.address.scopeIds[H]===C))continue;const L=await S(U.entry.address.scopeIds,U.entry.address.namespace);ht(U.entry.revisions,L)||await D(U)}await T()}catch(j){f(j),l()}})}}function Yn(e){return!!e&&typeof e=="object"&&["FILE_NOT_FOUND","ENOENT","NOT_FOUND"].includes(String(e.code))}const sE="RATE_LIMITED_BY_RUNTIME",aE="RATE_LIMITED",df=20,uf=40,lf=150,ff=20,hf=1e4,mf=45e3,gf=1,cE=300*1e3,dE=64;function gr(e,t){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:t}function uE(e,t){return typeof e=="number"&&Number.isFinite(e)&&e>=0?Math.floor(e):t}function lE(e={}){const t=e.now??Date.now,r=uE(e.coalesceWindowMs,lf),n=e.budget===!1?void 0:{ratePerSecond:Math.max(.001,gr(e.budget?.ratePerSecond,df)),burst:Math.max(1,Math.floor(gr(e.budget?.burst,uf)))},i=e.loopDetection===!1?void 0:{maxCalls:Math.max(1,Math.floor(gr(e.loopDetection?.maxCalls,ff))),windowMs:Math.max(1,Math.floor(gr(e.loopDetection?.windowMs,hf)))},o=e.circuitBreaker===!1?void 0:{failureThreshold:Math.max(1,Math.floor(gr(e.circuitBreaker?.failureThreshold,gf))),openMs:Math.max(1,Math.floor(gr(e.circuitBreaker?.openMs,mf)))},s=new Map,a=new Map,c=new Set,d=new Map,u=n?{tokens:n.burst,updatedAt:t()}:{tokens:0,updatedAt:0},f={coalesced:0,budgetRejected:0,loopRejected:0,circuitOpened:0,circuitRejected:0};let l=!1;function h(D){try{e.onReport?.(D)}catch{}}function m(D,I){if(!i)return{exceeded:!1,count:0};const v=a.get(D)??[],T=I-i.windowMs;let x=0;for(;x<v.length&&v[x]<=T;)x+=1;x>0&&v.splice(0,x);const N=v.length>=i.maxCalls;return N||(v.push(I),v.length>i.maxCalls+1&&v.splice(0,v.length-(i.maxCalls+1))),a.set(D,v),{exceeded:N,count:v.length}}function E(D){if(!n)return!0;const I=Math.max(0,D-u.updatedAt)/1e3;return u.tokens=Math.min(n.burst,u.tokens+I*n.ratePerSecond),u.updatedAt=D,u.tokens<1?!1:(u.tokens-=1,!0)}function _(D){if(!n)return 0;const I=Math.max(0,D-u.updatedAt)/1e3,v=Math.min(n.burst,u.tokens+I*n.ratePerSecond);return Math.max(0,Math.ceil((1-v)/n.ratePerSecond*1e3))}function w(D,I,v,T,x){if(!o)return;const N=d.get(I),b=(N?.open?0:N?.failures??0)+1;if(b<o.failureThreshold){d.set(I,{open:!1,openedAt:0,openMs:0,failures:b});return}const O=Math.min(Math.max(o.openMs,T),cE);d.set(I,{open:!0,openedAt:x,openMs:O,failures:b}),f.circuitOpened+=1,h({type:"circuit_opened",capability:D,endpointId:I,status:v,openMs:O,timestamp:x})}function S(D){const I=d.get(D);I&&!I.open&&d.delete(D)}function p(D){for(const[I,v]of s)!v.pending&&v.expiresAt<=D&&s.delete(I);for(;s.size>=dE;){const I=[...s].find(([,v])=>!v.pending);if(!I)break;s.delete(I[0])}}function M(D,I){if(D===void 0)return;const v=s.get(D);v?.promise===I&&(v.pending=!1)}function z(D,I){if(D===void 0)return;s.get(D)?.promise===I&&s.delete(D)}async function A(D){if(l)return D.load();const I=t();if(o){const N=d.get(D.endpointId);if(N?.open){const b=N.openedAt+N.openMs-I;if(b>0)throw f.circuitRejected+=1,h({type:"circuit_rejected",capability:D.capability,endpointId:D.endpointId,retryAfterMs:b,timestamp:I}),mE("上游已被网关限流,Runtime 熔断中,请稍后重试",{origin:"circuit",reason:"circuit_open",endpointId:D.endpointId,retryAfterMs:b});d.delete(D.endpointId)}}const v=m(D.endpointId,I);v.exceeded&&i?c.has(D.endpointId)||(c.add(D.endpointId),h({type:"loop_detected",capability:D.capability,endpointId:D.endpointId,count:v.count,windowMs:i.windowMs,timestamp:I})):c.delete(D.endpointId);const T=r>0?D.coalesceKey:void 0;if(T!==void 0){const N=s.get(T);if(N&&(N.pending||N.expiresAt>I))return f.coalesced+=1,h({type:"coalesced",capability:D.capability,endpointId:D.endpointId,timestamp:I}),N.promise;N&&s.delete(T)}if(v.exceeded&&i)throw f.loopRejected+=1,rd("检测到同一 endpoint 的高频循环调用,本次请求已在 Runtime 本地拒绝",{origin:"loop",reason:"loop",capability:D.capability,endpointId:D.endpointId,count:v.count,windowMs:i.windowMs});if(!E(I)){f.budgetRejected+=1;const N=_(I);throw h({type:"budget_exhausted",capability:D.capability,endpointId:D.endpointId,retryAfterMs:N,timestamp:I}),rd("请求过于频繁,已触发 Runtime 本地配额限制",{origin:"budget",reason:"budget",capability:D.capability,endpointId:D.endpointId,retryAfterMs:N})}T!==void 0&&p(I);const x=D.load().then(N=>(M(T,x),S(D.endpointId),N),N=>{z(T,x);const b=fE(N);throw b!==void 0&&w(D.capability,D.endpointId,b,hE(N),I),N});return T!==void 0&&s.set(T,{endpointId:D.endpointId,promise:x,expiresAt:I+r,pending:!0}),x}return{execute:A,invalidateCoalescing(D){if(D===void 0){s.clear();return}for(const[I,v]of s)D.includes(v.endpointId)&&s.delete(I)},snapshot(){return{...f,openCircuits:[...d.entries()].filter(([,D])=>D.open).map(([D])=>D)}},dispose(){l||(l=!0,s.clear(),a.clear(),c.clear(),d.clear())}}}function fE(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 hE(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 rd(e,t){return{code:sE,message:e,data:t}}function mE(e,t){return{code:aE,message:e,data:t}}const pf=3e4,yf=6e4,Zs=1440*60*1e3;function gE(e){const t=e!==!1&&(e?.enabled??!0),r=e===!1?void 0:e;return{enabled:t,debugReport:t&&r?.debugReport===!0,identityTtlMs:t?Math.max(0,Math.floor(r?.identityTtlMs??pf)):0,profileTtlMs:t?Math.max(0,Math.floor(r?.profileTtlMs??yf)):0,steamGameListTtlMs:t?pE(r?.steamGameListTtlMs):0,gateOptions:{budget:r?.budget??{ratePerSecond:df,burst:uf},coalesceWindowMs:r?.coalesceWindowMs??lf,loopDetection:r?.loopDetection??{maxCalls:ff,windowMs:hf},circuitBreaker:r?.circuitBreaker??{failureThreshold:gf,openMs:mf}}}}function pE(e){return e===void 0||!Number.isFinite(e)?Zs:Math.max(0,Math.floor(e))}function yE(e){return typeof e=="object"&&e!==null}function Te(e,t){const r=e.data;if(!yE(r)||typeof r.status!="string")throw new Error(t);return r}const Ef={auth:"optional",channel:"api",id:"heybox.account.user_base_info.envelope.get",method:"GET",path:"/account/get_user_base_info"},EE={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 Te(e,"工坊小程序详情加载失败")}};function Un(e){const t=e.runtimeAuthContextToken?.trim();return{mini_program_id:e.miniProgramId,...t?{runtime_auth_context_token:t}:{}}}function wE(e){return{challenge:e.challenge,expiresIn:e.expires_in,requestedScopes:e.requested_scopes||[],displayedScopes:e.displayed_scopes||[],consentUiVersion:e.consent_ui_version}}function IE(e){const t=Te(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=wE(r.consent_challenge)),{...t,result:n}}const AE={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=>({...Un(e.runtimeContext),challenge:e.challenge}),parse:e=>Te(e,"小程序授权取消接口响应异常")},_E={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=>Un(e.runtimeContext),parse:e=>Te(e,"小程序授权撤销接口响应异常")},DE={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=>Un(e.runtimeContext),parse(e){const t=Te(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}:{}}}}},NE={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=>({...Un(e.runtimeContext),...e.scopes?.length?{scopes:e.scopes.join(",")}:{}}),parse:e=>IE(e)},ME={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=>({...Un(e.runtimeContext),challenge:e.challenge,...e.selectedScopes.length?{selected_scopes:e.selectedScopes.join(",")}:{}}),parse(e){const t=Te(e,"小程序登录确认接口响应异常");return{...t,result:{code:t.result.code,expiresIn:t.result.expires_in,scopes:t.result.scopes}}}},SE=64;function wf(e){const t=e.ttlMs,r=Math.max(1,Math.floor(e.maxEntries??SE)),n=e.now??Date.now,i=new Map,o=new Map;let s=0,a=!1;function c(f){for(const[l,h]of i)h.expiresAt<=f&&i.delete(l)}function d(f,l,h){if(a||t<=0||h!==s)return;const m=n();for(c(m),i.delete(f);i.size>=r;){const E=i.keys().next();if(E.done)break;i.delete(E.value)}i.set(f,{expiresAt:m+t,value:l})}function u(f,l){if(a)return l();if(t>0){const _=i.get(f);if(_&&_.expiresAt>n())return Promise.resolve(_.value);_&&i.delete(f)}const h=o.get(f);if(h)return h;const m=s,E=l().then(_=>(d(f,_,m),_)).finally(()=>{o.get(f)===E&&o.delete(f)});return o.set(f,E),E}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 bE(e,t){return t?e?"server":"local":"legacy"}function TE(e,t){if(e==="local")throw y("SERVER_API_REQUIRED",`${t} 需要 effective network 启用后才能使用`)}const vE=["baseURL","errorMode","jsonParseMode","observability","queryEncoding","responseType","security"],OE=new Set(["auth","body","bodyEncoding","channel","failurePresentation","headers","id","method","parse","path","query","timeout"]),RE=/authorization|cookie|pkey|password|secret|token/i,If=/authorization|cookie|pkey|token|password|secret/i;function mt(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function PE(e){for(const t of Object.keys(e))if(!OE.has(t))throw new Le(`endpoint 字段不受 hb-sdk-runtime private mapper 支持: ${t}`);for(const t of vE)if(Object.prototype.hasOwnProperty.call(e,t)&&mt(e,t)!==void 0)throw new Le(`endpoint 字段不受 hb-sdk-runtime private mapper 支持: ${t}`);if(mt(e,"bodyEncoding")!==void 0&&mt(e,"bodyEncoding")!=="json"&&mt(e,"bodyEncoding")!=="form")throw new Le("endpoint bodyEncoding 不受 HostNetworkPort 支持");if(mt(e,"failurePresentation")!==void 0&&mt(e,"failurePresentation")!=="none")throw new Le("endpoint failurePresentation 必须为 none");if(mt(e,"auth")!==void 0&&mt(e,"auth")!=="none"&&mt(e,"auth")!=="optional"&&mt(e,"auth")!=="required")throw new Le("endpoint auth 必须为 none、optional 或 required")}function oo(e){if(Array.isArray(e))return e.map(oo);if(!e||typeof e!="object")return e;const t=e,r={};for(const[n,i]of Object.entries(t))RE.test(n)||(r[n]=oo(i));return r}function nd(e){if(!e)return;const t={};for(const[r,n]of Object.entries(e))If.test(r)||(t[r]=n);return t}function kE(e){if(!e)return;const t=Object.keys(e).find(r=>If.test(r));if(t)throw new Le(`endpoint 禁止声明 credential-bearing header: ${t}`)}class xn 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 id=1440*60*1e3,CE=/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun)\b/i;function LE(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,id):void 0}if(!CE.test(n))return;const i=Date.parse(n);if(!Number.isFinite(i))return;const o=i-t();return o>0?Math.min(o,id):void 0}function UE(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 Af(e,t){Object.defineProperty(e,"cause",{configurable:!1,enumerable:!1,value:t,writable:!1})}class Cr extends Error{code="INTERNAL_ENDPOINT_REQUEST_FAILED";endpointId;constructor(t){super(`内部 endpoint 请求执行失败: ${t.endpointId}`),this.name="InternalEndpointRequestError",this.endpointId=t.endpointId,Af(this,t.cause),Object.setPrototypeOf(this,new.target.prototype)}}class zn extends Error{code="INTERNAL_ENDPOINT_PARSE_FAILED";endpointId;constructor(t){super(`内部 endpoint 响应解析失败: ${t.endpointId}`),this.name="InternalEndpointParseError",this.endpointId=t.endpointId,Af(this,t.cause),Object.setPrototypeOf(this,new.target.prototype)}}function xE(e,t,r,n,i,o,s,a){return{config:{auth:e.auth,body:oo(i),bodyEncoding:e.bodyEncoding,channel:e.channel,credentials:s.credentials,headers:nd(o),method:e.method,metadata:{endpointId:e.id},query:oo(n),timeout:e.timeout,url:r},data:a.data,headers:nd(a.headers)||{},status:a.status,statusText:a.statusText}}async function ko(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(PE(t),typeof t.id!="string"||!t.id)throw new Le("endpoint id 必须为非空字符串");if(!["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"].includes(t.method))throw new Le("endpoint method 不受 HostNetworkPort 支持");const i=typeof t.path=="function"?await t.path(r):t.path;if(typeof i!="string"||!i)throw new Le("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;kE(a);const c=async()=>{let f;try{f=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(h){throw h instanceof Le?h:new Cr({endpointId:t.id,cause:h})}if(f.status<200||f.status>=300)throw new xn({endpointId:t.id,status:f.status,responseData:f.data,retryAfterMs:LE(f.headers)});const l=xE(t,r,i,o,s,a,n,f);if(t.parse)try{return await t.parse(l,r)}catch(h){throw new zn({endpointId:t.id,cause:h})}return l.data},d=n.gate;if(!d)return c();const u=UE(t,o,s,n.credentials);return d.gate.execute({capability:d.capability,endpointId:t.id,...u===void 0?{}:{coalesceKey:u},load:c})}const zE=new Set(["MINIPROGRAM_UNAVAILABLE","RUNTIME_CONTEXT_INVALID","CAPABILITY_NOT_GRANTED","AUTHORIZATION_CONTEXT_CHANGED","SERVER_API_REQUIRED","AUTHORIZATION_CANCELLED"]),jE=new Set(Pr),tc="steam_account",_f=new Set(Pr.filter(e=>e!==tc)),BE=1e3;function HE(e){const t=new Set,r=wf({ttlMs:Math.max(0,Math.floor(e.identityTtlMs??pf))}),n=new Set;let i=0,o=!1,s=Promise.resolve(),a;const c=e.steamAccount===!0,d=e.userDataMode??bE(e.networkEnabled===!0,c),u=e.requestPolicyEnabled!==!1,f=e.requestGate?{capability:"auth",gate:e.requestGate}:void 0;async function l(){if(!c&&!e.authorizationContext)return{};if(!e.authorizationContext)throw y("METHOD_FORBIDDEN","新能力版本缺少 Runtime auth context Port");let C;try{C=await e.authorizationContext.get(e.operationContext)}catch(F){throw Js(F)?Jo(F.code,F.message,F):Jo("REQUEST_FAILED","读取 Runtime auth context 失败",F)}if(C.steamAccount!==c||C.userDataMode!==d)throw y("AUTHORIZATION_CONTEXT_CHANGED","Runtime auth context 已变化,请重新打开小程序");const H=C.token.trim();if(!H)throw y("REQUEST_FAILED","Runtime auth context 为空");return{runtimeAuthContextToken:H}}const h=e.account.onChange(C=>{if(m(),E("heybox_app_login_change",C?{isHeyboxAppLoggedIn:!0}:{isHeyboxAppLoggedIn:!1,accountKey:null}),C&&e.account.getAccountKey){const H=i;z().then(F=>{!o&&i===H&&E("heybox_app_login_change",F)}).catch(()=>{})}});function m(){i+=1,a?.abort(),r.invalidate(),e.requestGate?.invalidateCoalescing(),n.clear()}function E(C,H){C==="user_info_authorization_change"&&QE(H)&&r.invalidate();for(const F of t)try{F(C,H)}catch{}}function _(){const C=e.identity.get()?.miniProgramId?.trim();if(!C)throw y("INVALID_STATE","当前能力缺少 canonical 小程序身份");return C}function w(){if(o||e.operationContext.signal.aborted)throw y("RUNTIME_DESTROYED","小程序 Runtime 已终止")}async function S(){w();let C;try{C=await e.account.getCurrentUserId(e.operationContext)}catch(H){throw cd(H,e.operationContext.signal,"读取小黑盒账号失败")}return typeof C=="string"&&C.trim()?C.trim():void 0}async function p(C,H){const F=await S();if(i!==H||F!==C)throw y("AUTHORIZATION_CONTEXT_CHANGED","授权期间账号上下文已变化,请重新操作")}async function M(C,H,F=_()){if(!e.account.getAccountKey)throw y("METHOD_FORBIDDEN","Host 不支持持久化账号比较");let $;try{$=await e.account.getAccountKey(F,C,e.operationContext)}catch{throw w(),y("REQUEST_FAILED","读取本地账号标识失败")}if(await p(C,H),_()!==F)throw y("AUTHORIZATION_CONTEXT_CHANGED","读取期间小程序上下文已变化");if(typeof $!="string"||!$.trim())throw y("INVALID_RESPONSE","Host 返回了无效的账号标识");return $}async function z(){const C=_(),H=i,F=await S();if(w(),i!==H)throw y("AUTHORIZATION_CONTEXT_CHANGED","读取期间账号上下文已变化");return F?{isHeyboxAppLoggedIn:!0,accountKey:await M(F,H,C)}:{isHeyboxAppLoggedIn:!1,accountKey:null}}async function A(C){w();try{await e.account.ensureAuthenticated({trustedUserGesture:C,reason:"runtime_auth",signal:e.operationContext.signal})}catch(F){throw cd(F,e.operationContext.signal,"小黑盒登录失败")}const H=await S();if(!H)throw y("HEYBOX_APP_LOGIN_REQUIRED","请先登录小黑盒");return H}async function D(C,H,F=e.operationContext.signal){try{if(F.aborted)throw Ks();return await qE(ko(e.network,C,H,{...e.operationContext,credentials:"heybox-session",signal:F,...f?{gate:f}:{}}),F)}catch($){throw e.operationContext.signal.aborted?y("RUNTIME_DESTROYED","小程序 Runtime 已终止"):$ instanceof Le?y("REQUEST_UNSUPPORTED",$.message):$ instanceof zn?y("INVALID_RESPONSE","授权接口响应不合法"):$ instanceof Cr?y("REQUEST_FAILED","授权请求失败"):$ instanceof xn?u&&($.status===403||$.status===429)?y("RATE_LIMITED","授权请求已被网关限流,请稍后重试",{status:$.status,...$.retryAfterMs===void 0?{}:{retryAfterMs:$.retryAfterMs}}):y("REQUEST_FAILED",$.message):Js($)?$:y("REQUEST_FAILED","授权请求失败")}}async function I(C,H){await D(AE,{runtimeContext:{miniProgramId:C,...await l()},challenge:H}).catch(()=>{})}function v(C){const H=async()=>{const $=sd(e.operationContext.signal);a=$;try{return await C($.signal)}finally{a===$&&(a=void 0),$.abort()}},F=s.then(H,H);return s=F.then(()=>{},()=>{}),F}async function T(C,H,F,$,K){if(!F)throw await I(C,H.challenge),y("USER_GESTURE_REQUIRED","展示授权确认需要用户手势");if(!e.authPresentation)throw await I(C,H.challenge),y("AUTHORIZATION_PRESENTATION_UNAVAILABLE","授权确认界面不可用");return v(async g=>{await p($,K);const k=await x(C,H.displayedScopes,g);await p($,K);let B;try{B=await e.authPresentation.confirmAuthorization({miniProgramId:C,scopes:H.displayedScopes,...k,signal:g})}catch(X){throw e.operationContext.signal.aborted?y("RUNTIME_DESTROYED","小程序 Runtime 已终止"):(await p($,K),await I(C,H.challenge),Jo("REQUEST_FAILED","授权确认界面执行失败",X))}if(await p($,K),B.status!=="granted")throw await I(C,H.challenge),y("AUTHORIZATION_CANCELLED","用户取消授权");const Q=GE(B.grantedScopes,H.displayedScopes,c);if(!Q.includes("identity"))throw await I(C,H.challenge),y("AUTHORIZATION_CANCELLED","用户拒绝授权");return Q})}async function x(C,H,F){const $=sd(F),K=setTimeout(()=>$.abort(),BE);try{const g=$E(e.miniProgramPresentation),[k,B]=await Promise.all([g?Promise.resolve(g):N(C,$.signal),H.includes("profile")?b($.signal):Promise.resolve(void 0)]);return{...k?{miniProgram:k}:{},...B?{userProfile:B}:{}}}finally{clearTimeout(K),$.abort()}}async function N(C,H){try{const F=e.identity.get()?.version?.trim(),$=await D(EE,{mini_program_id:C,...F?{miniprogram_version:F}:{}},H),K=pr($,"小程序公开资料"),g=Nr(K.name),k=Nr(K.icon_url);return g||k?{...g?{name:g}:{},...k?{avatarUrl:k}:{}}:void 0}catch{return}}async function b(C){try{const H=await D(Ef,void 0,C),F=pr(H,"账号基础信息"),$=Nr(F.display_username),K=Nr(F.display_avatar);return $||K?{...$?{nickname:$}:{},...K?{avatar:K}:{}}:void 0}catch{return}}async function O(C,H){if(TE(d,"auth.login"),!c&&C.includes(tc))throw y("INVALID_PARAMS","auth.login 参数不合法");const F=_(),$=await A(H),K=i,g=await D(NE,{runtimeContext:{miniProgramId:F,...await l()},scopes:C});await p($,K);const k=pr(g,"小程序登录"),B=ad(k,"loginCode"),Q=ad(k,"consentChallenge");if(B===Q)throw y("INVALID_RESPONSE","小程序登录 begin 必须返回 exact oneof");let X;if(B)X=od(k.loginCode,c);else{const ie=FE(k.consentChallenge,c),ue=await T(F,ie,H,$,K);await p($,K);const Ee=await D(ME,{runtimeContext:{miniProgramId:F,...await l()},challenge:ie.challenge,selectedScopes:ue});if(await p($,K),X=od(pr(Ee,"小程序登录确认"),c),X.scopes.some(me=>!ue.includes(me)))throw y("INVALID_RESPONSE","小程序登录确认返回了未选择的 scope")}n.clear();for(const ie of X.scopes)n.add(ie);r.invalidate();const ne=e.account.getAccountKey?await M($,K,F):void 0;return E("heybox_app_login_change",{isHeyboxAppLoggedIn:!0,...ne===void 0?{}:{accountKey:ne}}),E("user_info_authorization_change",Xo(n,c)),{...X,...ne===void 0?{}:{accountKey:ne}}}async function j(C,H){const F=i,$=await D(DE,{runtimeContext:{miniProgramId:H,...await l()}});await p(C,F);const K=VE(pr($,"用户本地身份"),c);for(const g of c?Pr:_f)n.add(g);return E("user_info_authorization_change",Xo(n,c)),K}function U(C){w();const H=_(),F=`${C}\0${H}\0${i}\0${c}`;return r.read(F,()=>j(C,H))}async function L(C){if(!C)throw y("USER_GESTURE_REQUIRED","撤销授权需要用户手势");const H=_(),F=i,$=await S();if(!$)throw y("HEYBOX_APP_LOGIN_REQUIRED","请先登录小黑盒");const K=await D(_E,{runtimeContext:{miniProgramId:H,...await l()}});await p($,F),pr(K,"用户授权撤销"),m(),E("user_info_authorization_change",{identity:"denied",profile:"denied",...c?{steam_account:"denied"}:{}})}return{getAccountState:z,login:O,async confirmGameSaves(C){if(!C)throw y("USER_GESTURE_REQUIRED","读取游戏存档需要点击按钮授权");if(!e.authPresentation)throw y("AUTHORIZATION_PRESENTATION_UNAVAILABLE","授权确认界面不可用");const H=_(),F=await A(C),$=i;await v(async K=>{await p(F,$);const g=await x(H,["identity"],K),k=await e.authPresentation.confirmAuthorization({miniProgramId:H,scopes:["identity","game_saves"],...g,signal:K});if(await p(F,$),k.status!=="granted"||!k.grantedScopes.includes("game_saves")||!k.grantedScopes.includes("identity"))throw y("AUTHORIZATION_CANCELLED","用户取消存档授权")})},getOrCreateLocalIdentity:U,invalidateLocalIdentity(){r.invalidate()},getAuthorization:()=>Xo(n,c),revoke:L,onEvent(C){return t.add(C),()=>t.delete(C)},dispose(){o||(o=!0,m(),r.dispose(),h(),t.clear())}}}function Jo(e,t,r){const n=y(e,t);return Object.defineProperty(n,"cause",{configurable:!0,enumerable:!1,value:r}),n}function pr(e,t){if(!re(e))throw y("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":zE.has(r)?r:"REQUEST_FAILED";throw y(n,r)}if(!re(e.result))throw y("INVALID_RESPONSE",`${t} result 必须是对象`);return e.result}function od(e,t){if(!re(e))throw y("INVALID_RESPONSE","login code 必须是对象");const r=so(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 y("INVALID_RESPONSE","login code 响应不合法");return{code:e.code,expiresIn:Number(e.expiresIn),scopes:r}}function FE(e,t){if(!re(e))throw y("INVALID_RESPONSE","授权 challenge 必须是对象");const r=so(e.requestedScopes,"challenge requestedScopes",t),n=so(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 y("INVALID_RESPONSE","授权 challenge 响应不合法");return{challenge:e.challenge.trim(),requestedScopes:r,displayedScopes:n}}function VE(e,t){if(!re(e)||typeof e.appUserId!="string"||!e.appUserId.trim())throw y("INVALID_RESPONSE","本地身份 appUserId 必须是非空字符串");const r=e.appUserId.trim();if(!t)return{appUserId:r};if(e.steamId!==void 0&&typeof e.steamId!="string")throw y("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 GE(e,t,r){const n=so(e,"授权选择 scopes",r);if(n.some(i=>!t.includes(i)))throw y("INVALID_RESPONSE","授权选择包含未展示的 scope");return n}function Nr(e){return typeof e=="string"&&e.trim()?e.trim():void 0}function $E(e){const t=Nr(e?.name),r=Nr(e?.avatarUrl);return t||r?{...t?{name:t}:{},...r?{avatarUrl:r}:{}}:void 0}function sd(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 qE(e,t){return t.aborted?Promise.reject(Ks()):new Promise((r,n)=>{let i=!1;const o=a=>{i||(i=!0,t.removeEventListener("abort",s),a())},s=()=>o(()=>n(Ks()));t.addEventListener("abort",s,{once:!0}),e.then(a=>o(()=>r(a)),a=>o(()=>n(a)))})}function Ks(){const e=new Error("The operation was aborted");return e.name="AbortError",e}function so(e,t,r){const n=r?jE:_f;if(!Array.isArray(e)||e.some(i=>typeof i!="string"||!n.has(i))||new Set(e).size!==e.length)throw y("INVALID_RESPONSE",`${t} 不合法`);return[...e]}function Xo(e,t){const r=t?Pr:Pr.filter(n=>n!==tc);return Object.fromEntries(r.map(n=>[n,e.has(n)?"granted":"not_requested"]))}function ad(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function QE(e){return re(e)?Object.values(e).some(t=>t==="denied"):!1}function Js(e){return re(e)&&typeof e.code=="string"&&typeof e.message=="string"}function cd(e,t,r){return t.aborted?y("RUNTIME_DESTROYED","小程序 Runtime 已终止"):Js(e)?e:y("REQUEST_FAILED",r)}const YE=new Set(Pr);function WE(e){return{[Ni]:async t=>{if(t!==void 0)throw y("INVALID_PARAMS","auth.getAccountState 不接受参数");return e.authorization.getAccountState()},[Mi]:async(t,r)=>e.authorization.login(ZE(t),r.trustedUserGesture)}}function ZE(e){if(e===void 0)return["identity"];if(!re(e)||Object.keys(e).some(t=>t!=="scopes"))throw dd();if(e.scopes===void 0)return["identity"];if(!Array.isArray(e.scopes)||e.scopes.some(t=>typeof t!="string"||!YE.has(t))||new Set(e.scopes).size!==e.scopes.length)throw dd();return[...e.scopes]}function dd(){return y("INVALID_PARAMS","auth.login 参数不合法")}const KE={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 Te(e,"排行榜记录删除接口响应异常")}},JE={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 Te(e,"当前排行榜记录接口响应异常")}},XE={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 Te(e,"排行榜信息接口响应异常")}},ew={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 Te(e,"排行榜列表接口响应异常")}},tw={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 Te(e,"排行榜提交接口响应异常")}},rw={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 Co(e,t,r){e.assertUsable();const n={request:async(i,o)=>(e.assertUsable(),e.network.request(i,o))};try{return await fe(()=>ko(n,t,r,{...e.operationContext,credentials:"heybox-session",...e.gate?{gate:e.gate}:{}}),e.operationContext.signal)}catch(i){if(uo(i)||an(i,"REQUEST_UNSUPPORTED")||an(i,"RATE_LIMITED")||an(i,"RATE_LIMITED_BY_RUNTIME"))throw i;if(i instanceof Le)throw ee("REQUEST_UNSUPPORTED",`当前 Host 不支持该${e.subject}请求`);if(i instanceof Cr&&an(i.cause,"INVALID_STATE"))throw i.cause;if(i instanceof xn){if(e.requestPolicyEnabled!==!1&&(i.status===403||i.status===429))throw ee("RATE_LIMITED",`${e.subject}请求已被网关限流,请稍后重试`,{status:i.status,...i.retryAfterMs===void 0?{}:{retryAfterMs:i.retryAfterMs}});if(i.status===401||i.status===403)throw ee("UNAUTHORIZED","当前用户未登录");const o=nw(i.responseData);if(Ie(o)&&typeof o.status=="string"&&o.status!=="ok"){const s=Ie(o.result)?Mt(o.result.error_code):void 0;if(o.status==="login"||o.status==="relogin"||ao(o.result)||ao(o)||s&&/^[A-Z][A-Z0-9_]+$/.test(s))throw Df(o,e.subject)}throw ee("HTTP_ERROR",`${e.subject}请求失败(HTTP ${i.status})`,{status:i.status})}throw i instanceof Cr?co(e.subject):i instanceof zn?Ne(i.cause instanceof Error?i.cause.message:`${e.subject}响应不合法`):Ne(i instanceof Error?i.message:`${e.subject}响应不合法`)}}function st(e,t,r){if(!Ie(e)||typeof e.status!="string")throw Ne(`${t} 响应必须是标准信封`);if(e.status!=="ok")throw Df(e,r);if(!Object.prototype.hasOwnProperty.call(e,"result")||e.result===void 0||e.result===null)throw Ne(`${t} 响应缺少 result`);return e.result}function Lo(e,t){try{return e.onChange(t)}catch(r){if(an(r,Fl))return()=>{};throw r}}function Df(e,t){if(e.status==="login"||e.status==="relogin")throw ee("UNAUTHORIZED",Mt(e.msg)||"当前用户未登录");if(Ie(e.result)){const i=Mt(e.result.error_code);if(i&&/^[A-Z][A-Z0-9_]+$/.test(i))throw ee(i,Mt(e.result.message)||Mt(e.msg)||`${t}请求失败`)}const r=ao(e.result)??ao(e),n=Mt(r?.user_message)||Mt(e.msg)||Mt(r?.developer_message)||`${t}请求失败`;throw r?ee(iw(r),n,{status:e.status,sbe:r}):ee("HEYBOX_API_ERROR",n,{status:e.status})}function nw(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return}}function ao(e){return Ie(e)&&Ie(e.sbe)?e.sbe:void 0}function iw(e){const t=Mt(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 rw[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 Ie(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Mt(e){return typeof e=="string"&&e.trim()?e.trim():void 0}function an(e,t){return Ie(e)&&e.code===t}function ee(e,t,r){return r===void 0?{code:e,message:t}:{code:e,message:t,data:r}}function Ne(e){return ee("INVALID_RESPONSE",e)}function co(e){return ee("REQUEST_FAILED",`${e}请求失败`)}function uo(e){return e instanceof Error&&e.name==="AbortError"}const ow="default",Vt="排行榜",sw=/^[A-Za-z0-9_-]{1,64}$/,aw=300*1e3,cw=250,dw=3;class uw{constructor(t){this.options=t,this.requestGateContext=t.requestGate?{capability:"cloud",gate:t.requestGate}:void 0,this.unsubscribeAccountChange=Lo(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(tw,{miniProgramId:n,...t});this.assertAccountGeneration(r);const o=st(i,bt,Vt);return this.invalidateMutableReads(this.createBucketKey(n,t.key)),es(o,bt)}getList(t){this.assertUsable();const r=this.readMiniProgramId(),n=this.createBucketKey(r,t.key),i=Jr("list",t.limit,t.cursor??null);return this.read(n,"list",i,async()=>{const o=await this.request(ew,{miniProgramId:r,...t}),s=st(o,at,Vt);if(!Ie(s)||!Array.isArray(s.entries)||typeof s.has_more!="boolean")throw Ne(`${at} 返回值不合法`);if(s.cursor!==void 0&&s.cursor!==null&&typeof s.cursor!="string")throw Ne(`${at} 返回的 cursor 必须是字符串`);return{entries:s.entries.map(a=>es(a,at)),...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=Jr("current",i);return this.read(o,"current",s,async()=>{const a=await this.request(JE,{miniProgramId:n,...t}),c=st(a,xt,Vt);if(!Ie(c))throw Ne(`${xt} 返回值必须是对象`);return c.entry===void 0||c.entry===null?void 0:es(c.entry,xt)})}async deleteCurrentUserEntry(t){this.assertUsable();const r=this.accountGeneration,n=this.readMiniProgramId();await this.requireCurrentUser(r);const i=await this.request(KE,{miniProgramId:n,...t});this.assertAccountGeneration(r);const o=st(i,ir,Vt);if(this.invalidateMutableReads(this.createBucketKey(n,t.key)),!Ie(o)||typeof o.deleted!="boolean")throw Ne(`${ir} 返回的 deleted 必须是布尔值`);return{deleted:o.deleted}}getInfo(t){this.assertUsable();const r=this.readMiniProgramId(),n=this.createBucketKey(r,t.key);return this.read(n,"info",Jr("info"),async()=>{const i=await this.request(XE,{miniProgramId:r,...t}),o=st(i,wt,Vt);if(!Ie(o)||typeof o.key!="string"||!sw.test(o.key))throw Ne(`${wt} 返回的 key 不合法`);if(t.key!==void 0&&o.key!==t.key)throw Ne(`${wt} 返回的 key 与请求不一致`);if(o.order!=="asc"&&o.order!=="desc")throw Ne(`${wt} 返回的 order 必须是 asc 或 desc`);if(typeof o.rank_limit!="number"||!Number.isInteger(o.rank_limit)||o.rank_limit<0)throw Ne(`${wt} 返回的 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=Jr(t,n),d=this.inflight.get(c);if(d)return d.promise;const u=this.accountGeneration,f=o?.generation,l=i().then(h=>(this.assertAccountGeneration(u),o&&s&&o.generation===f&&(r==="list"?s.size>=cw&&s.delete(s.keys().next().value):s.clear(),s.set(n,{expiresAt:Date.now()+aw,value:h})),h)).finally(()=>{this.inflight.get(c)?.promise===l&&this.inflight.delete(c),o&&this.removeEmptyBucket(t,o)});return this.inflight.set(c,{bucketKey:t,promise:l}),l}getOrCreateBucket(t){const r=this.buckets.get(t);if(r)return r;if(this.pruneExpiredBuckets(),this.buckets.size>=dw)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)ud(n,t),this.isBucketEmpty(r,n)&&this.buckets.delete(r)}removeEmptyBucket(t,r){ud(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 fe(()=>this.options.account.getCurrentUserId(this.options.operationContext),this.options.operationContext.signal)}catch(n){throw uo(n)?n:co(Vt)}if(this.assertAccountGeneration(t),typeof r!="string"||!r.trim())throw ee("UNAUTHORIZED","当前用户未登录");return r.trim()}readMiniProgramId(){const t=this.options.identity.get()?.miniProgramId.trim();if(!t)throw ee("INVALID_STATE","canonical mini-program identity 尚未绑定");return t}createBucketKey(t,r){return Jr(t,r??ow)}assertAccountGeneration(t){if(this.assertUsable(),t!==this.accountGeneration)throw ee("UNAUTHORIZED","登录状态已变化,请重试")}request(t,r){return Co({network:this.options.network,operationContext:this.options.operationContext,...this.requestGateContext?{gate:this.requestGateContext}:{},...this.options.requestPolicyEnabled===void 0?{}:{requestPolicyEnabled:this.options.requestPolicyEnabled},subject:Vt,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(pe(this.options.operationContext.signal),this.disposed)throw ee("INVALID_STATE","Cloud capability 已释放")}}function lw(e){return new uw(e)}function es(e,t){if(!Ie(e))throw Ne(`${t} 返回的 entry 必须是对象`);if(typeof e.ranked!="boolean")throw Ne(`${t} 返回的 ranked 必须是布尔值`);if(typeof e.rank!="number"||!Number.isInteger(e.rank)||(e.ranked?e.rank<=0:e.rank!==0))throw Ne(`${t} 返回的 rank/ranked 不合法`);if(typeof e.app_user_id!="string"||!e.app_user_id.trim())throw Ne(`${t} 返回的 appUserId 必须是非空字符串`);if(typeof e.score!="number"||!Number.isFinite(e.score))throw Ne(`${t} 返回的 score 必须是有限数字`);if(!Ie(e.extra))throw Ne(`${t} 返回的 extra 必须是对象`);if(typeof e.created_at!="number"||!Number.isFinite(e.created_at)||typeof e.updated_at!="number"||!Number.isFinite(e.updated_at))throw Ne(`${t} 返回的时间字段必须是有限数字`);return{appUserId:e.app_user_id,createdAt:e.created_at,extra:e.extra,rank:e.rank,ranked:e.ranked,score:e.score,updatedAt:e.updated_at}}function ud(e,t){for(const r of Object.values(e.caches))for(const[n,i]of r)i.expiresAt<=t&&r.delete(n)}function Jr(...e){return JSON.stringify(e)}const fw={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 Te(e,"云端存储删除接口响应异常")}},ld={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 Te(e,"云端存储读取接口响应异常")}},fd={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 Te(e,"云端存储 key 列表接口响应异常")}},hw={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 Te(e,"云端存储写入接口响应异常")}},Gt="云端存储",mw=3e4,gw=128,pw=500;class yw{constructor(t){this.options=t,this.requestGateContext=t.requestGate?{capability:"cloud.storage",gate:t.requestGate}:void 0,this.unsubscribeAccountChange=Lo(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=st(await this.request(fd,{}),or,Gt);if(this.assertAccountGeneration(t),!Ie(r)||r.keys!==void 0&&(!Array.isArray(r.keys)||!r.keys.every(i=>typeof i=="string")))throw Ne("cloud.storage.getKeys 返回的 keys 必须是字符串数组");const n=new Set(r.keys??[]);for(const i of this.unfinished)i.kind==="set"?n.add(i.key):n.delete(i.key);return[...n]}async enqueue(t,r,n){this.assertUsable(),this.readMiniProgramId();const i=this.accountGeneration;return await this.requireCurrentUser(i),this.assertAccountGeneration(i),t==="set"&&this.blockedKeys.has(r)?Promise.reject(this.blockedKeys.get(r)):new Promise((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"?pw: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=st(await this.request(fw,{key:t}),Rr,Gt);if(this.assertAccountGeneration(r.generation),!Ie(i)||i.deleted!==void 0&&typeof i.deleted!="boolean")throw Ne("删除结果不合法");this.writeCache(t,{value:"",found:!1,version:0,revision:""}),this.blockedKeys.delete(t)}else{const i=await this.readStored(t,r.generation,!0);if(this.assertAccountGeneration(r.generation),!Number.isSafeInteger(i.version+1))throw Ne("云存储版本超出安全整数范围");const o=st(await this.request(hw,{key:t,value:r.value,expectedVersion:i.version,expectedRevision:i.revision}),Or,Gt);if(this.assertAccountGeneration(r.generation),!Ie(o)||o.success!==!0)throw Ne("云存储写入结果不合法");const s=hd({...o,found:!0,value:r.value});if(s.version!==i.version+1||i.found&&s.revision!==i.revision)throw Ne("写入版本凭证不匹配");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(ld,{key:t}).then(c=>{this.assertAccountGeneration(r);const d=hd(st(c,vr,Gt));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>=gw&&this.cache.delete(this.cache.keys().next().value),this.cache.set(t,{expiresAt:Date.now()+mw,value:r})}invalidateRead(t){this.keyGenerations.set(t,(this.keyGenerations.get(t)??0)+1),this.inflight.delete(t),this.options.requestGate?.invalidateCoalescing([ld.id,fd.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(ee("INVALID_STATE","Cloud capability 已释放")))}invalidateForAccountChange(){this.purge(ee("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 fe(()=>this.options.account.getCurrentUserId(this.options.operationContext),this.options.operationContext.signal)}catch(o){throw uo(o)?o:co(Gt)}if(this.assertAccountGeneration(t),this.hasAccountObservation&&(n?.trim()||void 0)!==this.observedUserId)throw this.invalidateForAccountChange(),ee("UNAUTHORIZED","登录状态已变化,请重试");const i=JSON.stringify([r,n]);if(this.boundScope!==void 0&&this.boundScope!==i)throw this.invalidateForAccountChange(),ee("UNAUTHORIZED","登录状态已变化,请重试");if(typeof n!="string"||!n.trim())throw ee("UNAUTHORIZED","当前用户未登录");return this.boundScope=i,this.boundUserId=n.trim(),n}readMiniProgramId(){const t=this.options.identity.get()?.miniProgramId.trim();if(!t)throw ee("INVALID_STATE","canonical mini-program identity 尚未绑定");return t}assertAccountGeneration(t){if(this.assertUsable(),t!==this.accountGeneration)throw ee("UNAUTHORIZED","登录状态已变化,请重试")}async request(t,r){const n=this.accountGeneration;if(this.assertUsable(),!this.options.authorizationContext)throw ee("METHOD_FORBIDDEN","云端存储缺少受信运行上下文");let i;try{i=await fe(()=>this.options.authorizationContext.get(this.options.operationContext),this.options.operationContext.signal)}catch(s){throw uo(s)?s:co(Gt)}this.assertAccountGeneration(n);const o=i.token.trim();if(!o||i.expiresAt<=Date.now())throw ee("UNAUTHORIZED","小程序运行上下文无效,请重新打开");return Co({network:this.options.network,operationContext:this.options.operationContext,...this.requestGateContext?{gate:this.requestGateContext}:{},...this.options.requestPolicyEnabled===void 0?{}:{requestPolicyEnabled:this.options.requestPolicyEnabled},subject:Gt,assertUsable:()=>this.assertAccountGeneration(n)},t,{...r,runtimeAuthContextToken:o})}assertUsable(){if(pe(this.options.operationContext.signal),this.disposed)throw ee("INVALID_STATE","Cloud capability 已释放")}}function Ew(e){return new yw(e)}function hd(e){if(!Ie(e))throw Ne("云存储读取结果必须是对象");const t=e.found??!1,r=e.value??"",n=e.version??0,i=e.revision??"";if(typeof t!="boolean"||typeof r!="string"||typeof n!="number"||!Number.isSafeInteger(n)||n<0||typeof i!="string")throw Ne("云存储读取结果不合法");if(t&&(n===0||!/^[0-9a-f]{24}$/.test(i)||/^0+$/.test(i)))throw Ne("云存储版本凭证不合法");return t?{value:r,found:t,version:n,revision:i}:{value:"",found:!1,version:0,revision:""}}const ww=/^[A-Za-z0-9_-]{1,64}$/,md=20,Iw=100,gd=2048,Aw=/^[A-Za-z0-9_-]{1,128}$/,pd=16*1024;function _w(e){const t=lw(e),r=Ew(e);return{handlers:{[bt]:async i=>t.submit(Dw(i)),[at]:async i=>t.getList(Nw(i)),[xt]:async i=>t.getCurrentUserEntry(ts(i,xt)),[ir]:async i=>t.deleteCurrentUserEntry(ts(i,ir)),[wt]:async i=>t.getInfo(ts(i,wt)),[vr]:async i=>r.getItem(yd(i,vr)),[Or]:async i=>{const{key:o,value:s}=Mw(i);return r.setItem(o,s)},[Rr]:async i=>r.removeItem(yd(i,Rr)),[or]:async i=>(bw(i),r.getKeys())},dispose:()=>{t.dispose(),r.dispose()}}}function Dw(e){const t=$r(e,bt,!1);if(qr(t,["key","score","extra"],bt),typeof t.score!="number"||!Number.isFinite(t.score)||Math.abs(t.score)>Number.MAX_SAFE_INTEGER)throw Ye("INVALID_PARAMS","cloud.leaderboard.submit score 必须是有限安全数字");return{...rc(t.key,bt),score:t.score,...t.extra===void 0?{}:{extra:Tw(t.extra)}}}function Nw(e){if(e===void 0)return{limit:md};const t=$r(e,at,!0);qr(t,["key","limit","cursor"],at);const r=t.limit===void 0?md:t.limit;if(typeof r!="number"||!Number.isInteger(r)||r<=0||r>Iw)throw Ye("INVALID_PARAMS","cloud.leaderboard.getList limit 必须是 1-100 的整数");if(t.cursor!==void 0&&typeof t.cursor!="string")throw Ye("INVALID_PARAMS","cloud.leaderboard.getList cursor 必须是字符串");return{...rc(t.key,at),limit:r,...t.cursor===void 0?{}:{cursor:t.cursor}}}function ts(e,t){if(e===void 0)return{};const r=$r(e,t,!0);return qr(r,["key"],t),rc(r.key,t)}function yd(e,t){const r=$r(e,t,!1);return qr(r,["key"],t),Nf(r.key,t)}function Mw(e){const t=Or,r=$r(e,t,!1);qr(r,["key","value"],t);const n=Nf(r.key,t);if(typeof r.value!="string")throw Ye("INVALID_PARAMS",`${t} value 必须是字符串`);if(Sw(r.value))throw Ye("INVALID_PARAMS",`${t} value 不能包含不成对的代理字符`);if(new TextEncoder().encode(r.value).length>pd)throw Ye("INVALID_PARAMS",`${t} value 不能超过 ${pd} 字节`);return{key:n,value:r.value}}function Sw(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 bw(e){const t=$r(e,or,!0);qr(t,[],or)}function Nf(e,t){if(typeof e!="string"||!Aw.test(e))throw Ye("INVALID_PARAMS",`${t} key 仅支持 1–128 位英文字母、数字、下划线和连字符`);return e}function $r(e,t,r){if(e===void 0&&r)return{};if(!Mf(e))throw Ye("INVALID_PARAMS",`${t} 参数必须是对象`);return e}function qr(e,t,r){const n=Object.keys(e).find(i=>!t.includes(i));if(n)throw Ye("INVALID_PARAMS",`${r} 不支持参数 ${n}`)}function rc(e,t){if(e===void 0)return{};if(typeof e!="string"||!ww.test(e))throw Ye("INVALID_PARAMS",`${t} key 仅支持 1-64 位字母、数字、下划线和连字符`);return{key:e}}function Tw(e){if(!Mf(e))throw Ye("INVALID_PARAMS","cloud.leaderboard.submit extra 必须是对象");let t;try{t=JSON.stringify(e)}catch{throw Ye("INVALID_PARAMS","cloud.leaderboard.submit extra 必须可序列化")}if(typeof t!="string")throw Ye("INVALID_PARAMS","cloud.leaderboard.submit extra 必须可序列化");if(new TextEncoder().encode(t).length>gd)throw Ye("INVALID_PARAMS",`cloud.leaderboard.submit extra 不能超过 ${gd} 字节`);return e}function Mf(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ye(e,t){return{code:e,message:t}}const vw={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 Te(e,"游戏存档接口响应异常")}},Ow=new Map([["2358720","blackMythWukong"],["3678970","taskbarHero"],["4115450","phantomBladeZero"],["1245620","eldenRing"],["413150","stardewValley"],["2246340","monsterHunterWilds"],["3167020","duckov"],["3489700","stellarBlade"],["2001120","splitFiction"]]);function Xs(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=>Xs(r,t+1)):Ie(e)&&Object.values(e).every(r=>Xs(r,t+1))}function Rw(e,t){const r=Ow.get(t);if(!r||Ie(e)&&e.status==="unsupported")return{status:"unsupported"};if(Ie(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 ee(String(e.error_code),"账号或授权已变化");if(e.status==="ready"&&Ie(e.data)&&Xs(e.data))return{status:"ready",data:e.data}}return{status:"failed",error:{code:"STRUCTURED_DATA_UNAVAILABLE",message:"结构化数据暂时无法读取,请稍后重试"}}}function Sf(e){const t=new Map,r=new Map,n=c=>c.resource?`hb_runtime_game_save_resource_sync_v1_${[c.miniProgramId,c.userId,c.resource].map(encodeURIComponent).join(":")}`:`hb_runtime_game_save_sync_v1_${[c.miniProgramId,c.userId,c.gameId].map(encodeURIComponent).join(":")}`;async function i(c,d,u){const f=n(c),l=r.get(f)??Promise.resolve();let h;const m=new Promise(_=>{h=_}),E=l.then(()=>m);r.set(f,E);try{return await fe(()=>l,d.signal),pe(d.signal),e?.withLock?await e.withLock(f,u):await u()}finally{h(),r.get(f)===E&&E.then(()=>{r.get(f)===E&&r.delete(f)})}}async function o(c,d,u=!1){const f=n(c);if(!u&&t.has(f)||!e)return t.get(f);try{const l=await fe(()=>e.getRaw(f,d),d.signal);if(!l)return;const h=JSON.parse(l);if(!h||typeof h!="object")return;const m=h;return m.version!==1||m.miniProgramId!==c.miniProgramId||m.userId!==c.userId||m.gameId!==c.gameId||(c.resource?m.resource!==c.resource:typeof m.accountId!="string"||!/^[1-9][0-9]{0,19}$/.test(m.accountId))||typeof m.taskId!="string"||(c.resource?m.taskId.length<1||m.taskId.length>128:!/^[1-9][0-9]{0,19}$/.test(m.taskId))?void 0:(u||t.set(f,m),m)}catch(l){if(pe(d.signal),u)throw l;return t.get(f)}}async function s(c,d,u){pe(u.signal);const f=n(c),l=d?{...c,version:1,taskId:d}:void 0;if(t.set(f,l),!!e)try{await fe(()=>e.setRaw(f,l?JSON.stringify(l):"",u),u.signal)}catch{pe(u.signal)}}async function a(c,d,u){await i(c,u,async()=>{const f=n(c),l=t.get(f),h=l?.taskId===d&&l.accountId===c.accountId;let m;try{m=await o(c,u,!0)}catch{pe(u.signal),h&&t.set(f,void 0);return}m?.taskId===d&&m.accountId===c.accountId?(await s(c,void 0,u),l&&!h&&t.set(f,l)):h&&t.set(f,m)})}return{run:i,async get(c,d){const u=await o(c,d);if(u&&u.accountId!==c.accountId){t.delete(n(c));return}return u?.taskId},set:s,remove:a,clear(c){for(const d of t.values())d&&a(d,d.taskId,c).catch(()=>{})}}}const Pw=2e3,kw=5*6e4;function Cw(e){const t=Sf(e.storage);let r=0,n=!1,i;const o=e.fileDownloads??(e.files&&e.transfer?Xa({files:e.files,transfer:e.transfer,registry:e.fileRegistry,signal:e.operationContext.signal}):void 0),s=new Set,a=new Map,c={...e.operationContext,lifecycle:"cleanup",signal:new AbortController().signal},d=I=>o?.release(I)??Promise.resolve(),u=new Set;let f=new AbortController,l;const h=()=>{f.abort(),f=new AbortController,l=void 0},m=(I=!0)=>{I&&t.clear(c),r++,h();for(const v of u)v.abort();for(const v of s)d(v).catch(()=>{});s.clear(),a.clear()},E=Lo(e.account,I=>{i&&I!==i&&(m(),i=void 0)}),_=e.authorization.onEvent(()=>m());function w(I,v,T,x){if(S(T),x.signal.aborted||!I.account_id||!e.presentation?.showSteamLoginRequired)return;const N=`${I.account_id}:${I.game_id}:${I.task_id??"sync"}`;if(l!==N){l=N;try{e.presentation.showSteamLoginRequired({userId:v,accountId:I.account_id},Se(e.operationContext,f.signal))}catch{}}}function S(I){if(n||e.operationContext.signal.aborted)throw ee("RUNTIME_DESTROYED","小程序已关闭");if(I!==r)throw ee("AUTHORIZATION_CONTEXT_CHANGED","账号或授权已变化")}async function p(I,v,T){if(S(v),await e.account.getCurrentUserId(T)!==I)throw m(),ee("AUTHORIZATION_CONTEXT_CHANGED","账号已变化");S(v)}async function M(I,v,T,x){if(await p(v,T,x),!e.authorizationContext)throw ee("METHOD_FORBIDDEN","宿主不支持存档授权上下文");const N=await e.authorizationContext.get(x);if(!N.token||N.expiresAt<=Date.now())throw ee("UNAUTHORIZED","小程序运行上下文已过期");const b=await Co({network:e.network,operationContext:x,subject:"游戏存档",assertUsable:()=>S(T),...e.requestGate?{gate:{capability:"gameSaves",gate:e.requestGate}}:{},requestPolicyEnabled:e.requestPolicyEnabled},vw,{...I,runtime_auth_context_token:N.token});if(await p(v,T,x),b.status==="failed"&&Ie(b.result)&&b.result.error_code==="RECENT_SAVE_AVAILABLE")throw ee("RECENT_SAVE_AVAILABLE",typeof b.msg=="string"&&b.msg?b.msg:"已有近期存档,请直接查询使用");const O=st(b,I.action,"游戏存档");if(!Ie(O))throw ee("INVALID_RESPONSE","存档响应不合法");return O}async function z(I,v,T){const x=Lw(I,v),N=r;if(S(N),I==="file"&&(!e.transfer||!e.files))throw ee("METHOD_FORBIDDEN","宿主不支持存档文件读取");const b=new AbortController;u.add(b);let O=!1;const j=I==="sync"?setTimeout(()=>{O=!0,b.abort()},kw):void 0,U=Se(Se(e.operationContext,T.signal),b.signal);try{const L=await e.account.getCurrentUserId(U);if(!L)throw ee("UNAUTHORIZED","请先登录小黑盒");if(i&&i!==L)throw m(),ee("AUTHORIZATION_CONTEXT_CHANGED","账号已变化");if(i=L,I==="sync"||I==="parsed"){if(I==="sync"&&h(),!x.account_id){const K=await M({action:"check",game_id:x.game_id},L,N,U);x.account_id=vn(K.account_id)}if(I==="sync")return await A(x,L,N,U)}const C=await M({action:I,...x},L,N,U);if(I==="list")return Uw(C);if(I==="parsed")return Rw(C.parsed_data,x.game_id);if(bf(C.file).fileId!==x.file_id)throw ee("INVALID_RESPONSE","文件标识不匹配");if(!o)throw ee("REQUEST_UNSUPPORTED","宿主不支持存档下载");const F=await o.download(C,async K=>{try{S(N),await M({action:"check",game_id:x.game_id,account_id:x.account_id},L,N,K)}catch(g){const k=Ie(g)?String(g.code):"";throw["RUNTIME_DESTROYED","AUTHORIZATION_CONTEXT_CHANGED","STEAM_ACCOUNT_CHANGED","GAME_SAVES_AUTHORIZATION_REQUIRED","UNAUTHORIZED"].includes(k)?(m(),ee("FILE_ACCESS_REVOKED","游戏存档授权已失效")):g}},U);let $=!1;try{if(await p(L,N,U),S(N),U.signal.aborted)throw ee("DOWNLOAD_CANCELLED","存档下载已取消");const K=e.fileRegistry.registerFile(F,"game-save","read");return s.add(F),a.set(Ya(),{file:F,sizeBytes:o.sizeOf(F)}),$=!0,K}finally{$||await o.release(F)}}catch(L){throw O?ee("REQUEST_TIMEOUT","等待同步超时,任务可能仍在执行,请稍后查询存档列表"):L}finally{j!==void 0&&clearTimeout(j),u.delete(b)}}async function A(I,v,T,x){const N=e.identity.get()?.miniProgramId;if(!N)throw ee("INVALID_STATE","小程序身份尚未确认");const b={miniProgramId:N,userId:v,gameId:I.game_id,accountId:I.account_id},O=U=>M({action:"status",...I,task_id:U},v,T,x);let j;try{const U=await t.run(b,x,async()=>{await p(v,T,x);const C=await t.get(b,x);if(C){j=C;try{return{taskId:C,status:await O(C)}}catch(F){if(!Ie(F)||!["SYNC_TASK_NOT_FOUND","SYNC_TASK_CHANGED"].includes(String(F.code)))throw F;await t.set(b,void 0,x),j=void 0}}const H=await M({action:"sync",...I},v,T,x);return j=vn(H.task_id),await t.set(b,j,x),await p(v,T,x),{taskId:j,status:void 0}});j=U.taskId;let L=U.status;for(;;){if(S(T),x.signal.aborted)throw ee("REQUEST_CANCELLED","已停止等待存档同步");if(L??=await O(j),L.state==="succeeded"||L.state==="failed"){if(await t.remove(b,j,x),await p(v,T,x),L.state==="succeeded")return{state:"succeeded"};throw ee(L.error_code?lo(L.error_code):"SYNC_FAILED",L.message?lo(L.message):"存档同步失败")}if(L.state!=="syncing"&&L.state!=="uploading")throw ee("INVALID_RESPONSE","同步状态不合法");L=void 0,await xw(Pw,x.signal)}}catch(U){if(Ie(U)){const L=String(U.code);L==="STEAM_LOGIN_REQUIRED"&&w({...I,task_id:j},v,T,x),j&&["SYNC_TASK_NOT_FOUND","SYNC_TASK_CHANGED","STEAM_ACCOUNT_CHANGED","STEAM_ACCOUNT_REQUIRED","GAME_SAVES_AUTHORIZATION_REQUIRED","AUTHORIZATION_CONTEXT_CHANGED","UNAUTHORIZED"].includes(L)&&await t.remove(b,j,c)}throw U}}return{handlers:{"gameSaves.list":(I,v)=>z("list",I,v),"gameSaves.sync":(I,v)=>z("sync",I,v),"gameSaves.readParsedData":(I,v)=>z("parsed",I,v),"gameSaves.getFile":(I,v)=>z("file",I,v)},diagnostics:{async getSnapshot(){const I=r;return i&&await p(i,I,e.operationContext),S(I),Array.from(a,([v,T])=>({id:v,name:T.file.name,sizeBytes:T.sizeBytes}))},async readFile(I,v){const T=r;S(T);const x=a.get(I);if(!x)throw ee("FILE_ACCESS_REVOKED","存档文件已失效,请重新下载");const N=Se(e.operationContext,v);N.signal.throwIfAborted();const b=await x.file.read(N);try{return N.signal.throwIfAborted(),S(T),{name:x.file.name,bytes:b}}catch(O){throw b.fill(0),O}}},allowsRead(I,v){return["file.readBytes","file.readText","file.stat","file.exists"].includes(I)&&Ie(v)&&e.fileRegistry.isGameSaveRef(v.target)},dispose(){n||(n=!0,m(!1),E(),_())}}}function Lw(e,t){const r=e==="file"?["gameId","accountId","saveId","fileId"]:["gameId","accountId"];if(!Ie(t)||Object.keys(t).some(i=>!r.includes(i)))throw ee("INVALID_PARAMS","存档参数不合法");const n=cn(t.gameId);if(Number(n)>2147483647)throw ee("INVALID_PARAMS","Steam AppID 超出范围");return{game_id:n,...e==="file"||t.accountId!==void 0?{account_id:cn(t.accountId)}:{},...e==="file"?{save_id:cn(t.saveId),file_id:cn(t.fileId)}:{}}}function cn(e){if(typeof e!="string"||!/^[1-9][0-9]{0,19}$/.test(e))throw ee("INVALID_PARAMS","存档标识必须为十进制字符串");return e}function vn(e){try{return cn(e)}catch{throw ee("INVALID_RESPONSE","服务端存档标识无效")}}function lo(e){if(typeof e!="string")throw ee("INVALID_RESPONSE","服务端存档字段无效");return e}function ea(e){if(typeof e!="number"||!Number.isSafeInteger(e)||e<0)throw ee("INVALID_RESPONSE","服务端存档数值无效");return e}function bf(e){if(!Ie(e))throw ee("INVALID_RESPONSE","存档文件信息无效");return{fileId:vn(e.file_id),name:lo(e.name),originalPath:lo(e.original_path),sizeBytes:ea(e.size_bytes),modifiedAt:ea(e.modified_at)}}function Uw(e){if(!Array.isArray(e.saves)||e.saves.length>500)throw ee("INVALID_RESPONSE","存档列表无效");return{accountId:vn(e.account_id),saves:e.saves.map(t=>{if(!Ie(t)||!Array.isArray(t.files)||t.files.length>200)throw ee("INVALID_RESPONSE","存档文件列表无效");return{saveId:vn(t.save_id),createdAt:ea(t.created_at),files:t.files.map(bf)}})}}function xw(e,t){return new Promise((r,n)=>{const i=()=>{clearTimeout(o),t.removeEventListener("abort",i),n(ee("REQUEST_CANCELLED","已停止等待存档同步"))},o=setTimeout(()=>{t.removeEventListener("abort",i),r()},Math.max(0,e));t.addEventListener("abort",i,{once:!0}),t.aborted&&i()})}const zw=new Set(["stdio","attachments","notifications"]),Tf=new Set(["windows-x64","macos-arm64"]),jw=new Set(["unsigned","valid","invalid","unknown"]),Bw=/^[a-f0-9]{64}$/,Hw=new Set(["exited","terminated","crashed","host-shutdown","permission-revoked","output-limit"]),Fw=new Set(Ol),Vw=new Set([...Ol,"PERMISSION_DENIED","USER_GESTURE_REQUIRED"]),vf=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 Gw(e){const t=async(n,i,o,s)=>{const a=$w(n);try{Et(i.signal);const c=await o(a,{...e.operationContext,signal:i.signal});return Et(i.signal),c}catch(c){throw ra(c,s)}},r=async(n,i,o)=>{if(!o.trustedUserGesture)throw y("USER_GESTURE_REQUIRED","当前操作需要新的可信用户手势");if(!e.companionPresentation)throw y("COMPANION_UNSUPPORTED","Host 未提供 Companion 可信授权界面");const s={...e.operationContext,signal:o.signal},a=await e.companion.getInfo(i,s).then(d=>qw(d,i)).catch(d=>{throw ra(d)});Et(o.signal);const c=await e.companionPresentation.confirmCompanionOperation({action:n,companion:a,miniProgram:e.miniProgramPresentation,signal:o.signal});if(Et(o.signal),c.status!=="granted")throw y("COMPANION_USER_CANCELLED","用户取消了 Companion 操作")};return{[wo]:(n,i)=>t(n,i,async(o,s)=>ta(await e.companion.getInfo(o,s),o)),[Io]:(n,i)=>t(n,i,async(o,s)=>Ed(await e.companion.getPreparationStatus(o,s))),[Ao]:(n,i)=>t(n,i,async(o,s)=>{const a=Ed(await e.companion.getPreparationStatus(o,s));return Et(i.signal),a.state!=="ready"&&a.state!=="preparing"&&await r("prepare",o,i),Et(i.signal),ta(await e.companion.prepare(o,{...s,onProgress:c=>i.postProgress(Rf(c))}),o)},"COMPANION_PREPARATION_CANCELLED"),[_o]:(n,i)=>t(n,i,(o,s)=>e.companion.cancelPreparation(o,s)),[Do]:(n,i)=>t(n,i,async(o,s)=>wd(await e.companion.getActiveSession(o,s),o)),[No]:(n,i)=>t(n,i,async(o,s)=>{const a=wd(await e.companion.getActiveSession(o,s),o);return Et(i.signal),a||(await r("launch",o,i),Et(i.signal),Pf(await e.companion.launch(o,s),o))}),[Mo]:(n,i)=>yr(n,i,e,"write"),[So]:(n,i)=>yr(n,i,e,"closeStdin"),[bo]:(n,i)=>yr(n,i,e,"terminate"),[To]:(n,i)=>yr(n,i,e,"ackOutput"),[vo]:async(n,i)=>{const o=await yr(n,i,e,"openAttachment");return e.fileRegistry.registerFile(o,"companion-attachment","read")},[Oo]:(n,i)=>yr(n,i,e,"showNotification")}}function $w(e){if(!re(e)||typeof e.alias!="string"||!ng.test(e.alias))throw y("INVALID_PARAMS","Companion alias 不合法");return e.alias}function Et(e){if(e.aborted)throw Object.assign(new Error("Companion 操作已取消"),{name:"AbortError"})}async function yr(e,t,r,n){if(!re(e)||typeof e.sessionId!="string"||!e.sessionId||!Number.isSafeInteger(e.controllerGeneration)||Number(e.controllerGeneration)<0)throw y("INVALID_PARAMS","Companion Session controller 不合法");try{Et(t.signal);const i=await r.companion[n](Qw(e,n),{...r.operationContext,signal:t.signal});return Et(t.signal),i}catch(i){throw ra(i)}}function dt(){throw y("COMPANION_HOST_FAILED","Companion Host 返回了无效数据")}function Of(e){return!Array.isArray(e)||e.some(t=>!zw.has(t))?dt():Object.freeze([...new Set(e)])}function ta(e,t){return!re(e)||typeof e.alias!="string"||typeof e.displayName!="string"||t!==void 0&&e.alias!==t||!Tf.has(String(e.target))||!Number.isSafeInteger(e.archiveBytes)||Number(e.archiveBytes)<0||!jw.has(String(e.signatureStatus))||e.source!==void 0&&e.source!=="local-dev"&&e.source!=="preview"&&e.source!=="released"?dt():Object.freeze({alias:e.alias,displayName:e.displayName,target:e.target,capabilities:Of(e.capabilities),archiveBytes:e.archiveBytes,signatureStatus:e.signatureStatus,...e.source===void 0?{}:{source:e.source}})}function qw(e,t){const r=ta(e,t);return!re(e)||e.sha256===void 0?r:typeof e.sha256!="string"||!Bw.test(e.sha256)?dt():Object.freeze({...r,sha256:e.sha256})}function Rf(e){return re(e)?e.phase==="downloading"&&Number.isSafeInteger(e.loaded)&&Number(e.loaded)>=0&&(e.total===void 0||Number.isSafeInteger(e.total)&&Number(e.total)>=Number(e.loaded))?Object.freeze({phase:"downloading",loaded:e.loaded,...e.total===void 0?{}:{total:e.total}}):(e.phase==="verifying"||e.phase==="extracting")&&Number.isSafeInteger(e.processed)&&Number.isSafeInteger(e.total)&&Number(e.processed)>=0&&Number(e.total)>=Number(e.processed)?Object.freeze({phase:e.phase,processed:e.processed,total:e.total}):dt():dt()}function Ed(e){return re(e)?e.state==="not-prepared"?Object.freeze({state:"not-prepared"}):e.state==="preparing"?Object.freeze({state:"preparing",progress:Rf(e.progress)}):e.state==="ready"&&Number.isSafeInteger(e.preparedAt)&&Number(e.preparedAt)>=0?Object.freeze({state:"ready",preparedAt:e.preparedAt}):e.state==="failed"&&re(e.error)&&typeof e.error.code=="string"&&Fw.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:vf[e.error.code]??"Companion 操作失败",retryable:e.error.retryable})}):dt():dt()}function Pf(e,t){return!re(e)||typeof e.id!="string"||!e.id||typeof e.alias!="string"||t!==void 0&&e.alias!==t||!Tf.has(String(e.target))||e.state!=="running"||!Number.isSafeInteger(e.controllerGeneration)||Number(e.controllerGeneration)<0?dt():Object.freeze({id:e.id,alias:e.alias,target:e.target,capabilities:Of(e.capabilities),state:"running",controllerGeneration:e.controllerGeneration})}function wd(e,t){return e===void 0?void 0:Pf(e,t)}function Qw(e,t){const r=e,n={sessionId:r.sessionId,controllerGeneration:r.controllerGeneration};if(t==="write"){if(!Dl(r.data))throw y("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 y("INVALID_PARAMS","Companion output ack 不合法");return{...n,stream:r.stream,sequence:r.sequence}}if(t==="openAttachment"){if(typeof r.id!="string"||!r.id)throw y("INVALID_PARAMS","Companion Attachment ID 不合法");return{...n,id:r.id}}if(t==="showNotification"){if(!["completed","failed","stopped","attention"].includes(String(r.category)))throw y("INVALID_PARAMS","Companion notification category 不合法");return{...n,category:r.category}}return n}function Yw(e){return!re(e)||!Hw.has(String(e.reason))?dt():e.reason==="exited"?Number.isSafeInteger(e.exitCode)?Object.freeze({reason:"exited",exitCode:e.exitCode}):dt():e.exitCode!==void 0&&!Number.isSafeInteger(e.exitCode)?dt():Object.freeze({reason:e.reason,...e.exitCode===void 0?{}:{exitCode:e.exitCode}})}function Ww(e){if(!re(e)||!re(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||!Dl(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:Yw(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 ra(e,t){return re(e)&&typeof e.code=="string"&&Vw.has(e.code)?y(e.code,vf[e.code]??"Companion 操作失败",e.code==="COMPANION_DESCRIPTOR_UNAVAILABLE"?{retryable:!0}:typeof e.retryable=="boolean"?{retryable:e.retryable}:void 0):t&&re(e)&&e.name==="AbortError"?y(t,"Companion 准备已取消"):y("COMPANION_HOST_FAILED","Companion Host 操作失败")}const Id=5e3,Ad=1e4;function $e(e){throw{code:"INVALID_PARAMS",message:e}}function nc(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function kf(e,t,r){const n=Object.keys(e).filter(i=>!t.includes(i));n.length&&$e(`${r} 不支持字段: ${n.join(", ")}`)}function Zw(e){if(e===void 0)return{intensity:"light",delay:0};if(!nc(e))return $e("device.vibrate 参数必须是对象");kf(e,["intensity","delay"],"device.vibrate");const t=e.intensity??"light";if(t!=="light"&&t!=="medium"&&t!=="heavy")return $e("device.vibrate intensity 必须是 light、medium 或 heavy");const r=t,n=e.delay??0;return typeof n!="number"||!Number.isInteger(n)||n<0||n>Id?$e(`device.vibrate delay 必须是 0-${Id} 的整数毫秒`):{intensity:r,delay:n}}function Kw(e){return nc(e)?(kf(e,["text"],"device.setClipboard"),typeof e.text!="string"||!e.text.trim()?$e("device.setClipboard text 必须是非空字符串"):e.text.length>Ad?$e(`device.setClipboard text 不能超过 ${Ad} 字符`):{text:e.text}):$e("device.setClipboard 参数必须是对象")}function Jw(e){return typeof e=="string"?e.trim()?e:$e("device.executeProtocol 协议字符串不能为空"):nc(e)?typeof e.protocol_type!="string"||!e.protocol_type.trim()?$e("device.executeProtocol 协议对象必须包含非空字符串 protocol_type"):(na(e,new Set),e):$e("device.executeProtocol 参数必须是协议字符串或协议对象")}function na(e,t){if(e===null)return;switch(typeof e){case"string":case"boolean":return;case"number":Number.isFinite(e)||$e("device.executeProtocol 协议对象不能包含非有限数字");return;case"undefined":$e("device.executeProtocol 协议对象不能包含 undefined");return;case"function":case"symbol":case"bigint":$e(`device.executeProtocol 协议对象只能包含 JSON 数据,不能包含 ${typeof e}`);return}const r=e;if(t.has(r)&&$e("device.executeProtocol 协议对象不能包含循环引用"),t.add(r),Array.isArray(r)){for(const i of r)na(i,t);t.delete(r);return}const n=Object.getPrototypeOf(r);n!==Object.prototype&&n!==null&&$e("device.executeProtocol 协议对象只能包含普通 JSON 对象,不能包含类实例或特殊对象");for(const i of Object.values(r))na(i,t);t.delete(r)}function Xw(e){return{[Ji]:async(t,r)=>{const n=Se(e.operationContext,r.signal,r.requestId);pe(n.signal),await fe(()=>e.presentation.vibrate(Zw(t),n),n.signal)},[Xi]:async(t,r)=>{const n=Se(e.operationContext,r.signal,r.requestId);pe(n.signal),await fe(()=>e.presentation.setClipboard(Kw(t),n),n.signal)},[eo]:async(t,r)=>{const n=Se(e.operationContext,r.signal,r.requestId);pe(n.signal);const i=Jw(t);await fe(()=>e.protocol.invoke(i,n),n.signal)}}}const _d=1e3,eI=new Set(["FILE_NOT_FOUND","DIRECTORY_NOT_FOUND","FILE_TYPE_MISMATCH"]);function tI(e){const t=r=>Se(e.operationContext,r.signal);return{files:{[Bi]:async(r,n)=>{rs(n);const i=ns(e.picker),o=rI(r),s=await Ze(()=>i.pickFiles(o,t(n)));return e.registry.registerFiles(s,"external",o.mode,o.multiple?void 0:1)},[Hi]:async(r,n)=>{rs(n);const i=ns(e.picker),o=nI(r),s=await Ze(()=>i.pickDirectory(o,t(n)));return e.registry.registerDirectory(s,"external",o.mode)},[Fi]:async(r,n)=>{rs(n);const i=ns(e.picker),o=iI(r).suggestedName,s=t(n);if(!i.saveFile)throw tt("files.saveFile");const a=await Ze(()=>i.saveFile({suggestedName:o},s));return e.registry.registerFile(a,"external","readwrite")}},file:{[In]:async(r,n)=>{const i=Xe(r,["recursive","exclusive"]),o=e.registry.resolveFile(i.target);Er(o.mode),await Ze(()=>o.create(Dd(i),t(n)))},[An]:async(r,n)=>{const i=Xe(r),o=e.registry.resolveFileEntry(i.target);if(e.registry.assertSandboxOrigin(o),Er(o.handle.mode),!o.handle.remove)throw tt(An);await Ze(()=>o.handle.remove(t(n)))},[Vi]:async(r,n)=>{const i=Xe(r);return Nd(async()=>{const o=await e.registry.resolveFile(i.target).stat(t(n));if(!re(o)||o.kind!=="file")throw Sd()})},[_n]:async(r,n)=>{const i=Xe(r),o=Md(await Ze(()=>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 y("FILE_ENCODING_INVALID","文件不是合法 UTF-8 文本")}},[Gi]:async(r,n)=>{const i=Xe(r,["content"]);typeof i.content!="string"&&nt("content 必须是字符串");const o=e.registry.resolveFile(i.target);Er(o.mode),await Ze(()=>o.write(new TextEncoder().encode(i.content),t(n)))},[Dn]:async(r,n)=>{const i=Xe(r),o=await Ze(()=>e.registry.resolveFile(i.target).read(t(n)));return Md(o)},[$i]:async(r,n)=>{const i=Xe(r,["content"]),o=e.registry.resolveFile(i.target);Er(o.mode),await Ze(()=>o.write(sI(i.content),t(n)))},[Nn]:async(r,n)=>{const i=Xe(r),o=await Ze(()=>e.registry.resolveFile(i.target).stat(t(n)));return aI(o)}},directory:{[qi]:async(r,n)=>{const i=Xe(r,["recursive","exclusive"]),o=e.registry.resolveDirectory(i.target);Er(o.mode),await Ze(()=>o.create(Dd(i),t(n)))},[Mn]:async(r,n)=>{const i=Xe(r,["recursive"]);if(re(i.target)&&i.target.relativePath===".")throw y("FILE_ACCESS_DENIED","不能删除根目录");const o=e.registry.resolveDirectoryEntry(i.target);if(e.registry.assertSandboxOrigin(o),Er(o.handle.mode),!o.handle.remove)throw tt(Mn);await Ze(()=>o.handle.remove({recursive:i.recursive===void 0?!1:fo(i.recursive,"recursive")},t(n)))},[Qi]:async(r,n)=>{const i=Xe(r);return Nd(async()=>{const o=await e.registry.resolveDirectory(i.target).stat(t(n));if(!re(o)||o.kind!=="directory")throw Sd()})},[Yi]:async(r,n)=>{const i=Xe(r,["limit"]),o=oI(i.limit),s=e.registry.resolveDirectoryEntry(i.target),a=await Ze(()=>s.handle.list({limit:o},t(n)));return e.registry.describeListedEntries(s,a,o)}}}}function rI(e){if(e===void 0)return{mode:"read",multiple:!1};re(e)||nt("pickFiles 参数必须是对象"),Uo(e,["mode","accept","multiple"]);const t=Cf(e.mode,"read"),r=e.multiple===void 0?!1:fo(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)))&&nt("accept 必须是规范扩展名数组"),n=[...new Set(e.accept)]),{mode:t,multiple:r,...n===void 0?{}:{accept:n}}}function nI(e){return e===void 0?{mode:"read"}:(re(e)||nt("pickDirectory 参数必须是对象"),Uo(e,["mode"]),{mode:Cf(e.mode,"read")})}function iI(e){return re(e)||nt("saveFile 参数必须是对象"),Uo(e,["suggestedName"]),{suggestedName:Ln(e.suggestedName,"suggestedName")}}function Xe(e,t=[]){return(!re(e)||!Object.prototype.hasOwnProperty.call(e,"target"))&&nt("文件操作参数必须包含 target"),Uo(e,["target",...t]),e}function Dd(e){return{recursive:e.recursive===void 0?!1:fo(e.recursive,"recursive"),exclusive:e.exclusive===void 0?!1:fo(e.exclusive,"exclusive")}}function Cf(e,t){return e===void 0?t:(e!=="read"&&e!=="readwrite"&&nt("mode 必须是 read 或 readwrite"),e)}function fo(e,t){return typeof e!="boolean"&&nt(`${t} 必须是布尔值`),e}function oI(e){if(e===void 0)return _d;if((!Number.isSafeInteger(e)||e<=0)&&nt("limit 必须是正整数"),e>_d)throw y("DIRECTORY_LIST_LIMIT_EXCEEDED","目录项限制超过 Host 上限");return e}function Uo(e,t){const r=Object.keys(e).filter(n=>!t.includes(n));r.length&&nt(`不支持字段: ${r.join(", ")}`)}function Er(e){if(e!=="readwrite")throw y("FILE_ACCESS_DENIED","当前文件授权只允许读取")}function rs(e){if(!e.trustedUserGesture)throw y("USER_GESTURE_REQUIRED","当前操作需要可信用户手势")}function ns(e){if(!e)throw tt("files.external");return e}async function Nd(e){try{return await e(),!0}catch(t){if(eI.has(Wa(t)??""))return!1;throw kr(t)}}async function Ze(e){try{return await e()}catch(t){throw kr(t)}}function sI(e){return e instanceof Uint8Array||nt("content 必须是 Uint8Array"),typeof SharedArrayBuffer<"u"&&e.buffer instanceof SharedArrayBuffer&&nt("不支持 SharedArrayBuffer-backed Uint8Array"),new Uint8Array(e)}function Md(e){if(!(e instanceof Uint8Array))throw y("FILE_IO_FAILED","Host 返回了无效字节数据");return new Uint8Array(e)}function Sd(){return y("FILE_TYPE_MISMATCH","文件句柄类型不匹配")}function aI(e){if(!re(e)||e.kind!=="file"||!cI(e.size))throw y("FILE_IO_FAILED","Host 返回了无效 FileStat");for(const t of["modifiedAt","createdAt"])if(e[t]!==void 0&&!dI(e[t]))throw y("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 cI(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function dI(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0}function nt(e){throw y("INVALID_PARAMS",e)}const bd=16*1024,Td=200;function uI(e){const t=Kl(e.runtimePermissions);function r(n,i){e.capabilities&&Gl(i,e.capabilities);const o=t({kind:"all",permissions:["filesystem"]},i);if(!o.allowed)throw y(o.code,o.message);const s=Se(e.operationContext,n);return ia(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 vd(()=>s.handle.list({limit:Td},o),o);return e.registry.describeListedEntries(s,a,Td).map(({name:c,kind:d})=>({name:c,kind:d}))},async read(n,i={}){const o=i.maxBytes??bd;if(!Number.isSafeInteger(o)||o<1||o>bd)throw y("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 y("DIAGNOSTICS_UNSUPPORTED","当前 Host 不支持有界文件诊断读取");const c=await vd(()=>a.readPrefix({maxBytes:o},s),s);if(!c||!(c.bytes instanceof Uint8Array)||c.bytes.byteLength>o||typeof c.truncated!="boolean")throw y("FILE_IO_FAILED","Host 返回了无效的有界读取结果");return{bytes:new Uint8Array(c.bytes),truncated:c.truncated}}}}function ia(e){if(e.signal.aborted)throw y("FILE_ACCESS_REVOKED","诊断文件查询已取消或实例已结束")}async function vd(e,t){let r;try{const n=await Promise.race([e(),new Promise((i,o)=>{r=()=>o(y("FILE_ACCESS_REVOKED","诊断文件查询已取消或实例已结束")),t.signal.addEventListener("abort",r,{once:!0}),t.signal.aborted&&r()})]);return ia(t),n}catch(n){throw t.signal.aborted&&ia(t),kr(n)}finally{r&&t.signal.removeEventListener("abort",r)}}const lI=new Set(["METHOD_FORBIDDEN","MEDIA_PICKER_CANCELLED","MEDIA_SYSTEM_PERMISSION_DENIED","MEDIA_PREPARE_FAILED","MEDIA_PREVIEW_UNAVAILABLE","REQUEST_UNSUPPORTED","USER_GESTURE_REQUIRED"]),is={METHOD_FORBIDDEN:"当前 Host 未开放媒体选择能力",MEDIA_PICKER_CANCELLED:"用户取消了媒体选择",MEDIA_SYSTEM_PERMISSION_DENIED:"系统未授予相机或相册权限",MEDIA_PREPARE_FAILED:"媒体准备失败,未保留部分结果",MEDIA_PREVIEW_UNAVAILABLE:"当前 Host 无法提供受控媒体预览",REQUEST_UNSUPPORTED:"当前 Host 不支持该媒体请求形态",USER_GESTURE_REQUIRED:"当前操作需要可信用户手势"};function fI(e){if(e instanceof Le)return y("REQUEST_UNSUPPORTED",is.REQUEST_UNSUPPORTED);const t=Lf(e);return t!==void 0&&lI.has(t)?y(t,is[t]??"媒体操作失败"):y("MEDIA_PREPARE_FAILED",is.MEDIA_PREPARE_FAILED)}function Lf(e){try{if(!re(e))return;const t=Object.getOwnPropertyDescriptor(e,"code");return t&&"value"in t&&typeof t.value=="string"?t.value:void 0}catch{return}}const hI=["source","mediaType","maxCount"],ui=Object.freeze({source:"album",mediaType:"all",maxCount:1});function mI(e){if(e===void 0)return ui;if(!Um(e))throw y("INVALID_PARAMS",pI(e));return gI(e)}function gI(e){return Object.freeze({source:e.source??ui.source,mediaType:e.mediaType??ui.mediaType,maxCount:e.maxCount??ui.maxCount})}function pI(e){if(!re(e))return"media.pick 参数必须是对象";const t=Object.keys(e).filter(r=>!hI.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 yI=new Set(["METHOD_FORBIDDEN","FILE_QUOTA_EXCEEDED","FILE_ACCESS_REVOKED","FILE_ACCESS_DENIED"]),EI={kind:"file",name:"media-probe",mode:"read",ref:{kind:"file",handleId:"media-probe"}};class wI{constructor(t,r,n){this.registry=t,this.media=r,this.operationContext=n}committed=new Set;disposed=!1;commit(t,r){const n=II(t,r);let i=[];try{i=this.registerBatch(n,r.maxCount);const o=n.map((s,a)=>_I(s,i[a]));if(!xm(o))throw It("Host 返回的媒体结果未通过协议校验");for(const s of n)this.committed.add(s);return o}catch(o){throw this.registry.revokeFiles(i.map(DI).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=Lf(n);throw i!==void 0&&yI.has(i)?n:It("Host 返回的媒体文件资源无法登记为只读句柄")}}releaseItems(t,r){if(t.length!==0)try{const n=this.media.release(t,r);Promise.resolve(n).catch(()=>{})}catch{}}}function Od(e,t){if(e.signal.aborted)throw y("RUNTIME_DESTROYED","小程序 Runtime 已终止");if(t.aborted)throw y("REQUEST_CANCELLED","media.pick 已取消")}function II(e,t){if(!Array.isArray(e))throw It("Host 返回了无效媒体选择结果");const r=e.length;if(r===0)throw It("Host 未返回任何媒体项;用户取消不得作为空数组成功");if(r>t.maxCount)throw It("Host 返回的媒体项超过本次 maxCount");if(t.source==="camera"&&r!==1)throw It("相机必须恰好返回 1 项");for(let n=0;n<r;n+=1){if(!Object.prototype.hasOwnProperty.call(e,n))throw It("Host 返回了稀疏媒体结果");AI(e[n],n)}return e}function AI(e,t){if(!re(e))throw It(`第 ${t+1} 项不是对象`);if(!_l({...e,file:EI}))throw It(`第 ${t+1} 项不符合 media.pick 媒体项契约`);if(!re(e.file))throw It(`第 ${t+1} 项缺少文件句柄`)}function _I(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 DI(e){return"handleId"in e.ref?e.ref.handleId:void 0}function It(e){return y("MEDIA_PREPARE_FAILED",e)}function NI(e){const t=e.media?new wI(e.registry,e.media,e.operationContext):void 0;return{handlers:{[Sn]:async(n,i)=>{const o=mI(n);SI(i);const s=e.media,a=t;if(!s||typeof s.pick!="function"||!a)throw tt(Sn);const c=Se(e.operationContext,i.signal);Od(e.operationContext,i.signal);const d=await MI(s,o,c,e.operationContext,i.signal);Od(e.operationContext,i.signal);try{return a.commit(d,o)}catch(u){throw a.releaseBatch(d,c),u}}},dispose(){t?.dispose()}}}async function MI(e,t,r,n,i){try{return await fe(()=>e.pick(t,r),r.signal)}catch(o){throw n.signal.aborted?y("RUNTIME_DESTROYED","小程序 Runtime 已终止"):i.aborted?y("REQUEST_CANCELLED","media.pick 已取消"):fI(o)}}function SI(e){if(!e.trustedUserGesture)throw y("USER_GESTURE_REQUIRED","当前操作需要可信用户手势")}const Wn=4294967296;function bI(e){const t=new TI;return t.write(e),t.finish()}class TI{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<Wn?(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=vI(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<Wn)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/Wn),this.view.setUint32(this.offset+4,t),this.offset+=8}writeInt64(t){this.ensureCapacity(8),this.view.setUint32(this.offset,Math.floor(t/Wn)),this.view.setUint32(this.offset+4,t),this.offset+=8}}function vI(e){const t=new Uint8Array(OI(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 OI(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 Uf(e){oa(e);const t=bI(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 oa(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)oa(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");oa(s,t+1,r)}r.delete(e)}const RI=["pc","console","mobile"],PI=["game","wiki"];function ho(e){throw{code:"INVALID_PARAMS",message:e}}function kI(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function jt(e,t){return typeof e!="string"||!e.trim()?ho(t):e.trim()}function Rd(e,t,r){return typeof e!="string"||!t.includes(e)?ho(r):e}function CI(e){const t={target:"game_detail",appId:jt(e.appId,"navigation.openAppPage appId 必须是非空字符串"),gameType:Rd(e.gameType,RI,"navigation.openAppPage gameType 必须是 pc、console 或 mobile")};return e.page!==void 0&&(t.page=Rd(e.page,PI,"navigation.openAppPage page 必须是 game 或 wiki")),e.hSrc!==void 0&&(t.hSrc=jt(e.hSrc,"navigation.openAppPage hSrc 必须是非空字符串")),e.skuId!==void 0&&(t.skuId=jt(e.skuId,"navigation.openAppPage skuId 必须是非空字符串")),t}function LI(e){return{target:"user_detail",userId:jt(e.userId,"navigation.openAppPage userId 必须是非空字符串")}}function UI(e){const t={target:"post_detail",linkId:jt(e.linkId,"navigation.openAppPage linkId 必须是非空字符串")};return e.rootCommentId!==void 0&&(t.rootCommentId=jt(e.rootCommentId,"navigation.openAppPage rootCommentId 必须是非空字符串")),e.commentId!==void 0&&(t.commentId=jt(e.commentId,"navigation.openAppPage commentId 必须是非空字符串")),t}function xI(e){const t={target:"mini_program",miniProgramId:jt(e.miniProgramId,"navigation.openAppPage miniProgramId 必须是非空字符串")};return e.extra!==void 0&&(t.extra=e.extra),t}function zI(e){return kI(e)?e.target==="game_detail"?CI(e):e.target==="user_detail"?LI(e):e.target==="post_detail"?UI(e):e.target==="mini_program"?xI(e):ho("navigation.openAppPage target 不支持"):ho("navigation.openAppPage options 必须是对象")}function jI(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 BI(e){return{protocolType:"openRouterPath",path:"/user_home",params:{userid:e.userId}}}function HI(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 FI(e){const t=e;return t.target==="game_detail"?jI(t):t.target==="user_detail"?BI(t):HI(t)}const VI="data:image/svg+xml;base64,PHN2ZyBwcmVzZXJ2ZUFzcGVjdFJhdGlvPSJub25lIiBvdmVyZmxvdz0idmlzaWJsZSIgc3R5bGU9ImRpc3BsYXk6IGJsb2NrOyIgd2lkdGg9IjIwIiBoZWlnaHQ9IjIwIiB2aWV3Qm94PSIwIDAgMjAgMjAiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxnIGlkPSJJY29uIj4KPHBhdGggaWQ9IlVuaW9uIiBkPSJNNS4wMzMzOCAxLjI5Mjg5QzUuNDIzOSAwLjkwMjM2OSA2LjA1NzI0IDAuOTAyMzY5IDYuNDQ3NzYgMS4yOTI4OUM2LjgzODI3IDEuNjgzNDIgNi44MzgyOCAyLjMxNjc2IDYuNDQ3NzYgMi43MDcyN0w1LjIzODQ2IDMuOTE2NThIMTEuNjY2N0MxNS40NDA1IDMuOTE2NzEgMTguNTAwMSA2Ljk3NjIgMTguNTAwMSAxMC43NTAxQzE4LjUgMTQuNTIzOCAxNS40NDA0IDE3LjU4MzQgMTEuNjY2NyAxNy41ODM1SDMuMzMzMzVDMi43ODExMiAxNy41ODM1IDIuMzMzMjcgMTcuMTM1NiAyLjMzMzE5IDE2LjU4MzRDMi4zMzMxOSAxNi4wMzExIDIuNzgxMDcgMTUuNTgzMiAzLjMzMzM1IDE1LjU4MzJIMTEuNjY2N0MxNC4zMzU5IDE1LjU4MzEgMTYuNDk5NyAxMy40MTkzIDE2LjQ5OTggMTAuNzUwMUMxNi40OTk4IDguMDgwNzYgMTQuMzM1OSA1LjkxNzAzIDExLjY2NjcgNS45MTY5SDQuNTkwNjdMNi40NDc3NiA3Ljc3NDhDNi44MzgyMSA4LjE2NTMzIDYuODM4MjYgOC43OTg2OCA2LjQ0Nzc2IDkuMTg5MThDNi4wNTcyNCA5LjU3OTQ1IDUuNDIzODMgOS41Nzk1NiA1LjAzMzM4IDkuMTg5MThMMS43OTI4MyA1Ljk0NzgyQzEuNDAyMzEgNS41NTczIDEuNDAyMzEgNC45MjM5NiAxLjc5MjgzIDQuNTMzNDRMNS4wMzMzOCAxLjI5Mjg5WiIgZmlsbD0id2hpdGUiLz4KPC9nPgo8L3N2Zz4K",GI="data-hb-sdk-fullscreen-exit",$I=3e3,qI=2e3,Pd="var(--white-70a,rgba(255,255,255,.7))",kd="0 0 var(--space-8,8px) var(--white-20a,rgba(255,255,255,.2))";function QI(e){if(typeof document>"u"||!document.body)return;const t=document.createElement("button");t.type="button",t.setAttribute(GI,""),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 ${Pd}`,`box-shadow:${kd}`,"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=VI,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 f(){o||(t.style.width=u())}function l(){d?.cancel(),d=void 0}function h(_=qI){clearTimeout(c),c=setTimeout(()=>{l(),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")},_)}function m(){l(),o=!0,t.style.width="48px",t.style.opacity="1",t.style.borderColor=Pd,t.style.boxShadow=kd,n.style.visibility="",i.style.display="",t.setAttribute("aria-label","退出全屏"),t.setAttribute("aria-expanded","true"),h()}async function E(){if(!(s||a)){if(!o){m();return}a=!0,clearTimeout(c),l();try{await e()}catch{}finally{a=!1,s||m()}}}return t.addEventListener("click",E),window.addEventListener("resize",f),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"})),h($I),{dispose(){s=!0,clearTimeout(c),l(),t.removeEventListener("click",E),window.removeEventListener("resize",f),t.remove()}}}const xf=1e4;function zf(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()},xf);return{signal:r.signal,async run(s){try{return await fe(s,r.signal)}catch(a){throw n??a}},dispose(){clearTimeout(o),e.removeEventListener("abort",i),t?.removeEventListener("abort",i)}}}function Cd(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 os(e,t){return e.mode===t.mode&&e.hideCapsule===t.hideCapsule}function Xr(){return{code:"REQUEST_CANCELLED",message:"方向设置已取消"}}function YI(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(m){if(!m.hideCapsule){c();return}a??=QI(()=>h.apply({orientation:"portrait",fullscreen:!1},void 0,"user"))}e.operationContext.signal.addEventListener("abort",c,{once:!0});function u(m,E){if(n===m){if(n=void 0,clearTimeout(m.timer),e.operationContext.signal.removeEventListener("abort",f),"error"in E)m.controller.abort();else if(i={options:m.options,result:E.result},o=m.options,d(m.options),e.onApplied?.(m.options),E.result.supported&&!os(s,m.options)){s={...m.options};try{e.onDisplayChange?.({orientation:s.mode,fullscreen:s.hideCapsule,source:m.source})}catch{}}for(const _ of m.subscribers)_.dispose(),"error"in E?_.reject(E.error):_.resolve(E.result);m.subscribers.clear()}}function f(){n&&u(n,{error:Xr()})}function l(m,E){return new Promise((_,w)=>{const S=()=>{m.subscribers.delete(p),p.dispose(),w(Xr()),m.subscribers.size===0&&u(m,{error:Xr()})},p={resolve:_,reject:w,dispose:()=>E?.removeEventListener("abort",S)};m.subscribers.add(p),E?.addEventListener("abort",S,{once:!0}),E?.aborted&&S()})}const h={async runDisplayRequest(m,E,_){const w=++t,S=zf(E,e.operationContext.signal);try{return await S.run(async()=>{if(await _(S.signal),S.signal.aborted)throw Xr();if(Cd(m),w<r)throw{code:"ORIENTATION_SUPERSEDED",message:"方向设置已被后续设置替换"};return r=w,h.apply(m,S.signal)})}finally{S.dispose()}},async apply(m,E,_="api"){if(pe(e.operationContext.signal),E?.aborted)throw Xr();const w=Cd(m),S=n?.options??o,p={mode:w.orientation??S.mode,hideCapsule:w.fullscreen??S.hideCapsule};p.mode==="landscape"&&(p.hideCapsule=!0);const M=e.presentation.applyOrientation;if(!M)throw{code:"METHOD_FORBIDDEN",message:"当前宿主暂不支持方向控制"};if(n&&os(n.options,p))return l(n,E);if(n&&u(n,{error:{code:"ORIENTATION_SUPERSEDED",message:"方向设置已被后续设置替换"}}),i&&os(i.options,p))return i.result;i=void 0;const z={options:p,source:_,controller:new AbortController,subscribers:new Set};n=z;const A=l(z,E);return e.operationContext.signal.addEventListener("abort",f,{once:!0}),E||(z.timer=setTimeout(()=>{u(z,{error:{code:"ORIENTATION_TIMEOUT",message:"方向切换超时"}})},xf)),fe(()=>M.call(e.presentation,p,{...e.operationContext,signal:z.controller.signal}),z.controller.signal).then(D=>u(z,{result:D??{supported:!0}}),D=>u(z,{error:D})),A},dispose(){e.operationContext.signal.removeEventListener("abort",c),c()}};return h}function jf(e){throw{code:"INVALID_PARAMS",message:e}}function Ld(e,t){e!==void 0&&(typeof e!="object"||e===null||Array.isArray(e)||Object.keys(e).length)&&jf(`${t} 不支持参数`)}function WI(e){return{[to]:async(t,r)=>{const n=Se(e.operationContext,r.signal,r.requestId);pe(n.signal),Ld(t,"navigation.close"),await fe(()=>e.presentation.close(n),n.signal)},[ro]:async(t,r)=>{const n=Se(e.operationContext,r.signal,r.requestId);pe(n.signal),Ld(t,"navigation.reload"),await fe(()=>e.presentation.reload(n),n.signal)},[no]:async(t,r)=>{const n=Se(e.operationContext,r.signal,r.requestId);pe(n.signal);const i=zI(t);if(i.target==="mini_program"){let o;if(i.extra!==void 0)try{o=Uf(i.extra)}catch{jf("navigation.openAppPage extra 必须是符合限制的 JSON-compatible 数据")}const s=e.resetDisplay;if(s){const a=zf(n.signal);try{await a.run(()=>s(a.signal))}finally{a.dispose()}}pe(n.signal),await fe(()=>e.presentation.openWindow({miniProgramId:i.miniProgramId,...o===void 0?{}:{extra:o}},n),n.signal);return}await fe(()=>e.presentation.openAppPage(FI(i),n),n.signal)}}}const Ud={UPLOAD_CANCELLED:"上传已取消",UPLOAD_TIMEOUT:"上传空闲超时",UPLOAD_NETWORK_FAILED:"上传网络失败",FILE_CHANGED:"上传源文件已变化",METHOD_FORBIDDEN:"当前 Host 未开放上传能力"};async function ZI(e,t,r){const n=r.transfer?.upload,i=r.fileRegistry;if(!n||!i)throw tt("network.upload");const o=Se(r.operationContext,t.signal),s=()=>{if(o.signal.aborted)throw y("UPLOAD_CANCELLED","上传已取消")};s();let a,c;try{a=i.resolveFileEntry(e.from).hostHandle,c=await a.stat(o)}catch(l){throw s(),kr(l)}if(s(),c.kind!=="file"||!Number.isSafeInteger(c.size)||c.size<0)throw y("FILE_IO_FAILED","上传源文件状态无效");if(e.maxBytes!==void 0&&c.size>e.maxBytes)throw y("FILE_TOO_LARGE","文件超过大小限制");let d=0,u=!1;const f=l=>{u||o.signal.aborted||!Number.isSafeInteger(l)||l<d||l>c.size||(d=l,t.postProgress({loaded:d,total:c.size,lengthComputable:!0}))};try{const{from:l,...h}=e,m=await n.upload(a,{...h,expectedBytes:c.size,...e.format==="multipart"?{fileName:e.fileName??a.name}:{}},{...o,onProgress:f});if(u=!0,!Number.isSafeInteger(m.uploadedBytes)||m.uploadedBytes<d||m.uploadedBytes>c.size)throw y("UPLOAD_NETWORK_FAILED","Host 返回的上传字节数无效");if(m.status>=200&&m.status<300&&m.uploadedBytes!==c.size)throw y("FILE_CHANGED","上传源文件已变化");return t.postProgress({loaded:m.uploadedBytes,total:c.size,lengthComputable:!0}),m}catch(l){u=!0;const h=Wa(l);throw h&&Ud[h]?y(h,Ud[h]):o.signal.aborted?y("UPLOAD_CANCELLED","上传已取消"):h?.startsWith("FILE_")||h?.startsWith("DIRECTORY_")?kr(l):y("UPLOAD_NETWORK_FAILED","上传网络失败")}}const ic="withCredentials",KI=new Set(["url","method","params","data","headers","timeout",ic]),JI=new Set(["url","to","params","headers","timeout","suggestedName","overwrite","maxBytes",ic]),XI=new Set(["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"]),xd=3e4,sa=2*1024*1024,eA=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,Bf=/[\u0000-\u0008\u000A-\u001F\u007F]/,tA=/^(?:authorization|authentication-info|proxy-authentication-info|cookie|set-cookie|set-cookie2|pkey|x-pkey|x-access-token|x-auth-token)$/i,rA="network.request 不支持 multipart/form-data,请使用专用上传能力";function nA(e){const t=iA(e.runtimePermissions);t.firstParty=e.firstParty===!0,t.networkPolicy=t.firstParty?void 0:Ql(e.networkPolicy);const r=EA(e.allowedHttpOrigins);return{[ji]:async(n,i)=>{const o=sA(n,{permission:t,allowedHttpOrigins:r}),s=await ZI(o,i,e),{uploadedBytes:a,...c}=s;return jd(c)},[zi]:async(n,i)=>{const o=aA(n,{permission:t,allowedHttpOrigins:r});return of(o,i,{transfer:e.transfer,fileRegistry:e.fileRegistry,operationContext:e.operationContext})},[xi]:async(n,i)=>{const o=Se(e.operationContext,i?.signal);pe(o.signal);const s=oA(n,{permission:t,allowedHttpOrigins:r});let a;try{a=await fe(()=>e.network.request(s,o),o.signal)}catch(c){throw IA(c)?c:AA(c,"REQUEST_UNSUPPORTED")?he("REQUEST_UNSUPPORTED","当前 Host 不支持该网络请求"):he("REQUEST_FAILED","网络请求失败")}return jd(a)}}}function iA(e){const t=qe(e),r=t.permissions.network;return{enabled:t.valid&&r?.status==="enabled",useOfficialDomain:t.valid&&r?.status==="enabled"&&r.config.useOfficialDomain===!0}}function oA(e,t){const r=Lr(e,"network.request 参数必须是对象"),n=Object.keys(r).filter(c=>!KI.has(c));if(n.length>0)throw he("INVALID_PARAMS",`network.request 不支持字段: ${n.join(", ")}`);Hf(r,"network.request");const i=oc(r,t,"network.request"),o=dA(r.method),s=r.data;s!==void 0&&fA(s),mA(i.headers,s);const a=gA(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 sA(e,t){const r=Lr(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 he("INVALID_PARAMS","network.upload 包含不支持的字段");const i=oc(r,t,"network.upload");if(!t.permission.firstParty&&i.official)throw he("PERMISSION_DENIED","上传暂不支持官方域名");if(i.timeout!==void 0&&i.timeout<=0)throw he("INVALID_PARAMS","上传 timeout 必须是有限正数");if(!er(r.from))throw he("INVALID_PARAMS","from 必须是有效 File ref");if(r.maxBytes!==void 0&&(!Number.isSafeInteger(r.maxBytes)||r.maxBytes<=0))throw he("INVALID_PARAMS","maxBytes 必须是正的 safe integer");if(r.format!=="raw"&&r.format!=="multipart")throw he("INVALID_PARAMS","format 必须是 raw 或 multipart");const o=r.method??(r.format==="raw"?"PUT":"POST");if(o!=="POST"&&(r.format!=="raw"||o!=="PUT"))throw he("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 he("INVALID_PARAMS","raw 不接受 multipart 字段");return s}if(Object.keys(i.headers??{}).some(u=>u.toLowerCase()==="content-type"))throw he("INVALID_PARAMS","multipart Content-Type 由 Host 生成");const a=zd(r.fieldName),c=r.fields===void 0?void 0:Lr(r.fields,"fields 必须是字符串字典");for(const[u,f]of Object.entries(c??{}))if(zd(u),typeof f!="string"||u===a)throw he("INVALID_PARAMS","fields 必须是字符串且不得与文件字段重名");if(r.fileName!==void 0&&typeof r.fileName!="string")throw he("INVALID_PARAMS","fileName 必须是字符串");if(r.contentType!==void 0&&(typeof r.contentType!="string"||Bf.test(r.contentType)||!/^[^\s/;]+\/[^\s;]+(?:;[^\r\n]*)?$/.test(r.contentType)))throw he("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>sa)throw he("INVALID_PARAMS","multipart 元数据超过 2 MiB");return{...s,fieldName:a,...c===void 0?{}:{fields:{...c}},...r.fileName===void 0?{}:{fileName:Ka(r.fileName)},contentType:r.contentType??"application/octet-stream"}}function zd(e){if(typeof e!="string"||!e||/[\u0000-\u001F\u007F"\\]/.test(e))throw he("INVALID_PARAMS","multipart 字段名必须是非空且无控制字符的字符串");return e}function aA(e,t){const r=Lr(e,"network.download 参数必须是对象"),n=Object.keys(r).filter(c=>!JI.has(c));if(n.length>0)throw he("INVALID_PARAMS",`network.download 不支持字段: ${n.join(", ")}`);Hf(r,"network.download");const i=oc(r,t,"network.download");if(i.timeout!==void 0&&i.timeout<=0)throw he("INVALID_PARAMS","network.download timeout 必须是有限正数");Qy(i.headers);const o=er(r.to),s=Il(r.to);if(!o&&!s)throw he("INVALID_PARAMS","network.download to 必须是有效 File/Directory ref");if(o&&(r.suggestedName!==void 0||r.overwrite!==void 0))throw he("INVALID_PARAMS","File 下载目标不接受 suggestedName/overwrite");let a;if(r.suggestedName!==void 0){if(typeof r.suggestedName!="string")throw he("INVALID_PARAMS","suggestedName 必须是字符串");a=Ka(r.suggestedName)}if(r.overwrite!==void 0&&typeof r.overwrite!="boolean")throw he("INVALID_PARAMS","overwrite 必须是布尔值");if(r.maxBytes!==void 0&&(!Number.isSafeInteger(r.maxBytes)||r.maxBytes<=0))throw he("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 oc(e,t,r){const n=cA(e.url,t.allowedHttpOrigins,r),i=jp(n);if(!t.permission.firstParty){const o=t.permission.networkPolicy,s=o?.enforcement==="approved_domains"&&n.protocol==="http:"&&t.allowedHttpOrigins.has(n.origin);if(o&&!s&&(n.protocol!=="https:"||n.port!==""||!o.entries.some(a=>a.domain===n.hostname.toLowerCase())))throw he("PERMISSION_DENIED",`${r} 目标不在平台批准的域名清单中`);if(i&&!t.permission.useOfficialDomain)throw he("PERMISSION_DENIED","当前小程序暂不支持访问官方域名")}if(zp(n.pathname,i))throw he("PERMISSION_DENIED",`${r} 不允许访问 Runtime 或账号敏感接口`);return{url:n,official:i,params:e.params===void 0?void 0:{...Lr(e.params,`${r} params 必须是对象`)},headers:e.headers===void 0?void 0:uA(e.headers,r),timeout:lA(e.timeout,r)}}function cA(e,t,r="network.request"){if(typeof e!="string"||!e.trim())throw he("INVALID_PARAMS",`${r} url 必须是 HTTP(S) URL`);let n;try{n=new URL(e)}catch{throw he("INVALID_PARAMS",`${r} url 必须是 HTTP(S) URL`)}if(n.protocol!=="http:"&&n.protocol!=="https:")throw he("INVALID_PARAMS",`${r} url 必须是 HTTP(S) URL`);if(n.username||n.password)throw he("INVALID_PARAMS",`${r} url 不允许包含用户信息`);if(n.protocol==="http:"&&!t.has(n.origin))throw he("PERMISSION_DENIED",`${r} 生产环境只允许 HTTPS`);return n}function dA(e){if(e===void 0)return;if(typeof e!="string"||!e.trim())throw he("INVALID_PARAMS","network.request method 必须是字符串");const t=e.trim().toUpperCase();if(!XI.has(t))throw he("INVALID_PARAMS","network.request method 不合法");return t}function uA(e,t="network.request"){const r=Lr(e,`${t} headers 必须是 Record<string, string>`),n={};for(const[i,o]of Object.entries(r)){const s=i.trim();if(!s||s!==i||!eA.test(s)||typeof o!="string"||Bf.test(o))throw he("INVALID_PARAMS",`${t} headers 必须是 Record<string, string>`);if(Bp(s))throw he("INVALID_PARAMS",`${t} 不允许设置敏感请求头: ${i}`);n[s]=o}return n}function Hf(e,t){const r=e[ic];if(r!==void 0&&typeof r!="boolean")throw he("INVALID_PARAMS",`${t} 旧版凭据字段必须是布尔值`)}function lA(e,t="network.request"){if(e!==void 0){if(typeof e!="number"||!Number.isFinite(e)||e<0)throw he("INVALID_PARAMS",`${t} timeout 必须是非负数字`);if(t==="network.request"&&e>xd)throw he("INVALID_PARAMS",`${t} timeout 不能超过 ${xd}ms`);return e}}function fA(e){if(typeof Blob<"u"&&e instanceof Blob||typeof FormData<"u"&&e instanceof FormData)throw he("INVALID_PARAMS","network.request data 不支持 File、Blob 或 FormData,请使用专用上传能力");if(hA(e)>sa)throw he("INVALID_PARAMS",`network.request data 不能超过 ${sa} 字节`)}function hA(e){if(typeof e=="string")return ss(e);if(e instanceof ArrayBuffer||ArrayBuffer.isView(e))return e.byteLength;if(typeof URLSearchParams<"u"&&e instanceof URLSearchParams)return ss(e.toString());try{const t=JSON.stringify(e);return t?ss(t):0}catch{throw he("INVALID_PARAMS","network.request data 必须可序列化")}}function mA(e,t){const r=Ff(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 he("INVALID_PARAMS",rA)}function gA(e,t,r){if(t===void 0)return;const n=Ff(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)||yA(t))?"form":pA(t)?"json":void 0}function Ff(e){return e?Object.entries(e).find(([r])=>r.trim().toLowerCase()==="content-type")?.[1].toLowerCase():void 0}function pA(e){return e===null||typeof e=="boolean"||typeof e=="number"||typeof e=="object"&&!ArrayBuffer.isView(e)&&!(e instanceof ArrayBuffer)}function yA(e){if(typeof e!="object"||e===null)return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function EA(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&&wA(n.hostname)&&t.add(n.origin)}catch{}return t}function wA(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 jd(e){return Object.keys(e.headers).some(Bd)?{...e,headers:Object.fromEntries(Object.entries(e.headers).filter(([t])=>!Bd(t)))}:e}function Bd(e){const t=e.trim().toLowerCase();return tA.test(t)||t.startsWith("x-heybox-")||t.startsWith("x-xhh-")}function IA(e){return e instanceof Error&&e.name==="AbortError"}function AA(e,t){return typeof e=="object"&&e!==null&&"code"in e&&e.code===t}function Lr(e,t){if(typeof e!="object"||e===null||Array.isArray(e))throw he("INVALID_PARAMS",t);return e}function ss(e){return new TextEncoder().encode(e).length}function he(e,t){return{code:e,message:t}}function _A(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function DA(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 NA(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=DA(i);o?r.has(o)||(r.add(o),n.push(o)):t.push("post.topicIds 每项必须是正整数或非空字符串")}return{invalidMessages:t,values:n}}function MA(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 Vf(e,t){if(e==null)return{};if(!_A(e))return{invalidMessage:`${t.method} post 必须是对象或 null`};const r=NA(e.topicIds),n=MA(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 SA(e){try{return new URL(e).protocol==="heybox-mini-dev:"}catch{return!1}}async function bA(e){try{if(SA(e.getCurrentHref()))return!0}catch{}try{return!!await e.isDevRuntime()}catch{return!1}}function xe(e){throw{code:"INVALID_PARAMS",message:e}}function jn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function aa(e,t){return typeof e!="string"||!e.trim()?xe(t):e}function TA(e,t){const r=aa(e,t);try{const n=new URL(r);return n.protocol!=="http:"&&n.protocol!=="https:"?xe(t):r}catch{return xe(t)}}function vA(e){return e==="wechatSession"||e==="wechatTimeline"||e==="qqFriend"||e==="qzone"||e==="weibo"}function Gf(e,t,r){const n=e.identity.get(),i=n?.miniProgramId.trim();if(!i)return xe(`${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 xe(`${t} 缺少有效的小程序分享地址`)}}function OA(e,t){if(!jn(e))return xe("share.showShareMenu 参数必须是对象");if(Object.prototype.hasOwnProperty.call(e,"url"))return xe("share.showShareMenu 不支持自定义 url");const r=e.channel;if(r!==void 0&&!vA(r))return xe("share.showShareMenu channel 不合法");const n=$f(e.extra,"share.showShareMenu");return{title:aa(e.title,"share.showShareMenu title 必须是非空字符串"),description:aa(e.desc,"share.showShareMenu desc 必须是非空字符串"),url:Gf(t,"share.showShareMenu",n),...e.imageUrl===void 0?{}:{imageUrl:TA(e.imageUrl,"share.showShareMenu imageUrl 必须是 HTTP(S) URL")},...r===void 0?{}:{channel:r}}}function $f(e,t){if(e!==void 0)try{return Uf(e)}catch{return xe(`${t} extra 必须是符合限制的 JSON-compatible 数据`)}}async function qf(e,t){return e.invalidMessage&&await fe(()=>bA(t.environment),t.operationContext.signal)?xe(e.invalidMessage):e.post}function Hd(e,t){const r=Number(e);return Number.isFinite(r)&&r>0?r:t}function RA(e){const t=e.getViewportMetrics();return{left:0,top:0,width:Hd(t.windowWidth,0),height:Hd(t.windowHeight,0)}}function ca(e,t){const r=Number(e);return!Number.isFinite(r)||r<0?xe(t):r}function Fd(e,t){const r=Number(e);return!Number.isFinite(r)||r<=0?xe(t):r}function PA(e){return jn(e)?{left:ca(e.left,"share.screenshot rect.left 必须是非负数字"),top:ca(e.top,"share.screenshot rect.top 必须是非负数字"),width:Fd(e.width,"share.screenshot rect.width 必须是正数"),height:Fd(e.height,"share.screenshot rect.height 必须是正数")}:xe("share.screenshot rect 必须是对象")}function Vd(e,t){if(e!=null&&!jn(e))return xe("share.screenshot 参数必须是对象");const r=e??{};return r.saveToAlbum!==void 0&&typeof r.saveToAlbum!="boolean"?xe("share.screenshot saveToAlbum 必须是布尔值"):r.watermarkTheme!==void 0&&r.watermarkTheme!=="light"&&r.watermarkTheme!=="dark"?xe("share.screenshot watermarkTheme 必须是 light 或 dark"):{watermarkTheme:r.watermarkTheme??"dark",rect:r.rect===void 0?RA(t):PA(r.rect),...r.delay===void 0?{}:{delay:ca(r.delay,"share.screenshot delay 必须是非负数字")},...r.saveToAlbum===void 0?{}:{saveToAlbum:r.saveToAlbum}}}async function kA(e,t){pe(t.operationContext.signal);const r=OA(e,t);let n=Vf(e.post,{maxTopicIds:1,method:"share.showShareMenu"});r.channel&&n.post&&(n={invalidMessage:n.invalidMessage||"share.showShareMenu channel 与 post 不能同时使用"});const i=await qf(n,t);return fe(()=>t.presentation.showShareMenu({...r,post:i},t.operationContext),t.operationContext.signal)}async function CA(e,t){if(pe(t.operationContext.signal),e!==void 0&&!jn(e))return xe("share.copyLink 参数必须是对象");const r=$f(e?.extra,"share.copyLink"),n=Gf(t,"share.copyLink",r);return await fe(()=>t.presentation.setClipboard({text:n},t.operationContext),t.operationContext.signal),n}async function Gd(e,t,r,n=!1){pe(t.operationContext.signal);const i=Vf(jn(e)?e.post:void 0,{method:"share.screenshot"}),o=await qf(i,t),s=t.identity.get()?.miniProgramId.trim()||void 0,a=LA(),{watermarkTheme:c,...d}=r;let u=!1,f,l,h;try{if(n&&(!t.presentation.supportsLongScreenshot||!t.prepareLongScreenshot))throw{code:"REQUEST_UNSUPPORTED",message:"当前宿主不支持 DOM 长图,请更新宿主"};if(u=!0,await fe(()=>t.presentation.setScreenshotChromeHidden(!0,t.operationContext),t.operationContext.signal),n){const _=await t.prepareLongScreenshot(r.rect,t.operationContext.signal);f=_.restore,d.rect=_.rect}l=await t.prepareScreenshot?.(d.rect,t.operationContext.signal,c),h={status:"fulfilled",value:await fe(()=>t.presentation.captureAndShare({...d,...n?{longContent:!0}:{},post:o,...s?{sourceMiniProgramId:s}:{}},t.operationContext),t.operationContext.signal)}}catch(E){h={status:"rejected",error:E}}finally{try{l?.()}finally{f?.()}}const m=u?await UA(t.presentation,a,t.operationContext.signal):void 0;if(h.status==="rejected")throw h.error;if(m)throw m;return h.value}function LA(){return{lifecycle:"cleanup",signal:new AbortController().signal}}async function UA(e,t,r){let n;try{n=Promise.resolve(e.setScreenshotChromeHidden(!1,t))}catch{return}try{await fe(()=>n,r,{invokeWhenAborted:!0})}catch(i){if(r.aborted)return i}}function xA(e){let t=Promise.resolve();const r=async(n,i)=>{const o=Se(e.operationContext,i.signal,i.requestId),s=Vd(n,e.presentation);(s.rect.top+s.rect.height>1e4||s.rect.left+s.rect.width>2048||s.rect.width*s.rect.height>4e6)&&xe("长图尺寸超出限制");const a=t.then(()=>Gd(n,{...e,operationContext:o},s,!0));return t=a.then(()=>{},()=>{}),a};return{[Ci]:r,[Ri]:(n,i)=>CA(n,{...e,operationContext:Se(e.operationContext,i.signal,i.requestId)}),[Pi]:(n,i)=>kA(n,{...e,operationContext:Se(e.operationContext,i.signal,i.requestId)}),[ki]:async(n,i)=>{const o=Se(e.operationContext,i.signal,i.requestId);pe(o.signal);const s=Vd(n,e.presentation),a=t.then(()=>Gd(n,{...e,operationContext:o},s));return t=a.then(()=>{},()=>{}),fe(()=>a,o.signal)}}}const $d=new WeakMap,Zn=new Map;function Qf(e){const t=e.canonicalIdentity?.miniProgramId?.trim();if(t)return sp(t);const r=e.anonymousStorageScope?.trim();if(r)return`anon_${Vl(r)}`;throw Object.assign(new Error("storage scope 只能在 canonical identity 绑定后使用"),{code:"INVALID_STATE"})}function Yf(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 f=$d.get(t);f||(f=new Map,$d.set(t,f));const l=f.get(u)??Promise.resolve(),h=async()=>(pe(c.signal,{preserveReason:!0}),d(u)),m=l.catch(()=>{}).then(()=>e.lock?e.lock(u,h):h());f.set(u,m);try{return await m}finally{f.get(u)===m&&f.delete(u)}},o=async(c,d,u=!1)=>{const f=fr(c,"");if(e.diagnostics)return[...new Set((await e.diagnostics.listRaw(d)).filter(m=>m.key.startsWith(f)&&m.value!=="").map(m=>m.key.slice(f.length)))];const l=await e.storage.getRaw(Gn(c),d);if((l===void 0||l==="")&&!u)throw Object.assign(new Error("当前客户端缺少数据索引,且不支持遍历本地数据,暂无法清理"),{code:"STORAGE_INDEX_MISSING"});let h;try{h=l?JSON.parse(l):[]}catch{throw new Error("本地数据索引异常")}if(!Array.isArray(h)||h.length>Uc||h.some(m=>typeof m!="string"||!/^[A-Za-z0-9_-]{1,128}$/.test(m)))throw new Error("本地数据索引异常");return[...new Set(h)]},s=async(c,d)=>{if(e.diagnostics){const l=fr(c,"");return(await e.diagnostics.listRaw(d)).filter(h=>h.key.startsWith(l)&&h.value!=="").map(h=>({...h,key:h.key.slice(l.length)}))}const u=[],f=await o(c,d);for(let l=0;l<f.length;l+=16){pe(d.signal,{preserveReason:!0});const h=await Promise.all(f.slice(l,l+16).map(async m=>{const E=await e.storage.getRaw(fr(c,m),d);return E!==void 0&&E!==""?{area:"local",key:m,value:E}:void 0}));for(const m of h)m&&u.push(m)}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(fr(u,c),d))},set(c,d,u){return a(c),i(u,async f=>{const l=await o(f,u,!0);if(!l.includes(c)&&l.length>=Uc)throw Object.assign(new Error("storage key 数量超出上限"),{code:"STORAGE_QUOTA_EXCEEDED"});if(!e.diagnostics){const h=[...new Set([...l,c])];await e.storage.setRaw(Gn(f),JSON.stringify(h),u)}pe(u.signal,{preserveReason:!0}),await e.storage.setRaw(fr(f,c),d,u),pe(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(Gn(d),JSON.stringify(u),c);for(let f=0;f<u.length;f+=16){pe(c.signal,{preserveReason:!0});const h=(await Promise.allSettled(u.slice(f,f+16).map(m=>e.storage.setRaw(fr(d,m),"",c)))).find(m=>m.status==="rejected");if(h)throw h.reason}pe(c.signal,{preserveReason:!0}),await e.storage.setRaw(Gn(d),"[]",c)})}}}function Wf(e,t){if(typeof navigator<"u"&&navigator.locks)return new Promise((n,i)=>{navigator.locks.request(`hb-miniprogram-storage:${e}`,()=>t().then(n,i)).catch(i)});const r=(Zn.get(e)??Promise.resolve()).catch(()=>{}).then(t);return Zn.set(e,r),r.finally(()=>{Zn.get(e)===r&&Zn.delete(e)})}const zA=128,jA=/^[A-Za-z0-9_-]+$/;function BA(e){const t=e.scopedStorage??Yf({storage:e.storage,resolveScope:()=>Qf({canonicalIdentity:e.identity.get(),anonymousStorageScope:e.anonymousStorageScope}),diagnostics:e.storageDiagnostics}),r={[En]:async n=>{pe(e.operationContext.signal);const i=qd(n,En,e.storageLimits?.maxKeyLength),o=await fe(()=>t.get(i,e.operationContext),e.operationContext.signal);return{data:Qd(o)}},[wn]:async n=>{pe(e.operationContext.signal);const i=Zf(n,"storage.setStorage 参数必须是对象"),o=qd(i,wn,e.storageLimits?.maxKeyLength),s=HA(i.data,e.storageLimits?.maxValueBytes);await fe(()=>t.set(o,s,e.operationContext),e.operationContext.signal)}};return!e.storageDiagnostics&&!e.scopedStorage?{handlers:r}:{handlers:r,diagnostics:{getSnapshot:async()=>(pe(e.operationContext.signal),(await fe(()=>t.list(e.operationContext),e.operationContext.signal).catch(i=>{throw i&&typeof i=="object"&&"code"in i&&i.code==="INVALID_STATE"?rr("STORAGE_DIAGNOSTICS_NOT_READY","Storage diagnostics 只能在 canonical identity 绑定后使用"):i})).map(i=>{const o=i.value;return{area:i.area,key:i.key,value:Qd(o),serializedValue:o,bytes:Kf(o)}}).sort((i,o)=>i.key.localeCompare(o.key)))}}}function qd(e,t,r=zA){const i=Zf(e,`${t} 参数必须是对象`).key;if(typeof i!="string")throw rr("INVALID_PARAMS",`${t} key 必须是字符串`);if(!i||i.length>r||!jA.test(i))throw rr("INVALID_PARAMS",`storage key 仅支持 1-${r} 位字母、数字、下划线和连字符`);return i}function HA(e,t){let r;try{r=JSON.stringify(e)}catch{throw rr("INVALID_PARAMS","storage.setStorage data 必须可 JSON 序列化")}if(typeof r!="string")throw rr("INVALID_PARAMS","storage.setStorage data 必须可 JSON 序列化");if(t!==void 0&&Kf(r)>t)throw rr("STORAGE_QUOTA_EXCEEDED",`storage.setStorage data 超出 ${t} 字节限制`);return r}function Qd(e){if(!(e===void 0||e===""))try{return JSON.parse(e)}catch{return e}}function Zf(e,t){if(typeof e!="object"||e===null||Array.isArray(e))throw rr("INVALID_PARAMS",t);return e}function Kf(e){return new TextEncoder().encode(e).length}function rr(e,t){return{code:e,message:t}}const Yd=120;function Lt(e){throw{code:"INVALID_PARAMS",message:e}}function sc(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Jf(e,t,r){const n=Object.keys(e).filter(i=>!t.includes(i));n.length&&Lt(`${r} 不支持字段: ${n.join(", ")}`)}function FA(e){if(!sc(e))return Lt("ui.showToast 参数必须是对象");if(Jf(e,["message","status"],"ui.showToast"),typeof e.message!="string"||!e.message.trim())return Lt("ui.showToast message 必须是非空字符串");const t=e.message.trim();if(t.length>Yd)return Lt(`ui.showToast message 不能超过 ${Yd} 字符`);const r=e.status;if(r!==void 0&&r!=="success"&&r!=="error")return Lt("ui.showToast status 必须是 success 或 error");const n=r;return{message:t,...n===void 0?{}:{status:n}}}function VA(e){return e===void 0?{dismissible:!1}:sc(e)?(Jf(e,["dismissible"],"ui.showLoading"),e.dismissible!==void 0&&typeof e.dismissible!="boolean"?Lt("ui.showLoading dismissible 必须是布尔值"):{dismissible:e.dismissible??!1}):Lt("ui.showLoading 参数必须是对象")}function GA(e){e!==void 0&&(!sc(e)||Object.keys(e).length)&&Lt("ui.hideLoading 不支持参数")}function $A(e){return{[Wi]:async(t,r)=>{const n=Se(e.operationContext,r.signal,r.requestId);pe(n.signal),await fe(()=>e.presentation.showToast(FA(t),n),n.signal)},[Zi]:async(t,r)=>{const n=Se(e.operationContext,r.signal,r.requestId);pe(n.signal),await fe(()=>e.presentation.showLoading(VA(t),n),n.signal)},[Ki]:async(t,r)=>{const n=Se(e.operationContext,r.signal,r.requestId);pe(n.signal),GA(t),await fe(()=>e.presentation.hideLoading(n),n.signal)}}}const qA={auth:"optional",channel:"api",failurePresentation:"none",id:"heybox.account.home_v2.get",method:"GET",path:"/account/home_v2/",parse(e){return Te(e,"当前用户首页资料接口响应异常")}},QA=3e4;function YA(e,t,r={}){const n=r.ttlMs??QA,i=r.requestPolicyEnabled!==!1,o=r.requestGate?{capability:"user",gate:r.requestGate}:void 0;let s=0,a,c;async function d(){let f;try{f=await ko(e,qA,void 0,{...t,credentials:"heybox-session",...o?{gate:o}:{}})}catch(l){throw t.signal.aborted?y("RUNTIME_DESTROYED","小程序 Runtime 已终止"):l instanceof Le?y("REQUEST_UNSUPPORTED",l.message):l instanceof zn?y("INVALID_RESPONSE","user home_v2 响应不合法"):l instanceof Cr?y("REQUEST_FAILED","user home_v2 请求失败"):l instanceof xn?i&&(l.status===403||l.status===429)?y("RATE_LIMITED","user home_v2 请求已被网关限流,请稍后重试",{status:l.status,...l.retryAfterMs===void 0?{}:{retryAfterMs:l.retryAfterMs}}):y("REQUEST_FAILED",l.message):ZA(l)?l:y("REQUEST_FAILED","user home_v2 请求失败")}return WA(f,"user home_v2")}function u(f){const l=Date.now();if(a?.userId===f&&a.expiresAt>l)return Promise.resolve(a.value);if(c?.userId===f&&c.generation===s)return c.promise;const h=s,m=d().then(E=>(s===h&&(a={userId:f,value:E,expiresAt:Date.now()+n}),E)).finally(()=>{c?.promise===m&&(c=void 0)});return c={userId:f,generation:h,promise:m},m}return{get:u,clear(){s+=1,a=void 0,c=void 0}}}function WA(e,t){if(!re(e))throw y("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 y(n,r)}if(!re(e.result))throw y("INVALID_RESPONSE",`${t} result 必须是对象`);return e.result}function ZA(e){return re(e)&&typeof e.code=="string"&&typeof e.message=="string"}const KA={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 Te(e,"关注用户接口响应异常")}},JA={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 Te(e,"ApiXiaoheiheCnUserMiniprogramRuntimeAuthorFollowStatus 接口响应异常")}},XA={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 Te(e,"ApiXiaoheiheCnUserMiniprogramRuntimeAuthorFollowGuidanceBegin 接口响应异常")}},e_={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 Te(e,"Steam 游戏库接口响应异常")}};function t_(e,t=Zs){const r=Xy({version:"2",validate:n_}),n={ttlMs:Number.isFinite(t)?Math.max(0,Math.floor(t)):Zs,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 Wd(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 r_(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 n_(e){if(!re(e)||!Array.isArray(e.gameList)||typeof e.hasMore!="boolean"||!Number.isInteger(e.nextOffset)||Number(e.nextOffset)<0||(Zd(e,"total"),e.isMe!==void 0&&typeof e.isMe!="boolean"))throw Mr();for(const t of e.gameList){if(!re(t)||!da(t.appid)||!da(t.steamAppid)||typeof t.name!="string"||!t.name.trim())throw Mr();for(const r of["image","portraitImage","icon"])i_(t,r);for(const r of["playtimeForever","playtime2Weeks"])Zd(t,r);if(t.tags!==void 0&&(!Array.isArray(t.tags)||t.tags.some(r=>typeof r!="string"||!r.trim())))throw Mr()}return e}function da(e){return typeof e=="number"&&Number.isFinite(e)}function Zd(e,t){if(e[t]!==void 0&&!da(e[t]))throw Mr()}function i_(e,t){if(e[t]!==void 0&&typeof e[t]!="string")throw Mr()}function Mr(){return y("INVALID_RESPONSE","Steam 游戏库缓存数据不合法")}const Xf=20,o_=100,s_=128,eh=0,th="weeks",a_=100,c_=new Set(["weeks","all","achieved"]);function d_(){return{nickname:"",avatar:""}}function u_(e){const t=YA(e.network,e.operationContext,{requestGate:e.requestGate,requestPolicyEnabled:e.requestPolicyEnabled}),r=e.requestPolicyEnabled!==!1,n=e.cacheManager??cf(),i=t_(n,r?e.steamGameListTtlMs:0);let o;const s=new Map;let a=Promise.resolve();function c(O,j){const U=JSON.stringify([O,j]);return(!o||o.key!==U)&&(o={key:U,scope:n.createScope(j,n.createScope(O))}),o.scope}function d(){const O=o;o=void 0,O&&n.invalidateScope(O.scope).catch(()=>{}),s.clear()}const u=wf({ttlMs:Math.max(0,Math.floor(e.profileTtlMs??yf))}),f=e.requestGate?{capability:"user",gate:e.requestGate}:void 0;let l,h,m=0,E=!1;const _=e.account.onChange(()=>{m+=1,t.clear(),u.invalidate(),d()}),w=e.authorization.onEvent((O,j)=>{O==="user_info_authorization_change"&&Object.values(j).some(U=>U==="denied")&&(m+=1,t.clear(),u.invalidate(),d(),a=a.then(async()=>{if(E)return;const U=await e.account.getCurrentUserId(e.operationContext);typeof U=="string"&&U.trim()&&await n.invalidateScope(c(p(),U.trim()))}).catch(()=>{}))});function S(){if(E||e.operationContext.signal.aborted)throw y("RUNTIME_DESTROYED","小程序 Runtime 已终止")}function p(){const O=e.identity.get()?.miniProgramId?.trim();if(!O)throw y("INVALID_STATE","用户能力缺少 canonical 小程序身份");return O}async function M(){S(),await a,S();let O;try{O=await e.account.getCurrentUserId(e.operationContext)}catch(j){throw e.operationContext.signal.aborted?y("RUNTIME_DESTROYED","小程序 Runtime 已终止"):en(j)?j:y("REQUEST_FAILED","读取小黑盒账号失败")}return typeof O=="string"&&O.trim()?O.trim():void 0}async function z(O,j){const U=await M();if(m!==j||U!==O)throw y("AUTHORIZATION_CONTEXT_CHANGED","用户请求期间账号上下文已变化,请重新操作")}async function A(O,j,U=e.operationContext.signal){try{return await ko(e.network,O,j,{...e.operationContext,signal:U,credentials:"heybox-session",...f?{gate:f}:{}})}catch(L){throw e.operationContext.signal.aborted?y("RUNTIME_DESTROYED","小程序 Runtime 已终止"):L instanceof Le?y("REQUEST_UNSUPPORTED",L.message):L instanceof zn?y("INVALID_RESPONSE","用户接口响应不合法"):L instanceof Cr?y("REQUEST_FAILED","用户请求失败"):L instanceof xn?r&&(L.status===403||L.status===429)?y("RATE_LIMITED","用户请求已被网关限流,请稍后重试",{status:L.status,...L.retryAfterMs===void 0?{}:{retryAfterMs:L.retryAfterMs}}):y("REQUEST_FAILED",L.message):en(L)?L:y("REQUEST_FAILED","用户请求失败")}}async function D(O,j){if(!e.authorizationContext)return{mini_program_id:O};let U;try{U=await fe(()=>e.authorizationContext.get({...e.operationContext,signal:j}),j)}catch(L){if(en(L))throw L;const C=y("REQUEST_FAILED","读取 Runtime auth context 失败");throw Object.defineProperty(C,"cause",{configurable:!0,value:L}),C}if(!U.token?.trim())throw y("INVALID_STATE","关注作者缺少启动凭据");return{mini_program_id:O,runtime_auth_context_token:U.token}}async function I(){S();const O=p(),j=m,U=await M();if(!U){if(m!==j)throw y("AUTHORIZATION_CONTEXT_CHANGED","查询期间账号已变化");return"notFollowing"}const L=await D(O,e.operationContext.signal);await z(U,j);const C=await A(JA,L);if(await z(U,j),p()!==O)throw y("AUTHORIZATION_CONTEXT_CHANGED","查询期间小程序上下文已变化");return Xd(Jd(C))}function v(O,j){if(!O)return Promise.reject(y("USER_GESTURE_REQUIRED","请点击按钮关注作者"));if(j?.aborted)return Promise.reject(y("REQUEST_CANCELLED","关注操作已取消"));if(l)return Promise.reject(y("FOLLOW_IN_PROGRESS","关注确认流程尚未结束"));if(!e.authPresentation?.confirmFollowAuthor)return Promise.reject(y("METHOD_FORBIDDEN","当前宿主不支持关注确认框"));const U=T(j).finally(()=>{l===U&&(l=void 0)});return l=U,U}async function T(O){S();const j=p(),U=new AbortController;h=U;const L=()=>U.abort();e.operationContext.signal.addEventListener("abort",L,{once:!0}),O?.addEventListener("abort",L,{once:!0});let C=()=>{},H=!1;try{try{await fe(()=>e.account.ensureAuthenticated({trustedUserGesture:!0,reason:"user_action",signal:U.signal}),U.signal)}catch(ue){throw en(ue)&&["AUTH_CANCELLED","AUTHORIZATION_CANCELLED","HEYBOX_APP_LOGIN_REQUIRED","LOGIN_CANCELLED"].includes(ue.code)?y("FOLLOW_CANCELLED","已取消小黑盒登录"):ue}S();const F=m;C=e.account.onChange(()=>{H=!0,L()});const $=await fe(M,U.signal);if(!$)throw y("FOLLOW_CANCELLED","未完成小黑盒登录");const K=async()=>{if(await fe(()=>z($,F),U.signal),S(),p()!==j)throw y("AUTHORIZATION_CONTEXT_CHANGED","关注期间小程序上下文已变化")};await K();const g=await D(j,U.signal);await K();const k=w_(),B=await fe(()=>A(XA,{...g,request_id:k},U.signal),U.signal);await K();const Q=Jd(B);if(Q.status!=="notFollowing")return Xd(Q);if(Q.rateLimited)throw y("FOLLOW_GUIDANCE_LIMIT_REACHED","今日关注引导次数已达上限");const X=await fe(()=>e.authPresentation.confirmFollowAuthor({miniProgramId:j,signal:U.signal}),U.signal);if(await K(),X!=="confirmed")throw y("FOLLOW_CANCELLED","已取消关注作者");const ne=Q.authorId,ie=await fe(()=>A(KA,{body:{following_id:ne}},U.signal),U.signal);if(await K(),ie.status!=="ok"){const ue=["login","relogin","lack_token"].includes(ie.status)?"HEYBOX_APP_LOGIN_REQUIRED":"REQUEST_FAILED";throw y(ue,typeof ie.msg=="string"&&ie.msg.trim()?ie.msg.trim():"关注作者失败,请稍后重试")}return"following"}catch(F){throw S(),H?y("AUTHORIZATION_CONTEXT_CHANGED","关注期间账号已变化,请重新操作"):O?.aborted?y("REQUEST_CANCELLED","关注操作已取消"):en(F)?F:y("REQUEST_FAILED","关注作者失败,请稍后重试")}finally{C(),e.operationContext.signal.removeEventListener("abort",L),O?.removeEventListener("abort",L),h===U&&(h=void 0)}}async function x(){p();const O=m,j=await M();if(!j)return{isHeyboxAppLoggedIn:!1,authorization:null,userInfo:null};const[U,L]=await Promise.all([e.authorization.getOrCreateLocalIdentity(j),N(j).catch(()=>d_())]);return await z(j,O),{isHeyboxAppLoggedIn:!0,authorization:e.authorization.getAuthorization(),userInfo:{app_user_id:U.appUserId,profile:L,...U.steamId?{steam_id:U.steamId}:{}}}}function N(O){return u.read(O,()=>A(Ef,void 0).then(j=>{const U=ua(j,"账号基础信息");if(U.display_username!==void 0&&typeof U.display_username!="string")throw y("INVALID_RESPONSE","账号基础信息 nickname 不合法");if(U.display_avatar!==void 0&&typeof U.display_avatar!="string")throw y("INVALID_RESPONSE","账号基础信息 avatar 不合法");return{nickname:U.display_username??"",avatar:U.display_avatar??""}}))}async function b(O){const j=l_(O),U=p(),L=m,C=await M();if(!C)return d(),{isLogin:!1,isBound:!1,data:null};const H=await t.get(C);await z(C,L);const F=rh(H.steam_id_info);if(Object.keys(F).length===0)return await n.invalidateScope(c(U,C)).catch(()=>{}),await z(C,L),s.delete(JSON.stringify([U,C])),{isLogin:!0,isBound:!1,data:null};const $=JSON.stringify([U,C]),K=c(U,C),g=Wd({...j,steamId:void 0},F),k=nh(F.personal_infomation_open??F.personal_information_open),B=JSON.stringify([g??null,k??null]),Q=s.get($);Q&&Q.identity!==B&&(await n.invalidateScope(K).catch(()=>{}),await z(C,L));const X={identity:B,scope:n.createScope(B,K)};s.set($,X);const ne=Wd(j,F),ie=ne?i.persistent:i.unresolved,ue=n.createScope(ne??"unresolved",X.scope),Ee=async()=>{if(await z(C,L),p()!==U||s.get($)?.identity!==B)throw y("AUTHORIZATION_CONTEXT_CHANGED","Steam 游戏库请求期间绑定上下文已变化")},me=await ie.read({scope:ue,key:r_({miniProgramId:U,userId:C,effectiveSteamId:ne,personalInformationOpen:k,query:j}),signal:e.operationContext.signal,load:async ge=>{const ye=await A(e_,{userId:C,...j,personalInformationOpen:k},ge);return await Ee(),p_(ua(ye,"Steam 游戏库"),j)}}).catch(async ge=>{throw await Ee(),ge});return await Ee(),{isLogin:!0,isBound:!0,data:me}}return{getFollowStatus:I,requestFollowAuthor:v,getInfo:x,getSteamGameList:b,async invalidateSteamGameListCache(){const O=p(),j=m,U=await M();if(!U)return;const L=c(O,U);await Promise.all([i.persistent.invalidateScope(L),i.unresolved.invalidateScope(L)]),t.clear(),s.delete(JSON.stringify([O,U])),await z(U,j)},dispose(){E||(E=!0,h?.abort(),m+=1,_(),w(),t.clear(),u.dispose(),i.persistent.dispose(),i.unresolved.dispose(),e.cacheManager||n.dispose())}}}function l_(e){if(e==null)return{limit:Xf,offset:eh,sort:th,includeHidden:!1};if(!re(e))throw Ut("user.getSteamGameList 参数必须是对象");const t=Object.keys(e).find(n=>!["steamId","limit","offset","sort","q","includeHidden"].includes(n));if(t)throw Ut(`user.getSteamGameList 不支持字段: ${t}`);const r={limit:f_(e.limit),offset:h_(e.offset),sort:m_(e.sort),includeHidden:g_(e.includeHidden)};if(e.steamId!==void 0){if(typeof e.steamId!="string"||!e.steamId.trim()||e.steamId.trim().length>s_)throw Ut("user.getSteamGameList steamId 必须是非空字符串");r.steamId=e.steamId.trim()}if(e.q!==void 0){if(typeof e.q!="string")throw Ut("user.getSteamGameList q 必须是字符串");const n=e.q.trim();n&&(r.q=n.slice(0,a_))}return r}function f_(e){if(e===void 0)return Xf;if(!Number.isInteger(e)||Number(e)<1)throw Ut("user.getSteamGameList limit 必须是正整数");return Math.min(Number(e),o_)}function h_(e){if(e===void 0)return eh;if(!Number.isInteger(e)||Number(e)<0)throw Ut("user.getSteamGameList offset 必须是非负整数");return Number(e)}function m_(e){if(e===void 0)return th;if(typeof e!="string"||!c_.has(e))throw Ut("user.getSteamGameList sort 不支持");return e}function g_(e){if(e===void 0)return!1;if(typeof e!="boolean")throw Ut("user.getSteamGameList includeHidden 必须是 boolean");return e}function p_(e,t){if(!Array.isArray(e.game_list))throw y("INVALID_RESPONSE","Steam 游戏库 game_list 必须是数组");const r=e.game_list.map(y_).filter(a=>a!==void 0),n=mo(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=nh(e.is_me);return s!==void 0&&(o.isMe=s),o}function y_(e){const t=rh(e),r=mo(t.appid),n=mo(t.steam_appid)??r,i=ac(t.name);if(r===void 0||n===void 0||!i)return;const o={appid:r,steamAppid:n,name:i};as(o,"image",t.image),typeof t.vertical_head_image=="string"&&as(o,"portraitImage",t.vertical_head_image),as(o,"icon",t.appicon??t.icon),Kd(o,"playtimeForever",t.playtime_forever),Kd(o,"playtime2Weeks",t.playtime_2weeks);const s=E_(t.external_tags??t.tags);return s.length&&(o.tags=s),o}function ua(e,t){if(!re(e))throw y("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 y(n,r)}if(!re(e.result))throw y("INVALID_RESPONSE",`${t} result 必须是对象`);return e.result}function rh(e){return re(e)?e:{}}function ac(e){return typeof e=="string"?e.trim():typeof e=="number"||typeof e=="boolean"?String(e):""}function E_(e){return Array.isArray(e)?e.map(ac).filter(Boolean):[]}function mo(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"&&e.trim()&&Number.isFinite(Number(e)))return Number(e)}function nh(e){if(e===!0||e===1||e==="1")return!0;if(e===!1||e===0||e==="0")return!1}function as(e,t,r){const n=ac(r);n&&Object.assign(e,{[t]:n})}function Kd(e,t,r){const n=mo(r);n!==void 0&&Object.assign(e,{[t]:n})}function Ut(e){return y("INVALID_PARAMS",e)}function en(e){return re(e)&&typeof e.code=="string"&&typeof e.message=="string"}function Jd(e){const t=ua(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 y("INVALID_RESPONSE","关注状态响应不合法");return{status:t.follow_status===2?"self":t.follow_status===1?"following":"notFollowing",authorId:t.author_id,rateLimited:t.rate_limited}}function Xd(e){return e.status}function w_(){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 I_(e){return{[Si]:async t=>(Kn(t,"user.getFollowStatus"),e.user.getFollowStatus()),[bi]:async(t,r)=>(Kn(t,"user.requestFollowAuthor"),e.user.requestFollowAuthor(r.trustedUserGesture,r.signal)),[Ti]:async t=>(Kn(t,"user.getInfo"),e.user.getInfo()),[vi]:async(t,r)=>{Kn(t,"user.revokeAuthorization"),await e.authorization.revoke(r.trustedUserGesture)},[Oi]:async t=>e.user.getSteamGameList(t)}}function Kn(e,t){if(e!==void 0)throw y("INVALID_PARAMS",`${t} 不接收入参`)}function A_(){return y("USER_DATA_PERMISSION_STATE_INVALID","本地用户数据许可状态异常,已停止访问")}function eu(e){return y("USER_DATA_PERMISSION_SAVE_FAILED","本次运行已停止访问,设置未保存,请重试",e===void 0?void 0:{reason:e instanceof Error?e.message:String(e)})}function __(e){const t=e.managedResources??Wt,r=typeof e.storage.withLock=="function"||typeof navigator<"u"&&!!navigator.locks,n=e.hash??Ga,i=new Map,o=new Set;let s=!1;function a(){if(s)throw y("RUNTIME_DESTROYED","小程序 Runtime 已终止")}function c(p,M){if(e.storage.withLock)return e.storage.withLock(u(p),M);if(typeof navigator<"u"&&navigator.locks)return Wf(u(p),M);throw y("REQUEST_UNSUPPORTED","当前宿主不支持跨实例保存资料许可")}function d(p){return mp({miniProgramId:e.resolveMiniProgramId(),userId:p,environment:e.resolveEnvironment()})}function u(p){return cp(hp(d(p)))}function f(p,M){return e.purposeOf?n(bl(p,e.revisionOf(p),M,e.purposeOf(p))):n(`${p}\0${e.revisionOf(p)}\0${M}`)}function l(p,M){return`${p}\0${M}`}async function h(p,M){let z;try{z=await e.storage.getRaw(u(p),M)}catch(D){throw a(),M.signal.aborted?y("REQUEST_CANCELLED","许可操作已取消"):y("USER_DATA_PERMISSION_STORAGE_UNAVAILABLE","无法读取本地用户数据许可",{reason:D instanceof Error?D.message:String(D)})}if(a(),M.signal.aborted)throw y("REQUEST_CANCELLED","许可操作已取消");const A=z===void 0||z===""?void 0:fp(z);if(z!==void 0&&z!==""&&A===void 0)throw A_();return A??{schema_version:1,records:{}}}async function m(p,M,z){if(a(),z.signal.aborted)throw y("REQUEST_CANCELLED","许可操作已取消");await e.storage.setRaw(u(p),JSON.stringify(M),z)}function E(p){return p?.revision??0}function _(p,M,z){const A=new Set(z.declared??[]),D=new Set(t);for(const T of Object.keys(M.records))kt(T)&&D.add(T);for(const T of i.keys())T.startsWith(`${p}\0`)&&D.add(T.slice(p.length+1));const v=[...D].sort((T,x)=>{const N=Wt.indexOf(T),b=Wt.indexOf(x);return(N<0?Number.MAX_SAFE_INTEGER:N)-(b<0?Number.MAX_SAFE_INTEGER:b)}).map(T=>{const x=M.records[T],N=E(x),b=z.egressTier===void 0?void 0:f(T,z.egressTier),O=i.get(l(p,T)),j=O!==void 0&&O.revision===N&&(b===void 0||O.consentFingerprint===b);return{resource:T,name:Ha(T)?.name??T,purposeText:e.purposeOf?.(T)??"",scopeFingerprint:b??"",declared:A.has(T),available:A.has(T),decision:x?.decision??"ask",revision:N,...x?.decision==="allow"&&x.consentFingerprint?{consentFingerprint:x.consentFingerprint}:{},sessionAllowed:j,allowed:!o.has(l(p,T))&&A.has(T)&&x?.decision!=="deny"&&(j||r&&x?.decision==="allow"&&b!==void 0&&x.consentFingerprint===b)}});return Object.freeze({schema_version:1,canPersist:r,resources:Object.freeze(v),...z.egressTier===void 0?{}:{egressTier:z.egressTier}})}function w(p,M,z,A){const D=M.records[z],I=l(p,z);if(o.has(I))return{status:"denied",reason:"tightening"};if(D?.decision==="deny")return{status:"denied",reason:"deny"};const v=f(z,A);if(r&&D?.decision==="allow"&&D.consentFingerprint===v)return{status:"allowed",source:"persistent"};const T=i.get(I);return T&&T.revision===E(D)&&T.consentFingerprint===v?{status:"allowed",source:"session"}:{status:"ask"}}function S(p){if(typeof p!="string"||!Wt.includes(p))throw y("INVALID_PARAMS","用户数据资源标识不合法")}return{canPersist:r,async read(p,M,z={}){a();const A=await h(p,M);return _(p,A,z)},async evaluate(p,M,z){a(),S(M.resource);const A=await h(p,z);return w(p,A,M.resource,M.egressTier)},async decide(p,M){a(),S(p.resource);const z=async()=>{a();const A=await h(p.userId,M);if(a(),M.signal.aborted)throw y("REQUEST_CANCELLED","许可操作已取消");const D=A.records[p.resource],I=E(D);if(p.expectedRevision!==void 0&&I!==p.expectedRevision)throw y("AUTHORIZATION_CONTEXT_CHANGED","资料许可已变化,请重新确认");const v=l(p.userId,p.resource),T=f(p.resource,p.egressTier);if(p.expectedFingerprint!==void 0&&p.expectedFingerprint!==T)throw y("AUTHORIZATION_CONTEXT_CHANGED","资料披露范围已变化,请重新确认");if(p.scope==="session"){if(p.decision!=="allow")throw y("INVALID_PARAMS","本次许可只支持允许");return i.set(v,Object.freeze({revision:I,consentFingerprint:T})),_(p.userId,A,{egressTier:p.egressTier})}const x=I+1,N=p.decision==="allow"?{decision:"allow",revision:x,consentFingerprint:T}:{decision:p.decision,revision:x},b={schema_version:1,records:{...A.records,[p.resource]:N}};p.decision!=="allow"&&(o.add(v),i.delete(v));try{await m(p.userId,b,M)}catch(O){throw eu(O)}return o.delete(v),i.delete(v),_(p.userId,b,{egressTier:p.egressTier})};return p.scope==="session"?z():c(p.userId,z)},async revokeSession(p,M){a(),p.resource!==void 0&&S(p.resource);for(const A of[...i.keys()])A.startsWith(`${p.userId}\0`)&&(p.resource===void 0||A===l(p.userId,p.resource))&&i.delete(A);const z=await h(p.userId,M);return _(p.userId,z,{})},async reset(p,M){return a(),c(p.userId,async()=>{a();const z=await h(p.userId,M);if(a(),M.signal.aborted)throw y("REQUEST_CANCELLED","许可操作已取消");const A=new Set(t);for(const v of Object.keys(z.records))A.add(v);for(const v of i.keys())v.startsWith(`${p.userId}\0`)&&A.add(v.slice(p.userId.length+1));for(const v of A)o.add(l(p.userId,v));for(const v of[...i.keys()])v.startsWith(`${p.userId}\0`)&&i.delete(v);const D={...z.records};for(const v of A)D[v]={decision:"ask",revision:(D[v]?.revision??0)+1};const I={schema_version:1,records:D};try{await m(p.userId,I,M)}catch(v){throw eu(v)}for(const v of A)o.delete(l(p.userId,v));return _(p.userId,I,{})})},dispose(){s||(s=!0,i.clear(),o.clear())}}}const xo={auth:"none",channel:"api",method:"POST",bodyEncoding:"form",failurePresentation:"none",parse(e){return Te(e,"游戏资料接口响应异常")}};function zo(e){return{runtime_auth_context_token:e.runtime_auth_context_token,resource:e.resource,disclosure_revision:e.disclosure_revision}}const D_={...xo,id:"heybox.user_miniprogram.runtime.user_game_data.query.post",path:"/user_miniprogram/runtime/user_game_data/query",body(e){return{...zo(e),operation:e.operation,schema_version:e.schema_version,...e.cursor===void 0?{}:{cursor:e.cursor},...e.limit===void 0?{}:{limit:e.limit}}}},N_={...xo,id:"heybox.user_miniprogram.runtime.user_game_data.sync.post",path:"/user_miniprogram/runtime/user_game_data/sync",body:zo},tu={...xo,id:"heybox.user_miniprogram.runtime.user_game_data.sync_status.post",path:"/user_miniprogram/runtime/user_game_data/sync_status",body(e){return{...zo(e),task_id:e.task_id}}},M_={...xo,id:"heybox.user_miniprogram.runtime.user_game_data.file.post",path:"/user_miniprogram/runtime/user_game_data/file",body(e){return{...zo(e),save_id:e.save_id,file_id:e.file_id}}};function S_(e){const t=Sf(e.storage),r=e.fileDownloads??(e.files&&e.transfer?Xa({files:e.files,transfer:e.transfer,registry:e.registry,signal:e.signal}):void 0),n=new Set,i=d=>{if(e.signal.aborted||d.signal.aborted)throw ee("REQUEST_CANCELLED","资料请求已取消")};async function o(d,u){if(i(u),!e.authorizationContext)throw ee("REQUEST_UNSUPPORTED","宿主缺少受信运行上下文");const f=await e.authorizationContext.get(u);if(!f.token||!Number.isFinite(f.expiresAt)||f.expiresAt<=Date.now())throw ee("UNAUTHORIZED","受信运行上下文已过期");return{runtime_auth_context_token:f.token,resource:d.key,disclosure_revision:d.disclosureRevision}}async function s(d,u,f){i(f);const l=await Co({network:e.network,operationContext:f,subject:"游戏资料",assertUsable:()=>i(f),requestPolicyEnabled:e.requestPolicyEnabled,...e.requestGate?{gate:{capability:"userGameData",gate:e.requestGate}}:{}},d,u),h=st(l,"user.data","游戏资料");if(!Ie(h))throw ee("INVALID_RESPONSE","游戏资料响应无效");return i(f),h}const a=d=>{const u=Ha(d);if(!u)throw ee("REQUEST_UNSUPPORTED","未开放资料资源");return u};async function c(d){n.delete(d),await r?.release(d)}return{releaseFile:c,invalidate(){for(const d of n)r?.release(d);n.clear()},async query(d,u){const f=a(d.resource),l=f.queries[d.operation];if(!l)throw ee("REQUEST_UNSUPPORTED","未开放资料操作");const h=await s(D_,{...await o(f,u),operation:d.operation,schema_version:l.version,...d.cursor===void 0?{}:{cursor:d.cursor},...d.limit===void 0?{}:{limit:d.limit}},u);if(h.resource!==d.resource||h.operation!==d.operation||h.schema_version!==l.version||h.disclosure_revision!==f.disclosureRevision)throw ee("INVALID_RESPONSE","游戏资料合同不匹配");if(h.status==="ready"){if(!ip(l.schema,h.data))throw ee("INVALID_RESPONSE","游戏资料正文不匹配公开 schema");return{status:"ready",data:h.data,meta:{},schemaVersion:l.version}}if(h.status==="empty"&&(h.reason==="no_data"||h.reason==="not_ready")&&typeof h.message=="string")return{status:"empty",reason:h.reason,message:h.message,meta:{},schemaVersion:l.version};throw ee("INVALID_RESPONSE","游戏资料状态无效")},async sync(d,u,f){const l=a(d.resource);if(!l.operations.includes("sync"))throw ee("REQUEST_UNSUPPORTED","资源不支持同步");const h=await o(l,u),m=new AbortController,E=()=>m.abort();u.signal.addEventListener("abort",E,{once:!0}),u.signal.aborted&&E();let _=!1;const w=setTimeout(()=>{_=!0,E()},5*6e4),S={...u,signal:m.signal},p={...f,gameId:l.game,resource:d.resource};let M;try{const z=await t.run(p,S,async()=>{const D=await t.get(p,S);if(D)return M=D,{id:D,status:await s(tu,{...await o(l,S),task_id:D},S)};const I=await s(N_,h,S);if(typeof I.task_id!="string"||!I.task_id||I.task_id.length>128)throw ee("INVALID_RESPONSE","同步任务缺失");return await t.set(p,I.task_id,S),{id:I.task_id,status:I}});let A=z.status;for(M=z.id;;){if(i(S),A.state==="succeeded")return await t.remove(p,M,S),{status:"succeeded"};if(A.state==="failed")throw await t.remove(p,M,S),ee(typeof A.error_code=="string"?A.error_code:"SYNC_FAILED","存档同步失败");if(A.state!=="syncing"&&A.state!=="uploading")throw ee("INVALID_RESPONSE","同步状态无效");if(await b_(S.signal),A=await s(tu,{...await o(l,S),task_id:M},S),A.task_id!==M)throw ee("INVALID_RESPONSE","同步任务不匹配")}}catch(z){throw M&&Ie(z)&&["SYNC_TASK_NOT_FOUND","SYNC_TASK_CHANGED","STEAM_ACCOUNT_CHANGED"].includes(String(z.code))&&await t.remove(p,M,S),_?ee("REQUEST_TIMEOUT","等待同步超时,后台任务可能仍在执行"):z}finally{clearTimeout(w),u.signal.removeEventListener("abort",E)}},async file(d,u,f){const l=a(d.resource);if(!l.operations.includes("file")||!r)throw ee("REQUEST_UNSUPPORTED","宿主不支持资料文件下载");const h=async E=>{await f(E);const _=await s(M_,{...await o(l,E),save_id:d.saveId,file_id:d.fileId},E);if(!Ie(_.file)||_.file.file_id!==d.fileId)throw ee("INVALID_RESPONSE","文件标识不匹配");return await f(E),_},m=await r.download(await h(u),async E=>{await h(E)},u);try{return i(u),await f(u),i(u),n.add(m),m}catch(E){throw await c(m),E}}}}function b_(e){return new Promise((t,r)=>{const n=()=>{clearTimeout(i),e.removeEventListener("abort",n),r(ee("REQUEST_CANCELLED","已停止等待同步"))},i=setTimeout(()=>{e.removeEventListener("abort",n),t()},2e3);e.addEventListener("abort",n,{once:!0}),e.aborted&&n()})}const tn=["event_id","miniProgramId","environment","host_platform","host_version","sdk_version","runtime_version","egress_tier","resource","call_id","flow_id"],T_=Object.freeze({user_game_data_permission_show:new Set([...tn,"entry","reason"]),user_game_data_permission_result:new Set([...tn,"choice","apply_result"]),user_game_data_permission_manage:new Set([...tn,"operation","apply_result","succeeded_count","failed_count"]),user_game_data_action:new Set([...tn,"stage","action_type","outcome","duration_ms"]),user_game_data_access_result:new Set([...tn,"api","trigger","status","error_code","failure_stage","duration_ms","cache_hit","sample_rate","overview_status_counts"])}),ru=10*6e4,v_=256;function O_(e){const t=e.now??Date.now,r=e.random??Math.random,n=e.createId??C_,i=P_(e.sampleRate),o=new Map,s=new Map,a=new Map;let c=!1,d=0,u=0,f=0,l=0;const h={get emitted(){return d},get failed(){return u},get skipped(){return f},get deduplicated(){return l}};function m(A){return`${A}${n()}`}function E(){const A=t();for(const[D,I]of o)A-I.createdAt<=ru||(o.delete(D),s.get(I.key)===D&&s.delete(I.key));for(const[D,I]of a){if(A-I<=ru&&a.size<=v_)break;a.delete(D)}}function _(A){const D=o.get(A);D!==void 0&&(o.delete(A),s.get(D.key)===A&&s.delete(D.key))}function w(A){_(A),a.delete(A),a.set(A,t())}function S(A,D){const I=T_[A],v={};for(const[T,x]of Object.entries(D))x===void 0||!I.has(T)||(v[T]=x);return Object.freeze(v)}function p(A){const D={event_id:m("evt_"),miniProgramId:wr(()=>e.resolveMiniProgramId())??"unknown",environment:R_(wr(()=>e.resolveEnvironment())),host_platform:wr(e.resolveHostPlatform)??"unknown",host_version:wr(e.resolveHostVersion)??"unknown",sdk_version:wr(e.resolveSdkVersion)??"unknown",runtime_version:wr(e.resolveRuntimeVersion)??"unknown",egress_tier:k_(e)};return A.resource!==void 0&&(D.resource=A.resource),A.callId!==void 0&&(D.call_id=A.callId),A.flowId!==void 0&&(D.flow_id=A.flowId),D}function M(A,D){if(c){f+=1;return}try{if(e.sink===void 0){f+=1;return}e.sink.postEvent(A,S(A,D)),d+=1}catch{u+=1}}function z(A,D){if(A===void 0)return!1;const I=o.get(A);return I===void 0?!1:D==="start"&&I.started||D==="shown"&&I.shown||D==="decided"&&I.decided?!0:(D==="start"&&(I.started=!0),D==="shown"&&(I.shown=!0),D==="decided"&&(I.decided=!0),!1)}return{diagnostics:h,createCallId(){return m("call_")},beginFlow(A){E();const D=`${A.resource??""}\0${A.actionType}`,I=s.get(D);if(I!==void 0&&o.has(I))return I;const v=m("flow_");return o.set(v,{key:D,createdAt:t(),started:!1,shown:!1,decided:!1}),s.set(D,v),v},permissionShow(A){if(z(A.flowId,"shown")){l+=1;return}M("user_game_data_permission_show",{...p(A),entry:A.entry,reason:A.reason})},permissionResult(A){if(z(A.flowId,"decided")){l+=1;return}M("user_game_data_permission_result",{...p(A),choice:A.choice,apply_result:A.applyResult})},permissionManage(A){M("user_game_data_permission_manage",{...p(A),operation:A.operation,apply_result:A.applyResult,...A.succeededCount===void 0?{}:{succeeded_count:A.succeededCount},...A.failedCount===void 0?{}:{failed_count:A.failedCount}})},action(A){if(A.stage==="start"&&z(A.flowId,"start")){l+=1;return}if(A.stage==="finish"){if(A.flowId!==void 0&&a.has(A.flowId)){l+=1;return}A.flowId!==void 0&&w(A.flowId)}M("user_game_data_action",{...p(A),stage:A.stage,action_type:A.actionType,...A.outcome===void 0?{}:{outcome:A.outcome},...A.durationMs===void 0?{}:{duration_ms:Math.max(0,Math.round(A.durationMs))}})},access(A){if(i<=0){f+=1;return}if(i<1&&r()>=i){f+=1;return}M("user_game_data_access_result",{...p(A),api:A.api,trigger:A.trigger,status:A.status,duration_ms:Math.max(0,Math.round(A.durationMs)),sample_rate:i,...A.errorCode===void 0?{}:{error_code:A.errorCode},...A.failureStage===void 0?{}:{failure_stage:A.failureStage},...A.cacheHit===void 0?{}:{cache_hit:A.cacheHit},...A.overviewStatusCounts===void 0?{}:{overview_status_counts:A.overviewStatusCounts}})},dispose(){c||(c=!0,o.clear(),s.clear(),a.clear())}}}function R_(e){switch(e){case"public":case"production":return"production";case"preview":return"preview";case"development":case"dev":case"local":return"development";case"mock":return"mock";default:return"unknown"}}function P_(e){return e===void 0||!Number.isFinite(e)?1:e<=0?0:e>=1?1:e}function wr(e){if(e!==void 0)try{const t=e();if(typeof t!="string")return;const r=t.trim();return r===""?void 0:r}catch{return}}function k_(e){try{return e.resolveEgressTier()==="upload"?"upload":"no_network"}catch{return"no_network"}}function C_(){const e=globalThis.crypto;if(typeof e?.randomUUID=="function")return e.randomUUID();const t=new Uint8Array(16);if(typeof globalThis.crypto?.getRandomValues=="function")globalThis.crypto.getRandomValues(t);else for(let r=0;r<t.length;r+=1)t[r]=Math.floor(Math.random()*256);return Array.from(t,r=>r.toString(16).padStart(2,"0")).join("")}function gt(e){const t=qe(e);return t.valid?t.permissions.network?.status==="enabled"||t.permissions.companion?.status==="enabled"?"upload":"no_network":"upload"}function L_(e){let t=!1,r=0,n,i=!1;const o=new Map,s=new Map,a=new Set,c=new Map,d=e.now??Date.now,u=g=>w()[g]?.purpose??"",f=g=>{const k=Ha(g);if(!k)throw y("REQUEST_UNSUPPORTED","未开放的资料资源");return k},l=g=>bl(g,f(g).disclosureRevision,gt(e.runtimePermissions),u(g)),h=()=>__({storage:e.storage,resolveMiniProgramId:()=>e.identity.get()?.miniProgramId,resolveEnvironment:()=>e.environment,revisionOf:g=>f(g).disclosureRevision,purposeOf:u,...e.hash?{hash:e.hash}:{}});let m=h();const E=O_({resolveMiniProgramId:()=>e.identity.get()?.miniProgramId,resolveEnvironment:()=>e.environment,resolveEgressTier:()=>gt(e.runtimePermissions),...e.telemetry??{}}),_=S_({network:e.network,authorizationContext:e.authorizationContext,files:e.files,transfer:e.transfer,storage:e.storage,registry:e.fileRegistry,fileDownloads:e.fileDownloads,requestGate:e.requestGate,requestPolicyEnabled:e.requestPolicyEnabled,signal:e.operationContext.signal});function w(){const g=qe(e.runtimePermissions),k=g.valid?g.permissions.user_game_data:void 0;return k?.status==="enabled"?bn(k.config.resources):{}}function S(g){if(t||e.operationContext.signal.aborted)throw y("RUNTIME_DESTROYED","小程序已关闭");if(g?.signal.aborted)throw y("REQUEST_CANCELLED","资料请求已取消")}function p(g){for(const[k,B]of o)B!==void 0&&(g===void 0||B===g)&&k.abort()}function M(g){for(const[k,B]of s)(g===void 0||k===g)&&(B.abort(),s.delete(k))}function z(){r++,M();for(const g of o.keys())g.abort();for(const g of a)e.fileRegistry.revokeFiles([g]);a.clear(),c.clear(),_.invalidate()}const A=Lo(e.account,g=>{if(i&&n===g)return;const k=n;i=!0,n=g,k!==void 0&&(z(),m.dispose(),m=h())}),D=()=>z();e.operationContext.signal.addEventListener("abort",D,{once:!0});async function I(g,k){S(g);const B=new AbortController,Q=()=>B.abort();o.set(B,void 0),g.signal.addEventListener("abort",Q,{once:!0}),g.signal.aborted&&Q();const X={...e.operationContext,...g,signal:B.signal};try{const ne=await k(X);return S(X),ne}catch(ne){throw re(ne)&&ne.name==="AbortError"?y("REQUEST_CANCELLED","资料操作已取消"):ne}finally{g.signal.removeEventListener("abort",Q),o.delete(B)}}function v(g){const k=f(g);if(!u(k.key))throw y("USER_DATA_RESOURCE_NOT_DECLARED","小程序未声明这项游戏资料",{resource:k.key});return k}async function T(g){S(g);const k=await e.account.getCurrentUserId(g);if(S(g),!i)i=!0,n=k;else if(n!==k){const B=n;n=k,B!==void 0&&(z(),m.dispose(),m=h(),S(g))}return k}function x(g,k){const B={login_required:"请先登录小黑盒",permission_required:"尚未允许读取这项资料",permission_denied:"已拒绝读取这项资料",source_not_linked:"请先在小黑盒关联对应游戏账号",source_login_required:"请先在小黑盒更新游戏来源登录"},Q=k==="login_required"?{type:"user_login",label:"登录并授权"}:k==="permission_required"?{type:"permission",label:"允许读取"}:k==="permission_denied"&&e.presentation?.openDataPermissions?{type:"manage",label:"管理数据权限"}:void 0;return{status:"blocked",resource:g,reason:k,message:B[k],...Q?{interaction:Q}:{}}}async function N(g,k){v(g);const B=await T(k);if(!B)return x(g,"login_required");const Q=await m.evaluate(B,{resource:g,egressTier:gt(e.runtimePermissions)},k);return S(k),Q.status==="allowed"?{userId:B}:x(g,Q.status==="denied"?"permission_denied":"permission_required")}async function b(g,k,B,Q,X){if(S(X),r!==B||await T(X)!==k||l(g)!==Q)throw y("AUTHORIZATION_CONTEXT_CHANGED","账号或资料范围已变化");return N(g,X)}function O(g,k){if(!re(g)||typeof g.resource!="string")throw y("INVALID_PARAMS","资料请求无效");if(!kt(g.resource))throw y("REQUEST_UNSUPPORTED","当前宿主尚未开放该资料资源");const B=k==="query"?["resource","operation","schemaVersion","cursor","limit"]:["resource","saveId","fileId"];if(Object.keys(g).some(X=>!B.includes(X)))throw y("INVALID_PARAMS","资料请求包含未知参数");const Q=v(g.resource);if(k==="query"){if(g.operation!=="get"&&g.operation!=="list")throw y("INVALID_PARAMS","资料查询操作无效");const X=Q.queries[g.operation];if(!X)throw y("REQUEST_UNSUPPORTED","资源不支持该查询");if(g.schemaVersion!==X.version)throw y("REQUEST_UNSUPPORTED","SDK 与宿主正文合同版本不匹配");if(g.operation!=="list"&&(g.cursor!==void 0||g.limit!==void 0))throw y("INVALID_PARAMS","单份查询不能分页");if(g.cursor!==void 0&&(typeof g.cursor!="string"||!g.cursor||g.cursor.length>32768))throw y("INVALID_PARAMS","分页游标无效");if(!X.page&&(g.cursor!==void 0||g.limit!==void 0))throw y("INVALID_PARAMS","该列表不支持分页");if(g.limit!==void 0&&(typeof g.limit!="number"||!Number.isInteger(g.limit)||g.limit<1||g.limit>(X.page?.maxSize??100)))throw y("INVALID_PARAMS","分页数量无效")}else if(!Q.operations.includes(k))throw y("REQUEST_UNSUPPORTED","资源不支持该操作");if(k==="file"&&(typeof g.saveId!="string"||!g.saveId||typeof g.fileId!="string"||!g.fileId))throw y("INVALID_PARAMS","资料文件标识无效");return k==="query"?{resource:g.resource,operation:g.operation,schemaVersion:g.schemaVersion,...g.cursor===void 0?{}:{cursor:g.cursor},...g.limit===void 0?{}:{limit:g.limit}}:{resource:g.resource,saveId:g.saveId,fileId:g.fileId}}async function j(g,k,B,Q){const X=d(),ne=r,ie=l(k.resource);for(const ue of o.keys())ue.signal===B.signal&&o.set(ue,k.resource);try{const ue=await N(k.resource,B);if("status"in ue)return E.access({resource:k.resource,api:g,trigger:"initial",status:"blocked",durationMs:d()-X}),ue;let Ee;try{Ee=await Q()}catch(ge){const ye=re(ge)?ge.code:void 0;if(ye==="USER_DATA_SOURCE_NOT_LINKED"||ye==="USER_DATA_SOURCE_LOGIN_REQUIRED")return E.access({resource:k.resource,api:g,trigger:"initial",status:"blocked",durationMs:d()-X}),x(k.resource,ye==="USER_DATA_SOURCE_NOT_LINKED"?"source_not_linked":"source_login_required");throw ge}const me=await b(k.resource,ue.userId,ne,ie,B);return"status"in me?(E.access({resource:k.resource,api:g,trigger:"initial",status:"blocked",durationMs:d()-X}),me):(E.access({resource:k.resource,api:g,trigger:"initial",status:re(Ee)&&Ee.status==="empty"?"empty":g===un?"succeeded":"ready",durationMs:d()-X}),Ee)}catch(ue){throw E.access({resource:k.resource,api:g,trigger:"initial",status:"error",durationMs:d()-X,errorCode:re(ue)?String(ue.code):"REQUEST_FAILED"}),ue}}async function U(g){const k=await T(g);if(!k)throw y("UNAUTHORIZED","请先登录小黑盒");return m.read(k,g,{declared:Object.keys(w()),egressTier:gt(e.runtimePermissions)})}async function L(g,k){const B=v(g);let Q=await T(k);if(Q||(await e.account.ensureAuthenticated({trustedUserGesture:!0,reason:"user_action",signal:k.signal}),Q=await T(k)),!Q)return{status:"cancelled"};let X=await m.evaluate(Q,{resource:g,egressTier:gt(e.runtimePermissions)},k);if(X.status==="allowed")return{status:"allowed"};if(X.status==="denied"){if(e.presentation?.openDataPermissions){const Me=r,ke=l(g),ze=await e.presentation.openDataPermissions({resource:g,miniProgramName:e.miniProgramPresentation?.name,signal:k.signal});if(!("status"in await b(g,Q,Me,ke,k)))return{status:"allowed"};if(!ze)return{status:"cancelled"}}return X=await m.evaluate(Q,{resource:g,egressTier:gt(e.runtimePermissions)},k),{status:X.status==="allowed"?"allowed":"denied"}}if(!e.presentation?.confirmDataPermission)throw y("REQUEST_UNSUPPORTED","当前宿主不支持资料许可弹窗");M(g);const ne=new AbortController;s.set(g,ne);const ie=()=>ne.abort();k.signal.addEventListener("abort",ie,{once:!0}),k.signal.aborted&&ie();const ue={...k,signal:ne.signal},Ee=r,me=l(g),ge=m,ye=E.beginFlow({resource:g,actionType:"permission"});let Oe="error";try{const ke=(await ge.read(Q,ue,{egressTier:gt(e.runtimePermissions)})).resources.find(Ft=>Ft.resource===g);E.action({resource:g,flowId:ye,stage:"start",actionType:"permission"}),E.permissionShow({resource:g,flowId:ye,entry:"other",reason:ke?.decision==="allow"?"scope_changed":"first"});const ze=await fe(()=>e.presentation.confirmDataPermission({miniProgramName:e.miniProgramPresentation?.name,resource:g,scopeText:`此黑盒账号关联的${B.name}${B.operations.includes("sync")?`。${Ym}`:""}`,purposeText:u(g),egress:gt(e.runtimePermissions),canPersist:ge.canPersist,signal:ne.signal}),ne.signal);if(S(ue),r!==Ee||await T(ue)!==Q||l(g)!==me)throw y("AUTHORIZATION_CONTEXT_CHANGED","资料许可范围已变化");return ze.decision==="cancelled"?(Oe="cancelled",E.permissionResult({resource:g,flowId:ye,choice:"cancel",applyResult:"cancelled"}),{status:"cancelled"}):(await ge.decide({userId:Q,resource:g,decision:ze.decision==="deny"?"deny":"allow",scope:ze.decision==="session"?"session":"persistent",egressTier:gt(e.runtimePermissions),expectedRevision:ke?.revision??0,expectedFingerprint:ke?.scopeFingerprint},ue),ze.decision==="deny"&&p(g),Oe=ze.decision==="deny"?"unresolved":"resolved",E.permissionResult({resource:g,flowId:ye,choice:ze.decision,applyResult:"applied"}),{status:ze.decision==="deny"?"denied":"allowed"})}catch(Me){throw Oe=ue.signal.aborted?"cancelled":"error",E.permissionResult({resource:g,flowId:ye,choice:"cancel",applyResult:ue.signal.aborted?"cancelled":"error"}),Me}finally{E.action({resource:g,flowId:ye,stage:"finish",actionType:"permission",outcome:Oe}),k.signal.removeEventListener("abort",ie),s.get(g)===ne&&s.delete(g)}}async function C(g,k,B,Q,X,ne){k==="allow"?v(g):f(g);const ie=await T(Q);if(!ie)throw y("UNAUTHORIZED","请先登录小黑盒");try{await m.decide({userId:ie,resource:g,decision:k,scope:B,expectedRevision:X,expectedFingerprint:ne,egressTier:gt(e.runtimePermissions)},Q)}catch(ue){throw re(ue)&&ue.code==="USER_DATA_PERMISSION_SAVE_FAILED"&&p(g),ue}return M(g),k!=="allow"&&p(g),U(Q)}async function H(g,k,B){try{const Q=await B();return E.permissionManage({operation:g,resource:k,applyResult:"applied"}),Q}catch(Q){throw E.permissionManage({operation:g,resource:k,applyResult:re(Q)&&Q.code==="USER_DATA_PERMISSION_SAVE_FAILED"?"save_failed":"error"}),Q}}async function F(g,k){M(g),p(g);const B=await T(k);if(!B)throw y("UNAUTHORIZED","请先登录小黑盒");return H("revoke",g,async()=>(await m.revokeSession({userId:B,resource:g},k),U(k)))}function $(){let g;const k=B=>I(e.operationContext,async Q=>{const X=await T(Q);if(!X)throw y("UNAUTHORIZED","请先登录小黑盒");if(g&&(g.userId!==X||g.generation!==r))throw y("AUTHORIZATION_CONTEXT_CHANGED","管理页面所属账号已变化,请重新打开");return g??={userId:X,generation:r},B(Q)});return{getSnapshot:()=>k(U),setDecision:B=>k(Q=>H("modify",B.resource,()=>C(B.resource,B.decision,B.scope,Q,B.expectedRevision,B.expectedFingerprint))),revokeSession:B=>k(Q=>F(B?.resource,Q)),resetAll:()=>k(async B=>{M(),p();const Q=await T(B);return H("reset",void 0,async()=>(await m.reset({userId:Q},B),U(B)))})}}return{handlers:{[Ca]:async(g,k)=>I(k,async B=>{if(g!==void 0&&(!re(g)||Object.keys(g).some(ne=>ne!=="game")||g.game!==void 0&&typeof g.game!="string"))throw y("INVALID_PARAMS","概览参数无效");if(re(g)&&typeof g.game=="string"&&!bc(g.game))throw y("REQUEST_UNSUPPORTED","当前宿主尚未开放该游戏");const Q=Object.keys(w()),X=re(g)?g.game:void 0;return Ml.filter(ne=>X===void 0||ne===X).map(ne=>({game:ne,name:Nl[ne],resources:tr.filter(ie=>ie.game===ne&&Q.includes(ie.key)).map(ie=>({resource:ie.key,name:ie.name,status:"not_checked",statusText:"尚未检查"}))})).filter(ne=>ne.resources.length>0)}),[Ai]:async(g,k)=>I(k,B=>{const Q=O(g,"query");return j(Ai,Q,B,()=>_.query(Q,B))}),[un]:async(g,k)=>I(k,async B=>{if(!re(g)||Object.keys(g).length!==1||typeof g.game!="string"||!bc(g.game))throw y("INVALID_PARAMS","同步需要指定已开放的游戏");const Q={game:g.game};if(!tr.some(Ee=>Ee.game===Q.game&&Ee.sync))throw y("REQUEST_UNSUPPORTED","该游戏不支持存档同步");const X=tr.filter(Ee=>Ee.game===Q.game&&Ee.sync&&u(Ee.key));if(X.length===0)throw y("USER_DATA_RESOURCE_NOT_DECLARED","小程序未声明可同步的资料");let ne,ie;for(const Ee of X){const me=await N(Ee.key,B);if(!("status"in me)){ne=Ee.key;break}(!ie||ie.reason==="permission_denied")&&(ie=me)}if(!ne)return ie;const ue={resource:ne};return j(un,ue,B,async()=>{const Ee=await T(B),me=`${Ee}\0${ue.resource}`;let ge=c.get(me);if(!ge){const ye=new AbortController;o.set(ye,ue.resource);const Oe={controller:ye,waiters:0,settled:!1,promise:Promise.resolve(void 0)};Oe.promise=_.sync(ue,{...e.operationContext,signal:ye.signal},{userId:Ee,miniProgramId:e.identity.get()?.miniProgramId??""}).finally(()=>{Oe.settled=!0,o.delete(ye),c.get(me)===Oe&&c.delete(me)}),Oe.promise.catch(()=>{}),c.set(me,Oe),ge=Oe}ge.waiters++;try{return await fe(()=>ge.promise,B.signal)}finally{ge.waiters--,ge.waiters===0&&!ge.settled&&ge.controller.abort()}})}),[_i]:async(g,k)=>I(k,async B=>{const Q=O(g,"file"),X=await T(B),ne=r,ie=l(Q.resource),ue=async me=>{try{const ge=await b(Q.resource,X,ne,ie,me);if("status"in ge)throw y("FILE_ACCESS_REVOKED","文件授权已撤销",{reason:ge.reason})}catch(ge){throw re(ge)&&["AUTHORIZATION_CONTEXT_CHANGED","USER_DATA_RESOURCE_NOT_DECLARED"].includes(String(ge.code))?y("FILE_ACCESS_REVOKED","文件授权已失效",{causeCode:ge.code}):ge}};let Ee;try{const me=await j(_i,Q,B,async()=>(Ee=await _.file(Q,B,ue),{handle:Ee}));if(re(me)&&me.status==="blocked"){const Me=String(me.reason);throw y(Me==="source_not_linked"?"USER_DATA_SOURCE_NOT_LINKED":Me==="source_login_required"?"USER_DATA_SOURCE_LOGIN_REQUIRED":Me==="login_required"?"UNAUTHORIZED":"PERMISSION_DENIED",String(me.message),{reason:Me})}const ge=me.handle,ye={...ge,read:async Me=>{await ue(Me);const ke=await ge.read(Me);try{return await ue(Me),ke}catch(ze){throw ke.fill(0),ze}},stat:async Me=>{await ue(Me);const ke=await ge.stat(Me);return await ue(Me),ke}},Oe=e.fileRegistry.registerFile(ye,"download","read");return"handleId"in Oe.ref&&a.add(Oe.ref.handleId),Oe}catch(me){throw Ee&&await _.releaseFile(Ee),me}}),[La]:async(g,k)=>{if(!k.trustedUserGesture)throw y("USER_GESTURE_REQUIRED","许可操作需要点击");return I(k,B=>{if(!re(g)||Object.keys(g).length!==1||typeof g.resource!="string"||!kt(g.resource))throw y("INVALID_PARAMS","许可资源无效");return L(g.resource,B)})},[Ua]:async(g,k)=>I(k,U),[xa]:async(g,k)=>{if(!k.trustedUserGesture)throw y("USER_GESTURE_REQUIRED","修改许可需要点击");if(!re(g)||typeof g.resource!="string"||!kt(g.resource)||g.decision!=="deny"||g.scope!=="persistent"||Object.keys(g).some(B=>!["resource","decision","scope"].includes(B)))throw y("INVALID_PARAMS","允许许可只能由可信弹窗确认");return I(k,B=>C(g.resource,g.decision,"persistent",B))},[za]:async(g,k)=>{if(!k.trustedUserGesture)throw y("USER_GESTURE_REQUIRED","管理资料许可需要点击");if(!e.presentation?.openDataPermissions)throw y("REQUEST_UNSUPPORTED","宿主未提供资料管理界面");if(g!==void 0&&(!re(g)||Object.keys(g).some(B=>B!=="resource")||g.resource!==void 0&&(typeof g.resource!="string"||!kt(g.resource))))throw y("INVALID_PARAMS","管理资源无效");return I(k,async B=>(await e.presentation.openDataPermissions({resource:re(g)?g.resource:void 0,miniProgramName:e.miniProgramPresentation?.name,signal:B.signal}),U(B)))},[ja]:async(g,k)=>{if(!k.trustedUserGesture)throw y("USER_GESTURE_REQUIRED","撤销许可需要点击");if(g!==void 0&&(!re(g)||Object.keys(g).some(B=>B!=="resource")||g.resource!==void 0&&(typeof g.resource!="string"||!kt(g.resource))))throw y("INVALID_PARAMS","撤销资源无效");return I(k,B=>F(re(g)?g.resource:void 0,B))}},get permissionBridge(){return $()},diagnostics:{telemetry:E.diagnostics},dispose(){t||(t=!0,z(),A(),e.operationContext.signal.removeEventListener("abort",D),m.dispose(),E.dispose())}}}function nu(e){throw{code:"INVALID_PARAMS",message:e}}function rn(e,t){const r=Number(e);return Number.isFinite(r)&&r>0?r:t}function ih(e,t){const r=Number(e);return Number.isFinite(r)&&r>=0?r:t}function Jn(e,t,r){return Math.min(ih(e,t),r)}async function U_(e){try{return ih(await e.getNavigationBarHeight(),0)}catch{return 0}}function x_(e,t,r,n){const i=Jn(e.safeArea?.left,0,t),o=Math.max(i,Jn(e.safeArea?.right,t,t)),s=Jn(e.safeArea?.top,n,r),a=Math.max(s,Jn(e.safeArea?.bottom,r,r));return{left:i,right:o,top:s,bottom:a,width:o-i,height:a-s}}async function iu(e){const t=e.getViewportMetrics(),r=rn(t.windowWidth,0),n=rn(t.windowHeight,0),i=await U_(e);return{pixelRatio:rn(t.pixelRatio,1),screenWidth:rn(t.screenWidth,r),screenHeight:rn(t.screenHeight,n),windowWidth:r,windowHeight:n,statusBarHeight:i,safeArea:x_(t,r,n,i),screenTop:i}}function z_(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 f=++i;iu(r.presentation).then(l=>{if(n||r.operationContext.signal.aborted||f!==i)return;const h=JSON.stringify(l);h!==o&&(o=h,r.onViewportChange?.(l))}).catch(()=>{})},c=YI({...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:{[nr]:async(f,l)=>c.apply(f,l?.signal),[Li]:async()=>(pe(r.operationContext.signal),iu(r.presentation)),[Ui]:async f=>{if(pe(r.operationContext.signal),typeof f!="object"||f===null||Array.isArray(f))return nu("viewport.setNavigationBarStyle 参数必须是对象");const l=f.foregroundStyle;if(l!=="light"&&l!=="dark")return nu("viewport.setNavigationBarStyle foregroundStyle 必须是 light 或 dark");await fe(()=>r.presentation.setNavigationBarStyle(l,e.operationContext),r.operationContext.signal)}},runDisplayRequest:c.runDisplayRequest,applyOrientation:(f,l)=>c.apply({orientation:f.mode,fullscreen:f.hideCapsule},l),notifyChange:()=>{o=void 0,a()},dispose:d}}function j_(e){if(e===void 0)return{};if(!e||typeof e!="object"||Array.isArray(e))throw we("INVALID_PARAMS","工作区卡片刷新参数必须是对象");const t=e;if(Object.keys(t).some(i=>i!=="gameAppId"&&i!=="cardIds"))throw we("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 we("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 we("INVALID_PARAMS","工作区卡片编号无效");return{...r===void 0?{}:{gameAppId:r},...n===void 0?{}:{cardIds:[...n]}}}function B_(e,t){return{[Di]:async(r,n)=>{const i=Se(t,n.signal,n.requestId);if(pe(i.signal),!e)throw we("CAPABILITY_UNAVAILABLE","当前 Host 不支持工作区卡片");const o=j_(r),s=await fe(()=>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 we("HOST_INVALID_RESPONSE","工作区卡片刷新回执无效");return{scheduled:s.scheduled}}}}const H_=new Map(zt.map(e=>[e.method,e]));function cs(e,t,r){return{code:e,message:t,...r===void 0?{}:{data:r}}}function F_(e){const t=Kl(e);return r=>t(r.requirement,r.method)}function V_(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 G_(e){const t=F_(e.runtimePermissions),r=qe(e.runtimePermissions);let n=0;return{async dispatch(i,o,s){const a=e.now??$_,c=e.onTrace?a():0,d=e.onTrace?Date.now():0,u=e.onTrace?s.requestId??`runtime_${++n}`:"";e.onTrace&&ds(e.onTrace,{callId:u,method:i,startedAt:d,outcome:"started"},()=>c,c);try{if(e.terminalSignal.aborted)throw cs("RUNTIME_DESTROYED","小程序 Runtime 已终止");Gl(i,e.effectiveCapabilities);const f=H_.get(i);if(!f)throw new Error(`Capability method ${i} 缺少 protocol metadata`);const l=t(f),h=!l.allowed&&r.valid&&r.permissions.companion?.status==="enabled"&&e.allowsCompanionAttachmentAccess?.(i,o)===!0,m=!l.allowed&&r.valid&&r.permissions.gameSaves?.status==="enabled"&&e.allowsGameSaveAccess?.(i,o)===!0,E=!l.allowed&&r.valid&&r.permissions.user_game_data?.status==="enabled"&&e.allowsUserGameDataFileAccess?.(i,o)===!0;if(!l.allowed&&!h&&!m&&!E)throw cs(l.code,l.message,l.data);const _=e.handlers[i];if(!_)throw new Error(`Capability method ${i} 缺少 handler`);const w=async M=>{for(const z of e.policies??[]){const A=await z.evaluate({method:i,payload:o,capability:f});if(e.terminalSignal.aborted||M.aborted)throw su();if(!A.allowed)throw cs(A.code,A.message,A.data)}if(e.terminalSignal.aborted||M.aborted)throw su()},p=await V_(async()=>{if(i===nr){if(!e.runDisplayRequest)throw new Error("viewport.setDisplay 缺少执行 Module");return e.runDisplayRequest(o,s.signal,w)}return await w(e.terminalSignal),_(o,s)},void 0,s,e.terminalSignal);return e.onTrace&&ds(e.onTrace,ou(u,i,o,d,p),a,c),p}catch(f){throw e.onTrace&&ds(e.onTrace,ou(u,i,o,d,{status:"error",error:f}),a,c),f}}}}function $_(){return typeof performance>"u"?Date.now():performance.now()}function ds(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 ou(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:q_(i.error)}:{},...Q_(t,r,i)}}function q_(e){return typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"?e.code:void 0}function Q_(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"&&la(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 la(e){return typeof e=="object"&&e!==null}function su(){const e=new Error("The operation was aborted");return e.name="AbortError",e}function Y_(e){const t={signal:e.terminalSignal,...e.miniProgramDetail===void 0?{}:{miniProgramDetail:e.miniProgramDetail}},r=gE(e.requestPolicy);let n;if(e.files)try{n=oE(e.files,t)}catch{}const i=cf({store:n}),o=e.onRequestPolicyReport??(r.debugReport?W_:void 0),s=r.enabled?lE({...r.gateOptions,...o?{onReport:o}:{}}):void 0,a=new Za(e.files,e.miniProgramDetail),c=tI({registry:a,picker:e.picker,operationContext:t}),d=HE({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,f,l,h,m,E,_=()=>{},w=()=>{};try{u=z_({operationContext:t,presentation:e.hostPresentation,onDisplayChange:b=>e.eventSink.postEvent("display_change",b),onViewportChange:b=>e.eventSink.postEvent("viewport_change",b)}),l=u_({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}),_=d.onEvent((b,O)=>e.eventSink.postEvent(b,O)),w=e.hostCompanion?.onSessionEvent?.(b=>{const O=Ww(b);!e.terminalSignal.aborted&&O&&e.eventSink.postEvent(O.type,O.payload)})??(()=>{}),h=_w({authorizationContext:e.authorizationContext,account:e.account,identity:e.identity,network:e.network,operationContext:t,requestGate:s,requestPolicyEnabled:r.enabled});const S=e.files&&e.transfer?Xa({files:e.files,transfer:e.transfer,registry:a,signal:t.signal}):void 0,p=L_({identity:e.identity,account:e.account,storage:e.storage,network:e.network,authorizationContext:e.authorizationContext,files:e.files,transfer:e.transfer,fileDownloads:S,requestGate:s,requestPolicyEnabled:r.enabled,fileRegistry:a,...e.userDataPresentation===void 0?{}:{presentation:e.userDataPresentation},...e.miniProgramPresentation===void 0?{}:{miniProgramPresentation:e.miniProgramPresentation},runtimePermissions:e.runtimePermissions,environment:e.miniProgramDetail?.releaseChannel,operationContext:t,...e.onUserDataTelemetry===void 0?{}:{telemetry:{sink:{postEvent(b,O){e.onUserDataTelemetry?.({name:b,payload:O})}}}}});E=p,m=Cw({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,fileDownloads:S,requestGate:s,requestPolicyEnabled:r.enabled});const M=BA({storage:e.storage,scopedStorage:e.scopedStorage,storageDiagnostics:e.storageDiagnostics,identity:e.identity,operationContext:t,anonymousStorageScope:e.anonymousStorageScope,storageLimits:e.storageLimits});f=NI({registry:a,media:e.media,operationContext:t});const z=[{name:"gameSaves",handlers:Object.fromEntries(Object.entries(m.handlers).map(([b,O])=>[b,async(j,U)=>{const L=e.verifiedSdkVersion,C=L?ec(L,"0.10.0-0"):void 0;if(C===void 0||C>=0)throw y("REQUEST_UNSUPPORTED","当前 SDK 不支持旧游戏存档入口,请使用 user.games.get(...).saves");return O(j,U)}]))},{name:"auth",handlers:WE({authorization:d})},{name:"user",handlers:{...I_({user:l,authorization:d,runtimePermissions:e.runtimePermissions,steamAccount:e.runtimeFeatures?.steamAccount===!0,userDataMode:e.runtimeFeatures?.userDataMode}),...Jy({operationContext:t,presentation:e.hostPresentation,miniProgramPresentation:e.miniProgramPresentation})}},{name:"share",handlers:xA({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:M.handlers},{name:"network",handlers:nA({network:e.network,transfer:e.transfer,fileRegistry:a,operationContext:t,runtimePermissions:e.runtimePermissions,allowedHttpOrigins:e.allowedHttpOrigins,networkPolicy:e.networkPolicy,firstParty:e.firstParty})},{name:"workspaceCards",handlers:B_(e.workspaceCards,t)},{name:"files",handlers:c.files},{name:"file",handlers:c.file},{name:"directory",handlers:c.directory},{name:"media",handlers:f.handlers},{name:"ui",handlers:$A({operationContext:t,presentation:e.hostPresentation})},{name:"device",handlers:Xw({operationContext:t,presentation:e.hostPresentation,protocol:e.hostProtocol})},{name:"navigation",handlers:WI({operationContext:t,presentation:e.hostPresentation,...e.hostPresentation.applyOrientation?{resetDisplay:b=>u.applyOrientation({mode:"portrait",hideCapsule:!1},b)}:{}})},{name:"cloud",handlers:h.handlers},{name:"userGameData",handlers:E.handlers},{name:"companion",handlers:Gw({companion:e.hostCompanion,companionPresentation:e.companionPresentation,miniProgramPresentation:e.miniProgramPresentation,operationContext:t,fileRegistry:a})}],A=Z_(z);let D=!1;const I=()=>{D||(D=!0,e.terminalSignal.removeEventListener("abort",I),u?.dispose(),f?.dispose(),h?.dispose(),m?.dispose(),E?.dispose(),_(),w(),l?.dispose(),i.dispose(),d.dispose(),s?.dispose(),a.dispose())};e.terminalSignal.aborted?I():e.terminalSignal.addEventListener("abort",I,{once:!0});const v=new Set(["file.readText","file.readBytes","file.stat"]),T=(b,O)=>v.has(b)&&la(O)&&a.isCompanionAttachmentRef(O.target),x=new Set(["file.readText","file.readBytes","file.stat","file.exists"]),N=(b,O)=>x.has(b)&&la(O)&&a.isUserDataDownloadRef(O.target);return{get permissionBridge(){return p.permissionBridge},modules:z,handlers:A,runDisplayRequest:u.runDisplayRequest,allowsCompanionAttachmentAccess:T,allowsGameSaveAccess:m.allowsRead,allowsUserGameDataFileAccess:N,gameSaveDiagnostics:m.diagnostics,applyOrientation:u.applyOrientation,notifyViewportChange:u.notifyChange,...M.diagnostics?{storageDiagnostics:M.diagnostics}:{},...e.files?{sandboxDiagnostics:uI({registry:a,operationContext:t,runtimePermissions:e.runtimePermissions,capabilities:e.diagnosticCapabilities})}:{},dispose:I}}catch(S){throw u?.dispose(),f?.dispose(),h?.dispose(),m?.dispose(),E?.dispose(),_(),w(),l?.dispose(),i.dispose(),d.dispose(),s?.dispose(),a.dispose(),S}}function W_(e){try{console.warn("[hb-sdk-runtime] request-policy",e)}catch{}}function Z_(e){const t=new Map(zt.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=zt.map(i=>i.method).filter(i=>!r.has(i));if(n.length>0)throw new Error(`Capability registry 缺少 method: ${n.join(", ")}`);if(r.size!==zt.length)throw new Error(`Capability registry method 数量不合法: ${r.size}`);return Object.freeze(Object.fromEntries(r))}const K_="heybox-mini-dev:";function au(e){try{return J_(new URL(e))}catch{return!1}}function J_(e){return e.protocol===K_}function X_(e){return e==="localhost"||e==="127.0.0.1"||e==="[::1]"||eD(e)}function eD(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 tD=new Set(["android","ios","ohos","windows","macos","linux","unknown"]);function rD(e,t){const r=[],n=nD(e.environmentInfo,r),i=li(n?.appVersion,"host.appVersion",r),o=oD(n?.operatingSystem,r);return{info:Object.freeze({runtime:Object.freeze({mode:iD(e.sdkVersionPolicy?.releaseChannel,r)}),host:Object.freeze({appVersion:i}),miniProgram:Object.freeze({id:li(t.miniProgramId),version:li(t.miniProgramVersion)}),operatingSystem:Object.freeze(o)}),invalidFields:Object.freeze(r)}}function nD(e,t){if(e!=null){if(oh(e))return e;t.push("environmentInfo")}}function iD(e,t){return e==="public"?"production":e==="preview"||e==="development"?e:(e!=null&&t.push("runtime.mode"),"unknown")}function oD(e,t){if(e==null)return{name:"unknown",version:null};if(!oh(e))return t.push("operatingSystem"),{name:"unknown",version:null};const r=tD.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:li(e.version,"operatingSystem.version",t)}}function li(e,t,r){return e==null?null:typeof e=="string"&&e.trim()?e.trim():(t&&r&&r.push(t),null)}function oh(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const sD="data:image/svg+xml;base64,PHN2ZyBwcmVzZXJ2ZUFzcGVjdFJhdGlvPSJub25lIiBvdmVyZmxvdz0idmlzaWJsZSIgc3R5bGU9ImRpc3BsYXk6IGJsb2NrOyIgd2lkdGg9IjY3IiBoZWlnaHQ9IjIyIiB2aWV3Qm94PSIwIDAgNjcgMjIiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxwYXRoIGlkPSJTdWJ0cmFjdCIgZD0iTTY2IDBDNjYuMzM3MiAwIDY2LjY3MDYgMC4wMTcxODM4IDY3IDAuMDQ2ODc1QzYxLjM5MzYgMC41NTIxODkgNTcgNS4yNjIwMiA1NyAxMUM1NyAxNi43MzggNjEuMzkzNiAyMS40NDY4IDY3IDIxLjk1MjFDNjYuNjcwNiAyMS45ODE4IDY2LjMzNzIgMjIgNjYgMjJIMTFDNC45MjQ4NyAyMiAwIDE3LjA3NTEgMCAxMUMwIDQuOTI0ODcgNC45MjQ4NyAyLjY1NzU2ZS0wNyAxMSAwSDY2Wk04LjI0MzE2IDYuNzM1MzVDOC4yNDMxNiA2LjU5Mzk3IDguMTQyNTggNi41MzU3NiA4LjAxOTUzIDYuNjA2NDVMNi4yMjI2NiA3LjY0MDYyQzYuMTU3ODcgNy42ODIyOCA2LjEwNDE2IDcuNzM5MTcgNi4wNjU0MyA3LjgwNTY2QzYuMDI2NzIgNy44NzIyNyA2LjAwNDEgNy45NDc1MiA2IDguMDI0NDFWMTMuOTY1OEM2LjAwMzcxIDE0LjA0MzQgNi4wMjU4NSAxNC4xMTkxIDYuMDY0NDUgMTQuMTg2NUM2LjEwMzE5IDE0LjI1NCA2LjE1NzQgMTQuMzEyIDYuMjIyNjYgMTQuMzU0NUw5Ljg3MTA5IDE2LjQ1OEM5Ljk5MzQ2IDE2LjUyNzIgMTAuMDkzNiAxNi41ODQyIDEwLjA5NDcgMTYuNTg1OUMxMC4wOTQ3IDE2LjU4NzEgMTAuMTkzNCAxNi42NDUxIDEwLjMxNjQgMTYuNzE1OEwxMi41MDEgMTcuOTY5N0MxMi42MjI4IDE4LjA0MDMgMTIuNzIzNiAxNy45ODIyIDEyLjcyMzYgMTcuODQwOFYxMi4zNjcyQzEyLjcyMyAxMi4yOTk0IDEyLjY5NTcgMTIuMjM0MyAxMi42NDc1IDEyLjE4NjVDMTIuNTk5MiAxMi4xMzg4IDEyLjUzMzggMTIuMTEyMyAxMi40NjU4IDEyLjExMjNIMTAuNzM3M0MxMC42NzAyIDEyLjExMzIgMTAuNjA1OSAxMi4xMzk5IDEwLjU1ODYgMTIuMTg3NUMxMC41MTEzIDEyLjIzNTIgMTAuNDg0NyAxMi4zMDAxIDEwLjQ4NDQgMTIuMzY3MlYxMy44Mzc5QzEwLjQ4NDIgMTMuOTc4OSAxMC4zODQ2IDE0LjAzNjQgMTAuMjYxNyAxMy45NjU4TDguNDY0ODQgMTIuOTM1NUM4LjQwMDI2IDEyLjg5MzUgOC4zNDYxNCAxMi44MzcyIDguMzA3NjIgMTIuNzcwNUM4LjI2OTE5IDEyLjcwNCA4LjI0NzM1IDEyLjYyOTQgOC4yNDMxNiAxMi41NTI3VjYuNzM1MzVaTTI0LjMzNCAxNC4zOTI2QzI0LjMzMzkgMTQuOTk4NSAyNC4yMDU1IDE1LjE4NDYgMjMuNTk4NiAxNS4xOTYzTDIyLjMwMTggMTUuMjU0OUwyMi42NjUgMTYuMjU0OUgyNS4wODY5QzI1LjY3MDUgMTYuMDg0IDI1Ljg3MjEgMTUuNzE5NCAyNS44NzIxIDE0LjgyMzJWNS43ODIyM0wyNC4zMzQgNS43MjM2M1YxNC4zOTI2Wk0zMi4yODIyIDE0LjQ3NTZDMzEuOTQ2IDE1LjA0OTIgMzEuNDY1OSAxNS43NTcxIDMxLjA5OTYgMTYuMjU0OUgzMi42MTkxQzMzLjA2NzMgMTUuNTIxMiAzMy4zNzUxIDE0LjkyOCAzMy41NDg4IDE0LjQ3NTZIMzIuMjgyMlpNMzQuODEwNSAxNS4zOTc1QzM0Ljg3OTEgMTUuNzEwMSAzNC45MzExIDE1Ljk5ODIgMzQuOTczNiAxNi4yNTQ5SDM2LjE4NjVMMzYuMTgxNiAxNi4yMzU0QzM2LjA2NjIgMTUuNzM4OCAzNS44OTg5IDE1LjAxOCAzNS43NDEyIDE0LjQ3NTZIMzQuNTI5M0wzNC44MTA1IDE1LjM5NzVaTTM2Ljk4MTQgMTQuNjUzM0MzNy4wOTg0IDE0Ljg3NyAzNy4yNDExIDE1LjE1MDEgMzcuMzMzIDE1LjQwMjNMMzcuNjM1NyAxNi4yNTQ5SDM5LjA4MDFDMzkuMDMzNiAxNS44MzI1IDM4LjU5NCAxNS4wNTUzIDM4LjIzODMgMTQuNDc1NkgzNi44ODg3QzM2LjkxNjEgMTQuNTI5OCAzNi45NDggMTQuNTg5NCAzNi45ODE0IDE0LjY1MzNaTTM5LjI3MDUgMTQuNDc1NkMzOS44MzAxIDE1LjE4MjEgNDAuMTg2MyAxNS44MDA0IDQwLjQxMzEgMTYuMjU0OUg0MS44MzVDNDEuNzM2NyAxNS42NjU2IDQxLjIyOTIgMTQuOTkzNiA0MC43NzY0IDE0LjQ3NTZIMzkuMjcwNVpNNDMuOTIyOSAxNS4wMDQ5SDQyLjc2NjZWMTUuOTk2MUg1My4xMjVWMTUuMDA0OUg1MS45Njg4VjEyLjQ3NTZINDMuOTIyOVYxNS4wMDQ5Wk0xMC43MDQxIDQuMDMwMjdDMTAuNTgxMSAzLjk1OTU4IDEwLjQ4MDUgNC4wMTc4IDEwLjQ4MDUgNC4xNTkxOFY5LjYyMzA1QzEwLjQ4MDYgOS42OTA3NCAxMC41MDc4IDkuNzU1NzggMTAuNTU1NyA5LjgwMzcxQzEwLjYwMzcgOS44NTE3MSAxMC42NjkzIDkuODc4ODcgMTAuNzM3MyA5Ljg3ODkxSDEyLjQ2NDhDMTIuNDk4NiA5Ljg3OTA1IDEyLjUzMjIgOS44NzIxNyAxMi41NjM1IDkuODU5MzhDMTIuNTk0NCA5Ljg0NjY2IDEyLjYyMjcgOS44MjgyMSAxMi42NDY1IDkuODA0NjlDMTIuNjcwNCA5Ljc4MDg5IDEyLjY5MDIgOS43NTE4NSAxMi43MDMxIDkuNzIwN0MxMi43MTYgOS42ODk3NSAxMi43MjI2IDkuNjU2NTQgMTIuNzIyNyA5LjYyMzA1VjguMTUyMzRDMTIuNzIyNyA4LjAxMSAxMi44MjIzIDcuOTUyODIgMTIuOTQ1MyA4LjAyMzQ0TDE0Ljc0MTIgOS4wNjE1MkMxNC44MDYgOS4xMDM2MiAxNC44NTk3IDkuMTYwNzcgMTQuODk4NCA5LjIyNzU0QzE0LjkzNzEgOS4yOTQzIDE0Ljk1OTYgOS4zNjkyOSAxNC45NjM5IDkuNDQ2MjlWMTUuMjU5OEMxNC45NjQxIDE1LjQwMDcgMTUuMDYzNyAxNS40NTcgMTUuMTg2NSAxNS4zODc3TDE2Ljk4NDQgMTQuMzUwNkMxNy4wNDkgMTQuMzA4NyAxNy4xMDMgMTQuMjUyMSAxNy4xNDE2IDE0LjE4NTVDMTcuMTgwMyAxNC4xMTg3IDE3LjIwMyAxNC4wNDMgMTcuMjA3IDEzLjk2NThWOC4wMjQ0MUMxNy4yMDI5IDcuOTQ3MzYgMTcuMTgwMyA3Ljg3MjQ2IDE3LjE0MTYgNy44MDU2NkMxNy4xMDI5IDcuNzM4ODQgMTcuMDQ5MyA3LjY4MTY0IDE2Ljk4NDQgNy42Mzk2NUwxMS44MjMyIDQuNjY3OTdDMTEuNzAwMiA0LjU5NzI4IDExLjU5NzcgNC41NDEwMiAxMS41OTc3IDQuNTQxMDJDMTEuNTg0NiA0LjUzMDQ3IDExLjQ4NzkgNC40ODIxMyAxMS4zNzIxIDQuNDE1MDRMMTAuNzA0MSA0LjAzMDI3Wk00Ni4yNDcxIDE1LjAwNDlINDUuMDkwOFYxMy4zMzY5SDQ2LjI0NzFWMTUuMDA0OVpNNDguNTI0NCAxNS4wMDQ5SDQ3LjM3OTlWMTMuMzM2OUg0OC41MjQ0VjE1LjAwNDlaTTUwLjgzNTkgMTUuMDA0OUg0OS42NTcyVjEzLjMzNjlINTAuODM1OVYxNS4wMDQ5Wk0zMi4wNjE1IDEwLjM2NTJIMzUuODAwOFYxMC45ODI0SDMxLjk4NjNWMTIuMDkwOEgzNS44MDA4VjEyLjc1NDlIMzEuMjUxVjEzLjgyNzFINDEuNzY1NlYxMi43NTQ5SDM3LjI2MjdWMTIuMDkwOEg0MS4wMjkzVjEwLjk4MjRIMzcuMjYyN1YxMC4zNjUySDM5Ljg1ODRDNDAuNDYzNCAxMC4zNjUyIDQwLjk1NCA5Ljg3NTQzIDQwLjk1NDEgOS4yNzE0OFY2LjAxNjZIMzIuMDYxNVYxMC4zNjUyWk0yMS4yNDQxIDguMzAzNzFDMjAuOTY4NiA5LjU3MTM4IDIwLjcxMzcgMTAuNTAxIDIwLjQ4MDUgMTEuMDkzOEMyMC4yNDcyIDExLjY4NjMgMTkuODEyNiAxMi41MDg2IDE5LjE3NDggMTMuNTYyNUwxOS4xMTUyIDEzLjY2MTFIMjAuNTc5MUwyMC41OTg2IDEzLjYzMzhDMjEuMzE2NiAxMi42MTg4IDIxLjgwNzUgMTEuNzYwNCAyMi4wNjc0IDExLjA1OTZDMjIuMzI1NyAxMC4zNjI4IDIyLjU4MzUgOS40NTMxMSAyMi44NDA4IDguMzMyMDNMMjIuODU4NCA4LjI1MjkzSDIxLjI1NDlMMjEuMjQ0MSA4LjMwMzcxWk0yNy4xOTA0IDguNjk4MjRDMjcuNDE5MiA5LjY1Mjc1IDI3LjY0ODMgMTAuNDQwMiAyNy44Nzc5IDExLjA1OTZDMjguMTM3OCAxMS43NjAzIDI4LjYyNzggMTIuNjE4OSAyOS4zNDU3IDEzLjYzMzhMMjkuMzY1MiAxMy42NjExSDMwLjgyOTFMMzAuNjE0MyAxMy4zMDQ3QzMwLjA2MDQgMTIuMzczNiAyOS42Nzc2IDExLjYzNjggMjkuNDYzOSAxMS4wOTM4QzI5LjIzMDYgMTAuNTAxIDI4Ljk3NTggOS41NzEzOCAyOC43MDAyIDguMzAzNzFMMjguNjg5NSA4LjI1MjkzSDI3LjA4NTlMMjcuMTkwNCA4LjY5ODI0Wk00NC4zNTQ1IDExLjg5MjZINTAuNDc2NkM1MS4wODE1IDExLjg5MjUgNTEuNTcyMSAxMS40MDI3IDUxLjU3MjMgMTAuNzk4OFY5LjM1MDU5SDQ0LjM1NDVWMTEuODkyNlpNNTAuNDI3NyAxMC40MDE0QzUwLjQyNzUgMTAuNzAzMiA1MC4xODIzIDEwLjk0ODIgNDkuODc5OSAxMC45NDgySDQ1LjQ5OVYxMC4yODMySDUwLjQyNzdWMTAuNDAxNFpNMzUuODAwOCA5LjI1NzgxSDMzLjI1MjlWNi45NDgyNEgzNS44MDA4VjkuMjU3ODFaTTM5Ljc2MzcgOC43MTA5NEMzOS43NjM1IDkuMDEyNjYgMzkuNTE4MSA5LjI1NzYgMzkuMjE1OCA5LjI1NzgxSDM3LjI2MjdWNi45NDgyNEgzOS43NjM3VjguNzEwOTRaTTQ3LjQ1NDEgNS41ODU5NEM0Ni4yMTQ0IDYuOTI4NCA0NC41Mzc1IDcuODYyNTcgNDIuNjQ5NCA4LjE2NDA2VjkuMDczMjRDNDMuNDc4NiA4Ljk1Mjc3IDQ0LjY1ODcgOC43NTU5OCA0NS4zNzExIDguNDA2MjVWOC43NDMxNkg1MC41NDM5VjguNDE3OTdDNTEuMTk3OCA4Ljc0NDM0IDUyLjQxMjIgOC45NDExMSA1My4yNzY0IDkuMDczMjRMNTMuMjc3MyA4LjE5NjI5QzUzLjI0OCA4LjE4Njc5IDUzLjIxODYgOC4xNzc1MiA1My4xODk1IDguMTY3OTdDNTEuMzA2IDcuODcyNjcgNDkuNjMxNiA2Ljk0OCA0OC4zODk2IDUuNjE2MjFMNDcuNDU0MSA1LjU4NTk0Wk0zMy42OTkyIDcuMTY3OTdDMzMuODU5OCA4LjIyNTk3IDM0LjQ2NTQgOS4wMjk4NiAzNC40Nzc1IDkuMDQ1OUgzNS40NTEyQzM1LjQ0NDIgOS4wMzEwOCAzNC45MzE2IDcuOTM5OTcgMzQuOTMxNiA3LjE2Nzk3SDMzLjY5OTJaTTM4LjExMTMgNy4xNjc5N0MzOC4xMTEzIDcuOTM3OCAzNy42MDE2IDkuMDI1MTEgMzcuNTkxOCA5LjA0NTlIMzguNTY1NEMzOC41ODE1IDkuMDI0NjUgMzkuMTgzNyA4LjIyMjQ0IDM5LjM0MzggNy4xNjc5N0gzOC4xMTEzWk00Ny45NjM5IDYuNjExMzNDNDguMzI1OSA3LjA0MjU0IDQ4Ljg3NDggNy40NzQwNiA0OS42MTA0IDcuOTA1MjdINDYuMjkzQzQ3LjA1MjEgNy40NjIyNSA0Ny42MDE4IDcuMDMxMDMgNDcuOTYzOSA2LjYxMTMzWiIgZmlsbD0id2hpdGUiLz4KPC9zdmc+Cg==",aD="data:image/svg+xml;base64,PHN2ZyBwcmVzZXJ2ZUFzcGVjdFJhdGlvPSJub25lIiBvdmVyZmxvdz0idmlzaWJsZSIgc3R5bGU9ImRpc3BsYXk6IGJsb2NrOyIgd2lkdGg9IjEyIiBoZWlnaHQ9IjEyIiB2aWV3Qm94PSIwIDAgMTIgMTIiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxnIGlkPSIxLWNvbW1vbl9zZWFyY2hfbGluZV8yNHgyNCI+CjxnIGlkPSJ1bmlvbiI+CjxwYXRoIGZpbGwtcnVsZT0iZXZlbm9kZCIgY2xpcC1ydWxlPSJldmVub2RkIiBkPSJNNS44NjAxMyAxLjkyNTAxQzMuNzI4NzkgMS45MjUwMSAyLjAwMDAyIDMuNjU0NiAyLjAwMDAyIDUuNzg5MzdDMi4wMDAwMiA3LjkyNDEzIDMuNzI4NzkgOS42NTM3MiA1Ljg2MDEzIDkuNjUzNzJDNy45OTE0NyA5LjY1MzcyIDkuNzIwMjQgNy45MjQxMyA5LjcyMDI0IDUuNzg5MzdDOS43MjAyNCAzLjY1NDYgNy45OTE0NyAxLjkyNTAxIDUuODYwMTMgMS45MjUwMVpNMC44MDAwMjQgNS43ODkzN0MwLjgwMDAyNCAyLjk5Mjk0IDMuMDY0OTcgMC43MjUwMTIgNS44NjAxMyAwLjcyNTAxMkM4LjY1NTI5IDAuNzI1MDEyIDEwLjkyMDIgMi45OTI5NCAxMC45MjAyIDUuNzg5MzdDMTAuOTIwMiA4LjU4NTggOC42NTUyOSAxMC44NTM3IDUuODYwMTMgMTAuODUzN0MzLjA2NDk3IDEwLjg1MzcgMC44MDAwMjQgOC41ODU4IDAuODAwMDI0IDUuNzg5MzdaIiBmaWxsPSJ3aGl0ZSIvPgo8cGF0aCBmaWxsLXJ1bGU9ImV2ZW5vZGQiIGNsaXAtcnVsZT0iZXZlbm9kZCIgZD0iTTkuMDEzMTkgOC45MzQ5N0M5LjI0NzQgOC43MDA1NCA5LjYyNzExIDguNzAwNTQgOS44NjEzMiA4LjkzNDk3TDExLjA1MDggMTAuMTI1NkMxMS4yODUgMTAuMzYgMTEuMjg1IDEwLjc0MDEgMTEuMDUwOCAxMC45NzQ1QzEwLjgxNjYgMTEuMjA4OSAxMC40MzY5IDExLjIwODkgMTAuMjAyNyAxMC45NzQ1TDkuMDEzMTkgOS43ODM5QzguNzc4OTkgOS41NDk0OCA4Ljc3ODk5IDkuMTY5NCA5LjAxMzE5IDguOTM0OTdaIiBmaWxsPSJ3aGl0ZSIvPgo8L2c+CjwvZz4KPC9zdmc+Cg==",cD="data:image/svg+xml;base64,PHN2ZyBwcmVzZXJ2ZUFzcGVjdFJhdGlvPSJub25lIiBvdmVyZmxvdz0idmlzaWJsZSIgc3R5bGU9ImRpc3BsYXk6IGJsb2NrOyIgd2lkdGg9IjY3IiBoZWlnaHQ9IjIyIiB2aWV3Qm94PSIwIDAgNjcgMjIiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxwYXRoIGlkPSJTdWJ0cmFjdCIgZD0iTTY2IDBDNjYuMzM3MiAwIDY2LjY3MDYgMC4wMTcxODM4IDY3IDAuMDQ2ODc1QzYxLjM5MzYgMC41NTIxODkgNTcgNS4yNjIwMiA1NyAxMUM1NyAxNi43MzggNjEuMzkzNiAyMS40NDY4IDY3IDIxLjk1MjFDNjYuNjcwNiAyMS45ODE4IDY2LjMzNzIgMjIgNjYgMjJIMTFDNC45MjQ4NyAyMiAwIDE3LjA3NTEgMCAxMUMwIDQuOTI0ODcgNC45MjQ4NyAyLjY1NzU2ZS0wNyAxMSAwSDY2Wk04LjI0MzE2IDYuNzM1MzVDOC4yNDMxNiA2LjU5Mzk3IDguMTQyNTggNi41MzU3NiA4LjAxOTUzIDYuNjA2NDVMNi4yMjI2NiA3LjY0MDYyQzYuMTU3ODcgNy42ODIyOCA2LjEwNDE2IDcuNzM5MTcgNi4wNjU0MyA3LjgwNTY2QzYuMDI2NzIgNy44NzIyNyA2LjAwNDEgNy45NDc1MiA2IDguMDI0NDFWMTMuOTY1OEM2LjAwMzcxIDE0LjA0MzQgNi4wMjU4NSAxNC4xMTkxIDYuMDY0NDUgMTQuMTg2NUM2LjEwMzE5IDE0LjI1NCA2LjE1NzQgMTQuMzEyIDYuMjIyNjYgMTQuMzU0NUw5Ljg3MTA5IDE2LjQ1OEM5Ljk5MzQ2IDE2LjUyNzIgMTAuMDkzNiAxNi41ODQyIDEwLjA5NDcgMTYuNTg1OUMxMC4wOTQ3IDE2LjU4NzEgMTAuMTkzNCAxNi42NDUxIDEwLjMxNjQgMTYuNzE1OEwxMi41MDEgMTcuOTY5N0MxMi42MjI4IDE4LjA0MDMgMTIuNzIzNiAxNy45ODIyIDEyLjcyMzYgMTcuODQwOFYxMi4zNjcyQzEyLjcyMyAxMi4yOTk0IDEyLjY5NTcgMTIuMjM0MyAxMi42NDc1IDEyLjE4NjVDMTIuNTk5MiAxMi4xMzg4IDEyLjUzMzggMTIuMTEyMyAxMi40NjU4IDEyLjExMjNIMTAuNzM3M0MxMC42NzAyIDEyLjExMzIgMTAuNjA1OSAxMi4xMzk5IDEwLjU1ODYgMTIuMTg3NUMxMC41MTEzIDEyLjIzNTIgMTAuNDg0NyAxMi4zMDAxIDEwLjQ4NDQgMTIuMzY3MlYxMy44Mzc5QzEwLjQ4NDIgMTMuOTc4OSAxMC4zODQ2IDE0LjAzNjQgMTAuMjYxNyAxMy45NjU4TDguNDY0ODQgMTIuOTM1NUM4LjQwMDI2IDEyLjg5MzUgOC4zNDYxNCAxMi44MzcyIDguMzA3NjIgMTIuNzcwNUM4LjI2OTE5IDEyLjcwNCA4LjI0NzM1IDEyLjYyOTQgOC4yNDMxNiAxMi41NTI3VjYuNzM1MzVaTTI0LjMzNCAxNC4zOTI2QzI0LjMzMzkgMTQuOTk4NSAyNC4yMDU1IDE1LjE4NDYgMjMuNTk4NiAxNS4xOTYzTDIyLjMwMTggMTUuMjU0OUwyMi42NjUgMTYuMjU0OUgyNS4wODY5QzI1LjY3MDUgMTYuMDg0IDI1Ljg3MjEgMTUuNzE5NCAyNS44NzIxIDE0LjgyMzJWNS43ODIyM0wyNC4zMzQgNS43MjM2M1YxNC4zOTI2Wk0zMi4yODIyIDE0LjQ3NTZDMzEuOTQ2IDE1LjA0OTIgMzEuNDY1OSAxNS43NTcxIDMxLjA5OTYgMTYuMjU0OUgzMi42MTkxQzMzLjA2NzMgMTUuNTIxMiAzMy4zNzUxIDE0LjkyOCAzMy41NDg4IDE0LjQ3NTZIMzIuMjgyMlpNMzQuODEwNSAxNS4zOTc1QzM0Ljg3OTEgMTUuNzEwMSAzNC45MzExIDE1Ljk5ODIgMzQuOTczNiAxNi4yNTQ5SDM2LjE4NjVMMzYuMTgxNiAxNi4yMzU0QzM2LjA2NjIgMTUuNzM4OCAzNS44OTg5IDE1LjAxOCAzNS43NDEyIDE0LjQ3NTZIMzQuNTI5M0wzNC44MTA1IDE1LjM5NzVaTTM2Ljk4MTQgMTQuNjUzM0MzNy4wOTg0IDE0Ljg3NyAzNy4yNDExIDE1LjE1MDEgMzcuMzMzIDE1LjQwMjNMMzcuNjM1NyAxNi4yNTQ5SDM5LjA4MDFDMzkuMDMzNiAxNS44MzI1IDM4LjU5NCAxNS4wNTUzIDM4LjIzODMgMTQuNDc1NkgzNi44ODg3QzM2LjkxNjEgMTQuNTI5OCAzNi45NDggMTQuNTg5NCAzNi45ODE0IDE0LjY1MzNaTTM5LjI3MDUgMTQuNDc1NkMzOS44MzAxIDE1LjE4MjEgNDAuMTg2MyAxNS44MDA0IDQwLjQxMzEgMTYuMjU0OUg0MS44MzVDNDEuNzM2NyAxNS42NjU2IDQxLjIyOTIgMTQuOTkzNiA0MC43NzY0IDE0LjQ3NTZIMzkuMjcwNVpNNDMuOTIyOSAxNS4wMDQ5SDQyLjc2NjZWMTUuOTk2MUg1My4xMjVWMTUuMDA0OUg1MS45Njg4VjEyLjQ3NTZINDMuOTIyOVYxNS4wMDQ5Wk0xMC43MDQxIDQuMDMwMjdDMTAuNTgxMSAzLjk1OTU4IDEwLjQ4MDUgNC4wMTc4IDEwLjQ4MDUgNC4xNTkxOFY5LjYyMzA1QzEwLjQ4MDYgOS42OTA3NCAxMC41MDc4IDkuNzU1NzggMTAuNTU1NyA5LjgwMzcxQzEwLjYwMzcgOS44NTE3MSAxMC42NjkzIDkuODc4ODcgMTAuNzM3MyA5Ljg3ODkxSDEyLjQ2NDhDMTIuNDk4NiA5Ljg3OTA1IDEyLjUzMjIgOS44NzIxNyAxMi41NjM1IDkuODU5MzhDMTIuNTk0NCA5Ljg0NjY2IDEyLjYyMjcgOS44MjgyMSAxMi42NDY1IDkuODA0NjlDMTIuNjcwNCA5Ljc4MDg5IDEyLjY5MDIgOS43NTE4NSAxMi43MDMxIDkuNzIwN0MxMi43MTYgOS42ODk3NSAxMi43MjI2IDkuNjU2NTQgMTIuNzIyNyA5LjYyMzA1VjguMTUyMzRDMTIuNzIyNyA4LjAxMSAxMi44MjIzIDcuOTUyODIgMTIuOTQ1MyA4LjAyMzQ0TDE0Ljc0MTIgOS4wNjE1MkMxNC44MDYgOS4xMDM2MiAxNC44NTk3IDkuMTYwNzcgMTQuODk4NCA5LjIyNzU0QzE0LjkzNzEgOS4yOTQzIDE0Ljk1OTYgOS4zNjkyOSAxNC45NjM5IDkuNDQ2MjlWMTUuMjU5OEMxNC45NjQxIDE1LjQwMDcgMTUuMDYzNyAxNS40NTcgMTUuMTg2NSAxNS4zODc3TDE2Ljk4NDQgMTQuMzUwNkMxNy4wNDkgMTQuMzA4NyAxNy4xMDMgMTQuMjUyMSAxNy4xNDE2IDE0LjE4NTVDMTcuMTgwMyAxNC4xMTg3IDE3LjIwMyAxNC4wNDMgMTcuMjA3IDEzLjk2NThWOC4wMjQ0MUMxNy4yMDI5IDcuOTQ3MzYgMTcuMTgwMyA3Ljg3MjQ2IDE3LjE0MTYgNy44MDU2NkMxNy4xMDI5IDcuNzM4ODQgMTcuMDQ5MyA3LjY4MTY0IDE2Ljk4NDQgNy42Mzk2NUwxMS44MjMyIDQuNjY3OTdDMTEuNzAwMiA0LjU5NzI4IDExLjU5NzcgNC41NDEwMiAxMS41OTc3IDQuNTQxMDJDMTEuNTg0NiA0LjUzMDQ3IDExLjQ4NzkgNC40ODIxMyAxMS4zNzIxIDQuNDE1MDRMMTAuNzA0MSA0LjAzMDI3Wk00Ni4yNDcxIDE1LjAwNDlINDUuMDkwOFYxMy4zMzY5SDQ2LjI0NzFWMTUuMDA0OVpNNDguNTI0NCAxNS4wMDQ5SDQ3LjM3OTlWMTMuMzM2OUg0OC41MjQ0VjE1LjAwNDlaTTUwLjgzNTkgMTUuMDA0OUg0OS42NTcyVjEzLjMzNjlINTAuODM1OVYxNS4wMDQ5Wk0zMi4wNjE1IDEwLjM2NTJIMzUuODAwOFYxMC45ODI0SDMxLjk4NjNWMTIuMDkwOEgzNS44MDA4VjEyLjc1NDlIMzEuMjUxVjEzLjgyNzFINDEuNzY1NlYxMi43NTQ5SDM3LjI2MjdWMTIuMDkwOEg0MS4wMjkzVjEwLjk4MjRIMzcuMjYyN1YxMC4zNjUySDM5Ljg1ODRDNDAuNDYzNCAxMC4zNjUyIDQwLjk1NCA5Ljg3NTQzIDQwLjk1NDEgOS4yNzE0OFY2LjAxNjZIMzIuMDYxNVYxMC4zNjUyWk0yMS4yNDQxIDguMzAzNzFDMjAuOTY4NiA5LjU3MTM4IDIwLjcxMzcgMTAuNTAxIDIwLjQ4MDUgMTEuMDkzOEMyMC4yNDcyIDExLjY4NjMgMTkuODEyNiAxMi41MDg2IDE5LjE3NDggMTMuNTYyNUwxOS4xMTUyIDEzLjY2MTFIMjAuNTc5MUwyMC41OTg2IDEzLjYzMzhDMjEuMzE2NiAxMi42MTg4IDIxLjgwNzUgMTEuNzYwNCAyMi4wNjc0IDExLjA1OTZDMjIuMzI1NyAxMC4zNjI4IDIyLjU4MzUgOS40NTMxMSAyMi44NDA4IDguMzMyMDNMMjIuODU4NCA4LjI1MjkzSDIxLjI1NDlMMjEuMjQ0MSA4LjMwMzcxWk0yNy4xOTA0IDguNjk4MjRDMjcuNDE5MiA5LjY1Mjc1IDI3LjY0ODMgMTAuNDQwMiAyNy44Nzc5IDExLjA1OTZDMjguMTM3OCAxMS43NjAzIDI4LjYyNzggMTIuNjE4OSAyOS4zNDU3IDEzLjYzMzhMMjkuMzY1MiAxMy42NjExSDMwLjgyOTFMMzAuNjE0MyAxMy4zMDQ3QzMwLjA2MDQgMTIuMzczNiAyOS42Nzc2IDExLjYzNjggMjkuNDYzOSAxMS4wOTM4QzI5LjIzMDYgMTAuNTAxIDI4Ljk3NTggOS41NzEzOCAyOC43MDAyIDguMzAzNzFMMjguNjg5NSA4LjI1MjkzSDI3LjA4NTlMMjcuMTkwNCA4LjY5ODI0Wk00NC4zNTQ1IDExLjg5MjZINTAuNDc2NkM1MS4wODE1IDExLjg5MjUgNTEuNTcyMSAxMS40MDI3IDUxLjU3MjMgMTAuNzk4OFY5LjM1MDU5SDQ0LjM1NDVWMTEuODkyNlpNNTAuNDI3NyAxMC40MDE0QzUwLjQyNzUgMTAuNzAzMiA1MC4xODIzIDEwLjk0ODIgNDkuODc5OSAxMC45NDgySDQ1LjQ5OVYxMC4yODMySDUwLjQyNzdWMTAuNDAxNFpNMzUuODAwOCA5LjI1NzgxSDMzLjI1MjlWNi45NDgyNEgzNS44MDA4VjkuMjU3ODFaTTM5Ljc2MzcgOC43MTA5NEMzOS43NjM1IDkuMDEyNjYgMzkuNTE4MSA5LjI1NzYgMzkuMjE1OCA5LjI1NzgxSDM3LjI2MjdWNi45NDgyNEgzOS43NjM3VjguNzEwOTRaTTQ3LjQ1NDEgNS41ODU5NEM0Ni4yMTQ0IDYuOTI4NCA0NC41Mzc1IDcuODYyNTcgNDIuNjQ5NCA4LjE2NDA2VjkuMDczMjRDNDMuNDc4NiA4Ljk1Mjc3IDQ0LjY1ODcgOC43NTU5OCA0NS4zNzExIDguNDA2MjVWOC43NDMxNkg1MC41NDM5VjguNDE3OTdDNTEuMTk3OCA4Ljc0NDM0IDUyLjQxMjIgOC45NDExMSA1My4yNzY0IDkuMDczMjRMNTMuMjc3MyA4LjE5NjI5QzUzLjI0OCA4LjE4Njc5IDUzLjIxODYgOC4xNzc1MiA1My4xODk1IDguMTY3OTdDNTEuMzA2IDcuODcyNjcgNDkuNjMxNiA2Ljk0OCA0OC4zODk2IDUuNjE2MjFMNDcuNDU0MSA1LjU4NTk0Wk0zMy42OTkyIDcuMTY3OTdDMzMuODU5OCA4LjIyNTk3IDM0LjQ2NTQgOS4wMjk4NiAzNC40Nzc1IDkuMDQ1OUgzNS40NTEyQzM1LjQ0NDIgOS4wMzEwOCAzNC45MzE2IDcuOTM5OTcgMzQuOTMxNiA3LjE2Nzk3SDMzLjY5OTJaTTM4LjExMTMgNy4xNjc5N0MzOC4xMTEzIDcuOTM3OCAzNy42MDE2IDkuMDI1MTEgMzcuNTkxOCA5LjA0NTlIMzguNTY1NEMzOC41ODE1IDkuMDI0NjUgMzkuMTgzNyA4LjIyMjQ0IDM5LjM0MzggNy4xNjc5N0gzOC4xMTEzWk00Ny45NjM5IDYuNjExMzNDNDguMzI1OSA3LjA0MjU0IDQ4Ljg3NDggNy40NzQwNiA0OS42MTA0IDcuOTA1MjdINDYuMjkzQzQ3LjA1MjEgNy40NjIyNSA0Ny42MDE4IDcuMDMxMDMgNDcuOTYzOSA2LjYxMTMzWiIgZmlsbD0iYmxhY2siLz4KPC9zdmc+Cg==",dD="data:image/svg+xml;base64,PHN2ZyBwcmVzZXJ2ZUFzcGVjdFJhdGlvPSJub25lIiBvdmVyZmxvdz0idmlzaWJsZSIgc3R5bGU9ImRpc3BsYXk6IGJsb2NrOyIgd2lkdGg9IjEyIiBoZWlnaHQ9IjEyIiB2aWV3Qm94PSIwIDAgMTIgMTIiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxnIGlkPSIxLWNvbW1vbl9zZWFyY2hfbGluZV8yNHgyNCI+CjxnIGlkPSJ1bmlvbiI+CjxwYXRoIGZpbGwtcnVsZT0iZXZlbm9kZCIgY2xpcC1ydWxlPSJldmVub2RkIiBkPSJNNS44NjAxMyAxLjkyNTAxQzMuNzI4NzkgMS45MjUwMSAyLjAwMDAyIDMuNjU0NiAyLjAwMDAyIDUuNzg5MzdDMi4wMDAwMiA3LjkyNDEzIDMuNzI4NzkgOS42NTM3MiA1Ljg2MDEzIDkuNjUzNzJDNy45OTE0NyA5LjY1MzcyIDkuNzIwMjQgNy45MjQxMyA5LjcyMDI0IDUuNzg5MzdDOS43MjAyNCAzLjY1NDYgNy45OTE0NyAxLjkyNTAxIDUuODYwMTMgMS45MjUwMVpNMC44MDAwMjQgNS43ODkzN0MwLjgwMDAyNCAyLjk5Mjk0IDMuMDY0OTcgMC43MjUwMTIgNS44NjAxMyAwLjcyNTAxMkM4LjY1NTI5IDAuNzI1MDEyIDEwLjkyMDIgMi45OTI5NCAxMC45MjAyIDUuNzg5MzdDMTAuOTIwMiA4LjU4NTggOC42NTUyOSAxMC44NTM3IDUuODYwMTMgMTAuODUzN0MzLjA2NDk3IDEwLjg1MzcgMC44MDAwMjQgOC41ODU4IDAuODAwMDI0IDUuNzg5MzdaIiBmaWxsPSJibGFjayIvPgo8cGF0aCBmaWxsLXJ1bGU9ImV2ZW5vZGQiIGNsaXAtcnVsZT0iZXZlbm9kZCIgZD0iTTkuMDEzMTkgOC45MzQ5N0M5LjI0NzQgOC43MDA1NCA5LjYyNzExIDguNzAwNTQgOS44NjEzMiA4LjkzNDk3TDExLjA1MDggMTAuMTI1NkMxMS4yODUgMTAuMzYgMTEuMjg1IDEwLjc0MDEgMTEuMDUwOCAxMC45NzQ1QzEwLjgxNjYgMTEuMjA4OSAxMC40MzY5IDExLjIwODkgMTAuMjAyNyAxMC45NzQ1TDkuMDEzMTkgOS43ODM5QzguNzc4OTkgOS41NDk0OCA4Ljc3ODk5IDkuMTY5NCA5LjAxMzE5IDguOTM0OTdaIiBmaWxsPSJibGFjayIvPgo8L2c+CjwvZz4KPC9zdmc+Cg==";async function uD(e,t,r,n,i="dark"){pe(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 f=e.createElement("div");f.style.cssText="display:flex;align-items:center;max-width:calc(100% - 24px);height:22px;flex-shrink:0;";const l=e.createElement("img");l.src=a?cD:sD,l.style.cssText="width:67px;height:22px;flex-shrink:0;margin-right:-11px;";const h=e.createElement("div");h.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 m=e.createElement("img");m.src=a?dD:aD,m.style.cssText="width:12px;height:12px;flex-shrink:0;";const E=e.createElement("span");E.textContent=t?.trim()||"小程序工坊",E.style.cssText=`color:${c};font-size:11px;font-weight:500;line-height:16px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;`;const _=e.createElement("div");_.textContent="小黑盒工坊小程序",_.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;`,h.append(m,E),f.append(l,h),u.append(f,_),s.append(u),e.body.append(s);const w=()=>{s.remove(),n.removeEventListener("abort",w)};n.addEventListener("abort",w,{once:!0});try{return await fe(()=>Promise.all([l.decode(),m.decode()]),n),await fe(()=>new Promise(S=>{let p=o.requestAnimationFrame(()=>{p=o.requestAnimationFrame(()=>{n.removeEventListener("abort",M),S()})});const M=()=>o.cancelAnimationFrame(p);n.addEventListener("abort",M,{once:!0})}),n),w}catch(S){throw w(),S}}const lD=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"]),fD=new Set(["url","inline","eval","unknown"]),hD=/^\/(?:\:segment(?:\/\:segment)*)?$/,mD=/^[a-f0-9]{64}$/,gD=255,pD=160,yD=256;function ED(e,t){const r=e;if(!r||typeof r.sdkVersion!="string"||r.sdkVersion!==t||typeof r.effectiveDirective!="string"||!lD.has(r.effectiveDirective)||typeof r.violatedDirective!="string"||r.violatedDirective.length>yD||r.violatedDirective.split(/\s/,1)[0]!==r.effectiveDirective||!["enforce","report"].includes(r.disposition??"")||typeof r.blockedResourceType!="string"||!fD.has(r.blockedResourceType)||typeof r.timestamp!="number"||!Number.isFinite(r.timestamp)||r.timestamp<0)return;const n=wD(r.blockedOrigin);if(r.blockedOrigin!==void 0&&!n)return;const i=r.redactedPathname;if(i!==void 0&&(typeof i!="string"||i.length>pD||!hD.test(i)))return;const o=r.sanitizedPathnameHash;if(!(o!==void 0&&(typeof o!="string"||!mD.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 wD(e){if(e!==void 0&&!(typeof e!="string"||e.length>gD))try{const t=new URL(e);return["http:","https:"].includes(t.protocol)&&t.origin===e?t.origin:void 0}catch{return}}const jo=["android","ios","ohos","windows","macos","linux"],ID="0.9.0",AD=Object.freeze(["android","ios","ohos","windows","macos"]),sh="该小程序暂不支持当前平台",_D="PLATFORM_UNSUPPORTED";function DD(e){return typeof e=="string"&&jo.includes(e)}function ND(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 MD(e){const t=e.manifest;if(!OD(t))return{status:"invalid",reason:"manifest_not_object"};if(!Object.prototype.hasOwnProperty.call(t,"platforms")){const n=du(e.sdkVersion)??du(t.sdkVersion);return TD(n)?{status:"invalid",reason:"platforms_missing_after_hard_cutover"}:bD()}const r=ah(t.platforms);return"reason"in r?{status:"invalid",reason:r.reason}:{status:"resolved",declaredPlatforms:r.platforms,effectivePlatforms:r.platforms,platformsDeclared:!0,policy:"explicit"}}function SD(e){const t=ND(e.operatingSystemName);if(!t)return _r("host_operating_system_unknown");const r=e.platformAccess;if(!r)return _r("platform_access_missing",{platform:t});if(r.source==="compatibility-window")return{status:"allowed",platform:t,effectivePlatforms:jo,platformsDeclared:!1,policy:"legacy_mobile_default",compatibility:r.reason};if(r.source==="manifest"){const s=MD({manifest:r.manifest,...r.sdkVersion===void 0?{}:{sdkVersion:r.sdkVersion}});return s.status==="invalid"?_r("platform_declaration_invalid",{invalidReason:s.reason,platform:t}):cu(t,s)}if(r.effectivePlatforms===void 0)return _r("platform_declaration_invalid",{invalidReason:"effective_platforms_missing",platform:t});const n=ah(r.effectivePlatforms);if("reason"in n)return _r("platform_declaration_invalid",{invalidReason:n.reason,platform:t});const i=typeof r.platformsDeclared=="boolean"?r.platformsDeclared:!0,o=vD(r.platformPolicy)?r.platformPolicy:i?"explicit":"legacy_mobile_default";return cu(t,{declaredPlatforms:i?n.platforms:[],effectivePlatforms:n.platforms,platformsDeclared:i,policy:o})}function cu(e,t){return t.effectivePlatforms.includes(e)?{status:"allowed",platform:e,effectivePlatforms:t.effectivePlatforms,platformsDeclared:t.platformsDeclared,policy:t.policy}:_r("platform_not_supported",{effectivePlatforms:t.effectivePlatforms,platform:e})}function _r(e,t={}){return{status:"denied",reason:e,message:sh,...t}}function bD(){return{status:"resolved",declaredPlatforms:[],effectivePlatforms:AD,platformsDeclared:!1,policy:"legacy_mobile_default"}}function ah(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(!DD(r))return{reason:"platform_unknown_value"};if(t.has(r))return{reason:"platform_duplicate_value"};t.add(r)}return{platforms:Object.freeze(jo.filter(r=>t.has(r)))}}function TD(e){if(typeof e!="string"||!e.trim())return!1;const t=ec(e.trim(),ID);return t!==void 0&&t>=0}function du(e){return typeof e=="string"&&e.trim()?e.trim():void 0}function vD(e){return e==="explicit"||e==="legacy_mobile_default"}function OD(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function RD(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:PD(i.pathname),sanitizedPathnameHash:Ga(i.pathname)}}catch{return{type:"security_violation",errorCode:e,timestamp:n,sdkVersion:r}}}function PD(e){return(e==="/"?e:e.replace(/\/+$/,"")).split("/").map(r=>r?":segment":"").join("/")}const kD=1e4,CD=1e4,us=2e3,LD=2,UD="open-with-native-credential-policy",ch="安全提示",dh="即将打开未经验证的开发网页。该页面可能由本机或局域网服务提供,请确认来源可信后继续。";class xD{nonce=Vc();runtimeId=Vc();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;firstParty=!1;networkPolicy;networkPolicyDisposer;runtimeFeatures;miniProgramPresentation;miniProgramDetail;locationBasePath;anonymousStorageScope;allowedHttpOrigins;environmentInfo;constructor(t){this.options=t,this.iframe=t.iframe;const r=ql(t.ports,{callerCapabilities:t.capabilities,hostCapabilities:t.hostCapabilities,hasUserDataPresentation:t.userDataPresentation!==void 0,hasUserDataSettings:t.userDataPresentation?.openDataPermissions!==void 0});this.ports=r.ports,this.primitiveAvailability=r.primitiveAvailability,this.effectiveCapabilities=r.effectiveCapabilities,this.identity={},this.identityRef={get:()=>{const n=this.identity.miniProgramId?.trim();if(n)return{miniProgramId:n,...this.identity.miniProgramVersion?{version:this.identity.miniProgramVersion}:{}}}},this.handshakeTimeout=t.handshakeTimeout??kD,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}getDataPermissionBridge(){return this.capabilityGraph?.permissionBridge}get diagnostics(){const t=this.capabilityGraph?.storageDiagnostics,r=this.capabilityGraph?.sandboxDiagnostics,n=this.capabilityGraph?.gameSaveDiagnostics;return{...t?{storage:t}:{},...r?{sandbox:r}:{},...n?{gameSaves:n}:{}}}start(){return this.stateValue==="destroyed"?Promise.reject(this.terminalError??we("RUNTIME_DESTROYED","小程序运行时已销毁")):this.stateValue==="failed"?Promise.reject(this.terminalError??we("STARTUP_ERROR","小程序运行时启动失败")):this.readyContext?Promise.resolve(this.readyContext):this.startPromise?this.startPromise:(WD(),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??we("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=cy(t.runtimePermissions),this.firstParty=t.firstParty===!0,this.networkPolicy=this.firstParty?void 0:Ql(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 Gp(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=Zy(t.sdkVersionPolicy);const n=rD(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=SD({operatingSystemName:t.environmentInfo?.operatingSystem?.name,...t.platformAccess===void 0?{}:{platformAccess:t.platformAccess}}),this.platformGateDecision.status==="denied")throw JD(this.platformGateDecision);if(this.miniProgramDetail=XD(t),this.effectiveCapabilities=$l(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),GD(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(qD(i)),this.launchUrl=i,this.options.onDevDocumentReload&&t.sdkVersionPolicy?.releaseChannel==="development"){const s=Yl(new URL(i),this.locationBasePath);this.devDocumentDisposer=ay({iframe:this.iframe,launchUrl:i,nonce:this.nonce,locationBasePath:s,onLeaving:()=>{this.prepareForHistoryTraversal()},onResume:()=>{!this.isInactive()&&this.documentRevalidationPending&&this.beginDocumentRevalidation()},onReload:a=>{this.isInactive()||ot(c=>this.options.onDevDocumentReload?.(c,s),a)}})}if(this.miniProgramSrc=Xp(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=$a(s);this.trace({runtimeId:this.runtimeId,timestamp:Date.now(),type:"error",method:nr,errorCode:a.code,message:`默认展示设置失败,沿用宿主当前布局:${a.message}`})}if(this.isInactive())return}this.awaitingControlledDocumentLoad=!0,this.iframe.src=this.miniProgramSrc,ot(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[nr])&&this.bridgeServer?.postEvent(n,i)}};this.capabilityGraph=Y_({verifiedSdkVersion:this.sdkVersionDecision?.sdkVersion,diagnosticCapabilities:this.effectiveCapabilities,account:this.ports.account,network:this.ports.network,files:this.ports.files,picker:this.ports.picker,media:this.ports.media,transfer:this.ports.transfer,storage:this.ports.storage,scopedStorage:this.ports.scopedStorage,storageDiagnostics:this.ports.storageDiagnostics,hostPresentation:this.ports.presentation,hostCompanion:this.ports.companion,hostProtocol:this.ports.protocol,...this.options.userDataPresentation===void 0?{}:{userDataPresentation:this.options.userDataPresentation},...this.options.onUserDataTelemetry===void 0?{}:{onUserDataTelemetry:this.options.onUserDataTelemetry},workspaceCards:this.ports.workspaceCards,environment:this.options.environment,identity:this.identityRef,runtimePermissions:this.runtimePermissions,runtimeFeatures:this.runtimeFeatures,networkPolicy:this.networkPolicy,firstParty:this.firstParty,authorizationContext:this.options.authorizationContext,terminalSignal:this.terminalController.signal,eventSink:t,authPresentation:this.options.authPresentation,companionPresentation:this.options.companionPresentation,miniProgramPresentation:this.miniProgramPresentation,prepareLongScreenshot:(n,i)=>Vp(this.iframe,n,i),prepareScreenshot:(n,i,o)=>{const s=this.sdkVersionDecision?.sdkVersion;return!s||(ec(s,"0.9.1")??-1)<0?Promise.resolve(()=>{}):uD(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=G_({handlers:this.capabilityGraph.handlers,runDisplayRequest:this.capabilityGraph.runDisplayRequest,effectiveCapabilities:this.effectiveCapabilities,runtimePermissions:this.runtimePermissions,terminalSignal:this.terminalController.signal,allowsCompanionAttachmentAccess:this.capabilityGraph.allowsCompanionAttachmentAccess,allowsGameSaveAccess:this.capabilityGraph.allowsGameSaveAccess,allowsUserGameDataFileAccess:this.capabilityGraph.allowsUserGameDataFileAccess,policies:this.options.policies,...this.options.onCapabilityTrace?{onTrace:({callId:n,method:i,startedAt:o,timestamp:s,durationMs:a,outcome:c,errorCode:d,network:u})=>{const f={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}:{}};ot(this.options.onCapabilityTrace,f)}}:{}});this.bridgeServer=new hy({iframe:this.iframe,nonce:this.nonce,dispatcher:r,environmentInfo:this.environmentInfo,...this.options.onDevUploadSession?{onDevUploadSession:n=>{this.isInactive()||ot(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(we("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 VD(t)?t:uh(we("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 Jp(t,r,{allowPrivateNetwork:au(r)||uu(r)||await this.isDevRuntime()})}catch(r){throw we("INVALID_LAUNCH_URL",r instanceof Error?r.message:"小程序链接不合法",r)}}async confirmDevMiniProgramLaunch(t){return await this.shouldConfirmDevMiniProgramLaunch(t)?this.isInactive()?!1:!!await(this.options.confirmDevMiniProgramLaunch??YD)({message:dh,title:ch,url:t}):!0}async shouldConfirmDevMiniProgramLaunch(t){if($c(t)==="production")return!1;const r=this.options.environment.getCurrentHref();return!au(r)&&!uu(r)}async closeAfterDevLaunchCancellation(){const t=we("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{lu(),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(()=>lu())}async isDevRuntime(){return this.devRuntimePromise??=Promise.resolve().then(()=>this.options.environment.isDevRuntime()).then(Boolean).catch(()=>!1),this.devRuntimePromise}applyIframeDefaults(){this.iframe.setAttribute("allow",Yp),this.iframe.setAttribute("referrerpolicy",Wp),this.iframe.setAttribute("sandbox",Wl)}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(),ot(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(),ot(this.options.onReady,t)}handleBridgeHandshake(t){const r=this.sdkVersionDecision?.sdkVersion;if(r)try{Ky(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(we("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>=LD)){this.failRuntime(we("HEARTBEAT_TIMEOUT","小程序 SDK 心跳超时"));return}const t=`${Date.now().toString(36)}_${++this.probeSequence}`;this.pendingProbeId=t,this.bridgeServer?.postInternalRequest(Fn,t,{probeId:t,timestamp:Date.now()}),this.heartbeatTimer=setTimeout(()=>{this.heartbeatTimer=void 0,this.sendLocationProbe()},us),this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"location_probe",method:Fn})}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(Fn,t,{probeId:t,timestamp:Date.now()}),this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"location_probe",method:Fn})}armDocumentRevalidationTimer(t,r={}){this.clearDocumentRevalidationTimer(),this.hostVisible&&(this.documentRevalidationTimer=setTimeout(()=>{this.documentRevalidationTimer=void 0,!(this.isInactive()||!this.documentRevalidationPending||t!==this.documentRevalidationGeneration)&&this.failRuntime(we("DOCUMENT_REVALIDATION_TIMEOUT",r.waitingForDocument?"小程序 iframe 目标文档加载超时":"小程序 iframe 文档再验证超时"))},r.waitingForDocument?CD:us))}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()},us)),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===Om){this.handleCspViolation(t.payload);return}if(t.method!==vm)return;const r=this.sdkVersionDecision?.sdkVersion;if(!r)return;const n=t.payload;if(!n||n.sdkVersion!==r){this.failRuntime(we("SDK_VERSION_MISMATCH","URL report 的 SDK 版本不一致"));return}if(!(n.probeId!==void 0&&n.probeId!==this.pendingProbeId)){if(typeof n.href!="string"||!Zl(this.launchUrl,n.href,this.locationBasePath)){typeof n.href=="string"&&this.emitUrlSecurityViolation("URL_OUT_OF_SCOPE",n.href),this.failRuntime(we("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=ED(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){ot(this.options.onSecurityViolation,t),this.trace({runtimeId:this.nonce,...t})}emitUrlSecurityViolation(t,r){const n=RD(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(we("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:Qp,launchUrlType:$c(t),networkPolicy:UD})}failRuntime(t){const r=zD(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}),ot(this.options.onError,jD(r)),ot(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,ot(this.options.onStateChange,t))}isInactive(){return this.stateValue==="failed"||this.stateValue==="destroyed"}trace(t){ot(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 zD(e){const t=$a(e);return go(e)&&"cause"in e&&uh(t,e.cause),t}function uh(e,t){return Object.defineProperty(e,"cause",{configurable:!0,enumerable:!1,value:t}),e}function jD(e){return{code:e.code,message:e.message,...e.data!==void 0?{data:e.data}:{},...e.cause!==void 0?{cause:FD(e.cause)}:{}}}const ls=(()=>{const e=Object.getOwnPropertyDescriptor(new Error,"stack")?.get,t=Object.getOwnPropertyDescriptor(new Error,"stack")?.get;return typeof e=="function"&&e===t?e:void 0})(),BD=new Set([Error.prototype,TypeError.prototype,RangeError.prototype,ReferenceError.prototype,SyntaxError.prototype,URIError.prototype,EvalError.prototype]);function HD(e,t){const r=Object.getOwnPropertyDescriptor(e,t);if(!r)return;if("value"in r)return r.value;if(t!=="stack"||!ls||r.get!==ls)return;const n=Object.getPrototypeOf(e);if(BD.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 ls.call(e)}}function FD(e){if(!(!e||typeof e!="object"))try{const t={};for(const r of["name","message","stack"]){const n=HD(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 VD(e){return go(e)&&typeof e.code=="string"&&typeof e.message=="string"}function go(e){return!!e&&typeof e=="object"}function ot(e,t){try{e?.(t)}catch{}}function GD(e,t,r){try{e?.(t,r)}catch{}}function uu(e){try{const t=new URL(e);return t.protocol==="http:"&&X_(t.hostname)}catch{return!1}}function $D(e){try{return new URL(e).origin}catch{return}}function qD(e){return Zp()?"*":$D(e)}function QD(e){return`${ch}
6
6
 
7
7
  ${dh}
8
8
 
9
- URL: ${e}`}function YD(e){return typeof window>"u"||typeof window.confirm!="function"?!1:window.confirm(QD(e.url))}function lu(){typeof window<"u"&&typeof window.close=="function"&&window.close()}function WD(){const e=typeof navigator>"u"?void 0:navigator,t=typeof screen>"u"?void 0:screen,r=typeof window>"u"?void 0:window,n=Object.freeze({protocolVersion:gl,knownMethodCount:zt.length,supportsFileCreate:zt.some(i=>i.method===In),system:ZD(e?.userAgent,e?.platform),userAgent:e?.userAgent??"",platform:e?.platform??"",language:e?.language??"",hardwareConcurrency:Ir(e?.hardwareConcurrency),maxTouchPoints:Ir(e?.maxTouchPoints),screen:{width:Ir(t?.width),height:Ir(t?.height)},viewport:{width:Ir(r?.innerWidth),height:Ir(r?.innerHeight),devicePixelRatio:KD(r?.devicePixelRatio)}});console.info("[hb-sdk-runtime] environment",n)}function ZD(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 Ir(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0?Math.floor(e):0}function KD(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:1}function JD(e){return we(_D,sh,{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 XD(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 eN(e){if(!go(e?.ports)||Array.isArray(e.ports))throw new TypeError("createMiniProgramRuntime 必须显式提供 ports");if(!go(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 xD(e)}function tN(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 f=()=>n.signal.removeEventListener("abort",h),l=m=>{u||(u=!0,f(),c(m))},h=()=>l(new DOMException("账号标识读取已取消","AbortError"));d.onupgradeneeded=()=>{u?d.transaction?.abort():d.result.createObjectStore("accounts")},d.onerror=()=>l(d.error),d.onblocked=()=>l(new Error("账号存储被阻塞")),d.onsuccess=()=>{u?d.result.close():(u=!0,f(),a(d.result))},n.signal.addEventListener("abort",h,{once:!0}),n.signal.aborted&&h()});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"),f=JSON.stringify([t,r]);let l;const h=()=>{try{d.abort()}catch{}m(),c(new DOMException("账号标识读取已取消","AbortError"))};n.signal.addEventListener("abort",h,{once:!0});const m=()=>n.signal.removeEventListener("abort",h);d.oncomplete=()=>{m(),a(l)},d.onabort=d.onerror=()=>{m(),c(d.error??new Error("账号存储事务失败"))};const E=u.get(f);E.onsuccess=()=>{try{if(typeof E.result=="string"&&/^ak_[0-9a-f]{64}$/.test(E.result))l=E.result;else{const _=o.getRandomValues(new Uint8Array(32));l=`ak_${Array.from(_,w=>w.toString(16).padStart(2,"0")).join("")}`,u.put(l,f)}}catch{d.abort()}}})}finally{s.close()}}}const rN=/^(?: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,nN=new Set(["origin","referer","user-agent"]);function iN(e,t){return Ip({mode:"request-only",request:(r,n={signal:t.signal})=>t.run(n.signal,async i=>{const o={...n,signal:i},s=oN(r),a=await e.authenticatedRequest(s,o);return cN(a)})}).network}function oN(e){const t=sN(e.headers);return{...e,target:{...e.target},...e.params===void 0?{}:{params:{...e.params}},...t===void 0?{headers:void 0}:{headers:t}}}function sN(e){if(e!==void 0)return Object.fromEntries(Object.entries(e).filter(([t])=>!aN(t)))}function aN(e){const t=e.trim().toLowerCase();return nN.has(t)}function cN(e){return{status:e.status,...e.statusText===void 0?{}:{statusText:e.statusText},data:e.data,headers:dN(e.headers)??{}}}function dN(e){if(e!==void 0)return Object.fromEntries(Object.entries(e).filter(([t])=>!uN(t)))}function uN(e){const t=e.trim().toLowerCase();return rN.test(t)||t.startsWith("x-heybox-")||t.startsWith("x-xhh-")}function lN(e,t,r){const n=pN(e.presentation,t);return{account:mN(e,t,r),network:iN(e,t),...e.storage===void 0?{}:{storage:gN(e,t)},...e.storage===void 0?{}:fN(e,t),...n===void 0?{}:{presentation:n},...e.protocol===void 0?{}:{protocol:e.protocol}}}function fN(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 hN(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 mN(e,t,r){const n=e.account.getAccountKey?.bind(e.account)??tN();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 gN(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 pN(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)=>kp(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 yN(){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 Xn(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 Xn(i.reason);const o=new AbortController;let s;const a=new Promise((u,f)=>{s=f}),c=n.map(u=>{const f=()=>{o.signal.aborted||o.abort(u.reason),s(Xn(u.reason))};return u.addEventListener("abort",f,{once:!0}),{listener:f,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]),f=n.find(l=>l.aborted);if(f)throw Xn(f.reason);return u}finally{for(const{listener:u,source:f}of c)f.removeEventListener("abort",u)}}}}function Xn(e){return new DOMException("Web Host operation aborted","AbortError")}async function EN(e){const t=yN(),r=new Set;let n=!1;const i=l=>{if(n||t.signal.aborted)return fs(l),()=>{};let h=!0;const m=()=>{h&&(h=!1,r.delete(m),fs(l))};return r.add(m),m},o=()=>s(e.signal.reason),s=l=>{if(!n){n=!0,e.signal.removeEventListener("abort",o),t.abort(l);for(const h of[...r])h();e.onDispose&&fs(e.onDispose)}};e.signal.addEventListener("abort",o,{once:!0}),e.signal.aborted&&s(e.signal.reason);const a=lN(e,t,i);a.storage?.getRaw&&a.storage.setRaw&&(a.scopedStorage=Yf({storage:a.storage,diagnostics:a.storageDiagnostics,coordinationKey:e.storage.storage,lock:Wf,resolveScope:async()=>Qf((await f()).configuration)}));const c=ql(a,{hostCapabilities:e.hostCapabilities,hasUserDataPresentation:e.userDataPresentation!==void 0,hasUserDataSettings:e.userDataPresentation?.openDataPermissions!==void 0}),d=hN(e,t);let u;const f=()=>u??=t.run(void 0,l=>e.resolveLaunch(l));return{platform:"web",ports:a,environment:d,resolveLaunch:f,...e.authPresentation===void 0?{}:{authPresentation:wN(e.authPresentation,t)},...e.userDataPresentation===void 0?{}:{userDataPresentation:IN(e.userDataPresentation,t)},hostCapabilities:c.effectiveCapabilities,dispose:s}}function fs(e){try{e()}catch{}}function wN(e,t){return{...e.confirmFollowAuthor?{confirmFollowAuthor:r=>t.run(r.signal,n=>e.confirmFollowAuthor({...r,signal:n}))}:{},confirmAuthorization:r=>t.run(r.signal,n=>e.confirmAuthorization({...r,signal:n}))}}function IN(e,t){return{...e.openDataPermissions?{openDataPermissions:r=>t.run(r.signal,n=>e.openDataPermissions({...r,signal:n}))}:{},confirmDataPermission:r=>t.run(r.signal,n=>e.confirmDataPermission({...r,signal:n}))}}var Ar={},hs,fu;function AN(){return fu||(fu=1,hs=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then}),hs}var ms={},Rt={},hu;function cr(){if(hu)return Rt;hu=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 Rt.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},Rt.getSymbolTotalCodewords=function(n){return t[n]},Rt.getBCHDigit=function(r){let n=0;for(;r!==0;)n++,r>>>=1;return n},Rt.setToSJISFunction=function(n){if(typeof n!="function")throw new Error('"toSJISFunc" is not a valid function.');e=n},Rt.isKanjiModeEnabled=function(){return typeof e<"u"},Rt.toSJIS=function(n){return e(n)},Rt}var gs={},mu;function cc(){return mu||(mu=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}}})(gs)),gs}var ps,gu;function _N(){if(gu)return ps;gu=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++}},ps=e,ps}var ys,pu;function DN(){if(pu)return ys;pu=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]},ys=e,ys}var Es={},yu;function NN(){return yu||(yu=1,(function(e){const t=cr().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}})(Es)),Es}var ws={},Eu;function MN(){if(Eu)return ws;Eu=1;const e=cr().getSymbolSize,t=7;return ws.getPositions=function(n){const i=e(n);return[[0,0],[i-t,0],[0,i-t]]},ws}var Is={},wu;function SN(){return wu||(wu=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 f=0;f<o;f++){a=c=0,d=u=null;for(let l=0;l<o;l++){let h=i.get(f,l);h===d?a++:(a>=5&&(s+=t.N1+(a-5)),d=h,a=1),h=i.get(l,f),h===u?c++:(c>=5&&(s+=t.N1+(c-5)),u=h,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}})(Is)),Is}var ei={},Iu;function lh(){if(Iu)return ei;Iu=1;const e=cc(),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 ei.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}},ei.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}},ei}var As={},nn={},Au;function bN(){if(Au)return nn;Au=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]})(),nn.log=function(n){if(n<1)throw new Error("log("+n+")");return t[n]},nn.exp=function(n){return e[n]},nn.mul=function(n,i){return n===0||i===0?0:e[t[n]+t[i]]},nn}var _u;function TN(){return _u||(_u=1,(function(e){const t=bN();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}})(As)),As}var _s,Du;function vN(){if(Du)return _s;Du=1;const e=TN();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},_s=t,_s}var Ds={},Ns={},Ms={},Nu;function fh(){return Nu||(Nu=1,Ms.isValid=function(t){return!isNaN(t)&&t>=1&&t<=40}),Ms}var pt={},Mu;function hh(){if(Mu)return pt;Mu=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
- ]))+`;pt.KANJI=new RegExp(r,"g"),pt.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g"),pt.BYTE=new RegExp(n,"g"),pt.NUMERIC=new RegExp(e,"g"),pt.ALPHANUMERIC=new RegExp(t,"g");const i=new RegExp("^"+r+"$"),o=new RegExp("^"+e+"$"),s=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");return pt.testKanji=function(c){return i.test(c)},pt.testNumeric=function(c){return o.test(c)},pt.testAlphanumeric=function(c){return s.test(c)},pt}var Su;function dr(){return Su||(Su=1,(function(e){const t=fh(),r=hh();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}}})(Ns)),Ns}var bu;function ON(){return bu||(bu=1,(function(e){const t=cr(),r=lh(),n=cc(),i=dr(),o=fh(),s=7973,a=t.getBCHDigit(s);function c(l,h,m){for(let E=1;E<=40;E++)if(h<=e.getCapacity(E,m,l))return E}function d(l,h){return i.getCharCountIndicator(l,h)+4}function u(l,h){let m=0;return l.forEach(function(E){const _=d(E.mode,h);m+=_+E.getBitsLength()}),m}function f(l,h){for(let m=1;m<=40;m++)if(u(l,m)<=e.getCapacity(m,h,i.MIXED))return m}e.from=function(h,m){return o.isValid(h)?parseInt(h,10):m},e.getCapacity=function(h,m,E){if(!o.isValid(h))throw new Error("Invalid QR Code version");typeof E>"u"&&(E=i.BYTE);const _=t.getSymbolTotalCodewords(h),w=r.getTotalCodewordsCount(h,m),S=(_-w)*8;if(E===i.MIXED)return S;const p=S-d(E,h);switch(E){case i.NUMERIC:return Math.floor(p/10*3);case i.ALPHANUMERIC:return Math.floor(p/11*2);case i.KANJI:return Math.floor(p/13);case i.BYTE:default:return Math.floor(p/8)}},e.getBestVersionForData=function(h,m){let E;const _=n.from(m,n.M);if(Array.isArray(h)){if(h.length>1)return f(h,_);if(h.length===0)return 1;E=h[0]}else E=h;return c(E.mode,E.getLength(),_)},e.getEncodedBits=function(h){if(!o.isValid(h)||h<7)throw new Error("Invalid QR Code version");let m=h<<12;for(;t.getBCHDigit(m)-a>=0;)m^=s<<t.getBCHDigit(m)-a;return h<<12|m}})(Ds)),Ds}var Ss={},Tu;function RN(){if(Tu)return Ss;Tu=1;const e=cr(),t=1335,r=21522,n=e.getBCHDigit(t);return Ss.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},Ss}var bs={},Ts,vu;function kN(){if(vu)return Ts;vu=1;const e=dr();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))},Ts=t,Ts}var vs,Ou;function PN(){if(Ou)return vs;Ou=1;const e=dr(),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)},vs=r,vs}var Os,Ru;function CN(){if(Ru)return Os;Ru=1;const e=dr();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)},Os=t,Os}var Rs,ku;function LN(){if(ku)return Rs;ku=1;const e=dr(),t=cr();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)}},Rs=r,Rs}var ks={exports:{}},Pu;function UN(){return Pu||(Pu=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,f,l,h,m,E,_;!a.empty();){c=a.pop(),d=c.value,f=c.cost,l=r[d]||{};for(u in l)l.hasOwnProperty(u)&&(h=l[u],m=f+h,E=s[u],_=typeof s[u]>"u",(_||E>m)&&(s[u]=m,a.push(u,m),o[u]=d))}if(typeof i<"u"&&typeof s[i]>"u"){var w=["Could not find a path from ",n," to ",i,"."].join("");throw new Error(w)}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})(ks)),ks.exports}var Cu;function xN(){return Cu||(Cu=1,(function(e){const t=dr(),r=kN(),n=PN(),i=CN(),o=LN(),s=hh(),a=cr(),c=UN();function d(w){return unescape(encodeURIComponent(w)).length}function u(w,S,p){const M=[];let z;for(;(z=w.exec(p))!==null;)M.push({data:z[0],index:z.index,mode:S,length:z[0].length});return M}function f(w){const S=u(s.NUMERIC,t.NUMERIC,w),p=u(s.ALPHANUMERIC,t.ALPHANUMERIC,w);let M,z;return a.isKanjiModeEnabled()?(M=u(s.BYTE,t.BYTE,w),z=u(s.KANJI,t.KANJI,w)):(M=u(s.BYTE_KANJI,t.BYTE,w),z=[]),S.concat(p,M,z).sort(function(D,I){return D.index-I.index}).map(function(D){return{data:D.data,mode:D.mode,length:D.length}})}function l(w,S){switch(S){case t.NUMERIC:return r.getBitsLength(w);case t.ALPHANUMERIC:return n.getBitsLength(w);case t.KANJI:return o.getBitsLength(w);case t.BYTE:return i.getBitsLength(w)}}function h(w){return w.reduce(function(S,p){const M=S.length-1>=0?S[S.length-1]:null;return M&&M.mode===p.mode?(S[S.length-1].data+=p.data,S):(S.push(p),S)},[])}function m(w){const S=[];for(let p=0;p<w.length;p++){const M=w[p];switch(M.mode){case t.NUMERIC:S.push([M,{data:M.data,mode:t.ALPHANUMERIC,length:M.length},{data:M.data,mode:t.BYTE,length:M.length}]);break;case t.ALPHANUMERIC:S.push([M,{data:M.data,mode:t.BYTE,length:M.length}]);break;case t.KANJI:S.push([M,{data:M.data,mode:t.BYTE,length:d(M.data)}]);break;case t.BYTE:S.push([{data:M.data,mode:t.BYTE,length:d(M.data)}])}}return S}function E(w,S){const p={},M={start:{}};let z=["start"];for(let A=0;A<w.length;A++){const D=w[A],I=[];for(let v=0;v<D.length;v++){const T=D[v],x=""+A+v;I.push(x),p[x]={node:T,lastCount:0},M[x]={};for(let N=0;N<z.length;N++){const b=z[N];p[b]&&p[b].node.mode===T.mode?(M[b][x]=l(p[b].lastCount+T.length,T.mode)-l(p[b].lastCount,T.mode),p[b].lastCount+=T.length):(p[b]&&(p[b].lastCount=T.length),M[b][x]=l(T.length,T.mode)+4+t.getCharCountIndicator(T.mode,S))}}z=I}for(let A=0;A<z.length;A++)M[z[A]].end=0;return{map:M,table:p}}function _(w,S){let p;const M=t.getBestModeForData(w);if(p=t.from(S,M),p!==t.BYTE&&p.bit<M.bit)throw new Error('"'+w+'" cannot be encoded with mode '+t.toString(p)+`.
12
- Suggested mode is: `+t.toString(M));switch(p===t.KANJI&&!a.isKanjiModeEnabled()&&(p=t.BYTE),p){case t.NUMERIC:return new r(w);case t.ALPHANUMERIC:return new n(w);case t.KANJI:return new o(w);case t.BYTE:return new i(w)}}e.fromArray=function(S){return S.reduce(function(p,M){return typeof M=="string"?p.push(_(M,null)):M.data&&p.push(_(M.data,M.mode)),p},[])},e.fromString=function(S,p){const M=f(S,a.isKanjiModeEnabled()),z=m(M),A=E(z,p),D=c.find_path(A.map,"start","end"),I=[];for(let v=1;v<D.length-1;v++)I.push(A.table[D[v]].node);return e.fromArray(h(I))},e.rawSplit=function(S){return e.fromArray(f(S,a.isKanjiModeEnabled()))}})(bs)),bs}var Lu;function zN(){if(Lu)return ms;Lu=1;const e=cr(),t=cc(),r=_N(),n=DN(),i=NN(),o=MN(),s=SN(),a=lh(),c=vN(),d=ON(),u=RN(),f=dr(),l=xN();function h(A,D){const I=A.size,v=o.getPositions(D);for(let T=0;T<v.length;T++){const x=v[T][0],N=v[T][1];for(let b=-1;b<=7;b++)if(!(x+b<=-1||I<=x+b))for(let O=-1;O<=7;O++)N+O<=-1||I<=N+O||(b>=0&&b<=6&&(O===0||O===6)||O>=0&&O<=6&&(b===0||b===6)||b>=2&&b<=4&&O>=2&&O<=4?A.set(x+b,N+O,!0,!0):A.set(x+b,N+O,!1,!0))}}function m(A){const D=A.size;for(let I=8;I<D-8;I++){const v=I%2===0;A.set(I,6,v,!0),A.set(6,I,v,!0)}}function E(A,D){const I=i.getPositions(D);for(let v=0;v<I.length;v++){const T=I[v][0],x=I[v][1];for(let N=-2;N<=2;N++)for(let b=-2;b<=2;b++)N===-2||N===2||b===-2||b===2||N===0&&b===0?A.set(T+N,x+b,!0,!0):A.set(T+N,x+b,!1,!0)}}function _(A,D){const I=A.size,v=d.getEncodedBits(D);let T,x,N;for(let b=0;b<18;b++)T=Math.floor(b/3),x=b%3+I-8-3,N=(v>>b&1)===1,A.set(T,x,N,!0),A.set(x,T,N,!0)}function w(A,D,I){const v=A.size,T=u.getEncodedBits(D,I);let x,N;for(x=0;x<15;x++)N=(T>>x&1)===1,x<6?A.set(x,8,N,!0):x<8?A.set(x+1,8,N,!0):A.set(v-15+x,8,N,!0),x<8?A.set(8,v-x-1,N,!0):x<9?A.set(8,15-x-1+1,N,!0):A.set(8,15-x-1,N,!0);A.set(v-8,8,1,!0)}function S(A,D){const I=A.size;let v=-1,T=I-1,x=7,N=0;for(let b=I-1;b>0;b-=2)for(b===6&&b--;;){for(let O=0;O<2;O++)if(!A.isReserved(T,b-O)){let j=!1;N<D.length&&(j=(D[N]>>>x&1)===1),A.set(T,b-O,j),x--,x===-1&&(N++,x=7)}if(T+=v,T<0||I<=T){T-=v,v=-v;break}}}function p(A,D,I){const v=new r;I.forEach(function(O){v.put(O.mode.bit,4),v.put(O.getLength(),f.getCharCountIndicator(O.mode,A)),O.write(v)});const T=e.getSymbolTotalCodewords(A),x=a.getTotalCodewordsCount(A,D),N=(T-x)*8;for(v.getLengthInBits()+4<=N&&v.put(0,4);v.getLengthInBits()%8!==0;)v.putBit(0);const b=(N-v.getLengthInBits())/8;for(let O=0;O<b;O++)v.put(O%2?17:236,8);return M(v,A,D)}function M(A,D,I){const v=e.getSymbolTotalCodewords(D),T=a.getTotalCodewordsCount(D,I),x=v-T,N=a.getBlocksCount(D,I),b=v%N,O=N-b,j=Math.floor(v/N),U=Math.floor(x/N),L=U+1,C=j-U,H=new c(C);let F=0;const $=new Array(N),K=new Array(N);let g=0;const P=new Uint8Array(A.buffer);for(let ie=0;ie<N;ie++){const ue=ie<O?U:L;$[ie]=P.slice(F,F+ue),K[ie]=H.encode($[ie]),F+=ue,g=Math.max(g,ue)}const B=new Uint8Array(v);let Q=0,X,ne;for(X=0;X<g;X++)for(ne=0;ne<N;ne++)X<$[ne].length&&(B[Q++]=$[ne][X]);for(X=0;X<C;X++)for(ne=0;ne<N;ne++)B[Q++]=K[ne][X];return B}function z(A,D,I,v){let T;if(Array.isArray(A))T=l.fromArray(A);else if(typeof A=="string"){let j=D;if(!j){const U=l.rawSplit(A);j=d.getBestVersionForData(U,I)}T=l.fromString(A,j||40)}else throw new Error("Invalid data");const x=d.getBestVersionForData(T,I);if(!x)throw new Error("The amount of data is too big to be stored in a QR Code");if(!D)D=x;else if(D<x)throw new Error(`
9
+ URL: ${e}`}function YD(e){return typeof window>"u"||typeof window.confirm!="function"?!1:window.confirm(QD(e.url))}function lu(){typeof window<"u"&&typeof window.close=="function"&&window.close()}function WD(){const e=typeof navigator>"u"?void 0:navigator,t=typeof screen>"u"?void 0:screen,r=typeof window>"u"?void 0:window,n=Object.freeze({protocolVersion:gl,knownMethodCount:zt.length,supportsFileCreate:zt.some(i=>i.method===In),system:ZD(e?.userAgent,e?.platform),userAgent:e?.userAgent??"",platform:e?.platform??"",language:e?.language??"",hardwareConcurrency:Ir(e?.hardwareConcurrency),maxTouchPoints:Ir(e?.maxTouchPoints),screen:{width:Ir(t?.width),height:Ir(t?.height)},viewport:{width:Ir(r?.innerWidth),height:Ir(r?.innerHeight),devicePixelRatio:KD(r?.devicePixelRatio)}});console.info("[hb-sdk-runtime] environment",n)}function ZD(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 Ir(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0?Math.floor(e):0}function KD(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:1}function JD(e){return we(_D,sh,{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 XD(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 eN(e){if(!go(e?.ports)||Array.isArray(e.ports))throw new TypeError("createMiniProgramRuntime 必须显式提供 ports");if(!go(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 xD(e)}function tN(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 f=()=>n.signal.removeEventListener("abort",h),l=m=>{u||(u=!0,f(),c(m))},h=()=>l(new DOMException("账号标识读取已取消","AbortError"));d.onupgradeneeded=()=>{u?d.transaction?.abort():d.result.createObjectStore("accounts")},d.onerror=()=>l(d.error),d.onblocked=()=>l(new Error("账号存储被阻塞")),d.onsuccess=()=>{u?d.result.close():(u=!0,f(),a(d.result))},n.signal.addEventListener("abort",h,{once:!0}),n.signal.aborted&&h()});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"),f=JSON.stringify([t,r]);let l;const h=()=>{try{d.abort()}catch{}m(),c(new DOMException("账号标识读取已取消","AbortError"))};n.signal.addEventListener("abort",h,{once:!0});const m=()=>n.signal.removeEventListener("abort",h);d.oncomplete=()=>{m(),a(l)},d.onabort=d.onerror=()=>{m(),c(d.error??new Error("账号存储事务失败"))};const E=u.get(f);E.onsuccess=()=>{try{if(typeof E.result=="string"&&/^ak_[0-9a-f]{64}$/.test(E.result))l=E.result;else{const _=o.getRandomValues(new Uint8Array(32));l=`ak_${Array.from(_,w=>w.toString(16).padStart(2,"0")).join("")}`,u.put(l,f)}}catch{d.abort()}}})}finally{s.close()}}}const rN=/^(?: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,nN=new Set(["origin","referer","user-agent"]);function iN(e,t){return Ip({mode:"request-only",request:(r,n={signal:t.signal})=>t.run(n.signal,async i=>{const o={...n,signal:i},s=oN(r),a=await e.authenticatedRequest(s,o);return cN(a)})}).network}function oN(e){const t=sN(e.headers);return{...e,target:{...e.target},...e.params===void 0?{}:{params:{...e.params}},...t===void 0?{headers:void 0}:{headers:t}}}function sN(e){if(e!==void 0)return Object.fromEntries(Object.entries(e).filter(([t])=>!aN(t)))}function aN(e){const t=e.trim().toLowerCase();return nN.has(t)}function cN(e){return{status:e.status,...e.statusText===void 0?{}:{statusText:e.statusText},data:e.data,headers:dN(e.headers)??{}}}function dN(e){if(e!==void 0)return Object.fromEntries(Object.entries(e).filter(([t])=>!uN(t)))}function uN(e){const t=e.trim().toLowerCase();return rN.test(t)||t.startsWith("x-heybox-")||t.startsWith("x-xhh-")}function lN(e,t,r){const n=pN(e.presentation,t);return{account:mN(e,t,r),network:iN(e,t),...e.storage===void 0?{}:{storage:gN(e,t)},...e.storage===void 0?{}:fN(e,t),...n===void 0?{}:{presentation:n},...e.protocol===void 0?{}:{protocol:e.protocol}}}function fN(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 hN(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 mN(e,t,r){const n=e.account.getAccountKey?.bind(e.account)??tN();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 gN(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 pN(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)=>Pp(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 yN(){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 Xn(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 Xn(i.reason);const o=new AbortController;let s;const a=new Promise((u,f)=>{s=f}),c=n.map(u=>{const f=()=>{o.signal.aborted||o.abort(u.reason),s(Xn(u.reason))};return u.addEventListener("abort",f,{once:!0}),{listener:f,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]),f=n.find(l=>l.aborted);if(f)throw Xn(f.reason);return u}finally{for(const{listener:u,source:f}of c)f.removeEventListener("abort",u)}}}}function Xn(e){return new DOMException("Web Host operation aborted","AbortError")}async function EN(e){const t=yN(),r=new Set;let n=!1;const i=l=>{if(n||t.signal.aborted)return fs(l),()=>{};let h=!0;const m=()=>{h&&(h=!1,r.delete(m),fs(l))};return r.add(m),m},o=()=>s(e.signal.reason),s=l=>{if(!n){n=!0,e.signal.removeEventListener("abort",o),t.abort(l);for(const h of[...r])h();e.onDispose&&fs(e.onDispose)}};e.signal.addEventListener("abort",o,{once:!0}),e.signal.aborted&&s(e.signal.reason);const a=lN(e,t,i);a.storage?.getRaw&&a.storage.setRaw&&(a.scopedStorage=Yf({storage:a.storage,diagnostics:a.storageDiagnostics,coordinationKey:e.storage.storage,lock:Wf,resolveScope:async()=>Qf((await f()).configuration)}));const c=ql(a,{hostCapabilities:e.hostCapabilities,hasUserDataPresentation:e.userDataPresentation!==void 0,hasUserDataSettings:e.userDataPresentation?.openDataPermissions!==void 0}),d=hN(e,t);let u;const f=()=>u??=t.run(void 0,l=>e.resolveLaunch(l));return{platform:"web",ports:a,environment:d,resolveLaunch:f,...e.authPresentation===void 0?{}:{authPresentation:wN(e.authPresentation,t)},...e.userDataPresentation===void 0?{}:{userDataPresentation:IN(e.userDataPresentation,t)},hostCapabilities:c.effectiveCapabilities,dispose:s}}function fs(e){try{e()}catch{}}function wN(e,t){return{...e.confirmFollowAuthor?{confirmFollowAuthor:r=>t.run(r.signal,n=>e.confirmFollowAuthor({...r,signal:n}))}:{},confirmAuthorization:r=>t.run(r.signal,n=>e.confirmAuthorization({...r,signal:n}))}}function IN(e,t){return{...e.openDataPermissions?{openDataPermissions:r=>t.run(r.signal,n=>e.openDataPermissions({...r,signal:n}))}:{},confirmDataPermission:r=>t.run(r.signal,n=>e.confirmDataPermission({...r,signal:n}))}}var Ar={},hs,fu;function AN(){return fu||(fu=1,hs=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then}),hs}var ms={},Rt={},hu;function cr(){if(hu)return Rt;hu=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 Rt.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},Rt.getSymbolTotalCodewords=function(n){return t[n]},Rt.getBCHDigit=function(r){let n=0;for(;r!==0;)n++,r>>>=1;return n},Rt.setToSJISFunction=function(n){if(typeof n!="function")throw new Error('"toSJISFunc" is not a valid function.');e=n},Rt.isKanjiModeEnabled=function(){return typeof e<"u"},Rt.toSJIS=function(n){return e(n)},Rt}var gs={},mu;function cc(){return mu||(mu=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}}})(gs)),gs}var ps,gu;function _N(){if(gu)return ps;gu=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++}},ps=e,ps}var ys,pu;function DN(){if(pu)return ys;pu=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]},ys=e,ys}var Es={},yu;function NN(){return yu||(yu=1,(function(e){const t=cr().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}})(Es)),Es}var ws={},Eu;function MN(){if(Eu)return ws;Eu=1;const e=cr().getSymbolSize,t=7;return ws.getPositions=function(n){const i=e(n);return[[0,0],[i-t,0],[0,i-t]]},ws}var Is={},wu;function SN(){return wu||(wu=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 f=0;f<o;f++){a=c=0,d=u=null;for(let l=0;l<o;l++){let h=i.get(f,l);h===d?a++:(a>=5&&(s+=t.N1+(a-5)),d=h,a=1),h=i.get(l,f),h===u?c++:(c>=5&&(s+=t.N1+(c-5)),u=h,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}})(Is)),Is}var ei={},Iu;function lh(){if(Iu)return ei;Iu=1;const e=cc(),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 ei.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}},ei.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}},ei}var As={},nn={},Au;function bN(){if(Au)return nn;Au=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]})(),nn.log=function(n){if(n<1)throw new Error("log("+n+")");return t[n]},nn.exp=function(n){return e[n]},nn.mul=function(n,i){return n===0||i===0?0:e[t[n]+t[i]]},nn}var _u;function TN(){return _u||(_u=1,(function(e){const t=bN();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}})(As)),As}var _s,Du;function vN(){if(Du)return _s;Du=1;const e=TN();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},_s=t,_s}var Ds={},Ns={},Ms={},Nu;function fh(){return Nu||(Nu=1,Ms.isValid=function(t){return!isNaN(t)&&t>=1&&t<=40}),Ms}var pt={},Mu;function hh(){if(Mu)return pt;Mu=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
+ ]))+`;pt.KANJI=new RegExp(r,"g"),pt.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g"),pt.BYTE=new RegExp(n,"g"),pt.NUMERIC=new RegExp(e,"g"),pt.ALPHANUMERIC=new RegExp(t,"g");const i=new RegExp("^"+r+"$"),o=new RegExp("^"+e+"$"),s=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");return pt.testKanji=function(c){return i.test(c)},pt.testNumeric=function(c){return o.test(c)},pt.testAlphanumeric=function(c){return s.test(c)},pt}var Su;function dr(){return Su||(Su=1,(function(e){const t=fh(),r=hh();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}}})(Ns)),Ns}var bu;function ON(){return bu||(bu=1,(function(e){const t=cr(),r=lh(),n=cc(),i=dr(),o=fh(),s=7973,a=t.getBCHDigit(s);function c(l,h,m){for(let E=1;E<=40;E++)if(h<=e.getCapacity(E,m,l))return E}function d(l,h){return i.getCharCountIndicator(l,h)+4}function u(l,h){let m=0;return l.forEach(function(E){const _=d(E.mode,h);m+=_+E.getBitsLength()}),m}function f(l,h){for(let m=1;m<=40;m++)if(u(l,m)<=e.getCapacity(m,h,i.MIXED))return m}e.from=function(h,m){return o.isValid(h)?parseInt(h,10):m},e.getCapacity=function(h,m,E){if(!o.isValid(h))throw new Error("Invalid QR Code version");typeof E>"u"&&(E=i.BYTE);const _=t.getSymbolTotalCodewords(h),w=r.getTotalCodewordsCount(h,m),S=(_-w)*8;if(E===i.MIXED)return S;const p=S-d(E,h);switch(E){case i.NUMERIC:return Math.floor(p/10*3);case i.ALPHANUMERIC:return Math.floor(p/11*2);case i.KANJI:return Math.floor(p/13);case i.BYTE:default:return Math.floor(p/8)}},e.getBestVersionForData=function(h,m){let E;const _=n.from(m,n.M);if(Array.isArray(h)){if(h.length>1)return f(h,_);if(h.length===0)return 1;E=h[0]}else E=h;return c(E.mode,E.getLength(),_)},e.getEncodedBits=function(h){if(!o.isValid(h)||h<7)throw new Error("Invalid QR Code version");let m=h<<12;for(;t.getBCHDigit(m)-a>=0;)m^=s<<t.getBCHDigit(m)-a;return h<<12|m}})(Ds)),Ds}var Ss={},Tu;function RN(){if(Tu)return Ss;Tu=1;const e=cr(),t=1335,r=21522,n=e.getBCHDigit(t);return Ss.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},Ss}var bs={},Ts,vu;function PN(){if(vu)return Ts;vu=1;const e=dr();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))},Ts=t,Ts}var vs,Ou;function kN(){if(Ou)return vs;Ou=1;const e=dr(),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)},vs=r,vs}var Os,Ru;function CN(){if(Ru)return Os;Ru=1;const e=dr();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)},Os=t,Os}var Rs,Pu;function LN(){if(Pu)return Rs;Pu=1;const e=dr(),t=cr();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)}},Rs=r,Rs}var Ps={exports:{}},ku;function UN(){return ku||(ku=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,f,l,h,m,E,_;!a.empty();){c=a.pop(),d=c.value,f=c.cost,l=r[d]||{};for(u in l)l.hasOwnProperty(u)&&(h=l[u],m=f+h,E=s[u],_=typeof s[u]>"u",(_||E>m)&&(s[u]=m,a.push(u,m),o[u]=d))}if(typeof i<"u"&&typeof s[i]>"u"){var w=["Could not find a path from ",n," to ",i,"."].join("");throw new Error(w)}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})(Ps)),Ps.exports}var Cu;function xN(){return Cu||(Cu=1,(function(e){const t=dr(),r=PN(),n=kN(),i=CN(),o=LN(),s=hh(),a=cr(),c=UN();function d(w){return unescape(encodeURIComponent(w)).length}function u(w,S,p){const M=[];let z;for(;(z=w.exec(p))!==null;)M.push({data:z[0],index:z.index,mode:S,length:z[0].length});return M}function f(w){const S=u(s.NUMERIC,t.NUMERIC,w),p=u(s.ALPHANUMERIC,t.ALPHANUMERIC,w);let M,z;return a.isKanjiModeEnabled()?(M=u(s.BYTE,t.BYTE,w),z=u(s.KANJI,t.KANJI,w)):(M=u(s.BYTE_KANJI,t.BYTE,w),z=[]),S.concat(p,M,z).sort(function(D,I){return D.index-I.index}).map(function(D){return{data:D.data,mode:D.mode,length:D.length}})}function l(w,S){switch(S){case t.NUMERIC:return r.getBitsLength(w);case t.ALPHANUMERIC:return n.getBitsLength(w);case t.KANJI:return o.getBitsLength(w);case t.BYTE:return i.getBitsLength(w)}}function h(w){return w.reduce(function(S,p){const M=S.length-1>=0?S[S.length-1]:null;return M&&M.mode===p.mode?(S[S.length-1].data+=p.data,S):(S.push(p),S)},[])}function m(w){const S=[];for(let p=0;p<w.length;p++){const M=w[p];switch(M.mode){case t.NUMERIC:S.push([M,{data:M.data,mode:t.ALPHANUMERIC,length:M.length},{data:M.data,mode:t.BYTE,length:M.length}]);break;case t.ALPHANUMERIC:S.push([M,{data:M.data,mode:t.BYTE,length:M.length}]);break;case t.KANJI:S.push([M,{data:M.data,mode:t.BYTE,length:d(M.data)}]);break;case t.BYTE:S.push([{data:M.data,mode:t.BYTE,length:d(M.data)}])}}return S}function E(w,S){const p={},M={start:{}};let z=["start"];for(let A=0;A<w.length;A++){const D=w[A],I=[];for(let v=0;v<D.length;v++){const T=D[v],x=""+A+v;I.push(x),p[x]={node:T,lastCount:0},M[x]={};for(let N=0;N<z.length;N++){const b=z[N];p[b]&&p[b].node.mode===T.mode?(M[b][x]=l(p[b].lastCount+T.length,T.mode)-l(p[b].lastCount,T.mode),p[b].lastCount+=T.length):(p[b]&&(p[b].lastCount=T.length),M[b][x]=l(T.length,T.mode)+4+t.getCharCountIndicator(T.mode,S))}}z=I}for(let A=0;A<z.length;A++)M[z[A]].end=0;return{map:M,table:p}}function _(w,S){let p;const M=t.getBestModeForData(w);if(p=t.from(S,M),p!==t.BYTE&&p.bit<M.bit)throw new Error('"'+w+'" cannot be encoded with mode '+t.toString(p)+`.
12
+ Suggested mode is: `+t.toString(M));switch(p===t.KANJI&&!a.isKanjiModeEnabled()&&(p=t.BYTE),p){case t.NUMERIC:return new r(w);case t.ALPHANUMERIC:return new n(w);case t.KANJI:return new o(w);case t.BYTE:return new i(w)}}e.fromArray=function(S){return S.reduce(function(p,M){return typeof M=="string"?p.push(_(M,null)):M.data&&p.push(_(M.data,M.mode)),p},[])},e.fromString=function(S,p){const M=f(S,a.isKanjiModeEnabled()),z=m(M),A=E(z,p),D=c.find_path(A.map,"start","end"),I=[];for(let v=1;v<D.length-1;v++)I.push(A.table[D[v]].node);return e.fromArray(h(I))},e.rawSplit=function(S){return e.fromArray(f(S,a.isKanjiModeEnabled()))}})(bs)),bs}var Lu;function zN(){if(Lu)return ms;Lu=1;const e=cr(),t=cc(),r=_N(),n=DN(),i=NN(),o=MN(),s=SN(),a=lh(),c=vN(),d=ON(),u=RN(),f=dr(),l=xN();function h(A,D){const I=A.size,v=o.getPositions(D);for(let T=0;T<v.length;T++){const x=v[T][0],N=v[T][1];for(let b=-1;b<=7;b++)if(!(x+b<=-1||I<=x+b))for(let O=-1;O<=7;O++)N+O<=-1||I<=N+O||(b>=0&&b<=6&&(O===0||O===6)||O>=0&&O<=6&&(b===0||b===6)||b>=2&&b<=4&&O>=2&&O<=4?A.set(x+b,N+O,!0,!0):A.set(x+b,N+O,!1,!0))}}function m(A){const D=A.size;for(let I=8;I<D-8;I++){const v=I%2===0;A.set(I,6,v,!0),A.set(6,I,v,!0)}}function E(A,D){const I=i.getPositions(D);for(let v=0;v<I.length;v++){const T=I[v][0],x=I[v][1];for(let N=-2;N<=2;N++)for(let b=-2;b<=2;b++)N===-2||N===2||b===-2||b===2||N===0&&b===0?A.set(T+N,x+b,!0,!0):A.set(T+N,x+b,!1,!0)}}function _(A,D){const I=A.size,v=d.getEncodedBits(D);let T,x,N;for(let b=0;b<18;b++)T=Math.floor(b/3),x=b%3+I-8-3,N=(v>>b&1)===1,A.set(T,x,N,!0),A.set(x,T,N,!0)}function w(A,D,I){const v=A.size,T=u.getEncodedBits(D,I);let x,N;for(x=0;x<15;x++)N=(T>>x&1)===1,x<6?A.set(x,8,N,!0):x<8?A.set(x+1,8,N,!0):A.set(v-15+x,8,N,!0),x<8?A.set(8,v-x-1,N,!0):x<9?A.set(8,15-x-1+1,N,!0):A.set(8,15-x-1,N,!0);A.set(v-8,8,1,!0)}function S(A,D){const I=A.size;let v=-1,T=I-1,x=7,N=0;for(let b=I-1;b>0;b-=2)for(b===6&&b--;;){for(let O=0;O<2;O++)if(!A.isReserved(T,b-O)){let j=!1;N<D.length&&(j=(D[N]>>>x&1)===1),A.set(T,b-O,j),x--,x===-1&&(N++,x=7)}if(T+=v,T<0||I<=T){T-=v,v=-v;break}}}function p(A,D,I){const v=new r;I.forEach(function(O){v.put(O.mode.bit,4),v.put(O.getLength(),f.getCharCountIndicator(O.mode,A)),O.write(v)});const T=e.getSymbolTotalCodewords(A),x=a.getTotalCodewordsCount(A,D),N=(T-x)*8;for(v.getLengthInBits()+4<=N&&v.put(0,4);v.getLengthInBits()%8!==0;)v.putBit(0);const b=(N-v.getLengthInBits())/8;for(let O=0;O<b;O++)v.put(O%2?17:236,8);return M(v,A,D)}function M(A,D,I){const v=e.getSymbolTotalCodewords(D),T=a.getTotalCodewordsCount(D,I),x=v-T,N=a.getBlocksCount(D,I),b=v%N,O=N-b,j=Math.floor(v/N),U=Math.floor(x/N),L=U+1,C=j-U,H=new c(C);let F=0;const $=new Array(N),K=new Array(N);let g=0;const k=new Uint8Array(A.buffer);for(let ie=0;ie<N;ie++){const ue=ie<O?U:L;$[ie]=k.slice(F,F+ue),K[ie]=H.encode($[ie]),F+=ue,g=Math.max(g,ue)}const B=new Uint8Array(v);let Q=0,X,ne;for(X=0;X<g;X++)for(ne=0;ne<N;ne++)X<$[ne].length&&(B[Q++]=$[ne][X]);for(X=0;X<C;X++)for(ne=0;ne<N;ne++)B[Q++]=K[ne][X];return B}function z(A,D,I,v){let T;if(Array.isArray(A))T=l.fromArray(A);else if(typeof A=="string"){let j=D;if(!j){const U=l.rawSplit(A);j=d.getBestVersionForData(U,I)}T=l.fromString(A,j||40)}else throw new Error("Invalid data");const x=d.getBestVersionForData(T,I);if(!x)throw new Error("The amount of data is too big to be stored in a QR Code");if(!D)D=x;else if(D<x)throw new Error(`
13
13
  The chosen QR Code version cannot contain this amount of data.
14
14
  Minimum version required to store current data is: `+x+`.
15
- `);const N=p(D,I,T),b=e.getSymbolSize(D),O=new n(b);return h(O,D),m(O),E(O,D),w(O,I,0),D>=7&&_(O,D),S(O,N),isNaN(v)&&(v=s.getBestMask(O,w.bind(null,O,I))),s.applyMask(v,O),w(O,I,v),{modules:O,version:D,errorCorrectionLevel:I,maskPattern:v,segments:T}}return ms.create=function(D,I){if(typeof D>"u"||D==="")throw new Error("No input text");let v=t.M,T,x;return typeof I<"u"&&(v=t.from(I.errorCorrectionLevel,t.M),T=d.from(I.version),x=s.from(I.maskPattern),I.toSJISFunc&&e.setToSJISFunction(I.toSJISFunc)),z(D,T,v,x)},ms}var Ps={},Cs={},Uu;function mh(){return Uu||(Uu=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,f=[o.color.light,o.color.dark];for(let l=0;l<d;l++)for(let h=0;h<d;h++){let m=(l*d+h)*4,E=o.color.light;if(l>=u&&h>=u&&l<d-u&&h<d-u){const _=Math.floor((l-u)/c),w=Math.floor((h-u)/c);E=f[a[_*s+w]?1:0]}n[m++]=E.r,n[m++]=E.g,n[m++]=E.b,n[m]=E.a}}})(Cs)),Cs}var xu;function jN(){return xu||(xu=1,(function(e){const t=mh();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),f=d.getContext("2d"),l=f.createImageData(u,u);return t.qrToImageData(l.data,o,c),r(f,d,u),f.putImageData(l,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",f=c.rendererOpts||{};return d.toDataURL(u,f.quality)}})(Ps)),Ps}var Ls={},zu;function BN(){if(zu)return Ls;zu=1;const e=mh();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 f=0;f<i.length;f++){const l=Math.floor(f%o),h=Math.floor(f/o);!l&&!d&&(d=!0),i[f]?(u++,f>0&&l>0&&i[f-1]||(a+=d?r("M",l+s,.5+h+s):r("m",c,0),c=0,d=!1),l+1<o&&i[f+1]||(a+=r("h",u),u=0)):c++}return a}return Ls.render=function(o,s,a){const c=e.getOptions(s),d=o.modules.size,u=o.modules.data,f=d+c.margin*2,l=c.color.light.a?"<path "+t(c.color.light,"fill")+' d="M0 0h'+f+"v"+f+'H0z"/>':"",h="<path "+t(c.color.dark,"stroke")+' d="'+n(u,d,c.margin)+'"/>',m='viewBox="0 0 '+f+" "+f+'"',_='<svg xmlns="http://www.w3.org/2000/svg" '+(c.width?'width="'+c.width+'" height="'+c.width+'" ':"")+m+' shape-rendering="crispEdges">'+l+h+`</svg>
16
- `;return typeof a=="function"&&a(null,_),_},Ls}var ju;function HN(){if(ju)return Ar;ju=1;const e=AN(),t=zN(),r=jN(),n=BN();function i(o,s,a,c,d){const u=[].slice.call(arguments,1),f=u.length,l=typeof u[f-1]=="function";if(!l&&!e())throw new Error("Callback required as last argument");if(l){if(f<2)throw new Error("Too few arguments provided");f===2?(d=a,a=s,s=c=void 0):f===3&&(s.getContext&&typeof d>"u"?(d=c,c=void 0):(d=c,c=a,a=s,s=void 0))}else{if(f<1)throw new Error("Too few arguments provided");return f===1?(a=s,s=c=void 0):f===2&&!s.getContext&&(c=a,a=s,s=void 0),new Promise(function(h,m){try{const E=t.create(a,c);h(o(E,s,c))}catch(E){m(E)}})}try{const h=t.create(a,c);d(null,o(h,s,c))}catch(h){d(h)}}return Ar.create=t.create,Ar.toCanvas=i.bind(null,r.render),Ar.toDataURL=i.bind(null,r.renderToDataURL),Ar.toString=i.bind(null,function(o,s,a){return n.render(o,a)}),Ar}var Bu=HN();function FN(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,f]of c)f.kind!=="directory"||!/^hb-game-saves-[a-f0-9-]{36}$/.test(u)||await e.locks.request(r(u),{ifAvailable:!0},async l=>{l&&await Hu(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 Hu(c,t).catch(()=>{})}}).catch(i),o.catch(()=>{}),o}async function Hu(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 Us=8*1024*1024,VN=new Set(["content-length","content-type","content-encoding","transfer-encoding","content-disposition","content-range"]),GN="/__hb_sdk__/game-save-download",Ge=(e,t)=>({code:e,message:t});function $N(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=FN({getRoot:t,locks:r,signal:e.signal}),o=new WeakMap,s=new WeakSet,a=m=>{m.signal.throwIfAborted(),m.lifecycle!=="cleanup"&&e.signal.throwIfAborted()},c=()=>i;function d(m){if(!/^\.hb-game-saves\/[a-zA-Z0-9_-]+\.zip$/.test(m))throw Ge("FILE_ACCESS_DENIED","浏览器仅开放存档私有缓存");return m.slice(15)}async function u(m,E){a(E);const _=d(m);try{return await(await c()).getFileHandle(_)}catch(w){throw w instanceof DOMException&&w.name==="NotFoundError"?Ge("FILE_NOT_FOUND","存档缓存不存在"):w}}function f(m){const E={kind:"file",mode:"readwrite",name:m.split("/").at(-1),async create(_,w){a(w);const S=d(m),p=await c();if(_.exclusive)try{throw await p.getFileHandle(S),Ge("FILE_ALREADY_EXISTS","存档缓存已存在")}catch(M){if(!(M instanceof DOMException&&M.name==="NotFoundError"))throw M}a(w),await p.getFileHandle(S,{create:!0}),a(w)},async remove(_){a(_);const w=d(m);if(i)try{await(await i).removeEntry(w)}catch(S){if(!(S instanceof DOMException&&S.name==="NotFoundError"))throw S}},async read(_){const w=await(await u(m,_)).getFile();if(w.size>Us)throw Ge("FILE_TOO_LARGE","存档文件超过 8 MiB");const S=new Uint8Array(await w.arrayBuffer());try{return a(_),S}catch(p){throw S.fill(0),p}},async write(){throw Ge("FILE_ACCESS_DENIED","存档缓存仅允许受控下载写入")},async stat(_){const w=await(await u(m,_)).getFile();return a(_),{kind:"file",size:w.size,modifiedAt:w.lastModified}}};return o.set(E,m),E}const l=async()=>{throw Ge("FILE_ACCESS_DENIED","浏览器仅开放存档私有缓存")},h={kind:"directory",mode:"readwrite",name:"",file:f,directory(m){return{...h,name:m,async create(E,_){if(a(_),m!==".hb-game-saves")return l();await c(),a(_)}}},create:l,stat:l,list:l};return{files:{sandbox:h},transfer:{network:{async open(m,E){if(a(E),!Hl(m))throw Ge("METHOD_FORBIDDEN","仅支持受控存档下载");const _=await(e.fetch??fetch)(GN,{method:"POST",credentials:"same-origin",redirect:"error",headers:{"content-type":"application/json","x-hb-sdk-csrf":e.csrfToken()},body:JSON.stringify(m),signal:AbortSignal.any([E.signal,e.signal,AbortSignal.timeout(6e4)])});if(!_.ok){const w=await _.json().catch(()=>({}));throw Ge(w.code==="FILE_TOO_LARGE"?"FILE_TOO_LARGE":"DOWNLOAD_NETWORK_FAILED","存档下载失败")}return s.add(_),{status:_.status,headers:Object.fromEntries(Array.from(_.headers).filter(([w])=>VN.has(w)).map(([w,S])=>[w,[S]])),body:_}},async release(m){s.delete(m),await m.body?.cancel()}},files:{async writeResource(m,E,_,w){let S,p;try{a(w);const M=o.get(m);if(!M||!s.delete(E))throw Ge("FILE_ACCESS_DENIED","下载资源不属于当前存档会话");if(_.mode!=="replace-existing")throw Ge("FILE_ACCESS_DENIED","存档下载目标必须先创建");if(S=await(await u(M,w)).createWritable(),!E.body)throw Ge("DOWNLOAD_NETWORK_FAILED","存档下载没有响应内容");p=E.body.getReader();let A=0;for(;;){a(w);const D=await p.read().catch(I=>{throw a(w),Ge(I instanceof DOMException&&I.name==="TimeoutError"?"DOWNLOAD_TIMEOUT":"DOWNLOAD_NETWORK_FAILED","存档下载流中断")});if(a(w),D.done)break;if(A+=D.value.byteLength,A>Math.min(_.maxBytes??Us,Us))throw Ge("FILE_TOO_LARGE","存档文件超过 8 MiB");await S.write(new Uint8Array(D.value)),w.onProgress(A)}if(_.expectedBytes!==void 0&&A!==_.expectedBytes)throw Ge("DOWNLOAD_NETWORK_FAILED","存档下载长度不匹配");return a(w),await S.close(),S=void 0,{committedBytes:A}}catch(M){throw M instanceof DOMException&&M.name==="QuotaExceededError"?Ge("FILE_QUOTA_EXCEEDED","浏览器存储空间不足"):M}finally{await p?.cancel().catch(()=>{}),p||await E.body?.cancel().catch(()=>{}),await S?.abort().catch(()=>{}),s.delete(E)}}}}}}function yt(e,t){throw{code:e,message:t}}function on(e){return JSON.stringify(e,(t,r)=>r&&typeof r=="object"&&!Array.isArray(r)?Object.fromEntries(Object.keys(r).sort().map(n=>[n,r[n]])):r)}function qN(e){return{declaredPermissions:e.declaredPermissions??{},platforms:[...e.platforms??[]].sort(),runtimePermissions:e.runtimePermissions,networkPolicy:e.networkPolicy}}function QN(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(),yt("UNAUTHORIZED","请先通过 hb-sdk login 登录小黑盒"));const{signed:c,browser:d}=a,u=$g(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(),yt("INVALID_STATE","开发启动授权尚未就绪,请检查 CLI 登录、项目绑定及开发票据状态"));let f;try{f=jl({...u,declared_permissions:d.declaredPermissions??{},platforms:d.platforms??[]})}catch{}(d.source!=="remote"||d.miniProgramId!==c.miniProgramId||d.devSessionId!==u.session_id||c.devSessionId!==u.session_id||c.contextRevision!==u.revision||f!==c.developmentSnapshot||on(d.runtimePermissions)!==on(c.runtimePermissions)||on(d.networkPolicy)!==on(c.networkPolicy))&&(i(),yt("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:on([a.userId,a.accountRevision,l,d.contextRevision,qN(d)]),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(E){d.throwIfAborted();const _=E&&typeof E=="object"&&"code"in E?String(E.code):"";if(["SESSION_UNAUTHENTICATED","SESSION_INVALIDATED","UNAUTHORIZED"].includes(_)&&yt("UNAUTHORIZED","小黑盒登录已失效,请重新登录"),["REQUEST_CANCELLED","REQUEST_TIMEOUT"].includes(_)||E instanceof DOMException&&["AbortError","TimeoutError"].includes(E.name))throw E;yt("REQUEST_FAILED","获取开发运行授权失败,请稍后重试")}d.throwIfAborted(),await e.refreshAccount(d),d.throwIfAborted(),o().key!==a.key&&yt("AUTHORIZATION_CONTEXT_CHANGED","账号或开发快照已变化,请重试");const f=u.data;(u.status===401||f?.status==="login"||f?.status==="relogin")&&yt("UNAUTHORIZED","小黑盒登录已失效,请重新登录"),(u.status!==200||f?.status!=="ok")&&yt("REQUEST_FAILED","获取开发运行授权失败,请检查开发资格后重试");const l=f.result,h=Number(l?.expires_at)*1e3;(typeof l?.token!="string"||!l.token.trim()||!Number.isSafeInteger(l?.expires_at)||!Number.isSafeInteger(h)||h<=t()||!["legacy","local","server"].includes(String(l.user_data_mode)))&&yt("INVALID_RESPONSE","开发运行授权响应无效");const m={token:l.token,expiresAt:Math.min(h,a.expiresAt),steamAccount:l.steam_account===!0,userDataMode:l.user_data_mode};return r={key:a.key,value:m},m}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 l=new AbortController,h=s(d,{...a,signal:AbortSignal.any([l.signal,e.signal])});u={promise:h,controller:l,users:0},n.set(d.key,u);const m=u;h.finally(()=>{n.get(d.key)===m&&n.delete(d.key)}).catch(()=>{})}u.users++;let f;try{const l=await Promise.race([u.promise,new Promise((h,m)=>{f=()=>m(c.reason),c.addEventListener("abort",f,{once:!0}),c.aborted&&f()})]);return c.throwIfAborted(),o().key!==d.key&&yt("AUTHORIZATION_CONTEXT_CHANGED","账号或开发快照已变化,请重试"),l}finally{c.removeEventListener("abort",f),--u.users===0&&u.controller.abort()}}}}const YN="/__hb_sdk__/dev-context";function Fu(e,t){return On(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:On(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 fn(e,t=Date.now()){if(e.localDevGrant===void 0)return e;const r=Tl(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:tg({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 WN(e){if(!On(e)||!Vu(e,["networkRequest"]))return;const t=e.networkRequest;if(!(!On(t)||!Vu(t,["status","useOfficialDomain"]))&&!(t.status!=="enabled"&&t.status!=="disabled")&&typeof t.useOfficialDomain=="boolean")return{networkRequest:{status:t.status,useOfficialDomain:t.useOfficialDomain}}}const ZN={networkRequest:{status:"disabled",useOfficialDomain:!1}};function Bo(e){const t=qe(e.localDevGrant?Va({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}}:JN()}function gh(e,t,r){return r?.localDevGrant?Va({declaredPermissions:r.declaredPermissions??{},runtimePermissions:e,localDevGrant:r.localDevGrant}).runtimePermissions:ph(e,t,t.networkRequest.useOfficialDomain)}function KN(e){if(e.source!=="remote")return{schema_version:1,entries:[]};const t=Bo({...e,localDevGrant:void 0});return ph(e.runtimePermissions,t,!1)}function JN(){return{networkRequest:{...ZN.networkRequest}}}function ph(e,t,r){const n=qe(e);if(!n.valid)return{schema_version:1,entries:[]};const i=[];for(const s of sr){const a=n.permissions[s];a&&i.push(s==="network"?{key:s,status:t.networkRequest.status,config:{useOfficialDomain:r}}:s==="user_game_data"?{key:s,status:a.status,config:{resources:a.config.resources}}:{key:s,status:a.status,config:{}})}const o=On(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 On(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&Object.getPrototypeOf(e)===Object.prototype}function Vu(e,t){return Object.keys(e).length===t.length&&t.every(n=>Object.hasOwn(e,n))}function XN(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(f){a={ok:!1},!n&&!c.signal.aborted&&s(f);continue}finally{t===c&&(t=void 0)}if(n)return{ok:!1};let u;try{u=e.apply(d)}catch(f){a={ok:!1},n||s(f);continue}if(n)return{ok:!1};if(a={ok:!0},!!e.hasChanged(u))try{await e.onChanged(u)}catch(f){a={ok:!1},n||s(f)}}return n?{ok:!1}:a}function s(a){try{e.onError(a)}catch{}}}function eM(e){return XN({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 tM(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 xs=new WeakMap;function dc(e){return new Promise((t,r)=>{if(e.signal?.aborted){r(e.signal.reason);return}const{root:n,signal:i}=e;xs.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",l);const m=s()===n;if(n.remove(),m){const E=s();E&&(E.inert=!1,E.removeAttribute("aria-hidden"));let _=xs.get(n)??null;for(;_ instanceof HTMLElement&&!_.isConnected;){const w=_.closest("[data-host-dialog]");_=w?xs.get(w)??null:null}_ instanceof HTMLElement&&(!E||E.contains(_))?_.focus():E?.querySelector("button")?.focus()}},d=Yh({kind:"dialog",mode:e.mode??"simulated",title:e.title,method:e.method,...e.callId?{callId:e.callId}:{},actions:o.map(m=>m.textContent?.trim()??"")},m=>{c(),a!==void 0?t(a):r(i?.reason??new DOMException(`宿主弹窗已${m}`,"AbortError"))});function u(){d.finish("cancelled")}function f(m){a=m,d.finish(m===e.cancelAction?"cancelled":"confirmed")}function l(m){if(s()!==n||(m.key==="Escape"&&e.cancelAction&&(m.preventDefault(),f(e.cancelAction)),m.key!=="Tab"||o.length===0))return;const E=o[0],_=o.at(-1);m.shiftKey&&document.activeElement===E?(m.preventDefault(),_.focus()):!m.shiftKey&&document.activeElement===_&&(m.preventDefault(),E.focus())}if(!d.active)return;if(i?.aborted){u();return}for(const m of o)m.addEventListener("click",()=>f(m.dataset.action));n.addEventListener("click",m=>{m.target===n&&e.cancelAction&&f(e.cancelAction)}),n.dataset.interactionId=d.interactionId;const h=s();h&&(h.inert=!0,h.setAttribute("aria-hidden","true")),(document.querySelector("#host-overlay-layer")??document.body).appendChild(n),i?.addEventListener("abort",u,{once:!0}),document.addEventListener("keydown",l),o[0]?.focus(),i?.aborted&&u()})}function et(e){return e.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&#039;")}const Gu="hb-sdk-action-dialog-style";async function Ho(e){await yh(e)}async function rM(e){return await yh({title:"关注作者",detail:"是否关注当前小程序的作者?",signal:e.signal,method:"user.requestFollowAuthor",mode:"browser",confirmation:!0})?"confirmed":"cancelled"}async function yh(e){aM();const t=document.createElement("div");return t.className="hb-sdk-action-dialog",t.innerHTML=`
15
+ `);const N=p(D,I,T),b=e.getSymbolSize(D),O=new n(b);return h(O,D),m(O),E(O,D),w(O,I,0),D>=7&&_(O,D),S(O,N),isNaN(v)&&(v=s.getBestMask(O,w.bind(null,O,I))),s.applyMask(v,O),w(O,I,v),{modules:O,version:D,errorCorrectionLevel:I,maskPattern:v,segments:T}}return ms.create=function(D,I){if(typeof D>"u"||D==="")throw new Error("No input text");let v=t.M,T,x;return typeof I<"u"&&(v=t.from(I.errorCorrectionLevel,t.M),T=d.from(I.version),x=s.from(I.maskPattern),I.toSJISFunc&&e.setToSJISFunction(I.toSJISFunc)),z(D,T,v,x)},ms}var ks={},Cs={},Uu;function mh(){return Uu||(Uu=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,f=[o.color.light,o.color.dark];for(let l=0;l<d;l++)for(let h=0;h<d;h++){let m=(l*d+h)*4,E=o.color.light;if(l>=u&&h>=u&&l<d-u&&h<d-u){const _=Math.floor((l-u)/c),w=Math.floor((h-u)/c);E=f[a[_*s+w]?1:0]}n[m++]=E.r,n[m++]=E.g,n[m++]=E.b,n[m]=E.a}}})(Cs)),Cs}var xu;function jN(){return xu||(xu=1,(function(e){const t=mh();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),f=d.getContext("2d"),l=f.createImageData(u,u);return t.qrToImageData(l.data,o,c),r(f,d,u),f.putImageData(l,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",f=c.rendererOpts||{};return d.toDataURL(u,f.quality)}})(ks)),ks}var Ls={},zu;function BN(){if(zu)return Ls;zu=1;const e=mh();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 f=0;f<i.length;f++){const l=Math.floor(f%o),h=Math.floor(f/o);!l&&!d&&(d=!0),i[f]?(u++,f>0&&l>0&&i[f-1]||(a+=d?r("M",l+s,.5+h+s):r("m",c,0),c=0,d=!1),l+1<o&&i[f+1]||(a+=r("h",u),u=0)):c++}return a}return Ls.render=function(o,s,a){const c=e.getOptions(s),d=o.modules.size,u=o.modules.data,f=d+c.margin*2,l=c.color.light.a?"<path "+t(c.color.light,"fill")+' d="M0 0h'+f+"v"+f+'H0z"/>':"",h="<path "+t(c.color.dark,"stroke")+' d="'+n(u,d,c.margin)+'"/>',m='viewBox="0 0 '+f+" "+f+'"',_='<svg xmlns="http://www.w3.org/2000/svg" '+(c.width?'width="'+c.width+'" height="'+c.width+'" ':"")+m+' shape-rendering="crispEdges">'+l+h+`</svg>
16
+ `;return typeof a=="function"&&a(null,_),_},Ls}var ju;function HN(){if(ju)return Ar;ju=1;const e=AN(),t=zN(),r=jN(),n=BN();function i(o,s,a,c,d){const u=[].slice.call(arguments,1),f=u.length,l=typeof u[f-1]=="function";if(!l&&!e())throw new Error("Callback required as last argument");if(l){if(f<2)throw new Error("Too few arguments provided");f===2?(d=a,a=s,s=c=void 0):f===3&&(s.getContext&&typeof d>"u"?(d=c,c=void 0):(d=c,c=a,a=s,s=void 0))}else{if(f<1)throw new Error("Too few arguments provided");return f===1?(a=s,s=c=void 0):f===2&&!s.getContext&&(c=a,a=s,s=void 0),new Promise(function(h,m){try{const E=t.create(a,c);h(o(E,s,c))}catch(E){m(E)}})}try{const h=t.create(a,c);d(null,o(h,s,c))}catch(h){d(h)}}return Ar.create=t.create,Ar.toCanvas=i.bind(null,r.render),Ar.toDataURL=i.bind(null,r.renderToDataURL),Ar.toString=i.bind(null,function(o,s,a){return n.render(o,a)}),Ar}var Bu=HN();function FN(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,f]of c)f.kind!=="directory"||!/^hb-game-saves-[a-f0-9-]{36}$/.test(u)||await e.locks.request(r(u),{ifAvailable:!0},async l=>{l&&await Hu(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 Hu(c,t).catch(()=>{})}}).catch(i),o.catch(()=>{}),o}async function Hu(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 Us=8*1024*1024,VN=new Set(["content-length","content-type","content-encoding","transfer-encoding","content-disposition","content-range"]),GN="/__hb_sdk__/game-save-download",Ge=(e,t)=>({code:e,message:t});function $N(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=FN({getRoot:t,locks:r,signal:e.signal}),o=new WeakMap,s=new WeakSet,a=m=>{m.signal.throwIfAborted(),m.lifecycle!=="cleanup"&&e.signal.throwIfAborted()},c=()=>i;function d(m){if(!/^\.hb-game-saves\/[a-zA-Z0-9_-]+\.zip$/.test(m))throw Ge("FILE_ACCESS_DENIED","浏览器仅开放存档私有缓存");return m.slice(15)}async function u(m,E){a(E);const _=d(m);try{return await(await c()).getFileHandle(_)}catch(w){throw w instanceof DOMException&&w.name==="NotFoundError"?Ge("FILE_NOT_FOUND","存档缓存不存在"):w}}function f(m){const E={kind:"file",mode:"readwrite",name:m.split("/").at(-1),async create(_,w){a(w);const S=d(m),p=await c();if(_.exclusive)try{throw await p.getFileHandle(S),Ge("FILE_ALREADY_EXISTS","存档缓存已存在")}catch(M){if(!(M instanceof DOMException&&M.name==="NotFoundError"))throw M}a(w),await p.getFileHandle(S,{create:!0}),a(w)},async remove(_){a(_);const w=d(m);if(i)try{await(await i).removeEntry(w)}catch(S){if(!(S instanceof DOMException&&S.name==="NotFoundError"))throw S}},async read(_){const w=await(await u(m,_)).getFile();if(w.size>Us)throw Ge("FILE_TOO_LARGE","存档文件超过 8 MiB");const S=new Uint8Array(await w.arrayBuffer());try{return a(_),S}catch(p){throw S.fill(0),p}},async write(){throw Ge("FILE_ACCESS_DENIED","存档缓存仅允许受控下载写入")},async stat(_){const w=await(await u(m,_)).getFile();return a(_),{kind:"file",size:w.size,modifiedAt:w.lastModified}}};return o.set(E,m),E}const l=async()=>{throw Ge("FILE_ACCESS_DENIED","浏览器仅开放存档私有缓存")},h={kind:"directory",mode:"readwrite",name:"",file:f,directory(m){return{...h,name:m,async create(E,_){if(a(_),m!==".hb-game-saves")return l();await c(),a(_)}}},create:l,stat:l,list:l};return{files:{sandbox:h},transfer:{network:{async open(m,E){if(a(E),!Hl(m))throw Ge("METHOD_FORBIDDEN","仅支持受控存档下载");const _=await(e.fetch??fetch)(GN,{method:"POST",credentials:"same-origin",redirect:"error",headers:{"content-type":"application/json","x-hb-sdk-csrf":e.csrfToken()},body:JSON.stringify(m),signal:AbortSignal.any([E.signal,e.signal,AbortSignal.timeout(6e4)])});if(!_.ok){const w=await _.json().catch(()=>({}));throw Ge(w.code==="FILE_TOO_LARGE"?"FILE_TOO_LARGE":"DOWNLOAD_NETWORK_FAILED","存档下载失败")}return s.add(_),{status:_.status,headers:Object.fromEntries(Array.from(_.headers).filter(([w])=>VN.has(w)).map(([w,S])=>[w,[S]])),body:_}},async release(m){s.delete(m),await m.body?.cancel()}},files:{async writeResource(m,E,_,w){let S,p;try{a(w);const M=o.get(m);if(!M||!s.delete(E))throw Ge("FILE_ACCESS_DENIED","下载资源不属于当前存档会话");if(_.mode!=="replace-existing")throw Ge("FILE_ACCESS_DENIED","存档下载目标必须先创建");if(S=await(await u(M,w)).createWritable(),!E.body)throw Ge("DOWNLOAD_NETWORK_FAILED","存档下载没有响应内容");p=E.body.getReader();let A=0;for(;;){a(w);const D=await p.read().catch(I=>{throw a(w),Ge(I instanceof DOMException&&I.name==="TimeoutError"?"DOWNLOAD_TIMEOUT":"DOWNLOAD_NETWORK_FAILED","存档下载流中断")});if(a(w),D.done)break;if(A+=D.value.byteLength,A>Math.min(_.maxBytes??Us,Us))throw Ge("FILE_TOO_LARGE","存档文件超过 8 MiB");await S.write(new Uint8Array(D.value)),w.onProgress(A)}if(_.expectedBytes!==void 0&&A!==_.expectedBytes)throw Ge("DOWNLOAD_NETWORK_FAILED","存档下载长度不匹配");return a(w),await S.close(),S=void 0,{committedBytes:A}}catch(M){throw M instanceof DOMException&&M.name==="QuotaExceededError"?Ge("FILE_QUOTA_EXCEEDED","浏览器存储空间不足"):M}finally{await p?.cancel().catch(()=>{}),p||await E.body?.cancel().catch(()=>{}),await S?.abort().catch(()=>{}),s.delete(E)}}}}}}function yt(e,t){throw{code:e,message:t}}function on(e){return JSON.stringify(e,(t,r)=>r&&typeof r=="object"&&!Array.isArray(r)?Object.fromEntries(Object.keys(r).sort().map(n=>[n,r[n]])):r)}function qN(e){return{declaredPermissions:e.declaredPermissions??{},platforms:[...e.platforms??[]].sort(),runtimePermissions:e.runtimePermissions,networkPolicy:e.networkPolicy}}function QN(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(),yt("UNAUTHORIZED","请先通过 hb-sdk login 登录小黑盒"));const{signed:c,browser:d}=a,u=$g(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(),yt("INVALID_STATE","开发启动授权尚未就绪,请检查 CLI 登录、项目绑定及开发票据状态"));let f;try{f=jl({...u,declared_permissions:d.declaredPermissions??{},platforms:d.platforms??[]})}catch{}(d.source!=="remote"||d.miniProgramId!==c.miniProgramId||d.devSessionId!==u.session_id||c.devSessionId!==u.session_id||c.contextRevision!==u.revision||f!==c.developmentSnapshot||on(d.runtimePermissions)!==on(c.runtimePermissions)||on(d.networkPolicy)!==on(c.networkPolicy))&&(i(),yt("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:on([a.userId,a.accountRevision,l,d.contextRevision,qN(d)]),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(E){d.throwIfAborted();const _=E&&typeof E=="object"&&"code"in E?String(E.code):"";if(["SESSION_UNAUTHENTICATED","SESSION_INVALIDATED","UNAUTHORIZED"].includes(_)&&yt("UNAUTHORIZED","小黑盒登录已失效,请重新登录"),["REQUEST_CANCELLED","REQUEST_TIMEOUT"].includes(_)||E instanceof DOMException&&["AbortError","TimeoutError"].includes(E.name))throw E;yt("REQUEST_FAILED","获取开发运行授权失败,请稍后重试")}d.throwIfAborted(),await e.refreshAccount(d),d.throwIfAborted(),o().key!==a.key&&yt("AUTHORIZATION_CONTEXT_CHANGED","账号或开发快照已变化,请重试");const f=u.data;(u.status===401||f?.status==="login"||f?.status==="relogin")&&yt("UNAUTHORIZED","小黑盒登录已失效,请重新登录"),(u.status!==200||f?.status!=="ok")&&yt("REQUEST_FAILED","获取开发运行授权失败,请检查开发资格后重试");const l=f.result,h=Number(l?.expires_at)*1e3;(typeof l?.token!="string"||!l.token.trim()||!Number.isSafeInteger(l?.expires_at)||!Number.isSafeInteger(h)||h<=t()||!["legacy","local","server"].includes(String(l.user_data_mode)))&&yt("INVALID_RESPONSE","开发运行授权响应无效");const m={token:l.token,expiresAt:Math.min(h,a.expiresAt),steamAccount:l.steam_account===!0,userDataMode:l.user_data_mode};return r={key:a.key,value:m},m}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 l=new AbortController,h=s(d,{...a,signal:AbortSignal.any([l.signal,e.signal])});u={promise:h,controller:l,users:0},n.set(d.key,u);const m=u;h.finally(()=>{n.get(d.key)===m&&n.delete(d.key)}).catch(()=>{})}u.users++;let f;try{const l=await Promise.race([u.promise,new Promise((h,m)=>{f=()=>m(c.reason),c.addEventListener("abort",f,{once:!0}),c.aborted&&f()})]);return c.throwIfAborted(),o().key!==d.key&&yt("AUTHORIZATION_CONTEXT_CHANGED","账号或开发快照已变化,请重试"),l}finally{c.removeEventListener("abort",f),--u.users===0&&u.controller.abort()}}}}const YN="/__hb_sdk__/dev-context";function Fu(e,t){return On(e)&&(e.source==="remote"||e.source==="anonymous")?{source:e.source,miniProgramId:typeof e.miniProgramId=="string"?e.miniProgramId:void 0,developmentSnapshot:typeof e.developmentSnapshot=="string"?e.developmentSnapshot:void 0,developmentSnapshotDigest:typeof e.developmentSnapshotDigest=="string"?e.developmentSnapshotDigest:void 0,localDevLaunchToken:typeof e.localDevLaunchToken=="string"?e.localDevLaunchToken:void 0,runtimePermissions:e.runtimePermissions,networkPolicy:e.networkPolicy,...e.source==="remote"&&e.firstParty===!0?{firstParty:!0}:{},publishedRuntimePermissions:e.publishedRuntimePermissions,warning:typeof e.warning=="string"?e.warning:void 0,declaredPermissions:On(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 fn(e,t=Date.now()){if(e.localDevGrant===void 0)return e;const r=Tl(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:tg({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 WN(e){if(!On(e)||!Vu(e,["networkRequest"]))return;const t=e.networkRequest;if(!(!On(t)||!Vu(t,["status","useOfficialDomain"]))&&!(t.status!=="enabled"&&t.status!=="disabled")&&typeof t.useOfficialDomain=="boolean")return{networkRequest:{status:t.status,useOfficialDomain:t.useOfficialDomain}}}const ZN={networkRequest:{status:"disabled",useOfficialDomain:!1}};function Bo(e){const t=qe(e.localDevGrant?Va({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}}:JN()}function gh(e,t,r){return r?.localDevGrant?Va({declaredPermissions:r.declaredPermissions??{},runtimePermissions:e,localDevGrant:r.localDevGrant}).runtimePermissions:ph(e,t,t.networkRequest.useOfficialDomain)}function KN(e){if(e.source!=="remote")return{schema_version:1,entries:[]};const t=Bo({...e,localDevGrant:void 0});return ph(e.runtimePermissions,t,!1)}function JN(){return{networkRequest:{...ZN.networkRequest}}}function ph(e,t,r){const n=qe(e);if(!n.valid)return{schema_version:1,entries:[]};const i=[];for(const s of sr){const a=n.permissions[s];a&&i.push(s==="network"?{key:s,status:t.networkRequest.status,config:{useOfficialDomain:r}}:s==="user_game_data"?{key:s,status:a.status,config:{resources:a.config.resources}}:{key:s,status:a.status,config:{}})}const o=On(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 On(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&Object.getPrototypeOf(e)===Object.prototype}function Vu(e,t){return Object.keys(e).length===t.length&&t.every(n=>Object.hasOwn(e,n))}function XN(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(f){a={ok:!1},!n&&!c.signal.aborted&&s(f);continue}finally{t===c&&(t=void 0)}if(n)return{ok:!1};let u;try{u=e.apply(d)}catch(f){a={ok:!1},n||s(f);continue}if(n)return{ok:!1};if(a={ok:!0},!!e.hasChanged(u))try{await e.onChanged(u)}catch(f){a={ok:!1},n||s(f)}}return n?{ok:!1}:a}function s(a){try{e.onError(a)}catch{}}}function eM(e){return XN({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 tM(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 xs=new WeakMap;function dc(e){return new Promise((t,r)=>{if(e.signal?.aborted){r(e.signal.reason);return}const{root:n,signal:i}=e;xs.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",l);const m=s()===n;if(n.remove(),m){const E=s();E&&(E.inert=!1,E.removeAttribute("aria-hidden"));let _=xs.get(n)??null;for(;_ instanceof HTMLElement&&!_.isConnected;){const w=_.closest("[data-host-dialog]");_=w?xs.get(w)??null:null}_ instanceof HTMLElement&&(!E||E.contains(_))?_.focus():E?.querySelector("button")?.focus()}},d=Yh({kind:"dialog",mode:e.mode??"simulated",title:e.title,method:e.method,...e.callId?{callId:e.callId}:{},actions:o.map(m=>m.textContent?.trim()??"")},m=>{c(),a!==void 0?t(a):r(i?.reason??new DOMException(`宿主弹窗已${m}`,"AbortError"))});function u(){d.finish("cancelled")}function f(m){a=m,d.finish(m===e.cancelAction?"cancelled":"confirmed")}function l(m){if(s()!==n||(m.key==="Escape"&&e.cancelAction&&(m.preventDefault(),f(e.cancelAction)),m.key!=="Tab"||o.length===0))return;const E=o[0],_=o.at(-1);m.shiftKey&&document.activeElement===E?(m.preventDefault(),_.focus()):!m.shiftKey&&document.activeElement===_&&(m.preventDefault(),E.focus())}if(!d.active)return;if(i?.aborted){u();return}for(const m of o)m.addEventListener("click",()=>f(m.dataset.action));n.addEventListener("click",m=>{m.target===n&&e.cancelAction&&f(e.cancelAction)}),n.dataset.interactionId=d.interactionId;const h=s();h&&(h.inert=!0,h.setAttribute("aria-hidden","true")),(document.querySelector("#host-overlay-layer")??document.body).appendChild(n),i?.addEventListener("abort",u,{once:!0}),document.addEventListener("keydown",l),o[0]?.focus(),i?.aborted&&u()})}function et(e){return e.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&#039;")}const Gu="hb-sdk-action-dialog-style";async function Ho(e){await yh(e)}async function rM(e){return await yh({title:"关注作者",detail:"是否关注当前小程序的作者?",signal:e.signal,method:"user.requestFollowAuthor",mode:"browser",confirmation:!0})?"confirmed":"cancelled"}async function yh(e){aM();const t=document.createElement("div");return t.className="hb-sdk-action-dialog",t.innerHTML=`
17
17
  <div class="hb-sdk-action-dialog__panel">
18
18
  <h2>${et(e.title)}</h2>
19
19
  <pre class="hb-sdk-action-dialog__detail">${et(e.detail)}</pre>
@@ -92,7 +92,7 @@ Minimum version required to store current data is: `+x+`.
92
92
  <button type="button" class="primary" data-action="allow">允许</button>
93
93
  </div>
94
94
  </div>
95
- `,await dc({root:t,title:"授权请求",method:"auth.authorize",mode:"browser",signal:e.signal,cancelAction:"deny"})==="allow"?{status:"granted",grantedScopes:[...e.scopes]}:{status:"cancelled"}}function uM(e){const t=e.miniProgramName?.trim();return{launchUrl:e.launchUrl,...e.locationBasePath!==void 0?{locationBasePath:e.locationBasePath}:{},...t?{miniProgramPresentation:{name:t}}:{},sdkVersionPolicy:{minimumSdkVersion:"0.5.0",sdkVersion:wc,releaseChannel:"development"},runtimePermissions:e.runtimePermissions,networkPolicy:e.networkPolicy,...e.anonymousStorageScope?{anonymousStorageScope:e.anonymousStorageScope}:{},platformAccess:{source:"manifest",manifest:{platforms:jo},sdkVersion:wc},environmentInfo:{appVersion:null,operatingSystem:{name:e.operatingSystem??"unknown",version:null}},...e.miniProgramId?{canonicalIdentity:{miniProgramId:e.miniProgramId}}:{}}}const $u="hb-sdk-user-data-dialog-style",lM=new Map(tr.map(e=>[e.key,e.name]));function fM(e){return(Pt(e)?lM.get(e):void 0)??"游戏资料"}function hM(e){return e==="upload"?"可上传":"无网络权限"}async function mM(e){pM();const t=e.miniProgramName?.trim()||"当前小程序",r=fM(e.resource),n=`“${t}”想读取你的${r}`,i=hM(e.egress),o=lp[e.egress],s=e.egress==="upload"?"↑":"⊘",a=document.createElement("div");a.className="hb-sdk-user-data-dialog",a.innerHTML=`
95
+ `,await dc({root:t,title:"授权请求",method:"auth.authorize",mode:"browser",signal:e.signal,cancelAction:"deny"})==="allow"?{status:"granted",grantedScopes:[...e.scopes]}:{status:"cancelled"}}function uM(e){const t=e.miniProgramName?.trim();return{launchUrl:e.launchUrl,...e.locationBasePath!==void 0?{locationBasePath:e.locationBasePath}:{},...t?{miniProgramPresentation:{name:t}}:{},sdkVersionPolicy:{minimumSdkVersion:"0.5.0",sdkVersion:wc,releaseChannel:"development"},runtimePermissions:e.runtimePermissions,networkPolicy:e.networkPolicy,firstParty:e.firstParty===!0,...e.anonymousStorageScope?{anonymousStorageScope:e.anonymousStorageScope}:{},platformAccess:{source:"manifest",manifest:{platforms:jo},sdkVersion:wc},environmentInfo:{appVersion:null,operatingSystem:{name:e.operatingSystem??"unknown",version:null}},...e.miniProgramId?{canonicalIdentity:{miniProgramId:e.miniProgramId}}:{}}}const $u="hb-sdk-user-data-dialog-style",lM=new Map(tr.map(e=>[e.key,e.name]));function fM(e){return(kt(e)?lM.get(e):void 0)??"游戏资料"}function hM(e){return e==="upload"?"可上传":"无网络权限"}async function mM(e){pM();const t=e.miniProgramName?.trim()||"当前小程序",r=fM(e.resource),n=`“${t}”想读取你的${r}`,i=hM(e.egress),o=lp[e.egress],s=e.egress==="upload"?"↑":"⊘",a=document.createElement("div");a.className="hb-sdk-user-data-dialog",a.innerHTML=`
96
96
  <div class="hb-sdk-user-data-dialog__panel">
97
97
  <h2>${et(n)}</h2>
98
98
  <dl class="hb-sdk-user-data-dialog__meta">
@@ -220,9 +220,9 @@ Minimum version required to store current data is: `+x+`.
220
220
  color: #fff;
221
221
  background: #2563eb;
222
222
  }
223
- `,document.head.appendChild(e)}function yM(e){let t,r,n,i,o,s=0,a=0,c=0,d=!1,u=Promise.resolve();const f=new Set,l=()=>{const w=e.resolveScope();return w?JSON.stringify(w):void 0},h=()=>{if(!d)for(const w of f)w()},m=async()=>{if(d||c)return;const w=t,S=l(),p=++s;if(!w||!S){r=void 0,i=void 0,h();return}try{const M=await w.getSnapshot();if(d||p!==s||t!==w||S!==l())return;r=M,n=S,i=void 0}catch(M){if(d||p!==s||t!==w||S!==l())return;r=void 0,o=S,i=M instanceof Error?M.message:"许可状态不可用"}h()},E=w=>{const S=t,p=l(),M=a;if(d||!S||!p)return Promise.resolve();const z=++s;c++;const A=u.then(async()=>{if(!(d||a!==M||p!==l()))try{const D=await w(S);if(d||z!==s||a!==M||p!==l())return;r=D,n=p,i=void 0}catch(D){if(d||z!==s||a!==M||p!==l())return;r=void 0,o=p,i=D instanceof Error?D.message:"许可设置失败"}}).finally(()=>{a===M&&c--,h()});return u=A,A},_=()=>{a++,s++,c=0,u=Promise.resolve(),t=void 0,r=void 0,i=void 0};return{snapshot(){const w=l(),S=w&&w===n?r:void 0,p=e.declared?.();return{scenario:"unknown",dataScenario:"unknown",egressTier:e.egressTier(),declaredSource:p?.source??"manifest",permissionStateReady:S!==void 0,stateError:w&&w===o?i:void 0,simulatedSession:[],resources:tr.map(M=>{const z=S?.resources.find(D=>D.resource===M.key),A=z?.allowed===!0;return{resource:M.key,name:M.name,declared:p?.resources.includes(M.key)??!1,decision:z?.decision??"ask",revision:z?.revision??0,sessionAllowed:z?.sessionAllowed??!1,sessionSimulated:!1,licensed:A,...A?{sourceStatus:"unknown"}:{}}})}},subscribe(w){return d||f.add(w),()=>f.delete(w)},bind(w){d||(_(),t=w,m())},refresh:m,revokeSession:()=>E(w=>w.revokeSession()),resetAll:()=>E(w=>w.resetAll()),clearSession(){_(),h()},dispose(){d=!0,_(),f.clear()}}}function EM(e){const t="hb_user_game_data_consent_",r="hb_browser_real_user_game_data_consent_",n=i=>i.startsWith(t)?`${r}${i.slice(t.length)}`:i;return{getItem(i){return e.getItem(n(i))},setItem(i,o){e.setItem(n(i),o)},get length(){return e.length},key(i){const o=e.key(i);return o?.startsWith(t)?null:o?.startsWith(r)?`${t}${o.slice(r.length)}`:o}}}function wM(e){const t=qe(e.runtimePermissions);let r={};return t.valid&&t.permissions.user_game_data?.status==="enabled"?r=bn(t.permissions.user_game_data.config.resources):e.runtimePermissions===void 0&&e.declaredPermissions?.user_game_data?.enabled&&(r=bn(e.declaredPermissions.user_game_data.resources)),{resources:Jm(r),source:"manifest"}}const IM=Object.freeze({user_game_data_permission_show:["entry","reason"],user_game_data_permission_result:["choice","apply_result"],user_game_data_permission_manage:["operation","apply_result","succeeded_count","failed_count"],user_game_data_action:["stage","action_type","outcome","duration_ms"],user_game_data_access_result:["api","trigger","status","error_code","failure_stage","duration_ms","cache_hit"]}),AM="host.userDataTelemetry",qu=80;function _M(e){return{method:AM,detail:{...e.payload,eventName:e.name,message:DM(e)}}}function DM(e){const t=IM[e.name]??[],r=[];for(const n of t){const i=e.payload[n];i!==void 0&&r.push(`${n}: ${Eh(i)}`)}return[e.name,...r].join(" · ")}function Eh(e){let t;if(typeof e=="string")t=e;else if(typeof e=="number"||typeof e=="boolean")t=String(e);else if(Array.isArray(e))t=e.map(r=>Eh(r)).join(",");else try{t=JSON.stringify(e)??""}catch{t="[无法序列化]"}return t.length>qu?`${t.slice(0,qu)}…`:t}const NM=44;function MM(e){const t=()=>e.isCapsuleHidden?.()?0:NM,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:Xh,showLoading:Jh,hideLoading:Kh,vibrate:Zh,openAppPage:nM,openWindow:iM,showShareMenu:oM,captureAndShare:sM,setScreenshotChromeHidden:Wh}}const Qu=["launch-only","stdio","full","prepare-fail","prepare-cancel","launch-cancel","os-blocked","normal-exit","crash","output-limit"],ti=[{phase:"downloading",loaded:4,total:12},{phase:"verifying",processed:8,total:12},{phase:"extracting",processed:12,total:12}],Yu={"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 SM{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]:[...Qu];for(const n of r){const i=this.preparations.get(n);for(const o of i?.operation?.timers??[])this.clearSchedule(o);i?.operation?.reject(je("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:Yu[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:ti[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:ti[0]},operation:c};this.preparations.set(n,d),this.diagnostic("prepare.started",n),ti.forEach((u,f)=>{const l=this.schedule(()=>{if(c.timers.delete(l),!c.cancelled){d.status={state:"preparing",progress:u};try{c.listeners.forEach(h=>h(u))}catch(h){c.cancelled=!0;for(const m of c.timers)this.clearSchedule(m);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:h instanceof Error?h.message:String(h)}),c.reject(h);return}if(this.diagnostic("prepare.progress",n,{phase:u.phase}),f===ti.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(je("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)}}},f+1);c.timers.add(l)})}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(je("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(Pm,{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 je("COMPANION_NOT_PREPARED","固定 Fake 尚未准备完成");if(r==="os-blocked")throw je("COMPANION_OS_BLOCKED","操作系统安全策略已阻止启动");const n=this.sessions.get(r);if(n&&!n.exited)throw je("COMPANION_LAUNCH_FAILED","固定 Fake Session 已在运行");const i={id:`browser-fake-${++this.nextSessionId}`,alias:r,target:this.getInfo(r).target,capabilities:Yu[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
223
+ `,document.head.appendChild(e)}function yM(e){let t,r,n,i,o,s=0,a=0,c=0,d=!1,u=Promise.resolve();const f=new Set,l=()=>{const w=e.resolveScope();return w?JSON.stringify(w):void 0},h=()=>{if(!d)for(const w of f)w()},m=async()=>{if(d||c)return;const w=t,S=l(),p=++s;if(!w||!S){r=void 0,i=void 0,h();return}try{const M=await w.getSnapshot();if(d||p!==s||t!==w||S!==l())return;r=M,n=S,i=void 0}catch(M){if(d||p!==s||t!==w||S!==l())return;r=void 0,o=S,i=M instanceof Error?M.message:"许可状态不可用"}h()},E=w=>{const S=t,p=l(),M=a;if(d||!S||!p)return Promise.resolve();const z=++s;c++;const A=u.then(async()=>{if(!(d||a!==M||p!==l()))try{const D=await w(S);if(d||z!==s||a!==M||p!==l())return;r=D,n=p,i=void 0}catch(D){if(d||z!==s||a!==M||p!==l())return;r=void 0,o=p,i=D instanceof Error?D.message:"许可设置失败"}}).finally(()=>{a===M&&c--,h()});return u=A,A},_=()=>{a++,s++,c=0,u=Promise.resolve(),t=void 0,r=void 0,i=void 0};return{snapshot(){const w=l(),S=w&&w===n?r:void 0,p=e.declared?.();return{scenario:"unknown",dataScenario:"unknown",egressTier:e.egressTier(),declaredSource:p?.source??"manifest",permissionStateReady:S!==void 0,stateError:w&&w===o?i:void 0,simulatedSession:[],resources:tr.map(M=>{const z=S?.resources.find(D=>D.resource===M.key),A=z?.allowed===!0;return{resource:M.key,name:M.name,declared:p?.resources.includes(M.key)??!1,decision:z?.decision??"ask",revision:z?.revision??0,sessionAllowed:z?.sessionAllowed??!1,sessionSimulated:!1,licensed:A,...A?{sourceStatus:"unknown"}:{}}})}},subscribe(w){return d||f.add(w),()=>f.delete(w)},bind(w){d||(_(),t=w,m())},refresh:m,revokeSession:()=>E(w=>w.revokeSession()),resetAll:()=>E(w=>w.resetAll()),clearSession(){_(),h()},dispose(){d=!0,_(),f.clear()}}}function EM(e){const t="hb_user_game_data_consent_",r="hb_browser_real_user_game_data_consent_",n=i=>i.startsWith(t)?`${r}${i.slice(t.length)}`:i;return{getItem(i){return e.getItem(n(i))},setItem(i,o){e.setItem(n(i),o)},get length(){return e.length},key(i){const o=e.key(i);return o?.startsWith(t)?null:o?.startsWith(r)?`${t}${o.slice(r.length)}`:o}}}function wM(e){const t=qe(e.runtimePermissions);let r={};return t.valid&&t.permissions.user_game_data?.status==="enabled"?r=bn(t.permissions.user_game_data.config.resources):e.runtimePermissions===void 0&&e.declaredPermissions?.user_game_data?.enabled&&(r=bn(e.declaredPermissions.user_game_data.resources)),{resources:Jm(r),source:"manifest"}}const IM=Object.freeze({user_game_data_permission_show:["entry","reason"],user_game_data_permission_result:["choice","apply_result"],user_game_data_permission_manage:["operation","apply_result","succeeded_count","failed_count"],user_game_data_action:["stage","action_type","outcome","duration_ms"],user_game_data_access_result:["api","trigger","status","error_code","failure_stage","duration_ms","cache_hit"]}),AM="host.userDataTelemetry",qu=80;function _M(e){return{method:AM,detail:{...e.payload,eventName:e.name,message:DM(e)}}}function DM(e){const t=IM[e.name]??[],r=[];for(const n of t){const i=e.payload[n];i!==void 0&&r.push(`${n}: ${Eh(i)}`)}return[e.name,...r].join(" · ")}function Eh(e){let t;if(typeof e=="string")t=e;else if(typeof e=="number"||typeof e=="boolean")t=String(e);else if(Array.isArray(e))t=e.map(r=>Eh(r)).join(",");else try{t=JSON.stringify(e)??""}catch{t="[无法序列化]"}return t.length>qu?`${t.slice(0,qu)}…`:t}const NM=44;function MM(e){const t=()=>e.isCapsuleHidden?.()?0:NM,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:Xh,showLoading:Jh,hideLoading:Kh,vibrate:Zh,openAppPage:nM,openWindow:iM,showShareMenu:oM,captureAndShare:sM,setScreenshotChromeHidden:Wh}}const Qu=["launch-only","stdio","full","prepare-fail","prepare-cancel","launch-cancel","os-blocked","normal-exit","crash","output-limit"],ti=[{phase:"downloading",loaded:4,total:12},{phase:"verifying",processed:8,total:12},{phase:"extracting",processed:12,total:12}],Yu={"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 SM{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]:[...Qu];for(const n of r){const i=this.preparations.get(n);for(const o of i?.operation?.timers??[])this.clearSchedule(o);i?.operation?.reject(je("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:Yu[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:ti[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:ti[0]},operation:c};this.preparations.set(n,d),this.diagnostic("prepare.started",n),ti.forEach((u,f)=>{const l=this.schedule(()=>{if(c.timers.delete(l),!c.cancelled){d.status={state:"preparing",progress:u};try{c.listeners.forEach(h=>h(u))}catch(h){c.cancelled=!0;for(const m of c.timers)this.clearSchedule(m);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:h instanceof Error?h.message:String(h)}),c.reject(h);return}if(this.diagnostic("prepare.progress",n,{phase:u.phase}),f===ti.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(je("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)}}},f+1);c.timers.add(l)})}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(je("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(km,{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 je("COMPANION_NOT_PREPARED","固定 Fake 尚未准备完成");if(r==="os-blocked")throw je("COMPANION_OS_BLOCKED","操作系统安全策略已阻止启动");const n=this.sessions.get(r);if(n&&!n.exited)throw je("COMPANION_LAUNCH_FAILED","固定 Fake Session 已在运行");const i={id:`browser-fake-${++this.nextSessionId}`,alias:r,target:this.getInfo(r).target,capabilities:Yu[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
224
224
  `),this.queueOutput(o,"stderr",1,`fake:diagnostic
225
225
  `)},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 je("COMPANION_PIPE_CLOSED","stdio 未启用");if(r.stdinClosed)throw je("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 je("COMPANION_ATTACHMENT_NOT_FOUND","attachments 未启用");if(t.id!=="report")throw je("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
226
- `);return{kind:"file",name:"browser-fake-report.txt",mode:"read",create:async()=>{throw je("FILE_ACCESS_DENIED","Attachment 只读")},read:async()=>new Uint8Array(n),write:async()=>{throw je("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 je("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(Rm,{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(km,{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 je("COMPANION_SESSION_EXITED","固定 Fake Session 不存在");if(r.snapshot.controllerGeneration!==t.controllerGeneration)throw je("COMPANION_SESSION_OWNERSHIP_LOST","固定 Fake Session 控制权已转移");return r}readAlias(t){if(!Qu.includes(t))throw je("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 bM=Object.freeze({[wo]:!0,[Io]:!0,[Ao]:!0,[_o]:!0,[Do]:!0,[No]:!0,[Mo]:!0,[So]:!0,[bo]:!0,[To]:!0,[vo]:!0,[Oo]:!0,[Dn]:!0,[_n]:!0,[Nn]:!0});function TM(e){return new SM(e)}function je(e,t){return Object.assign(new Error(t),{code:e})}const vM=/^[A-Za-z0-9_-]{22}$/,OM="https://api.xiaoheihe.cn/open_inapp/";function RM(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(!vM.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 kM(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`${OM}#${r}`}function PM(e={}){const t=e.source??jM(e.document??document),r=e.readMetadata??BM,n=e.createPreviewUrl??(d=>URL.createObjectURL(d)),i=e.revokePreviewUrl??(d=>URL.revokeObjectURL(d)),o=new WeakMap,s=new Set,a=d=>{if(!(!d||!s.has(d))){s.delete(d);try{i(d)}catch{}}},c=()=>{for(const d of[...s])a(d)};return e.signal?.addEventListener("abort",c,{once:!0}),{async pick(d,u){switch(dn(u.signal),e.getMode?.()??"normal"){case"cancel":throw ve("MEDIA_PICKER_CANCELLED","用户取消了媒体选择");case"system-permission-denied":throw ve("MEDIA_SYSTEM_PERMISSION_DENIED","系统未授予相机或相册权限");case"prepare-failure":throw ve("MEDIA_PREPARE_FAILED","媒体准备失败,未保留部分结果");case"preview-unavailable":throw ve("MEDIA_PREVIEW_UNAVAILABLE","当前 Host 无法提供受控媒体预览")}const f=d.source==="camera"?[await t.capture({mediaType:d.mediaType})]:await CM(t,d);if(dn(u.signal),d.source==="camera"&&f.length!==1)throw ve("MEDIA_PREPARE_FAILED","相机模拟必须恰好返回 1 项");const l=[];try{for(const h of f)dn(u.signal),l.push(await UM(h,d,u.signal,r,n,o,s));dn(u.signal)}catch(h){for(const m of l)a(o.get(m.file));throw h}return l},release(d){for(const u of d)a(o.get(u.file))}}}async function CM(e,t){const r=await e.pickAlbum({accept:LM(t.mediaType),maxCount:t.maxCount,multiple:t.maxCount>1});if(!r||r.length===0)throw ve("MEDIA_PICKER_CANCELLED","用户取消了媒体选择");if(r.length>t.maxCount)throw ve("MEDIA_PREPARE_FAILED",`本次选择 ${r.length} 项,超过 maxCount ${t.maxCount}`);return r}function LM(e){switch(e){case"image":return"image/*";case"video":return"video/*";default:return"image/*,video/*"}}async function UM(e,t,r,n,i,o,s){const a=xM(e.type);if(!a)throw ve("MEDIA_PREPARE_FAILED",`浏览器未提供可识别的媒体类型: ${e.name}`);if(t.mediaType!=="all"&&t.mediaType!==a)throw ve("MEDIA_PREPARE_FAILED",`所选媒体 ${e.name} 与 mediaType 不匹配`);const c=await n(e);dn(r);const d=Wu(c.width),u=Wu(c.height);if(d===void 0||u===void 0)throw ve("MEDIA_PREPARE_FAILED",`无法读取 ${e.name} 的显示尺寸`);if(a==="video"){if(Zu(c.durationMs)===void 0)throw ve("MEDIA_PREPARE_FAILED",`无法读取 ${e.name} 的视频时长`)}else if(c.durationMs!==void 0)throw ve("MEDIA_PREPARE_FAILED",`图片 ${e.name} 不应携带视频时长`);const f=i(e);if(!f)throw ve("MEDIA_PREVIEW_UNAVAILABLE","无法提供受控媒体预览");const l=zM(e);o.set(l,f),s.add(f);const h={type:a,mimeType:e.type,size:e.size,width:d,height:u,previewUrl:f,file:l};return a==="video"?{...h,durationMs:Zu(c.durationMs)}:h}function xM(e){if(e.startsWith("image/"))return"image";if(e.startsWith("video/"))return"video"}function zM(e){const t=()=>Promise.reject(Object.assign(new Error("Browser Dev Host 媒体句柄只读"),{code:"FILE_ACCESS_DENIED"}));return{kind:"file",name:e.name,mode:"read",create:t,read:async()=>new Uint8Array(await e.arrayBuffer()),write:t,stat:async()=>({kind:"file",size:e.size,...e.lastModified?{modifiedAt:e.lastModified}:{}})}}function jM(e=document){return{pickAlbum(t){return new Promise(r=>{const n=e.createElement("input");n.type="file",n.accept=t.accept,n.multiple=t.multiple,n.style.display="none";let i=!1;const o=()=>{n.removeEventListener("change",a),n.removeEventListener("cancel",c),n.remove()},s=d=>{i||(i=!0,o(),r(d))},a=()=>s(n.files?Array.from(n.files):[]),c=()=>s(void 0);n.addEventListener("change",a),n.addEventListener("cancel",c),e.body.append(n),n.click()})},capture(t){return t.mediaType==="video"?$M():GM()}}}async function BM(e){return e.type.startsWith("video/")?FM(e):HM(e)}async function HM(e){if(typeof globalThis.createImageBitmap=="function"){const r=await globalThis.createImageBitmap(e),n={width:r.width,height:r.height};return r.close?.(),n}const t=URL.createObjectURL(e);try{const r=new Image;return await new Promise((n,i)=>{r.onload=()=>n(),r.onerror=()=>i(ve("MEDIA_PREPARE_FAILED","无法解码所选图片")),r.src=t}),{width:r.naturalWidth,height:r.naturalHeight}}finally{URL.revokeObjectURL(t)}}async function FM(e){const t=URL.createObjectURL(e),r=document.createElement("video");r.preload="metadata";try{await new Promise((i,o)=>{r.onloadedmetadata=()=>i(),r.onerror=()=>o(ve("MEDIA_PREPARE_FAILED","无法读取所选视频元数据")),r.src=t});let n=r.duration;return Number.isFinite(n)||(n=await VM(r)),{width:r.videoWidth,height:r.videoHeight,durationMs:Number.isFinite(n)?Math.max(0,Math.round(n*1e3)):0}}finally{r.removeAttribute("src"),URL.revokeObjectURL(t)}}function VM(e){return new Promise(t=>{const r=()=>{e.removeEventListener("durationchange",r),e.removeEventListener("timeupdate",r),t(e.duration)};e.addEventListener("durationchange",r),e.addEventListener("timeupdate",r),e.currentTime=1e101})}async function GM(){const e=document.createElement("canvas");e.width=640,e.height=480;const t=e.getContext("2d");if(!t)throw ve("MEDIA_PREPARE_FAILED","当前浏览器不支持 2D 画布");const r=t.createLinearGradient(0,0,e.width,e.height);r.addColorStop(0,"#2b2b3a"),r.addColorStop(1,"#0f7b6c"),t.fillStyle=r,t.fillRect(0,0,e.width,e.height),t.fillStyle="#ffffff",t.font="28px sans-serif",t.fillText("Browser Dev Host 模拟拍摄",40,e.height/2);const n=await new Promise(i=>e.toBlob(i,"image/png"));if(!n)throw ve("MEDIA_PREPARE_FAILED","无法生成测试图片");return new File([n],"browser-dev-camera.png",{type:"image/png"})}async function $M(){const e=document.createElement("canvas");e.width=320,e.height=240;const t=e.getContext("2d");if(!t)throw ve("MEDIA_PREPARE_FAILED","当前浏览器不支持 2D 画布");const r=e.captureStream?.bind(e),n=globalThis.MediaRecorder;if(!r||!n)throw ve("MEDIA_PREPARE_FAILED","当前浏览器不支持 MediaRecorder 视频模拟");const i=r.call(e,12),o=new n(i,{mimeType:qM(n)}),s=[],a=new Promise((u,f)=>{o.ondataavailable=l=>{l.data.size>0&&s.push(l.data)},o.onstop=()=>u(),o.onerror=()=>f(ve("MEDIA_PREPARE_FAILED","模拟拍摄录制失败"))});o.start();const c=Date.now();await QM(t,e,()=>Date.now()-c<900),o.stop(),await a;for(const u of i.getTracks())u.stop();const d=new Blob(s,{type:o.mimeType||"video/webm"});if(d.size===0)throw ve("MEDIA_PREPARE_FAILED","模拟拍摄未生成视频数据");return new File([d],"browser-dev-camera.webm",{type:d.type})}function qM(e){for(const t of["video/webm;codecs=vp8","video/webm","video/mp4"])if(e.isTypeSupported?.(t))return t;return"video/webm"}async function QM(e,t,r){for(;r();){const n=Math.min(1,Date.now()%900/900);e.fillStyle="#101820",e.fillRect(0,0,t.width,t.height),e.fillStyle=`rgb(${Math.round(40+n*180)}, 120, ${Math.round(200-n*120)})`,e.fillRect(0,t.height*(1-n),t.width,8),e.fillStyle="#ffffff",e.font="18px sans-serif",e.fillText("模拟拍摄中",24,t.height/2),await new Promise(i=>setTimeout(i,60))}}function dn(e){if(e.aborted){const t=new Error("Browser Dev Host 媒体选择已取消");throw t.name="AbortError",t}}function ve(e,t){const r=new Error(t);return r.name="BrowserDevMediaError",r.code=e,r}function Wu(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>0?e:void 0}function Zu(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0?e:void 0}function YM(e){const t=qe(e.runtimePermissions),r=Va({declaredPermissions:e.declaredPermissions??{},runtimePermissions:e.runtimePermissions,localDevGrant:e.localDevGrant}),n=[],i=qe(e.publishedRuntimePermissions),o=qe(r.runtimePermissions);for(const s of Fa){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(f=>f===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 Kt(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 Ku="__hb_sdk_mini_dev_console_installed__",WM=["log","debug","info","warn","error"];function ZM(e,t=console){if(t[Ku])return;let r=!1;for(const n of WM){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[Ku]=!0)}const fa=1,Ju=64*1024,KM=64,JM=/^[A-Za-z0-9_-]{22}$/;class Ke extends TypeError{code;constructor(t,r){super(r),this.name="BrowserDevHostChannelError",this.code=t}}function XM(e,t=!1){const r=tS(e,t);switch(ha(r,"Server message"),rS(r),r.type){case"grant":return hn(r,["version","type","connectionEpoch","nextClientSequence","nextServerSequence","snapshot"],"grant"),mn(r.connectionEpoch,"connectionEpoch"),Jt(r.nextClientSequence,"nextClientSequence"),Jt(r.nextServerSequence,"nextServerSequence"),Xu(r.snapshot),r;case"event":return hn(r,["version","type","connectionEpoch","sequence","event","snapshot"],"event"),mn(r.connectionEpoch,"connectionEpoch"),Jt(r.sequence,"sequence"),r.event!=="account.changed"&&r.event!=="status.changed"&&Ht("event must be account.changed or status.changed"),Xu(r.snapshot),r;case"heartbeat":return hn(r,["version","type","connectionEpoch","sequence"],"heartbeat"),mn(r.connectionEpoch,"connectionEpoch"),Jt(r.sequence,"sequence"),r;default:return Ht("Unknown server message type")}}function eS(e){const t=e.connectionEpoch;mn(t,"connectionEpoch"),Jt(e.nextSequence,"nextSequence");let r=e.nextSequence;return{get nextSequence(){return r},accept(n){if(mn(n.connectionEpoch,"connectionEpoch"),Jt(n.sequence,"sequence"),n.connectionEpoch!==t)throw new Ke("INVALID_SEQUENCE","Connection epoch does not match");if(r===void 0)throw new Ke("INVALID_SEQUENCE","Sequence is exhausted");if(n.sequence!==r)throw new Ke("INVALID_SEQUENCE",`Expected sequence ${r}`);r=r===Number.MAX_SAFE_INTEGER?void 0:r+1}}}function tS(e,t){if(t)throw new Ke("BINARY_FRAME","Binary frames are not supported");if(typeof e!="string")throw new Ke("TEXT_FRAME_REQUIRED","Channel frame must be text");if(e.length>Ju)throw new Ke("TEXT_FRAME_TOO_LARGE","Channel text frame exceeds 64 KiB");if(new TextEncoder().encode(e).byteLength>Ju)throw new Ke("TEXT_FRAME_TOO_LARGE","Channel text frame exceeds 64 KiB");try{return nS(e),JSON.parse(e)}catch(r){throw r instanceof Ke?r:new Ke("INVALID_JSON","Channel frame must contain strict JSON")}}function Xu(e){ha(e,"snapshot"),hn(e,["account","permissions"],"snapshot"),ha(e.account,"snapshot.account"),hn(e.account,["revision"],"snapshot.account"),Jt(e.account.revision,"snapshot.account.revision"),WN(e.permissions)||Ht("snapshot.permissions is invalid")}function rS(e){e.version!==fa&&Ht("version must be 1")}function ha(e,t){(typeof e!="object"||e===null||Array.isArray(e)||Object.getPrototypeOf(e)!==Object.prototype)&&Ht(`${t} must be a plain JSON object`)}function hn(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 Jt(e,t){(typeof e!="number"||!Number.isSafeInteger(e)||e<0)&&Ht(`${t} must be a non-negative safe integer`)}function mn(e,t){(typeof e!="string"||!JM.test(e))&&Ht(`${t} must be a 22-character base64url value`)}function Ht(e){throw new Ke("INVALID_MESSAGE",e)}function nS(e){new iS(e).scan()}class iS{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>=KM)throw new Ke("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 Ke("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 el=[1e3,2e3,4e3,8e3,15e3];function oS(e){const t=new Set,r=e.webSocketFactory??(T=>new WebSocket(T)),n=e.randomValues??(T=>crypto.getRandomValues(T)),i=e.timers??{clearTimeout:T=>window.clearTimeout(T),setTimeout:(T,x)=>window.setTimeout(T,x)},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,f=!1,l=0,h,m=!1,E=!1;const _=new Set,w=(T,x)=>{if(!(!e.onDiagnostic||_.has(T))){_.add(T);try{e.onDiagnostic({phase:T,...x?{code:x}:{}})}catch{}}},S=(T,x,N=!1)=>{if(u&&T.account.revision<u.account.revision)return;const b=u&&JSON.stringify(T)===JSON.stringify(u);if(u=T,!(b&&!N))for(const O of t)O(T,x)},p=()=>{if(f||h!==void 0||c)return;const T=el[Math.min(l,el.length-1)];l+=1,h=i.setTimeout(()=>{h=void 0,v()},T)},M=()=>{f||!m||c||(h!==void 0&&(i.clearTimeout(h),h=void 0),v())},z=()=>{a()&&M()},A=()=>{s&&!s.hidden&&M()},D=()=>{E||(E=!0,o?.addEventListener("online",z),s?.addEventListener("visibilitychange",A))},I=()=>{E&&(E=!1,o?.removeEventListener("online",z),s?.removeEventListener("visibilitychange",A))},v=()=>{if(f||c)return;m=!0,D(),h!==void 0&&(i.clearTimeout(h),h=void 0);let T,x;try{T=r(e.url)}catch{w("constructor","WEBSOCKET_CONSTRUCTION_FAILED"),p();return}try{x=aS(n)}catch{w("entropy","NONCE_GENERATION_FAILED");try{T?.close(1011,"channel initialization failed")}catch{}p();return}c=T;let N,b,O;const j=()=>{T.removeEventListener("open",L),T.removeEventListener("message",C),T.removeEventListener("close",H),T.removeEventListener("error",F),d===j&&(d=void 0)},U=()=>{if(c===T){c=void 0,j();try{T.close(1008,"invalid channel state")}catch{}p()}},L=()=>{if(!(f||c!==T))try{T.send(JSON.stringify({version:fa,type:"hello",csrfToken:e.csrfToken,clientNonce:x}))}catch{w("send","HELLO_SEND_FAILED"),U()}},C=$=>{if(f||c!==T)return;if(typeof $.data!="string"){w("parse","TEXT_FRAME_REQUIRED"),U();return}let K;try{K=XM($.data)}catch(g){w("parse",g instanceof Ke?g.code:"INVALID_MESSAGE"),U();return}if(K.type==="grant"){if(O){w("sequence","DUPLICATE_GRANT"),U();return}N=K.connectionEpoch,b=K.nextClientSequence,O=eS({connectionEpoch:N,nextSequence:K.nextServerSequence}),l=0,_.clear(),S(K.snapshot,{type:"grant"});return}if(!O||!N||b===void 0){w("sequence","MESSAGE_BEFORE_GRANT"),U();return}try{O.accept(K)}catch{w("sequence","INVALID_SEQUENCE"),U();return}if(K.type==="heartbeat"){try{T.send(JSON.stringify({version:fa,type:"heartbeat.ack",connectionEpoch:N,sequence:b}))}catch{w("send","HEARTBEAT_ACK_SEND_FAILED"),U()}b=b===Number.MAX_SAFE_INTEGER?void 0:b+1;return}S(K.snapshot,{type:"event",event:K.event},!0)},H=()=>{c===T&&(w("close","SOCKET_CLOSED"),c=void 0,j(),p())},F=()=>{w("open","SOCKET_ERROR"),U()};T.addEventListener("open",L),T.addEventListener("message",C),T.addEventListener("close",H),T.addEventListener("error",F),d=j};return{connect:v,subscribeUpdates(T){return t.add(T),()=>t.delete(T)},dispose(){if(f)return;f=!0,m=!1,I(),h!==void 0&&i.clearTimeout(h),h=void 0;const T=c;c=void 0,d?.(),T?.close(1e3,"client disposed"),t.clear()}}}function sS(e){const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";let r="";for(let n=0;n<e.length;n+=3){const i=e[n]??0,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 aS(e){const t=e(new Uint8Array(16));if(!(t instanceof Uint8Array)||t.byteLength!==16)throw new TypeError("Channel nonce source must fill 16 bytes");const r=sS(t);if(!/^[A-Za-z0-9_-]{22}$/.test(r))throw new TypeError("Channel nonce source returned invalid bytes");return r}let Ae=!1,wh=!1,He;const Ih=new AbortController;try{ZM((e,t)=>{Xt(`console.${e}`,{source:"host",message:t.map(r=>NS(r)).join(" ")},Date.now(),e==="log"||e==="debug"?"log":e)})}catch{}const cS="/__hb_sdk_bootstrap__",dS="/__hb_sdk__/mobile-launch-redirect",uS="/__hb_sdk__/network",lS="/session/status",fS="/session/request",hS="/session/events",tl=320,mS=1e3,gS=1e3,pS=15e3,rl="dark",yS=["windows","macos","linux","unknown"],Ah=new URL(location.href).searchParams,_h=Ah.get("mini_url"),Fe=Ah.get("ui_preview")==="1",be={get device(){return ni("#device")},get mobileLanSelect(){return ni("#mobile-lan-select")},get mobileQrImage(){return ni("#mobile-qr-image")},get mobileQrStatus(){return ni("#mobile-qr-status")}};if(!_h&&!Fe)throw be.device.innerHTML='<div class="error">Missing mini_url query.</div>',new Error("Missing mini_url query.");const Dh=_h??"about:blank",De=await gc(),uc=Fe?void 0:await ct.configure({csrfToken:De.csrfToken??"",diagnosticsToken:De.diagnosticsToken??"",signal:Ih.signal,query:WS,onDropped:e=>{q.diagnosticsDropped=e},onOwnershipLost:Oh});q.diagnosticTargetId=uc?.targetId??"";q.diagnosticOwnerId=uc?.ownerId??"";q.diagnosticTargetName=uc?.metadata.displayName??"";q.openPlatformBaseUrl=De.openPlatformBaseUrl;q.devReadiness=De.devReadiness;q.miniProgramSupportsDesktop=De.miniProgramSupportsDesktop;q.miniProgramPlatforms=De.devContext.platforms??[];q.desktopLaunch.workspaceCardsEnabled=De.workspaceCardsEnabled;al(De.hostPlatform);cl(De.windowForm);let kt=De.lanAddresses,fi=De.defaultLanAddressId,Dr=De.mobileLaunchRedirect,lc=De.nativeAppLaunchUnavailableReason,gn=De.devSessionId,ma=De.miniProgramManifestAccessToken,hi=De.workspaceCardsEnabled,mi=De,fc=Vo(De),Je=De.devContext,br=De.browserDevContext,Ue=fn(br);Eo();let xr=Bo(Ue),Fo=0;const ar=new AbortController;let hc=0,At,ga=0,pa,St=0,Tt=!1,gi,ya,zs=!1;const zr=mm({apply:gm,waitForLayout:async e=>{await Ii(),await fl(e),await hl(e)}});let mc=!1;function js(e){if(e.throwIfAborted(),Ae)throw new Yt("SESSION_CLOSED","调试台已关闭");if(q.diagnosticOwnershipLost)throw new Yt("TARGET_OWNERSHIP_LOST","此调试页已失效,请重新打开预览");if(!mc)throw new Yt("PREVIEW_NOT_READY","调试台正在初始化,请稍后重试");if(Sr)throw new Yt("SESSION_DISCONNECTED","开发服务已断开,请重新启动 dev")}const Ea=fm({observe:()=>{const e=kn()?{width:wi.value.width,height:wi.value.height}:{width:Qs.value.screenWidth,height:Qs.value.screenHeight};return{preset:q.deviceSelectionId,orientation:kn()?e.width>=e.height?"landscape":"portrait":q.display.orientation,runtimeStatus:q.runtimeStatus,viewport:e,instanceId:He?.mounted?He.instanceId:null,browserPixelRatio:window.devicePixelRatio,presentation:ym()}},async selectPreset(e,t){js(t),q.deviceSelectOpen=!1;const r=q.previewMode,n=He;pm(e),await Ii(),t.throwIfAborted(),q.previewMode!==r&&await nl(n,t)},async applyOrientation(e,t){js(t),q.deviceSelectOpen=!1,await zr.applyDisplay({mode:e,hideCapsule:q.display.capsuleHidden},t)},async reload(e){js(e),q.deviceSelectOpen=!1;const t=He;Bt("runtime.restart",{boundary:hc+1}),ur("manual restart").catch(()=>{}),await nl(t,e)},async waitForLayout(e){await Ii(),e.throwIfAborted(),await fl(e),await hl(e)}}),pi=Dm(),Nh={...Ea.bridge,prepareCapture:pi.prepare,restoreCapture:pi.restore,cancel(e){Ea.bridge.cancel(e),pi.cancel(e)}};window.__HB_SDK_PREVIEW__=Nh;async function nl(e,t){for(;;){if(t.throwIfAborted(),Ae)throw new Yt("SESSION_CLOSED","调试台已关闭");if(He!==e&&At===void 0){const r=q.runtimeStatus;if(r==="ready"||Fe&&r==="idle")return;if(r==="error")throw new Yt("RUNTIME_START_FAILED","小程序 Runtime 启动失败,请查看调试日志");if(r==="closed")throw new Yt("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 wa,Ia,Aa,_a,Da,Na,il=Date.now(),Sr=!1,ol=Promise.resolve(),Tr=-1,Rn=!1,vt,Ma,Sa,yi,Qt;const po=new Set,sl="hb-sdk:browser-dev-host:user-data-device";function ES(){try{const e=localStorage.getItem(sl)?.trim();if(e)return e;const t=typeof crypto.randomUUID=="function"?crypto.randomUUID():`mock-${Date.now().toString(36)}`;return localStorage.setItem(sl,t),t}catch{return"browser-mock-device"}}const wS=ES();function IS(){return{miniProgramId:Je.miniProgramId?.trim().toLowerCase()||"anonymous-mini-program",userId:vt?.trim()||"anonymous-user",deviceId:wS,environment:"development"}}function Mh(){return gh(Ue.runtimePermissions,xr,Ue)}function AS(){const e=qe(Mh());return e.valid&&e.permissions.network?.status==="enabled"?"upload":"no_network"}function _S(){return wM({declaredPermissions:Ue.declaredPermissions,runtimePermissions:Mh()})}const _t=yM({resolveScope:IS,egressTier:AS,declared:_S});function jr(){wh&&hm({..._t.snapshot(),targetId:q.diagnosticTargetId,instanceId:He?.instanceId})}_t.subscribe(jr);wh=!0;jr();function Bs(){const e=_t.snapshot().stateError;if(e)throw new Error(e)}em({async refresh(){await _t.refresh(),Bs()},async revokeSession(){await _t.revokeSession(),Bs()},async resetAll(){await _t.resetAll(),Bs()}});const ba=TM({onDiagnostic:({action:e,alias:t,detail:r})=>Bt(`companion.fake.${e}`,{...t?{alias:t}:{},...r})}),Br=eM({applyStatus:e=>Lh(e,!0),fetchStatus:e=>Ch(Vh(ar.signal,e)),getCanonicalRevision:()=>Tr,onError:KS,reconcile:()=>PS(Fo)}),Ta=tM({connectEvents:Uh,invalidate:()=>Br.invalidate(),isDisposed:()=>Ae,maxDelayMs:pS,minDelayMs:gS,timers:{clearTimeout:e=>window.clearTimeout(e),setTimeout:(e,t)=>window.setTimeout(()=>{e()},t)}});let Hs=0,ri="",Fs=!1,va,Oa;function Sh(){Fe||Ae||q.diagnosticOwnershipLost||ct.poll().finally(()=>{!Ae&&!q.diagnosticOwnershipLost&&(Oa=window.setTimeout(Sh,1e3))})}Sh();await yo(!1);jh();Hh(Bh(De));Fe&&SS();Pn();Fe||await Th();DS();bh();zS();await ur("initial");Fe||(Uh(),RS());mc=!0;function bh(){!Fe&&!Ae&&(va=window.setTimeout(()=>{Th().finally(bh)},1e3))}async function Th(){if(!(Fs||Ae)){Fs=!0;try{const e=await fetch(`${Ic}?after=${Hs}&limit=500`,{headers:{"x-hb-sdk-csrf":De.csrfToken??""},signal:AbortSignal.any([ar.signal,AbortSignal.timeout(5e3)])});if(!e.ok){q.diagnosticsStale=!0;return}const t=await e.json();if(Ae)return;if(ri&&t.epoch!==ri){Hs=0,ri=t.epoch,tm();return}ri=t.epoch,q.uploadSessions=t.uploadSessions;const r=await fetch(`${Ic}?mode=inspect`,{headers:{"x-hb-sdk-csrf":De.csrfToken??""},signal:AbortSignal.any([ar.signal,AbortSignal.timeout(5e3)])});if(r.ok){const o=await r.json();q.diagnosticInstances=o.instances,q.diagnosticTargets=o.targets,q.diagnosticPrimaryTargetId=o.primaryTargetId;const s=o.targets.find(a=>a.targetId===q.diagnosticTargetId);s&&(q.diagnosticTargetName=s.metadata.displayName),s&&(s.state==="closed"||s.ownerId!==q.diagnosticOwnerId)&&Oh()}q.diagnosticsStale=!r.ok,q.diagnosticsGap=q.diagnosticsGap||t.gap===!0;const n=new Map(q.diagnosticTargets.map(o=>[o.targetId,o.metadata.displayName])),i=new Map(q.diagnosticInstances.map(o=>[o.instanceId,n.get(o.targetId)]));for(const o of t.items){const s=rm(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,nm(s,o.cursor))}Hs=t.nextCursor}catch{q.diagnosticsStale=!0}finally{Fs=!1}}}function DS(){window.addEventListener("beforeunload",JS),window.addEventListener("hb-sdk:refresh-storage",Pn),window.addEventListener("hb-sdk:qr-open-change",vh),wa=im(()=>document.querySelector("#host-fullscreen-exit-mount")),Ia=Qr(()=>[pn.value,Gs.value,ii.value?.state,ii.value?.stale,ii.value?.capabilities.storage].join("|"),()=>{q.storage=[],q.storageError="",Pn()}),Aa=Qr(()=>q.devicePresetId,()=>zr.notifyViewportChange(),{flush:"post"}),_a=Qr(()=>q.previewMode,()=>{Ot("preview mode changed"),dl(!1),om(!1),Hr("preview mode changed")},{flush:"sync"}),Da=Qr(()=>wi.value,()=>zr.notifyViewportChange(),{flush:"post"}),Na=Qr(()=>q.desktopWindow.closed,(e,t)=>{if(kn()){if(e){Ot("desktop window closed"),q.runtimeStatus="closed";return}t&&q.runtimeStatus==="closed"&&Hr("desktop window reopened")}},{flush:"sync"})}function NS(e){if(typeof e=="string")return e;if(e instanceof Error)return(typeof e.stack=="string"?e.stack.split(`
226
+ `);return{kind:"file",name:"browser-fake-report.txt",mode:"read",create:async()=>{throw je("FILE_ACCESS_DENIED","Attachment 只读")},read:async()=>new Uint8Array(n),write:async()=>{throw je("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 je("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(Rm,{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(Pm,{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 je("COMPANION_SESSION_EXITED","固定 Fake Session 不存在");if(r.snapshot.controllerGeneration!==t.controllerGeneration)throw je("COMPANION_SESSION_OWNERSHIP_LOST","固定 Fake Session 控制权已转移");return r}readAlias(t){if(!Qu.includes(t))throw je("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 bM=Object.freeze({[wo]:!0,[Io]:!0,[Ao]:!0,[_o]:!0,[Do]:!0,[No]:!0,[Mo]:!0,[So]:!0,[bo]:!0,[To]:!0,[vo]:!0,[Oo]:!0,[Dn]:!0,[_n]:!0,[Nn]:!0});function TM(e){return new SM(e)}function je(e,t){return Object.assign(new Error(t),{code:e})}const vM=/^[A-Za-z0-9_-]{22}$/,OM="https://api.xiaoheihe.cn/open_inapp/";function RM(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(!vM.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 PM(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`${OM}#${r}`}function kM(e={}){const t=e.source??jM(e.document??document),r=e.readMetadata??BM,n=e.createPreviewUrl??(d=>URL.createObjectURL(d)),i=e.revokePreviewUrl??(d=>URL.revokeObjectURL(d)),o=new WeakMap,s=new Set,a=d=>{if(!(!d||!s.has(d))){s.delete(d);try{i(d)}catch{}}},c=()=>{for(const d of[...s])a(d)};return e.signal?.addEventListener("abort",c,{once:!0}),{async pick(d,u){switch(dn(u.signal),e.getMode?.()??"normal"){case"cancel":throw ve("MEDIA_PICKER_CANCELLED","用户取消了媒体选择");case"system-permission-denied":throw ve("MEDIA_SYSTEM_PERMISSION_DENIED","系统未授予相机或相册权限");case"prepare-failure":throw ve("MEDIA_PREPARE_FAILED","媒体准备失败,未保留部分结果");case"preview-unavailable":throw ve("MEDIA_PREVIEW_UNAVAILABLE","当前 Host 无法提供受控媒体预览")}const f=d.source==="camera"?[await t.capture({mediaType:d.mediaType})]:await CM(t,d);if(dn(u.signal),d.source==="camera"&&f.length!==1)throw ve("MEDIA_PREPARE_FAILED","相机模拟必须恰好返回 1 项");const l=[];try{for(const h of f)dn(u.signal),l.push(await UM(h,d,u.signal,r,n,o,s));dn(u.signal)}catch(h){for(const m of l)a(o.get(m.file));throw h}return l},release(d){for(const u of d)a(o.get(u.file))}}}async function CM(e,t){const r=await e.pickAlbum({accept:LM(t.mediaType),maxCount:t.maxCount,multiple:t.maxCount>1});if(!r||r.length===0)throw ve("MEDIA_PICKER_CANCELLED","用户取消了媒体选择");if(r.length>t.maxCount)throw ve("MEDIA_PREPARE_FAILED",`本次选择 ${r.length} 项,超过 maxCount ${t.maxCount}`);return r}function LM(e){switch(e){case"image":return"image/*";case"video":return"video/*";default:return"image/*,video/*"}}async function UM(e,t,r,n,i,o,s){const a=xM(e.type);if(!a)throw ve("MEDIA_PREPARE_FAILED",`浏览器未提供可识别的媒体类型: ${e.name}`);if(t.mediaType!=="all"&&t.mediaType!==a)throw ve("MEDIA_PREPARE_FAILED",`所选媒体 ${e.name} 与 mediaType 不匹配`);const c=await n(e);dn(r);const d=Wu(c.width),u=Wu(c.height);if(d===void 0||u===void 0)throw ve("MEDIA_PREPARE_FAILED",`无法读取 ${e.name} 的显示尺寸`);if(a==="video"){if(Zu(c.durationMs)===void 0)throw ve("MEDIA_PREPARE_FAILED",`无法读取 ${e.name} 的视频时长`)}else if(c.durationMs!==void 0)throw ve("MEDIA_PREPARE_FAILED",`图片 ${e.name} 不应携带视频时长`);const f=i(e);if(!f)throw ve("MEDIA_PREVIEW_UNAVAILABLE","无法提供受控媒体预览");const l=zM(e);o.set(l,f),s.add(f);const h={type:a,mimeType:e.type,size:e.size,width:d,height:u,previewUrl:f,file:l};return a==="video"?{...h,durationMs:Zu(c.durationMs)}:h}function xM(e){if(e.startsWith("image/"))return"image";if(e.startsWith("video/"))return"video"}function zM(e){const t=()=>Promise.reject(Object.assign(new Error("Browser Dev Host 媒体句柄只读"),{code:"FILE_ACCESS_DENIED"}));return{kind:"file",name:e.name,mode:"read",create:t,read:async()=>new Uint8Array(await e.arrayBuffer()),write:t,stat:async()=>({kind:"file",size:e.size,...e.lastModified?{modifiedAt:e.lastModified}:{}})}}function jM(e=document){return{pickAlbum(t){return new Promise(r=>{const n=e.createElement("input");n.type="file",n.accept=t.accept,n.multiple=t.multiple,n.style.display="none";let i=!1;const o=()=>{n.removeEventListener("change",a),n.removeEventListener("cancel",c),n.remove()},s=d=>{i||(i=!0,o(),r(d))},a=()=>s(n.files?Array.from(n.files):[]),c=()=>s(void 0);n.addEventListener("change",a),n.addEventListener("cancel",c),e.body.append(n),n.click()})},capture(t){return t.mediaType==="video"?$M():GM()}}}async function BM(e){return e.type.startsWith("video/")?FM(e):HM(e)}async function HM(e){if(typeof globalThis.createImageBitmap=="function"){const r=await globalThis.createImageBitmap(e),n={width:r.width,height:r.height};return r.close?.(),n}const t=URL.createObjectURL(e);try{const r=new Image;return await new Promise((n,i)=>{r.onload=()=>n(),r.onerror=()=>i(ve("MEDIA_PREPARE_FAILED","无法解码所选图片")),r.src=t}),{width:r.naturalWidth,height:r.naturalHeight}}finally{URL.revokeObjectURL(t)}}async function FM(e){const t=URL.createObjectURL(e),r=document.createElement("video");r.preload="metadata";try{await new Promise((i,o)=>{r.onloadedmetadata=()=>i(),r.onerror=()=>o(ve("MEDIA_PREPARE_FAILED","无法读取所选视频元数据")),r.src=t});let n=r.duration;return Number.isFinite(n)||(n=await VM(r)),{width:r.videoWidth,height:r.videoHeight,durationMs:Number.isFinite(n)?Math.max(0,Math.round(n*1e3)):0}}finally{r.removeAttribute("src"),URL.revokeObjectURL(t)}}function VM(e){return new Promise(t=>{const r=()=>{e.removeEventListener("durationchange",r),e.removeEventListener("timeupdate",r),t(e.duration)};e.addEventListener("durationchange",r),e.addEventListener("timeupdate",r),e.currentTime=1e101})}async function GM(){const e=document.createElement("canvas");e.width=640,e.height=480;const t=e.getContext("2d");if(!t)throw ve("MEDIA_PREPARE_FAILED","当前浏览器不支持 2D 画布");const r=t.createLinearGradient(0,0,e.width,e.height);r.addColorStop(0,"#2b2b3a"),r.addColorStop(1,"#0f7b6c"),t.fillStyle=r,t.fillRect(0,0,e.width,e.height),t.fillStyle="#ffffff",t.font="28px sans-serif",t.fillText("Browser Dev Host 模拟拍摄",40,e.height/2);const n=await new Promise(i=>e.toBlob(i,"image/png"));if(!n)throw ve("MEDIA_PREPARE_FAILED","无法生成测试图片");return new File([n],"browser-dev-camera.png",{type:"image/png"})}async function $M(){const e=document.createElement("canvas");e.width=320,e.height=240;const t=e.getContext("2d");if(!t)throw ve("MEDIA_PREPARE_FAILED","当前浏览器不支持 2D 画布");const r=e.captureStream?.bind(e),n=globalThis.MediaRecorder;if(!r||!n)throw ve("MEDIA_PREPARE_FAILED","当前浏览器不支持 MediaRecorder 视频模拟");const i=r.call(e,12),o=new n(i,{mimeType:qM(n)}),s=[],a=new Promise((u,f)=>{o.ondataavailable=l=>{l.data.size>0&&s.push(l.data)},o.onstop=()=>u(),o.onerror=()=>f(ve("MEDIA_PREPARE_FAILED","模拟拍摄录制失败"))});o.start();const c=Date.now();await QM(t,e,()=>Date.now()-c<900),o.stop(),await a;for(const u of i.getTracks())u.stop();const d=new Blob(s,{type:o.mimeType||"video/webm"});if(d.size===0)throw ve("MEDIA_PREPARE_FAILED","模拟拍摄未生成视频数据");return new File([d],"browser-dev-camera.webm",{type:d.type})}function qM(e){for(const t of["video/webm;codecs=vp8","video/webm","video/mp4"])if(e.isTypeSupported?.(t))return t;return"video/webm"}async function QM(e,t,r){for(;r();){const n=Math.min(1,Date.now()%900/900);e.fillStyle="#101820",e.fillRect(0,0,t.width,t.height),e.fillStyle=`rgb(${Math.round(40+n*180)}, 120, ${Math.round(200-n*120)})`,e.fillRect(0,t.height*(1-n),t.width,8),e.fillStyle="#ffffff",e.font="18px sans-serif",e.fillText("模拟拍摄中",24,t.height/2),await new Promise(i=>setTimeout(i,60))}}function dn(e){if(e.aborted){const t=new Error("Browser Dev Host 媒体选择已取消");throw t.name="AbortError",t}}function ve(e,t){const r=new Error(t);return r.name="BrowserDevMediaError",r.code=e,r}function Wu(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>0?e:void 0}function Zu(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0?e:void 0}function YM(e){const t=qe(e.runtimePermissions),r=Va({declaredPermissions:e.declaredPermissions??{},runtimePermissions:e.runtimePermissions,localDevGrant:e.localDevGrant}),n=[],i=qe(e.publishedRuntimePermissions),o=qe(r.runtimePermissions);for(const s of Fa){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(f=>f===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 Kt(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 Ku="__hb_sdk_mini_dev_console_installed__",WM=["log","debug","info","warn","error"];function ZM(e,t=console){if(t[Ku])return;let r=!1;for(const n of WM){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[Ku]=!0)}const fa=1,Ju=64*1024,KM=64,JM=/^[A-Za-z0-9_-]{22}$/;class Ke extends TypeError{code;constructor(t,r){super(r),this.name="BrowserDevHostChannelError",this.code=t}}function XM(e,t=!1){const r=tS(e,t);switch(ha(r,"Server message"),rS(r),r.type){case"grant":return hn(r,["version","type","connectionEpoch","nextClientSequence","nextServerSequence","snapshot"],"grant"),mn(r.connectionEpoch,"connectionEpoch"),Jt(r.nextClientSequence,"nextClientSequence"),Jt(r.nextServerSequence,"nextServerSequence"),Xu(r.snapshot),r;case"event":return hn(r,["version","type","connectionEpoch","sequence","event","snapshot"],"event"),mn(r.connectionEpoch,"connectionEpoch"),Jt(r.sequence,"sequence"),r.event!=="account.changed"&&r.event!=="status.changed"&&Ht("event must be account.changed or status.changed"),Xu(r.snapshot),r;case"heartbeat":return hn(r,["version","type","connectionEpoch","sequence"],"heartbeat"),mn(r.connectionEpoch,"connectionEpoch"),Jt(r.sequence,"sequence"),r;default:return Ht("Unknown server message type")}}function eS(e){const t=e.connectionEpoch;mn(t,"connectionEpoch"),Jt(e.nextSequence,"nextSequence");let r=e.nextSequence;return{get nextSequence(){return r},accept(n){if(mn(n.connectionEpoch,"connectionEpoch"),Jt(n.sequence,"sequence"),n.connectionEpoch!==t)throw new Ke("INVALID_SEQUENCE","Connection epoch does not match");if(r===void 0)throw new Ke("INVALID_SEQUENCE","Sequence is exhausted");if(n.sequence!==r)throw new Ke("INVALID_SEQUENCE",`Expected sequence ${r}`);r=r===Number.MAX_SAFE_INTEGER?void 0:r+1}}}function tS(e,t){if(t)throw new Ke("BINARY_FRAME","Binary frames are not supported");if(typeof e!="string")throw new Ke("TEXT_FRAME_REQUIRED","Channel frame must be text");if(e.length>Ju)throw new Ke("TEXT_FRAME_TOO_LARGE","Channel text frame exceeds 64 KiB");if(new TextEncoder().encode(e).byteLength>Ju)throw new Ke("TEXT_FRAME_TOO_LARGE","Channel text frame exceeds 64 KiB");try{return nS(e),JSON.parse(e)}catch(r){throw r instanceof Ke?r:new Ke("INVALID_JSON","Channel frame must contain strict JSON")}}function Xu(e){ha(e,"snapshot"),hn(e,["account","permissions"],"snapshot"),ha(e.account,"snapshot.account"),hn(e.account,["revision"],"snapshot.account"),Jt(e.account.revision,"snapshot.account.revision"),WN(e.permissions)||Ht("snapshot.permissions is invalid")}function rS(e){e.version!==fa&&Ht("version must be 1")}function ha(e,t){(typeof e!="object"||e===null||Array.isArray(e)||Object.getPrototypeOf(e)!==Object.prototype)&&Ht(`${t} must be a plain JSON object`)}function hn(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 Jt(e,t){(typeof e!="number"||!Number.isSafeInteger(e)||e<0)&&Ht(`${t} must be a non-negative safe integer`)}function mn(e,t){(typeof e!="string"||!JM.test(e))&&Ht(`${t} must be a 22-character base64url value`)}function Ht(e){throw new Ke("INVALID_MESSAGE",e)}function nS(e){new iS(e).scan()}class iS{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>=KM)throw new Ke("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 Ke("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 el=[1e3,2e3,4e3,8e3,15e3];function oS(e){const t=new Set,r=e.webSocketFactory??(T=>new WebSocket(T)),n=e.randomValues??(T=>crypto.getRandomValues(T)),i=e.timers??{clearTimeout:T=>window.clearTimeout(T),setTimeout:(T,x)=>window.setTimeout(T,x)},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,f=!1,l=0,h,m=!1,E=!1;const _=new Set,w=(T,x)=>{if(!(!e.onDiagnostic||_.has(T))){_.add(T);try{e.onDiagnostic({phase:T,...x?{code:x}:{}})}catch{}}},S=(T,x,N=!1)=>{if(u&&T.account.revision<u.account.revision)return;const b=u&&JSON.stringify(T)===JSON.stringify(u);if(u=T,!(b&&!N))for(const O of t)O(T,x)},p=()=>{if(f||h!==void 0||c)return;const T=el[Math.min(l,el.length-1)];l+=1,h=i.setTimeout(()=>{h=void 0,v()},T)},M=()=>{f||!m||c||(h!==void 0&&(i.clearTimeout(h),h=void 0),v())},z=()=>{a()&&M()},A=()=>{s&&!s.hidden&&M()},D=()=>{E||(E=!0,o?.addEventListener("online",z),s?.addEventListener("visibilitychange",A))},I=()=>{E&&(E=!1,o?.removeEventListener("online",z),s?.removeEventListener("visibilitychange",A))},v=()=>{if(f||c)return;m=!0,D(),h!==void 0&&(i.clearTimeout(h),h=void 0);let T,x;try{T=r(e.url)}catch{w("constructor","WEBSOCKET_CONSTRUCTION_FAILED"),p();return}try{x=aS(n)}catch{w("entropy","NONCE_GENERATION_FAILED");try{T?.close(1011,"channel initialization failed")}catch{}p();return}c=T;let N,b,O;const j=()=>{T.removeEventListener("open",L),T.removeEventListener("message",C),T.removeEventListener("close",H),T.removeEventListener("error",F),d===j&&(d=void 0)},U=()=>{if(c===T){c=void 0,j();try{T.close(1008,"invalid channel state")}catch{}p()}},L=()=>{if(!(f||c!==T))try{T.send(JSON.stringify({version:fa,type:"hello",csrfToken:e.csrfToken,clientNonce:x}))}catch{w("send","HELLO_SEND_FAILED"),U()}},C=$=>{if(f||c!==T)return;if(typeof $.data!="string"){w("parse","TEXT_FRAME_REQUIRED"),U();return}let K;try{K=XM($.data)}catch(g){w("parse",g instanceof Ke?g.code:"INVALID_MESSAGE"),U();return}if(K.type==="grant"){if(O){w("sequence","DUPLICATE_GRANT"),U();return}N=K.connectionEpoch,b=K.nextClientSequence,O=eS({connectionEpoch:N,nextSequence:K.nextServerSequence}),l=0,_.clear(),S(K.snapshot,{type:"grant"});return}if(!O||!N||b===void 0){w("sequence","MESSAGE_BEFORE_GRANT"),U();return}try{O.accept(K)}catch{w("sequence","INVALID_SEQUENCE"),U();return}if(K.type==="heartbeat"){try{T.send(JSON.stringify({version:fa,type:"heartbeat.ack",connectionEpoch:N,sequence:b}))}catch{w("send","HEARTBEAT_ACK_SEND_FAILED"),U()}b=b===Number.MAX_SAFE_INTEGER?void 0:b+1;return}S(K.snapshot,{type:"event",event:K.event},!0)},H=()=>{c===T&&(w("close","SOCKET_CLOSED"),c=void 0,j(),p())},F=()=>{w("open","SOCKET_ERROR"),U()};T.addEventListener("open",L),T.addEventListener("message",C),T.addEventListener("close",H),T.addEventListener("error",F),d=j};return{connect:v,subscribeUpdates(T){return t.add(T),()=>t.delete(T)},dispose(){if(f)return;f=!0,m=!1,I(),h!==void 0&&i.clearTimeout(h),h=void 0;const T=c;c=void 0,d?.(),T?.close(1e3,"client disposed"),t.clear()}}}function sS(e){const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";let r="";for(let n=0;n<e.length;n+=3){const i=e[n]??0,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 aS(e){const t=e(new Uint8Array(16));if(!(t instanceof Uint8Array)||t.byteLength!==16)throw new TypeError("Channel nonce source must fill 16 bytes");const r=sS(t);if(!/^[A-Za-z0-9_-]{22}$/.test(r))throw new TypeError("Channel nonce source returned invalid bytes");return r}let Ae=!1,wh=!1,He;const Ih=new AbortController;try{ZM((e,t)=>{Xt(`console.${e}`,{source:"host",message:t.map(r=>NS(r)).join(" ")},Date.now(),e==="log"||e==="debug"?"log":e)})}catch{}const cS="/__hb_sdk_bootstrap__",dS="/__hb_sdk__/mobile-launch-redirect",uS="/__hb_sdk__/network",lS="/session/status",fS="/session/request",hS="/session/events",tl=320,mS=1e3,gS=1e3,pS=15e3,rl="dark",yS=["windows","macos","linux","unknown"],Ah=new URL(location.href).searchParams,_h=Ah.get("mini_url"),Fe=Ah.get("ui_preview")==="1",be={get device(){return ni("#device")},get mobileLanSelect(){return ni("#mobile-lan-select")},get mobileQrImage(){return ni("#mobile-qr-image")},get mobileQrStatus(){return ni("#mobile-qr-status")}};if(!_h&&!Fe)throw be.device.innerHTML='<div class="error">Missing mini_url query.</div>',new Error("Missing mini_url query.");const Dh=_h??"about:blank",De=await gc(),uc=Fe?void 0:await ct.configure({csrfToken:De.csrfToken??"",diagnosticsToken:De.diagnosticsToken??"",signal:Ih.signal,query:WS,onDropped:e=>{q.diagnosticsDropped=e},onOwnershipLost:Oh});q.diagnosticTargetId=uc?.targetId??"";q.diagnosticOwnerId=uc?.ownerId??"";q.diagnosticTargetName=uc?.metadata.displayName??"";q.openPlatformBaseUrl=De.openPlatformBaseUrl;q.devReadiness=De.devReadiness;q.miniProgramSupportsDesktop=De.miniProgramSupportsDesktop;q.miniProgramPlatforms=De.devContext.platforms??[];q.desktopLaunch.workspaceCardsEnabled=De.workspaceCardsEnabled;al(De.hostPlatform);cl(De.windowForm);let Pt=De.lanAddresses,fi=De.defaultLanAddressId,Dr=De.mobileLaunchRedirect,lc=De.nativeAppLaunchUnavailableReason,gn=De.devSessionId,ma=De.miniProgramManifestAccessToken,hi=De.workspaceCardsEnabled,mi=De,fc=Vo(De),Je=De.devContext,br=De.browserDevContext,Ue=fn(br);Eo();let xr=Bo(Ue),Fo=0;const ar=new AbortController;let hc=0,At,ga=0,pa,St=0,Tt=!1,gi,ya,zs=!1;const zr=mm({apply:gm,waitForLayout:async e=>{await Ii(),await fl(e),await hl(e)}});let mc=!1;function js(e){if(e.throwIfAborted(),Ae)throw new Yt("SESSION_CLOSED","调试台已关闭");if(q.diagnosticOwnershipLost)throw new Yt("TARGET_OWNERSHIP_LOST","此调试页已失效,请重新打开预览");if(!mc)throw new Yt("PREVIEW_NOT_READY","调试台正在初始化,请稍后重试");if(Sr)throw new Yt("SESSION_DISCONNECTED","开发服务已断开,请重新启动 dev")}const Ea=fm({observe:()=>{const e=Pn()?{width:wi.value.width,height:wi.value.height}:{width:Qs.value.screenWidth,height:Qs.value.screenHeight};return{preset:q.deviceSelectionId,orientation:Pn()?e.width>=e.height?"landscape":"portrait":q.display.orientation,runtimeStatus:q.runtimeStatus,viewport:e,instanceId:He?.mounted?He.instanceId:null,browserPixelRatio:window.devicePixelRatio,presentation:ym()}},async selectPreset(e,t){js(t),q.deviceSelectOpen=!1;const r=q.previewMode,n=He;pm(e),await Ii(),t.throwIfAborted(),q.previewMode!==r&&await nl(n,t)},async applyOrientation(e,t){js(t),q.deviceSelectOpen=!1,await zr.applyDisplay({mode:e,hideCapsule:q.display.capsuleHidden},t)},async reload(e){js(e),q.deviceSelectOpen=!1;const t=He;Bt("runtime.restart",{boundary:hc+1}),ur("manual restart").catch(()=>{}),await nl(t,e)},async waitForLayout(e){await Ii(),e.throwIfAborted(),await fl(e),await hl(e)}}),pi=Dm(),Nh={...Ea.bridge,prepareCapture:pi.prepare,restoreCapture:pi.restore,cancel(e){Ea.bridge.cancel(e),pi.cancel(e)}};window.__HB_SDK_PREVIEW__=Nh;async function nl(e,t){for(;;){if(t.throwIfAborted(),Ae)throw new Yt("SESSION_CLOSED","调试台已关闭");if(He!==e&&At===void 0){const r=q.runtimeStatus;if(r==="ready"||Fe&&r==="idle")return;if(r==="error")throw new Yt("RUNTIME_START_FAILED","小程序 Runtime 启动失败,请查看调试日志");if(r==="closed")throw new Yt("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 wa,Ia,Aa,_a,Da,Na,il=Date.now(),Sr=!1,ol=Promise.resolve(),Tr=-1,Rn=!1,vt,Ma,Sa,yi,Qt;const po=new Set,sl="hb-sdk:browser-dev-host:user-data-device";function ES(){try{const e=localStorage.getItem(sl)?.trim();if(e)return e;const t=typeof crypto.randomUUID=="function"?crypto.randomUUID():`mock-${Date.now().toString(36)}`;return localStorage.setItem(sl,t),t}catch{return"browser-mock-device"}}const wS=ES();function IS(){return{miniProgramId:Je.miniProgramId?.trim().toLowerCase()||"anonymous-mini-program",userId:vt?.trim()||"anonymous-user",deviceId:wS,environment:"development"}}function Mh(){return gh(Ue.runtimePermissions,xr,Ue)}function AS(){const e=qe(Mh());return e.valid&&e.permissions.network?.status==="enabled"?"upload":"no_network"}function _S(){return wM({declaredPermissions:Ue.declaredPermissions,runtimePermissions:Mh()})}const _t=yM({resolveScope:IS,egressTier:AS,declared:_S});function jr(){wh&&hm({..._t.snapshot(),targetId:q.diagnosticTargetId,instanceId:He?.instanceId})}_t.subscribe(jr);wh=!0;jr();function Bs(){const e=_t.snapshot().stateError;if(e)throw new Error(e)}em({async refresh(){await _t.refresh(),Bs()},async revokeSession(){await _t.revokeSession(),Bs()},async resetAll(){await _t.resetAll(),Bs()}});const ba=TM({onDiagnostic:({action:e,alias:t,detail:r})=>Bt(`companion.fake.${e}`,{...t?{alias:t}:{},...r})}),Br=eM({applyStatus:e=>Lh(e,!0),fetchStatus:e=>Ch(Vh(ar.signal,e)),getCanonicalRevision:()=>Tr,onError:KS,reconcile:()=>kS(Fo)}),Ta=tM({connectEvents:Uh,invalidate:()=>Br.invalidate(),isDisposed:()=>Ae,maxDelayMs:pS,minDelayMs:gS,timers:{clearTimeout:e=>window.clearTimeout(e),setTimeout:(e,t)=>window.setTimeout(()=>{e()},t)}});let Hs=0,ri="",Fs=!1,va,Oa;function Sh(){Fe||Ae||q.diagnosticOwnershipLost||ct.poll().finally(()=>{!Ae&&!q.diagnosticOwnershipLost&&(Oa=window.setTimeout(Sh,1e3))})}Sh();await yo(!1);jh();Hh(Bh(De));Fe&&SS();kn();Fe||await Th();DS();bh();zS();await ur("initial");Fe||(Uh(),RS());mc=!0;function bh(){!Fe&&!Ae&&(va=window.setTimeout(()=>{Th().finally(bh)},1e3))}async function Th(){if(!(Fs||Ae)){Fs=!0;try{const e=await fetch(`${Ic}?after=${Hs}&limit=500`,{headers:{"x-hb-sdk-csrf":De.csrfToken??""},signal:AbortSignal.any([ar.signal,AbortSignal.timeout(5e3)])});if(!e.ok){q.diagnosticsStale=!0;return}const t=await e.json();if(Ae)return;if(ri&&t.epoch!==ri){Hs=0,ri=t.epoch,tm();return}ri=t.epoch,q.uploadSessions=t.uploadSessions;const r=await fetch(`${Ic}?mode=inspect`,{headers:{"x-hb-sdk-csrf":De.csrfToken??""},signal:AbortSignal.any([ar.signal,AbortSignal.timeout(5e3)])});if(r.ok){const o=await r.json();q.diagnosticInstances=o.instances,q.diagnosticTargets=o.targets,q.diagnosticPrimaryTargetId=o.primaryTargetId;const s=o.targets.find(a=>a.targetId===q.diagnosticTargetId);s&&(q.diagnosticTargetName=s.metadata.displayName),s&&(s.state==="closed"||s.ownerId!==q.diagnosticOwnerId)&&Oh()}q.diagnosticsStale=!r.ok,q.diagnosticsGap=q.diagnosticsGap||t.gap===!0;const n=new Map(q.diagnosticTargets.map(o=>[o.targetId,o.metadata.displayName])),i=new Map(q.diagnosticInstances.map(o=>[o.instanceId,n.get(o.targetId)]));for(const o of t.items){const s=rm(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,nm(s,o.cursor))}Hs=t.nextCursor}catch{q.diagnosticsStale=!0}finally{Fs=!1}}}function DS(){window.addEventListener("beforeunload",JS),window.addEventListener("hb-sdk:refresh-storage",kn),window.addEventListener("hb-sdk:qr-open-change",vh),wa=im(()=>document.querySelector("#host-fullscreen-exit-mount")),Ia=Qr(()=>[pn.value,Gs.value,ii.value?.state,ii.value?.stale,ii.value?.capabilities.storage].join("|"),()=>{q.storage=[],q.storageError="",kn()}),Aa=Qr(()=>q.devicePresetId,()=>zr.notifyViewportChange(),{flush:"post"}),_a=Qr(()=>q.previewMode,()=>{Ot("preview mode changed"),dl(!1),om(!1),Hr("preview mode changed")},{flush:"sync"}),Da=Qr(()=>wi.value,()=>zr.notifyViewportChange(),{flush:"post"}),Na=Qr(()=>q.desktopWindow.closed,(e,t)=>{if(Pn()){if(e){Ot("desktop window closed"),q.runtimeStatus="closed";return}t&&q.runtimeStatus==="closed"&&Hr("desktop window reopened")}},{flush:"sync"})}function NS(e){if(typeof e=="string")return e;if(e instanceof Error)return(typeof e.stack=="string"?e.stack.split(`
227
227
  `).slice(0,4).join(`
228
- `):"")||`${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 vh(e){const t=e.detail?.open===!0;t!==Tt&&(Tt=t,St+=1,Go(),t&&(be.mobileLanSelect.addEventListener("change",MS),xh(),Bn()))}function MS(){Tt&&Bn()}function Hr(e){Ae||At!==void 0||(Bt("runtime.restart",{boundary:hc+1}),At=window.setTimeout(()=>{At=void 0,Ae||ur(e)},0))}async function ur(e,t=Dh,r){if(Ae||Sr||q.diagnosticOwnershipLost)return;if(At!==void 0&&window.clearTimeout(At),At=void 0,Ot(e),kn()&&q.desktopWindow.closed){q.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=sm(i,c=>{Fe||ct.event(i,c)}),s={instanceId:i,launchUrl:t,locationBasePath:r,interactions:o,sequence:++hc,state:"starting",iframe:n,terminal:new AbortController,permissions:qh(xr),mounted:!1,hadReady:!1,pendingNavigationReload:!1};if(s.iframe.dataset.hbSdkInstanceId=s.instanceId,He=s,q.runtimeStatus="loading",kh(),Fe||ct.send({operation:"register",instanceId:s.instanceId}),await Ii(),!Be(s))return;const a=Qh("#device");if(!a){Vs(s,new Error("预览容器尚未挂载"));return}if(Fe){a.innerHTML='<div class="browser-mock-preview"><span class="browser-mock-preview__icon">UI</span><strong>Browser Mock</strong><small>mp_preview</small></div>',q.runtimeStatus="idle";return}a.replaceChildren(s.iframe),s.mounted=!0,ct.send({operation:"activate",instanceId:s.instanceId});try{const c=await EN(bS(s));if(!Be(s)){c.dispose();return}s.assembly=c,c.ports.companion=ba.port,c.ports.media=PM({getMode:()=>q.mediaSimulation,signal:s.terminal.signal});const d=$N({signal:s.terminal.signal,csrfToken:()=>De.csrfToken??""}),u=eN({iframe:s.iframe,authorizationContext:QN({signal:s.terminal.signal,refreshAccount:f=>yo(!0,f),request:Ph,readState:()=>({signed:Je,browser:Ue,userId:vt,accountRevision:Tr,networkEnabled:s.permissions.networkRequest.status==="enabled"})}),ports:{...c.ports,...d},environment:c.environment,hostCapabilities:{...c.hostCapabilities,"media.pick":!0,...d?{"gameSaves.getFile":!0,"user.data.file":!0,"file.readBytes":!0,"file.readText":!0,"file.stat":!0,"file.exists":!0}:{},...bM},authPresentation:c.authPresentation,userDataPresentation:c.userDataPresentation,companionPresentation:ba.presentation,resolveLaunchConfiguration:async()=>(await c.resolveLaunch()).configuration,dispose:()=>Ra(s),onDevDocumentReload:(f,l)=>{Be(s)&&ur("development document reloaded",f,l)},onDevUploadSession:f=>{Be(s)&&(s.uploadSessionId=f,Fr(s,{uploadSessionId:f}))},onReady:()=>{Be(s)&&(s.state="ready",s.hadReady=!0,Pa.value=d?u.diagnostics.gameSaves:void 0,q.runtimeStatus="ready",Fr(s),Xt("runtime.ready",{generation:s.sequence},Date.now(),void 0,s.instanceId))},onUserDataTelemetry:f=>{_t.refresh();const l=_M(f);Xt(l.method,l.detail,Date.now(),"info",s.instanceId)},onTrace:f=>OS(s,f),onError:f=>{Be(s)&&Vs(s,f)},onCapabilityTrace:f=>{Xt(f.method,{...f,source:"host"},f.timestamp,void 0,s.instanceId),Be(s)&&f.method==="storage.setStorage"&&f.outcome==="success"&&Pn()}});s.runtime=u,await u.start(),Be(s)&&_t.bind(u.getDataPermissionBridge())}catch(c){if(!Be(s))return;Vs(s,c),Xt("runtime.start.failed",Fh(c,s),Date.now(),"error",s.instanceId),s.terminal.abort(c),s.runtime?.destroy(),s.iframe.remove(),Ra(s)}}function Oh(){Ae||q.diagnosticOwnershipLost||(q.diagnosticOwnershipLost=!0,Ot("预览页面授权已失效"),q.runtimeStatus="closed",mc=!1)}function Be(e){return He===e&&!Ae&&!e.terminal.signal.aborted&&e.state!=="closed"&&e.state!=="failed"}function Fr(e,t={}){ct.send({operation:"update",instanceId:e.instanceId,state:e.state,...t})}function Rh(e,t){e.mounted&&(e.mounted=!1,ct.send({operation:"detach",instanceId:e.instanceId,reason:t}))}function Ra(e){He===e&&(Pa.value=void 0),e.interactions.dispose();const t=e.assembly;e.assembly=void 0,t?.dispose()}function Vs(e,t){e.state==="failed"||e.state==="closed"||(e.state="failed",e.interactions.dispose(),Fr(e,{error:Fh(t,e),...e.uploadSessionId?{uploadSessionId:e.uploadSessionId}:{}}),Rh(e,"Runtime failed"),He===e&&(q.runtimeStatus="error"))}function Ot(e){const t=He;t&&(He=void 0,Pa.value=void 0,_t.clearSession(),t.state!=="failed"&&(t.state="closed",Fr(t,{reason:e})),Rh(t,e),(!pn.value||pn.value===q.diagnosticTargetId)&&(ga+=1,pa?.abort()),am(),ba.reset(),t.terminal.abort(new DOMException(e,"AbortError")),t.runtime?.destroy(),t.iframe.remove(),Ra(t),zr.reset())}function SS(){const e=wm();q.diagnosticTargetId=e.targetId,q.diagnosticOwnerId=e.ownerId,q.diagnosticPrimaryTargetId=e.targetId,q.diagnosticTargetName=e.metadata.displayName,q.diagnosticTargets=[e],q.diagnosticInstances=[{instanceId:e.currentInstanceId,targetId:e.targetId,ownerId:e.ownerId,adapterId:e.adapterId,kind:"browser",capabilities:e.capabilities,state:"ready",startedAt:Date.now(),updatedAt:Date.now(),startCursor:0,lastCursor:0,stale:!1}];const t={...e,targetId:"ui-preview-phone",ownerId:"ui-preview-phone-owner",kind:"mobile",currentInstanceId:"ui-preview-phone-instance",metadata:{displayName:"小黑盒",deviceModel:"iPhone 16 Pro",os:"iOS"}};q.diagnosticTargets.push(t),q.diagnosticInstances.push({...q.diagnosticInstances[0],instanceId:t.currentInstanceId,targetId:t.targetId,ownerId:t.ownerId,kind:"mobile"}),$s({...qs("console.error",{source:"app",message:"真机示例:请求超时"},Date.now(),"error"),targetId:t.targetId,instanceId:t.currentInstanceId}),Bt("runtime.ready",{generation:1}),$s(qs("console.info",{source:"app",message:"页面初始化完成"},Date.now(),"info")),Bt("user.getInfo",{durationMs:34,outcome:"success"}),Bt("network.request",{durationMs:86,network:{method:"GET",origin:"https://api.example.com",pathname:"/demo",responseStatus:200},outcome:"success"})}function bS(e){const t=e.terminal.signal,r=Ue,n=gn,i=gh(r.runtimePermissions,e.permissions,r),o=kn();return{signal:t,account:{async getCurrentUserId(){return(await yo(!1,t)).user_id},async ensureAuthenticated({signal:s}){await yo(!1,s)},onChange(s){return po.add(s),()=>po.delete(s)}},authenticatedRequest:Ph,storage:{area:"local",storage:EM(localStorage)},presentation:MM({close:async()=>{Be(e)&&(Ot("mini program closed"),kh(),q.runtimeStatus="closed",o&&dl(!0))},reload:()=>{Be(e)&&(e.pendingNavigationReload=!0)},onNavigationBarStyleChange:s=>{Be(e)&&ul(s)},...o?{getViewportMetrics:()=>{const s=wi.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:()=>Em}:{getDeviceMetrics:()=>Qs.value,applyDisplay:(s,a)=>zr.applyDisplay(s,a),isCapsuleHidden:()=>q.display.capsuleHidden},onViewportChange:s=>zr.onViewportChange(s)}),environment:{getCurrentHref:()=>location.href,isDevRuntime:()=>!0,setDocumentTitle:s=>{document.title=s}},resolveLaunch:async()=>({configuration:uM({launchUrl:e.launchUrl,locationBasePath:e.locationBasePath,runtimePermissions:i,networkPolicy:r.networkPolicy,...q.miniProgram.bound&&q.miniProgram.name.trim()?{miniProgramName:q.miniProgram.name}:{},...r.miniProgramId?{miniProgramId:r.miniProgramId}:n?{anonymousStorageScope:n}:{},operatingSystem:o?q.hostPlatform:cm.value.platform}),hostHints:{launchKind:r.source==="remote"?"dev-session":"anonymous-local-dev"}}),authPresentation:{confirmAuthorization:s=>dM(s),confirmFollowAuthor:s=>rM(s)},userDataPresentation:{confirmDataPermission:mM},protocol:TS(e)}}function kn(){return q.previewMode==="desktop"}function TS(e){return{async invoke(t){Xt("device.executeProtocol",{outcome:"success",delivery:"mock",protocolType:vS(t)},Date.now(),void 0,e.instanceId)}}}function vS(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 We(r)&&typeof r.protocol_type=="string"?r.protocol_type:void 0}catch{return}}function kh(){document.documentElement.dataset.navigationBarStyle=rl,ul(rl)}function OS(e,t){Be(e)&&t.type==="document_validation"&&typeof t.documentVerifying=="boolean"&&Fr(e,{documentVerifying:t.documentVerifying}),Ae||ct.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(dm({...t,generation:e.sequence})),...t.errorCode?{errorCode:t.errorCode}:{}}),e.runtimeId!==t.runtimeId&&(e.runtimeId=t.runtimeId,Fr(e,{runtimeId:t.runtimeId})),Be(e)&&e.pendingNavigationReload&&t.type==="bridge_response"&&t.method==="navigation.reload"&&t.outcome==="success"&&(e.pendingNavigationReload=!1,Hr("navigation.reload"))}async function Ph(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 pc(n?uS:fS,{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&&Br.invalidate();const o=await i.json();if(!i.ok)throw o;return o}async function yo(e,t){const r=Fo,n=await Ch(Vh(ar.signal,t));return Gh(r)?Lh(n,e).status:ka()}async function Ch(e){return await(await fetch(lS,{cache:"no-store",credentials:"same-origin",redirect:"error",signal:e})).json()}function Lh(e,t){if(!Number.isSafeInteger(e.revision)||e.revision<Tr)return{changed:!1,status:ka()};const r=e.authenticated?e.user_id:void 0,n=e.authenticated?Re(e.nickname):void 0,i=e.authenticated?Re(e.avatar):void 0,o=e.revision!==Tr||e.authenticated!==Rn||r!==vt||n!==Ma||i!==Sa;return Tr=e.revision,Rn=e.authenticated,vt=r,Ma=n,Sa=i,jh(),jr(),t&&o&&po.forEach(s=>s(vt)),{changed:o,status:ka()}}function ka(){return{authenticated:Rn,revision:Tr,...Rn&&vt?{user_id:vt}:{}}}function RS(){if(!(!De.csrfToken||Ae))try{const e=new URL("/__hb_sdk__/channel",location.href);e.protocol=e.protocol==="https:"?"wss:":"ws:",Qt=oS({csrfToken:De.csrfToken,onDiagnostic:t=>Bt("channel.diagnostic",t),url:e.toString()}),Qt.subscribeUpdates((t,r)=>kS(t,r)),Qt.connect()}catch{Qt?.dispose(),Qt=void 0}}function kS(e,t){Br.invalidate(e.account.revision),tb(xr,e.permissions)?t.type==="event"&&t.event==="status.changed"&&ur("status changed"):(xr=qh(e.permissions),CS())}function Uh(){if(yi?.close(),yi=void 0,!vt||Ae)return;const e=new EventSource(hS);yi=e,e.addEventListener("account-invalidated",()=>{Br.invalidate()}),e.addEventListener("account-revision",()=>{Br.invalidate()}),e.onopen=()=>{Ta.reset()},e.onerror=()=>{e.close(),Ta.schedule()}}async function PS(e){Gh(e)&&await ur("account revision changed")}async function CS(){Ae||(await ur("permission changed"),!Ae&&await Bn())}async function gc(){const e=await fetch(cS,{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(!We(t))throw new Error("Browser Dev Host bootstrap is invalid");const r=$h(t.mobileLaunchRedirect);if(Object.hasOwn(t,"mobileLaunchRedirect")&&t.mobileLaunchRedirect!==void 0&&!r)throw new Vr;return{openPlatformBaseUrl:typeof t.openPlatformBaseUrl=="string"?t.openPlatformBaseUrl:void 0,devReadiness:xS(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:Fu(t.devContext,t.runtimePermissions),browserDevContext:Fu(t.browserDevContext??t.devContext,t.runtimePermissions),lanAddresses:Array.isArray(t.lanAddresses)?t.lanAddresses.filter(eb):[],loginAvailable:t.loginAvailable===!0,miniProgram:QS(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:US(t.windowForm),hostPlatform:LS(t.hostPlatform)}}function LS(e){return yS.includes(e)?e:"unknown"}function US(e){if(!We(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 xS(e){if(!We(e))return;const t=s=>{if(!(!We(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||!We(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=>We(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 pc(e,t){const r=new Headers(t.headers);return r.set("content-type","application/json"),De.csrfToken&&r.set("x-hb-sdk-csrf",De.csrfToken),fetch(e,{...t,headers:r,cache:"no-store",credentials:"same-origin",redirect:"error"})}function zS(){yc(),Fe||(ya=window.setInterval(()=>{qS()},mS))}function xh(e=be.mobileLanSelect.options.length>0?be.mobileLanSelect.value:void 0){be.mobileLanSelect.replaceChildren();for(const t of kt){const r=document.createElement("option");r.value=t.id,r.textContent=`${t.name} · ${t.address}`,be.mobileLanSelect.appendChild(r)}e&&kt.some(({id:t})=>t===e)?be.mobileLanSelect.value=e:fi&&kt.some(({id:t})=>t===fi)?be.mobileLanSelect.value=fi:kt[0]&&(be.mobileLanSelect.value=kt[0].id),be.mobileLanSelect.disabled=kt.length===0}async function Bn(){if(Ae)return;const e=++St;if(Go(),Fe){const r=await Bu.toDataURL("hb-sdk-ui-preview",{width:tl,margin:1});if(e!==St||Ae||!Tt)return;be.mobileQrImage.src=r,be.mobileQrStatus.textContent="UI 预览示例,不用于真机连接";return}if(Je.source!=="remote"||!Je.localDevLaunchToken||Je.expiresAt!==void 0&&Je.expiresAt<=Date.now()){be.mobileQrImage.removeAttribute("src"),be.mobileQrStatus.textContent=lc||"需要有效的本地调试启动票";return}const t=XS();if(!t?.mobileAppQrPayload){be.mobileQrImage.removeAttribute("src"),be.mobileQrStatus.textContent="未发现可用的局域网地址";return}be.mobileQrStatus.textContent="正在生成二维码...";try{const r=await VS(t);if(e!==St||Ae)return;const n=await jS(r.address,r.expiresAt);if(e!==St||Ae)return;const i=await Bu.toDataURL(n.payload,{width:tl,margin:1});if(e!==St||Ae)return;be.mobileQrImage.src=i,be.mobileQrStatus.textContent=`${r.address.name} · ${r.address.address}`,$S(n.expiresAt,e)}catch(r){if(e!==St||Ae)return;if(r instanceof Vr){Ei();return}be.mobileQrImage.removeAttribute("src"),be.mobileQrStatus.textContent=Ec(r)}}async function jS(e,t){const r=e.mobileAppQrPayload;if(!r)throw new Error("Mobile 启动配置不可用");const n=await BS(e,r);if(!n)return{expiresAt:t,payload:r};try{return{expiresAt:Math.min(t,n.expiresAt),payload:kM(RM({host:e.address,port:location.port,token:n.token}))}}catch{throw new Vr}}async function BS(e,t){if(Dr?.addressId===e.id)return Dr;if(!Dr)return;const r=await pc(dS,{method:"POST",body:JSON.stringify({address_id:e.id,payload:t,previous_token:Dr.token})});if(!r.ok)throw new Vr;const n=await r.json(),i=We(n)?$h({addressId:n.address_id,expiresAt:n.expires_at,token:n.token}):void 0;if(!i||i.addressId!==e.id)throw new Vr;return Dr=i,mi={...mi,mobileLaunchRedirect:i},fc=Vo(mi),i}async function HS(e){const t=await gc(),r=FS(t,e),n=r?.mobileAppQrPayload;if(!r||!n)throw new Error("Mobile 启动配置不可用");return zh(t),{...r,mobileAppQrPayload:n}}function FS(e,t){return e.lanAddresses.find(({id:r})=>r===t)??e.lanAddresses.find(({id:r})=>r===e.defaultLanAddressId)??e.lanAddresses[0]}function zh(e){const t=Kt(Ue);q.devReadiness=e.devReadiness,q.miniProgramSupportsDesktop=e.miniProgramSupportsDesktop,q.miniProgramPlatforms=e.devContext.platforms??[],al(e.hostPlatform),cl(e.windowForm),hi=e.workspaceCardsEnabled,mi=e,fc=Vo(e),Je=e.devContext,br=e.browserDevContext,Ue=fn(br),xr=Bo(Ue),Eo(),kt=e.lanAddresses,fi=e.defaultLanAddressId,Dr=e.mobileLaunchRedirect,lc=e.nativeAppLaunchUnavailableReason,gn=e.devSessionId,ma=e.miniProgramManifestAccessToken,Hh(Bh(e)),Tt&&xh(),yc(),t!==Kt(Ue)&&(Ot("local permission context changed"),Hr("local permission context changed"))}function Eo(){if(Fe){q.localPermissions=Im(),q.devContextWarning="";return}q.localPermissions=YM(Ue),q.devContextWarning=Ue.source==="anonymous"?"未连接线上上下文":Ue.warning?"本地上下文受限,请检查 CLI 状态":"",jr()}function yc(){let e;try{e=um(Dh)}catch{}const t=Je.miniProgramId?.trim().toLowerCase();let r=lc?.trim()??"";!r&&(Je.source!=="remote"||!t)&&(r="请先绑定可管理的小程序"),!r&&!Je.localDevLaunchToken?.trim()&&(r="正在等待有效的本地调试启动票"),!r&&hi&&!gn&&(r="本地调试会话尚未就绪"),!r&&Je.expiresAt!==void 0&&Je.expiresAt<=Date.now()&&(r="本地调试启动票已过期"),!r&&!e&&(r="未发现可用的本机调试地址"),ll({...e?{address:e}:{},...t?{miniProgramId:t}:{},...hi&&gn?{devSessionId:gn}:{},...ma?{miniProgramManifestToken:ma}:{},workspaceCardsEnabled:hi,ready:r==="",...r?{unavailableReason:r}:{}})}class Vr extends Error{}async function VS(e){const t=ol.then(()=>GS(e));return ol=t.then(()=>{},()=>{}),t}async function GS(e){const t=new URL(e.appUrl),r=new URL(YN,location.origin),n=await pc(r.pathname,{method:"POST",body:JSON.stringify({mini_url_origin:t.origin,runtime_permissions:KN(Je)})}),i=await n.json();if(!n.ok||!We(i)||typeof i.token!="string"||typeof i.expires_at!="number")throw new Error("创建 Mobile Dev Session 失败");return{address:await HS(e.id),expiresAt:i.expires_at}}function $S(e,t){gi=window.setTimeout(()=>{!Ae&&Tt&&t===St&&Bn()},Math.max(1e3,e-Date.now()-3e4))}async function qS(){if(!(zs||Ae)){zs=!0;try{const e=await gc();il=Date.now();const t=Sr;Sr=!1;const r=Vo(e);if(!t&&r===fc&&Kt(fn(e.browserDevContext))===Kt(Ue)){br=e.browserDevContext,Ue=fn(br),Eo();return}zh(e),t&&Hr("CLI dev session reconnected"),Tt&&Bn()}catch(e){e instanceof Vr&&Ei();const t=fn(br);Kt(t)!==Kt(Ue)&&(Ue=t,xr=Bo(Ue),Eo(),Ot("local permission context expired"),Hr("local permission context expired"),yc(),Tt&&Ei()),Date.now()-il>=3e4&&!Sr&&(Sr=!0,Ot("CLI dev session disconnected"),Qh("#device")?.replaceChildren(),q.runtimeStatus="closed",q.localPermissions=[],q.devContextWarning="调试会话已断开",ll({ready:!1,unavailableReason:"调试会话已断开"}),q.devReadiness={browser:{state:"blocked",reason:"调试会话已断开,等待 CLI 恢复"},mobile:{state:"blocked",reason:"调试会话已断开"},companion:{state:"blocked",reason:"调试会话已断开"}},Tt&&Ei())}finally{zs=!1}}}function Ei(){St+=1,Go(),be.mobileQrImage.removeAttribute("src"),be.mobileQrStatus.textContent="Mobile 短链接配置无效"}function Vo(e){return JSON.stringify({devReadiness:e.devReadiness,devSessionId:e.devSessionId,defaultLanAddressId:e.defaultLanAddressId,lanAddresses:e.lanAddresses,mobileLaunchRedirect:e.mobileLaunchRedirect?{addressId:e.mobileLaunchRedirect.addressId,expiresAt:e.mobileLaunchRedirect.expiresAt,token:e.mobileLaunchRedirect.token}:void 0,devContext:{platforms:e.devContext.platforms,permissionContext:Kt(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 jh(){if(!Rn){q.account={authenticated:!1,avatar:"",nickname:"未登录"};return}q.account={authenticated:!0,avatar:Sa??"",nickname:Ma||vt||"已登录"}}function Bh(e){if(e.miniProgram?.miniProgramId)return e.miniProgram;const t=e.devContext.miniProgramId?.trim();return t?{miniProgramId:t}:e.miniProgram??null}function Hh(e){if(!!!e?.miniProgramId||!e){q.miniProgram={bound:!1,id:"",iconUrl:"",name:"未绑定小程序",detail:"本地调试",description:"",version:""},jr();return}q.miniProgram={bound:!0,id:e.miniProgramId,iconUrl:e.iconUrl??"",name:e.name||e.miniProgramId,detail:[e.miniProgramId,e.version].filter(Boolean).join(" · "),description:e.description??"",version:e.version??""},jr()}function QS(e){if(e===null)return null;if(!We(e))return;const t=Re(e.miniProgramId)??Re(e.mini_program_id);if(t)return{miniProgramId:t,...Re(e.description)?{description:Re(e.description)}:{},...Re(e.name)?{name:Re(e.name)}:{},...Re(e.iconUrl)??Re(e.icon_url)?{iconUrl:Re(e.iconUrl)??Re(e.icon_url)}:{},...Re(e.status)?{status:Re(e.status)}:{},...Re(e.version)?{version:Re(e.version)}:{},...Re(e.developerName)??Re(e.developer_name)?{developerName:Re(e.developerName)??Re(e.developer_name)}:{}}}function Re(e){return typeof e=="string"&&e.trim()?e.trim():void 0}async function Pn(){const e=++ga;pa?.abort();const t=new AbortController;pa=t;const r=pn.value,n=!r||r===q.diagnosticTargetId,i=ii.value,o=Gs.value||(n?He?.instanceId:void 0),s=()=>!Ae&&e===ga&&r===pn.value&&o===(Gs.value||(n?He?.instanceId:void 0));if(!n&&(!i||!o||i.stale||i.state!=="attached"||!i.capabilities.storage)){q.storage=[],q.storageError=!i||!i.capabilities.storage?"当前设备不支持存储诊断":"当前设备未连接或没有运行实例";return}if(Fe){q.storage=[{area:"local",key:"preferences",serializedValue:'{"theme":"light","language":"zh-CN"}',bytes:36},{area:"local",key:n?"lastOpenedProject":"deviceModel",serializedValue:n?'"demo-project"':'"iPhone 16 Pro"',bytes:n?14:15}],q.storageError="";return}if(!o){q.storage=[],q.storageError="";return}try{const a=await lm({instanceId:o,resource:"storage"},{csrfToken:De.csrfToken,signal:AbortSignal.any([t.signal,ar.signal])});if(!s())return;if(a.code)throw new Error(a.error??"Storage 诊断查询失败");q.storage=a.value,q.storageError=""}catch(a){if(!s())return;q.storage=[],q.storageError=Ec(a)}}function Fh(e,t=He){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 Xt(e,t,r=Date.now(),n,i){YS(qs(e,t,r,n==="debug"?"log":n),i)}function YS(e,t){if(Ae)return;if(Fe){$s({...e,targetId:q.diagnosticTargetId});return}const r=We(e.detail)?e.detail:{};ct.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}:{},...We(r.network)?{network:r.network}:{}})}async function WS(e){const t=He;if(!t||e.instanceId!==t.instanceId||!Be(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!Be(t)||r!==t.runtime||e.instanceId!==t.instanceId?{code:"closed",error:"查询期间实例已结束"}:{value:s}}function ZS(e,t){Bt("host.message",{message:e,status:t})}function KS(e){Ae||ZS(Ec(e),"error")}function Bt(e,t){Xt(e,t)}function JS(){ct.close(),va!==void 0&&window.clearTimeout(va),Oa!==void 0&&window.clearTimeout(Oa),!Ae&&(Ae=!0,pi.dispose(),Ea.dispose(),window.__HB_SDK_PREVIEW__===Nh&&delete window.__HB_SDK_PREVIEW__,window.removeEventListener("hb-sdk:refresh-storage",Pn),window.removeEventListener("hb-sdk:qr-open-change",vh),Fo+=1,ar.abort(new DOMException("Browser Dev Host disposed","AbortError")),Br.dispose(),Ot("Browser Dev Host disposed"),_t.dispose(),ct.send({operation:"close-target",reason:"Browser Dev Host disposed"}),window.setTimeout(()=>Ih.abort(),2e3),yi?.close(),Qt?.dispose(),Qt=void 0,Ta.dispose(),At!==void 0&&window.clearTimeout(At),At=void 0,Go(),ya!==void 0&&window.clearInterval(ya),po.clear(),wa?.(),wa=void 0,Ia?.(),Ia=void 0,Aa?.(),Aa=void 0,_a?.(),_a=void 0,Da?.(),Da=void 0,Na?.(),Na=void 0)}function Go(){gi!==void 0&&window.clearTimeout(gi),gi=void 0}function Vh(e,t){return t?AbortSignal.any([e,t]):e}function Gh(e){return!Ae&&e===Fo}function XS(){return kt.find(({id:e})=>e===be.mobileLanSelect.value)}function eb(e){return We(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 $h(e){if(!(!We(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 qh(e){return{networkRequest:{...e.networkRequest}}}function tb(e,t){return e.networkRequest.status===t.networkRequest.status&&e.networkRequest.useOfficialDomain===t.networkRequest.useOfficialDomain}function Ec(e){return e instanceof Error&&e.message?e.message:"操作失败"}function We(e){return Object.prototype.toString.call(e)==="[object Object]"}function ni(e){const t=document.querySelector(e);if(!t)throw new Error(`Missing Browser Dev Host element: ${e}`);return t}function Qh(e){return document.querySelector(e)??void 0}
228
+ `):"")||`${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 vh(e){const t=e.detail?.open===!0;t!==Tt&&(Tt=t,St+=1,Go(),t&&(be.mobileLanSelect.addEventListener("change",MS),xh(),Bn()))}function MS(){Tt&&Bn()}function Hr(e){Ae||At!==void 0||(Bt("runtime.restart",{boundary:hc+1}),At=window.setTimeout(()=>{At=void 0,Ae||ur(e)},0))}async function ur(e,t=Dh,r){if(Ae||Sr||q.diagnosticOwnershipLost)return;if(At!==void 0&&window.clearTimeout(At),At=void 0,Ot(e),Pn()&&q.desktopWindow.closed){q.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=sm(i,c=>{Fe||ct.event(i,c)}),s={instanceId:i,launchUrl:t,locationBasePath:r,interactions:o,sequence:++hc,state:"starting",iframe:n,terminal:new AbortController,permissions:qh(xr),mounted:!1,hadReady:!1,pendingNavigationReload:!1};if(s.iframe.dataset.hbSdkInstanceId=s.instanceId,He=s,q.runtimeStatus="loading",Ph(),Fe||ct.send({operation:"register",instanceId:s.instanceId}),await Ii(),!Be(s))return;const a=Qh("#device");if(!a){Vs(s,new Error("预览容器尚未挂载"));return}if(Fe){a.innerHTML='<div class="browser-mock-preview"><span class="browser-mock-preview__icon">UI</span><strong>Browser Mock</strong><small>mp_preview</small></div>',q.runtimeStatus="idle";return}a.replaceChildren(s.iframe),s.mounted=!0,ct.send({operation:"activate",instanceId:s.instanceId});try{const c=await EN(bS(s));if(!Be(s)){c.dispose();return}s.assembly=c,c.ports.companion=ba.port,c.ports.media=kM({getMode:()=>q.mediaSimulation,signal:s.terminal.signal});const d=$N({signal:s.terminal.signal,csrfToken:()=>De.csrfToken??""}),u=eN({iframe:s.iframe,authorizationContext:QN({signal:s.terminal.signal,refreshAccount:f=>yo(!0,f),request:kh,readState:()=>({signed:Je,browser:Ue,userId:vt,accountRevision:Tr,networkEnabled:s.permissions.networkRequest.status==="enabled"})}),ports:{...c.ports,...d},environment:c.environment,hostCapabilities:{...c.hostCapabilities,"media.pick":!0,...d?{"gameSaves.getFile":!0,"user.data.file":!0,"file.readBytes":!0,"file.readText":!0,"file.stat":!0,"file.exists":!0}:{},...bM},authPresentation:c.authPresentation,userDataPresentation:c.userDataPresentation,companionPresentation:ba.presentation,resolveLaunchConfiguration:async()=>(await c.resolveLaunch()).configuration,dispose:()=>Ra(s),onDevDocumentReload:(f,l)=>{Be(s)&&ur("development document reloaded",f,l)},onDevUploadSession:f=>{Be(s)&&(s.uploadSessionId=f,Fr(s,{uploadSessionId:f}))},onReady:()=>{Be(s)&&(s.state="ready",s.hadReady=!0,ka.value=d?u.diagnostics.gameSaves:void 0,q.runtimeStatus="ready",Fr(s),Xt("runtime.ready",{generation:s.sequence},Date.now(),void 0,s.instanceId))},onUserDataTelemetry:f=>{_t.refresh();const l=_M(f);Xt(l.method,l.detail,Date.now(),"info",s.instanceId)},onTrace:f=>OS(s,f),onError:f=>{Be(s)&&Vs(s,f)},onCapabilityTrace:f=>{Xt(f.method,{...f,source:"host"},f.timestamp,void 0,s.instanceId),Be(s)&&f.method==="storage.setStorage"&&f.outcome==="success"&&kn()}});s.runtime=u,await u.start(),Be(s)&&_t.bind(u.getDataPermissionBridge())}catch(c){if(!Be(s))return;Vs(s,c),Xt("runtime.start.failed",Fh(c,s),Date.now(),"error",s.instanceId),s.terminal.abort(c),s.runtime?.destroy(),s.iframe.remove(),Ra(s)}}function Oh(){Ae||q.diagnosticOwnershipLost||(q.diagnosticOwnershipLost=!0,Ot("预览页面授权已失效"),q.runtimeStatus="closed",mc=!1)}function Be(e){return He===e&&!Ae&&!e.terminal.signal.aborted&&e.state!=="closed"&&e.state!=="failed"}function Fr(e,t={}){ct.send({operation:"update",instanceId:e.instanceId,state:e.state,...t})}function Rh(e,t){e.mounted&&(e.mounted=!1,ct.send({operation:"detach",instanceId:e.instanceId,reason:t}))}function Ra(e){He===e&&(ka.value=void 0),e.interactions.dispose();const t=e.assembly;e.assembly=void 0,t?.dispose()}function Vs(e,t){e.state==="failed"||e.state==="closed"||(e.state="failed",e.interactions.dispose(),Fr(e,{error:Fh(t,e),...e.uploadSessionId?{uploadSessionId:e.uploadSessionId}:{}}),Rh(e,"Runtime failed"),He===e&&(q.runtimeStatus="error"))}function Ot(e){const t=He;t&&(He=void 0,ka.value=void 0,_t.clearSession(),t.state!=="failed"&&(t.state="closed",Fr(t,{reason:e})),Rh(t,e),(!pn.value||pn.value===q.diagnosticTargetId)&&(ga+=1,pa?.abort()),am(),ba.reset(),t.terminal.abort(new DOMException(e,"AbortError")),t.runtime?.destroy(),t.iframe.remove(),Ra(t),zr.reset())}function SS(){const e=wm();q.diagnosticTargetId=e.targetId,q.diagnosticOwnerId=e.ownerId,q.diagnosticPrimaryTargetId=e.targetId,q.diagnosticTargetName=e.metadata.displayName,q.diagnosticTargets=[e],q.diagnosticInstances=[{instanceId:e.currentInstanceId,targetId:e.targetId,ownerId:e.ownerId,adapterId:e.adapterId,kind:"browser",capabilities:e.capabilities,state:"ready",startedAt:Date.now(),updatedAt:Date.now(),startCursor:0,lastCursor:0,stale:!1}];const t={...e,targetId:"ui-preview-phone",ownerId:"ui-preview-phone-owner",kind:"mobile",currentInstanceId:"ui-preview-phone-instance",metadata:{displayName:"小黑盒",deviceModel:"iPhone 16 Pro",os:"iOS"}};q.diagnosticTargets.push(t),q.diagnosticInstances.push({...q.diagnosticInstances[0],instanceId:t.currentInstanceId,targetId:t.targetId,ownerId:t.ownerId,kind:"mobile"}),$s({...qs("console.error",{source:"app",message:"真机示例:请求超时"},Date.now(),"error"),targetId:t.targetId,instanceId:t.currentInstanceId}),Bt("runtime.ready",{generation:1}),$s(qs("console.info",{source:"app",message:"页面初始化完成"},Date.now(),"info")),Bt("user.getInfo",{durationMs:34,outcome:"success"}),Bt("network.request",{durationMs:86,network:{method:"GET",origin:"https://api.example.com",pathname:"/demo",responseStatus:200},outcome:"success"})}function bS(e){const t=e.terminal.signal,r=Ue,n=gn,i=gh(r.runtimePermissions,e.permissions,r),o=Pn();return{signal:t,account:{async getCurrentUserId(){return(await yo(!1,t)).user_id},async ensureAuthenticated({signal:s}){await yo(!1,s)},onChange(s){return po.add(s),()=>po.delete(s)}},authenticatedRequest:kh,storage:{area:"local",storage:EM(localStorage)},presentation:MM({close:async()=>{Be(e)&&(Ot("mini program closed"),Ph(),q.runtimeStatus="closed",o&&dl(!0))},reload:()=>{Be(e)&&(e.pendingNavigationReload=!0)},onNavigationBarStyleChange:s=>{Be(e)&&ul(s)},...o?{getViewportMetrics:()=>{const s=wi.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:()=>Em}:{getDeviceMetrics:()=>Qs.value,applyDisplay:(s,a)=>zr.applyDisplay(s,a),isCapsuleHidden:()=>q.display.capsuleHidden},onViewportChange:s=>zr.onViewportChange(s)}),environment:{getCurrentHref:()=>location.href,isDevRuntime:()=>!0,setDocumentTitle:s=>{document.title=s}},resolveLaunch:async()=>({configuration:uM({launchUrl:e.launchUrl,locationBasePath:e.locationBasePath,runtimePermissions:i,networkPolicy:r.networkPolicy,firstParty:r.source==="remote"&&r.firstParty===!0,...q.miniProgram.bound&&q.miniProgram.name.trim()?{miniProgramName:q.miniProgram.name}:{},...r.miniProgramId?{miniProgramId:r.miniProgramId}:n?{anonymousStorageScope:n}:{},operatingSystem:o?q.hostPlatform:cm.value.platform}),hostHints:{launchKind:r.source==="remote"?"dev-session":"anonymous-local-dev"}}),authPresentation:{confirmAuthorization:s=>dM(s),confirmFollowAuthor:s=>rM(s)},userDataPresentation:{confirmDataPermission:mM},protocol:TS(e)}}function Pn(){return q.previewMode==="desktop"}function TS(e){return{async invoke(t){Xt("device.executeProtocol",{outcome:"success",delivery:"mock",protocolType:vS(t)},Date.now(),void 0,e.instanceId)}}}function vS(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 We(r)&&typeof r.protocol_type=="string"?r.protocol_type:void 0}catch{return}}function Ph(){document.documentElement.dataset.navigationBarStyle=rl,ul(rl)}function OS(e,t){Be(e)&&t.type==="document_validation"&&typeof t.documentVerifying=="boolean"&&Fr(e,{documentVerifying:t.documentVerifying}),Ae||ct.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(dm({...t,generation:e.sequence})),...t.errorCode?{errorCode:t.errorCode}:{}}),e.runtimeId!==t.runtimeId&&(e.runtimeId=t.runtimeId,Fr(e,{runtimeId:t.runtimeId})),Be(e)&&e.pendingNavigationReload&&t.type==="bridge_response"&&t.method==="navigation.reload"&&t.outcome==="success"&&(e.pendingNavigationReload=!1,Hr("navigation.reload"))}async function kh(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 pc(n?uS:fS,{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&&Br.invalidate();const o=await i.json();if(!i.ok)throw o;return o}async function yo(e,t){const r=Fo,n=await Ch(Vh(ar.signal,t));return Gh(r)?Lh(n,e).status:Pa()}async function Ch(e){return await(await fetch(lS,{cache:"no-store",credentials:"same-origin",redirect:"error",signal:e})).json()}function Lh(e,t){if(!Number.isSafeInteger(e.revision)||e.revision<Tr)return{changed:!1,status:Pa()};const r=e.authenticated?e.user_id:void 0,n=e.authenticated?Re(e.nickname):void 0,i=e.authenticated?Re(e.avatar):void 0,o=e.revision!==Tr||e.authenticated!==Rn||r!==vt||n!==Ma||i!==Sa;return Tr=e.revision,Rn=e.authenticated,vt=r,Ma=n,Sa=i,jh(),jr(),t&&o&&po.forEach(s=>s(vt)),{changed:o,status:Pa()}}function Pa(){return{authenticated:Rn,revision:Tr,...Rn&&vt?{user_id:vt}:{}}}function RS(){if(!(!De.csrfToken||Ae))try{const e=new URL("/__hb_sdk__/channel",location.href);e.protocol=e.protocol==="https:"?"wss:":"ws:",Qt=oS({csrfToken:De.csrfToken,onDiagnostic:t=>Bt("channel.diagnostic",t),url:e.toString()}),Qt.subscribeUpdates((t,r)=>PS(t,r)),Qt.connect()}catch{Qt?.dispose(),Qt=void 0}}function PS(e,t){Br.invalidate(e.account.revision),tb(xr,e.permissions)?t.type==="event"&&t.event==="status.changed"&&ur("status changed"):(xr=qh(e.permissions),CS())}function Uh(){if(yi?.close(),yi=void 0,!vt||Ae)return;const e=new EventSource(hS);yi=e,e.addEventListener("account-invalidated",()=>{Br.invalidate()}),e.addEventListener("account-revision",()=>{Br.invalidate()}),e.onopen=()=>{Ta.reset()},e.onerror=()=>{e.close(),Ta.schedule()}}async function kS(e){Gh(e)&&await ur("account revision changed")}async function CS(){Ae||(await ur("permission changed"),!Ae&&await Bn())}async function gc(){const e=await fetch(cS,{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(!We(t))throw new Error("Browser Dev Host bootstrap is invalid");const r=$h(t.mobileLaunchRedirect);if(Object.hasOwn(t,"mobileLaunchRedirect")&&t.mobileLaunchRedirect!==void 0&&!r)throw new Vr;return{openPlatformBaseUrl:typeof t.openPlatformBaseUrl=="string"?t.openPlatformBaseUrl:void 0,devReadiness:xS(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:Fu(t.devContext,t.runtimePermissions),browserDevContext:Fu(t.browserDevContext??t.devContext,t.runtimePermissions),lanAddresses:Array.isArray(t.lanAddresses)?t.lanAddresses.filter(eb):[],loginAvailable:t.loginAvailable===!0,miniProgram:QS(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:US(t.windowForm),hostPlatform:LS(t.hostPlatform)}}function LS(e){return yS.includes(e)?e:"unknown"}function US(e){if(!We(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 xS(e){if(!We(e))return;const t=s=>{if(!(!We(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||!We(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=>We(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 pc(e,t){const r=new Headers(t.headers);return r.set("content-type","application/json"),De.csrfToken&&r.set("x-hb-sdk-csrf",De.csrfToken),fetch(e,{...t,headers:r,cache:"no-store",credentials:"same-origin",redirect:"error"})}function zS(){yc(),Fe||(ya=window.setInterval(()=>{qS()},mS))}function xh(e=be.mobileLanSelect.options.length>0?be.mobileLanSelect.value:void 0){be.mobileLanSelect.replaceChildren();for(const t of Pt){const r=document.createElement("option");r.value=t.id,r.textContent=`${t.name} · ${t.address}`,be.mobileLanSelect.appendChild(r)}e&&Pt.some(({id:t})=>t===e)?be.mobileLanSelect.value=e:fi&&Pt.some(({id:t})=>t===fi)?be.mobileLanSelect.value=fi:Pt[0]&&(be.mobileLanSelect.value=Pt[0].id),be.mobileLanSelect.disabled=Pt.length===0}async function Bn(){if(Ae)return;const e=++St;if(Go(),Fe){const r=await Bu.toDataURL("hb-sdk-ui-preview",{width:tl,margin:1});if(e!==St||Ae||!Tt)return;be.mobileQrImage.src=r,be.mobileQrStatus.textContent="UI 预览示例,不用于真机连接";return}if(Je.source!=="remote"||!Je.localDevLaunchToken||Je.expiresAt!==void 0&&Je.expiresAt<=Date.now()){be.mobileQrImage.removeAttribute("src"),be.mobileQrStatus.textContent=lc||"需要有效的本地调试启动票";return}const t=XS();if(!t?.mobileAppQrPayload){be.mobileQrImage.removeAttribute("src"),be.mobileQrStatus.textContent="未发现可用的局域网地址";return}be.mobileQrStatus.textContent="正在生成二维码...";try{const r=await VS(t);if(e!==St||Ae)return;const n=await jS(r.address,r.expiresAt);if(e!==St||Ae)return;const i=await Bu.toDataURL(n.payload,{width:tl,margin:1});if(e!==St||Ae)return;be.mobileQrImage.src=i,be.mobileQrStatus.textContent=`${r.address.name} · ${r.address.address}`,$S(n.expiresAt,e)}catch(r){if(e!==St||Ae)return;if(r instanceof Vr){Ei();return}be.mobileQrImage.removeAttribute("src"),be.mobileQrStatus.textContent=Ec(r)}}async function jS(e,t){const r=e.mobileAppQrPayload;if(!r)throw new Error("Mobile 启动配置不可用");const n=await BS(e,r);if(!n)return{expiresAt:t,payload:r};try{return{expiresAt:Math.min(t,n.expiresAt),payload:PM(RM({host:e.address,port:location.port,token:n.token}))}}catch{throw new Vr}}async function BS(e,t){if(Dr?.addressId===e.id)return Dr;if(!Dr)return;const r=await pc(dS,{method:"POST",body:JSON.stringify({address_id:e.id,payload:t,previous_token:Dr.token})});if(!r.ok)throw new Vr;const n=await r.json(),i=We(n)?$h({addressId:n.address_id,expiresAt:n.expires_at,token:n.token}):void 0;if(!i||i.addressId!==e.id)throw new Vr;return Dr=i,mi={...mi,mobileLaunchRedirect:i},fc=Vo(mi),i}async function HS(e){const t=await gc(),r=FS(t,e),n=r?.mobileAppQrPayload;if(!r||!n)throw new Error("Mobile 启动配置不可用");return zh(t),{...r,mobileAppQrPayload:n}}function FS(e,t){return e.lanAddresses.find(({id:r})=>r===t)??e.lanAddresses.find(({id:r})=>r===e.defaultLanAddressId)??e.lanAddresses[0]}function zh(e){const t=Kt(Ue);q.devReadiness=e.devReadiness,q.miniProgramSupportsDesktop=e.miniProgramSupportsDesktop,q.miniProgramPlatforms=e.devContext.platforms??[],al(e.hostPlatform),cl(e.windowForm),hi=e.workspaceCardsEnabled,mi=e,fc=Vo(e),Je=e.devContext,br=e.browserDevContext,Ue=fn(br),xr=Bo(Ue),Eo(),Pt=e.lanAddresses,fi=e.defaultLanAddressId,Dr=e.mobileLaunchRedirect,lc=e.nativeAppLaunchUnavailableReason,gn=e.devSessionId,ma=e.miniProgramManifestAccessToken,Hh(Bh(e)),Tt&&xh(),yc(),t!==Kt(Ue)&&(Ot("local permission context changed"),Hr("local permission context changed"))}function Eo(){if(Fe){q.localPermissions=Im(),q.devContextWarning="";return}q.localPermissions=YM(Ue),q.devContextWarning=Ue.source==="anonymous"?"未连接线上上下文":Ue.warning?"本地上下文受限,请检查 CLI 状态":"",jr()}function yc(){let e;try{e=um(Dh)}catch{}const t=Je.miniProgramId?.trim().toLowerCase();let r=lc?.trim()??"";!r&&(Je.source!=="remote"||!t)&&(r="请先绑定可管理的小程序"),!r&&!Je.localDevLaunchToken?.trim()&&(r="正在等待有效的本地调试启动票"),!r&&hi&&!gn&&(r="本地调试会话尚未就绪"),!r&&Je.expiresAt!==void 0&&Je.expiresAt<=Date.now()&&(r="本地调试启动票已过期"),!r&&!e&&(r="未发现可用的本机调试地址"),ll({...e?{address:e}:{},...t?{miniProgramId:t}:{},...hi&&gn?{devSessionId:gn}:{},...ma?{miniProgramManifestToken:ma}:{},workspaceCardsEnabled:hi,ready:r==="",...r?{unavailableReason:r}:{}})}class Vr extends Error{}async function VS(e){const t=ol.then(()=>GS(e));return ol=t.then(()=>{},()=>{}),t}async function GS(e){const t=new URL(e.appUrl),r=new URL(YN,location.origin),n=await pc(r.pathname,{method:"POST",body:JSON.stringify({mini_url_origin:t.origin,runtime_permissions:KN(Je)})}),i=await n.json();if(!n.ok||!We(i)||typeof i.token!="string"||typeof i.expires_at!="number")throw new Error("创建 Mobile Dev Session 失败");return{address:await HS(e.id),expiresAt:i.expires_at}}function $S(e,t){gi=window.setTimeout(()=>{!Ae&&Tt&&t===St&&Bn()},Math.max(1e3,e-Date.now()-3e4))}async function qS(){if(!(zs||Ae)){zs=!0;try{const e=await gc();il=Date.now();const t=Sr;Sr=!1;const r=Vo(e);if(!t&&r===fc&&Kt(fn(e.browserDevContext))===Kt(Ue)){br=e.browserDevContext,Ue=fn(br),Eo();return}zh(e),t&&Hr("CLI dev session reconnected"),Tt&&Bn()}catch(e){e instanceof Vr&&Ei();const t=fn(br);Kt(t)!==Kt(Ue)&&(Ue=t,xr=Bo(Ue),Eo(),Ot("local permission context expired"),Hr("local permission context expired"),yc(),Tt&&Ei()),Date.now()-il>=3e4&&!Sr&&(Sr=!0,Ot("CLI dev session disconnected"),Qh("#device")?.replaceChildren(),q.runtimeStatus="closed",q.localPermissions=[],q.devContextWarning="调试会话已断开",ll({ready:!1,unavailableReason:"调试会话已断开"}),q.devReadiness={browser:{state:"blocked",reason:"调试会话已断开,等待 CLI 恢复"},mobile:{state:"blocked",reason:"调试会话已断开"},companion:{state:"blocked",reason:"调试会话已断开"}},Tt&&Ei())}finally{zs=!1}}}function Ei(){St+=1,Go(),be.mobileQrImage.removeAttribute("src"),be.mobileQrStatus.textContent="Mobile 短链接配置无效"}function Vo(e){return JSON.stringify({devReadiness:e.devReadiness,devSessionId:e.devSessionId,defaultLanAddressId:e.defaultLanAddressId,lanAddresses:e.lanAddresses,mobileLaunchRedirect:e.mobileLaunchRedirect?{addressId:e.mobileLaunchRedirect.addressId,expiresAt:e.mobileLaunchRedirect.expiresAt,token:e.mobileLaunchRedirect.token}:void 0,devContext:{platforms:e.devContext.platforms,permissionContext:Kt(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 jh(){if(!Rn){q.account={authenticated:!1,avatar:"",nickname:"未登录"};return}q.account={authenticated:!0,avatar:Sa??"",nickname:Ma||vt||"已登录"}}function Bh(e){if(e.miniProgram?.miniProgramId)return e.miniProgram;const t=e.devContext.miniProgramId?.trim();return t?{miniProgramId:t}:e.miniProgram??null}function Hh(e){if(!!!e?.miniProgramId||!e){q.miniProgram={bound:!1,id:"",iconUrl:"",name:"未绑定小程序",detail:"本地调试",description:"",version:""},jr();return}q.miniProgram={bound:!0,id:e.miniProgramId,iconUrl:e.iconUrl??"",name:e.name||e.miniProgramId,detail:[e.miniProgramId,e.version].filter(Boolean).join(" · "),description:e.description??"",version:e.version??""},jr()}function QS(e){if(e===null)return null;if(!We(e))return;const t=Re(e.miniProgramId)??Re(e.mini_program_id);if(t)return{miniProgramId:t,...Re(e.description)?{description:Re(e.description)}:{},...Re(e.name)?{name:Re(e.name)}:{},...Re(e.iconUrl)??Re(e.icon_url)?{iconUrl:Re(e.iconUrl)??Re(e.icon_url)}:{},...Re(e.status)?{status:Re(e.status)}:{},...Re(e.version)?{version:Re(e.version)}:{},...Re(e.developerName)??Re(e.developer_name)?{developerName:Re(e.developerName)??Re(e.developer_name)}:{}}}function Re(e){return typeof e=="string"&&e.trim()?e.trim():void 0}async function kn(){const e=++ga;pa?.abort();const t=new AbortController;pa=t;const r=pn.value,n=!r||r===q.diagnosticTargetId,i=ii.value,o=Gs.value||(n?He?.instanceId:void 0),s=()=>!Ae&&e===ga&&r===pn.value&&o===(Gs.value||(n?He?.instanceId:void 0));if(!n&&(!i||!o||i.stale||i.state!=="attached"||!i.capabilities.storage)){q.storage=[],q.storageError=!i||!i.capabilities.storage?"当前设备不支持存储诊断":"当前设备未连接或没有运行实例";return}if(Fe){q.storage=[{area:"local",key:"preferences",serializedValue:'{"theme":"light","language":"zh-CN"}',bytes:36},{area:"local",key:n?"lastOpenedProject":"deviceModel",serializedValue:n?'"demo-project"':'"iPhone 16 Pro"',bytes:n?14:15}],q.storageError="";return}if(!o){q.storage=[],q.storageError="";return}try{const a=await lm({instanceId:o,resource:"storage"},{csrfToken:De.csrfToken,signal:AbortSignal.any([t.signal,ar.signal])});if(!s())return;if(a.code)throw new Error(a.error??"Storage 诊断查询失败");q.storage=a.value,q.storageError=""}catch(a){if(!s())return;q.storage=[],q.storageError=Ec(a)}}function Fh(e,t=He){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 Xt(e,t,r=Date.now(),n,i){YS(qs(e,t,r,n==="debug"?"log":n),i)}function YS(e,t){if(Ae)return;if(Fe){$s({...e,targetId:q.diagnosticTargetId});return}const r=We(e.detail)?e.detail:{};ct.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}:{},...We(r.network)?{network:r.network}:{}})}async function WS(e){const t=He;if(!t||e.instanceId!==t.instanceId||!Be(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!Be(t)||r!==t.runtime||e.instanceId!==t.instanceId?{code:"closed",error:"查询期间实例已结束"}:{value:s}}function ZS(e,t){Bt("host.message",{message:e,status:t})}function KS(e){Ae||ZS(Ec(e),"error")}function Bt(e,t){Xt(e,t)}function JS(){ct.close(),va!==void 0&&window.clearTimeout(va),Oa!==void 0&&window.clearTimeout(Oa),!Ae&&(Ae=!0,pi.dispose(),Ea.dispose(),window.__HB_SDK_PREVIEW__===Nh&&delete window.__HB_SDK_PREVIEW__,window.removeEventListener("hb-sdk:refresh-storage",kn),window.removeEventListener("hb-sdk:qr-open-change",vh),Fo+=1,ar.abort(new DOMException("Browser Dev Host disposed","AbortError")),Br.dispose(),Ot("Browser Dev Host disposed"),_t.dispose(),ct.send({operation:"close-target",reason:"Browser Dev Host disposed"}),window.setTimeout(()=>Ih.abort(),2e3),yi?.close(),Qt?.dispose(),Qt=void 0,Ta.dispose(),At!==void 0&&window.clearTimeout(At),At=void 0,Go(),ya!==void 0&&window.clearInterval(ya),po.clear(),wa?.(),wa=void 0,Ia?.(),Ia=void 0,Aa?.(),Aa=void 0,_a?.(),_a=void 0,Da?.(),Da=void 0,Na?.(),Na=void 0)}function Go(){gi!==void 0&&window.clearTimeout(gi),gi=void 0}function Vh(e,t){return t?AbortSignal.any([e,t]):e}function Gh(e){return!Ae&&e===Fo}function XS(){return Pt.find(({id:e})=>e===be.mobileLanSelect.value)}function eb(e){return We(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 $h(e){if(!(!We(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 qh(e){return{networkRequest:{...e.networkRequest}}}function tb(e,t){return e.networkRequest.status===t.networkRequest.status&&e.networkRequest.useOfficialDomain===t.networkRequest.useOfficialDomain}function Ec(e){return e instanceof Error&&e.message?e.message:"操作失败"}function We(e){return Object.prototype.toString.call(e)==="[object Object]"}function ni(e){const t=document.querySelector(e);if(!t)throw new Error(`Missing Browser Dev Host element: ${e}`);return t}function Qh(e){return document.querySelector(e)??void 0}