@heybox/hb-sdk 0.9.9-alpha.0 → 0.9.9-alpha.2
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.
- package/CHANGELOG.md +16 -0
- package/README.md +2 -0
- package/dist/cli-chunks/{build-Vi5Zyplz.cjs → build-BlDpuz8v.cjs} +5 -5
- package/dist/cli-chunks/{create-Cfz1IcYf.cjs → create-BQbqb-ph.cjs} +2 -2
- package/dist/cli-chunks/{dev-C2dtgF42.cjs → dev-U8fYtFNt.cjs} +15 -10
- package/dist/cli-chunks/{doctor-D-zMCLIA.cjs → doctor-CGJfat87.cjs} +1 -1
- package/dist/cli-chunks/{game-binding-guide-z3X6h8ck.cjs → game-binding-guide-C0fNljyC.cjs} +3 -3
- package/dist/cli-chunks/{game-bindings-DiVP8PdD.cjs → game-bindings-Dun_g-3H.cjs} +4 -4
- package/dist/cli-chunks/{games-THhcga6y.cjs → games-C6qjqKus.cjs} +1 -1
- package/dist/cli-chunks/{index-BuYCoach.cjs → index-D9duvEkQ.cjs} +1 -1
- package/dist/cli-chunks/{index-H9U6-mLY.cjs → index-DcyYtbXh.cjs} +40 -25
- package/dist/cli-chunks/{index.esm-XiyiK7eH.cjs → index.esm-CdNQ_kHI.cjs} +9 -9
- package/dist/cli-chunks/{index.esm-D8lqHXUQ.cjs → index.esm-CenYK5Bl.cjs} +72 -3
- package/dist/cli-chunks/{login-Bw_1UJ8i.cjs → login-P7RtNdwf.cjs} +1 -1
- package/dist/cli-chunks/{project-vite-CFfq-fV7.cjs → project-vite-BH7q_pzh.cjs} +1 -1
- package/dist/cli-chunks/{remote-CU88U8t8.cjs → remote-D39sRE7v.cjs} +142 -26
- package/dist/cli-chunks/{runtime-permission-env-BtxzR-dv.cjs → runtime-permission-env-CZNyFKnx.cjs} +24 -4
- package/dist/cli-chunks/{skill-7RZJxGDO.cjs → skill-Dm6lUW7l.cjs} +2 -2
- package/dist/cli-chunks/{version-COTSItDf.cjs → version-7t_EYjo_.cjs} +1 -1
- package/dist/cli.cjs +1 -1
- package/dist/devtools/browser-dev-host/assets/browser-dev-host-D52x803m.js +224 -0
- package/dist/devtools/browser-dev-host/assets/{desktop-app-launch-az2quV7I.js → desktop-app-launch-BNPRuxe6.js} +1 -1
- package/dist/devtools/browser-dev-host/assets/{index-o5r5oqtq.js → index-t_066TMb.js} +3 -3
- package/dist/devtools/browser-dev-host/index.html +2 -2
- package/dist/index.cjs.js +149 -4
- package/dist/index.esm.js +149 -5
- package/dist/miniapp-publish.cjs.js +64 -1
- package/dist/miniapp-publish.esm.js +63 -2
- package/dist/protocol.cjs.js +51 -5
- package/dist/protocol.esm.js +51 -5
- package/dist/vite.cjs.js +59 -2
- package/dist/vite.esm.js +59 -2
- package/package.json +7 -7
- package/skill/skill.json +4 -4
- package/types/index.d.ts +140 -4
- package/types/miniapp-publish/index.d.ts +14 -3
- package/dist/devtools/browser-dev-host/assets/browser-dev-host-CHdD15qt.js +0 -221
|
@@ -1,221 +0,0 @@
|
|
|
1
|
-
import{m as Ff,H as Qa,b0 as Bf,bC as Vf,a5 as Gf,bj as $f,bk as Qf,n as ct,bM as B,bc as su,l as au,aO as qf,e as qa,aT as Yf,aF as Wf,k as Zf,ar as un,aP as Kf,bG as Br,a_ as ln,aZ as gs,a$ as Xn,b4 as cu,b6 as Xf,f as hi,w as Jf,$ as oa,aS as eh,j as ps,av as ys,h as th,bg as du,aK as rh,o as Ya,I as nh,b2 as uu,X as ih,A as oh,aH as sh,z as ah,bd as ch,bE as lu,bD as fu,b8 as dh,g as Es,aJ as uh,b as qt,c as lh}from"./desktop-app-launch-az2quV7I.js";function fh(){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 hh(){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 xn={device:'[data-preview-target="device"]',screen:'[data-preview-target="screen"]',app:"#device iframe",workbench:'[data-testid="workbench-root"]'},Wa=15e3,mh=32*1024*1024,Za="data-hb-preview-capture-device",zo="data-hb-preview-capture-ancestor",Ka="data-hb-preview-capture-surface",Xa=64,gh=1024;function ph(e={}){const t=e.document??globalThis.document,r=t.defaultView,n=e.leaseMs??Wa;if(!Number.isFinite(n)||n<=0||n>Wa)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:p,name:m,previous:E}of u.attributes)p.getAttribute(m)===d&&(E===null?p.removeAttribute(m):p.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 p=f.getBoundingClientRect();return["left","top","width","height"].every(m=>Math.abs(p[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(xn,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>mh)throw Ve("INVALID_CAPTURE_IMAGE","共享窗口冻结图无效或过大");if(i)throw Ve("PREVIEW_BUSY","已有设备截图正在执行");const f=t.querySelectorAll(xn.device);if(f.length!==1)throw Ve("DEVICE_NOT_UNIQUE","设备画面不唯一或尚未创建");const l=f[0],p=d.scope==="device"?l:t.querySelector(xn[d.scope]);if(!p||p!==l&&!l.contains(p))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",j=>j.preventDefault(),{passive:!1}),E.addEventListener("touchmove",j=>j.preventDefault(),{passive:!1});const w=Math.min(Date.now()+n,d.deadlineAt),I={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:w};i=I,I.timer=setTimeout(()=>s(I.token),Math.max(0,w-Date.now()));const v=()=>s(I.token);u?.addEventListener("abort",v,{once:!0}),I.removeAbort=()=>u?.removeEventListener("abort",v);const y=()=>{const{viewport:j}=I;(r.innerWidth!==j.width||r.innerHeight!==j.height||r.devicePixelRatio!==j.devicePixelRatio)&&s(I.token)};r.addEventListener("resize",y),I.removeResize=()=>r.removeEventListener("resize",y);const O=()=>{if(u?.throwIfAborted(),i!==I||Date.now()>=w)throw Ve("CAPTURE_EXPIRED","截图布局租约已结束,请重新截图")};try{E.src=d.previewImage,await E.decode(),O();const j=I.token,b=`[${Za}="${j}"]`,T=r.getComputedStyle(l),D=new r.DOMMatrixReadOnly(T.transform==="none"?void 0:T.transform),x=Math.atan2(D.b,D.a),P=l.querySelector(".desktop-window__surface"),Q=P?P.offsetWidth:Number.parseFloat(T.width),R=P?P.offsetHeight:Number.parseFloat(T.height),L=T.backgroundColor,C=r.getComputedStyle(t.body).backgroundColor,z=ye=>!ye||ye==="transparent"||ye==="rgba(0, 0, 0, 0)",k=z(L)?z(C)?"#fff":C:L;if(!(Q>0&&R>0))throw Ve("CAPTURE_TARGET_UNAVAILABLE","设备布局尺寸无效");O(),t.body.append(E),o(I,l,Za),P&&o(I,P,Ka);for(let ye=l.parentElement;ye;ye=ye.parentElement)o(I,ye,zo);const S=t.createElement("style");I.style=S;const M=`
|
|
2
|
-
[${zo}="${j}"] {overflow:visible!important;scrollbar-width:none!important;}
|
|
3
|
-
[${zo}="${j}"]::-webkit-scrollbar {display:none!important;}
|
|
4
|
-
[${Ka}="${j}"] {transform:none!important;transition:none!important;}
|
|
5
|
-
`,H=(ye,Oe,Me=0,Pe=0)=>`${b} {position:absolute!important;left:${ye}px!important;top:${Oe}px!important;width:${Q}px!important;height:${R}px!important;transform:translate(${Me}px,${Pe}px) rotate(${x}rad)!important;transition:none!important;z-index:2147483646!important;background-color:${k}!important;}`;S.textContent=M+H(0,0),O(),t.head.append(S);const F=l.getBoundingClientRect(),$=t.querySelector(xn.app),K=$&&l.contains($)?$.getBoundingClientRect():void 0,h=K&&K.width>0&&K.height>0?K:void 0,N=h?Math.floor(r.innerWidth-1-(h.left-F.left)):r.innerWidth+64,U=h?Math.floor(r.innerHeight-1-(h.top-F.top)):32,q=N-F.left,ae=U-F.top;O(),S.textContent=M+H(q,ae);const de=l.getBoundingClientRect();S.textContent=M+H(q,ae,N-de.left,U-de.top),O();const ce=p.getBoundingClientRect(),le=Math.floor(ar(ce.left+r.scrollX)),Ee=Math.floor(ar(ce.top+r.scrollY)),me={x:le,y:Ee,width:Math.ceil(ar(ce.right+r.scrollX))-le,height:Math.ceil(ar(ce.bottom+r.scrollY))-Ee};if(!(me.width>0&&me.height>0)||me.x<0||me.y<0)throw Ve("CAPTURE_LAYOUT_INVALID","无法建立完整设备截图布局");if(h&&$){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(ar(Oe.left))-1,Pe=Math.floor(ar(Oe.top))-1,je=r.innerWidth-Me,Ft=r.innerHeight-Pe;if(Me<0||Pe<0||je<=0||Ft<=0||je>Xa||Ft>Xa||je*Ft>gh)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:je,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;`,I.bounds=ge,O(),t.body.append(ge),I.target=p,I.rect=ce,await yh(r,u),O(),!a(I))throw Ve("CAPTURE_LAYOUT_INVALID","截图准备期间布局发生变化,请重新截图");I.observer=new r.ResizeObserver(()=>{i===I&&!a(I)&&s(I.token)});for(const{element:ye}of I.attributes)I.observer.observe(ye);return{token:j,clip:me,devicePixelRatio:r.devicePixelRatio,expiresAt:w}}catch(j){throw s(I.token),j}}return{prepare:c,restore:s,cancel:d=>i?.operationId!==d?!1:(s(i.token),!0),dispose:()=>{i&&s(i.token)}}}function yh(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 ar(e){const t=Math.round(e);return Math.abs(e-t)<.001?t:e}const sa="user.games.getOverview",mi="user.data.query",nn="user.data.sync",gi="user.data.file",aa="user.dataPermission.request",ca="user.dataPermission.get",da="user.dataPermission.set",ua="user.dataPermission.openSettings",la="user.dataPermission.revokeSession",hu=[sa,mi,nn,gi,aa,ca,da,ua,la],pi="workspaceCards.requestRefresh",yi="auth.getAccountState",Ei="auth.login",wi="user.getFollowStatus",Ii="user.requestFollowAuthor",Eh="gameSaves.list",wh="gameSaves.sync",Ih="gameSaves.getFile",Ah="gameSaves.readParsedData",Ai="user.getInfo",_i="user.revokeAuthorization",Di="user.getSteamGameList",fn="user.showAppreciation",Ni="share.copyLink",Mi="share.showShareMenu",bi="share.screenshot",Si="share.screenshotLong",rr="viewport.setDisplay",Ti="viewport.getWindowInfo",vi="viewport.setNavigationBarStyle",hn="storage.getStorage",mn="storage.setStorage",Oi="network.request",Ri="network.download",ki="network.upload",Pi="files.pickFiles",Li="files.pickDirectory",Ci="files.saveFile",gn="file.create",pn="file.remove",xi="file.exists",yn="file.readText",Ui="file.writeText",En="file.readBytes",ji="file.writeBytes",wn="file.stat",zi="directory.create",In="directory.remove",Hi="directory.exists",Fi="directory.list",An="media.pick",Bi="ui.showToast",Vi="ui.showLoading",Gi="ui.hideLoading",$i="device.vibrate",Qi="device.setClipboard",qi="device.executeProtocol",Yi="navigation.close",Wi="navigation.reload",Zi="navigation.openAppPage",St="cloud.leaderboard.submit",at="cloud.leaderboard.getList",Ct="cloud.leaderboard.getCurrentUserEntry",nr="cloud.leaderboard.deleteCurrentUserEntry",Et="cloud.leaderboard.getInfo",Nr="cloud.storage.getStorage",Mr="cloud.storage.setStorage",br="cloud.storage.removeItem",ir="cloud.storage.getKeys",ho="companion.getInfo",mo="companion.getPreparationStatus",go="companion.prepare",po="companion.cancelPreparation",yo="companion.getActiveSession",Eo="companion.launch",wo="companion.session.write",Io="companion.session.closeStdin",Ao="companion.session.terminate",_o="companion.session.ackOutput",Do="companion.openAttachment",No="companion.showNotification",xt=[...[Eh,wh,Ih,Ah].map(e=>({method:e,module:"gameSaves",capability:e,requirement:{kind:"all",permissions:["gameSaves"]},risk:"high"})),...hu.map(e=>({method:e,module:"userGameData",capability:e,requirement:{kind:"all",permissions:["user_game_data"]},risk:"high"})),{method:pi,module:"workspaceCards",capability:pi,requirement:{kind:"all",permissions:["workspaceCards"]},risk:"high"},{method:yi,module:"auth",capability:yi,requirement:{kind:"none"},risk:"low"},{method:Ei,module:"auth",capability:Ei,requirement:{kind:"all",permissions:["userInfo"]},risk:"medium"},{method:wi,module:"user",capability:wi,requirement:{kind:"none"},risk:"low"},{method:Ii,module:"user",capability:Ii,requirement:{kind:"none"},risk:"high"},{method:Ai,module:"user",capability:Ai,requirement:{kind:"all",permissions:["userInfo"]},risk:"medium"},{method:_i,module:"user",capability:_i,requirement:{kind:"none"},risk:"high"},{method:Di,module:"user",capability:Di,requirement:{kind:"all",permissions:["steamLibrary"]},risk:"high"},{method:fn,module:"user",capability:fn,requirement:{kind:"none"},risk:"medium"},{method:Ni,module:"share",capability:Ni,requirement:{kind:"all",permissions:["share"]},risk:"medium"},{method:Mi,module:"share",capability:Mi,requirement:{kind:"all",permissions:["share"]},risk:"low"},{method:bi,module:"share",capability:bi,requirement:{kind:"all",permissions:["share"]},risk:"medium"},{method:Si,module:"share",capability:Si,requirement:{kind:"all",permissions:["share"]},risk:"medium"},{method:Ti,module:"viewport",capability:Ti,requirement:{kind:"none"},risk:"low"},{method:vi,module:"viewport",capability:vi,requirement:{kind:"none"},risk:"low"},{method:rr,module:"viewport",capability:rr,requirement:{kind:"none"},risk:"low"},{method:hn,module:"storage",capability:hn,requirement:{kind:"all",permissions:["storage"]},risk:"low"},{method:mn,module:"storage",capability:mn,requirement:{kind:"all",permissions:["storage"]},risk:"medium"},{method:Oi,module:"network",capability:Oi,requirement:{kind:"all",permissions:["network"]},risk:"high"},{method:Ri,module:"network",capability:Ri,requirement:{kind:"all",permissions:["network","filesystem"]},risk:"high"},{method:ki,module:"network",capability:ki,requirement:{kind:"all",permissions:["network","filesystem"]},risk:"high"},{method:Pi,module:"files",capability:Pi,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Li,module:"files",capability:Li,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Ci,module:"files",capability:Ci,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:gn,module:"file",capability:gn,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:pn,module:"file",capability:pn,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:xi,module:"file",capability:xi,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:yn,module:"file",capability:yn,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Ui,module:"file",capability:Ui,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:En,module:"file",capability:En,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:ji,module:"file",capability:ji,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:wn,module:"file",capability:wn,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:zi,module:"directory",capability:zi,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:In,module:"directory",capability:In,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Hi,module:"directory",capability:Hi,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:Fi,module:"directory",capability:Fi,requirement:{kind:"all",permissions:["filesystem"]},risk:"high"},{method:An,module:"media",capability:An,requirement:{kind:"all",permissions:["media"]},risk:"high"},{method:Bi,module:"ui",capability:Bi,requirement:{kind:"none"},risk:"low"},{method:Vi,module:"ui",capability:Vi,requirement:{kind:"none"},risk:"low"},{method:Gi,module:"ui",capability:Gi,requirement:{kind:"none"},risk:"low"},{method:$i,module:"device",capability:$i,requirement:{kind:"none"},risk:"low"},{method:Qi,module:"device",capability:Qi,requirement:{kind:"all",permissions:["clipboard"]},risk:"medium"},{method:qi,module:"device",capability:qi,requirement:{kind:"all",permissions:["appProtocol"]},risk:"high"},{method:Yi,module:"navigation",capability:Yi,requirement:{kind:"none"},risk:"medium"},{method:Wi,module:"navigation",capability:Wi,requirement:{kind:"none"},risk:"medium"},{method:Zi,module:"navigation",capability:Zi,requirement:{kind:"none"},risk:"medium"},{method:St,module:"cloud",capability:St,requirement:{kind:"all",permissions:["leaderboard"]},risk:"medium"},{method:at,module:"cloud",capability:at,requirement:{kind:"all",permissions:["leaderboard"]},risk:"low"},{method:Ct,module:"cloud",capability:Ct,requirement:{kind:"all",permissions:["leaderboard"]},risk:"medium"},{method:nr,module:"cloud",capability:nr,requirement:{kind:"all",permissions:["leaderboard"]},risk:"medium"},{method:Et,module:"cloud",capability:Et,requirement:{kind:"all",permissions:["leaderboard"]},risk:"low"},{method:Nr,module:"cloud",capability:Nr,requirement:{kind:"all",permissions:["cloud_storage"]},risk:"low"},{method:Mr,module:"cloud",capability:Mr,requirement:{kind:"all",permissions:["cloud_storage"]},risk:"medium"},{method:br,module:"cloud",capability:br,requirement:{kind:"all",permissions:["cloud_storage"]},risk:"medium"},{method:ir,module:"cloud",capability:ir,requirement:{kind:"all",permissions:["cloud_storage"]},risk:"low"},...[ho,mo,go,po,yo,Eo,wo,Io,Ao,_o,Do,No].map(e=>({method:e,module:"companion",capability:e,requirement:{kind:"all",permissions:["companion"]},risk:"high"}))],Gt="heybox:miniprogram",mu=2,gu="hb_mini_bridge_nonce",pu="sdk.handshake",Un="runtime.location.probe",_h="sdk.location.report",Dh="sdk.csp.violation",yu="operation.progress",Nh="companion.session.output",Mh="companion.session.exit",bh="companion.session.ownershipLost";function Sh(e){return!ut(e)||e.namespace!==Gt||e.version!==1&&e.version!==2||!ke(e.nonce)?!1:e.type==="handshake"?ke(e.id)&&e.method===pu&&e.error===void 0&&Ch(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||xh(e.error)):e.type==="event"?!ke(e.method)||e.error!==void 0?!1:e.method===yu?e.version===2&&ke(e.id)&&Lh(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 fa(e){return typeof e!="string"||!e||e.startsWith("/")||e.endsWith("/")||/[\\\u0000-\u001f\u007f]/.test(e)?!1:e.split("/").every(t=>!!t&&t!=="."&&t!=="..")}function Eu(e){return ut(e)?e.kind==="sandbox"?rt(e,["kind"]):e.kind==="directory"&&ke(e.handleId)&&rt(e,["kind","handleId"]):!1}function Jt(e){return!ut(e)||e.kind!=="file"?!1:ke(e.handleId)?rt(e,["kind","handleId"]):Eu(e.root)&&fa(e.relativePath)&&rt(e,["kind","root","relativePath"])}function wu(e){return!ut(e)||e.kind!=="directory"?!1:ke(e.handleId)?rt(e,["kind","handleId"]):Eu(e.root)&&(e.relativePath==="."||fa(e.relativePath))&&rt(e,["kind","root","relativePath"])}function Th(e){return ut(e)&&e.kind==="file"&&ke(e.name)&&Uh(e.mode)&&Jt(e.ref)&&rt(e,["kind","name","mode","ref"])}const Iu=20,Ja=["type","mimeType","size","width","height","previewUrl","file"];function vh(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&&(!jh(e.maxCount,1,Iu)||e.source==="camera"&&e.maxCount!==1))}function Au(e){if(!ut(e)||e.type!=="image"&&e.type!=="video")return!1;const t=e.type==="video";return!rt(e,t?[...Ja,"durationMs"]:Ja)||!ke(e.mimeType)||!kt(e.size)||!ec(e.width)||!ec(e.height)||!ke(e.previewUrl)||!Rh(e.file)?!1:t?kt(e.durationMs):!0}function Oh(e){if(!Array.isArray(e)||e.length<1||e.length>Iu)return!1;for(let t=0;t<e.length;t+=1)if(!Object.prototype.hasOwnProperty.call(e,t)||!Au(e[t]))return!1;return!0}function Rh(e){return!Th(e)||e.mode!=="read"?!1:e.ref.kind==="file"&&"handleId"in e.ref&&ke(e.ref.handleId)}function _u(e){return e instanceof Uint8Array&&e.buffer instanceof ArrayBuffer}function kh(e){return!ut(e)||!kt(e.loaded)||typeof e.lengthComputable!="boolean"||!rt(e,["loaded","total","lengthComputable"])?!1:e.lengthComputable?kt(e.total)&&e.loaded<=e.total:e.total===void 0}function Ph(e){return ut(e)?e.phase==="downloading"?kt(e.loaded)&&(e.total===void 0||kt(e.total)&&e.loaded<=e.total)&&rt(e,["phase","loaded","total"]):e.phase!=="verifying"&&e.phase!=="extracting"?!1:kt(e.processed)&&kt(e.total)&&e.processed<=e.total&&rt(e,["phase","processed","total"]):!1}function Lh(e){return kh(e)||Ph(e)}function Ch(e){return ut(e)&&ke(e.href)&&typeof e.userAgent=="string"&&ke(e.sdkVersion)}function xh(e){return ut(e)&&ke(e.code)&&typeof e.message=="string"}function Uh(e){return e==="read"||e==="readwrite"}function kt(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function ec(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>0}function jh(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 Du={ark:"明日方舟",black_myth_wukong:"黑神话悟空",task_bar_hero:"任务栏英雄",phantom_blade_zero:"影之刃零"},Nu=Object.keys(Du),er=[{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}],Yt=er.map(e=>e.key),zh=new Set(Yt),Hh=new Set(Nu);function Rt(e){return zh.has(e)}function tc(e){return Hh.has(e)}function ha(e){const t=er.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 Fh="同步时,原始存档将上传至小黑盒;向小程序提供原始文件仍需单独许可。",or=["userInfo","steamLibrary","share","storage","cloud_storage","gameSaves","filesystem","media","clipboard","leaderboard","network","companion","appProtocol","workspaceCards","user_game_data"],ma=[{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:Yt,description:"精确资源声明对象;每项必须填写 1~30 个 Unicode 码点的 purpose,不接受通配符或未开放资源。"}},methods:hu,conditions:["逐项声明资源与用途,读取前需用户许可;未取得许可不查询个人来源。","文件与解析结果分别许可;本次许可仅当前实例有效,持久许可保存在本机。","同步会将原存档上传至小黑盒,向小程序交付原文件仍需 `save_files` 许可。","平台取数不授予小程序 `network` 权限;已交付的数据副本无法撤回。"]}];new Set(or);const Bh=30;function Vh(e){if(typeof e!="string")throw new Error("purpose 必须是字符串");const t=e.trim(),r=Array.from(t);if(r.length<1||r.length>Bh)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 _n(e){return Mu(e,!1)}function Gh(e){return Mu(e,!0)}function Mu(e,t){if(!rc(e))throw new Error("resources 必须是资源声明对象;每项资源必须填写 purpose");const r={};for(const n of Object.keys(e).sort()){const i=e[n];if(!rc(i)||Object.keys(i).length!==1||!Object.prototype.hasOwnProperty.call(i,"purpose"))throw new Error(`resources.${n} 必须且只能包含 purpose`);let o;try{o=Vh(i.purpose)}catch(s){throw new Error(`resources.${n}: ${s.message}`)}if(!Rt(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 $h(e){return Yt.filter(t=>Object.prototype.hasOwnProperty.call(e,t))}function rc(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function bu(e,t,r,n){return JSON.stringify(["user-game-data-purpose-v1",e,t,r,n])}const Qh=new Set(or);function qh(e){return Qh.has(e)}function Qe(e){if(!Vr(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(!Vr(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),!!qh(o)){if(o==="network"){const s=n.config;if(!Vr(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(!Vr(s))return{valid:!1,permissions:{}};try{const a=Gh(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&&(!Vr(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 Vr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const Jn=["network","companion","appProtocol"];function Su(e){if(!Gr(e,["schema_version","revision","entries"])||e.schema_version!==1||typeof e.revision!="number"||!Number.isSafeInteger(e.revision)||e.revision<0||!Array.isArray(e.entries)||e.entries.length>Jn.length)return{valid:!1};const t=[],r=new Set;for(const n of e.entries){if(!Gr(n,["key","status","config"])||n.status!=="enabled")return{valid:!1};if(typeof n.key!="string"||r.has(n.key))return{valid:!1};if(r.add(n.key),n.key==="network"){if(!Gr(n.config,["useOfficialDomain"])||n.config.useOfficialDomain!==!1)return{valid:!1};t.push({key:"network",status:"enabled",config:{useOfficialDomain:!1}})}else if(n.key==="companion"){if(!Gr(n.config,[]))return{valid:!1};t.push({key:"companion",status:"enabled",config:{}})}else if(n.key==="appProtocol"){if(!Gr(n.config,[]))return{valid:!1};t.push({key:"appProtocol",status:"enabled",config:{}})}else return{valid:!1}}return t.sort((n,i)=>Jn.indexOf(n.key)-Jn.indexOf(i.key)),{valid:!0,grant:{schema_version:1,revision:e.revision,entries:t}}}function Yh(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 Jn)!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 ga(e){const t=Qe(e.runtimePermissions),r=Su(e.localDevGrant),n=t.valid?t.permissions:{};for(const s of or)e.declaredPermissions[s]?.enabled!==!0?delete n[s]:ma.some(a=>a.key===s&&a.access==="declaration")?n[s]={key:s,status:"enabled",config:Wh(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=Tu(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:or.flatMap(s=>n[s]?[n[s]]:[])},temporaryPermissionKeys:i,grantValid:r.valid}}function Wh(e,t){const r=ma.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"?_n(t[e]?.resources):{});return n}function Tu(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Gr(e,t){return Tu(e)&&Object.keys(e).length===t.length&&t.every(r=>Object.prototype.hasOwnProperty.call(e,r))}const Sr=["identity","profile","steam_account"],Zh=/^[a-z][a-z0-9-]{0,31}$/,vu=["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 nc;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 on extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}(nc=globalThis).__zod_globalConfig??(nc.__zod_globalConfig={});const ic=globalThis.__zod_globalConfig;function zr(e){return e&&Object.assign(ic,e),ic}function Kh(e,t){return typeof t=="bigint"?t.toString():t}function Xh(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function Ou(e){const t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}const oc=Symbol("evaluating");function qe(e,t,r){let n;Object.defineProperty(e,t,{get(){if(n!==oc)return n===void 0&&(n=oc,n=r()),n},set(i){Object.defineProperty(e,t,{value:i})},configurable:!0})}const Ru="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function Jh(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function sc(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function em(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 tm(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}const rm={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 Jr(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 nm(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 ku(e,t){return t.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(e),r})}function jn(e){return typeof e=="string"?e:e?.message}function vn(e,t,r){const n=e.message?e.message:jn(e.inst?._zod.def?.error?.(e))??jn(t?.error?.(e))??jn(r.customError?.(e))??jn(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 Pu=(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,Kh,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},im=_e("$ZodError",Pu),Mo=_e("$ZodError",Pu,{Parent:Error}),om=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 on;if(s.issues.length){const a=new(i?.Err??e)(s.issues.map(c=>vn(c,o,zr())));throw Ru(a,i?.callee),a}return s.value},sm=om(Mo),am=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=>vn(c,o,zr())));throw Ru(a,i?.callee),a}return s.value},cm=am(Mo),dm=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 on;return o.issues.length?{success:!1,error:new(e??im)(o.issues.map(s=>vn(s,i,zr())))}:{success:!0,data:o.value}},Lu=dm(Mo),um=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=>vn(s,i,zr())))}:{success:!0,data:o.value}},Cu=um(Mo),lm=e=>{const t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},fm=/^-?\d+$/,hm=/^-?\d+(?:\.\d+)?$/,mm=/^null$/i,bo=_e("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),xu={number:"number",bigint:"bigint",object:"date"},gm=_e("$ZodCheckLessThan",(e,t)=>{bo.init(e,t);const r=xu[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})}}),pm=_e("$ZodCheckGreaterThan",(e,t)=>{bo.init(e,t);const r=xu[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})}}),ym=_e("$ZodCheckNumberFormat",(e,t)=>{bo.init(e,t),t.format=t.format||"float64";const r=t.format?.includes("int"),n=r?"int":"number",[i,o]=rm[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=fm)}),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})}}),Em=_e("$ZodCheckStringFormat",(e,t)=>{var r,n;bo.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=()=>{})}),wm=_e("$ZodCheckRegex",(e,t)=>{Em.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})}}),Im={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=Im;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=Jr(s),u;for(const f of a){if(f._zod.def.when){if(nm(s)||!f._zod.def.when(s))continue}else if(d)continue;const l=s.issues.length,p=f._zod.check(s);if(p instanceof Promise&&c?.async===!1)throw new on;if(u||p instanceof Promise)u=(u??Promise.resolve()).then(async()=>{await p,s.issues.length!==l&&(d||(d=Jr(s,l)))});else{if(s.issues.length===l)continue;d||(d=Jr(s,l))}}return u?u.then(()=>s):s},o=(s,a,c)=>{if(Jr(s))return s.aborted=!0,s;const d=i(a,n,c);if(d instanceof Promise){if(c.async===!1)throw new on;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 on;return c.then(d=>i(d,n,a))}return i(c,n,a)}}qe(e,"~standard",()=>({validate:i=>{try{const o=Lu(e,i);return o.success?{value:o.data}:{issues:o.error?.issues}}catch{return Cu(e,i).then(s=>s.success?{value:s.data}:{issues:s.error?.issues})}},vendor:"zod",version:1}))}),Am=_e("$ZodString",(e,t)=>{lt.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??lm(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}}),Uu=_e("$ZodNumber",(e,t)=>{lt.init(e,t),e._zod.pattern=e._zod.bag.pattern??hm,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}}),_m=_e("$ZodNumberFormat",(e,t)=>{ym.init(e,t),Uu.init(e,t)}),Dm=_e("$ZodNull",(e,t)=>{lt.init(e,t),e._zod.pattern=mm,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}}),Nm=_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 ac(e,t,r){e.issues.length&&t.issues.push(...ku(r,e.issues)),t.value[r]=e.value}const Mm=_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=>ac(d,r,s))):ac(c,r,s)}return o.length?Promise.all(o).then(()=>r):r}});function Ki(e,t,r,n,i,o){const s=r in n;if(e.issues.length){if(i&&o&&!s)return;t.issues.push(...ku(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 bm(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=tm(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(r)}}function Sm(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 p=c.run({value:t[l],issues:[]},n);p instanceof Promise?e.push(p.then(m=>Ki(m,r,l,t,u,f))):Ki(p,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 Tm=_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=Xh(()=>bm(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=Jh,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 p=f[l],m=p._zod.optin==="optional",E=p._zod.optout==="optional",w=p._zod.run({value:d[l],issues:[]},c);w instanceof Promise?u.push(w.then(I=>Ki(I,a,l,d,m,E))):Ki(w,a,l,d,m,E)}return o?Sm(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=>!Jr(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=>vn(s,n,zr())))}),t)}const vm=_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=>Ou(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)}}),Om=_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"?sc(n):n?sc(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 dc(e,t){return t===void 0&&(e.issues.length||e.fallback)?{issues:[],value:void 0}:e}const Rm=_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(`^(${Ou(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=>dc(s,i)):dc(o,i)}return r.value===void 0?r:t.innerType._zod.run(r,n)}}),km=_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 Pm(e,t){return new e({type:"string",...it()})}function Lm(e,t){return new e({type:"number",checks:[],...it()})}function Cm(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...it()})}function xm(e,t){return new e({type:"null",...it()})}function Um(e,t){return new e({type:"never",...it()})}function ne(e,t){return new gm({check:"less_than",...it(),value:e,inclusive:!0})}function ie(e,t){return new pm({check:"greater_than",...it(),value:e,inclusive:!0})}function oe(e,t){return new wm({check:"string_format",format:"regex",...it(),pattern:e})}zr({jitless:!0});function ju(e){if(e.schema_version!==1||!/^[a-f0-9]{32}$/.test(e.session_id)||!Number.isSafeInteger(e.revision)||e.revision<1||!/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/.test(e.sdk_version)||!e.declared_permissions||typeof e.declared_permissions!="object"||Array.isArray(e.declared_permissions)||!Array.isArray(e.platforms)||e.platforms.some(r=>!["android","ios","ohos","windows","macos","linux"].includes(r))||new Set(e.platforms).size!==e.platforms.length)throw new Error("开发快照无效");const t={};for(const r of or){const n=e.declared_permissions[r];if(n){if(typeof n.enabled!="boolean")throw new Error("开发权限声明无效");if(r==="network"){t[r]={enabled:n.enabled,useOfficialDomain:n.useOfficialDomain===!0};continue}if(r==="user_game_data"){t[r]={enabled:n.enabled,resources:_n(n.resources)};continue}t[r]={enabled:n.enabled}}}if(Object.keys(e.declared_permissions).some(r=>!or.includes(r)))throw new Error("开发权限声明无效");if(e.companion_manifest_sha256!==void 0&&!/^[a-f0-9]{64}$/.test(e.companion_manifest_sha256))throw new Error("开发产物摘要无效");return JSON.stringify({schema_version:1,session_id:e.session_id,revision:e.revision,sdk_version:e.sdk_version,declared_permissions:t,platforms:[...e.platforms].sort(),...e.companion_manifest_sha256?{companion_manifest_sha256:e.companion_manifest_sha256}:{}})}function jm(e){if(!(typeof e!="string"||e.length>16384))try{const t=JSON.parse(e);return ju(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)=>sm(e,r,n,{callee:e.parse}),e.safeParse=(r,n)=>Lu(e,r,n),e.parseAsync=async(r,n)=>cm(e,r,n,{callee:e.parseAsync}),e.safeParseAsync=async(r,n)=>Cu(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)=>em(e,r,n),e.brand=()=>e,e.register=((r,n)=>(r.add(e,n),e)),e.apply=r=>r(e)}),zm=_e("ZodMiniString",(e,t)=>{Am.init(e,t),Dt.init(e,t)});function _(e){return Pm(zm)}const zu=_e("ZodMiniNumber",(e,t)=>{Uu.init(e,t),Dt.init(e,t)});function V(e){return Lm(zu)}const Hm=_e("ZodMiniNumberFormat",(e,t)=>{_m.init(e,t),zu.init(e,t)});function se(e){return Cm(Hm)}const Fm=_e("ZodMiniNull",(e,t)=>{Dm.init(e,t),Dt.init(e,t)});function ee(e){return xm(Fm)}const Bm=_e("ZodMiniNever",(e,t)=>{Nm.init(e,t),Dt.init(e,t)});function Vm(e){return Um(Bm)}const Gm=_e("ZodMiniArray",(e,t)=>{Mm.init(e,t),Dt.init(e,t)});function X(e,t){return new Gm({type:"array",element:e,...it()})}const $m=_e("ZodMiniObject",(e,t)=>{Tm.init(e,t),Dt.init(e,t),qe(e,"shape",()=>t.shape)});function re(e,t){return new $m({type:"object",shape:e,catchall:Vm(),...it()})}const Qm=_e("ZodMiniUnion",(e,t)=>{vm.init(e,t),Dt.init(e,t)});function A(e,t){return new Qm({type:"union",options:e,...it()})}const qm=_e("ZodMiniLiteral",(e,t)=>{Om.init(e,t),Dt.init(e,t)});function ue(e,t){return new qm({type:"literal",values:Array.isArray(e)?e:[e],...it()})}const Ym=_e("ZodMiniOptional",(e,t)=>{Rm.init(e,t),Dt.init(e,t)});function G(e){return new Ym({type:"optional",innerType:e})}const Wm=_e("ZodMiniLazy",(e,t)=>{km.init(e,t),Dt.init(e,t)});function Y(e){return new Wm({type:"lazy",getter:e})}const W={ArkProfile:re({uid:_(),name:_(),level:V(),avatar:G(Y(()=>W.ArkPlayerAvatar)),characterCount:V(),totalCharacterCount:V(),mainStageProgress:_(),rogueLevel:V(),campaignFullKillCount:V(),tag:_(),observedAt:G(A([_(),V()])),lastOnlineTs:G(A([_(),V()])),registerTs:G(A([_(),V()])),changeTime:G(A([_(),V()])),operators:G(X(Y(()=>W.ArkOperator)))}),ArkPlayerAvatar:re({url:_(),type:_(),id:_()}),ArkOperator:re({characterId:_(),name:_(),profession:_(),evolvePhase:V(),potentialRank:V()}),ArkGachaAnalysis:re({uid:_(),year:V(),total:V(),srCount:V(),upCount:V(),missCount:V(),careerEvaluation:_(),careerIsLucky:A([ue(!1),ue(!0)]),pools:X(Y(()=>W.ArkGachaPoolStat)),records:X(Y(()=>W.ArkGachaAnalysisRecord)),luckyLottery:X(V())}),ArkGachaPoolStat:re({poolId:_(),totalCost:V(),ssrCount:V(),ssrCost:V(),records:X(Y(()=>W.ArkGachaAnalysisRecord))}),ArkGachaAnalysisRecord:re({name:_(),timestamp:A([se().check(ie(-9007199254740991),ne(9007199254740991)),_().check(oe(new RegExp("^-?(0|[1-9][0-9]*)$")))]),diff:V(),negativeDiff:V(),tag:_(),missUp:A([ue(!1),ue(!0)])}),GachaRecord:re({id:_(),name:_(),pool:_(),rarity:V(),timestamp:A([se().check(ie(-9007199254740991),ne(9007199254740991)),_().check(oe(new RegExp("^-?(0|[1-9][0-9]*)$")))])}),BlackMythWukongSave:re({level:G(V()),newGamePlusCount:G(V()),gameTotalTime:G(V()),playerDeathCount:G(V()),totalMoney:G(_()),meditationList:G(A([ee(),X(V())])),monsterCollectionList:G(A([ee(),X(V())])),returnPointList:G(A([ee(),X(V())])),activatedWeaponIdList:G(A([ee(),X(_())])),activatedEquipIdList:G(A([ee(),X(V())])),magicArtifactList:G(A([ee(),X(V())])),soulSkillIdList:G(A([ee(),X(V())])),huluIdLits:G(A([ee(),X(V())])),wineIdList:G(A([ee(),X(V())])),wineIdPartnerList:G(A([ee(),X(V())])),cropIdList:G(A([ee(),X(V())])),recipeIdList:G(A([ee(),X(V())])),wearedWaeponId:G(_()),wearedMagicArtifact:G(V()),wearedSoulSkill:G(V()),wearedHead:G(V()),wearedUpware:G(V()),wearedArm:G(V()),wearedFoot:G(V()),wearedHulu:G(V()),wearedAccessoryList:G(A([ee(),X(V())])),spellQishu:G(A([ee(),X(V())])),spellShenfa:G(A([ee(),X(V())])),spellHaomao:G(A([ee(),X(V())])),spellBianshen:G(A([ee(),X(V())])),bossRushBossgroup:G(Y(()=>W.BlackMythWukongBossRushData)),bossRushRefight:G(Y(()=>W.BlackMythWukongBossRefightData))}),BlackMythWukongBossRushData:re({bossGroups:G(A([ee(),X(Y(()=>W.BlackMythWukongBossRushRecord))]))}),BlackMythWukongBossRushRecord:re({bossGroupId:G(V()),isPassed:G(A([ue(!1),ue(!0)])),bestRecords:G(A([ee(),X(Y(()=>W.BlackMythWukongBattleRecord))])),encounterBossIndex:G(V()),battleCount:G(V())}),BlackMythWukongBattleRecord:re({battleId:G(_()),battleData:G(Y(()=>W.BlackMythWukongBattleData))}),BlackMythWukongBattleData:re({totalTime:G(V()),score:G(V()),debuffList:G(A([ee(),X(V())])),targetId:G(V()),archiveTime:G(_()),roleBase:G(Y(()=>W.BlackMythWukongRoleBase)),battleStyleInfo:G(Y(()=>W.BlackMythWukongBattleStyleInfo)),damageInfo:G(Y(()=>W.BlackMythWukongDamageInfo))}),BlackMythWukongRoleBase:re({level:G(V()),atk:G(V()),hpMax:G(V()),staminaMax:G(V()),mpMax:G(V())}),BlackMythWukongBattleStyleInfo:re({spellList:G(A([ee(),X(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:re({castId:G(V()),castCount:G(V())}),BlackMythWukongDamageInfo:re({totalDamage:G(A([_(),V()])),hightestDamage:G(A([_(),V()])),criticalDmgRate:G(V()),totalBeDamaged:G(A([_(),V()])),criticalDmgTotal:G(A([_(),V()])),elemDotDmgTotal:G(A([_(),V()])),elemDotDmgRate:G(V())}),BlackMythWukongBossRefightData:re({bossList:G(A([ee(),X(Y(()=>W.BlackMythWukongBossRefightRecord))]))}),BlackMythWukongBossRefightRecord:re({bossId:G(V()),passedMaxLevel:G(V()),lastChallengeLevel:G(V()),bestRecords:G(A([ee(),X(Y(()=>W.BlackMythWukongBattleRecord))])),refightStatisticsList:G(A([ee(),X(Y(()=>W.BlackMythWukongRefightStatistic))]))}),BlackMythWukongRefightStatistic:re({challengeLevel:G(V()),battleCount:G(V())}),TaskBarHeroSave:re({update_time:A([se().check(ie(-9007199254740991),ne(9007199254740991)),_().check(oe(new RegExp("^-?(0|[1-9][0-9]*)$")))]),game_version:_(),account_version:_(),play_time:V(),last_saved_time:_(),common:Y(()=>W.TaskBarHeroCommon),summary:Y(()=>W.TaskBarHeroSummary),heroes:A([ee(),X(Y(()=>W.TaskBarHeroHero))]),rune_save_data:A([ee(),X(Y(()=>W.TaskBarHeroRune))]),pets:A([ee(),X(Y(()=>W.TaskBarHeroPet))]),attributes:A([ee(),X(Y(()=>W.TaskBarHeroAttribute))]),inventory_slots:A([ee(),X(Y(()=>W.TaskBarHeroItemSlot))]),stash_slots:A([ee(),X(Y(()=>W.TaskBarHeroItemSlot))]),item_instances:A([ee(),X(Y(()=>W.TaskBarHeroItemInstance))]),values:Y(()=>W.TaskBarHeroValueSummary)}),TaskBarHeroCommon:re({max_completed_stage:A([se().check(ie(-9007199254740991),ne(9007199254740991)),_().check(oe(new RegExp("^-?(0|[1-9][0-9]*)$")))]),current_stage_key:A([se().check(ie(-9007199254740991),ne(9007199254740991)),_().check(oe(new RegExp("^-?(0|[1-9][0-9]*)$")))]),current_stage_wave:A([se().check(ie(-9007199254740991),ne(9007199254740991)),_().check(oe(new RegExp("^-?(0|[1-9][0-9]*)$")))]),arranged_hero_keys:A([ee(),X(A([se().check(ie(-9007199254740991),ne(9007199254740991)),_().check(oe(new RegExp("^-?(0|[1-9][0-9]*)$")))]))]),arranged_pet_key:A([se().check(ie(-9007199254740991),ne(9007199254740991)),_().check(oe(new RegExp("^-?(0|[1-9][0-9]*)$")))])}),TaskBarHeroSummary:re({max_hero_level:A([se().check(ie(-9007199254740991),ne(9007199254740991)),_().check(oe(new RegExp("^-?(0|[1-9][0-9]*)$")))]),learned_rune_count:A([se().check(ie(-9007199254740991),ne(9007199254740991)),_().check(oe(new RegExp("^-?(0|[1-9][0-9]*)$")))]),unlocked_hero:A([se().check(ie(-9007199254740991),ne(9007199254740991)),_().check(oe(new RegExp("^-?(0|[1-9][0-9]*)$")))]),total_hero:A([se().check(ie(-9007199254740991),ne(9007199254740991)),_().check(oe(new RegExp("^-?(0|[1-9][0-9]*)$")))]),item_count:A([se().check(ie(-9007199254740991),ne(9007199254740991)),_().check(oe(new RegExp("^-?(0|[1-9][0-9]*)$")))]),inventory_slots:A([se().check(ie(-9007199254740991),ne(9007199254740991)),_().check(oe(new RegExp("^-?(0|[1-9][0-9]*)$")))]),stash_slots:A([se().check(ie(-9007199254740991),ne(9007199254740991)),_().check(oe(new RegExp("^-?(0|[1-9][0-9]*)$")))])}),TaskBarHeroHero:re({hero_key:A([se().check(ie(-9007199254740991),ne(9007199254740991)),_().check(oe(new RegExp("^-?(0|[1-9][0-9]*)$")))]),hero_level:A([se().check(ie(-9007199254740991),ne(9007199254740991)),_().check(oe(new RegExp("^-?(0|[1-9][0-9]*)$")))]),is_unlock:A([ue(!1),ue(!0)]),hero_exp:V(),ability_point:A([se().check(ie(-9007199254740991),ne(9007199254740991)),_().check(oe(new RegExp("^-?(0|[1-9][0-9]*)$")))]),allocated_hero_ability_point:A([se().check(ie(-9007199254740991),ne(9007199254740991)),_().check(oe(new RegExp("^-?(0|[1-9][0-9]*)$")))]),equipped_item_ids:A([ee(),X(_())]),equipped_skill_keys:A([ee(),X(A([se().check(ie(-9007199254740991),ne(9007199254740991)),_().check(oe(new RegExp("^-?(0|[1-9][0-9]*)$")))]))]),unlocked_attribute_group_keys:A([ee(),X(A([se().check(ie(-9007199254740991),ne(9007199254740991)),_().check(oe(new RegExp("^-?(0|[1-9][0-9]*)$")))]))])}),TaskBarHeroRune:re({rune_key:A([se().check(ie(-9007199254740991),ne(9007199254740991)),_().check(oe(new RegExp("^-?(0|[1-9][0-9]*)$")))]),level:A([se().check(ie(-9007199254740991),ne(9007199254740991)),_().check(oe(new RegExp("^-?(0|[1-9][0-9]*)$")))])}),TaskBarHeroPet:re({pet_key:A([se().check(ie(-9007199254740991),ne(9007199254740991)),_().check(oe(new RegExp("^-?(0|[1-9][0-9]*)$")))]),is_unlock:A([ue(!1),ue(!0)])}),TaskBarHeroAttribute:re({key:A([se().check(ie(-9007199254740991),ne(9007199254740991)),_().check(oe(new RegExp("^-?(0|[1-9][0-9]*)$")))]),level:A([se().check(ie(-9007199254740991),ne(9007199254740991)),_().check(oe(new RegExp("^-?(0|[1-9][0-9]*)$")))])}),TaskBarHeroItemSlot:re({index:A([se().check(ie(-9007199254740991),ne(9007199254740991)),_().check(oe(new RegExp("^-?(0|[1-9][0-9]*)$")))]),item_unique_id:_(),is_unlock:A([ue(!1),ue(!0)]),is_unlocked_by_rune:A([ue(!1),ue(!0)])}),TaskBarHeroItemInstance:re({item_key:A([se().check(ie(-9007199254740991),ne(9007199254740991)),_().check(oe(new RegExp("^-?(0|[1-9][0-9]*)$")))]),unique_id:_(),is_chaotic:A([ue(!1),ue(!0)]),is_blocked:A([ue(!1),ue(!0)]),is_server_pending_item:A([ue(!1),ue(!0)]),enchant_count:A([ee(),X(A([se().check(ie(-9007199254740991),ne(9007199254740991)),_().check(oe(new RegExp("^-?(0|[1-9][0-9]*)$")))]))]),enchant_data:A([ee(),X(Y(()=>W.TaskBarHeroEnchantData))]),item_get_source_type:A([se().check(ie(-9007199254740991),ne(9007199254740991)),_().check(oe(new RegExp("^-?(0|[1-9][0-9]*)$")))]),decoration_applied_total_count:A([se().check(ie(-9007199254740991),ne(9007199254740991)),_().check(oe(new RegExp("^-?(0|[1-9][0-9]*)$")))]),engraving_applied_total_count:A([se().check(ie(-9007199254740991),ne(9007199254740991)),_().check(oe(new RegExp("^-?(0|[1-9][0-9]*)$")))]),inscription_applied_total_count:A([se().check(ie(-9007199254740991),ne(9007199254740991)),_().check(oe(new RegExp("^-?(0|[1-9][0-9]*)$")))])}),TaskBarHeroEnchantData:re({stat_mod_key:A([se().check(ie(-9007199254740991),ne(9007199254740991)),_().check(oe(new RegExp("^-?(0|[1-9][0-9]*)$")))]),tier:A([se().check(ie(-9007199254740991),ne(9007199254740991)),_().check(oe(new RegExp("^-?(0|[1-9][0-9]*)$")))]),value:V(),recipe_type:A([se().check(ie(-9007199254740991),ne(9007199254740991)),_().check(oe(new RegExp("^-?(0|[1-9][0-9]*)$")))]),mod_type:A([se().check(ie(-9007199254740991),ne(9007199254740991)),_().check(oe(new RegExp("^-?(0|[1-9][0-9]*)$")))]),material_key:A([se().check(ie(-9007199254740991),ne(9007199254740991)),_().check(oe(new RegExp("^-?(0|[1-9][0-9]*)$")))]),stat_type:A([se().check(ie(-9007199254740991),ne(9007199254740991)),_().check(oe(new RegExp("^-?(0|[1-9][0-9]*)$")))])}),TaskBarHeroValueSummary:re({market_value:A([se().check(ie(-9007199254740991),ne(9007199254740991)),_().check(oe(new RegExp("^-?(0|[1-9][0-9]*)$")))]),price_state:_(),currency:_()}),PhantomBladeZeroSave:re({defaultSlot:_(),slots:X(Y(()=>W.PhantomBladeZeroSaveSlot))}),PhantomBladeZeroSaveSlot:re({slot:_(),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:A([ee(),Y(()=>W.PhantomBladeZeroQuestDetails)]),inventory_details:A([ee(),X(Y(()=>W.PhantomBladeZeroInventoryItem))]),detail:Y(()=>W.PhantomBladeZeroSlotDetail)}),PhantomBladeZeroSlotHead:re({saveTime:_(),currentLevel:_(),cycle:_(),difficulty:Y(()=>W.PhantomBladeZeroSlotDifficulty)}),PhantomBladeZeroSlotDifficulty:re({raw:V(),name:_()}),PhantomBladeZeroSlotFirstClear:re({clearDate:Y(()=>W.PhantomBladeZeroUnavailableValue),cycles:A([ee(),X(Y(()=>W.PhantomBladeZeroClearanceRecord))])}),PhantomBladeZeroUnavailableValue:re({value:ee(),reason:_()}),PhantomBladeZeroClearanceRecord:re({Cycle:G(A([ee(),V()])),Ending:V(),Difficulty:V(),GameTime:A([se().check(ie(-9007199254740991),ne(9007199254740991)),_().check(oe(new RegExp("^-?(0|[1-9][0-9]*)$")))]),Completion:V(),DiedTimes:A([se().check(ie(-9007199254740991),ne(9007199254740991)),_().check(oe(new RegExp("^-?(0|[1-9][0-9]*)$")))])}),PhantomBladeZeroSlotProgress:re({playTimeSeconds:A([se().check(ie(-9007199254740991),ne(9007199254740991)),_().check(oe(new RegExp("^-?(0|[1-9][0-9]*)$")))]),playTime:_(),lastLaunch:Y(()=>W.PhantomBladeZeroUnavailableValue),narrativePercentage:V(),chapter:_(),remainingDays:A([se().check(ie(-9007199254740991),ne(9007199254740991)),_().check(oe(new RegExp("^-?(0|[1-9][0-9]*)$")))])}),PhantomBladeZeroSlotCombat:re({loadout:G(Y(()=>W.PhantomBladeZeroSlotLoadout)),totalDeaths:A([se().check(ie(-9007199254740991),ne(9007199254740991)),_().check(oe(new RegExp("^-?(0|[1-9][0-9]*)$")))]),cycleDeaths:A([se().check(ie(-9007199254740991),ne(9007199254740991)),_().check(oe(new RegExp("^-?(0|[1-9][0-9]*)$")))]),bossKillTotal:A([se().check(ie(-9007199254740991),ne(9007199254740991)),_().check(oe(new RegExp("^-?(0|[1-9][0-9]*)$")))]),currentMainWeapon:G(A([ee(),Y(()=>W.PhantomBladeZeroNamedItem)])),mainWeapon:Y(()=>W.PhantomBladeZeroCollectionCount),currentShaqi:G(A([ee(),Y(()=>W.PhantomBladeZeroNamedItem)])),shaqi:Y(()=>W.PhantomBladeZeroCollectionCount)}),PhantomBladeZeroSlotLoadout:re({states:G(A([ee(),X(Y(()=>W.PhantomBladeZeroLoadoutState))])),main_weapons:A([ee(),X(_())]),shaqi_weapons:A([ee(),X(_())]),accessory_ids:A([ee(),X(_())]),top_medicine:_(),bottom_medicine:_(),current_weapon_index:V(),current_shaqi_weapon_index:V()}),PhantomBladeZeroLoadoutState:re({category:_(),id:_(),level:G(V()),soul_forged:G(A([ue(!1),ue(!0)])),reincarnation_count:G(V())}),PhantomBladeZeroNamedItem:re({id:_(),name:_()}),PhantomBladeZeroCollectionCount:re({unknown:G(A([_(),V()])),done:A([se().check(ie(-9007199254740991),ne(9007199254740991)),_().check(oe(new RegExp("^-?(0|[1-9][0-9]*)$")))]),total:A([se().check(ie(-9007199254740991),ne(9007199254740991)),_().check(oe(new RegExp("^-?(0|[1-9][0-9]*)$")))])}),PhantomBladeZeroSlotAchievementSummary:re({unlocked:A([se().check(ie(-9007199254740991),ne(9007199254740991)),_().check(oe(new RegExp("^-?(0|[1-9][0-9]*)$")))]),total:A([se().check(ie(-9007199254740991),ne(9007199254740991)),_().check(oe(new RegExp("^-?(0|[1-9][0-9]*)$")))]),reason:_()}),PhantomBladeZeroSlotBossSummary:re({groups:A([ee(),X(Y(()=>W.PhantomBladeZeroBossGroup))])}),PhantomBladeZeroBossGroup:re({map:_(),mapName:_(),count:A([se().check(ie(-9007199254740991),ne(9007199254740991)),_().check(oe(new RegExp("^-?(0|[1-9][0-9]*)$")))]),bosses:A([ee(),X(Y(()=>W.PhantomBladeZeroBoss))])}),PhantomBladeZeroBoss:re({id:_(),classPath:_(),map:_(),mapName:_(),encountered:A([ue(!1),ue(!0)]),killed:A([ue(!1),ue(!0)]),kill:A([se().check(ie(-9007199254740991),ne(9007199254740991)),_().check(oe(new RegExp("^-?(0|[1-9][0-9]*)$")))]),attempt:A([se().check(ie(-9007199254740991),ne(9007199254740991)),_().check(oe(new RegExp("^-?(0|[1-9][0-9]*)$")))]),bestTimeMs:A([se().check(ie(-9007199254740991),ne(9007199254740991)),_().check(oe(new RegExp("^-?(0|[1-9][0-9]*)$")))]),records:A([ee(),X(Y(()=>W.PhantomBladeZeroBossRecord))])}),PhantomBladeZeroBossRecord:re({cycle:_(),diff:_(),diffName:_(),kill:A([se().check(ie(-9007199254740991),ne(9007199254740991)),_().check(oe(new RegExp("^-?(0|[1-9][0-9]*)$")))]),attempt:A([se().check(ie(-9007199254740991),ne(9007199254740991)),_().check(oe(new RegExp("^-?(0|[1-9][0-9]*)$")))]),bestTimeMs:A([se().check(ie(-9007199254740991),ne(9007199254740991)),_().check(oe(new RegExp("^-?(0|[1-9][0-9]*)$")))])}),PhantomBladeZeroSlotCollectibles:re({overall:Y(()=>W.PhantomBladeZeroCollectionSummary),craneBellCount:A([se().check(ie(-9007199254740991),ne(9007199254740991)),_().check(oe(new RegExp("^-?(0|[1-9][0-9]*)$")))]),byBigMap:A([ee(),X(Y(()=>W.PhantomBladeZeroBigMapProgress))]),currentChapter:Y(()=>W.PhantomBladeZeroChapterProgress)}),PhantomBladeZeroCollectionSummary:re({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:re({unknown:G(A([_(),V()])),mapID:_(),name:_(),pct:V(),done:A([se().check(ie(-9007199254740991),ne(9007199254740991)),_().check(oe(new RegExp("^-?(0|[1-9][0-9]*)$")))]),total:A([se().check(ie(-9007199254740991),ne(9007199254740991)),_().check(oe(new RegExp("^-?(0|[1-9][0-9]*)$")))]),subMaps:A([ee(),X(_())])}),PhantomBladeZeroChapterProgress:re({unknown:G(A([_(),V()])),mapID:_(),pct:V(),done:A([se().check(ie(-9007199254740991),ne(9007199254740991)),_().check(oe(new RegExp("^-?(0|[1-9][0-9]*)$")))]),total:A([se().check(ie(-9007199254740991),ne(9007199254740991)),_().check(oe(new RegExp("^-?(0|[1-9][0-9]*)$")))]),reason:_()}),PhantomBladeZeroQuestDetails:re({CurrentMainQuestPath:_(),CurrentTutorialQuestPath:_(),TrackedQuestPath:_(),TrackedBranchID:_(),TrackedTaskPointID:_(),ManualTrackingOptOut:A([ue(!1),ue(!0)]),NarrativeSavedQuests:A([ee(),X(Y(()=>W.PhantomBladeZeroQuest))])}),PhantomBladeZeroQuest:re({QuestClass:_(),QuestCompletion:_(),QuestBranches:A([ee(),X(Y(()=>W.PhantomBladeZeroQuestBranch))]),CompletedBranches:A([ee(),X(_())]),ReachedStateNames:A([ee(),X(_())])}),PhantomBladeZeroQuestBranch:re({BranchID:_(),TasksProgress:A([ee(),X(A([se().check(ie(-9007199254740991),ne(9007199254740991)),_().check(oe(new RegExp("^-?(0|[1-9][0-9]*)$")))]))]),BranchType:_()}),PhantomBladeZeroInventoryItem:re({id:_(),amount:A([se().check(ie(-9007199254740991),ne(9007199254740991)),_().check(oe(new RegExp("^-?(0|[1-9][0-9]*)$")))])}),PhantomBladeZeroSlotDetail:re({bell:A([ee(),X(Y(()=>W.PhantomBladeZeroBellDetail))]),weapon:A([ee(),X(Y(()=>W.PhantomBladeZeroItemDetail))]),shaqi:A([ee(),X(Y(()=>W.PhantomBladeZeroItemDetail))]),accessory:A([ee(),X(Y(()=>W.PhantomBladeZeroItemDetail))]),medicine:A([ee(),X(Y(()=>W.PhantomBladeZeroItemDetail))]),challenge:A([ee(),X(Y(()=>W.PhantomBladeZeroChallengeDetail))]),hupo:A([ee(),X(Y(()=>W.PhantomBladeZeroWorldItemDetail))]),heishi:A([ee(),X(Y(()=>W.PhantomBladeZeroWorldItemDetail))]),flower:A([ee(),X(Y(()=>W.PhantomBladeZeroItemDetail))]),achievements:A([ee(),X(Y(()=>W.PhantomBladeZeroAchievementDetail))])}),PhantomBladeZeroBellDetail:re({unknown:G(A([ue(!1),ue(!0)])),id:_(),done:A([ue(!1),ue(!0)]),equip:A([ue(!1),ue(!0)])}),PhantomBladeZeroItemDetail:re({level:G(V()),soul_forged:G(A([ue(!1),ue(!0)])),reincarnation_count:G(V()),unknown:G(A([ue(!1),ue(!0)])),id:_(),name:_(),done:A([ue(!1),ue(!0)]),equip:A([ue(!1),ue(!0)]),locs:A([ee(),X(Y(()=>W.PhantomBladeZeroLocation))])}),PhantomBladeZeroLocation:re({map:_(),mapName:_(),x:V(),y:V(),z:V()}),PhantomBladeZeroChallengeDetail:re({key:G(_()),unknown:G(A([ue(!1),ue(!0)])),index:A([se().check(ie(-9007199254740991),ne(9007199254740991)),_().check(oe(new RegExp("^-?(0|[1-9][0-9]*)$")))]),guids:A([ee(),X(_())]),done:A([ue(!1),ue(!0)]),locs:A([ee(),X(Y(()=>W.PhantomBladeZeroLocation))])}),PhantomBladeZeroWorldItemDetail:re({key:G(_()),unknown:G(A([ue(!1),ue(!0)])),id:_(),saveGuid:_(),mobDomain:_(),done:A([ue(!1),ue(!0)]),locs:A([ee(),X(Y(()=>W.PhantomBladeZeroLocation))])}),PhantomBladeZeroAchievementDetail:re({id:_(),name:_(),desc:_(),grade:_(),hidden:A([ue(!1),ue(!0)]),done:A([ue(!1),ue(!0)])}),UserGameDataSaveFilePage:re({items:X(Y(()=>W.UserGameDataSaveInfo)),hasMore:ue(!1)}),UserGameDataSaveInfo:re({saveId:_(),createdAt:_(),files:X(Y(()=>W.UserGameDataSaveFileInfo))}),UserGameDataSaveFileInfo:re({fileId:_(),name:_(),sizeBytes:V(),modifiedAt:_()})},Zm=new Map([["ark.profile",Y(()=>W.ArkProfile)],["ark.gacha-analysis",Y(()=>W.ArkGachaAnalysis)],["ark.gacha-record-page",re({items:X(Y(()=>W.GachaRecord)),nextCursor:G(_()),hasMore:A([ue(!1),ue(!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 Km(e,t){return Zm.get(e)?.safeParse(t).success??!1}xt.map(e=>e.method);function ei(){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:ei()}function Hu(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 Fu="METHOD_FORBIDDEN";function tt(e){const t=new Error(`小程序能力已禁用: ${e}`);return t.name="MethodForbiddenError",t.code=Fu,t}class Ce 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 Xm=/^[A-Za-z0-9_-]{1,64}$/,uc=1e3;function Bu(e){return Xm.test(e)?e:rg(e)}function Jm(e){return`id_${Bu(e.trim())}`}function cr(e,t){return`hb_miniprogram_${e}_${t}`}function zn(e){return`hb_miniprogram_keys_${e}`}const eg="hb_user_game_data_consent_";function tg(e){return`${eg}${e}`}function rg(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 ng=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 pa(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 w=0;w<16;w+=1)o[w]=s.getUint32(a+w*4,!1);for(let w=16;w<64;w+=1){const I=o[w-15],v=o[w-2],y=ft(I,7)^ft(I,18)^I>>>3,O=ft(v,17)^ft(v,19)^v>>>10;o[w]=o[w-16]+y+o[w-7]+O>>>0}let[c,d,u,f,l,p,m,E]=i;for(let w=0;w<64;w+=1){const I=E+(ft(l,6)^ft(l,11)^ft(l,25))+(l&p^~l&m)+ng[w]+o[w]>>>0,v=(ft(c,2)^ft(c,13)^ft(c,22))+(c&d^c&u^d&u);E=m,m=p,p=l,l=f+I>>>0,f=u,u=d,d=c,c=I+v>>>0}[c,d,u,f,l,p,m,E].forEach((w,I)=>{i[I]=i[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 ig=Object.freeze({upload:"你允许读取的数据可能会被上传至开发者服务器。",no_network:"此小程序未获准将你允许读取的数据上传至开发者服务器。"});function og(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&&!cg(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 sg(e){return pa(`${e.miniProgramId}\0${e.userId}\0${e.environment}`).slice(0,32)}function ag(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 cg(e){return typeof e=="string"&&/^[0-9a-f]{64}$/.test(e)}function we(e,t,r){return{code:e,message:t,data:r}}function ya(e){return dg(e)?{code:e.code,message:e.message,data:e.data}:e instanceof Error?we("RUNTIME_ERROR",e.message):we("UNKNOWN_ERROR","小程序运行时异常",e)}function dg(e){return!!e&&typeof e=="object"&&typeof e.code=="string"&&typeof e.message=="string"}const $t=["account.getCurrentUserId","account.onChange","storage.getRaw","storage.setRaw"],Ho=[...$t,"network.request"],lc={"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"],[pi]:["workspaceCards.requestRefresh"],[yi]:["account.getCurrentUserId","account.getAccountKey","account.onChange"],[Ei]:["account.getCurrentUserId","account.ensureAuthenticated","account.onChange","network.request"],[wi]:["account.getCurrentUserId","account.onChange","network.request"],[Ii]:["account.getCurrentUserId","account.ensureAuthenticated","account.onChange","network.request"],[Ai]:["account.getCurrentUserId","account.onChange","network.request"],[_i]:["account.getCurrentUserId","account.onChange","network.request"],[Di]:["account.getCurrentUserId","account.onChange","network.request"],[Ni]:["presentation.setClipboard"],[Mi]:["presentation.showShareMenu"],[bi]:["presentation.getViewportMetrics","presentation.captureAndShare"],[Si]:["presentation.getViewportMetrics","presentation.captureAndShare"],[rr]:["presentation.applyOrientation"],[Ti]:["presentation.getViewportMetrics","presentation.getNavigationBarHeight"],[vi]:["presentation.setNavigationBarStyle"],[hn]:["storage.getRaw"],[mn]:["storage.setRaw"],[Oi]:["network.request"],[Ri]:["network.stream","files.transfer","files.access"],[ki]:["network.upload","files.access"],[Pi]:["files.external"],[Li]:["files.external"],[Ci]:["files.save"],[gn]:["files.access"],[pn]:["files.removeFile"],[xi]:["files.access"],[yn]:["files.access"],[Ui]:["files.access"],[En]:["files.access"],[ji]:["files.access"],[wn]:["files.access"],[zi]:["files.access"],[In]:["files.removeDirectory"],[Hi]:["files.access"],[Fi]:["files.access"],[An]:["media.pick"],[fn]:["presentation.showAppreciation"],[Bi]:["presentation.showToast"],[Vi]:["presentation.showLoading"],[Gi]:["presentation.hideLoading"],[$i]:["presentation.vibrate"],[Qi]:["presentation.setClipboard"],[qi]:["protocol.invoke"],[Yi]:["presentation.close"],[Wi]:["presentation.reload"],[Zi]:["presentation.openAppPage"],[St]:["account.getCurrentUserId","account.onChange","network.request"],[at]:["account.onChange","network.request"],[Ct]:["account.getCurrentUserId","account.onChange","network.request"],[nr]:["account.getCurrentUserId","account.onChange","network.request"],[Et]:["account.onChange","network.request"],[Nr]:["account.getCurrentUserId","account.onChange","network.request"],[Mr]:["account.getCurrentUserId","account.onChange","network.request"],[br]:["account.getCurrentUserId","account.onChange","network.request"],[ir]:["account.getCurrentUserId","account.onChange","network.request"],[ho]:["companion.getInfo"],[mo]:["companion.getPreparationStatus"],[go]:["companion.getInfo","companion.getPreparationStatus","companion.prepare"],[po]:["companion.cancelPreparation"],[yo]:["companion.getActiveSession"],[Eo]:["companion.getInfo","companion.launch"],[wo]:["companion.session.write"],[Io]:["companion.session.closeStdin"],[Ao]:["companion.session.terminate"],[_o]:["companion.session.ackOutput"],[Do]:["companion.openAttachment"],[No]:["companion.showNotification"],[sa]:$t,[mi]:Ho,[nn]:Ho,[gi]:[...Ho,"files.sandbox","files.removeFile","network.stream","files.transfer"],[aa]:[...$t,"presentation.confirmDataPermission"],[ca]:$t,[da]:$t,[ua]:[...$t,"presentation.openDataPermissions"],[la]:$t},ug=new Set([fn]);function Vu(e,t){if(t[e]!==!0)throw ug.has(e)?we("REQUEST_UNSUPPORTED","当前宿主不支持该能力"):tt(e)}const lg=32*1024*1024,fg=/^application\/(?:[a-z0-9!#$&^_.+-]+\+)?json(?:\s*;|$)/i;function hg(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:lg},i);return mg(o,a)}catch(a){throw s=a,a}finally{try{await r.release(o.body)}catch(a){if(s===void 0)throw a}}}}}}function mg(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:gg(t,yg(e,"content-type"))}}function gg(e,t){pg(t);let r;try{r=new TextDecoder("utf-8",{fatal:!0}).decode(e)}catch(n){throw new Ce("Host network response 不是合法 UTF-8 文本",{cause:n})}if(r.charCodeAt(0)===65279&&(r=r.slice(1)),!t||!fg.test(t)||r==="")return r;try{return JSON.parse(r)}catch{return r}}function pg(e){if(!e)return;const t=/(?:^|;)\s*charset\s*=\s*["']?([^;"'\s]+)/i.exec(e)?.[1];if(t&&!/^utf-?8$/i.test(t))throw new Ce(`Host network response 不支持 charset=${t}`)}function yg(e,t){return Object.entries(e.headers).find(([r])=>r.toLowerCase()===t)?.[1]?.[0]}function Z(e){return typeof e=="function"}function fc(e){return(...t)=>{throw tt(e)}}function Le(e){return async(...t)=>{throw tt(e)}}const Eg=(e,t)=>{},wg=()=>()=>{};function Ig(e){const t={request:Z(e.network?.request)?e.network.request.bind(e.network):Le("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):Le("account.getCurrentUserId"),ensureAuthenticated:Z(e.account?.ensureAuthenticated)?e.account.ensureAuthenticated.bind(e.account):Le("account.ensureAuthenticated"),onChange:Z(e.account?.onChange)?e.account.onChange.bind(e.account):wg},n={...e.storage?.withLock?{withLock:e.storage.withLock.bind(e.storage)}:{},getRaw:Z(e.storage?.getRaw)?e.storage.getRaw.bind(e.storage):Le("storage.getRaw"),setRaw:Z(e.storage?.setRaw)?e.storage.setRaw.bind(e.storage):Le("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):Le("presentation.close"),reload:Z(e.presentation?.reload)?e.presentation.reload.bind(e.presentation):Le("presentation.reload"),openAppPage:Z(e.presentation?.openAppPage)?e.presentation.openAppPage.bind(e.presentation):Le("presentation.openAppPage"),openWindow:Z(e.presentation?.openWindow)?e.presentation.openWindow.bind(e.presentation):Le("presentation.openWindow"),getViewportMetrics:Z(e.presentation?.getViewportMetrics)?e.presentation.getViewportMetrics.bind(e.presentation):fc("presentation.getViewportMetrics"),getNavigationBarHeight:Z(e.presentation?.getNavigationBarHeight)?e.presentation.getNavigationBarHeight.bind(e.presentation):fc("presentation.getNavigationBarHeight"),setNavigationBarStyle:Z(e.presentation?.setNavigationBarStyle)?e.presentation.setNavigationBarStyle.bind(e.presentation):Le("presentation.setNavigationBarStyle"),showShareMenu:Z(e.presentation?.showShareMenu)?e.presentation.showShareMenu.bind(e.presentation):Le("presentation.showShareMenu"),setScreenshotChromeHidden:Z(e.presentation?.setScreenshotChromeHidden)?e.presentation.setScreenshotChromeHidden.bind(e.presentation):Eg,supportsLongScreenshot:e.presentation?.supportsLongScreenshot===!0,captureAndShare:Z(e.presentation?.captureAndShare)?e.presentation.captureAndShare.bind(e.presentation):Le("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):Le("presentation.showToast"),showLoading:Z(e.presentation?.showLoading)?e.presentation.showLoading.bind(e.presentation):Le("presentation.showLoading"),hideLoading:Z(e.presentation?.hideLoading)?e.presentation.hideLoading.bind(e.presentation):Le("presentation.hideLoading"),vibrate:Z(e.presentation?.vibrate)?e.presentation.vibrate.bind(e.presentation):Le("presentation.vibrate"),setClipboard:Z(e.presentation?.setClipboard)?e.presentation.setClipboard.bind(e.presentation):Le("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):Le(`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):Le("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 Ag(e,t={}){const r=_g(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 _g(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 hc(e,t){return t?.[e]!==!1}function Dg(e){return e==="network.download"||e.startsWith("files.")||e.startsWith("file.")||e.startsWith("directory.")||e.startsWith("media.")||e.startsWith("companion.")}function Gu(e,t={}){const r={};for(const n of Object.keys(lc)){const o=lc[n].every(a=>e[a]),s=!Dg(n)||!!t.miniProgramDetail?.miniProgramId.trim();r[n]=hc(n,t.callerCapabilities)&&hc(n,t.hostCapabilities)&&o&&s}return r}function $u(e={},t={}){const r=Ag(e,t),n=Gu(r,t);return{ports:Ig(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]):Ng(e.signal,t);return{...e,signal:n,...r===void 0?{}:{requestId:r}}}function Ng(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 Mg(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 bg=4,Sg=["xiaoheihe.cn","max-c.com","debugmode.cn","maxjia.com"],Tg=new Set(["connection","content-length","host","origin","referer","keep-alive","proxy-connection","te","trailer","transfer-encoding","upgrade","x-heybox-runtime-auth-context-token"]),vg=["/user_miniprogram/runtime/auth","/user_miniprogram/openapi/v1"],Og=["/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 Rg(e,t){const r=Lg(e);return r===null||mc(r,vg)?!0:t&&mc(r,Og)}function kg(e){const t=e.hostname.toLowerCase().replace(/\.$/,"");return Sg.some(r=>t===r||t.endsWith(`.${r}`))}function Pg(e){const t=e.trim().toLowerCase();return t.startsWith("x-hb-sdk-")||t.startsWith("sec-")||Tg.has(t)||/^(?:x-heybox|x-xhh)-(?:access-token|auth|authorization|pkey|session|token)$/.test(t)}function Lg(e){let t=e;for(let r=0;r<bg;r+=1){let n;try{n=decodeURIComponent(t)}catch{return null}if(n===t)return gc(t);t=n}try{if(decodeURIComponent(t)!==t)return null}catch{return null}return gc(t)}function mc(e,t){return t.some(r=>e===r||e.startsWith(`${r}/`))}function gc(e){const t=[];for(const r of e.replace(/\\/g,"/").split("/"))!r||r==="."||(r===".."?t.pop():t.push(r));return`/${t.join("/")}`}function Cg(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 Qu(e){if(e==null)return;if(typeof e!="object"||Array.isArray(e))throw Fo("网络策略格式无效");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 Fo("网络策略格式无效");const n=new Set;for(const i of r){const o=Cg(i&&typeof i=="object"?i.domain:void 0);if(!o)throw Fo("网络策略包含无效域名");n.add(o)}return Object.freeze({revision:t.revision,enforcement:t.enforcement,entries:Object.freeze([...n].sort().map(i=>Object.freeze({domain:i})))})}function Fo(e){return Object.assign(new TypeError(e),{code:"NETWORK_POLICY_INVALID"})}function pc(e){return e instanceof Ce?{code:"REQUEST_UNSUPPORTED",message:e.message}:e}function fe(e,t,r={}){if(t.aborted&&!r.invokeWhenAborted)return Promise.reject(ei());let n;try{n=e()}catch(i){return Promise.reject(pc(i))}return t.aborted?(Promise.resolve(n).catch(()=>{}),Promise.reject(ei())):new Promise((i,o)=>{let s=!1;const a=d=>{s||(s=!0,t.removeEventListener("abort",c),d())},c=()=>a(()=>o(ei()));t.addEventListener("abort",c,{once:!0}),Promise.resolve(n).then(d=>a(()=>i(d)),d=>a(()=>o(pc(d))))})}async function xg(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),p=f.getBoundingClientRect();if(["hidden","clip","scroll","auto"].includes(l.overflowY)&&(u.top+t.top<p.top-1||u.top+t.top+t.height>p.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 Ug(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 qu(e,t){return jg(t)??zg(e.pathname)}function jg(e){if(!e)return;const t=new URL(e,"https://mini-program.invalid").pathname;return t.endsWith("/")?t:`${t}/`}function zg(e){const t=/^(\/u\/[^/]+\/[^/]+\/)/.exec(e)?.[1];if(t)return t;const r=e.lastIndexOf("/");return r>=0?e.slice(0,r+1):"/"}const Hg=1,Yu="allow-scripts allow-same-origin",Fg="",Bg="no-referrer";function Vg(e=Yu){return!e.split(/\s+/).includes("allow-same-origin")}function yc(){return window.crypto?.randomUUID?window.crypto.randomUUID():`${Date.now().toString(36)}_${Math.random().toString(36).slice(2)}`}const Gg=new Set(["javascript:","data:","blob:","file:"]),Ec="xiaoheihe.cn";function $g(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(Gg.has(i.protocol)||!["http:","https:"].includes(i.protocol))throw new Error("不支持的小程序链接协议");if(!qg(i,t,r))throw new Error("小程序链接必须属于 https://*.xiaoheihe.cn 或本地调试地址");return i.toString()}function Qg(e,t){const r=new URL(e);return r.searchParams.set(gu,t),r.toString()}function Wu(e,t,r){try{const n=new URL(e),i=new URL(t);if(n.origin!==i.origin)return!1;const o=qu(n,r);return i.pathname.startsWith(o)}catch{return!1}}function wc(e){const t=new URL(e);return Ea(t)?"loopback":wa(t)?"lan":"production"}function qg(e,t,r){return Yg(e)||Ea(e)||wa(e)&&Zg(t,r)}function Yg(e){return e.protocol==="https:"&&Jg(e.hostname)}function Ea(e){return e.protocol==="http:"&&Wg(e.hostname)}function Wg(e){return e==="localhost"||e==="127.0.0.1"||e==="[::1]"}function wa(e){return e.protocol==="http:"&&Kg(e.hostname)}function Zg(e,t){if(t.allowPrivateNetwork)return!0;try{const r=new URL(e);return Ea(r)||wa(r)}catch{return!1}}function Kg(e){const t=Xg(e);return t?t[0]===10||t[0]===172&&t[1]>=16&&t[1]<=31||t[0]===192&&t[1]===168:!1}function Xg(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 Jg(e){return e===Ec||e.endsWith(`.${Ec}`)}function ep(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||!Wu(e.launchUrl,a.href,e.locationBasePath))return;const c=new URL(a.href);if(!(c.username||c.password||c.searchParams.get(gu)!==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 Zu(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 tp(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 rp(){try{return{activeElement:globalThis.document?.activeElement??null,userActivation:globalThis.navigator?.userActivation}}catch{return{activeElement:null}}}const np=1e3;function ip(e,t=rp()){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<=np}const op="runtime.gate.probe",Ku=new Set(xt.map(e=>e.method));class sp{iframe;nonce;onReady;getWorkspaceCardLaunchContext;onHandshake;onDuplicateHandshake;onInternalEvent;onResponsePosted;onDevUploadSession;handleMessage;handleUserInteraction;dispatcher;environmentInfo;started=!1;destroyed=!1;handshaken=!1;bridgeVersion=mu;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:Gt,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:Gt,version:this.bridgeVersion,nonce:this.nonce,type:"event",method:t,payload:r})}postInternalRequest(t,r,n){this.destroyed||this.postMessage({namespace:Gt,version:this.bridgeVersion,nonce:this.nonce,type:"request",id:r,method:t,payload:n})}postProgress(t,r){this.bridgeVersion===2&&this.postMessage({namespace:Gt,version:2,nonce:this.nonce,type:"event",id:t,method:yu,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=ip(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&&Sh(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:Gt,version:this.bridgeVersion,nonce:this.nonce,type:"response",id:t.id,method:pu,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===op){this.postResponse(t,{ready:!0});return}if(!this.handshaken){this.postResponse(t,void 0,we("BRIDGE_NOT_READY","小程序 SDK 尚未完成握手"));return}if(!Ku.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=ya(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:Gt,version:t.version,nonce:this.nonce,type:"response",id:t.id,method:t.method,payload:r,error:n})||!ap(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 ap(e){return typeof e=="string"&&Ku.has(e)}function g(e,t,r){return r===void 0?{code:e,message:t}:{code:e,message:t,data:r}}function te(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ia(){const e=globalThis.crypto;if(!e||typeof e.getRandomValues!="function")throw g("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 g("FILE_IO_FAILED","无法生成安全文件标识")}}function Xu(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):ws,remove:o?s=>e.remove(s):el,read:s=>e.read(s),...typeof e.readPrefix=="function"?{readPrefix:(s,a)=>e.readPrefix(s,a)}:{},write:i?(s,a)=>e.write(s,a):ws,stat:s=>e.stat(s)})}function Ju(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=>Xu(e.file(a),n,{allowRemove:o}),directory:a=>Ju(e.directory(a),n,{allowRemove:o}),create:i?(a,c)=>e.create(a,c):ws,remove:s?(a,c)=>e.remove(a,c):el,stat:a=>e.stat(a),list:(a,c)=>e.list(a,c)})}function ws(){return Promise.reject(g("FILE_ACCESS_DENIED","当前文件授权只允许读取"))}function el(){return Promise.reject(g("FILE_ACCESS_DENIED","外部文件授权不允许删除"))}const cp=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"]),dp={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 Tr(e){const t=Aa(e),r=t&&cp.has(t)?g(t,dp[t]??"文件操作失败"):g("FILE_IO_FAILED","文件操作失败");return Object.defineProperty(r,"cause",{value:e,enumerable:!1}),r}function Nt(e){try{return e()}catch(t){throw Tr(t)}}function Aa(e){try{if(!te(e))return;const t=Object.getOwnPropertyDescriptor(e,"code");return t&&"value"in t&&typeof t.value=="string"?t.value:void 0}catch{return}}const Ic=1024;class _a{constructor(t,r){this.files=t,this.miniProgramDetail=r}handles=new Map;disposed=!1;createTransferScope(){return this.assertCanonicalDetail(),new _a(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 Hn(i.handle,{kind:"file",handleId:o})}registerFiles(t,r="external",n,i){this.assertCanonicalDetail();const o=Nt(()=>{if(!Array.isArray(t))throw g("FILE_IO_FAILED","Host 返回了无效文件选择结果");const a=t.length;if(i!==void 0&&a>i)throw g("FILE_IO_FAILED","Host 返回了过多文件选择结果");if(this.handles.size+a>Ic)throw g("FILE_QUOTA_EXCEEDED","当前会话的文件授权句柄已达上限");const c=[];for(let d=0;d<a;d+=1){if(!Object.prototype.hasOwnProperty.call(t,d))throw g("FILE_IO_FAILED","Host 返回了稀疏文件选择结果");c.push(this.prepareFile(t[d],r,n))}return c}),s=this.registerMany(o);return o.map((a,c)=>Hn(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 _c(i.handle,{kind:"directory",handleId:o})}resolveFile(t){return this.resolveFileEntry(t).handle}resolveDirectory(t){return this.resolveDirectoryEntry(t).handle}isCompanionAttachmentRef(t){return!Jt(t)||!("handleId"in t)?!1:this.handles.get(t.handleId)?.origin==="companion-attachment"}isGameSaveRef(t){return!Jt(t)||!("handleId"in t)?!1:this.handles.get(t.handleId)?.origin==="game-save"}isUserDataDownloadRef(t){return!Jt(t)||!("handleId"in t)?!1:this.handles.get(t.handleId)?.origin==="download"}resolveFileEntry(t){this.assertCanonicalDetail();const r=lp(t);if("handleId"in r){const s=this.readDirect(r.handleId,"file");return{ref:r,...s}}const n=this.resolveRoot(r.root),i=Dn(r.relativePath);Bo(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=fp(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==="."?".":Dn(r.relativePath);Bo(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 Nc(t),Hn(t,r)}describeListedEntries(t,r,n){return this.assertCanonicalDetail(),Nt(()=>{if(!Array.isArray(r))throw g("FILE_IO_FAILED","Host 返回了无效目录列表");const i=r.length;if(i>n)throw g("DIRECTORY_LIST_LIMIT_EXCEEDED","目录项数量超过限制");const o=[];for(let s=0;s<i;s+=1){if(!Object.prototype.hasOwnProperty.call(r,s))throw g("FILE_IO_FAILED","Host 返回了稀疏目录列表");const a=r[s];t.origin==="sandbox"&&te(a)&&typeof a.name=="string"&&tl(a.name)||o.push(this.describeListedEntry(t,a))}return this.assertCanonicalDetail(),o})}describeListedEntry(t,r){return Nt(()=>{if(te(r)&&r.kind==="file"){const n=this.prepareFile(r,t.origin,t.handle.mode);return Hn(n.handle,Ac(t.ref,n.handle.name))}if(te(r)&&r.kind==="directory"){const n=this.prepareDirectory(r,t.origin,t.handle.mode);return _c(n.handle,up(t.ref,n.handle.name))}throw g("FILE_IO_FAILED","Host 返回了无效目录项")})}deriveFile(t,r){this.assertCanonicalDetail();const n=On(r);Bo(t.origin,n);const i=this.prepareFile(Nt(()=>t.hostHandle.file(n)),t.origin,t.handle.mode);return{ref:Ac(t.ref,n),...i}}assertSandboxOrigin(t){if(t.origin!=="sandbox")throw g("FILE_ACCESS_DENIED","外部文件授权不允许删除")}prepareFile(t,r,n){return Nt(()=>{Nc(t);const i=n??t.mode;return Dc(t.mode,i),{handle:Xu(t,i,{allowRemove:r==="sandbox"}),hostHandle:t,origin:r}})}prepareDirectory(t,r,n,i=!1){return Nt(()=>{gp(t,i);const o=n??t.mode;return Dc(t.mode,o),{handle:Ju(t,o,{allowRemove:r==="sandbox"}),hostHandle:t,origin:r}})}registerMany(t){if(this.assertCanonicalDetail(),this.handles.size+t.length>Ic)throw g("FILE_QUOTA_EXCEEDED","当前会话的文件授权句柄已达上限");const r=new Set,n=t.map(()=>{for(let i=0;i<8;i+=1){const o=Ia();if(!this.handles.has(o)&&!r.has(o))return r.add(o),o}throw g("FILE_IO_FAILED","无法创建文件授权句柄")});return t.forEach((i,o)=>this.handles.set(n[o],i)),n}readDirect(t,r){if(!hp(t))throw g("FILE_ACCESS_REVOKED","文件授权句柄无效");const n=this.handles.get(t);if(!n)throw g("FILE_ACCESS_REVOKED","文件授权已失效");if(n.handle.kind!==r||n.hostHandle.kind!==r)throw g("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 g("FILE_ACCESS_REVOKED","文件授权已失效");if(!this.miniProgramDetail?.miniProgramId.trim())throw tt("files")}}function Dn(e){if(!fa(e))throw g("INVALID_PARAMS","relativePath 不是规范逻辑路径");return e}function Bo(e,t){if(e==="sandbox"&&tl(t))throw g("FILE_ACCESS_DENIED","Runtime 私有缓存不能通过沙箱路径访问")}function tl(e){return e.split("/").some(t=>t.replace(/[. ]+$/,"").toLowerCase()===".hb-game-saves")}function On(e,t="文件名"){const r=Dn(e);if(r.includes("/"))throw g("INVALID_PARAMS",`${t} 只能是 basename`);return r}function Ac(e,t){return"handleId"in e?{kind:"file",root:{kind:"directory",handleId:e.handleId},relativePath:t}:{kind:"file",root:e.root,relativePath:Dn(e.relativePath==="."?t:`${e.relativePath}/${t}`)}}function up(e,t){return"handleId"in e?{kind:"directory",root:{kind:"directory",handleId:e.handleId},relativePath:t}:{kind:"directory",root:e.root,relativePath:Dn(e.relativePath==="."?t:`${e.relativePath}/${t}`)}}function Hn(e,t){return{kind:"file",name:e.name,mode:e.mode,ref:t}}function _c(e,t){return{kind:"directory",name:e.name,mode:e.mode,ref:t}}function Dc(e,t){if(t==="readwrite"&&e!=="readwrite")throw g("FILE_ACCESS_DENIED","Host 未授予请求的文件写权限")}function lp(e){return Jt(e)||rl(),e}function fp(e){return wu(e)||rl(),e}function rl(){throw g("INVALID_PARAMS","文件引用不合法")}function hp(e){return/^[0-9a-f]{32}$/.test(e)}function mp(e){return te(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 Nc(e){if(!mp(e))throw g("FILE_IO_FAILED","Host 返回了无效 File handle");On(e.name,"Host File name")}function gp(e,t=!1){if(!te(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 g("FILE_IO_FAILED","Host 返回了无效 Directory handle");if(!t&&e.name.length===0)throw g("FILE_IO_FAILED","Host Directory name 不能为空");e.name&&On(e.name,"Host Directory name")}const pp=new Set(["content-length","content-encoding","transfer-encoding","content-disposition","content-range","content-type"]),yp=new Set(["content-length","content-encoding","content-disposition","content-range","content-type"]),Ep=new Set(["range","if-range","a-im"]),wp=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"]),Ip=/^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\..*)?$/i,Fn={initial:0,target:1,open:2,validate:3,transfer:4,committed:5,completed:6};class Ap{constructor(t){this.signal=t}phase="initial";transition(t){if(Fn[t]<=Fn[this.phase])throw g("FILE_IO_FAILED","下载状态转换不合法");this.phase=t}throwIfCancelled(){if(Fn[this.phase]<Fn.committed&&this.signal.aborted)throw ol()}normalizeHostError(t,r){return this.throwIfCancelled(),Na(t,r,this.signal)}}async function nl(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 Ap(o.signal);s.transition("target"),s.throwIfCancelled();let a;try{a=await Mp(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=Sp(c);Tp(c,u);const f=vp(c.status,u);if(e.maxBytes!==void 0&&f.expectedBytes!==void 0&&f.expectedBytes>e.maxBytes)throw g("FILE_TOO_LARGE","下载响应超过 maxBytes");s.throwIfCancelled();const l=bp(e,a,u,i);let p=0;const m=Dp(f.expectedBytes,e.maxBytes);Go(t,Vo(0,f));const E={...o,onProgress(v){!Number.isSafeInteger(v)||v<p||m!==void 0&&v>m||(p=v,Go(t,Vo(p,f)))}};s.transition("transfer"),d=!0;let w;try{w=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(v){throw s.normalizeHostError(v,"transfer")}s.transition("committed"),p=_p(w,f,p,e.maxBytes),Go(t,Vo(p,f));const I=i.describeFile(l.handle,l.ref);return s.transition("completed"),I}finally{d||Np(n.network,c.body)}}function _p(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 Dp(e,t){return e===void 0?t:t===void 0?e:Math.min(e,t)}function Np(e,t){try{Promise.resolve(e.release(t)).catch(()=>{})}catch{}}async function Mp(e,t,r){if(e.targetKind==="file"){const i=t.resolveFileEntry(e.to);return Is(i.handle.mode),await xp(i.handle,r),{kind:"file",...i}}const n=t.resolveDirectoryEntry(e.to);return Is(n.handle.mode),await Up(n.handle,r),{kind:"directory",...n}}function bp(e,t,r,n){if(t.kind==="file")return{ref:t.ref,handle:t.handle,hostHandle:t.hostHandle,mode:"replace-existing"};const i=Rp(e,r),o=n.deriveFile(t,i);return Is(o.handle.mode),{...o,mode:e.overwrite===!0?"upsert":"create-exclusive"}}function Sp(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 g("DOWNLOAD_NETWORK_FAILED","Host 返回了无效 stream response");if(!te(e.headers))throw g("DOWNLOAD_NETWORK_FAILED","Host 返回了无效 stream headers");const t={};for(const[r,n]of Object.entries(e.headers)){if(r!==r.toLowerCase()||!pp.has(r)||!Array.isArray(n)||n.length===0)throw g("DOWNLOAD_NETWORK_FAILED","Host 返回了不安全 stream header");if(n.some(i=>typeof i!="string"||/[\r\n]/.test(i)))throw g("DOWNLOAD_NETWORK_FAILED","Host 返回了无效 stream header value");t[r]=[...n]}return t}function Tp(e,t){if(e.status<200||e.status>=300||e.status===206||e.status===226)throw g("DOWNLOAD_HTTP_STATUS",`下载请求失败: HTTP ${e.status}`,{status:e.status,...e.statusText===void 0?{}:{statusText:e.statusText},headers:Cp(t,yp)});if((t["content-range"]?.length??0)>0)throw g("DOWNLOAD_NETWORK_FAILED","下载响应包含 Content-Range")}function vp(e,t){const r=t["content-length"]??[],n=t["transfer-encoding"]??[];if(r.length>0&&n.length>0)throw g("DOWNLOAD_NETWORK_FAILED","下载响应同时包含 Transfer-Encoding 与 Content-Length");if((e===204||e===205)&&r.some(d=>d!=="0"))throw g("DOWNLOAD_NETWORK_FAILED","无内容响应声明了非零 Content-Length");if((e===204||e===205)&&n.length>0)throw g("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=Op(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 Op(e){return!e||e.length===0?!0:e.length===1&&e[0].trim().toLowerCase()==="identity"}function Vo(e,t){return{loaded:e,...t.total===void 0?{}:{total:t.total},lengthComputable:t.lengthComputable}}function Go(e,t){try{e.postProgress(t)}catch{}}function Rp(e,t){const r=t["content-disposition"]??[];for(const i of r){const o=kp(i);if(o&&ti(o))return o}for(const i of r){const o=Pp(i);if(o&&ti(o))return o}if(e.suggestedName!==void 0)return Da(e.suggestedName);const n=Lp(e.url);return n&&ti(n)?n:"download.bin"}function kp(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 Pp(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 Lp(e){const t=e.pathname.split("/").pop();if(t)try{return decodeURIComponent(t)}catch{return}}function Da(e){try{On(e,"suggestedName")}catch{throw g("INVALID_PARAMS","suggestedName 不是安全 basename")}if(!ti(e))throw g("INVALID_PARAMS","suggestedName 不是安全 basename");return e}function ti(e){return!(!e||e==="."||e===".."||Array.from(e).length>255||/[\\/<>:"|?*\u0000-\u001f\u007f]/.test(e)||/[. ]$/.test(e)||Ip.test(e))}function Cp(e,t){return Object.fromEntries(Object.entries(e).filter(([r])=>t.has(r)).map(([r,n])=>[r,n.join(", ")]))}async function xp(e,t){try{const r=await e.stat(t);if(!r||r.kind!=="file")throw il()}catch(r){throw Na(r,"file",t.signal)}}async function Up(e,t){try{const r=await e.stat(t);if(!r||r.kind!=="directory")throw il()}catch(r){throw Na(r,"file",t.signal)}}function Is(e){if(e!=="readwrite")throw g("FILE_ACCESS_DENIED","下载目标只允许读取")}const jp={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 Na(e,t,r){if(r.aborted)return ol();const n=zp(e);if(n&&wp.has(n)){const o=g(n,jp[n]??"下载失败");return Object.defineProperty(o,"cause",{value:e,enumerable:!1}),o}if(e instanceof Error&&e.name==="AbortError")return t==="network"||t==="transfer"?g("DOWNLOAD_TIMEOUT","下载网络请求超时"):g("FILE_IO_FAILED","下载文件写入失败");const i=t==="network"?g("DOWNLOAD_NETWORK_FAILED","下载网络请求失败"):g("FILE_IO_FAILED","下载文件写入失败");return Object.defineProperty(i,"cause",{value:e,enumerable:!1}),i}function zp(e){return te(e)&&typeof e.code=="string"?e.code:void 0}function il(){return g("FILE_TYPE_MISMATCH","下载目标类型不匹配")}function ol(){return g("DOWNLOAD_CANCELLED","下载已取消")}function Hp(e){if(!e)return;const t=Object.keys(e).find(r=>Ep.has(r.trim().toLowerCase()));if(t)throw g("INVALID_PARAMS",`network.download 不允许设置请求头: ${t}`)}const Mc=8*1024*1024,Fp=32*1024*1024;function Ma(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 g("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 g("INVALID_RESPONSE","存档下载描述无效");if(u.size_bytes>Mc)throw g("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(!Hu(f)||new URL(a.download_url).pathname!==`/cloud_archive/${u.file_id}.zip`||a.expires_at<=Date.now())throw g("INVALID_RESPONSE","存档下载地址无效");s(d);const l=Math.min(Mc,Fp-r);if(l<=0)throw g("FILE_QUOTA_EXCEEDED","当前会话存档缓存已达上限");const p=e.files.sandbox.file(`.hb-game-saves/${Ia()}.zip`);if(!p.remove)throw g("REQUEST_UNSUPPORTED","宿主不支持私有存档清理");r+=l;let m=!1;try{await e.files.sandbox.directory(".hb-game-saves").create({recursive:!0,exclusive:!1},d),await p.create({recursive:!0,exclusive:!0},d);const E=e.registry.createTransferScope();try{const y=E.registerFile(p,"game-save","readwrite");await nl({request:f,url:new URL(a.download_url),to:y.ref,targetKind:"file",maxBytes:l},{...d,trustedUserGesture:!1,postEvent:()=>{},postProgress:()=>{}},{transfer:e.transfer,fileRegistry:E,operationContext:d})}finally{E.dispose()}s(d);const w=(await p.stat(d)).size;if(!Number.isSafeInteger(w)||w<0||w>l)throw g("FILE_TOO_LARGE","存档实际大小超过限额");await c(d),s(d);const I=async()=>{throw g("FILE_ACCESS_DENIED","存档文件只读")},v={kind:"file",mode:"read",name:u.name,create:I,write:I,async read(y){s(y),await c(y);const O=await p.read(y);try{if(s(y),await c(y),O.byteLength!==w)throw g("INVALID_RESPONSE","私有存档副本长度不匹配");return O}catch(j){throw O.fill(0),j}},async stat(y){return s(y),await c(y),await p.stat(y),s(y),await c(y),{kind:"file",size:w,...typeof u.modified_at=="number"&&Number.isSafeInteger(u.modified_at)?{modifiedAt:u.modified_at}:{}}}};return r-=l-w,t.set(v,{target:p,size:w}),m=!0,v}finally{m||(r-=l,await i(p))}}}}const Bp=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*)(?:\.(?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*))*))?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/;function Vp(e){if(!e?.minimumSdkVersion)throw we("MINIMUM_SDK_VERSION_UNAVAILABLE","平台最低 SDK 版本配置不可用");const t=Wt(e.minimumSdkVersion),r=e.sdkVersion?Wt(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=Wt("0.6.0");if(!r){if(ri(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(ri(r,t)<0)throw we("SDK_VERSION_TOO_LOW","小程序 SDK 版本低于平台最低要求");return{heartbeatEnabled:ri(r,Wt("0.6.0-0"))>=0,sdkVersion:e.sdkVersion}}function Gp(e,t){if(typeof t!="string"||!Wt(t))throw we("SDK_VERSION_INVALID","SDK handshake 版本不合法");if(t!==e)throw we("SDK_VERSION_MISMATCH","SDK handshake 版本与 Version record 不一致")}function ba(e,t){const r=Wt(e),n=Wt(t);if(!(!r||!n))return ri(r,n)}function Wt(e){const t=Bp.exec(e);if(t)return{major:Number(t[1]),minor:Number(t[2]),patch:Number(t[3]),prerelease:t[4]?.split(".").map(r=>/^\d+$/.test(r)?Number(r):r)??[]}}function ri(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 $p(e){return{[fn]:async(t,r)=>{const n=Se(e.operationContext,r.signal);if(pe(n.signal),t!==void 0)throw g("INVALID_PARAMS","user.showAppreciation 不支持参数");if(!r.trustedUserGesture)throw g("USER_GESTURE_REQUIRED","请通过点击打开赞赏码");const i=e.miniProgramPresentation;if(!i?.name||!i.author)throw g("INVALID_STATE","缺少小程序名称或开发者信息,无法展示赞赏码");const o=e.presentation.showAppreciation;if(!o)throw g("REQUEST_UNSUPPORTED","当前宿主不支持赞赏码");await fe(()=>o({name:i.name,author:i.author},n),n.signal)}}}function dr(){const e=new Error("Runtime cache read cancelled");return e.name="AbortError",e}function bc(e,t){return e.length===t.length&&e.every((r,n)=>r===t[n])}function sl(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,w){try{e.onEvent&&Promise.resolve(e.onEvent({namespace:E,type:w})).catch(()=>{})}catch{}}function u(E){const w=r.get(E);if(!w)throw new Error("Unknown runtime cache scope");return w}function f(E,w){return E.flatMap((I,v)=>{const y=JSON.stringify(E.slice(0,v+1));return[JSON.stringify([y]),JSON.stringify([y,w])]})}function l(E,w){return JSON.stringify(f(E,w).map(I=>n.get(I)??0))}async function p(E,w){const I=u(E),v=JSON.stringify([JSON.stringify(I),...w?[w]:[]]),y=(n.get(v)??0)+1;n.set(v,y),i.add(v);for(const O of a)O(I,w);if(!e.store){i.delete(v),d(w??"*","invalidation");return}try{await e.store.invalidate(I,w)}catch(O){throw d(w??"*","storage_error"),O}n.get(v)===y&&i.delete(v),d(w??"*","invalidation")}function m(E){if(c)throw new Error("Runtime cache manager disposed");const w=o.get(E.namespace);if(w){if(w.sourceCodec!==E.codec||w.definition.codec.version!==E.codec.version||JSON.stringify(w.definition.policy)!==JSON.stringify(E.policy))throw new Error("Conflicting runtime cache namespace");return w.cache}if(!E.namespace||!E.codec.version)throw new Error("Invalid runtime cache definition");const I=Object.freeze({...E.policy}),v=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)}),y=E.namespace;for(const S of[I.ttlMs,I.memoryMaxEntries,I.diskMaxEntries,I.diskMaxBytes,I.maxEntryBytes])if(!Number.isFinite(S)||S<0)throw new Error("Invalid runtime cache policy");const O=new Map,j=new Map,b=new Map;let T=!1;function D(S,M,H){if(c||T||S.aborted||l(M,y)!==H)throw dr()}function x(S){return I.ttlMs>0&&I.persistence==="memory-and-disk"&&!!e.store&&!f(S,y).some(M=>i.has(M))}function P(S,M,H){const F=t();return S.envelopeVersion===1&&JSON.stringify(S.address)===JSON.stringify(M)&&bc(S.revisions,H)&&S.payload.byteLength<=I.maxEntryBytes&&Number.isFinite(S.cachedAt)&&Number.isFinite(S.expiresAt)&&S.cachedAt<=F&&S.cachedAt>=0&&S.expiresAt>S.cachedAt&&Math.min(S.expiresAt,S.cachedAt+I.ttlMs)>F}function Q(S,M,H,F,$){if(!(I.ttlMs<=0||I.memoryMaxEntries<1)){for(const[K,h]of O)Math.min(h.entry.expiresAt,h.entry.cachedAt+I.ttlMs)<=t()&&O.delete(K);for(O.delete(S);O.size>=Math.floor(I.memoryMaxEntries);){const K=O.keys().next();if(K.done)break;O.delete(K.value)}O.set(S,{entry:M,value:H,epoch:F,persistent:$})}}async function R(S,M,H,F){const $={namespace:y,codecVersion:v.version,scopeIds:M,key:S.key},K=JSON.stringify($);let h=[],N=x(M);if(N)try{h=await e.store.readRevisions(M,y)}catch{N=!1,d(y,"storage_error")}D(F.signal,M,H);async function U(){if(!N)return!0;try{return bc(h,await e.store.readRevisions(M,y))}catch{return N=!1,d(y,"storage_error"),!1}}const q=O.get(K);if(I.ttlMs>0&&q&&q.epoch===H&&P(q.entry,$,h)&&q.persistent===N&&await U())return D(F.signal,M,H),d(y,"memory_hit"),q.value;if(O.delete(K),N){let ce,le;try{ce=await e.store.read($,I.maxEntryBytes),ce&&P(ce,$,h)?le=v.decode(ce.payload):ce=void 0}catch{ce=void 0,d(y,"storage_error")}if(D(F.signal,M,H),ce&&await U())return D(F.signal,M,H),Q(K,ce,le,H,!0),d(y,"disk_hit"),le}d(y,"miss");const ae=v.validate(await S.load(F.signal));D(F.signal,M,H);const de=v.clone(ae);if(!await U()&&N)throw dr();if(D(F.signal,M,H),I.ttlMs>0){const ce=t();let le;try{le=v.encode(de)}catch{return de}const Ee={envelopeVersion:1,address:$,revisions:N?h:[],cachedAt:ce,expiresAt:ce+I.ttlMs,payload:le};if(N&&le.byteLength<=I.maxEntryBytes){let me=!0,ge=!1;try{me=await e.store.publish(Ee,I),ge=me}catch{d(y,"storage_error")}if(D(F.signal,M,H),!me)throw dr();ge&&d(y,"published")}D(F.signal,M,H),Q(K,Ee,de,H,N)}return de}async function L(S){if(c||T||S.signal?.aborted)return Promise.reject(dr());const M=u(S.scope),H=l(M,y);let F;if(x(M)){const N=new AbortController;b.set(N,M);const U=()=>N.abort();S.signal?.addEventListener("abort",U,{once:!0});let q=()=>{};try{F=await Promise.race([e.store.readRevisions(M,y),new Promise((ae,de)=>{const ce=()=>de(dr());N.signal.addEventListener("abort",ce,{once:!0}),q=()=>N.signal.removeEventListener("abort",ce)})])}catch{N.signal.aborted||d(y,"storage_error")}finally{q(),b.delete(N),S.signal?.removeEventListener("abort",U)}}D(S.signal??new AbortController().signal,M,H);const $=JSON.stringify([M,S.key,H,F]);let K=j.get($);if(K?.controller.signal.aborted&&(K=void 0),!K){const N=new AbortController;K={ids:M,controller:N,waiters:0,promise:Promise.resolve(void 0)};const U=K;U.promise=R(S,M,H,N).finally(()=>{j.get($)===U&&j.delete($)}),j.set($,U)}const h=K;return h.waiters+=1,new Promise((N,U)=>{let q=!1;function ae(ce){q||(q=!0,S.signal?.removeEventListener("abort",de),h.controller.signal.removeEventListener("abort",de),h.waiters-=1,h.waiters===0&&h.controller.abort(),ce())}function de(){ae(()=>U(dr()))}S.signal?.addEventListener("abort",de,{once:!0}),h.controller.signal.addEventListener("abort",de,{once:!0}),h.promise.then(ce=>ae(()=>{try{D(S.signal??new AbortController().signal,M,H),N(v.clone(ce))}catch(le){U(le)}}),ce=>ae(()=>U(ce)))})}function C(S,M){if(M&&M!==y)return;const H=F=>S.every(($,K)=>F[K]===$);for(const[F,$]of O)H($.entry.address.scopeIds)&&O.delete(F);for(const[F,$]of j)H($.ids)&&($.controller.abort(),j.delete(F));for(const[F,$]of b)H($)&&F.abort()}function z(){if(!T){T=!0,O.clear();for(const S of b.keys())S.abort();b.clear();for(const S of j.values())S.controller.abort();j.clear(),s.delete(z),a.delete(C),o.get(y)?.cache===k&&o.delete(y)}}const k={read:L,invalidateScope:S=>p(S,y),dispose:z};return s.add(z),a.add(C),o.set(y,{definition:{namespace:y,codec:v,policy:I},sourceCodec:E.codec,cache:k}),k}return{createScope(E,w){if(c||!E)throw new Error("Invalid runtime cache scope");const I=Object.freeze({});return r.set(I,[...w?u(w):[],E]),I},register:m,invalidateScope:E=>p(E),dispose(){if(!c){c=!0;for(const E of[...s])E();o.clear(),n.clear(),i.clear()}}}}function Qp(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 qp=".hb-runtime-cache-v1",Yp=1e3,$o=64*1024,ur=1e3,Wp=2048,$r=32*1024*1024,Zp=1024,ni=new TextEncoder,Sc=new TextDecoder("utf-8",{fatal:!0});function Qr(){return Object.assign(new Error("缓存文件操作已取消"),{name:"AbortError"})}async function Bn(e){const t=await globalThis.crypto.subtle.digest("SHA-256",ni.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 Tc(){return Array.from(globalThis.crypto.getRandomValues(new Uint8Array(16)),e=>e.toString(16).padStart(2,"0")).join("")}function Kp(e){return!!e&&typeof e=="object"&&["METHOD_FORBIDDEN","NOT_SUPPORTED","UNSUPPORTED_OPERATION","ENOSYS","ENOTSUP","EOPNOTSUPP"].includes(String(e.code))}function vc(e,t){if(t.some(r=>typeof e[r]!="function"))throw Object.assign(new Error("Host 文件原语不完整,关闭磁盘缓存"),{code:"METHOD_FORBIDDEN"})}function Xp(e,t){const r=e.sandbox.directory(qp),n=r.directory("revisions"),i=r.directory("entries");for(const R of[r,n,i,i.directory("capability-check")])vc(R,["directory","file","create","stat","list","remove"]),vc(R.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(R){d=R,o.abort(),t.signal.removeEventListener("abort",s)}function f(R){if(Kp(R))throw u(R),R}function l(){if(d)throw d;if(a.signal.aborted)throw Qr()}function p(R,L=a.signal){const C=c.then(()=>{if(L.aborted)throw d??Qr();return l(),R()},()=>{if(L.aborted)throw d??Qr();return l(),R()}).catch(M=>{throw f(M),M});if(c=C.catch(()=>{}),L.aborted)return Promise.reject(d??Qr());let z=()=>{};const k=new Promise((M,H)=>{const F=()=>H(d??Qr());L.addEventListener("abort",F,{once:!0}),z=()=>L.removeEventListener("abort",F)}),S=setTimeout(()=>{u(Object.assign(new Error("缓存文件操作超时,已降级为内存缓存"),{code:"CACHE_STORAGE_TIMEOUT"}))},Yp);return Promise.race([C,k]).finally(()=>{clearTimeout(S),z()})}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(R,L){const C=n.file(`${await Bn([R,L??null])}.revision`);await I(C);let z=!1;try{await C.create({recursive:!1,exclusive:!0},a),z=!0}catch(M){f(M),l()}if(z){const M=Tc();return await C.write(ni.encode(M),a),l(),M}const k=await C.stat(a);if(k.size<1||k.size>128)throw new Error("缓存 revision 文件损坏");const S=Sc.decode(await C.read(a));if(!/^(?:[0-9a-f]{32}|[0-9a-f-]{36})$/.test(S))throw new Error("缓存 revision 文件损坏");return l(),S}async function w(R){const L=await R.list({limit:ur},a);if(L.length>=ur)throw new Error("缓存目录超过治理上限");return L}async function I(R){try{await R.stat(a);return}catch(C){if(!Vn(C))throw C}if((await w(n)).length>=ur-1)throw new Error("缓存 metadata 超过治理上限")}async function v(R,L){await m();const C=[];for(let z=0;z<R.length;z+=1){const k=R.slice(0,z+1);C.push(await E(k),await E(k,L))}return C}async function y(R){return r.directory(`entries/${await Bn([R.namespace,R.codecVersion,R.scopeIds])}`)}async function O(R){return(await y(R)).file(`${await Bn(R.key)}.cache`)}async function j(R,L){const C=await R.stat(a);if(C.size<5||C.size>L+$o+4)throw new Error("缓存条目超过大小限制");const z=await R.read(a);if(l(),z.length!==C.size)throw new Error("缓存条目读取不完整");const k=new DataView(z.buffer,z.byteOffset,z.byteLength).getUint32(0);if(k<1||k>$o||k+4>z.length)throw new Error("缓存信封损坏");const S=JSON.parse(Sc.decode(z.subarray(4,k+4))),M=z.slice(k+4);if(S.envelopeVersion!==1||!S.address||!Array.isArray(S.address.scopeIds)||!S.address.scopeIds.every(H=>typeof H=="string")||typeof S.address.namespace!="string"||typeof S.address.codecVersion!="string"||typeof S.address.key!="string"||!Array.isArray(S.revisions)||S.revisions.length!==S.address.scopeIds.length*2||!S.revisions.every(H=>typeof H=="string"&&H.length>0)||!Number.isSafeInteger(S.cachedAt)||!Number.isSafeInteger(S.expiresAt)||S.cachedAt<0||S.expiresAt<=S.cachedAt||S.payloadBytes!==M.length||M.length>L)throw new Error("缓存信封损坏");return{envelopeVersion:1,address:S.address,revisions:S.revisions,cachedAt:S.cachedAt,expiresAt:S.expiresAt,payload:M}}async function b(R){if(!R.remove)throw new Error("Host 不支持缓存文件删除");await R.remove(a)}async function T(R){try{if((await R.file.stat(a)).size!==R.size)return!1;const L=await j(R.file,$r);return!ht(L.address,R.entry.address)||!ht(L.revisions,R.entry.revisions)||L.cachedAt!==R.entry.cachedAt||L.expiresAt!==R.entry.expiresAt||!ht(await D(L.payload),await D(R.entry.payload))?!1:(await b(R.file),!0)}catch(L){if(Vn(L))return!0;throw L}}async function D(R){const L=await globalThis.crypto.subtle.digest("SHA-256",R);return Array.from(new Uint8Array(L),C=>C.toString(16).padStart(2,"0")).join("")}async function x(){const R=await w(n);let L=0;for(const S of R)if(S.kind==="file"&&(L+=(await S.stat(a)).size,L>$r))throw new Error("缓存扫描超过字节上限");const C=[];let z=0,k=L;for(const S of await w(i)){if(S.kind!=="directory")throw new Error("缓存目录结构损坏");for(const M of await w(S)){if(M.kind!=="file"||++z>Wp)throw new Error("缓存文件超过治理上限");const H=(await M.stat(a)).size;if(k+=H,k>$r)throw new Error("缓存扫描超过字节上限");try{const F=await j(M,$r);C.push({file:M,entry:F,size:(await M.stat(a)).size,bucketName:S.name})}catch(F){f(F),l(),Vn(F)||await b(M)}}}return{entries:C,metadataBytes:L}}async function P(){for(const R of await w(i))if(R.kind==="directory"&&R.remove&&(await w(R)).length===0)try{await R.remove({recursive:!1},a)}catch(L){f(L),l()}}function Q(R){const{payload:L,...C}=R,z=ni.encode(JSON.stringify({...C,payloadBytes:L.length}));if(z.length>$o)throw new Error("缓存信封过大");const k=new Uint8Array(4+z.length+L.length);return new DataView(k.buffer).setUint32(0,z.length),k.set(z,4),k.set(L,z.length+4),k}return{readRevisions:(R,L)=>p(()=>v(R,L)),read:(R,L)=>p(async()=>{l();const C=await O(R);let z;try{z=await j(C,L)}catch(k){if(l(),Vn(k))return;throw k}if(!(!ht(z.address,R)||z.expiresAt<=Date.now())&&ht(z.revisions,await v(R.scopeIds,R.namespace)))return z}),publish:(R,L)=>p(async()=>{l();const{address:C}=R;if(!ht(R.revisions,await v(C.scopeIds,C.namespace)))return!1;const z=Q(R);if(R.payload.length>L.maxEntryBytes||z.length>L.diskMaxBytes||L.diskMaxEntries<1)throw new Error("缓存条目超出容量预算");await m();const k=await y(C),S=await O(C),M=await x(),H=[],F=new Map;for(const h of M.entries){if(h.bucketName===k.name&&h.file.name===S.name)continue;const N=JSON.stringify([h.entry.address.scopeIds,h.entry.address.namespace]);let U=F.get(N);if(U||(U=await v(h.entry.address.scopeIds,h.entry.address.namespace),F.set(N,U)),h.entry.expiresAt<=Date.now()||!ht(h.entry.revisions,U)){if(!await T(h))throw new Error("缓存治理期间条目已变化")}else H.push(h)}H.sort((h,N)=>h.entry.cachedAt-N.entry.cachedAt);function $(){const h=H.filter(N=>N.bucketName===k.name);return H.length+1>Zp||z.length+M.metadataBytes+H.reduce((N,U)=>N+U.size,0)>$r||h.length+1>Math.min(L.diskMaxEntries,ur-1)||z.length+h.reduce((N,U)=>N+U.size,0)>L.diskMaxBytes}for(;$();){const h=H.filter(q=>q.bucketName===k.name),U=h.length+1>Math.min(L.diskMaxEntries,ur-1)||z.length+h.reduce((q,ae)=>q+ae.size,0)>L.diskMaxBytes?h[0]:H[0];if(!U||!await T(U))throw new Error("缓存容量不足或条目已变化");H.splice(H.indexOf(U),1)}await P();const K=await w(i);if(!K.some(h=>h.name===k.name)&&K.length>=ur-1)throw new Error("缓存目录超过治理上限");if(await k.create({recursive:!0,exclusive:!1},a),!ht(R.revisions,await v(C.scopeIds,C.namespace)))return!1;try{await S.create({recursive:!1,exclusive:!0},a)}catch(h){f(h),await S.stat(a)}return await S.write(z,a),l(),ht(R.revisions,await v(C.scopeIds,C.namespace))}),invalidate:(R,L)=>p(async()=>{await m();const C=n.file(`${await Bn([R,L??null])}.revision`);await I(C);try{await C.create({recursive:!1,exclusive:!0},a)}catch(z){f(z),await C.stat(a)}await C.write(ni.encode(Tc()),a),l();try{const{entries:z}=await x();for(const k of z){if(L!==void 0&&k.entry.address.namespace!==L||!R.every((M,H)=>k.entry.address.scopeIds[H]===M))continue;const S=await v(k.entry.address.scopeIds,k.entry.address.namespace);ht(k.entry.revisions,S)||await T(k)}await P()}catch(z){f(z),l()}})}}function Vn(e){return!!e&&typeof e=="object"&&["FILE_NOT_FOUND","ENOENT","NOT_FOUND"].includes(String(e.code))}const Jp="RATE_LIMITED_BY_RUNTIME",ey="RATE_LIMITED",al=20,cl=40,dl=150,ul=20,ll=1e4,fl=45e3,hl=1,ty=300*1e3,ry=64;function lr(e,t){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:t}function ny(e,t){return typeof e=="number"&&Number.isFinite(e)&&e>=0?Math.floor(e):t}function iy(e={}){const t=e.now??Date.now,r=ny(e.coalesceWindowMs,dl),n=e.budget===!1?void 0:{ratePerSecond:Math.max(.001,lr(e.budget?.ratePerSecond,al)),burst:Math.max(1,Math.floor(lr(e.budget?.burst,cl)))},i=e.loopDetection===!1?void 0:{maxCalls:Math.max(1,Math.floor(lr(e.loopDetection?.maxCalls,ul))),windowMs:Math.max(1,Math.floor(lr(e.loopDetection?.windowMs,ll)))},o=e.circuitBreaker===!1?void 0:{failureThreshold:Math.max(1,Math.floor(lr(e.circuitBreaker?.failureThreshold,hl))),openMs:Math.max(1,Math.floor(lr(e.circuitBreaker?.openMs,fl)))},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 p(T){try{e.onReport?.(T)}catch{}}function m(T,D){if(!i)return{exceeded:!1,count:0};const x=a.get(T)??[],P=D-i.windowMs;let Q=0;for(;Q<x.length&&x[Q]<=P;)Q+=1;Q>0&&x.splice(0,Q);const R=x.length>=i.maxCalls;return R||(x.push(D),x.length>i.maxCalls+1&&x.splice(0,x.length-(i.maxCalls+1))),a.set(T,x),{exceeded:R,count:x.length}}function E(T){if(!n)return!0;const D=Math.max(0,T-u.updatedAt)/1e3;return u.tokens=Math.min(n.burst,u.tokens+D*n.ratePerSecond),u.updatedAt=T,u.tokens<1?!1:(u.tokens-=1,!0)}function w(T){if(!n)return 0;const D=Math.max(0,T-u.updatedAt)/1e3,x=Math.min(n.burst,u.tokens+D*n.ratePerSecond);return Math.max(0,Math.ceil((1-x)/n.ratePerSecond*1e3))}function I(T,D,x,P,Q){if(!o)return;const R=d.get(D),L=(R?.open?0:R?.failures??0)+1;if(L<o.failureThreshold){d.set(D,{open:!1,openedAt:0,openMs:0,failures:L});return}const C=Math.min(Math.max(o.openMs,P),ty);d.set(D,{open:!0,openedAt:Q,openMs:C,failures:L}),f.circuitOpened+=1,p({type:"circuit_opened",capability:T,endpointId:D,status:x,openMs:C,timestamp:Q})}function v(T){const D=d.get(T);D&&!D.open&&d.delete(T)}function y(T){for(const[D,x]of s)!x.pending&&x.expiresAt<=T&&s.delete(D);for(;s.size>=ry;){const D=[...s].find(([,x])=>!x.pending);if(!D)break;s.delete(D[0])}}function O(T,D){if(T===void 0)return;const x=s.get(T);x?.promise===D&&(x.pending=!1)}function j(T,D){if(T===void 0)return;s.get(T)?.promise===D&&s.delete(T)}async function b(T){if(l)return T.load();const D=t();if(o){const R=d.get(T.endpointId);if(R?.open){const L=R.openedAt+R.openMs-D;if(L>0)throw f.circuitRejected+=1,p({type:"circuit_rejected",capability:T.capability,endpointId:T.endpointId,retryAfterMs:L,timestamp:D}),ay("上游已被网关限流,Runtime 熔断中,请稍后重试",{origin:"circuit",reason:"circuit_open",endpointId:T.endpointId,retryAfterMs:L});d.delete(T.endpointId)}}const x=m(T.endpointId,D);x.exceeded&&i?c.has(T.endpointId)||(c.add(T.endpointId),p({type:"loop_detected",capability:T.capability,endpointId:T.endpointId,count:x.count,windowMs:i.windowMs,timestamp:D})):c.delete(T.endpointId);const P=r>0?T.coalesceKey:void 0;if(P!==void 0){const R=s.get(P);if(R&&(R.pending||R.expiresAt>D))return f.coalesced+=1,p({type:"coalesced",capability:T.capability,endpointId:T.endpointId,timestamp:D}),R.promise;R&&s.delete(P)}if(x.exceeded&&i)throw f.loopRejected+=1,Oc("检测到同一 endpoint 的高频循环调用,本次请求已在 Runtime 本地拒绝",{origin:"loop",reason:"loop",capability:T.capability,endpointId:T.endpointId,count:x.count,windowMs:i.windowMs});if(!E(D)){f.budgetRejected+=1;const R=w(D);throw p({type:"budget_exhausted",capability:T.capability,endpointId:T.endpointId,retryAfterMs:R,timestamp:D}),Oc("请求过于频繁,已触发 Runtime 本地配额限制",{origin:"budget",reason:"budget",capability:T.capability,endpointId:T.endpointId,retryAfterMs:R})}P!==void 0&&y(D);const Q=T.load().then(R=>(O(P,Q),v(T.endpointId),R),R=>{j(P,Q);const L=oy(R);throw L!==void 0&&I(T.capability,T.endpointId,L,sy(R),D),R});return P!==void 0&&s.set(P,{endpointId:T.endpointId,promise:Q,expiresAt:D+r,pending:!0}),Q}return{execute:b,invalidateCoalescing(T){if(T===void 0){s.clear();return}for(const[D,x]of s)T.includes(x.endpointId)&&s.delete(D)},snapshot(){return{...f,openCircuits:[...d.entries()].filter(([,T])=>T.open).map(([T])=>T)}},dispose(){l||(l=!0,s.clear(),a.clear(),c.clear(),d.clear())}}}function oy(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 sy(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 Oc(e,t){return{code:Jp,message:e,data:t}}function ay(e,t){return{code:ey,message:e,data:t}}const ml=3e4,gl=6e4,As=1440*60*1e3;function cy(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??ml)):0,profileTtlMs:t?Math.max(0,Math.floor(r?.profileTtlMs??gl)):0,steamGameListTtlMs:t?dy(r?.steamGameListTtlMs):0,gateOptions:{budget:r?.budget??{ratePerSecond:al,burst:cl},coalesceWindowMs:r?.coalesceWindowMs??dl,loopDetection:r?.loopDetection??{maxCalls:ul,windowMs:ll},circuitBreaker:r?.circuitBreaker??{failureThreshold:hl,openMs:fl}}}}function dy(e){return e===void 0||!Number.isFinite(e)?As:Math.max(0,Math.floor(e))}function uy(e){return typeof e=="object"&&e!==null}function Te(e,t){const r=e.data;if(!uy(r)||typeof r.status!="string")throw new Error(t);return r}const pl={auth:"optional",channel:"api",id:"heybox.account.user_base_info.envelope.get",method:"GET",path:"/account/get_user_base_info"},ly={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 Rn(e){const t=e.runtimeAuthContextToken?.trim();return{mini_program_id:e.miniProgramId,...t?{runtime_auth_context_token:t}:{}}}function fy(e){return{challenge:e.challenge,expiresIn:e.expires_in,requestedScopes:e.requested_scopes||[],displayedScopes:e.displayed_scopes||[],consentUiVersion:e.consent_ui_version}}function hy(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=fy(r.consent_challenge)),{...t,result:n}}const my={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=>({...Rn(e.runtimeContext),challenge:e.challenge}),parse:e=>Te(e,"小程序授权取消接口响应异常")},gy={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=>Rn(e.runtimeContext),parse:e=>Te(e,"小程序授权撤销接口响应异常")},py={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=>Rn(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}:{}}}}},yy={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=>({...Rn(e.runtimeContext),...e.scopes?.length?{scopes:e.scopes.join(",")}:{}}),parse:e=>hy(e)},Ey={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=>({...Rn(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}}}},wy=64;function yl(e){const t=e.ttlMs,r=Math.max(1,Math.floor(e.maxEntries??wy)),n=e.now??Date.now,i=new Map,o=new Map;let s=0,a=!1;function c(f){for(const[l,p]of i)p.expiresAt<=f&&i.delete(l)}function d(f,l,p){if(a||t<=0||p!==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 w=i.get(f);if(w&&w.expiresAt>n())return Promise.resolve(w.value);w&&i.delete(f)}const p=o.get(f);if(p)return p;const m=s,E=l().then(w=>(d(f,w,m),w)).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 Iy(e,t){return t?e?"server":"local":"legacy"}function Ay(e,t){if(e==="local")throw g("SERVER_API_REQUIRED",`${t} 需要 effective network 启用后才能使用`)}const _y=["baseURL","errorMode","jsonParseMode","observability","queryEncoding","responseType","security"],Dy=new Set(["auth","body","bodyEncoding","channel","failurePresentation","headers","id","method","parse","path","query","timeout"]),Ny=/authorization|cookie|pkey|password|secret|token/i,El=/authorization|cookie|pkey|token|password|secret/i;function mt(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function My(e){for(const t of Object.keys(e))if(!Dy.has(t))throw new Ce(`endpoint 字段不受 hb-sdk-runtime private mapper 支持: ${t}`);for(const t of _y)if(Object.prototype.hasOwnProperty.call(e,t)&&mt(e,t)!==void 0)throw new Ce(`endpoint 字段不受 hb-sdk-runtime private mapper 支持: ${t}`);if(mt(e,"bodyEncoding")!==void 0&&mt(e,"bodyEncoding")!=="json"&&mt(e,"bodyEncoding")!=="form")throw new Ce("endpoint bodyEncoding 不受 HostNetworkPort 支持");if(mt(e,"failurePresentation")!==void 0&&mt(e,"failurePresentation")!=="none")throw new Ce("endpoint failurePresentation 必须为 none");if(mt(e,"auth")!==void 0&&mt(e,"auth")!=="none"&&mt(e,"auth")!=="optional"&&mt(e,"auth")!=="required")throw new Ce("endpoint auth 必须为 none、optional 或 required")}function Xi(e){if(Array.isArray(e))return e.map(Xi);if(!e||typeof e!="object")return e;const t=e,r={};for(const[n,i]of Object.entries(t))Ny.test(n)||(r[n]=Xi(i));return r}function Rc(e){if(!e)return;const t={};for(const[r,n]of Object.entries(e))El.test(r)||(t[r]=n);return t}function by(e){if(!e)return;const t=Object.keys(e).find(r=>El.test(r));if(t)throw new Ce(`endpoint 禁止声明 credential-bearing header: ${t}`)}class kn 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 kc=1440*60*1e3,Sy=/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun)\b/i;function Ty(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,kc):void 0}if(!Sy.test(n))return;const i=Date.parse(n);if(!Number.isFinite(i))return;const o=i-t();return o>0?Math.min(o,kc):void 0}function vy(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 wl(e,t){Object.defineProperty(e,"cause",{configurable:!1,enumerable:!1,value:t,writable:!1})}class vr extends Error{code="INTERNAL_ENDPOINT_REQUEST_FAILED";endpointId;constructor(t){super(`内部 endpoint 请求执行失败: ${t.endpointId}`),this.name="InternalEndpointRequestError",this.endpointId=t.endpointId,wl(this,t.cause),Object.setPrototypeOf(this,new.target.prototype)}}class Pn extends Error{code="INTERNAL_ENDPOINT_PARSE_FAILED";endpointId;constructor(t){super(`内部 endpoint 响应解析失败: ${t.endpointId}`),this.name="InternalEndpointParseError",this.endpointId=t.endpointId,wl(this,t.cause),Object.setPrototypeOf(this,new.target.prototype)}}function Oy(e,t,r,n,i,o,s,a){return{config:{auth:e.auth,body:Xi(i),bodyEncoding:e.bodyEncoding,channel:e.channel,credentials:s.credentials,headers:Rc(o),method:e.method,metadata:{endpointId:e.id},query:Xi(n),timeout:e.timeout,url:r},data:a.data,headers:Rc(a.headers)||{},status:a.status,statusText:a.statusText}}async function So(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(My(t),typeof t.id!="string"||!t.id)throw new Ce("endpoint id 必须为非空字符串");if(!["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"].includes(t.method))throw new Ce("endpoint method 不受 HostNetworkPort 支持");const i=typeof t.path=="function"?await t.path(r):t.path;if(typeof i!="string"||!i)throw new Ce("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;by(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(p){throw p instanceof Ce?p:new vr({endpointId:t.id,cause:p})}if(f.status<200||f.status>=300)throw new kn({endpointId:t.id,status:f.status,responseData:f.data,retryAfterMs:Ty(f.headers)});const l=Oy(t,r,i,o,s,a,n,f);if(t.parse)try{return await t.parse(l,r)}catch(p){throw new Pn({endpointId:t.id,cause:p})}return l.data},d=n.gate;if(!d)return c();const u=vy(t,o,s,n.credentials);return d.gate.execute({capability:d.capability,endpointId:t.id,...u===void 0?{}:{coalesceKey:u},load:c})}const Ry=new Set(["MINIPROGRAM_UNAVAILABLE","RUNTIME_CONTEXT_INVALID","CAPABILITY_NOT_GRANTED","AUTHORIZATION_CONTEXT_CHANGED","SERVER_API_REQUIRED","AUTHORIZATION_CANCELLED"]),ky=new Set(Sr),Sa="steam_account",Il=new Set(Sr.filter(e=>e!==Sa)),Py=1e3;function Ly(e){const t=new Set,r=yl({ttlMs:Math.max(0,Math.floor(e.identityTtlMs??ml))}),n=new Set;let i=0,o=!1,s=Promise.resolve(),a;const c=e.steamAccount===!0,d=e.userDataMode??Iy(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 g("METHOD_FORBIDDEN","新能力版本缺少 Runtime auth context Port");let M;try{M=await e.authorizationContext.get(e.operationContext)}catch(F){throw Ds(F)?Qo(F.code,F.message,F):Qo("REQUEST_FAILED","读取 Runtime auth context 失败",F)}if(M.steamAccount!==c||M.userDataMode!==d)throw g("AUTHORIZATION_CONTEXT_CHANGED","Runtime auth context 已变化,请重新打开小程序");const H=M.token.trim();if(!H)throw g("REQUEST_FAILED","Runtime auth context 为空");return{runtimeAuthContextToken:H}}const p=e.account.onChange(M=>{if(m(),E("heybox_app_login_change",M?{isHeyboxAppLoggedIn:!0}:{isHeyboxAppLoggedIn:!1,accountKey:null}),M&&e.account.getAccountKey){const H=i;j().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(M,H){M==="user_info_authorization_change"&&Hy(H)&&r.invalidate();for(const F of t)try{F(M,H)}catch{}}function w(){const M=e.identity.get()?.miniProgramId?.trim();if(!M)throw g("INVALID_STATE","当前能力缺少 canonical 小程序身份");return M}function I(){if(o||e.operationContext.signal.aborted)throw g("RUNTIME_DESTROYED","小程序 Runtime 已终止")}async function v(){I();let M;try{M=await e.account.getCurrentUserId(e.operationContext)}catch(H){throw xc(H,e.operationContext.signal,"读取小黑盒账号失败")}return typeof M=="string"&&M.trim()?M.trim():void 0}async function y(M,H){const F=await v();if(i!==H||F!==M)throw g("AUTHORIZATION_CONTEXT_CHANGED","授权期间账号上下文已变化,请重新操作")}async function O(M,H,F=w()){if(!e.account.getAccountKey)throw g("METHOD_FORBIDDEN","Host 不支持持久化账号比较");let $;try{$=await e.account.getAccountKey(F,M,e.operationContext)}catch{throw I(),g("REQUEST_FAILED","读取本地账号标识失败")}if(await y(M,H),w()!==F)throw g("AUTHORIZATION_CONTEXT_CHANGED","读取期间小程序上下文已变化");if(typeof $!="string"||!$.trim())throw g("INVALID_RESPONSE","Host 返回了无效的账号标识");return $}async function j(){const M=w(),H=i,F=await v();if(I(),i!==H)throw g("AUTHORIZATION_CONTEXT_CHANGED","读取期间账号上下文已变化");return F?{isHeyboxAppLoggedIn:!0,accountKey:await O(F,H,M)}:{isHeyboxAppLoggedIn:!1,accountKey:null}}async function b(M){I();try{await e.account.ensureAuthenticated({trustedUserGesture:M,reason:"runtime_auth",signal:e.operationContext.signal})}catch(F){throw xc(F,e.operationContext.signal,"小黑盒登录失败")}const H=await v();if(!H)throw g("HEYBOX_APP_LOGIN_REQUIRED","请先登录小黑盒");return H}async function T(M,H,F=e.operationContext.signal){try{if(F.aborted)throw _s();return await zy(So(e.network,M,H,{...e.operationContext,credentials:"heybox-session",signal:F,...f?{gate:f}:{}}),F)}catch($){throw e.operationContext.signal.aborted?g("RUNTIME_DESTROYED","小程序 Runtime 已终止"):$ instanceof Ce?g("REQUEST_UNSUPPORTED",$.message):$ instanceof Pn?g("INVALID_RESPONSE","授权接口响应不合法"):$ instanceof vr?g("REQUEST_FAILED","授权请求失败"):$ instanceof kn?u&&($.status===403||$.status===429)?g("RATE_LIMITED","授权请求已被网关限流,请稍后重试",{status:$.status,...$.retryAfterMs===void 0?{}:{retryAfterMs:$.retryAfterMs}}):g("REQUEST_FAILED",$.message):Ds($)?$:g("REQUEST_FAILED","授权请求失败")}}async function D(M,H){await T(my,{runtimeContext:{miniProgramId:M,...await l()},challenge:H}).catch(()=>{})}function x(M){const H=async()=>{const $=Lc(e.operationContext.signal);a=$;try{return await M($.signal)}finally{a===$&&(a=void 0),$.abort()}},F=s.then(H,H);return s=F.then(()=>{},()=>{}),F}async function P(M,H,F,$,K){if(!F)throw await D(M,H.challenge),g("USER_GESTURE_REQUIRED","展示授权确认需要用户手势");if(!e.authPresentation)throw await D(M,H.challenge),g("AUTHORIZATION_PRESENTATION_UNAVAILABLE","授权确认界面不可用");return x(async h=>{await y($,K);const N=await Q(M,H.displayedScopes,h);await y($,K);let U;try{U=await e.authPresentation.confirmAuthorization({miniProgramId:M,scopes:H.displayedScopes,...N,signal:h})}catch(ae){throw e.operationContext.signal.aborted?g("RUNTIME_DESTROYED","小程序 Runtime 已终止"):(await y($,K),await D(M,H.challenge),Qo("REQUEST_FAILED","授权确认界面执行失败",ae))}if(await y($,K),U.status!=="granted")throw await D(M,H.challenge),g("AUTHORIZATION_CANCELLED","用户取消授权");const q=Uy(U.grantedScopes,H.displayedScopes,c);if(!q.includes("identity"))throw await D(M,H.challenge),g("AUTHORIZATION_CANCELLED","用户拒绝授权");return q})}async function Q(M,H,F){const $=Lc(F),K=setTimeout(()=>$.abort(),Py);try{const h=jy(e.miniProgramPresentation),[N,U]=await Promise.all([h?Promise.resolve(h):R(M,$.signal),H.includes("profile")?L($.signal):Promise.resolve(void 0)]);return{...N?{miniProgram:N}:{},...U?{userProfile:U}:{}}}finally{clearTimeout(K),$.abort()}}async function R(M,H){try{const F=e.identity.get()?.version?.trim(),$=await T(ly,{mini_program_id:M,...F?{miniprogram_version:F}:{}},H),K=fr($,"小程序公开资料"),h=wr(K.name),N=wr(K.icon_url);return h||N?{...h?{name:h}:{},...N?{avatarUrl:N}:{}}:void 0}catch{return}}async function L(M){try{const H=await T(pl,void 0,M),F=fr(H,"账号基础信息"),$=wr(F.display_username),K=wr(F.display_avatar);return $||K?{...$?{nickname:$}:{},...K?{avatar:K}:{}}:void 0}catch{return}}async function C(M,H){if(Ay(d,"auth.login"),!c&&M.includes(Sa))throw g("INVALID_PARAMS","auth.login 参数不合法");const F=w(),$=await b(H),K=i,h=await T(yy,{runtimeContext:{miniProgramId:F,...await l()},scopes:M});await y($,K);const N=fr(h,"小程序登录"),U=Cc(N,"loginCode"),q=Cc(N,"consentChallenge");if(U===q)throw g("INVALID_RESPONSE","小程序登录 begin 必须返回 exact oneof");let ae;if(U)ae=Pc(N.loginCode,c);else{const ce=Cy(N.consentChallenge,c),le=await P(F,ce,H,$,K);await y($,K);const Ee=await T(Ey,{runtimeContext:{miniProgramId:F,...await l()},challenge:ce.challenge,selectedScopes:le});if(await y($,K),ae=Pc(fr(Ee,"小程序登录确认"),c),ae.scopes.some(me=>!le.includes(me)))throw g("INVALID_RESPONSE","小程序登录确认返回了未选择的 scope")}n.clear();for(const ce of ae.scopes)n.add(ce);r.invalidate();const de=e.account.getAccountKey?await O($,K,F):void 0;return E("heybox_app_login_change",{isHeyboxAppLoggedIn:!0,...de===void 0?{}:{accountKey:de}}),E("user_info_authorization_change",qo(n,c)),{...ae,...de===void 0?{}:{accountKey:de}}}async function z(M,H){const F=i,$=await T(py,{runtimeContext:{miniProgramId:H,...await l()}});await y(M,F);const K=xy(fr($,"用户本地身份"),c);for(const h of c?Sr:Il)n.add(h);return E("user_info_authorization_change",qo(n,c)),K}function k(M){I();const H=w(),F=`${M}\0${H}\0${i}\0${c}`;return r.read(F,()=>z(M,H))}async function S(M){if(!M)throw g("USER_GESTURE_REQUIRED","撤销授权需要用户手势");const H=w(),F=i,$=await v();if(!$)throw g("HEYBOX_APP_LOGIN_REQUIRED","请先登录小黑盒");const K=await T(gy,{runtimeContext:{miniProgramId:H,...await l()}});await y($,F),fr(K,"用户授权撤销"),m(),E("user_info_authorization_change",{identity:"denied",profile:"denied",...c?{steam_account:"denied"}:{}})}return{getAccountState:j,login:C,async confirmGameSaves(M){if(!M)throw g("USER_GESTURE_REQUIRED","读取游戏存档需要点击按钮授权");if(!e.authPresentation)throw g("AUTHORIZATION_PRESENTATION_UNAVAILABLE","授权确认界面不可用");const H=w(),F=await b(M),$=i;await x(async K=>{await y(F,$);const h=await Q(H,["identity"],K),N=await e.authPresentation.confirmAuthorization({miniProgramId:H,scopes:["identity","game_saves"],...h,signal:K});if(await y(F,$),N.status!=="granted"||!N.grantedScopes.includes("game_saves")||!N.grantedScopes.includes("identity"))throw g("AUTHORIZATION_CANCELLED","用户取消存档授权")})},getOrCreateLocalIdentity:k,invalidateLocalIdentity(){r.invalidate()},getAuthorization:()=>qo(n,c),revoke:S,onEvent(M){return t.add(M),()=>t.delete(M)},dispose(){o||(o=!0,m(),r.dispose(),p(),t.clear())}}}function Qo(e,t,r){const n=g(e,t);return Object.defineProperty(n,"cause",{configurable:!0,enumerable:!1,value:r}),n}function fr(e,t){if(!te(e))throw g("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":Ry.has(r)?r:"REQUEST_FAILED";throw g(n,r)}if(!te(e.result))throw g("INVALID_RESPONSE",`${t} result 必须是对象`);return e.result}function Pc(e,t){if(!te(e))throw g("INVALID_RESPONSE","login code 必须是对象");const r=Ji(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 g("INVALID_RESPONSE","login code 响应不合法");return{code:e.code,expiresIn:Number(e.expiresIn),scopes:r}}function Cy(e,t){if(!te(e))throw g("INVALID_RESPONSE","授权 challenge 必须是对象");const r=Ji(e.requestedScopes,"challenge requestedScopes",t),n=Ji(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 g("INVALID_RESPONSE","授权 challenge 响应不合法");return{challenge:e.challenge.trim(),requestedScopes:r,displayedScopes:n}}function xy(e,t){if(!te(e)||typeof e.appUserId!="string"||!e.appUserId.trim())throw g("INVALID_RESPONSE","本地身份 appUserId 必须是非空字符串");const r=e.appUserId.trim();if(!t)return{appUserId:r};if(e.steamId!==void 0&&typeof e.steamId!="string")throw g("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 Uy(e,t,r){const n=Ji(e,"授权选择 scopes",r);if(n.some(i=>!t.includes(i)))throw g("INVALID_RESPONSE","授权选择包含未展示的 scope");return n}function wr(e){return typeof e=="string"&&e.trim()?e.trim():void 0}function jy(e){const t=wr(e?.name),r=wr(e?.avatarUrl);return t||r?{...t?{name:t}:{},...r?{avatarUrl:r}:{}}:void 0}function Lc(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 zy(e,t){return t.aborted?Promise.reject(_s()):new Promise((r,n)=>{let i=!1;const o=a=>{i||(i=!0,t.removeEventListener("abort",s),a())},s=()=>o(()=>n(_s()));t.addEventListener("abort",s,{once:!0}),e.then(a=>o(()=>r(a)),a=>o(()=>n(a)))})}function _s(){const e=new Error("The operation was aborted");return e.name="AbortError",e}function Ji(e,t,r){const n=r?ky:Il;if(!Array.isArray(e)||e.some(i=>typeof i!="string"||!n.has(i))||new Set(e).size!==e.length)throw g("INVALID_RESPONSE",`${t} 不合法`);return[...e]}function qo(e,t){const r=t?Sr:Sr.filter(n=>n!==Sa);return Object.fromEntries(r.map(n=>[n,e.has(n)?"granted":"not_requested"]))}function Cc(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function Hy(e){return te(e)?Object.values(e).some(t=>t==="denied"):!1}function Ds(e){return te(e)&&typeof e.code=="string"&&typeof e.message=="string"}function xc(e,t,r){return t.aborted?g("RUNTIME_DESTROYED","小程序 Runtime 已终止"):Ds(e)?e:g("REQUEST_FAILED",r)}const Fy=new Set(Sr);function By(e){return{[yi]:async t=>{if(t!==void 0)throw g("INVALID_PARAMS","auth.getAccountState 不接受参数");return e.authorization.getAccountState()},[Ei]:async(t,r)=>e.authorization.login(Vy(t),r.trustedUserGesture)}}function Vy(e){if(e===void 0)return["identity"];if(!te(e)||Object.keys(e).some(t=>t!=="scopes"))throw Uc();if(e.scopes===void 0)return["identity"];if(!Array.isArray(e.scopes)||e.scopes.some(t=>typeof t!="string"||!Fy.has(t))||new Set(e.scopes).size!==e.scopes.length)throw Uc();return[...e.scopes]}function Uc(){return g("INVALID_PARAMS","auth.login 参数不合法")}const Gy={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,"排行榜记录删除接口响应异常")}},$y={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,"当前排行榜记录接口响应异常")}},Qy={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,"排行榜信息接口响应异常")}},qy={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,"排行榜列表接口响应异常")}},Yy={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,"排行榜提交接口响应异常")}},Wy={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 To(e,t,r){e.assertUsable();const n={request:async(i,o)=>(e.assertUsable(),e.network.request(i,o))};try{return await fe(()=>So(n,t,r,{...e.operationContext,credentials:"heybox-session",...e.gate?{gate:e.gate}:{}}),e.operationContext.signal)}catch(i){if(ro(i)||en(i,"REQUEST_UNSUPPORTED")||en(i,"RATE_LIMITED")||en(i,"RATE_LIMITED_BY_RUNTIME"))throw i;if(i instanceof Ce)throw J("REQUEST_UNSUPPORTED",`当前 Host 不支持该${e.subject}请求`);if(i instanceof vr&&en(i.cause,"INVALID_STATE"))throw i.cause;if(i instanceof kn){if(e.requestPolicyEnabled!==!1&&(i.status===403||i.status===429))throw J("RATE_LIMITED",`${e.subject}请求已被网关限流,请稍后重试`,{status:i.status,...i.retryAfterMs===void 0?{}:{retryAfterMs:i.retryAfterMs}});if(i.status===401||i.status===403)throw J("UNAUTHORIZED","当前用户未登录");const o=Zy(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"||eo(o.result)||eo(o)||s&&/^[A-Z][A-Z0-9_]+$/.test(s))throw Al(o,e.subject)}throw J("HTTP_ERROR",`${e.subject}请求失败(HTTP ${i.status})`,{status:i.status})}throw i instanceof vr?to(e.subject):i instanceof Pn?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 Al(e,r);if(!Object.prototype.hasOwnProperty.call(e,"result")||e.result===void 0||e.result===null)throw Ne(`${t} 响应缺少 result`);return e.result}function vo(e,t){try{return e.onChange(t)}catch(r){if(en(r,Fu))return()=>{};throw r}}function Al(e,t){if(e.status==="login"||e.status==="relogin")throw J("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 J(i,Mt(e.result.message)||Mt(e.msg)||`${t}请求失败`)}const r=eo(e.result)??eo(e),n=Mt(r?.user_message)||Mt(e.msg)||Mt(r?.developer_message)||`${t}请求失败`;throw r?J(Ky(r),n,{status:e.status,sbe:r}):J("HEYBOX_API_ERROR",n,{status:e.status})}function Zy(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return}}function eo(e){return Ie(e)&&Ie(e.sbe)?e.sbe:void 0}function Ky(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 Wy[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 en(e,t){return Ie(e)&&e.code===t}function J(e,t,r){return r===void 0?{code:e,message:t}:{code:e,message:t,data:r}}function Ne(e){return J("INVALID_RESPONSE",e)}function to(e){return J("REQUEST_FAILED",`${e}请求失败`)}function ro(e){return e instanceof Error&&e.name==="AbortError"}const Xy="default",Bt="排行榜",Jy=/^[A-Za-z0-9_-]{1,64}$/,eE=300*1e3,tE=250,rE=3;class nE{constructor(t){this.options=t,this.requestGateContext=t.requestGate?{capability:"cloud",gate:t.requestGate}:void 0,this.unsubscribeAccountChange=vo(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(Yy,{miniProgramId:n,...t});this.assertAccountGeneration(r);const o=st(i,St,Bt);return this.invalidateMutableReads(this.createBucketKey(n,t.key)),Yo(o,St)}getList(t){this.assertUsable();const r=this.readMiniProgramId(),n=this.createBucketKey(r,t.key),i=qr("list",t.limit,t.cursor??null);return this.read(n,"list",i,async()=>{const o=await this.request(qy,{miniProgramId:r,...t}),s=st(o,at,Bt);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=>Yo(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=qr("current",i);return this.read(o,"current",s,async()=>{const a=await this.request($y,{miniProgramId:n,...t}),c=st(a,Ct,Bt);if(!Ie(c))throw Ne(`${Ct} 返回值必须是对象`);return c.entry===void 0||c.entry===null?void 0:Yo(c.entry,Ct)})}async deleteCurrentUserEntry(t){this.assertUsable();const r=this.accountGeneration,n=this.readMiniProgramId();await this.requireCurrentUser(r);const i=await this.request(Gy,{miniProgramId:n,...t});this.assertAccountGeneration(r);const o=st(i,nr,Bt);if(this.invalidateMutableReads(this.createBucketKey(n,t.key)),!Ie(o)||typeof o.deleted!="boolean")throw Ne(`${nr} 返回的 deleted 必须是布尔值`);return{deleted:o.deleted}}getInfo(t){this.assertUsable();const r=this.readMiniProgramId(),n=this.createBucketKey(r,t.key);return this.read(n,"info",qr("info"),async()=>{const i=await this.request(Qy,{miniProgramId:r,...t}),o=st(i,Et,Bt);if(!Ie(o)||typeof o.key!="string"||!Jy.test(o.key))throw Ne(`${Et} 返回的 key 不合法`);if(t.key!==void 0&&o.key!==t.key)throw Ne(`${Et} 返回的 key 与请求不一致`);if(o.order!=="asc"&&o.order!=="desc")throw Ne(`${Et} 返回的 order 必须是 asc 或 desc`);if(typeof o.rank_limit!="number"||!Number.isInteger(o.rank_limit)||o.rank_limit<0)throw Ne(`${Et} 返回的 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=qr(t,n),d=this.inflight.get(c);if(d)return d.promise;const u=this.accountGeneration,f=o?.generation,l=i().then(p=>(this.assertAccountGeneration(u),o&&s&&o.generation===f&&(r==="list"?s.size>=tE&&s.delete(s.keys().next().value):s.clear(),s.set(n,{expiresAt:Date.now()+eE,value:p})),p)).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>=rE)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)jc(n,t),this.isBucketEmpty(r,n)&&this.buckets.delete(r)}removeEmptyBucket(t,r){jc(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 ro(n)?n:to(Bt)}if(this.assertAccountGeneration(t),typeof r!="string"||!r.trim())throw J("UNAUTHORIZED","当前用户未登录");return r.trim()}readMiniProgramId(){const t=this.options.identity.get()?.miniProgramId.trim();if(!t)throw J("INVALID_STATE","canonical mini-program identity 尚未绑定");return t}createBucketKey(t,r){return qr(t,r??Xy)}assertAccountGeneration(t){if(this.assertUsable(),t!==this.accountGeneration)throw J("UNAUTHORIZED","登录状态已变化,请重试")}request(t,r){return To({network:this.options.network,operationContext:this.options.operationContext,...this.requestGateContext?{gate:this.requestGateContext}:{},...this.options.requestPolicyEnabled===void 0?{}:{requestPolicyEnabled:this.options.requestPolicyEnabled},subject:Bt,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 J("INVALID_STATE","Cloud capability 已释放")}}function iE(e){return new nE(e)}function Yo(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 jc(e,t){for(const r of Object.values(e.caches))for(const[n,i]of r)i.expiresAt<=t&&r.delete(n)}function qr(...e){return JSON.stringify(e)}const oE={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,"云端存储删除接口响应异常")}},zc={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,"云端存储读取接口响应异常")}},Hc={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 列表接口响应异常")}},sE={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,"云端存储写入接口响应异常")}},Vt="云端存储",aE=3e4,cE=128,dE=500;class uE{constructor(t){this.options=t,this.requestGateContext=t.requestGate?{capability:"cloud.storage",gate:t.requestGate}:void 0,this.unsubscribeAccountChange=vo(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(Hc,{}),ir,Vt);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"?dE: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(oE,{key:t}),br,Vt);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(sE,{key:t,value:r.value,expectedVersion:i.version,expectedRevision:i.revision}),Mr,Vt);if(this.assertAccountGeneration(r.generation),!Ie(o)||o.success!==!0)throw Ne("云存储写入结果不合法");const s=Fc({...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(zc,{key:t}).then(c=>{this.assertAccountGeneration(r);const d=Fc(st(c,Nr,Vt));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>=cE&&this.cache.delete(this.cache.keys().next().value),this.cache.set(t,{expiresAt:Date.now()+aE,value:r})}invalidateRead(t){this.keyGenerations.set(t,(this.keyGenerations.get(t)??0)+1),this.inflight.delete(t),this.options.requestGate?.invalidateCoalescing([zc.id,Hc.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(J("INVALID_STATE","Cloud capability 已释放")))}invalidateForAccountChange(){this.purge(J("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 ro(o)?o:to(Vt)}if(this.assertAccountGeneration(t),this.hasAccountObservation&&(n?.trim()||void 0)!==this.observedUserId)throw this.invalidateForAccountChange(),J("UNAUTHORIZED","登录状态已变化,请重试");const i=JSON.stringify([r,n]);if(this.boundScope!==void 0&&this.boundScope!==i)throw this.invalidateForAccountChange(),J("UNAUTHORIZED","登录状态已变化,请重试");if(typeof n!="string"||!n.trim())throw J("UNAUTHORIZED","当前用户未登录");return this.boundScope=i,this.boundUserId=n.trim(),n}readMiniProgramId(){const t=this.options.identity.get()?.miniProgramId.trim();if(!t)throw J("INVALID_STATE","canonical mini-program identity 尚未绑定");return t}assertAccountGeneration(t){if(this.assertUsable(),t!==this.accountGeneration)throw J("UNAUTHORIZED","登录状态已变化,请重试")}async request(t,r){const n=this.accountGeneration;if(this.assertUsable(),!this.options.authorizationContext)throw J("METHOD_FORBIDDEN","云端存储缺少受信运行上下文");let i;try{i=await fe(()=>this.options.authorizationContext.get(this.options.operationContext),this.options.operationContext.signal)}catch(s){throw ro(s)?s:to(Vt)}this.assertAccountGeneration(n);const o=i.token.trim();if(!o||i.expiresAt<=Date.now())throw J("UNAUTHORIZED","小程序运行上下文无效,请重新打开");return To({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.assertAccountGeneration(n)},t,{...r,runtimeAuthContextToken:o})}assertUsable(){if(pe(this.options.operationContext.signal),this.disposed)throw J("INVALID_STATE","Cloud capability 已释放")}}function lE(e){return new uE(e)}function Fc(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 fE=/^[A-Za-z0-9_-]{1,64}$/,Bc=20,hE=100,Vc=2048,mE=/^[A-Za-z0-9_-]{1,128}$/,Gc=16*1024;function gE(e){const t=iE(e),r=lE(e);return{handlers:{[St]:async i=>t.submit(pE(i)),[at]:async i=>t.getList(yE(i)),[Ct]:async i=>t.getCurrentUserEntry(Wo(i,Ct)),[nr]:async i=>t.deleteCurrentUserEntry(Wo(i,nr)),[Et]:async i=>t.getInfo(Wo(i,Et)),[Nr]:async i=>r.getItem($c(i,Nr)),[Mr]:async i=>{const{key:o,value:s}=EE(i);return r.setItem(o,s)},[br]:async i=>r.removeItem($c(i,br)),[ir]:async i=>(IE(i),r.getKeys())},dispose:()=>{t.dispose(),r.dispose()}}}function pE(e){const t=Hr(e,St,!1);if(Fr(t,["key","score","extra"],St),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{...Ta(t.key,St),score:t.score,...t.extra===void 0?{}:{extra:AE(t.extra)}}}function yE(e){if(e===void 0)return{limit:Bc};const t=Hr(e,at,!0);Fr(t,["key","limit","cursor"],at);const r=t.limit===void 0?Bc:t.limit;if(typeof r!="number"||!Number.isInteger(r)||r<=0||r>hE)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{...Ta(t.key,at),limit:r,...t.cursor===void 0?{}:{cursor:t.cursor}}}function Wo(e,t){if(e===void 0)return{};const r=Hr(e,t,!0);return Fr(r,["key"],t),Ta(r.key,t)}function $c(e,t){const r=Hr(e,t,!1);return Fr(r,["key"],t),_l(r.key,t)}function EE(e){const t=Mr,r=Hr(e,t,!1);Fr(r,["key","value"],t);const n=_l(r.key,t);if(typeof r.value!="string")throw Ye("INVALID_PARAMS",`${t} value 必须是字符串`);if(wE(r.value))throw Ye("INVALID_PARAMS",`${t} value 不能包含不成对的代理字符`);if(new TextEncoder().encode(r.value).length>Gc)throw Ye("INVALID_PARAMS",`${t} value 不能超过 ${Gc} 字节`);return{key:n,value:r.value}}function wE(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 IE(e){const t=Hr(e,ir,!0);Fr(t,[],ir)}function _l(e,t){if(typeof e!="string"||!mE.test(e))throw Ye("INVALID_PARAMS",`${t} key 仅支持 1–128 位英文字母、数字、下划线和连字符`);return e}function Hr(e,t,r){if(e===void 0&&r)return{};if(!Dl(e))throw Ye("INVALID_PARAMS",`${t} 参数必须是对象`);return e}function Fr(e,t,r){const n=Object.keys(e).find(i=>!t.includes(i));if(n)throw Ye("INVALID_PARAMS",`${r} 不支持参数 ${n}`)}function Ta(e,t){if(e===void 0)return{};if(typeof e!="string"||!fE.test(e))throw Ye("INVALID_PARAMS",`${t} key 仅支持 1-64 位字母、数字、下划线和连字符`);return{key:e}}function AE(e){if(!Dl(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>Vc)throw Ye("INVALID_PARAMS",`cloud.leaderboard.submit extra 不能超过 ${Vc} 字节`);return e}function Dl(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ye(e,t){return{code:e,message:t}}const _E={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,"游戏存档接口响应异常")}},DE=new Map([["2358720","blackMythWukong"],["3678970","taskbarHero"],["4115450","phantomBladeZero"],["1245620","eldenRing"],["413150","stardewValley"],["2246340","monsterHunterWilds"],["3167020","duckov"],["3489700","stellarBlade"],["2001120","splitFiction"]]);function Ns(e,t=0){return t>64?!1:e===null||typeof e=="string"||typeof e=="boolean"?!0:typeof e=="number"?Number.isFinite(e)&&(!Number.isInteger(e)||Number.isSafeInteger(e)):Array.isArray(e)?e.every(r=>Ns(r,t+1)):Ie(e)&&Object.values(e).every(r=>Ns(r,t+1))}function NE(e,t){const r=DE.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 J(String(e.error_code),"账号或授权已变化");if(e.status==="ready"&&Ie(e.data)&&Ns(e.data))return{status:"ready",data:e.data}}return{status:"failed",error:{code:"STRUCTURED_DATA_UNAVAILABLE",message:"结构化数据暂时无法读取,请稍后重试"}}}function Nl(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 p;const m=new Promise(w=>{p=w}),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{p(),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 p=JSON.parse(l);if(!p||typeof p!="object")return;const m=p;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),p=l?.taskId===d&&l.accountId===c.accountId;let m;try{m=await o(c,u,!0)}catch{pe(u.signal),p&&t.set(f,void 0);return}m?.taskId===d&&m.accountId===c.accountId?(await s(c,void 0,u),l&&!p&&t.set(f,l)):p&&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 ME=2e3,bE=5*6e4;function SE(e){const t=Nl(e.storage);let r=0,n=!1,i;const o=e.fileDownloads??(e.files&&e.transfer?Ma({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=D=>o?.release(D)??Promise.resolve(),u=new Set;let f=new AbortController,l;const p=()=>{f.abort(),f=new AbortController,l=void 0},m=(D=!0)=>{D&&t.clear(c),r++,p();for(const x of u)x.abort();for(const x of s)d(x).catch(()=>{});s.clear(),a.clear()},E=vo(e.account,D=>{i&&D!==i&&(m(),i=void 0)}),w=e.authorization.onEvent(()=>m());function I(D,x,P,Q){if(v(P),Q.signal.aborted||!D.account_id||!e.presentation?.showSteamLoginRequired)return;const R=`${D.account_id}:${D.game_id}:${D.task_id??"sync"}`;if(l!==R){l=R;try{e.presentation.showSteamLoginRequired({userId:x,accountId:D.account_id},Se(e.operationContext,f.signal))}catch{}}}function v(D){if(n||e.operationContext.signal.aborted)throw J("RUNTIME_DESTROYED","小程序已关闭");if(D!==r)throw J("AUTHORIZATION_CONTEXT_CHANGED","账号或授权已变化")}async function y(D,x,P){if(v(x),await e.account.getCurrentUserId(P)!==D)throw m(),J("AUTHORIZATION_CONTEXT_CHANGED","账号已变化");v(x)}async function O(D,x,P,Q){if(await y(x,P,Q),!e.authorizationContext)throw J("METHOD_FORBIDDEN","宿主不支持存档授权上下文");const R=await e.authorizationContext.get(Q);if(!R.token||R.expiresAt<=Date.now())throw J("UNAUTHORIZED","小程序运行上下文已过期");const L=await To({network:e.network,operationContext:Q,subject:"游戏存档",assertUsable:()=>v(P),...e.requestGate?{gate:{capability:"gameSaves",gate:e.requestGate}}:{},requestPolicyEnabled:e.requestPolicyEnabled},_E,{...D,runtime_auth_context_token:R.token});if(await y(x,P,Q),L.status==="failed"&&Ie(L.result)&&L.result.error_code==="RECENT_SAVE_AVAILABLE")throw J("RECENT_SAVE_AVAILABLE",typeof L.msg=="string"&&L.msg?L.msg:"已有近期存档,请直接查询使用");const C=st(L,D.action,"游戏存档");if(!Ie(C))throw J("INVALID_RESPONSE","存档响应不合法");return C}async function j(D,x,P){const Q=TE(D,x),R=r;if(v(R),D==="file"&&(!e.transfer||!e.files))throw J("METHOD_FORBIDDEN","宿主不支持存档文件读取");const L=new AbortController;u.add(L);let C=!1;const z=D==="sync"?setTimeout(()=>{C=!0,L.abort()},bE):void 0,k=Se(Se(e.operationContext,P.signal),L.signal);try{const S=await e.account.getCurrentUserId(k);if(!S)throw J("UNAUTHORIZED","请先登录小黑盒");if(i&&i!==S)throw m(),J("AUTHORIZATION_CONTEXT_CHANGED","账号已变化");if(i=S,D==="sync"||D==="parsed"){if(D==="sync"&&p(),!Q.account_id){const K=await O({action:"check",game_id:Q.game_id},S,R,k);Q.account_id=Nn(K.account_id)}if(D==="sync")return await b(Q,S,R,k)}const M=await O({action:D,...Q},S,R,k);if(D==="list")return vE(M);if(D==="parsed")return NE(M.parsed_data,Q.game_id);if(Ml(M.file).fileId!==Q.file_id)throw J("INVALID_RESPONSE","文件标识不匹配");if(!o)throw J("REQUEST_UNSUPPORTED","宿主不支持存档下载");const F=await o.download(M,async K=>{try{v(R),await O({action:"check",game_id:Q.game_id,account_id:Q.account_id},S,R,K)}catch(h){const N=Ie(h)?String(h.code):"";throw["RUNTIME_DESTROYED","AUTHORIZATION_CONTEXT_CHANGED","STEAM_ACCOUNT_CHANGED","GAME_SAVES_AUTHORIZATION_REQUIRED","UNAUTHORIZED"].includes(N)?(m(),J("FILE_ACCESS_REVOKED","游戏存档授权已失效")):h}},k);let $=!1;try{if(await y(S,R,k),v(R),k.signal.aborted)throw J("DOWNLOAD_CANCELLED","存档下载已取消");const K=e.fileRegistry.registerFile(F,"game-save","read");return s.add(F),a.set(Ia(),{file:F,sizeBytes:o.sizeOf(F)}),$=!0,K}finally{$||await o.release(F)}}catch(S){throw C?J("REQUEST_TIMEOUT","等待同步超时,任务可能仍在执行,请稍后查询存档列表"):S}finally{z!==void 0&&clearTimeout(z),u.delete(L)}}async function b(D,x,P,Q){const R=e.identity.get()?.miniProgramId;if(!R)throw J("INVALID_STATE","小程序身份尚未确认");const L={miniProgramId:R,userId:x,gameId:D.game_id,accountId:D.account_id},C=k=>O({action:"status",...D,task_id:k},x,P,Q);let z;try{const k=await t.run(L,Q,async()=>{await y(x,P,Q);const M=await t.get(L,Q);if(M){z=M;try{return{taskId:M,status:await C(M)}}catch(F){if(!Ie(F)||!["SYNC_TASK_NOT_FOUND","SYNC_TASK_CHANGED"].includes(String(F.code)))throw F;await t.set(L,void 0,Q),z=void 0}}const H=await O({action:"sync",...D},x,P,Q);return z=Nn(H.task_id),await t.set(L,z,Q),await y(x,P,Q),{taskId:z,status:void 0}});z=k.taskId;let S=k.status;for(;;){if(v(P),Q.signal.aborted)throw J("REQUEST_CANCELLED","已停止等待存档同步");if(S??=await C(z),S.state==="succeeded"||S.state==="failed"){if(await t.remove(L,z,Q),await y(x,P,Q),S.state==="succeeded")return{state:"succeeded"};throw J(S.error_code?no(S.error_code):"SYNC_FAILED",S.message?no(S.message):"存档同步失败")}if(S.state!=="syncing"&&S.state!=="uploading")throw J("INVALID_RESPONSE","同步状态不合法");S=void 0,await OE(ME,Q.signal)}}catch(k){if(Ie(k)){const S=String(k.code);S==="STEAM_LOGIN_REQUIRED"&&I({...D,task_id:z},x,P,Q),z&&["SYNC_TASK_NOT_FOUND","SYNC_TASK_CHANGED","STEAM_ACCOUNT_CHANGED","STEAM_ACCOUNT_REQUIRED","GAME_SAVES_AUTHORIZATION_REQUIRED","AUTHORIZATION_CONTEXT_CHANGED","UNAUTHORIZED"].includes(S)&&await t.remove(L,z,c)}throw k}}return{handlers:{"gameSaves.list":(D,x)=>j("list",D,x),"gameSaves.sync":(D,x)=>j("sync",D,x),"gameSaves.readParsedData":(D,x)=>j("parsed",D,x),"gameSaves.getFile":(D,x)=>j("file",D,x)},diagnostics:{async getSnapshot(){const D=r;return i&&await y(i,D,e.operationContext),v(D),Array.from(a,([x,P])=>({id:x,name:P.file.name,sizeBytes:P.sizeBytes}))},async readFile(D,x){const P=r;v(P);const Q=a.get(D);if(!Q)throw J("FILE_ACCESS_REVOKED","存档文件已失效,请重新下载");const R=Se(e.operationContext,x);R.signal.throwIfAborted();const L=await Q.file.read(R);try{return R.signal.throwIfAborted(),v(P),{name:Q.file.name,bytes:L}}catch(C){throw L.fill(0),C}}},allowsRead(D,x){return["file.readBytes","file.readText","file.stat","file.exists"].includes(D)&&Ie(x)&&e.fileRegistry.isGameSaveRef(x.target)},dispose(){n||(n=!0,m(!1),E(),w())}}}function TE(e,t){const r=e==="file"?["gameId","accountId","saveId","fileId"]:["gameId","accountId"];if(!Ie(t)||Object.keys(t).some(i=>!r.includes(i)))throw J("INVALID_PARAMS","存档参数不合法");const n=tn(t.gameId);if(Number(n)>2147483647)throw J("INVALID_PARAMS","Steam AppID 超出范围");return{game_id:n,...e==="file"||t.accountId!==void 0?{account_id:tn(t.accountId)}:{},...e==="file"?{save_id:tn(t.saveId),file_id:tn(t.fileId)}:{}}}function tn(e){if(typeof e!="string"||!/^[1-9][0-9]{0,19}$/.test(e))throw J("INVALID_PARAMS","存档标识必须为十进制字符串");return e}function Nn(e){try{return tn(e)}catch{throw J("INVALID_RESPONSE","服务端存档标识无效")}}function no(e){if(typeof e!="string")throw J("INVALID_RESPONSE","服务端存档字段无效");return e}function Ms(e){if(typeof e!="number"||!Number.isSafeInteger(e)||e<0)throw J("INVALID_RESPONSE","服务端存档数值无效");return e}function Ml(e){if(!Ie(e))throw J("INVALID_RESPONSE","存档文件信息无效");return{fileId:Nn(e.file_id),name:no(e.name),originalPath:no(e.original_path),sizeBytes:Ms(e.size_bytes),modifiedAt:Ms(e.modified_at)}}function vE(e){if(!Array.isArray(e.saves)||e.saves.length>500)throw J("INVALID_RESPONSE","存档列表无效");return{accountId:Nn(e.account_id),saves:e.saves.map(t=>{if(!Ie(t)||!Array.isArray(t.files)||t.files.length>200)throw J("INVALID_RESPONSE","存档文件列表无效");return{saveId:Nn(t.save_id),createdAt:Ms(t.created_at),files:t.files.map(Ml)}})}}function OE(e,t){return new Promise((r,n)=>{const i=()=>{clearTimeout(o),t.removeEventListener("abort",i),n(J("REQUEST_CANCELLED","已停止等待存档同步"))},o=setTimeout(()=>{t.removeEventListener("abort",i),r()},Math.max(0,e));t.addEventListener("abort",i,{once:!0}),t.aborted&&i()})}const RE=new Set(["stdio","attachments","notifications"]),bl=new Set(["windows-x64","macos-arm64"]),kE=new Set(["unsigned","valid","invalid","unknown"]),PE=/^[a-f0-9]{64}$/,LE=new Set(["exited","terminated","crashed","host-shutdown","permission-revoked","output-limit"]),CE=new Set(vu),xE=new Set([...vu,"PERMISSION_DENIED","USER_GESTURE_REQUIRED"]),Sl=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 UE(e){const t=async(n,i,o,s)=>{const a=jE(n);try{yt(i.signal);const c=await o(a,{...e.operationContext,signal:i.signal});return yt(i.signal),c}catch(c){throw Ss(c,s)}},r=async(n,i,o)=>{if(!o.trustedUserGesture)throw g("USER_GESTURE_REQUIRED","当前操作需要新的可信用户手势");if(!e.companionPresentation)throw g("COMPANION_UNSUPPORTED","Host 未提供 Companion 可信授权界面");const s={...e.operationContext,signal:o.signal},a=await e.companion.getInfo(i,s).then(d=>zE(d,i)).catch(d=>{throw Ss(d)});yt(o.signal);const c=await e.companionPresentation.confirmCompanionOperation({action:n,companion:a,miniProgram:e.miniProgramPresentation,signal:o.signal});if(yt(o.signal),c.status!=="granted")throw g("COMPANION_USER_CANCELLED","用户取消了 Companion 操作")};return{[ho]:(n,i)=>t(n,i,async(o,s)=>bs(await e.companion.getInfo(o,s),o)),[mo]:(n,i)=>t(n,i,async(o,s)=>Qc(await e.companion.getPreparationStatus(o,s))),[go]:(n,i)=>t(n,i,async(o,s)=>{const a=Qc(await e.companion.getPreparationStatus(o,s));return yt(i.signal),a.state!=="ready"&&a.state!=="preparing"&&await r("prepare",o,i),yt(i.signal),bs(await e.companion.prepare(o,{...s,onProgress:c=>i.postProgress(vl(c))}),o)},"COMPANION_PREPARATION_CANCELLED"),[po]:(n,i)=>t(n,i,(o,s)=>e.companion.cancelPreparation(o,s)),[yo]:(n,i)=>t(n,i,async(o,s)=>qc(await e.companion.getActiveSession(o,s),o)),[Eo]:(n,i)=>t(n,i,async(o,s)=>{const a=qc(await e.companion.getActiveSession(o,s),o);return yt(i.signal),a||(await r("launch",o,i),yt(i.signal),Ol(await e.companion.launch(o,s),o))}),[wo]:(n,i)=>hr(n,i,e,"write"),[Io]:(n,i)=>hr(n,i,e,"closeStdin"),[Ao]:(n,i)=>hr(n,i,e,"terminate"),[_o]:(n,i)=>hr(n,i,e,"ackOutput"),[Do]:async(n,i)=>{const o=await hr(n,i,e,"openAttachment");return e.fileRegistry.registerFile(o,"companion-attachment","read")},[No]:(n,i)=>hr(n,i,e,"showNotification")}}function jE(e){if(!te(e)||typeof e.alias!="string"||!Zh.test(e.alias))throw g("INVALID_PARAMS","Companion alias 不合法");return e.alias}function yt(e){if(e.aborted)throw Object.assign(new Error("Companion 操作已取消"),{name:"AbortError"})}async function hr(e,t,r,n){if(!te(e)||typeof e.sessionId!="string"||!e.sessionId||!Number.isSafeInteger(e.controllerGeneration)||Number(e.controllerGeneration)<0)throw g("INVALID_PARAMS","Companion Session controller 不合法");try{yt(t.signal);const i=await r.companion[n](HE(e,n),{...r.operationContext,signal:t.signal});return yt(t.signal),i}catch(i){throw Ss(i)}}function dt(){throw g("COMPANION_HOST_FAILED","Companion Host 返回了无效数据")}function Tl(e){return!Array.isArray(e)||e.some(t=>!RE.has(t))?dt():Object.freeze([...new Set(e)])}function bs(e,t){return!te(e)||typeof e.alias!="string"||typeof e.displayName!="string"||t!==void 0&&e.alias!==t||!bl.has(String(e.target))||!Number.isSafeInteger(e.archiveBytes)||Number(e.archiveBytes)<0||!kE.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:Tl(e.capabilities),archiveBytes:e.archiveBytes,signatureStatus:e.signatureStatus,...e.source===void 0?{}:{source:e.source}})}function zE(e,t){const r=bs(e,t);return!te(e)||e.sha256===void 0?r:typeof e.sha256!="string"||!PE.test(e.sha256)?dt():Object.freeze({...r,sha256:e.sha256})}function vl(e){return te(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 Qc(e){return te(e)?e.state==="not-prepared"?Object.freeze({state:"not-prepared"}):e.state==="preparing"?Object.freeze({state:"preparing",progress:vl(e.progress)}):e.state==="ready"&&Number.isSafeInteger(e.preparedAt)&&Number(e.preparedAt)>=0?Object.freeze({state:"ready",preparedAt:e.preparedAt}):e.state==="failed"&&te(e.error)&&typeof e.error.code=="string"&&CE.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:Sl[e.error.code]??"Companion 操作失败",retryable:e.error.retryable})}):dt():dt()}function Ol(e,t){return!te(e)||typeof e.id!="string"||!e.id||typeof e.alias!="string"||t!==void 0&&e.alias!==t||!bl.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:Tl(e.capabilities),state:"running",controllerGeneration:e.controllerGeneration})}function qc(e,t){return e===void 0?void 0:Ol(e,t)}function HE(e,t){const r=e,n={sessionId:r.sessionId,controllerGeneration:r.controllerGeneration};if(t==="write"){if(!_u(r.data))throw g("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 g("INVALID_PARAMS","Companion output ack 不合法");return{...n,stream:r.stream,sequence:r.sequence}}if(t==="openAttachment"){if(typeof r.id!="string"||!r.id)throw g("INVALID_PARAMS","Companion Attachment ID 不合法");return{...n,id:r.id}}if(t==="showNotification"){if(!["completed","failed","stopped","attention"].includes(String(r.category)))throw g("INVALID_PARAMS","Companion notification category 不合法");return{...n,category:r.category}}return n}function FE(e){return!te(e)||!LE.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 BE(e){if(!te(e)||!te(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||!_u(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:FE(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 Ss(e,t){return te(e)&&typeof e.code=="string"&&xE.has(e.code)?g(e.code,Sl[e.code]??"Companion 操作失败",e.code==="COMPANION_DESCRIPTOR_UNAVAILABLE"?{retryable:!0}:typeof e.retryable=="boolean"?{retryable:e.retryable}:void 0):t&&te(e)&&e.name==="AbortError"?g(t,"Companion 准备已取消"):g("COMPANION_HOST_FAILED","Companion Host 操作失败")}const Yc=5e3,Wc=1e4;function $e(e){throw{code:"INVALID_PARAMS",message:e}}function va(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Rl(e,t,r){const n=Object.keys(e).filter(i=>!t.includes(i));n.length&&$e(`${r} 不支持字段: ${n.join(", ")}`)}function VE(e){if(e===void 0)return{intensity:"light",delay:0};if(!va(e))return $e("device.vibrate 参数必须是对象");Rl(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>Yc?$e(`device.vibrate delay 必须是 0-${Yc} 的整数毫秒`):{intensity:r,delay:n}}function GE(e){return va(e)?(Rl(e,["text"],"device.setClipboard"),typeof e.text!="string"||!e.text.trim()?$e("device.setClipboard text 必须是非空字符串"):e.text.length>Wc?$e(`device.setClipboard text 不能超过 ${Wc} 字符`):{text:e.text}):$e("device.setClipboard 参数必须是对象")}function $E(e){return typeof e=="string"?e.trim()?e:$e("device.executeProtocol 协议字符串不能为空"):va(e)?typeof e.protocol_type!="string"||!e.protocol_type.trim()?$e("device.executeProtocol 协议对象必须包含非空字符串 protocol_type"):(Ts(e,new Set),e):$e("device.executeProtocol 参数必须是协议字符串或协议对象")}function Ts(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)Ts(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))Ts(i,t);t.delete(r)}function QE(e){return{[$i]:async(t,r)=>{const n=Se(e.operationContext,r.signal,r.requestId);pe(n.signal),await fe(()=>e.presentation.vibrate(VE(t),n),n.signal)},[Qi]:async(t,r)=>{const n=Se(e.operationContext,r.signal,r.requestId);pe(n.signal),await fe(()=>e.presentation.setClipboard(GE(t),n),n.signal)},[qi]:async(t,r)=>{const n=Se(e.operationContext,r.signal,r.requestId);pe(n.signal);const i=$E(t);await fe(()=>e.protocol.invoke(i,n),n.signal)}}}const Zc=1e3,qE=new Set(["FILE_NOT_FOUND","DIRECTORY_NOT_FOUND","FILE_TYPE_MISMATCH"]);function YE(e){const t=r=>Se(e.operationContext,r.signal);return{files:{[Pi]:async(r,n)=>{Zo(n);const i=Ko(e.picker),o=WE(r),s=await Ze(()=>i.pickFiles(o,t(n)));return e.registry.registerFiles(s,"external",o.mode,o.multiple?void 0:1)},[Li]:async(r,n)=>{Zo(n);const i=Ko(e.picker),o=ZE(r),s=await Ze(()=>i.pickDirectory(o,t(n)));return e.registry.registerDirectory(s,"external",o.mode)},[Ci]:async(r,n)=>{Zo(n);const i=Ko(e.picker),o=KE(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:{[gn]:async(r,n)=>{const i=Je(r,["recursive","exclusive"]),o=e.registry.resolveFile(i.target);mr(o.mode),await Ze(()=>o.create(Kc(i),t(n)))},[pn]:async(r,n)=>{const i=Je(r),o=e.registry.resolveFileEntry(i.target);if(e.registry.assertSandboxOrigin(o),mr(o.handle.mode),!o.handle.remove)throw tt(pn);await Ze(()=>o.handle.remove(t(n)))},[xi]:async(r,n)=>{const i=Je(r);return Xc(async()=>{const o=await e.registry.resolveFile(i.target).stat(t(n));if(!te(o)||o.kind!=="file")throw ed()})},[yn]:async(r,n)=>{const i=Je(r),o=Jc(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 g("FILE_ENCODING_INVALID","文件不是合法 UTF-8 文本")}},[Ui]:async(r,n)=>{const i=Je(r,["content"]);typeof i.content!="string"&&nt("content 必须是字符串");const o=e.registry.resolveFile(i.target);mr(o.mode),await Ze(()=>o.write(new TextEncoder().encode(i.content),t(n)))},[En]:async(r,n)=>{const i=Je(r),o=await Ze(()=>e.registry.resolveFile(i.target).read(t(n)));return Jc(o)},[ji]:async(r,n)=>{const i=Je(r,["content"]),o=e.registry.resolveFile(i.target);mr(o.mode),await Ze(()=>o.write(JE(i.content),t(n)))},[wn]:async(r,n)=>{const i=Je(r),o=await Ze(()=>e.registry.resolveFile(i.target).stat(t(n)));return ew(o)}},directory:{[zi]:async(r,n)=>{const i=Je(r,["recursive","exclusive"]),o=e.registry.resolveDirectory(i.target);mr(o.mode),await Ze(()=>o.create(Kc(i),t(n)))},[In]:async(r,n)=>{const i=Je(r,["recursive"]);if(te(i.target)&&i.target.relativePath===".")throw g("FILE_ACCESS_DENIED","不能删除根目录");const o=e.registry.resolveDirectoryEntry(i.target);if(e.registry.assertSandboxOrigin(o),mr(o.handle.mode),!o.handle.remove)throw tt(In);await Ze(()=>o.handle.remove({recursive:i.recursive===void 0?!1:io(i.recursive,"recursive")},t(n)))},[Hi]:async(r,n)=>{const i=Je(r);return Xc(async()=>{const o=await e.registry.resolveDirectory(i.target).stat(t(n));if(!te(o)||o.kind!=="directory")throw ed()})},[Fi]:async(r,n)=>{const i=Je(r,["limit"]),o=XE(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 WE(e){if(e===void 0)return{mode:"read",multiple:!1};te(e)||nt("pickFiles 参数必须是对象"),Oo(e,["mode","accept","multiple"]);const t=kl(e.mode,"read"),r=e.multiple===void 0?!1:io(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 ZE(e){return e===void 0?{mode:"read"}:(te(e)||nt("pickDirectory 参数必须是对象"),Oo(e,["mode"]),{mode:kl(e.mode,"read")})}function KE(e){return te(e)||nt("saveFile 参数必须是对象"),Oo(e,["suggestedName"]),{suggestedName:On(e.suggestedName,"suggestedName")}}function Je(e,t=[]){return(!te(e)||!Object.prototype.hasOwnProperty.call(e,"target"))&&nt("文件操作参数必须包含 target"),Oo(e,["target",...t]),e}function Kc(e){return{recursive:e.recursive===void 0?!1:io(e.recursive,"recursive"),exclusive:e.exclusive===void 0?!1:io(e.exclusive,"exclusive")}}function kl(e,t){return e===void 0?t:(e!=="read"&&e!=="readwrite"&&nt("mode 必须是 read 或 readwrite"),e)}function io(e,t){return typeof e!="boolean"&&nt(`${t} 必须是布尔值`),e}function XE(e){if(e===void 0)return Zc;if((!Number.isSafeInteger(e)||e<=0)&&nt("limit 必须是正整数"),e>Zc)throw g("DIRECTORY_LIST_LIMIT_EXCEEDED","目录项限制超过 Host 上限");return e}function Oo(e,t){const r=Object.keys(e).filter(n=>!t.includes(n));r.length&&nt(`不支持字段: ${r.join(", ")}`)}function mr(e){if(e!=="readwrite")throw g("FILE_ACCESS_DENIED","当前文件授权只允许读取")}function Zo(e){if(!e.trustedUserGesture)throw g("USER_GESTURE_REQUIRED","当前操作需要可信用户手势")}function Ko(e){if(!e)throw tt("files.external");return e}async function Xc(e){try{return await e(),!0}catch(t){if(qE.has(Aa(t)??""))return!1;throw Tr(t)}}async function Ze(e){try{return await e()}catch(t){throw Tr(t)}}function JE(e){return e instanceof Uint8Array||nt("content 必须是 Uint8Array"),typeof SharedArrayBuffer<"u"&&e.buffer instanceof SharedArrayBuffer&&nt("不支持 SharedArrayBuffer-backed Uint8Array"),new Uint8Array(e)}function Jc(e){if(!(e instanceof Uint8Array))throw g("FILE_IO_FAILED","Host 返回了无效字节数据");return new Uint8Array(e)}function ed(){return g("FILE_TYPE_MISMATCH","文件句柄类型不匹配")}function ew(e){if(!te(e)||e.kind!=="file"||!tw(e.size))throw g("FILE_IO_FAILED","Host 返回了无效 FileStat");for(const t of["modifiedAt","createdAt"])if(e[t]!==void 0&&!rw(e[t]))throw g("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 tw(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function rw(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0}function nt(e){throw g("INVALID_PARAMS",e)}const td=16*1024,rd=200;function nw(e){const t=Zu(e.runtimePermissions);function r(n,i){e.capabilities&&Vu(i,e.capabilities);const o=t({kind:"all",permissions:["filesystem"]},i);if(!o.allowed)throw g(o.code,o.message);const s=Se(e.operationContext,n);return vs(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 nd(()=>s.handle.list({limit:rd},o),o);return e.registry.describeListedEntries(s,a,rd).map(({name:c,kind:d})=>({name:c,kind:d}))},async read(n,i={}){const o=i.maxBytes??td;if(!Number.isSafeInteger(o)||o<1||o>td)throw g("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 g("DIAGNOSTICS_UNSUPPORTED","当前 Host 不支持有界文件诊断读取");const c=await nd(()=>a.readPrefix({maxBytes:o},s),s);if(!c||!(c.bytes instanceof Uint8Array)||c.bytes.byteLength>o||typeof c.truncated!="boolean")throw g("FILE_IO_FAILED","Host 返回了无效的有界读取结果");return{bytes:new Uint8Array(c.bytes),truncated:c.truncated}}}}function vs(e){if(e.signal.aborted)throw g("FILE_ACCESS_REVOKED","诊断文件查询已取消或实例已结束")}async function nd(e,t){let r;try{const n=await Promise.race([e(),new Promise((i,o)=>{r=()=>o(g("FILE_ACCESS_REVOKED","诊断文件查询已取消或实例已结束")),t.signal.addEventListener("abort",r,{once:!0}),t.signal.aborted&&r()})]);return vs(t),n}catch(n){throw t.signal.aborted&&vs(t),Tr(n)}finally{r&&t.signal.removeEventListener("abort",r)}}const iw=new Set(["METHOD_FORBIDDEN","MEDIA_PICKER_CANCELLED","MEDIA_SYSTEM_PERMISSION_DENIED","MEDIA_PREPARE_FAILED","MEDIA_PREVIEW_UNAVAILABLE","REQUEST_UNSUPPORTED","USER_GESTURE_REQUIRED"]),Xo={METHOD_FORBIDDEN:"当前 Host 未开放媒体选择能力",MEDIA_PICKER_CANCELLED:"用户取消了媒体选择",MEDIA_SYSTEM_PERMISSION_DENIED:"系统未授予相机或相册权限",MEDIA_PREPARE_FAILED:"媒体准备失败,未保留部分结果",MEDIA_PREVIEW_UNAVAILABLE:"当前 Host 无法提供受控媒体预览",REQUEST_UNSUPPORTED:"当前 Host 不支持该媒体请求形态",USER_GESTURE_REQUIRED:"当前操作需要可信用户手势"};function ow(e){if(e instanceof Ce)return g("REQUEST_UNSUPPORTED",Xo.REQUEST_UNSUPPORTED);const t=Pl(e);return t!==void 0&&iw.has(t)?g(t,Xo[t]??"媒体操作失败"):g("MEDIA_PREPARE_FAILED",Xo.MEDIA_PREPARE_FAILED)}function Pl(e){try{if(!te(e))return;const t=Object.getOwnPropertyDescriptor(e,"code");return t&&"value"in t&&typeof t.value=="string"?t.value:void 0}catch{return}}const sw=["source","mediaType","maxCount"],ii=Object.freeze({source:"album",mediaType:"all",maxCount:1});function aw(e){if(e===void 0)return ii;if(!vh(e))throw g("INVALID_PARAMS",dw(e));return cw(e)}function cw(e){return Object.freeze({source:e.source??ii.source,mediaType:e.mediaType??ii.mediaType,maxCount:e.maxCount??ii.maxCount})}function dw(e){if(!te(e))return"media.pick 参数必须是对象";const t=Object.keys(e).filter(r=>!sw.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 uw=new Set(["METHOD_FORBIDDEN","FILE_QUOTA_EXCEEDED","FILE_ACCESS_REVOKED","FILE_ACCESS_DENIED"]),lw={kind:"file",name:"media-probe",mode:"read",ref:{kind:"file",handleId:"media-probe"}};class fw{constructor(t,r,n){this.registry=t,this.media=r,this.operationContext=n}committed=new Set;disposed=!1;commit(t,r){const n=hw(t,r);let i=[];try{i=this.registerBatch(n,r.maxCount);const o=n.map((s,a)=>gw(s,i[a]));if(!Oh(o))throw wt("Host 返回的媒体结果未通过协议校验");for(const s of n)this.committed.add(s);return o}catch(o){throw this.registry.revokeFiles(i.map(pw).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=Pl(n);throw i!==void 0&&uw.has(i)?n:wt("Host 返回的媒体文件资源无法登记为只读句柄")}}releaseItems(t,r){if(t.length!==0)try{const n=this.media.release(t,r);Promise.resolve(n).catch(()=>{})}catch{}}}function id(e,t){if(e.signal.aborted)throw g("RUNTIME_DESTROYED","小程序 Runtime 已终止");if(t.aborted)throw g("REQUEST_CANCELLED","media.pick 已取消")}function hw(e,t){if(!Array.isArray(e))throw wt("Host 返回了无效媒体选择结果");const r=e.length;if(r===0)throw wt("Host 未返回任何媒体项;用户取消不得作为空数组成功");if(r>t.maxCount)throw wt("Host 返回的媒体项超过本次 maxCount");if(t.source==="camera"&&r!==1)throw wt("相机必须恰好返回 1 项");for(let n=0;n<r;n+=1){if(!Object.prototype.hasOwnProperty.call(e,n))throw wt("Host 返回了稀疏媒体结果");mw(e[n],n)}return e}function mw(e,t){if(!te(e))throw wt(`第 ${t+1} 项不是对象`);if(!Au({...e,file:lw}))throw wt(`第 ${t+1} 项不符合 media.pick 媒体项契约`);if(!te(e.file))throw wt(`第 ${t+1} 项缺少文件句柄`)}function gw(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 pw(e){return"handleId"in e.ref?e.ref.handleId:void 0}function wt(e){return g("MEDIA_PREPARE_FAILED",e)}function yw(e){const t=e.media?new fw(e.registry,e.media,e.operationContext):void 0;return{handlers:{[An]:async(n,i)=>{const o=aw(n);ww(i);const s=e.media,a=t;if(!s||typeof s.pick!="function"||!a)throw tt(An);const c=Se(e.operationContext,i.signal);id(e.operationContext,i.signal);const d=await Ew(s,o,c,e.operationContext,i.signal);id(e.operationContext,i.signal);try{return a.commit(d,o)}catch(u){throw a.releaseBatch(d,c),u}}},dispose(){t?.dispose()}}}async function Ew(e,t,r,n,i){try{return await fe(()=>e.pick(t,r),r.signal)}catch(o){throw n.signal.aborted?g("RUNTIME_DESTROYED","小程序 Runtime 已终止"):i.aborted?g("REQUEST_CANCELLED","media.pick 已取消"):ow(o)}}function ww(e){if(!e.trustedUserGesture)throw g("USER_GESTURE_REQUIRED","当前操作需要可信用户手势")}const Gn=4294967296;function Iw(e){const t=new Aw;return t.write(e),t.finish()}class Aw{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<Gn?(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=_w(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<Gn)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/Gn),this.view.setUint32(this.offset+4,t),this.offset+=8}writeInt64(t){this.ensureCapacity(8),this.view.setUint32(this.offset,Math.floor(t/Gn)),this.view.setUint32(this.offset+4,t),this.offset+=8}}function _w(e){const t=new Uint8Array(Dw(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 Dw(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 Ll(e){Os(e);const t=Iw(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 Os(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)Os(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");Os(s,t+1,r)}r.delete(e)}const Nw=["pc","console","mobile"],Mw=["game","wiki"];function oo(e){throw{code:"INVALID_PARAMS",message:e}}function bw(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ut(e,t){return typeof e!="string"||!e.trim()?oo(t):e.trim()}function od(e,t,r){return typeof e!="string"||!t.includes(e)?oo(r):e}function Sw(e){const t={target:"game_detail",appId:Ut(e.appId,"navigation.openAppPage appId 必须是非空字符串"),gameType:od(e.gameType,Nw,"navigation.openAppPage gameType 必须是 pc、console 或 mobile")};return e.page!==void 0&&(t.page=od(e.page,Mw,"navigation.openAppPage page 必须是 game 或 wiki")),e.hSrc!==void 0&&(t.hSrc=Ut(e.hSrc,"navigation.openAppPage hSrc 必须是非空字符串")),e.skuId!==void 0&&(t.skuId=Ut(e.skuId,"navigation.openAppPage skuId 必须是非空字符串")),t}function Tw(e){return{target:"user_detail",userId:Ut(e.userId,"navigation.openAppPage userId 必须是非空字符串")}}function vw(e){const t={target:"post_detail",linkId:Ut(e.linkId,"navigation.openAppPage linkId 必须是非空字符串")};return e.rootCommentId!==void 0&&(t.rootCommentId=Ut(e.rootCommentId,"navigation.openAppPage rootCommentId 必须是非空字符串")),e.commentId!==void 0&&(t.commentId=Ut(e.commentId,"navigation.openAppPage commentId 必须是非空字符串")),t}function Ow(e){const t={target:"mini_program",miniProgramId:Ut(e.miniProgramId,"navigation.openAppPage miniProgramId 必须是非空字符串")};return e.extra!==void 0&&(t.extra=e.extra),t}function Rw(e){return bw(e)?e.target==="game_detail"?Sw(e):e.target==="user_detail"?Tw(e):e.target==="post_detail"?vw(e):e.target==="mini_program"?Ow(e):oo("navigation.openAppPage target 不支持"):oo("navigation.openAppPage options 必须是对象")}function kw(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 Pw(e){return{protocolType:"openRouterPath",path:"/user_home",params:{userid:e.userId}}}function Lw(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 Cw(e){const t=e;return t.target==="game_detail"?kw(t):t.target==="user_detail"?Pw(t):Lw(t)}const xw="data:image/svg+xml;base64,PHN2ZyBwcmVzZXJ2ZUFzcGVjdFJhdGlvPSJub25lIiBvdmVyZmxvdz0idmlzaWJsZSIgc3R5bGU9ImRpc3BsYXk6IGJsb2NrOyIgd2lkdGg9IjIwIiBoZWlnaHQ9IjIwIiB2aWV3Qm94PSIwIDAgMjAgMjAiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxnIGlkPSJJY29uIj4KPHBhdGggaWQ9IlVuaW9uIiBkPSJNNS4wMzMzOCAxLjI5Mjg5QzUuNDIzOSAwLjkwMjM2OSA2LjA1NzI0IDAuOTAyMzY5IDYuNDQ3NzYgMS4yOTI4OUM2LjgzODI3IDEuNjgzNDIgNi44MzgyOCAyLjMxNjc2IDYuNDQ3NzYgMi43MDcyN0w1LjIzODQ2IDMuOTE2NThIMTEuNjY2N0MxNS40NDA1IDMuOTE2NzEgMTguNTAwMSA2Ljk3NjIgMTguNTAwMSAxMC43NTAxQzE4LjUgMTQuNTIzOCAxNS40NDA0IDE3LjU4MzQgMTEuNjY2NyAxNy41ODM1SDMuMzMzMzVDMi43ODExMiAxNy41ODM1IDIuMzMzMjcgMTcuMTM1NiAyLjMzMzE5IDE2LjU4MzRDMi4zMzMxOSAxNi4wMzExIDIuNzgxMDcgMTUuNTgzMiAzLjMzMzM1IDE1LjU4MzJIMTEuNjY2N0MxNC4zMzU5IDE1LjU4MzEgMTYuNDk5NyAxMy40MTkzIDE2LjQ5OTggMTAuNzUwMUMxNi40OTk4IDguMDgwNzYgMTQuMzM1OSA1LjkxNzAzIDExLjY2NjcgNS45MTY5SDQuNTkwNjdMNi40NDc3NiA3Ljc3NDhDNi44MzgyMSA4LjE2NTMzIDYuODM4MjYgOC43OTg2OCA2LjQ0Nzc2IDkuMTg5MThDNi4wNTcyNCA5LjU3OTQ1IDUuNDIzODMgOS41Nzk1NiA1LjAzMzM4IDkuMTg5MThMMS43OTI4MyA1Ljk0NzgyQzEuNDAyMzEgNS41NTczIDEuNDAyMzEgNC45MjM5NiAxLjc5MjgzIDQuNTMzNDRMNS4wMzMzOCAxLjI5Mjg5WiIgZmlsbD0id2hpdGUiLz4KPC9nPgo8L3N2Zz4K",Uw="data-hb-sdk-fullscreen-exit",jw=3e3,zw=2e3,sd="var(--white-70a,rgba(255,255,255,.7))",ad="0 0 var(--space-8,8px) var(--white-20a,rgba(255,255,255,.2))";function Hw(e){if(typeof document>"u"||!document.body)return;const t=document.createElement("button");t.type="button",t.setAttribute(Uw,""),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 ${sd}`,`box-shadow:${ad}`,"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=xw,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 p(w=zw){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")},w)}function m(){l(),o=!0,t.style.width="48px",t.style.opacity="1",t.style.borderColor=sd,t.style.boxShadow=ad,n.style.visibility="",i.style.display="",t.setAttribute("aria-label","退出全屏"),t.setAttribute("aria-expanded","true"),p()}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"})),p(jw),{dispose(){s=!0,clearTimeout(c),l(),t.removeEventListener("click",E),window.removeEventListener("resize",f),t.remove()}}}const Cl=1e4;function xl(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()},Cl);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 Jo(e,t){return e.mode===t.mode&&e.hideCapsule===t.hideCapsule}function Yr(){return{code:"REQUEST_CANCELLED",message:"方向设置已取消"}}function Fw(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??=Hw(()=>p.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&&!Jo(s,m.options)){s={...m.options};try{e.onDisplayChange?.({orientation:s.mode,fullscreen:s.hideCapsule,source:m.source})}catch{}}for(const w of m.subscribers)w.dispose(),"error"in E?w.reject(E.error):w.resolve(E.result);m.subscribers.clear()}}function f(){n&&u(n,{error:Yr()})}function l(m,E){return new Promise((w,I)=>{const v=()=>{m.subscribers.delete(y),y.dispose(),I(Yr()),m.subscribers.size===0&&u(m,{error:Yr()})},y={resolve:w,reject:I,dispose:()=>E?.removeEventListener("abort",v)};m.subscribers.add(y),E?.addEventListener("abort",v,{once:!0}),E?.aborted&&v()})}const p={async runDisplayRequest(m,E,w){const I=++t,v=xl(E,e.operationContext.signal);try{return await v.run(async()=>{if(await w(v.signal),v.signal.aborted)throw Yr();if(cd(m),I<r)throw{code:"ORIENTATION_SUPERSEDED",message:"方向设置已被后续设置替换"};return r=I,p.apply(m,v.signal)})}finally{v.dispose()}},async apply(m,E,w="api"){if(pe(e.operationContext.signal),E?.aborted)throw Yr();const I=cd(m),v=n?.options??o,y={mode:I.orientation??v.mode,hideCapsule:I.fullscreen??v.hideCapsule};y.mode==="landscape"&&(y.hideCapsule=!0);const O=e.presentation.applyOrientation;if(!O)throw{code:"METHOD_FORBIDDEN",message:"当前宿主暂不支持方向控制"};if(n&&Jo(n.options,y))return l(n,E);if(n&&u(n,{error:{code:"ORIENTATION_SUPERSEDED",message:"方向设置已被后续设置替换"}}),i&&Jo(i.options,y))return i.result;i=void 0;const j={options:y,source:w,controller:new AbortController,subscribers:new Set};n=j;const b=l(j,E);return e.operationContext.signal.addEventListener("abort",f,{once:!0}),E||(j.timer=setTimeout(()=>{u(j,{error:{code:"ORIENTATION_TIMEOUT",message:"方向切换超时"}})},Cl)),fe(()=>O.call(e.presentation,y,{...e.operationContext,signal:j.controller.signal}),j.controller.signal).then(T=>u(j,{result:T??{supported:!0}}),T=>u(j,{error:T})),b},dispose(){e.operationContext.signal.removeEventListener("abort",c),c()}};return p}function Ul(e){throw{code:"INVALID_PARAMS",message:e}}function dd(e,t){e!==void 0&&(typeof e!="object"||e===null||Array.isArray(e)||Object.keys(e).length)&&Ul(`${t} 不支持参数`)}function Bw(e){return{[Yi]:async(t,r)=>{const n=Se(e.operationContext,r.signal,r.requestId);pe(n.signal),dd(t,"navigation.close"),await fe(()=>e.presentation.close(n),n.signal)},[Wi]:async(t,r)=>{const n=Se(e.operationContext,r.signal,r.requestId);pe(n.signal),dd(t,"navigation.reload"),await fe(()=>e.presentation.reload(n),n.signal)},[Zi]:async(t,r)=>{const n=Se(e.operationContext,r.signal,r.requestId);pe(n.signal);const i=Rw(t);if(i.target==="mini_program"){let o;if(i.extra!==void 0)try{o=Ll(i.extra)}catch{Ul("navigation.openAppPage extra 必须是符合限制的 JSON-compatible 数据")}const s=e.resetDisplay;if(s){const a=xl(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(Cw(i),n),n.signal)}}}const ud={UPLOAD_CANCELLED:"上传已取消",UPLOAD_TIMEOUT:"上传空闲超时",UPLOAD_NETWORK_FAILED:"上传网络失败",FILE_CHANGED:"上传源文件已变化",METHOD_FORBIDDEN:"当前 Host 未开放上传能力"};async function Vw(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 g("UPLOAD_CANCELLED","上传已取消")};s();let a,c;try{a=i.resolveFileEntry(e.from).hostHandle,c=await a.stat(o)}catch(l){throw s(),Tr(l)}if(s(),c.kind!=="file"||!Number.isSafeInteger(c.size)||c.size<0)throw g("FILE_IO_FAILED","上传源文件状态无效");if(e.maxBytes!==void 0&&c.size>e.maxBytes)throw g("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,...p}=e,m=await n.upload(a,{...p,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 g("UPLOAD_NETWORK_FAILED","Host 返回的上传字节数无效");if(m.status>=200&&m.status<300&&m.uploadedBytes!==c.size)throw g("FILE_CHANGED","上传源文件已变化");return t.postProgress({loaded:m.uploadedBytes,total:c.size,lengthComputable:!0}),m}catch(l){u=!0;const p=Aa(l);throw p&&ud[p]?g(p,ud[p]):o.signal.aborted?g("UPLOAD_CANCELLED","上传已取消"):p?.startsWith("FILE_")||p?.startsWith("DIRECTORY_")?Tr(l):g("UPLOAD_NETWORK_FAILED","上传网络失败")}}const Oa="withCredentials",Gw=new Set(["url","method","params","data","headers","timeout",Oa]),$w=new Set(["url","to","params","headers","timeout","suggestedName","overwrite","maxBytes",Oa]),Qw=new Set(["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"]),ld=3e4,Rs=2*1024*1024,qw=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,jl=/[\u0000-\u0008\u000A-\u001F\u007F]/,Yw=/^(?:authorization|authentication-info|proxy-authentication-info|cookie|set-cookie|set-cookie2|pkey|x-pkey|x-access-token|x-auth-token)$/i,Ww="network.request 不支持 multipart/form-data,请使用专用上传能力";function Zw(e){const t=Kw(e.runtimePermissions);t.firstParty=e.firstParty===!0,t.networkPolicy=t.firstParty?void 0:Qu(e.networkPolicy);const r=lI(e.allowedHttpOrigins);return{[ki]:async(n,i)=>{const o=Jw(n,{permission:t,allowedHttpOrigins:r}),s=await Vw(o,i,e),{uploadedBytes:a,...c}=s;return hd(c)},[Ri]:async(n,i)=>{const o=eI(n,{permission:t,allowedHttpOrigins:r});return nl(o,i,{transfer:e.transfer,fileRegistry:e.fileRegistry,operationContext:e.operationContext})},[Oi]:async(n,i)=>{const o=Se(e.operationContext,i?.signal);pe(o.signal);const s=Xw(n,{permission:t,allowedHttpOrigins:r});let a;try{a=await fe(()=>e.network.request(s,o),o.signal)}catch(c){throw hI(c)?c:mI(c,"REQUEST_UNSUPPORTED")?he("REQUEST_UNSUPPORTED","当前 Host 不支持该网络请求"):he("REQUEST_FAILED","网络请求失败")}return hd(a)}}}function Kw(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 Xw(e,t){const r=Or(e,"network.request 参数必须是对象"),n=Object.keys(r).filter(c=>!Gw.has(c));if(n.length>0)throw he("INVALID_PARAMS",`network.request 不支持字段: ${n.join(", ")}`);zl(r,"network.request");const i=Ra(r,t,"network.request"),o=rI(r.method),s=r.data;s!==void 0&&oI(s),aI(i.headers,s);const a=cI(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 Jw(e,t){const r=Or(e,"network.upload 参数必须是对象"),n=new Set(["url","from","format","method","params","headers","timeout","maxBytes","fieldName","fields","fileName","contentType"]);if(Object.keys(r).some(u=>!n.has(u)))throw he("INVALID_PARAMS","network.upload 包含不支持的字段");const i=Ra(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(!Jt(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=fd(r.fieldName),c=r.fields===void 0?void 0:Or(r.fields,"fields 必须是字符串字典");for(const[u,f]of Object.entries(c??{}))if(fd(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"||jl.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>Rs)throw he("INVALID_PARAMS","multipart 元数据超过 2 MiB");return{...s,fieldName:a,...c===void 0?{}:{fields:{...c}},...r.fileName===void 0?{}:{fileName:Da(r.fileName)},contentType:r.contentType??"application/octet-stream"}}function fd(e){if(typeof e!="string"||!e||/[\u0000-\u001F\u007F"\\]/.test(e))throw he("INVALID_PARAMS","multipart 字段名必须是非空且无控制字符的字符串");return e}function eI(e,t){const r=Or(e,"network.download 参数必须是对象"),n=Object.keys(r).filter(c=>!$w.has(c));if(n.length>0)throw he("INVALID_PARAMS",`network.download 不支持字段: ${n.join(", ")}`);zl(r,"network.download");const i=Ra(r,t,"network.download");if(i.timeout!==void 0&&i.timeout<=0)throw he("INVALID_PARAMS","network.download timeout 必须是有限正数");Hp(i.headers);const o=Jt(r.to),s=wu(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=Da(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 Ra(e,t,r){const n=tI(e.url,t.allowedHttpOrigins,r),i=kg(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(Rg(n.pathname,i))throw he("PERMISSION_DENIED",`${r} 不允许访问 Runtime 或账号敏感接口`);return{url:n,official:i,params:e.params===void 0?void 0:{...Or(e.params,`${r} params 必须是对象`)},headers:e.headers===void 0?void 0:nI(e.headers,r),timeout:iI(e.timeout,r)}}function tI(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 rI(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(!Qw.has(t))throw he("INVALID_PARAMS","network.request method 不合法");return t}function nI(e,t="network.request"){const r=Or(e,`${t} headers 必须是 Record<string, string>`),n={};for(const[i,o]of Object.entries(r)){const s=i.trim();if(!s||s!==i||!qw.test(s)||typeof o!="string"||jl.test(o))throw he("INVALID_PARAMS",`${t} headers 必须是 Record<string, string>`);if(Pg(s))throw he("INVALID_PARAMS",`${t} 不允许设置敏感请求头: ${i}`);n[s]=o}return n}function zl(e,t){const r=e[Oa];if(r!==void 0&&typeof r!="boolean")throw he("INVALID_PARAMS",`${t} 旧版凭据字段必须是布尔值`)}function iI(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>ld)throw he("INVALID_PARAMS",`${t} timeout 不能超过 ${ld}ms`);return e}}function oI(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(sI(e)>Rs)throw he("INVALID_PARAMS",`network.request data 不能超过 ${Rs} 字节`)}function sI(e){if(typeof e=="string")return es(e);if(e instanceof ArrayBuffer||ArrayBuffer.isView(e))return e.byteLength;if(typeof URLSearchParams<"u"&&e instanceof URLSearchParams)return es(e.toString());try{const t=JSON.stringify(e);return t?es(t):0}catch{throw he("INVALID_PARAMS","network.request data 必须可序列化")}}function aI(e,t){const r=Hl(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",Ww)}function cI(e,t,r){if(t===void 0)return;const n=Hl(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)||uI(t))?"form":dI(t)?"json":void 0}function Hl(e){return e?Object.entries(e).find(([r])=>r.trim().toLowerCase()==="content-type")?.[1].toLowerCase():void 0}function dI(e){return e===null||typeof e=="boolean"||typeof e=="number"||typeof e=="object"&&!ArrayBuffer.isView(e)&&!(e instanceof ArrayBuffer)}function uI(e){if(typeof e!="object"||e===null)return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function lI(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&&fI(n.hostname)&&t.add(n.origin)}catch{}return t}function fI(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 hd(e){return Object.keys(e.headers).some(md)?{...e,headers:Object.fromEntries(Object.entries(e.headers).filter(([t])=>!md(t)))}:e}function md(e){const t=e.trim().toLowerCase();return Yw.test(t)||t.startsWith("x-heybox-")||t.startsWith("x-xhh-")}function hI(e){return e instanceof Error&&e.name==="AbortError"}function mI(e,t){return typeof e=="object"&&e!==null&&"code"in e&&e.code===t}function Or(e,t){if(typeof e!="object"||e===null||Array.isArray(e))throw he("INVALID_PARAMS",t);return e}function es(e){return new TextEncoder().encode(e).length}function he(e,t){return{code:e,message:t}}function gI(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function pI(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 yI(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=pI(i);o?r.has(o)||(r.add(o),n.push(o)):t.push("post.topicIds 每项必须是正整数或非空字符串")}return{invalidMessages:t,values:n}}function EI(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 Fl(e,t){if(e==null)return{};if(!gI(e))return{invalidMessage:`${t.method} post 必须是对象或 null`};const r=yI(e.topicIds),n=EI(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 wI(e){try{return new URL(e).protocol==="heybox-mini-dev:"}catch{return!1}}async function II(e){try{if(wI(e.getCurrentHref()))return!0}catch{}try{return!!await e.isDevRuntime()}catch{return!1}}function Ue(e){throw{code:"INVALID_PARAMS",message:e}}function Ln(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ks(e,t){return typeof e!="string"||!e.trim()?Ue(t):e}function AI(e,t){const r=ks(e,t);try{const n=new URL(r);return n.protocol!=="http:"&&n.protocol!=="https:"?Ue(t):r}catch{return Ue(t)}}function _I(e){return e==="wechatSession"||e==="wechatTimeline"||e==="qqFriend"||e==="qzone"||e==="weibo"}function Bl(e,t,r){const n=e.identity.get(),i=n?.miniProgramId.trim();if(!i)return Ue(`${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 Ue(`${t} 缺少有效的小程序分享地址`)}}function DI(e,t){if(!Ln(e))return Ue("share.showShareMenu 参数必须是对象");if(Object.prototype.hasOwnProperty.call(e,"url"))return Ue("share.showShareMenu 不支持自定义 url");const r=e.channel;if(r!==void 0&&!_I(r))return Ue("share.showShareMenu channel 不合法");const n=Vl(e.extra,"share.showShareMenu");return{title:ks(e.title,"share.showShareMenu title 必须是非空字符串"),description:ks(e.desc,"share.showShareMenu desc 必须是非空字符串"),url:Bl(t,"share.showShareMenu",n),...e.imageUrl===void 0?{}:{imageUrl:AI(e.imageUrl,"share.showShareMenu imageUrl 必须是 HTTP(S) URL")},...r===void 0?{}:{channel:r}}}function Vl(e,t){if(e!==void 0)try{return Ll(e)}catch{return Ue(`${t} extra 必须是符合限制的 JSON-compatible 数据`)}}async function Gl(e,t){return e.invalidMessage&&await fe(()=>II(t.environment),t.operationContext.signal)?Ue(e.invalidMessage):e.post}function gd(e,t){const r=Number(e);return Number.isFinite(r)&&r>0?r:t}function NI(e){const t=e.getViewportMetrics();return{left:0,top:0,width:gd(t.windowWidth,0),height:gd(t.windowHeight,0)}}function Ps(e,t){const r=Number(e);return!Number.isFinite(r)||r<0?Ue(t):r}function pd(e,t){const r=Number(e);return!Number.isFinite(r)||r<=0?Ue(t):r}function MI(e){return Ln(e)?{left:Ps(e.left,"share.screenshot rect.left 必须是非负数字"),top:Ps(e.top,"share.screenshot rect.top 必须是非负数字"),width:pd(e.width,"share.screenshot rect.width 必须是正数"),height:pd(e.height,"share.screenshot rect.height 必须是正数")}:Ue("share.screenshot rect 必须是对象")}function yd(e,t){if(e!=null&&!Ln(e))return Ue("share.screenshot 参数必须是对象");const r=e??{};return r.saveToAlbum!==void 0&&typeof r.saveToAlbum!="boolean"?Ue("share.screenshot saveToAlbum 必须是布尔值"):r.watermarkTheme!==void 0&&r.watermarkTheme!=="light"&&r.watermarkTheme!=="dark"?Ue("share.screenshot watermarkTheme 必须是 light 或 dark"):{watermarkTheme:r.watermarkTheme??"dark",rect:r.rect===void 0?NI(t):MI(r.rect),...r.delay===void 0?{}:{delay:Ps(r.delay,"share.screenshot delay 必须是非负数字")},...r.saveToAlbum===void 0?{}:{saveToAlbum:r.saveToAlbum}}}async function bI(e,t){pe(t.operationContext.signal);const r=DI(e,t);let n=Fl(e.post,{maxTopicIds:1,method:"share.showShareMenu"});r.channel&&n.post&&(n={invalidMessage:n.invalidMessage||"share.showShareMenu channel 与 post 不能同时使用"});const i=await Gl(n,t);return fe(()=>t.presentation.showShareMenu({...r,post:i},t.operationContext),t.operationContext.signal)}async function SI(e,t){if(pe(t.operationContext.signal),e!==void 0&&!Ln(e))return Ue("share.copyLink 参数必须是对象");const r=Vl(e?.extra,"share.copyLink"),n=Bl(t,"share.copyLink",r);return await fe(()=>t.presentation.setClipboard({text:n},t.operationContext),t.operationContext.signal),n}async function Ed(e,t,r,n=!1){pe(t.operationContext.signal);const i=Fl(Ln(e)?e.post:void 0,{method:"share.screenshot"}),o=await Gl(i,t),s=t.identity.get()?.miniProgramId.trim()||void 0,a=TI(),{watermarkTheme:c,...d}=r;let u=!1,f,l,p;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 w=await t.prepareLongScreenshot(r.rect,t.operationContext.signal);f=w.restore,d.rect=w.rect}l=await t.prepareScreenshot?.(d.rect,t.operationContext.signal,c),p={status:"fulfilled",value:await fe(()=>t.presentation.captureAndShare({...d,...n?{longContent:!0}:{},post:o,...s?{sourceMiniProgramId:s}:{}},t.operationContext),t.operationContext.signal)}}catch(E){p={status:"rejected",error:E}}finally{try{l?.()}finally{f?.()}}const m=u?await vI(t.presentation,a,t.operationContext.signal):void 0;if(p.status==="rejected")throw p.error;if(m)throw m;return p.value}function TI(){return{lifecycle:"cleanup",signal:new AbortController().signal}}async function vI(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 OI(e){let t=Promise.resolve();const r=async(n,i)=>{const o=Se(e.operationContext,i.signal,i.requestId),s=yd(n,e.presentation);(s.rect.top+s.rect.height>1e4||s.rect.left+s.rect.width>2048||s.rect.width*s.rect.height>4e6)&&Ue("长图尺寸超出限制");const a=t.then(()=>Ed(n,{...e,operationContext:o},s,!0));return t=a.then(()=>{},()=>{}),a};return{[Si]:r,[Ni]:(n,i)=>SI(n,{...e,operationContext:Se(e.operationContext,i.signal,i.requestId)}),[Mi]:(n,i)=>bI(n,{...e,operationContext:Se(e.operationContext,i.signal,i.requestId)}),[bi]:async(n,i)=>{const o=Se(e.operationContext,i.signal,i.requestId);pe(o.signal);const s=yd(n,e.presentation),a=t.then(()=>Ed(n,{...e,operationContext:o},s));return t=a.then(()=>{},()=>{}),fe(()=>a,o.signal)}}}const wd=new WeakMap,$n=new Map;function $l(e){const t=e.canonicalIdentity?.miniProgramId?.trim();if(t)return Jm(t);const r=e.anonymousStorageScope?.trim();if(r)return`anon_${Bu(r)}`;throw Object.assign(new Error("storage scope 只能在 canonical identity 绑定后使用"),{code:"INVALID_STATE"})}function Ql(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=wd.get(t);f||(f=new Map,wd.set(t,f));const l=f.get(u)??Promise.resolve(),p=async()=>(pe(c.signal,{preserveReason:!0}),d(u)),m=l.catch(()=>{}).then(()=>e.lock?e.lock(u,p):p());f.set(u,m);try{return await m}finally{f.get(u)===m&&f.delete(u)}},o=async(c,d,u=!1)=>{const f=cr(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(zn(c),d);if((l===void 0||l==="")&&!u)throw Object.assign(new Error("当前客户端缺少数据索引,且不支持遍历本地数据,暂无法清理"),{code:"STORAGE_INDEX_MISSING"});let p;try{p=l?JSON.parse(l):[]}catch{throw new Error("本地数据索引异常")}if(!Array.isArray(p)||p.length>uc||p.some(m=>typeof m!="string"||!/^[A-Za-z0-9_-]{1,128}$/.test(m)))throw new Error("本地数据索引异常");return[...new Set(p)]},s=async(c,d)=>{if(e.diagnostics){const l=cr(c,"");return(await e.diagnostics.listRaw(d)).filter(p=>p.key.startsWith(l)&&p.value!=="").map(p=>({...p,key:p.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 p=await Promise.all(f.slice(l,l+16).map(async m=>{const E=await e.storage.getRaw(cr(c,m),d);return E!==void 0&&E!==""?{area:"local",key:m,value:E}:void 0}));for(const m of p)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(cr(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 p=[...new Set([...l,c])];await e.storage.setRaw(zn(f),JSON.stringify(p),u)}pe(u.signal,{preserveReason:!0}),await e.storage.setRaw(cr(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(zn(d),JSON.stringify(u),c);for(let f=0;f<u.length;f+=16){pe(c.signal,{preserveReason:!0});const p=(await Promise.allSettled(u.slice(f,f+16).map(m=>e.storage.setRaw(cr(d,m),"",c)))).find(m=>m.status==="rejected");if(p)throw p.reason}pe(c.signal,{preserveReason:!0}),await e.storage.setRaw(zn(d),"[]",c)})}}}function ql(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=($n.get(e)??Promise.resolve()).catch(()=>{}).then(t);return $n.set(e,r),r.finally(()=>{$n.get(e)===r&&$n.delete(e)})}const RI=128,kI=/^[A-Za-z0-9_-]+$/;function PI(e){const t=e.scopedStorage??Ql({storage:e.storage,resolveScope:()=>$l({canonicalIdentity:e.identity.get(),anonymousStorageScope:e.anonymousStorageScope}),diagnostics:e.storageDiagnostics}),r={[hn]:async n=>{pe(e.operationContext.signal);const i=Id(n,hn,e.storageLimits?.maxKeyLength),o=await fe(()=>t.get(i,e.operationContext),e.operationContext.signal);return{data:Ad(o)}},[mn]:async n=>{pe(e.operationContext.signal);const i=Yl(n,"storage.setStorage 参数必须是对象"),o=Id(i,mn,e.storageLimits?.maxKeyLength),s=LI(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"?tr("STORAGE_DIAGNOSTICS_NOT_READY","Storage diagnostics 只能在 canonical identity 绑定后使用"):i})).map(i=>{const o=i.value;return{area:i.area,key:i.key,value:Ad(o),serializedValue:o,bytes:Wl(o)}}).sort((i,o)=>i.key.localeCompare(o.key)))}}}function Id(e,t,r=RI){const i=Yl(e,`${t} 参数必须是对象`).key;if(typeof i!="string")throw tr("INVALID_PARAMS",`${t} key 必须是字符串`);if(!i||i.length>r||!kI.test(i))throw tr("INVALID_PARAMS",`storage key 仅支持 1-${r} 位字母、数字、下划线和连字符`);return i}function LI(e,t){let r;try{r=JSON.stringify(e)}catch{throw tr("INVALID_PARAMS","storage.setStorage data 必须可 JSON 序列化")}if(typeof r!="string")throw tr("INVALID_PARAMS","storage.setStorage data 必须可 JSON 序列化");if(t!==void 0&&Wl(r)>t)throw tr("STORAGE_QUOTA_EXCEEDED",`storage.setStorage data 超出 ${t} 字节限制`);return r}function Ad(e){if(!(e===void 0||e===""))try{return JSON.parse(e)}catch{return e}}function Yl(e,t){if(typeof e!="object"||e===null||Array.isArray(e))throw tr("INVALID_PARAMS",t);return e}function Wl(e){return new TextEncoder().encode(e).length}function tr(e,t){return{code:e,message:t}}const _d=120;function Pt(e){throw{code:"INVALID_PARAMS",message:e}}function ka(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Zl(e,t,r){const n=Object.keys(e).filter(i=>!t.includes(i));n.length&&Pt(`${r} 不支持字段: ${n.join(", ")}`)}function CI(e){if(!ka(e))return Pt("ui.showToast 参数必须是对象");if(Zl(e,["message","status"],"ui.showToast"),typeof e.message!="string"||!e.message.trim())return Pt("ui.showToast message 必须是非空字符串");const t=e.message.trim();if(t.length>_d)return Pt(`ui.showToast message 不能超过 ${_d} 字符`);const r=e.status;if(r!==void 0&&r!=="success"&&r!=="error")return Pt("ui.showToast status 必须是 success 或 error");const n=r;return{message:t,...n===void 0?{}:{status:n}}}function xI(e){return e===void 0?{dismissible:!1}:ka(e)?(Zl(e,["dismissible"],"ui.showLoading"),e.dismissible!==void 0&&typeof e.dismissible!="boolean"?Pt("ui.showLoading dismissible 必须是布尔值"):{dismissible:e.dismissible??!1}):Pt("ui.showLoading 参数必须是对象")}function UI(e){e!==void 0&&(!ka(e)||Object.keys(e).length)&&Pt("ui.hideLoading 不支持参数")}function jI(e){return{[Bi]:async(t,r)=>{const n=Se(e.operationContext,r.signal,r.requestId);pe(n.signal),await fe(()=>e.presentation.showToast(CI(t),n),n.signal)},[Vi]:async(t,r)=>{const n=Se(e.operationContext,r.signal,r.requestId);pe(n.signal),await fe(()=>e.presentation.showLoading(xI(t),n),n.signal)},[Gi]:async(t,r)=>{const n=Se(e.operationContext,r.signal,r.requestId);pe(n.signal),UI(t),await fe(()=>e.presentation.hideLoading(n),n.signal)}}}const zI={auth:"optional",channel:"api",failurePresentation:"none",id:"heybox.account.home_v2.get",method:"GET",path:"/account/home_v2/",parse(e){return Te(e,"当前用户首页资料接口响应异常")}},HI=3e4;function FI(e,t,r={}){const n=r.ttlMs??HI,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 So(e,zI,void 0,{...t,credentials:"heybox-session",...o?{gate:o}:{}})}catch(l){throw t.signal.aborted?g("RUNTIME_DESTROYED","小程序 Runtime 已终止"):l instanceof Ce?g("REQUEST_UNSUPPORTED",l.message):l instanceof Pn?g("INVALID_RESPONSE","user home_v2 响应不合法"):l instanceof vr?g("REQUEST_FAILED","user home_v2 请求失败"):l instanceof kn?i&&(l.status===403||l.status===429)?g("RATE_LIMITED","user home_v2 请求已被网关限流,请稍后重试",{status:l.status,...l.retryAfterMs===void 0?{}:{retryAfterMs:l.retryAfterMs}}):g("REQUEST_FAILED",l.message):VI(l)?l:g("REQUEST_FAILED","user home_v2 请求失败")}return BI(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 p=s,m=d().then(E=>(s===p&&(a={userId:f,value:E,expiresAt:Date.now()+n}),E)).finally(()=>{c?.promise===m&&(c=void 0)});return c={userId:f,generation:p,promise:m},m}return{get:u,clear(){s+=1,a=void 0,c=void 0}}}function BI(e,t){if(!te(e))throw g("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 g(n,r)}if(!te(e.result))throw g("INVALID_RESPONSE",`${t} result 必须是对象`);return e.result}function VI(e){return te(e)&&typeof e.code=="string"&&typeof e.message=="string"}const GI={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,"关注用户接口响应异常")}},$I={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 接口响应异常")}},QI={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 接口响应异常")}},qI={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 YI(e,t=As){const r=Qp({version:"2",validate:ZI}),n={ttlMs:Number.isFinite(t)?Math.max(0,Math.floor(t)):As,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 Dd(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 WI(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 ZI(e){if(!te(e)||!Array.isArray(e.gameList)||typeof e.hasMore!="boolean"||!Number.isInteger(e.nextOffset)||Number(e.nextOffset)<0||(Nd(e,"total"),e.isMe!==void 0&&typeof e.isMe!="boolean"))throw Ir();for(const t of e.gameList){if(!te(t)||!Ls(t.appid)||!Ls(t.steamAppid)||typeof t.name!="string"||!t.name.trim())throw Ir();for(const r of["image","portraitImage","icon"])KI(t,r);for(const r of["playtimeForever","playtime2Weeks"])Nd(t,r);if(t.tags!==void 0&&(!Array.isArray(t.tags)||t.tags.some(r=>typeof r!="string"||!r.trim())))throw Ir()}return e}function Ls(e){return typeof e=="number"&&Number.isFinite(e)}function Nd(e,t){if(e[t]!==void 0&&!Ls(e[t]))throw Ir()}function KI(e,t){if(e[t]!==void 0&&typeof e[t]!="string")throw Ir()}function Ir(){return g("INVALID_RESPONSE","Steam 游戏库缓存数据不合法")}const Kl=20,XI=100,JI=128,Xl=0,Jl="weeks",eA=100,tA=new Set(["weeks","all","achieved"]);function rA(){return{nickname:"",avatar:""}}function nA(e){const t=FI(e.network,e.operationContext,{requestGate:e.requestGate,requestPolicyEnabled:e.requestPolicyEnabled}),r=e.requestPolicyEnabled!==!1,n=e.cacheManager??sl(),i=YI(n,r?e.steamGameListTtlMs:0);let o;const s=new Map;let a=Promise.resolve();function c(C,z){const k=JSON.stringify([C,z]);return(!o||o.key!==k)&&(o={key:k,scope:n.createScope(z,n.createScope(C))}),o.scope}function d(){const C=o;o=void 0,C&&n.invalidateScope(C.scope).catch(()=>{}),s.clear()}const u=yl({ttlMs:Math.max(0,Math.floor(e.profileTtlMs??gl))}),f=e.requestGate?{capability:"user",gate:e.requestGate}:void 0;let l,p,m=0,E=!1;const w=e.account.onChange(()=>{m+=1,t.clear(),u.invalidate(),d()}),I=e.authorization.onEvent((C,z)=>{C==="user_info_authorization_change"&&Object.values(z).some(k=>k==="denied")&&(m+=1,t.clear(),u.invalidate(),d(),a=a.then(async()=>{if(E)return;const k=await e.account.getCurrentUserId(e.operationContext);typeof k=="string"&&k.trim()&&await n.invalidateScope(c(y(),k.trim()))}).catch(()=>{}))});function v(){if(E||e.operationContext.signal.aborted)throw g("RUNTIME_DESTROYED","小程序 Runtime 已终止")}function y(){const C=e.identity.get()?.miniProgramId?.trim();if(!C)throw g("INVALID_STATE","用户能力缺少 canonical 小程序身份");return C}async function O(){v(),await a,v();let C;try{C=await e.account.getCurrentUserId(e.operationContext)}catch(z){throw e.operationContext.signal.aborted?g("RUNTIME_DESTROYED","小程序 Runtime 已终止"):Wr(z)?z:g("REQUEST_FAILED","读取小黑盒账号失败")}return typeof C=="string"&&C.trim()?C.trim():void 0}async function j(C,z){const k=await O();if(m!==z||k!==C)throw g("AUTHORIZATION_CONTEXT_CHANGED","用户请求期间账号上下文已变化,请重新操作")}async function b(C,z,k=e.operationContext.signal){try{return await So(e.network,C,z,{...e.operationContext,signal:k,credentials:"heybox-session",...f?{gate:f}:{}})}catch(S){throw e.operationContext.signal.aborted?g("RUNTIME_DESTROYED","小程序 Runtime 已终止"):S instanceof Ce?g("REQUEST_UNSUPPORTED",S.message):S instanceof Pn?g("INVALID_RESPONSE","用户接口响应不合法"):S instanceof vr?g("REQUEST_FAILED","用户请求失败"):S instanceof kn?r&&(S.status===403||S.status===429)?g("RATE_LIMITED","用户请求已被网关限流,请稍后重试",{status:S.status,...S.retryAfterMs===void 0?{}:{retryAfterMs:S.retryAfterMs}}):g("REQUEST_FAILED",S.message):Wr(S)?S:g("REQUEST_FAILED","用户请求失败")}}async function T(C,z){if(!e.authorizationContext)return{mini_program_id:C};let k;try{k=await fe(()=>e.authorizationContext.get({...e.operationContext,signal:z}),z)}catch(S){if(Wr(S))throw S;const M=g("REQUEST_FAILED","读取 Runtime auth context 失败");throw Object.defineProperty(M,"cause",{configurable:!0,value:S}),M}if(!k.token?.trim())throw g("INVALID_STATE","关注作者缺少启动凭据");return{mini_program_id:C,runtime_auth_context_token:k.token}}async function D(){v();const C=y(),z=m,k=await O();if(!k){if(m!==z)throw g("AUTHORIZATION_CONTEXT_CHANGED","查询期间账号已变化");return"notFollowing"}const S=await T(C,e.operationContext.signal);await j(k,z);const M=await b($I,S);if(await j(k,z),y()!==C)throw g("AUTHORIZATION_CONTEXT_CHANGED","查询期间小程序上下文已变化");return Sd(bd(M))}function x(C,z){if(!C)return Promise.reject(g("USER_GESTURE_REQUIRED","请点击按钮关注作者"));if(z?.aborted)return Promise.reject(g("REQUEST_CANCELLED","关注操作已取消"));if(l)return Promise.reject(g("FOLLOW_IN_PROGRESS","关注确认流程尚未结束"));if(!e.authPresentation?.confirmFollowAuthor)return Promise.reject(g("METHOD_FORBIDDEN","当前宿主不支持关注确认框"));const k=P(z).finally(()=>{l===k&&(l=void 0)});return l=k,k}async function P(C){v();const z=y(),k=new AbortController;p=k;const S=()=>k.abort();e.operationContext.signal.addEventListener("abort",S,{once:!0}),C?.addEventListener("abort",S,{once:!0});let M=()=>{},H=!1;try{try{await fe(()=>e.account.ensureAuthenticated({trustedUserGesture:!0,reason:"user_action",signal:k.signal}),k.signal)}catch(le){throw Wr(le)&&["AUTH_CANCELLED","AUTHORIZATION_CANCELLED","HEYBOX_APP_LOGIN_REQUIRED","LOGIN_CANCELLED"].includes(le.code)?g("FOLLOW_CANCELLED","已取消小黑盒登录"):le}v();const F=m;M=e.account.onChange(()=>{H=!0,S()});const $=await fe(O,k.signal);if(!$)throw g("FOLLOW_CANCELLED","未完成小黑盒登录");const K=async()=>{if(await fe(()=>j($,F),k.signal),v(),y()!==z)throw g("AUTHORIZATION_CONTEXT_CHANGED","关注期间小程序上下文已变化")};await K();const h=await T(z,k.signal);await K();const N=fA(),U=await fe(()=>b(QI,{...h,request_id:N},k.signal),k.signal);await K();const q=bd(U);if(q.status!=="notFollowing")return Sd(q);if(q.rateLimited)throw g("FOLLOW_GUIDANCE_LIMIT_REACHED","今日关注引导次数已达上限");const ae=await fe(()=>e.authPresentation.confirmFollowAuthor({miniProgramId:z,signal:k.signal}),k.signal);if(await K(),ae!=="confirmed")throw g("FOLLOW_CANCELLED","已取消关注作者");const de=q.authorId,ce=await fe(()=>b(GI,{body:{following_id:de}},k.signal),k.signal);if(await K(),ce.status!=="ok"){const le=["login","relogin","lack_token"].includes(ce.status)?"HEYBOX_APP_LOGIN_REQUIRED":"REQUEST_FAILED";throw g(le,typeof ce.msg=="string"&&ce.msg.trim()?ce.msg.trim():"关注作者失败,请稍后重试")}return"following"}catch(F){throw v(),H?g("AUTHORIZATION_CONTEXT_CHANGED","关注期间账号已变化,请重新操作"):C?.aborted?g("REQUEST_CANCELLED","关注操作已取消"):Wr(F)?F:g("REQUEST_FAILED","关注作者失败,请稍后重试")}finally{M(),e.operationContext.signal.removeEventListener("abort",S),C?.removeEventListener("abort",S),p===k&&(p=void 0)}}async function Q(){y();const C=m,z=await O();if(!z)return{isHeyboxAppLoggedIn:!1,authorization:null,userInfo:null};const[k,S]=await Promise.all([e.authorization.getOrCreateLocalIdentity(z),R(z).catch(()=>rA())]);return await j(z,C),{isHeyboxAppLoggedIn:!0,authorization:e.authorization.getAuthorization(),userInfo:{app_user_id:k.appUserId,profile:S,...k.steamId?{steam_id:k.steamId}:{}}}}function R(C){return u.read(C,()=>b(pl,void 0).then(z=>{const k=Cs(z,"账号基础信息");if(k.display_username!==void 0&&typeof k.display_username!="string")throw g("INVALID_RESPONSE","账号基础信息 nickname 不合法");if(k.display_avatar!==void 0&&typeof k.display_avatar!="string")throw g("INVALID_RESPONSE","账号基础信息 avatar 不合法");return{nickname:k.display_username??"",avatar:k.display_avatar??""}}))}async function L(C){const z=iA(C),k=y(),S=m,M=await O();if(!M)return d(),{isLogin:!1,isBound:!1,data:null};const H=await t.get(M);await j(M,S);const F=ef(H.steam_id_info);if(Object.keys(F).length===0)return await n.invalidateScope(c(k,M)).catch(()=>{}),await j(M,S),s.delete(JSON.stringify([k,M])),{isLogin:!0,isBound:!1,data:null};const $=JSON.stringify([k,M]),K=c(k,M),h=Dd({...z,steamId:void 0},F),N=tf(F.personal_infomation_open??F.personal_information_open),U=JSON.stringify([h??null,N??null]),q=s.get($);q&&q.identity!==U&&(await n.invalidateScope(K).catch(()=>{}),await j(M,S));const ae={identity:U,scope:n.createScope(U,K)};s.set($,ae);const de=Dd(z,F),ce=de?i.persistent:i.unresolved,le=n.createScope(de??"unresolved",ae.scope),Ee=async()=>{if(await j(M,S),y()!==k||s.get($)?.identity!==U)throw g("AUTHORIZATION_CONTEXT_CHANGED","Steam 游戏库请求期间绑定上下文已变化")},me=await ce.read({scope:le,key:WI({miniProgramId:k,userId:M,effectiveSteamId:de,personalInformationOpen:N,query:z}),signal:e.operationContext.signal,load:async ge=>{const ye=await b(qI,{userId:M,...z,personalInformationOpen:N},ge);return await Ee(),dA(Cs(ye,"Steam 游戏库"),z)}}).catch(async ge=>{throw await Ee(),ge});return await Ee(),{isLogin:!0,isBound:!0,data:me}}return{getFollowStatus:D,requestFollowAuthor:x,getInfo:Q,getSteamGameList:L,async invalidateSteamGameListCache(){const C=y(),z=m,k=await O();if(!k)return;const S=c(C,k);await Promise.all([i.persistent.invalidateScope(S),i.unresolved.invalidateScope(S)]),t.clear(),s.delete(JSON.stringify([C,k])),await j(k,z)},dispose(){E||(E=!0,p?.abort(),m+=1,w(),I(),t.clear(),u.dispose(),i.persistent.dispose(),i.unresolved.dispose(),e.cacheManager||n.dispose())}}}function iA(e){if(e==null)return{limit:Kl,offset:Xl,sort:Jl,includeHidden:!1};if(!te(e))throw Lt("user.getSteamGameList 参数必须是对象");const t=Object.keys(e).find(n=>!["steamId","limit","offset","sort","q","includeHidden"].includes(n));if(t)throw Lt(`user.getSteamGameList 不支持字段: ${t}`);const r={limit:oA(e.limit),offset:sA(e.offset),sort:aA(e.sort),includeHidden:cA(e.includeHidden)};if(e.steamId!==void 0){if(typeof e.steamId!="string"||!e.steamId.trim()||e.steamId.trim().length>JI)throw Lt("user.getSteamGameList steamId 必须是非空字符串");r.steamId=e.steamId.trim()}if(e.q!==void 0){if(typeof e.q!="string")throw Lt("user.getSteamGameList q 必须是字符串");const n=e.q.trim();n&&(r.q=n.slice(0,eA))}return r}function oA(e){if(e===void 0)return Kl;if(!Number.isInteger(e)||Number(e)<1)throw Lt("user.getSteamGameList limit 必须是正整数");return Math.min(Number(e),XI)}function sA(e){if(e===void 0)return Xl;if(!Number.isInteger(e)||Number(e)<0)throw Lt("user.getSteamGameList offset 必须是非负整数");return Number(e)}function aA(e){if(e===void 0)return Jl;if(typeof e!="string"||!tA.has(e))throw Lt("user.getSteamGameList sort 不支持");return e}function cA(e){if(e===void 0)return!1;if(typeof e!="boolean")throw Lt("user.getSteamGameList includeHidden 必须是 boolean");return e}function dA(e,t){if(!Array.isArray(e.game_list))throw g("INVALID_RESPONSE","Steam 游戏库 game_list 必须是数组");const r=e.game_list.map(uA).filter(a=>a!==void 0),n=so(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=tf(e.is_me);return s!==void 0&&(o.isMe=s),o}function uA(e){const t=ef(e),r=so(t.appid),n=so(t.steam_appid)??r,i=Pa(t.name);if(r===void 0||n===void 0||!i)return;const o={appid:r,steamAppid:n,name:i};ts(o,"image",t.image),typeof t.vertical_head_image=="string"&&ts(o,"portraitImage",t.vertical_head_image),ts(o,"icon",t.appicon??t.icon),Md(o,"playtimeForever",t.playtime_forever),Md(o,"playtime2Weeks",t.playtime_2weeks);const s=lA(t.external_tags??t.tags);return s.length&&(o.tags=s),o}function Cs(e,t){if(!te(e))throw g("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 g(n,r)}if(!te(e.result))throw g("INVALID_RESPONSE",`${t} result 必须是对象`);return e.result}function ef(e){return te(e)?e:{}}function Pa(e){return typeof e=="string"?e.trim():typeof e=="number"||typeof e=="boolean"?String(e):""}function lA(e){return Array.isArray(e)?e.map(Pa).filter(Boolean):[]}function so(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"&&e.trim()&&Number.isFinite(Number(e)))return Number(e)}function tf(e){if(e===!0||e===1||e==="1")return!0;if(e===!1||e===0||e==="0")return!1}function ts(e,t,r){const n=Pa(r);n&&Object.assign(e,{[t]:n})}function Md(e,t,r){const n=so(r);n!==void 0&&Object.assign(e,{[t]:n})}function Lt(e){return g("INVALID_PARAMS",e)}function Wr(e){return te(e)&&typeof e.code=="string"&&typeof e.message=="string"}function bd(e){const t=Cs(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 g("INVALID_RESPONSE","关注状态响应不合法");return{status:t.follow_status===2?"self":t.follow_status===1?"following":"notFollowing",authorId:t.author_id,rateLimited:t.rate_limited}}function Sd(e){return e.status}function fA(){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 hA(e){return{[wi]:async t=>(Qn(t,"user.getFollowStatus"),e.user.getFollowStatus()),[Ii]:async(t,r)=>(Qn(t,"user.requestFollowAuthor"),e.user.requestFollowAuthor(r.trustedUserGesture,r.signal)),[Ai]:async t=>(Qn(t,"user.getInfo"),e.user.getInfo()),[_i]:async(t,r)=>{Qn(t,"user.revokeAuthorization"),await e.authorization.revoke(r.trustedUserGesture)},[Di]:async t=>e.user.getSteamGameList(t)}}function Qn(e,t){if(e!==void 0)throw g("INVALID_PARAMS",`${t} 不接收入参`)}function mA(){return g("USER_DATA_PERMISSION_STATE_INVALID","本地用户数据许可状态异常,已停止访问")}function Td(e){return g("USER_DATA_PERMISSION_SAVE_FAILED","本次运行已停止访问,设置未保存,请重试",e===void 0?void 0:{reason:e instanceof Error?e.message:String(e)})}function gA(e){const t=e.managedResources??Yt,r=typeof e.storage.withLock=="function"||typeof navigator<"u"&&!!navigator.locks,n=e.hash??pa,i=new Map,o=new Set;let s=!1;function a(){if(s)throw g("RUNTIME_DESTROYED","小程序 Runtime 已终止")}function c(y,O){if(e.storage.withLock)return e.storage.withLock(u(y),O);if(typeof navigator<"u"&&navigator.locks)return ql(u(y),O);throw g("REQUEST_UNSUPPORTED","当前宿主不支持跨实例保存资料许可")}function d(y){return ag({miniProgramId:e.resolveMiniProgramId(),userId:y,environment:e.resolveEnvironment()})}function u(y){return tg(sg(d(y)))}function f(y,O){return e.purposeOf?n(bu(y,e.revisionOf(y),O,e.purposeOf(y))):n(`${y}\0${e.revisionOf(y)}\0${O}`)}function l(y,O){return`${y}\0${O}`}async function p(y,O){let j;try{j=await e.storage.getRaw(u(y),O)}catch(T){throw a(),O.signal.aborted?g("REQUEST_CANCELLED","许可操作已取消"):g("USER_DATA_PERMISSION_STORAGE_UNAVAILABLE","无法读取本地用户数据许可",{reason:T instanceof Error?T.message:String(T)})}if(a(),O.signal.aborted)throw g("REQUEST_CANCELLED","许可操作已取消");const b=j===void 0||j===""?void 0:og(j);if(j!==void 0&&j!==""&&b===void 0)throw mA();return b??{schema_version:1,records:{}}}async function m(y,O,j){if(a(),j.signal.aborted)throw g("REQUEST_CANCELLED","许可操作已取消");await e.storage.setRaw(u(y),JSON.stringify(O),j)}function E(y){return y?.revision??0}function w(y,O,j){const b=new Set(j.declared??[]),T=new Set(t);for(const P of Object.keys(O.records))Rt(P)&&T.add(P);for(const P of i.keys())P.startsWith(`${y}\0`)&&T.add(P.slice(y.length+1));const x=[...T].sort((P,Q)=>{const R=Yt.indexOf(P),L=Yt.indexOf(Q);return(R<0?Number.MAX_SAFE_INTEGER:R)-(L<0?Number.MAX_SAFE_INTEGER:L)}).map(P=>{const Q=O.records[P],R=E(Q),L=j.egressTier===void 0?void 0:f(P,j.egressTier),C=i.get(l(y,P)),z=C!==void 0&&C.revision===R&&(L===void 0||C.consentFingerprint===L);return{resource:P,name:ha(P)?.name??P,purposeText:e.purposeOf?.(P)??"",scopeFingerprint:L??"",declared:b.has(P),available:b.has(P),decision:Q?.decision??"ask",revision:R,...Q?.decision==="allow"&&Q.consentFingerprint?{consentFingerprint:Q.consentFingerprint}:{},sessionAllowed:z,allowed:!o.has(l(y,P))&&b.has(P)&&Q?.decision!=="deny"&&(z||r&&Q?.decision==="allow"&&L!==void 0&&Q.consentFingerprint===L)}});return Object.freeze({schema_version:1,canPersist:r,resources:Object.freeze(x),...j.egressTier===void 0?{}:{egressTier:j.egressTier}})}function I(y,O,j,b){const T=O.records[j],D=l(y,j);if(o.has(D))return{status:"denied",reason:"tightening"};if(T?.decision==="deny")return{status:"denied",reason:"deny"};const x=f(j,b);if(r&&T?.decision==="allow"&&T.consentFingerprint===x)return{status:"allowed",source:"persistent"};const P=i.get(D);return P&&P.revision===E(T)&&P.consentFingerprint===x?{status:"allowed",source:"session"}:{status:"ask"}}function v(y){if(typeof y!="string"||!Yt.includes(y))throw g("INVALID_PARAMS","用户数据资源标识不合法")}return{canPersist:r,async read(y,O,j={}){a();const b=await p(y,O);return w(y,b,j)},async evaluate(y,O,j){a(),v(O.resource);const b=await p(y,j);return I(y,b,O.resource,O.egressTier)},async decide(y,O){a(),v(y.resource);const j=async()=>{a();const b=await p(y.userId,O);if(a(),O.signal.aborted)throw g("REQUEST_CANCELLED","许可操作已取消");const T=b.records[y.resource],D=E(T);if(y.expectedRevision!==void 0&&D!==y.expectedRevision)throw g("AUTHORIZATION_CONTEXT_CHANGED","资料许可已变化,请重新确认");const x=l(y.userId,y.resource),P=f(y.resource,y.egressTier);if(y.expectedFingerprint!==void 0&&y.expectedFingerprint!==P)throw g("AUTHORIZATION_CONTEXT_CHANGED","资料披露范围已变化,请重新确认");if(y.scope==="session"){if(y.decision!=="allow")throw g("INVALID_PARAMS","本次许可只支持允许");return i.set(x,Object.freeze({revision:D,consentFingerprint:P})),w(y.userId,b,{egressTier:y.egressTier})}const Q=D+1,R=y.decision==="allow"?{decision:"allow",revision:Q,consentFingerprint:P}:{decision:y.decision,revision:Q},L={schema_version:1,records:{...b.records,[y.resource]:R}};y.decision!=="allow"&&(o.add(x),i.delete(x));try{await m(y.userId,L,O)}catch(C){throw Td(C)}return o.delete(x),i.delete(x),w(y.userId,L,{egressTier:y.egressTier})};return y.scope==="session"?j():c(y.userId,j)},async revokeSession(y,O){a(),y.resource!==void 0&&v(y.resource);for(const b of[...i.keys()])b.startsWith(`${y.userId}\0`)&&(y.resource===void 0||b===l(y.userId,y.resource))&&i.delete(b);const j=await p(y.userId,O);return w(y.userId,j,{})},async reset(y,O){return a(),c(y.userId,async()=>{a();const j=await p(y.userId,O);if(a(),O.signal.aborted)throw g("REQUEST_CANCELLED","许可操作已取消");const b=new Set(t);for(const x of Object.keys(j.records))b.add(x);for(const x of i.keys())x.startsWith(`${y.userId}\0`)&&b.add(x.slice(y.userId.length+1));for(const x of b)o.add(l(y.userId,x));for(const x of[...i.keys()])x.startsWith(`${y.userId}\0`)&&i.delete(x);const T={...j.records};for(const x of b)T[x]={decision:"ask",revision:(T[x]?.revision??0)+1};const D={schema_version:1,records:T};try{await m(y.userId,D,O)}catch(x){throw Td(x)}for(const x of b)o.delete(l(y.userId,x));return w(y.userId,D,{})})},dispose(){s||(s=!0,i.clear(),o.clear())}}}const Ro={auth:"none",channel:"api",method:"POST",bodyEncoding:"form",failurePresentation:"none",parse(e){return Te(e,"游戏资料接口响应异常")}};function ko(e){return{runtime_auth_context_token:e.runtime_auth_context_token,resource:e.resource,disclosure_revision:e.disclosure_revision}}const pA={...Ro,id:"heybox.user_miniprogram.runtime.user_game_data.query.post",path:"/user_miniprogram/runtime/user_game_data/query",body(e){return{...ko(e),operation:e.operation,schema_version:e.schema_version,...e.cursor===void 0?{}:{cursor:e.cursor},...e.limit===void 0?{}:{limit:e.limit}}}},yA={...Ro,id:"heybox.user_miniprogram.runtime.user_game_data.sync.post",path:"/user_miniprogram/runtime/user_game_data/sync",body:ko},vd={...Ro,id:"heybox.user_miniprogram.runtime.user_game_data.sync_status.post",path:"/user_miniprogram/runtime/user_game_data/sync_status",body(e){return{...ko(e),task_id:e.task_id}}},EA={...Ro,id:"heybox.user_miniprogram.runtime.user_game_data.file.post",path:"/user_miniprogram/runtime/user_game_data/file",body(e){return{...ko(e),save_id:e.save_id,file_id:e.file_id}}};function wA(e){const t=Nl(e.storage),r=e.fileDownloads??(e.files&&e.transfer?Ma({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 J("REQUEST_CANCELLED","资料请求已取消")};async function o(d,u){if(i(u),!e.authorizationContext)throw J("REQUEST_UNSUPPORTED","宿主缺少受信运行上下文");const f=await e.authorizationContext.get(u);if(!f.token||!Number.isFinite(f.expiresAt)||f.expiresAt<=Date.now())throw J("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 To({network:e.network,operationContext:f,subject:"游戏资料",assertUsable:()=>i(f),requestPolicyEnabled:e.requestPolicyEnabled,...e.requestGate?{gate:{capability:"userGameData",gate:e.requestGate}}:{}},d,u),p=st(l,"user.data","游戏资料");if(!Ie(p))throw J("INVALID_RESPONSE","游戏资料响应无效");return i(f),p}const a=d=>{const u=ha(d);if(!u)throw J("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 J("REQUEST_UNSUPPORTED","未开放资料操作");const p=await s(pA,{...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(p.resource!==d.resource||p.operation!==d.operation||p.schema_version!==l.version||p.disclosure_revision!==f.disclosureRevision)throw J("INVALID_RESPONSE","游戏资料合同不匹配");if(p.status==="ready"){if(!Km(l.schema,p.data))throw J("INVALID_RESPONSE","游戏资料正文不匹配公开 schema");return{status:"ready",data:p.data,meta:{},schemaVersion:l.version}}if(p.status==="empty"&&(p.reason==="no_data"||p.reason==="not_ready")&&typeof p.message=="string")return{status:"empty",reason:p.reason,message:p.message,meta:{},schemaVersion:l.version};throw J("INVALID_RESPONSE","游戏资料状态无效")},async sync(d,u,f){const l=a(d.resource);if(!l.operations.includes("sync"))throw J("REQUEST_UNSUPPORTED","资源不支持同步");const p=await o(l,u),m=new AbortController,E=()=>m.abort();u.signal.addEventListener("abort",E,{once:!0}),u.signal.aborted&&E();let w=!1;const I=setTimeout(()=>{w=!0,E()},5*6e4),v={...u,signal:m.signal},y={...f,gameId:l.game,resource:d.resource};let O;try{const j=await t.run(y,v,async()=>{const T=await t.get(y,v);if(T)return O=T,{id:T,status:await s(vd,{...await o(l,v),task_id:T},v)};const D=await s(yA,p,v);if(typeof D.task_id!="string"||!D.task_id||D.task_id.length>128)throw J("INVALID_RESPONSE","同步任务缺失");return await t.set(y,D.task_id,v),{id:D.task_id,status:D}});let b=j.status;for(O=j.id;;){if(i(v),b.state==="succeeded")return await t.remove(y,O,v),{status:"succeeded"};if(b.state==="failed")throw await t.remove(y,O,v),J(typeof b.error_code=="string"?b.error_code:"SYNC_FAILED","存档同步失败");if(b.state!=="syncing"&&b.state!=="uploading")throw J("INVALID_RESPONSE","同步状态无效");if(await IA(v.signal),b=await s(vd,{...await o(l,v),task_id:O},v),b.task_id!==O)throw J("INVALID_RESPONSE","同步任务不匹配")}}catch(j){throw O&&Ie(j)&&["SYNC_TASK_NOT_FOUND","SYNC_TASK_CHANGED","STEAM_ACCOUNT_CHANGED"].includes(String(j.code))&&await t.remove(y,O,v),w?J("REQUEST_TIMEOUT","等待同步超时,后台任务可能仍在执行"):j}finally{clearTimeout(I),u.signal.removeEventListener("abort",E)}},async file(d,u,f){const l=a(d.resource);if(!l.operations.includes("file")||!r)throw J("REQUEST_UNSUPPORTED","宿主不支持资料文件下载");const p=async E=>{await f(E);const w=await s(EA,{...await o(l,E),save_id:d.saveId,file_id:d.fileId},E);if(!Ie(w.file)||w.file.file_id!==d.fileId)throw J("INVALID_RESPONSE","文件标识不匹配");return await f(E),w},m=await r.download(await p(u),async E=>{await p(E)},u);try{return i(u),await f(u),i(u),n.add(m),m}catch(E){throw await c(m),E}}}}function IA(e){return new Promise((t,r)=>{const n=()=>{clearTimeout(i),e.removeEventListener("abort",n),r(J("REQUEST_CANCELLED","已停止等待同步"))},i=setTimeout(()=>{e.removeEventListener("abort",n),t()},2e3);e.addEventListener("abort",n,{once:!0}),e.aborted&&n()})}const Zr=["event_id","miniProgramId","environment","host_platform","host_version","sdk_version","runtime_version","egress_tier","resource","call_id","flow_id"],AA=Object.freeze({user_game_data_permission_show:new Set([...Zr,"entry","reason"]),user_game_data_permission_result:new Set([...Zr,"choice","apply_result"]),user_game_data_permission_manage:new Set([...Zr,"operation","apply_result","succeeded_count","failed_count"]),user_game_data_action:new Set([...Zr,"stage","action_type","outcome","duration_ms"]),user_game_data_access_result:new Set([...Zr,"api","trigger","status","error_code","failure_stage","duration_ms","cache_hit","sample_rate","overview_status_counts"])}),Od=10*6e4,_A=256;function DA(e){const t=e.now??Date.now,r=e.random??Math.random,n=e.createId??SA,i=MA(e.sampleRate),o=new Map,s=new Map,a=new Map;let c=!1,d=0,u=0,f=0,l=0;const p={get emitted(){return d},get failed(){return u},get skipped(){return f},get deduplicated(){return l}};function m(b){return`${b}${n()}`}function E(){const b=t();for(const[T,D]of o)b-D.createdAt<=Od||(o.delete(T),s.get(D.key)===T&&s.delete(D.key));for(const[T,D]of a){if(b-D<=Od&&a.size<=_A)break;a.delete(T)}}function w(b){const T=o.get(b);T!==void 0&&(o.delete(b),s.get(T.key)===b&&s.delete(T.key))}function I(b){w(b),a.delete(b),a.set(b,t())}function v(b,T){const D=AA[b],x={};for(const[P,Q]of Object.entries(T))Q===void 0||!D.has(P)||(x[P]=Q);return Object.freeze(x)}function y(b){const T={event_id:m("evt_"),miniProgramId:gr(()=>e.resolveMiniProgramId())??"unknown",environment:NA(gr(()=>e.resolveEnvironment())),host_platform:gr(e.resolveHostPlatform)??"unknown",host_version:gr(e.resolveHostVersion)??"unknown",sdk_version:gr(e.resolveSdkVersion)??"unknown",runtime_version:gr(e.resolveRuntimeVersion)??"unknown",egress_tier:bA(e)};return b.resource!==void 0&&(T.resource=b.resource),b.callId!==void 0&&(T.call_id=b.callId),b.flowId!==void 0&&(T.flow_id=b.flowId),T}function O(b,T){if(c){f+=1;return}try{if(e.sink===void 0){f+=1;return}e.sink.postEvent(b,v(b,T)),d+=1}catch{u+=1}}function j(b,T){if(b===void 0)return!1;const D=o.get(b);return D===void 0?!1:T==="start"&&D.started||T==="shown"&&D.shown||T==="decided"&&D.decided?!0:(T==="start"&&(D.started=!0),T==="shown"&&(D.shown=!0),T==="decided"&&(D.decided=!0),!1)}return{diagnostics:p,createCallId(){return m("call_")},beginFlow(b){E();const T=`${b.resource??""}\0${b.actionType}`,D=s.get(T);if(D!==void 0&&o.has(D))return D;const x=m("flow_");return o.set(x,{key:T,createdAt:t(),started:!1,shown:!1,decided:!1}),s.set(T,x),x},permissionShow(b){if(j(b.flowId,"shown")){l+=1;return}O("user_game_data_permission_show",{...y(b),entry:b.entry,reason:b.reason})},permissionResult(b){if(j(b.flowId,"decided")){l+=1;return}O("user_game_data_permission_result",{...y(b),choice:b.choice,apply_result:b.applyResult})},permissionManage(b){O("user_game_data_permission_manage",{...y(b),operation:b.operation,apply_result:b.applyResult,...b.succeededCount===void 0?{}:{succeeded_count:b.succeededCount},...b.failedCount===void 0?{}:{failed_count:b.failedCount}})},action(b){if(b.stage==="start"&&j(b.flowId,"start")){l+=1;return}if(b.stage==="finish"){if(b.flowId!==void 0&&a.has(b.flowId)){l+=1;return}b.flowId!==void 0&&I(b.flowId)}O("user_game_data_action",{...y(b),stage:b.stage,action_type:b.actionType,...b.outcome===void 0?{}:{outcome:b.outcome},...b.durationMs===void 0?{}:{duration_ms:Math.max(0,Math.round(b.durationMs))}})},access(b){if(i<=0){f+=1;return}if(i<1&&r()>=i){f+=1;return}O("user_game_data_access_result",{...y(b),api:b.api,trigger:b.trigger,status:b.status,duration_ms:Math.max(0,Math.round(b.durationMs)),sample_rate:i,...b.errorCode===void 0?{}:{error_code:b.errorCode},...b.failureStage===void 0?{}:{failure_stage:b.failureStage},...b.cacheHit===void 0?{}:{cache_hit:b.cacheHit},...b.overviewStatusCounts===void 0?{}:{overview_status_counts:b.overviewStatusCounts}})},dispose(){c||(c=!0,o.clear(),s.clear(),a.clear())}}}function NA(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 MA(e){return e===void 0||!Number.isFinite(e)?1:e<=0?0:e>=1?1:e}function gr(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 bA(e){try{return e.resolveEgressTier()==="upload"?"upload":"no_network"}catch{return"no_network"}}function SA(){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 TA(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=h=>I()[h]?.purpose??"",f=h=>{const N=ha(h);if(!N)throw g("REQUEST_UNSUPPORTED","未开放的资料资源");return N},l=h=>bu(h,f(h).disclosureRevision,gt(e.runtimePermissions),u(h)),p=()=>gA({storage:e.storage,resolveMiniProgramId:()=>e.identity.get()?.miniProgramId,resolveEnvironment:()=>e.environment,revisionOf:h=>f(h).disclosureRevision,purposeOf:u,...e.hash?{hash:e.hash}:{}});let m=p();const E=DA({resolveMiniProgramId:()=>e.identity.get()?.miniProgramId,resolveEnvironment:()=>e.environment,resolveEgressTier:()=>gt(e.runtimePermissions),...e.telemetry??{}}),w=wA({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 I(){const h=Qe(e.runtimePermissions),N=h.valid?h.permissions.user_game_data:void 0;return N?.status==="enabled"?_n(N.config.resources):{}}function v(h){if(t||e.operationContext.signal.aborted)throw g("RUNTIME_DESTROYED","小程序已关闭");if(h?.signal.aborted)throw g("REQUEST_CANCELLED","资料请求已取消")}function y(h){for(const[N,U]of o)U!==void 0&&(h===void 0||U===h)&&N.abort()}function O(h){for(const[N,U]of s)(h===void 0||N===h)&&(U.abort(),s.delete(N))}function j(){r++,O();for(const h of o.keys())h.abort();for(const h of a)e.fileRegistry.revokeFiles([h]);a.clear(),c.clear(),w.invalidate()}const b=vo(e.account,h=>{if(i&&n===h)return;const N=n;i=!0,n=h,N!==void 0&&(j(),m.dispose(),m=p())}),T=()=>j();e.operationContext.signal.addEventListener("abort",T,{once:!0});async function D(h,N){v(h);const U=new AbortController,q=()=>U.abort();o.set(U,void 0),h.signal.addEventListener("abort",q,{once:!0}),h.signal.aborted&&q();const ae={...e.operationContext,...h,signal:U.signal};try{const de=await N(ae);return v(ae),de}catch(de){throw te(de)&&de.name==="AbortError"?g("REQUEST_CANCELLED","资料操作已取消"):de}finally{h.signal.removeEventListener("abort",q),o.delete(U)}}function x(h){const N=f(h);if(!u(N.key))throw g("USER_DATA_RESOURCE_NOT_DECLARED","小程序未声明这项游戏资料",{resource:N.key});return N}async function P(h){v(h);const N=await e.account.getCurrentUserId(h);if(v(h),!i)i=!0,n=N;else if(n!==N){const U=n;n=N,U!==void 0&&(j(),m.dispose(),m=p(),v(h))}return N}function Q(h,N){const U={login_required:"请先登录小黑盒",permission_required:"尚未允许读取这项资料",permission_denied:"已拒绝读取这项资料",source_not_linked:"请先在小黑盒关联对应游戏账号",source_login_required:"请先在小黑盒更新游戏来源登录"},q=N==="login_required"?{type:"user_login",label:"登录并授权"}:N==="permission_required"?{type:"permission",label:"允许读取"}:N==="permission_denied"&&e.presentation?.openDataPermissions?{type:"manage",label:"管理数据权限"}:void 0;return{status:"blocked",resource:h,reason:N,message:U[N],...q?{interaction:q}:{}}}async function R(h,N){x(h);const U=await P(N);if(!U)return Q(h,"login_required");const q=await m.evaluate(U,{resource:h,egressTier:gt(e.runtimePermissions)},N);return v(N),q.status==="allowed"?{userId:U}:Q(h,q.status==="denied"?"permission_denied":"permission_required")}async function L(h,N,U,q,ae){if(v(ae),r!==U||await P(ae)!==N||l(h)!==q)throw g("AUTHORIZATION_CONTEXT_CHANGED","账号或资料范围已变化");return R(h,ae)}function C(h,N){if(!te(h)||typeof h.resource!="string")throw g("INVALID_PARAMS","资料请求无效");if(!Rt(h.resource))throw g("REQUEST_UNSUPPORTED","当前宿主尚未开放该资料资源");const U=N==="query"?["resource","operation","schemaVersion","cursor","limit"]:["resource","saveId","fileId"];if(Object.keys(h).some(ae=>!U.includes(ae)))throw g("INVALID_PARAMS","资料请求包含未知参数");const q=x(h.resource);if(N==="query"){if(h.operation!=="get"&&h.operation!=="list")throw g("INVALID_PARAMS","资料查询操作无效");const ae=q.queries[h.operation];if(!ae)throw g("REQUEST_UNSUPPORTED","资源不支持该查询");if(h.schemaVersion!==ae.version)throw g("REQUEST_UNSUPPORTED","SDK 与宿主正文合同版本不匹配");if(h.operation!=="list"&&(h.cursor!==void 0||h.limit!==void 0))throw g("INVALID_PARAMS","单份查询不能分页");if(h.cursor!==void 0&&(typeof h.cursor!="string"||!h.cursor||h.cursor.length>32768))throw g("INVALID_PARAMS","分页游标无效");if(!ae.page&&(h.cursor!==void 0||h.limit!==void 0))throw g("INVALID_PARAMS","该列表不支持分页");if(h.limit!==void 0&&(typeof h.limit!="number"||!Number.isInteger(h.limit)||h.limit<1||h.limit>(ae.page?.maxSize??100)))throw g("INVALID_PARAMS","分页数量无效")}else if(!q.operations.includes(N))throw g("REQUEST_UNSUPPORTED","资源不支持该操作");if(N==="file"&&(typeof h.saveId!="string"||!h.saveId||typeof h.fileId!="string"||!h.fileId))throw g("INVALID_PARAMS","资料文件标识无效");return N==="query"?{resource:h.resource,operation:h.operation,schemaVersion:h.schemaVersion,...h.cursor===void 0?{}:{cursor:h.cursor},...h.limit===void 0?{}:{limit:h.limit}}:{resource:h.resource,saveId:h.saveId,fileId:h.fileId}}async function z(h,N,U,q){const ae=d(),de=r,ce=l(N.resource);for(const le of o.keys())le.signal===U.signal&&o.set(le,N.resource);try{const le=await R(N.resource,U);if("status"in le)return E.access({resource:N.resource,api:h,trigger:"initial",status:"blocked",durationMs:d()-ae}),le;let Ee;try{Ee=await q()}catch(ge){const ye=te(ge)?ge.code:void 0;if(ye==="USER_DATA_SOURCE_NOT_LINKED"||ye==="USER_DATA_SOURCE_LOGIN_REQUIRED")return E.access({resource:N.resource,api:h,trigger:"initial",status:"blocked",durationMs:d()-ae}),Q(N.resource,ye==="USER_DATA_SOURCE_NOT_LINKED"?"source_not_linked":"source_login_required");throw ge}const me=await L(N.resource,le.userId,de,ce,U);return"status"in me?(E.access({resource:N.resource,api:h,trigger:"initial",status:"blocked",durationMs:d()-ae}),me):(E.access({resource:N.resource,api:h,trigger:"initial",status:te(Ee)&&Ee.status==="empty"?"empty":h===nn?"succeeded":"ready",durationMs:d()-ae}),Ee)}catch(le){throw E.access({resource:N.resource,api:h,trigger:"initial",status:"error",durationMs:d()-ae,errorCode:te(le)?String(le.code):"REQUEST_FAILED"}),le}}async function k(h){const N=await P(h);if(!N)throw g("UNAUTHORIZED","请先登录小黑盒");return m.read(N,h,{declared:Object.keys(I()),egressTier:gt(e.runtimePermissions)})}async function S(h,N){const U=x(h);let q=await P(N);if(q||(await e.account.ensureAuthenticated({trustedUserGesture:!0,reason:"user_action",signal:N.signal}),q=await P(N)),!q)return{status:"cancelled"};let ae=await m.evaluate(q,{resource:h,egressTier:gt(e.runtimePermissions)},N);if(ae.status==="allowed")return{status:"allowed"};if(ae.status==="denied"){if(e.presentation?.openDataPermissions){const Me=r,Pe=l(h),je=await e.presentation.openDataPermissions({resource:h,miniProgramName:e.miniProgramPresentation?.name,signal:N.signal});if(!("status"in await L(h,q,Me,Pe,N)))return{status:"allowed"};if(!je)return{status:"cancelled"}}return ae=await m.evaluate(q,{resource:h,egressTier:gt(e.runtimePermissions)},N),{status:ae.status==="allowed"?"allowed":"denied"}}if(!e.presentation?.confirmDataPermission)throw g("REQUEST_UNSUPPORTED","当前宿主不支持资料许可弹窗");O(h);const de=new AbortController;s.set(h,de);const ce=()=>de.abort();N.signal.addEventListener("abort",ce,{once:!0}),N.signal.aborted&&ce();const le={...N,signal:de.signal},Ee=r,me=l(h),ge=m,ye=E.beginFlow({resource:h,actionType:"permission"});let Oe="error";try{const Pe=(await ge.read(q,le,{egressTier:gt(e.runtimePermissions)})).resources.find(Ft=>Ft.resource===h);E.action({resource:h,flowId:ye,stage:"start",actionType:"permission"}),E.permissionShow({resource:h,flowId:ye,entry:"other",reason:Pe?.decision==="allow"?"scope_changed":"first"});const je=await fe(()=>e.presentation.confirmDataPermission({miniProgramName:e.miniProgramPresentation?.name,resource:h,scopeText:`此黑盒账号关联的${U.name}${U.operations.includes("sync")?`。${Fh}`:""}`,purposeText:u(h),egress:gt(e.runtimePermissions),canPersist:ge.canPersist,signal:de.signal}),de.signal);if(v(le),r!==Ee||await P(le)!==q||l(h)!==me)throw g("AUTHORIZATION_CONTEXT_CHANGED","资料许可范围已变化");return je.decision==="cancelled"?(Oe="cancelled",E.permissionResult({resource:h,flowId:ye,choice:"cancel",applyResult:"cancelled"}),{status:"cancelled"}):(await ge.decide({userId:q,resource:h,decision:je.decision==="deny"?"deny":"allow",scope:je.decision==="session"?"session":"persistent",egressTier:gt(e.runtimePermissions),expectedRevision:Pe?.revision??0,expectedFingerprint:Pe?.scopeFingerprint},le),je.decision==="deny"&&y(h),Oe=je.decision==="deny"?"unresolved":"resolved",E.permissionResult({resource:h,flowId:ye,choice:je.decision,applyResult:"applied"}),{status:je.decision==="deny"?"denied":"allowed"})}catch(Me){throw Oe=le.signal.aborted?"cancelled":"error",E.permissionResult({resource:h,flowId:ye,choice:"cancel",applyResult:le.signal.aborted?"cancelled":"error"}),Me}finally{E.action({resource:h,flowId:ye,stage:"finish",actionType:"permission",outcome:Oe}),N.signal.removeEventListener("abort",ce),s.get(h)===de&&s.delete(h)}}async function M(h,N,U,q,ae,de){N==="allow"?x(h):f(h);const ce=await P(q);if(!ce)throw g("UNAUTHORIZED","请先登录小黑盒");try{await m.decide({userId:ce,resource:h,decision:N,scope:U,expectedRevision:ae,expectedFingerprint:de,egressTier:gt(e.runtimePermissions)},q)}catch(le){throw te(le)&&le.code==="USER_DATA_PERMISSION_SAVE_FAILED"&&y(h),le}return O(h),N!=="allow"&&y(h),k(q)}async function H(h,N,U){try{const q=await U();return E.permissionManage({operation:h,resource:N,applyResult:"applied"}),q}catch(q){throw E.permissionManage({operation:h,resource:N,applyResult:te(q)&&q.code==="USER_DATA_PERMISSION_SAVE_FAILED"?"save_failed":"error"}),q}}async function F(h,N){O(h),y(h);const U=await P(N);if(!U)throw g("UNAUTHORIZED","请先登录小黑盒");return H("revoke",h,async()=>(await m.revokeSession({userId:U,resource:h},N),k(N)))}function $(){let h;const N=U=>D(e.operationContext,async q=>{const ae=await P(q);if(!ae)throw g("UNAUTHORIZED","请先登录小黑盒");if(h&&(h.userId!==ae||h.generation!==r))throw g("AUTHORIZATION_CONTEXT_CHANGED","管理页面所属账号已变化,请重新打开");return h??={userId:ae,generation:r},U(q)});return{getSnapshot:()=>N(k),setDecision:U=>N(q=>H("modify",U.resource,()=>M(U.resource,U.decision,U.scope,q,U.expectedRevision,U.expectedFingerprint))),revokeSession:U=>N(q=>F(U?.resource,q)),resetAll:()=>N(async U=>{O(),y();const q=await P(U);return H("reset",void 0,async()=>(await m.reset({userId:q},U),k(U)))})}}return{handlers:{[sa]:async(h,N)=>D(N,async U=>{if(h!==void 0&&(!te(h)||Object.keys(h).some(de=>de!=="game")||h.game!==void 0&&typeof h.game!="string"))throw g("INVALID_PARAMS","概览参数无效");if(te(h)&&typeof h.game=="string"&&!tc(h.game))throw g("REQUEST_UNSUPPORTED","当前宿主尚未开放该游戏");const q=Object.keys(I()),ae=te(h)?h.game:void 0;return Nu.filter(de=>ae===void 0||de===ae).map(de=>({game:de,name:Du[de],resources:er.filter(ce=>ce.game===de&&q.includes(ce.key)).map(ce=>({resource:ce.key,name:ce.name,status:"not_checked",statusText:"尚未检查"}))})).filter(de=>de.resources.length>0)}),[mi]:async(h,N)=>D(N,U=>{const q=C(h,"query");return z(mi,q,U,()=>w.query(q,U))}),[nn]:async(h,N)=>D(N,async U=>{if(!te(h)||Object.keys(h).length!==1||typeof h.game!="string"||!tc(h.game))throw g("INVALID_PARAMS","同步需要指定已开放的游戏");const q={game:h.game};if(!er.some(Ee=>Ee.game===q.game&&Ee.sync))throw g("REQUEST_UNSUPPORTED","该游戏不支持存档同步");const ae=er.filter(Ee=>Ee.game===q.game&&Ee.sync&&u(Ee.key));if(ae.length===0)throw g("USER_DATA_RESOURCE_NOT_DECLARED","小程序未声明可同步的资料");let de,ce;for(const Ee of ae){const me=await R(Ee.key,U);if(!("status"in me)){de=Ee.key;break}(!ce||ce.reason==="permission_denied")&&(ce=me)}if(!de)return ce;const le={resource:de};return z(nn,le,U,async()=>{const Ee=await P(U),me=`${Ee}\0${le.resource}`;let ge=c.get(me);if(!ge){const ye=new AbortController;o.set(ye,le.resource);const Oe={controller:ye,waiters:0,settled:!1,promise:Promise.resolve(void 0)};Oe.promise=w.sync(le,{...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,U.signal)}finally{ge.waiters--,ge.waiters===0&&!ge.settled&&ge.controller.abort()}})}),[gi]:async(h,N)=>D(N,async U=>{const q=C(h,"file"),ae=await P(U),de=r,ce=l(q.resource),le=async me=>{try{const ge=await L(q.resource,ae,de,ce,me);if("status"in ge)throw g("FILE_ACCESS_REVOKED","文件授权已撤销",{reason:ge.reason})}catch(ge){throw te(ge)&&["AUTHORIZATION_CONTEXT_CHANGED","USER_DATA_RESOURCE_NOT_DECLARED"].includes(String(ge.code))?g("FILE_ACCESS_REVOKED","文件授权已失效",{causeCode:ge.code}):ge}};let Ee;try{const me=await z(gi,q,U,async()=>(Ee=await w.file(q,U,le),{handle:Ee}));if(te(me)&&me.status==="blocked"){const Me=String(me.reason);throw g(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 le(Me);const Pe=await ge.read(Me);try{return await le(Me),Pe}catch(je){throw Pe.fill(0),je}},stat:async Me=>{await le(Me);const Pe=await ge.stat(Me);return await le(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 w.releaseFile(Ee),me}}),[aa]:async(h,N)=>{if(!N.trustedUserGesture)throw g("USER_GESTURE_REQUIRED","许可操作需要点击");return D(N,U=>{if(!te(h)||Object.keys(h).length!==1||typeof h.resource!="string"||!Rt(h.resource))throw g("INVALID_PARAMS","许可资源无效");return S(h.resource,U)})},[ca]:async(h,N)=>D(N,k),[da]:async(h,N)=>{if(!N.trustedUserGesture)throw g("USER_GESTURE_REQUIRED","修改许可需要点击");if(!te(h)||typeof h.resource!="string"||!Rt(h.resource)||h.decision!=="deny"||h.scope!=="persistent"||Object.keys(h).some(U=>!["resource","decision","scope"].includes(U)))throw g("INVALID_PARAMS","允许许可只能由可信弹窗确认");return D(N,U=>M(h.resource,h.decision,"persistent",U))},[ua]:async(h,N)=>{if(!N.trustedUserGesture)throw g("USER_GESTURE_REQUIRED","管理资料许可需要点击");if(!e.presentation?.openDataPermissions)throw g("REQUEST_UNSUPPORTED","宿主未提供资料管理界面");if(h!==void 0&&(!te(h)||Object.keys(h).some(U=>U!=="resource")||h.resource!==void 0&&(typeof h.resource!="string"||!Rt(h.resource))))throw g("INVALID_PARAMS","管理资源无效");return D(N,async U=>(await e.presentation.openDataPermissions({resource:te(h)?h.resource:void 0,miniProgramName:e.miniProgramPresentation?.name,signal:U.signal}),k(U)))},[la]:async(h,N)=>{if(!N.trustedUserGesture)throw g("USER_GESTURE_REQUIRED","撤销许可需要点击");if(h!==void 0&&(!te(h)||Object.keys(h).some(U=>U!=="resource")||h.resource!==void 0&&(typeof h.resource!="string"||!Rt(h.resource))))throw g("INVALID_PARAMS","撤销资源无效");return D(N,U=>F(te(h)?h.resource:void 0,U))}},get permissionBridge(){return $()},diagnostics:{telemetry:E.diagnostics},dispose(){t||(t=!0,j(),b(),e.operationContext.signal.removeEventListener("abort",T),m.dispose(),E.dispose())}}}function Rd(e){throw{code:"INVALID_PARAMS",message:e}}function Kr(e,t){const r=Number(e);return Number.isFinite(r)&&r>0?r:t}function rf(e,t){const r=Number(e);return Number.isFinite(r)&&r>=0?r:t}function qn(e,t,r){return Math.min(rf(e,t),r)}async function vA(e){try{return rf(await e.getNavigationBarHeight(),0)}catch{return 0}}function OA(e,t,r,n){const i=qn(e.safeArea?.left,0,t),o=Math.max(i,qn(e.safeArea?.right,t,t)),s=qn(e.safeArea?.top,n,r),a=Math.max(s,qn(e.safeArea?.bottom,r,r));return{left:i,right:o,top:s,bottom:a,width:o-i,height:a-s}}async function kd(e){const t=e.getViewportMetrics(),r=Kr(t.windowWidth,0),n=Kr(t.windowHeight,0),i=await vA(e);return{pixelRatio:Kr(t.pixelRatio,1),screenWidth:Kr(t.screenWidth,r),screenHeight:Kr(t.screenHeight,n),windowWidth:r,windowHeight:n,statusBarHeight:i,safeArea:OA(t,r,n,i),screenTop:i}}function RA(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;kd(r.presentation).then(l=>{if(n||r.operationContext.signal.aborted||f!==i)return;const p=JSON.stringify(l);p!==o&&(o=p,r.onViewportChange?.(l))}).catch(()=>{})},c=Fw({...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:{[rr]:async(f,l)=>c.apply(f,l?.signal),[Ti]:async()=>(pe(r.operationContext.signal),kd(r.presentation)),[vi]:async f=>{if(pe(r.operationContext.signal),typeof f!="object"||f===null||Array.isArray(f))return Rd("viewport.setNavigationBarStyle 参数必须是对象");const l=f.foregroundStyle;if(l!=="light"&&l!=="dark")return Rd("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 kA(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 PA(e,t){return{[pi]:async(r,n)=>{const i=Se(t,n.signal,n.requestId);if(pe(i.signal),!e)throw we("CAPABILITY_UNAVAILABLE","当前 Host 不支持工作区卡片");const o=kA(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 LA=new Map(xt.map(e=>[e.method,e]));function rs(e,t,r){return{code:e,message:t,...r===void 0?{}:{data:r}}}function CA(e){const t=Zu(e);return r=>t(r.requirement,r.method)}function xA(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 UA(e){const t=CA(e.runtimePermissions),r=Qe(e.runtimePermissions);let n=0;return{async dispatch(i,o,s){const a=e.now??jA,c=e.onTrace?a():0,d=e.onTrace?Date.now():0,u=e.onTrace?s.requestId??`runtime_${++n}`:"";e.onTrace&&ns(e.onTrace,{callId:u,method:i,startedAt:d,outcome:"started"},()=>c,c);try{if(e.terminalSignal.aborted)throw rs("RUNTIME_DESTROYED","小程序 Runtime 已终止");Vu(i,e.effectiveCapabilities);const f=LA.get(i);if(!f)throw new Error(`Capability method ${i} 缺少 protocol metadata`);const l=t(f),p=!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&&!p&&!m&&!E)throw rs(l.code,l.message,l.data);const w=e.handlers[i];if(!w)throw new Error(`Capability method ${i} 缺少 handler`);const I=async O=>{for(const j of e.policies??[]){const b=await j.evaluate({method:i,payload:o,capability:f});if(e.terminalSignal.aborted||O.aborted)throw Ld();if(!b.allowed)throw rs(b.code,b.message,b.data)}if(e.terminalSignal.aborted||O.aborted)throw Ld()},y=await xA(async()=>{if(i===rr){if(!e.runDisplayRequest)throw new Error("viewport.setDisplay 缺少执行 Module");return e.runDisplayRequest(o,s.signal,I)}return await I(e.terminalSignal),w(o,s)},void 0,s,e.terminalSignal);return e.onTrace&&ns(e.onTrace,Pd(u,i,o,d,y),a,c),y}catch(f){throw e.onTrace&&ns(e.onTrace,Pd(u,i,o,d,{status:"error",error:f}),a,c),f}}}}function jA(){return typeof performance>"u"?Date.now():performance.now()}function ns(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 Pd(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:zA(i.error)}:{},...HA(t,r,i)}}function zA(e){return typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"?e.code:void 0}function HA(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"&&xs(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 xs(e){return typeof e=="object"&&e!==null}function Ld(){const e=new Error("The operation was aborted");return e.name="AbortError",e}function FA(e){const t={signal:e.terminalSignal,...e.miniProgramDetail===void 0?{}:{miniProgramDetail:e.miniProgramDetail}},r=cy(e.requestPolicy);let n;if(e.files)try{n=Xp(e.files,t)}catch{}const i=sl({store:n}),o=e.onRequestPolicyReport??(r.debugReport?BA:void 0),s=r.enabled?iy({...r.gateOptions,...o?{onReport:o}:{}}):void 0,a=new _a(e.files,e.miniProgramDetail),c=YE({registry:a,picker:e.picker,operationContext:t}),d=Ly({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,p,m,E,w=()=>{},I=()=>{};try{u=RA({operationContext:t,presentation:e.hostPresentation,onDisplayChange:L=>e.eventSink.postEvent("display_change",L),onViewportChange:L=>e.eventSink.postEvent("viewport_change",L)}),l=nA({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}),w=d.onEvent((L,C)=>e.eventSink.postEvent(L,C)),I=e.hostCompanion?.onSessionEvent?.(L=>{const C=BE(L);!e.terminalSignal.aborted&&C&&e.eventSink.postEvent(C.type,C.payload)})??(()=>{}),p=gE({authorizationContext:e.authorizationContext,account:e.account,identity:e.identity,network:e.network,operationContext:t,requestGate:s,requestPolicyEnabled:r.enabled});const v=e.files&&e.transfer?Ma({files:e.files,transfer:e.transfer,registry:a,signal:t.signal}):void 0,y=TA({identity:e.identity,account:e.account,storage:e.storage,network:e.network,authorizationContext:e.authorizationContext,files:e.files,transfer:e.transfer,fileDownloads:v,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(L,C){e.onUserDataTelemetry?.({name:L,payload:C})}}}}});E=y,m=SE({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:v,requestGate:s,requestPolicyEnabled:r.enabled});const O=PI({storage:e.storage,scopedStorage:e.scopedStorage,storageDiagnostics:e.storageDiagnostics,identity:e.identity,operationContext:t,anonymousStorageScope:e.anonymousStorageScope,storageLimits:e.storageLimits});f=yw({registry:a,media:e.media,operationContext:t});const j=[{name:"gameSaves",handlers:Object.fromEntries(Object.entries(m.handlers).map(([L,C])=>[L,async(z,k)=>{const S=e.verifiedSdkVersion,M=S?ba(S,"0.10.0-0"):void 0;if(M===void 0||M>=0)throw g("REQUEST_UNSUPPORTED","当前 SDK 不支持旧游戏存档入口,请使用 user.games.get(...).saves");return C(z,k)}]))},{name:"auth",handlers:By({authorization:d})},{name:"user",handlers:{...hA({user:l,authorization:d,runtimePermissions:e.runtimePermissions,steamAccount:e.runtimeFeatures?.steamAccount===!0,userDataMode:e.runtimeFeatures?.userDataMode}),...$p({operationContext:t,presentation:e.hostPresentation,miniProgramPresentation:e.miniProgramPresentation})}},{name:"share",handlers:OI({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:O.handlers},{name:"network",handlers:Zw({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:PA(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:jI({operationContext:t,presentation:e.hostPresentation})},{name:"device",handlers:QE({operationContext:t,presentation:e.hostPresentation,protocol:e.hostProtocol})},{name:"navigation",handlers:Bw({operationContext:t,presentation:e.hostPresentation,...e.hostPresentation.applyOrientation?{resetDisplay:L=>u.applyOrientation({mode:"portrait",hideCapsule:!1},L)}:{}})},{name:"cloud",handlers:p.handlers},{name:"userGameData",handlers:E.handlers},{name:"companion",handlers:UE({companion:e.hostCompanion,companionPresentation:e.companionPresentation,miniProgramPresentation:e.miniProgramPresentation,operationContext:t,fileRegistry:a})}],b=VA(j);let T=!1;const D=()=>{T||(T=!0,e.terminalSignal.removeEventListener("abort",D),u?.dispose(),f?.dispose(),p?.dispose(),m?.dispose(),E?.dispose(),w(),I(),l?.dispose(),i.dispose(),d.dispose(),s?.dispose(),a.dispose())};e.terminalSignal.aborted?D():e.terminalSignal.addEventListener("abort",D,{once:!0});const x=new Set(["file.readText","file.readBytes","file.stat"]),P=(L,C)=>x.has(L)&&xs(C)&&a.isCompanionAttachmentRef(C.target),Q=new Set(["file.readText","file.readBytes","file.stat","file.exists"]),R=(L,C)=>Q.has(L)&&xs(C)&&a.isUserDataDownloadRef(C.target);return{get permissionBridge(){return y.permissionBridge},modules:j,handlers:b,runDisplayRequest:u.runDisplayRequest,allowsCompanionAttachmentAccess:P,allowsGameSaveAccess:m.allowsRead,allowsUserGameDataFileAccess:R,gameSaveDiagnostics:m.diagnostics,applyOrientation:u.applyOrientation,notifyViewportChange:u.notifyChange,...O.diagnostics?{storageDiagnostics:O.diagnostics}:{},...e.files?{sandboxDiagnostics:nw({registry:a,operationContext:t,runtimePermissions:e.runtimePermissions,capabilities:e.diagnosticCapabilities})}:{},dispose:D}}catch(v){throw u?.dispose(),f?.dispose(),p?.dispose(),m?.dispose(),E?.dispose(),w(),I(),l?.dispose(),i.dispose(),d.dispose(),s?.dispose(),a.dispose(),v}}function BA(e){try{console.warn("[hb-sdk-runtime] request-policy",e)}catch{}}function VA(e){const t=new Map(xt.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=xt.map(i=>i.method).filter(i=>!r.has(i));if(n.length>0)throw new Error(`Capability registry 缺少 method: ${n.join(", ")}`);if(r.size!==xt.length)throw new Error(`Capability registry method 数量不合法: ${r.size}`);return Object.freeze(Object.fromEntries(r))}const GA="heybox-mini-dev:";function Cd(e){try{return $A(new URL(e))}catch{return!1}}function $A(e){return e.protocol===GA}function QA(e){return e==="localhost"||e==="127.0.0.1"||e==="[::1]"||qA(e)}function qA(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 YA=new Set(["android","ios","ohos","windows","macos","linux","unknown"]);function WA(e,t){const r=[],n=ZA(e.environmentInfo,r),i=oi(n?.appVersion,"host.appVersion",r),o=XA(n?.operatingSystem,r);return{info:Object.freeze({runtime:Object.freeze({mode:KA(e.sdkVersionPolicy?.releaseChannel,r)}),host:Object.freeze({appVersion:i}),miniProgram:Object.freeze({id:oi(t.miniProgramId),version:oi(t.miniProgramVersion)}),operatingSystem:Object.freeze(o)}),invalidFields:Object.freeze(r)}}function ZA(e,t){if(e!=null){if(nf(e))return e;t.push("environmentInfo")}}function KA(e,t){return e==="public"?"production":e==="preview"||e==="development"?e:(e!=null&&t.push("runtime.mode"),"unknown")}function XA(e,t){if(e==null)return{name:"unknown",version:null};if(!nf(e))return t.push("operatingSystem"),{name:"unknown",version:null};const r=YA.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:oi(e.version,"operatingSystem.version",t)}}function oi(e,t,r){return e==null?null:typeof e=="string"&&e.trim()?e.trim():(t&&r&&r.push(t),null)}function nf(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const JA="data:image/svg+xml;base64,PHN2ZyBwcmVzZXJ2ZUFzcGVjdFJhdGlvPSJub25lIiBvdmVyZmxvdz0idmlzaWJsZSIgc3R5bGU9ImRpc3BsYXk6IGJsb2NrOyIgd2lkdGg9IjY3IiBoZWlnaHQ9IjIyIiB2aWV3Qm94PSIwIDAgNjcgMjIiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxwYXRoIGlkPSJTdWJ0cmFjdCIgZD0iTTY2IDBDNjYuMzM3MiAwIDY2LjY3MDYgMC4wMTcxODM4IDY3IDAuMDQ2ODc1QzYxLjM5MzYgMC41NTIxODkgNTcgNS4yNjIwMiA1NyAxMUM1NyAxNi43MzggNjEuMzkzNiAyMS40NDY4IDY3IDIxLjk1MjFDNjYuNjcwNiAyMS45ODE4IDY2LjMzNzIgMjIgNjYgMjJIMTFDNC45MjQ4NyAyMiAwIDE3LjA3NTEgMCAxMUMwIDQuOTI0ODcgNC45MjQ4NyAyLjY1NzU2ZS0wNyAxMSAwSDY2Wk04LjI0MzE2IDYuNzM1MzVDOC4yNDMxNiA2LjU5Mzk3IDguMTQyNTggNi41MzU3NiA4LjAxOTUzIDYuNjA2NDVMNi4yMjI2NiA3LjY0MDYyQzYuMTU3ODcgNy42ODIyOCA2LjEwNDE2IDcuNzM5MTcgNi4wNjU0MyA3LjgwNTY2QzYuMDI2NzIgNy44NzIyNyA2LjAwNDEgNy45NDc1MiA2IDguMDI0NDFWMTMuOTY1OEM2LjAwMzcxIDE0LjA0MzQgNi4wMjU4NSAxNC4xMTkxIDYuMDY0NDUgMTQuMTg2NUM2LjEwMzE5IDE0LjI1NCA2LjE1NzQgMTQuMzEyIDYuMjIyNjYgMTQuMzU0NUw5Ljg3MTA5IDE2LjQ1OEM5Ljk5MzQ2IDE2LjUyNzIgMTAuMDkzNiAxNi41ODQyIDEwLjA5NDcgMTYuNTg1OUMxMC4wOTQ3IDE2LjU4NzEgMTAuMTkzNCAxNi42NDUxIDEwLjMxNjQgMTYuNzE1OEwxMi41MDEgMTcuOTY5N0MxMi42MjI4IDE4LjA0MDMgMTIuNzIzNiAxNy45ODIyIDEyLjcyMzYgMTcuODQwOFYxMi4zNjcyQzEyLjcyMyAxMi4yOTk0IDEyLjY5NTcgMTIuMjM0MyAxMi42NDc1IDEyLjE4NjVDMTIuNTk5MiAxMi4xMzg4IDEyLjUzMzggMTIuMTEyMyAxMi40NjU4IDEyLjExMjNIMTAuNzM3M0MxMC42NzAyIDEyLjExMzIgMTAuNjA1OSAxMi4xMzk5IDEwLjU1ODYgMTIuMTg3NUMxMC41MTEzIDEyLjIzNTIgMTAuNDg0NyAxMi4zMDAxIDEwLjQ4NDQgMTIuMzY3MlYxMy44Mzc5QzEwLjQ4NDIgMTMuOTc4OSAxMC4zODQ2IDE0LjAzNjQgMTAuMjYxNyAxMy45NjU4TDguNDY0ODQgMTIuOTM1NUM4LjQwMDI2IDEyLjg5MzUgOC4zNDYxNCAxMi44MzcyIDguMzA3NjIgMTIuNzcwNUM4LjI2OTE5IDEyLjcwNCA4LjI0NzM1IDEyLjYyOTQgOC4yNDMxNiAxMi41NTI3VjYuNzM1MzVaTTI0LjMzNCAxNC4zOTI2QzI0LjMzMzkgMTQuOTk4NSAyNC4yMDU1IDE1LjE4NDYgMjMuNTk4NiAxNS4xOTYzTDIyLjMwMTggMTUuMjU0OUwyMi42NjUgMTYuMjU0OUgyNS4wODY5QzI1LjY3MDUgMTYuMDg0IDI1Ljg3MjEgMTUuNzE5NCAyNS44NzIxIDE0LjgyMzJWNS43ODIyM0wyNC4zMzQgNS43MjM2M1YxNC4zOTI2Wk0zMi4yODIyIDE0LjQ3NTZDMzEuOTQ2IDE1LjA0OTIgMzEuNDY1OSAxNS43NTcxIDMxLjA5OTYgMTYuMjU0OUgzMi42MTkxQzMzLjA2NzMgMTUuNTIxMiAzMy4zNzUxIDE0LjkyOCAzMy41NDg4IDE0LjQ3NTZIMzIuMjgyMlpNMzQuODEwNSAxNS4zOTc1QzM0Ljg3OTEgMTUuNzEwMSAzNC45MzExIDE1Ljk5ODIgMzQuOTczNiAxNi4yNTQ5SDM2LjE4NjVMMzYuMTgxNiAxNi4yMzU0QzM2LjA2NjIgMTUuNzM4OCAzNS44OTg5IDE1LjAxOCAzNS43NDEyIDE0LjQ3NTZIMzQuNTI5M0wzNC44MTA1IDE1LjM5NzVaTTM2Ljk4MTQgMTQuNjUzM0MzNy4wOTg0IDE0Ljg3NyAzNy4yNDExIDE1LjE1MDEgMzcuMzMzIDE1LjQwMjNMMzcuNjM1NyAxNi4yNTQ5SDM5LjA4MDFDMzkuMDMzNiAxNS44MzI1IDM4LjU5NCAxNS4wNTUzIDM4LjIzODMgMTQuNDc1NkgzNi44ODg3QzM2LjkxNjEgMTQuNTI5OCAzNi45NDggMTQuNTg5NCAzNi45ODE0IDE0LjY1MzNaTTM5LjI3MDUgMTQuNDc1NkMzOS44MzAxIDE1LjE4MjEgNDAuMTg2MyAxNS44MDA0IDQwLjQxMzEgMTYuMjU0OUg0MS44MzVDNDEuNzM2NyAxNS42NjU2IDQxLjIyOTIgMTQuOTkzNiA0MC43NzY0IDE0LjQ3NTZIMzkuMjcwNVpNNDMuOTIyOSAxNS4wMDQ5SDQyLjc2NjZWMTUuOTk2MUg1My4xMjVWMTUuMDA0OUg1MS45Njg4VjEyLjQ3NTZINDMuOTIyOVYxNS4wMDQ5Wk0xMC43MDQxIDQuMDMwMjdDMTAuNTgxMSAzLjk1OTU4IDEwLjQ4MDUgNC4wMTc4IDEwLjQ4MDUgNC4xNTkxOFY5LjYyMzA1QzEwLjQ4MDYgOS42OTA3NCAxMC41MDc4IDkuNzU1NzggMTAuNTU1NyA5LjgwMzcxQzEwLjYwMzcgOS44NTE3MSAxMC42NjkzIDkuODc4ODcgMTAuNzM3MyA5Ljg3ODkxSDEyLjQ2NDhDMTIuNDk4NiA5Ljg3OTA1IDEyLjUzMjIgOS44NzIxNyAxMi41NjM1IDkuODU5MzhDMTIuNTk0NCA5Ljg0NjY2IDEyLjYyMjcgOS44MjgyMSAxMi42NDY1IDkuODA0NjlDMTIuNjcwNCA5Ljc4MDg5IDEyLjY5MDIgOS43NTE4NSAxMi43MDMxIDkuNzIwN0MxMi43MTYgOS42ODk3NSAxMi43MjI2IDkuNjU2NTQgMTIuNzIyNyA5LjYyMzA1VjguMTUyMzRDMTIuNzIyNyA4LjAxMSAxMi44MjIzIDcuOTUyODIgMTIuOTQ1MyA4LjAyMzQ0TDE0Ljc0MTIgOS4wNjE1MkMxNC44MDYgOS4xMDM2MiAxNC44NTk3IDkuMTYwNzcgMTQuODk4NCA5LjIyNzU0QzE0LjkzNzEgOS4yOTQzIDE0Ljk1OTYgOS4zNjkyOSAxNC45NjM5IDkuNDQ2MjlWMTUuMjU5OEMxNC45NjQxIDE1LjQwMDcgMTUuMDYzNyAxNS40NTcgMTUuMTg2NSAxNS4zODc3TDE2Ljk4NDQgMTQuMzUwNkMxNy4wNDkgMTQuMzA4NyAxNy4xMDMgMTQuMjUyMSAxNy4xNDE2IDE0LjE4NTVDMTcuMTgwMyAxNC4xMTg3IDE3LjIwMyAxNC4wNDMgMTcuMjA3IDEzLjk2NThWOC4wMjQ0MUMxNy4yMDI5IDcuOTQ3MzYgMTcuMTgwMyA3Ljg3MjQ2IDE3LjE0MTYgNy44MDU2NkMxNy4xMDI5IDcuNzM4ODQgMTcuMDQ5MyA3LjY4MTY0IDE2Ljk4NDQgNy42Mzk2NUwxMS44MjMyIDQuNjY3OTdDMTEuNzAwMiA0LjU5NzI4IDExLjU5NzcgNC41NDEwMiAxMS41OTc3IDQuNTQxMDJDMTEuNTg0NiA0LjUzMDQ3IDExLjQ4NzkgNC40ODIxMyAxMS4zNzIxIDQuNDE1MDRMMTAuNzA0MSA0LjAzMDI3Wk00Ni4yNDcxIDE1LjAwNDlINDUuMDkwOFYxMy4zMzY5SDQ2LjI0NzFWMTUuMDA0OVpNNDguNTI0NCAxNS4wMDQ5SDQ3LjM3OTlWMTMuMzM2OUg0OC41MjQ0VjE1LjAwNDlaTTUwLjgzNTkgMTUuMDA0OUg0OS42NTcyVjEzLjMzNjlINTAuODM1OVYxNS4wMDQ5Wk0zMi4wNjE1IDEwLjM2NTJIMzUuODAwOFYxMC45ODI0SDMxLjk4NjNWMTIuMDkwOEgzNS44MDA4VjEyLjc1NDlIMzEuMjUxVjEzLjgyNzFINDEuNzY1NlYxMi43NTQ5SDM3LjI2MjdWMTIuMDkwOEg0MS4wMjkzVjEwLjk4MjRIMzcuMjYyN1YxMC4zNjUySDM5Ljg1ODRDNDAuNDYzNCAxMC4zNjUyIDQwLjk1NCA5Ljg3NTQzIDQwLjk1NDEgOS4yNzE0OFY2LjAxNjZIMzIuMDYxNVYxMC4zNjUyWk0yMS4yNDQxIDguMzAzNzFDMjAuOTY4NiA5LjU3MTM4IDIwLjcxMzcgMTAuNTAxIDIwLjQ4MDUgMTEuMDkzOEMyMC4yNDcyIDExLjY4NjMgMTkuODEyNiAxMi41MDg2IDE5LjE3NDggMTMuNTYyNUwxOS4xMTUyIDEzLjY2MTFIMjAuNTc5MUwyMC41OTg2IDEzLjYzMzhDMjEuMzE2NiAxMi42MTg4IDIxLjgwNzUgMTEuNzYwNCAyMi4wNjc0IDExLjA1OTZDMjIuMzI1NyAxMC4zNjI4IDIyLjU4MzUgOS40NTMxMSAyMi44NDA4IDguMzMyMDNMMjIuODU4NCA4LjI1MjkzSDIxLjI1NDlMMjEuMjQ0MSA4LjMwMzcxWk0yNy4xOTA0IDguNjk4MjRDMjcuNDE5MiA5LjY1Mjc1IDI3LjY0ODMgMTAuNDQwMiAyNy44Nzc5IDExLjA1OTZDMjguMTM3OCAxMS43NjAzIDI4LjYyNzggMTIuNjE4OSAyOS4zNDU3IDEzLjYzMzhMMjkuMzY1MiAxMy42NjExSDMwLjgyOTFMMzAuNjE0MyAxMy4zMDQ3QzMwLjA2MDQgMTIuMzczNiAyOS42Nzc2IDExLjYzNjggMjkuNDYzOSAxMS4wOTM4QzI5LjIzMDYgMTAuNTAxIDI4Ljk3NTggOS41NzEzOCAyOC43MDAyIDguMzAzNzFMMjguNjg5NSA4LjI1MjkzSDI3LjA4NTlMMjcuMTkwNCA4LjY5ODI0Wk00NC4zNTQ1IDExLjg5MjZINTAuNDc2NkM1MS4wODE1IDExLjg5MjUgNTEuNTcyMSAxMS40MDI3IDUxLjU3MjMgMTAuNzk4OFY5LjM1MDU5SDQ0LjM1NDVWMTEuODkyNlpNNTAuNDI3NyAxMC40MDE0QzUwLjQyNzUgMTAuNzAzMiA1MC4xODIzIDEwLjk0ODIgNDkuODc5OSAxMC45NDgySDQ1LjQ5OVYxMC4yODMySDUwLjQyNzdWMTAuNDAxNFpNMzUuODAwOCA5LjI1NzgxSDMzLjI1MjlWNi45NDgyNEgzNS44MDA4VjkuMjU3ODFaTTM5Ljc2MzcgOC43MTA5NEMzOS43NjM1IDkuMDEyNjYgMzkuNTE4MSA5LjI1NzYgMzkuMjE1OCA5LjI1NzgxSDM3LjI2MjdWNi45NDgyNEgzOS43NjM3VjguNzEwOTRaTTQ3LjQ1NDEgNS41ODU5NEM0Ni4yMTQ0IDYuOTI4NCA0NC41Mzc1IDcuODYyNTcgNDIuNjQ5NCA4LjE2NDA2VjkuMDczMjRDNDMuNDc4NiA4Ljk1Mjc3IDQ0LjY1ODcgOC43NTU5OCA0NS4zNzExIDguNDA2MjVWOC43NDMxNkg1MC41NDM5VjguNDE3OTdDNTEuMTk3OCA4Ljc0NDM0IDUyLjQxMjIgOC45NDExMSA1My4yNzY0IDkuMDczMjRMNTMuMjc3MyA4LjE5NjI5QzUzLjI0OCA4LjE4Njc5IDUzLjIxODYgOC4xNzc1MiA1My4xODk1IDguMTY3OTdDNTEuMzA2IDcuODcyNjcgNDkuNjMxNiA2Ljk0OCA0OC4zODk2IDUuNjE2MjFMNDcuNDU0MSA1LjU4NTk0Wk0zMy42OTkyIDcuMTY3OTdDMzMuODU5OCA4LjIyNTk3IDM0LjQ2NTQgOS4wMjk4NiAzNC40Nzc1IDkuMDQ1OUgzNS40NTEyQzM1LjQ0NDIgOS4wMzEwOCAzNC45MzE2IDcuOTM5OTcgMzQuOTMxNiA3LjE2Nzk3SDMzLjY5OTJaTTM4LjExMTMgNy4xNjc5N0MzOC4xMTEzIDcuOTM3OCAzNy42MDE2IDkuMDI1MTEgMzcuNTkxOCA5LjA0NTlIMzguNTY1NEMzOC41ODE1IDkuMDI0NjUgMzkuMTgzNyA4LjIyMjQ0IDM5LjM0MzggNy4xNjc5N0gzOC4xMTEzWk00Ny45NjM5IDYuNjExMzNDNDguMzI1OSA3LjA0MjU0IDQ4Ljg3NDggNy40NzQwNiA0OS42MTA0IDcuOTA1MjdINDYuMjkzQzQ3LjA1MjEgNy40NjIyNSA0Ny42MDE4IDcuMDMxMDMgNDcuOTYzOSA2LjYxMTMzWiIgZmlsbD0id2hpdGUiLz4KPC9zdmc+Cg==",e_="data:image/svg+xml;base64,PHN2ZyBwcmVzZXJ2ZUFzcGVjdFJhdGlvPSJub25lIiBvdmVyZmxvdz0idmlzaWJsZSIgc3R5bGU9ImRpc3BsYXk6IGJsb2NrOyIgd2lkdGg9IjEyIiBoZWlnaHQ9IjEyIiB2aWV3Qm94PSIwIDAgMTIgMTIiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxnIGlkPSIxLWNvbW1vbl9zZWFyY2hfbGluZV8yNHgyNCI+CjxnIGlkPSJ1bmlvbiI+CjxwYXRoIGZpbGwtcnVsZT0iZXZlbm9kZCIgY2xpcC1ydWxlPSJldmVub2RkIiBkPSJNNS44NjAxMyAxLjkyNTAxQzMuNzI4NzkgMS45MjUwMSAyLjAwMDAyIDMuNjU0NiAyLjAwMDAyIDUuNzg5MzdDMi4wMDAwMiA3LjkyNDEzIDMuNzI4NzkgOS42NTM3MiA1Ljg2MDEzIDkuNjUzNzJDNy45OTE0NyA5LjY1MzcyIDkuNzIwMjQgNy45MjQxMyA5LjcyMDI0IDUuNzg5MzdDOS43MjAyNCAzLjY1NDYgNy45OTE0NyAxLjkyNTAxIDUuODYwMTMgMS45MjUwMVpNMC44MDAwMjQgNS43ODkzN0MwLjgwMDAyNCAyLjk5Mjk0IDMuMDY0OTcgMC43MjUwMTIgNS44NjAxMyAwLjcyNTAxMkM4LjY1NTI5IDAuNzI1MDEyIDEwLjkyMDIgMi45OTI5NCAxMC45MjAyIDUuNzg5MzdDMTAuOTIwMiA4LjU4NTggOC42NTUyOSAxMC44NTM3IDUuODYwMTMgMTAuODUzN0MzLjA2NDk3IDEwLjg1MzcgMC44MDAwMjQgOC41ODU4IDAuODAwMDI0IDUuNzg5MzdaIiBmaWxsPSJ3aGl0ZSIvPgo8cGF0aCBmaWxsLXJ1bGU9ImV2ZW5vZGQiIGNsaXAtcnVsZT0iZXZlbm9kZCIgZD0iTTkuMDEzMTkgOC45MzQ5N0M5LjI0NzQgOC43MDA1NCA5LjYyNzExIDguNzAwNTQgOS44NjEzMiA4LjkzNDk3TDExLjA1MDggMTAuMTI1NkMxMS4yODUgMTAuMzYgMTEuMjg1IDEwLjc0MDEgMTEuMDUwOCAxMC45NzQ1QzEwLjgxNjYgMTEuMjA4OSAxMC40MzY5IDExLjIwODkgMTAuMjAyNyAxMC45NzQ1TDkuMDEzMTkgOS43ODM5QzguNzc4OTkgOS41NDk0OCA4Ljc3ODk5IDkuMTY5NCA5LjAxMzE5IDguOTM0OTdaIiBmaWxsPSJ3aGl0ZSIvPgo8L2c+CjwvZz4KPC9zdmc+Cg==",t_="data:image/svg+xml;base64,PHN2ZyBwcmVzZXJ2ZUFzcGVjdFJhdGlvPSJub25lIiBvdmVyZmxvdz0idmlzaWJsZSIgc3R5bGU9ImRpc3BsYXk6IGJsb2NrOyIgd2lkdGg9IjY3IiBoZWlnaHQ9IjIyIiB2aWV3Qm94PSIwIDAgNjcgMjIiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxwYXRoIGlkPSJTdWJ0cmFjdCIgZD0iTTY2IDBDNjYuMzM3MiAwIDY2LjY3MDYgMC4wMTcxODM4IDY3IDAuMDQ2ODc1QzYxLjM5MzYgMC41NTIxODkgNTcgNS4yNjIwMiA1NyAxMUM1NyAxNi43MzggNjEuMzkzNiAyMS40NDY4IDY3IDIxLjk1MjFDNjYuNjcwNiAyMS45ODE4IDY2LjMzNzIgMjIgNjYgMjJIMTFDNC45MjQ4NyAyMiAwIDE3LjA3NTEgMCAxMUMwIDQuOTI0ODcgNC45MjQ4NyAyLjY1NzU2ZS0wNyAxMSAwSDY2Wk04LjI0MzE2IDYuNzM1MzVDOC4yNDMxNiA2LjU5Mzk3IDguMTQyNTggNi41MzU3NiA4LjAxOTUzIDYuNjA2NDVMNi4yMjI2NiA3LjY0MDYyQzYuMTU3ODcgNy42ODIyOCA2LjEwNDE2IDcuNzM5MTcgNi4wNjU0MyA3LjgwNTY2QzYuMDI2NzIgNy44NzIyNyA2LjAwNDEgNy45NDc1MiA2IDguMDI0NDFWMTMuOTY1OEM2LjAwMzcxIDE0LjA0MzQgNi4wMjU4NSAxNC4xMTkxIDYuMDY0NDUgMTQuMTg2NUM2LjEwMzE5IDE0LjI1NCA2LjE1NzQgMTQuMzEyIDYuMjIyNjYgMTQuMzU0NUw5Ljg3MTA5IDE2LjQ1OEM5Ljk5MzQ2IDE2LjUyNzIgMTAuMDkzNiAxNi41ODQyIDEwLjA5NDcgMTYuNTg1OUMxMC4wOTQ3IDE2LjU4NzEgMTAuMTkzNCAxNi42NDUxIDEwLjMxNjQgMTYuNzE1OEwxMi41MDEgMTcuOTY5N0MxMi42MjI4IDE4LjA0MDMgMTIuNzIzNiAxNy45ODIyIDEyLjcyMzYgMTcuODQwOFYxMi4zNjcyQzEyLjcyMyAxMi4yOTk0IDEyLjY5NTcgMTIuMjM0MyAxMi42NDc1IDEyLjE4NjVDMTIuNTk5MiAxMi4xMzg4IDEyLjUzMzggMTIuMTEyMyAxMi40NjU4IDEyLjExMjNIMTAuNzM3M0MxMC42NzAyIDEyLjExMzIgMTAuNjA1OSAxMi4xMzk5IDEwLjU1ODYgMTIuMTg3NUMxMC41MTEzIDEyLjIzNTIgMTAuNDg0NyAxMi4zMDAxIDEwLjQ4NDQgMTIuMzY3MlYxMy44Mzc5QzEwLjQ4NDIgMTMuOTc4OSAxMC4zODQ2IDE0LjAzNjQgMTAuMjYxNyAxMy45NjU4TDguNDY0ODQgMTIuOTM1NUM4LjQwMDI2IDEyLjg5MzUgOC4zNDYxNCAxMi44MzcyIDguMzA3NjIgMTIuNzcwNUM4LjI2OTE5IDEyLjcwNCA4LjI0NzM1IDEyLjYyOTQgOC4yNDMxNiAxMi41NTI3VjYuNzM1MzVaTTI0LjMzNCAxNC4zOTI2QzI0LjMzMzkgMTQuOTk4NSAyNC4yMDU1IDE1LjE4NDYgMjMuNTk4NiAxNS4xOTYzTDIyLjMwMTggMTUuMjU0OUwyMi42NjUgMTYuMjU0OUgyNS4wODY5QzI1LjY3MDUgMTYuMDg0IDI1Ljg3MjEgMTUuNzE5NCAyNS44NzIxIDE0LjgyMzJWNS43ODIyM0wyNC4zMzQgNS43MjM2M1YxNC4zOTI2Wk0zMi4yODIyIDE0LjQ3NTZDMzEuOTQ2IDE1LjA0OTIgMzEuNDY1OSAxNS43NTcxIDMxLjA5OTYgMTYuMjU0OUgzMi42MTkxQzMzLjA2NzMgMTUuNTIxMiAzMy4zNzUxIDE0LjkyOCAzMy41NDg4IDE0LjQ3NTZIMzIuMjgyMlpNMzQuODEwNSAxNS4zOTc1QzM0Ljg3OTEgMTUuNzEwMSAzNC45MzExIDE1Ljk5ODIgMzQuOTczNiAxNi4yNTQ5SDM2LjE4NjVMMzYuMTgxNiAxNi4yMzU0QzM2LjA2NjIgMTUuNzM4OCAzNS44OTg5IDE1LjAxOCAzNS43NDEyIDE0LjQ3NTZIMzQuNTI5M0wzNC44MTA1IDE1LjM5NzVaTTM2Ljk4MTQgMTQuNjUzM0MzNy4wOTg0IDE0Ljg3NyAzNy4yNDExIDE1LjE1MDEgMzcuMzMzIDE1LjQwMjNMMzcuNjM1NyAxNi4yNTQ5SDM5LjA4MDFDMzkuMDMzNiAxNS44MzI1IDM4LjU5NCAxNS4wNTUzIDM4LjIzODMgMTQuNDc1NkgzNi44ODg3QzM2LjkxNjEgMTQuNTI5OCAzNi45NDggMTQuNTg5NCAzNi45ODE0IDE0LjY1MzNaTTM5LjI3MDUgMTQuNDc1NkMzOS44MzAxIDE1LjE4MjEgNDAuMTg2MyAxNS44MDA0IDQwLjQxMzEgMTYuMjU0OUg0MS44MzVDNDEuNzM2NyAxNS42NjU2IDQxLjIyOTIgMTQuOTkzNiA0MC43NzY0IDE0LjQ3NTZIMzkuMjcwNVpNNDMuOTIyOSAxNS4wMDQ5SDQyLjc2NjZWMTUuOTk2MUg1My4xMjVWMTUuMDA0OUg1MS45Njg4VjEyLjQ3NTZINDMuOTIyOVYxNS4wMDQ5Wk0xMC43MDQxIDQuMDMwMjdDMTAuNTgxMSAzLjk1OTU4IDEwLjQ4MDUgNC4wMTc4IDEwLjQ4MDUgNC4xNTkxOFY5LjYyMzA1QzEwLjQ4MDYgOS42OTA3NCAxMC41MDc4IDkuNzU1NzggMTAuNTU1NyA5LjgwMzcxQzEwLjYwMzcgOS44NTE3MSAxMC42NjkzIDkuODc4ODcgMTAuNzM3MyA5Ljg3ODkxSDEyLjQ2NDhDMTIuNDk4NiA5Ljg3OTA1IDEyLjUzMjIgOS44NzIxNyAxMi41NjM1IDkuODU5MzhDMTIuNTk0NCA5Ljg0NjY2IDEyLjYyMjcgOS44MjgyMSAxMi42NDY1IDkuODA0NjlDMTIuNjcwNCA5Ljc4MDg5IDEyLjY5MDIgOS43NTE4NSAxMi43MDMxIDkuNzIwN0MxMi43MTYgOS42ODk3NSAxMi43MjI2IDkuNjU2NTQgMTIuNzIyNyA5LjYyMzA1VjguMTUyMzRDMTIuNzIyNyA4LjAxMSAxMi44MjIzIDcuOTUyODIgMTIuOTQ1MyA4LjAyMzQ0TDE0Ljc0MTIgOS4wNjE1MkMxNC44MDYgOS4xMDM2MiAxNC44NTk3IDkuMTYwNzcgMTQuODk4NCA5LjIyNzU0QzE0LjkzNzEgOS4yOTQzIDE0Ljk1OTYgOS4zNjkyOSAxNC45NjM5IDkuNDQ2MjlWMTUuMjU5OEMxNC45NjQxIDE1LjQwMDcgMTUuMDYzNyAxNS40NTcgMTUuMTg2NSAxNS4zODc3TDE2Ljk4NDQgMTQuMzUwNkMxNy4wNDkgMTQuMzA4NyAxNy4xMDMgMTQuMjUyMSAxNy4xNDE2IDE0LjE4NTVDMTcuMTgwMyAxNC4xMTg3IDE3LjIwMyAxNC4wNDMgMTcuMjA3IDEzLjk2NThWOC4wMjQ0MUMxNy4yMDI5IDcuOTQ3MzYgMTcuMTgwMyA3Ljg3MjQ2IDE3LjE0MTYgNy44MDU2NkMxNy4xMDI5IDcuNzM4ODQgMTcuMDQ5MyA3LjY4MTY0IDE2Ljk4NDQgNy42Mzk2NUwxMS44MjMyIDQuNjY3OTdDMTEuNzAwMiA0LjU5NzI4IDExLjU5NzcgNC41NDEwMiAxMS41OTc3IDQuNTQxMDJDMTEuNTg0NiA0LjUzMDQ3IDExLjQ4NzkgNC40ODIxMyAxMS4zNzIxIDQuNDE1MDRMMTAuNzA0MSA0LjAzMDI3Wk00Ni4yNDcxIDE1LjAwNDlINDUuMDkwOFYxMy4zMzY5SDQ2LjI0NzFWMTUuMDA0OVpNNDguNTI0NCAxNS4wMDQ5SDQ3LjM3OTlWMTMuMzM2OUg0OC41MjQ0VjE1LjAwNDlaTTUwLjgzNTkgMTUuMDA0OUg0OS42NTcyVjEzLjMzNjlINTAuODM1OVYxNS4wMDQ5Wk0zMi4wNjE1IDEwLjM2NTJIMzUuODAwOFYxMC45ODI0SDMxLjk4NjNWMTIuMDkwOEgzNS44MDA4VjEyLjc1NDlIMzEuMjUxVjEzLjgyNzFINDEuNzY1NlYxMi43NTQ5SDM3LjI2MjdWMTIuMDkwOEg0MS4wMjkzVjEwLjk4MjRIMzcuMjYyN1YxMC4zNjUySDM5Ljg1ODRDNDAuNDYzNCAxMC4zNjUyIDQwLjk1NCA5Ljg3NTQzIDQwLjk1NDEgOS4yNzE0OFY2LjAxNjZIMzIuMDYxNVYxMC4zNjUyWk0yMS4yNDQxIDguMzAzNzFDMjAuOTY4NiA5LjU3MTM4IDIwLjcxMzcgMTAuNTAxIDIwLjQ4MDUgMTEuMDkzOEMyMC4yNDcyIDExLjY4NjMgMTkuODEyNiAxMi41MDg2IDE5LjE3NDggMTMuNTYyNUwxOS4xMTUyIDEzLjY2MTFIMjAuNTc5MUwyMC41OTg2IDEzLjYzMzhDMjEuMzE2NiAxMi42MTg4IDIxLjgwNzUgMTEuNzYwNCAyMi4wNjc0IDExLjA1OTZDMjIuMzI1NyAxMC4zNjI4IDIyLjU4MzUgOS40NTMxMSAyMi44NDA4IDguMzMyMDNMMjIuODU4NCA4LjI1MjkzSDIxLjI1NDlMMjEuMjQ0MSA4LjMwMzcxWk0yNy4xOTA0IDguNjk4MjRDMjcuNDE5MiA5LjY1Mjc1IDI3LjY0ODMgMTAuNDQwMiAyNy44Nzc5IDExLjA1OTZDMjguMTM3OCAxMS43NjAzIDI4LjYyNzggMTIuNjE4OSAyOS4zNDU3IDEzLjYzMzhMMjkuMzY1MiAxMy42NjExSDMwLjgyOTFMMzAuNjE0MyAxMy4zMDQ3QzMwLjA2MDQgMTIuMzczNiAyOS42Nzc2IDExLjYzNjggMjkuNDYzOSAxMS4wOTM4QzI5LjIzMDYgMTAuNTAxIDI4Ljk3NTggOS41NzEzOCAyOC43MDAyIDguMzAzNzFMMjguNjg5NSA4LjI1MjkzSDI3LjA4NTlMMjcuMTkwNCA4LjY5ODI0Wk00NC4zNTQ1IDExLjg5MjZINTAuNDc2NkM1MS4wODE1IDExLjg5MjUgNTEuNTcyMSAxMS40MDI3IDUxLjU3MjMgMTAuNzk4OFY5LjM1MDU5SDQ0LjM1NDVWMTEuODkyNlpNNTAuNDI3NyAxMC40MDE0QzUwLjQyNzUgMTAuNzAzMiA1MC4xODIzIDEwLjk0ODIgNDkuODc5OSAxMC45NDgySDQ1LjQ5OVYxMC4yODMySDUwLjQyNzdWMTAuNDAxNFpNMzUuODAwOCA5LjI1NzgxSDMzLjI1MjlWNi45NDgyNEgzNS44MDA4VjkuMjU3ODFaTTM5Ljc2MzcgOC43MTA5NEMzOS43NjM1IDkuMDEyNjYgMzkuNTE4MSA5LjI1NzYgMzkuMjE1OCA5LjI1NzgxSDM3LjI2MjdWNi45NDgyNEgzOS43NjM3VjguNzEwOTRaTTQ3LjQ1NDEgNS41ODU5NEM0Ni4yMTQ0IDYuOTI4NCA0NC41Mzc1IDcuODYyNTcgNDIuNjQ5NCA4LjE2NDA2VjkuMDczMjRDNDMuNDc4NiA4Ljk1Mjc3IDQ0LjY1ODcgOC43NTU5OCA0NS4zNzExIDguNDA2MjVWOC43NDMxNkg1MC41NDM5VjguNDE3OTdDNTEuMTk3OCA4Ljc0NDM0IDUyLjQxMjIgOC45NDExMSA1My4yNzY0IDkuMDczMjRMNTMuMjc3MyA4LjE5NjI5QzUzLjI0OCA4LjE4Njc5IDUzLjIxODYgOC4xNzc1MiA1My4xODk1IDguMTY3OTdDNTEuMzA2IDcuODcyNjcgNDkuNjMxNiA2Ljk0OCA0OC4zODk2IDUuNjE2MjFMNDcuNDU0MSA1LjU4NTk0Wk0zMy42OTkyIDcuMTY3OTdDMzMuODU5OCA4LjIyNTk3IDM0LjQ2NTQgOS4wMjk4NiAzNC40Nzc1IDkuMDQ1OUgzNS40NTEyQzM1LjQ0NDIgOS4wMzEwOCAzNC45MzE2IDcuOTM5OTcgMzQuOTMxNiA3LjE2Nzk3SDMzLjY5OTJaTTM4LjExMTMgNy4xNjc5N0MzOC4xMTEzIDcuOTM3OCAzNy42MDE2IDkuMDI1MTEgMzcuNTkxOCA5LjA0NTlIMzguNTY1NEMzOC41ODE1IDkuMDI0NjUgMzkuMTgzNyA4LjIyMjQ0IDM5LjM0MzggNy4xNjc5N0gzOC4xMTEzWk00Ny45NjM5IDYuNjExMzNDNDguMzI1OSA3LjA0MjU0IDQ4Ljg3NDggNy40NzQwNiA0OS42MTA0IDcuOTA1MjdINDYuMjkzQzQ3LjA1MjEgNy40NjIyNSA0Ny42MDE4IDcuMDMxMDMgNDcuOTYzOSA2LjYxMTMzWiIgZmlsbD0iYmxhY2siLz4KPC9zdmc+Cg==",r_="data:image/svg+xml;base64,PHN2ZyBwcmVzZXJ2ZUFzcGVjdFJhdGlvPSJub25lIiBvdmVyZmxvdz0idmlzaWJsZSIgc3R5bGU9ImRpc3BsYXk6IGJsb2NrOyIgd2lkdGg9IjEyIiBoZWlnaHQ9IjEyIiB2aWV3Qm94PSIwIDAgMTIgMTIiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxnIGlkPSIxLWNvbW1vbl9zZWFyY2hfbGluZV8yNHgyNCI+CjxnIGlkPSJ1bmlvbiI+CjxwYXRoIGZpbGwtcnVsZT0iZXZlbm9kZCIgY2xpcC1ydWxlPSJldmVub2RkIiBkPSJNNS44NjAxMyAxLjkyNTAxQzMuNzI4NzkgMS45MjUwMSAyLjAwMDAyIDMuNjU0NiAyLjAwMDAyIDUuNzg5MzdDMi4wMDAwMiA3LjkyNDEzIDMuNzI4NzkgOS42NTM3MiA1Ljg2MDEzIDkuNjUzNzJDNy45OTE0NyA5LjY1MzcyIDkuNzIwMjQgNy45MjQxMyA5LjcyMDI0IDUuNzg5MzdDOS43MjAyNCAzLjY1NDYgNy45OTE0NyAxLjkyNTAxIDUuODYwMTMgMS45MjUwMVpNMC44MDAwMjQgNS43ODkzN0MwLjgwMDAyNCAyLjk5Mjk0IDMuMDY0OTcgMC43MjUwMTIgNS44NjAxMyAwLjcyNTAxMkM4LjY1NTI5IDAuNzI1MDEyIDEwLjkyMDIgMi45OTI5NCAxMC45MjAyIDUuNzg5MzdDMTAuOTIwMiA4LjU4NTggOC42NTUyOSAxMC44NTM3IDUuODYwMTMgMTAuODUzN0MzLjA2NDk3IDEwLjg1MzcgMC44MDAwMjQgOC41ODU4IDAuODAwMDI0IDUuNzg5MzdaIiBmaWxsPSJibGFjayIvPgo8cGF0aCBmaWxsLXJ1bGU9ImV2ZW5vZGQiIGNsaXAtcnVsZT0iZXZlbm9kZCIgZD0iTTkuMDEzMTkgOC45MzQ5N0M5LjI0NzQgOC43MDA1NCA5LjYyNzExIDguNzAwNTQgOS44NjEzMiA4LjkzNDk3TDExLjA1MDggMTAuMTI1NkMxMS4yODUgMTAuMzYgMTEuMjg1IDEwLjc0MDEgMTEuMDUwOCAxMC45NzQ1QzEwLjgxNjYgMTEuMjA4OSAxMC40MzY5IDExLjIwODkgMTAuMjAyNyAxMC45NzQ1TDkuMDEzMTkgOS43ODM5QzguNzc4OTkgOS41NDk0OCA4Ljc3ODk5IDkuMTY5NCA5LjAxMzE5IDguOTM0OTdaIiBmaWxsPSJibGFjayIvPgo8L2c+CjwvZz4KPC9zdmc+Cg==";async function n_(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?t_:JA,l.style.cssText="width:67px;height:22px;flex-shrink:0;margin-right:-11px;";const p=e.createElement("div");p.style.cssText=`display:flex;align-items:center;gap:2px;min-width:0;height:22px;box-sizing:border-box;border:1.5px solid ${c};border-radius:11px;padding:0 7px 0 6px;`;const m=e.createElement("img");m.src=a?r_:e_,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 w=e.createElement("div");w.textContent="小黑盒工坊小程序",w.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;`,p.append(m,E),f.append(l,p),u.append(f,w),s.append(u),e.body.append(s);const I=()=>{s.remove(),n.removeEventListener("abort",I)};n.addEventListener("abort",I,{once:!0});try{return await fe(()=>Promise.all([l.decode(),m.decode()]),n),await fe(()=>new Promise(v=>{let y=o.requestAnimationFrame(()=>{y=o.requestAnimationFrame(()=>{n.removeEventListener("abort",O),v()})});const O=()=>o.cancelAnimationFrame(y);n.addEventListener("abort",O,{once:!0})}),n),I}catch(v){throw I(),v}}const i_=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"]),o_=new Set(["url","inline","eval","unknown"]),s_=/^\/(?:\:segment(?:\/\:segment)*)?$/,a_=/^[a-f0-9]{64}$/,c_=255,d_=160,u_=256;function l_(e,t){const r=e;if(!r||typeof r.sdkVersion!="string"||r.sdkVersion!==t||typeof r.effectiveDirective!="string"||!i_.has(r.effectiveDirective)||typeof r.violatedDirective!="string"||r.violatedDirective.length>u_||r.violatedDirective.split(/\s/,1)[0]!==r.effectiveDirective||!["enforce","report"].includes(r.disposition??"")||typeof r.blockedResourceType!="string"||!o_.has(r.blockedResourceType)||typeof r.timestamp!="number"||!Number.isFinite(r.timestamp)||r.timestamp<0)return;const n=f_(r.blockedOrigin);if(r.blockedOrigin!==void 0&&!n)return;const i=r.redactedPathname;if(i!==void 0&&(typeof i!="string"||i.length>d_||!s_.test(i)))return;const o=r.sanitizedPathnameHash;if(!(o!==void 0&&(typeof o!="string"||!a_.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 f_(e){if(e!==void 0&&!(typeof e!="string"||e.length>c_))try{const t=new URL(e);return["http:","https:"].includes(t.protocol)&&t.origin===e?t.origin:void 0}catch{return}}const Po=["android","ios","ohos","windows","macos","linux"],h_="0.9.0",m_=Object.freeze(["android","ios","ohos","windows","macos"]),of="该小程序暂不支持当前平台",g_="PLATFORM_UNSUPPORTED";function p_(e){return typeof e=="string"&&Po.includes(e)}function y_(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 E_(e){const t=e.manifest;if(!D_(t))return{status:"invalid",reason:"manifest_not_object"};if(!Object.prototype.hasOwnProperty.call(t,"platforms")){const n=Ud(e.sdkVersion)??Ud(t.sdkVersion);return A_(n)?{status:"invalid",reason:"platforms_missing_after_hard_cutover"}:I_()}const r=sf(t.platforms);return"reason"in r?{status:"invalid",reason:r.reason}:{status:"resolved",declaredPlatforms:r.platforms,effectivePlatforms:r.platforms,platformsDeclared:!0,policy:"explicit"}}function w_(e){const t=y_(e.operatingSystemName);if(!t)return yr("host_operating_system_unknown");const r=e.platformAccess;if(!r)return yr("platform_access_missing",{platform:t});if(r.source==="compatibility-window")return{status:"allowed",platform:t,effectivePlatforms:Po,platformsDeclared:!1,policy:"legacy_mobile_default",compatibility:r.reason};if(r.source==="manifest"){const s=E_({manifest:r.manifest,...r.sdkVersion===void 0?{}:{sdkVersion:r.sdkVersion}});return s.status==="invalid"?yr("platform_declaration_invalid",{invalidReason:s.reason,platform:t}):xd(t,s)}if(r.effectivePlatforms===void 0)return yr("platform_declaration_invalid",{invalidReason:"effective_platforms_missing",platform:t});const n=sf(r.effectivePlatforms);if("reason"in n)return yr("platform_declaration_invalid",{invalidReason:n.reason,platform:t});const i=typeof r.platformsDeclared=="boolean"?r.platformsDeclared:!0,o=__(r.platformPolicy)?r.platformPolicy:i?"explicit":"legacy_mobile_default";return xd(t,{declaredPlatforms:i?n.platforms:[],effectivePlatforms:n.platforms,platformsDeclared:i,policy:o})}function xd(e,t){return t.effectivePlatforms.includes(e)?{status:"allowed",platform:e,effectivePlatforms:t.effectivePlatforms,platformsDeclared:t.platformsDeclared,policy:t.policy}:yr("platform_not_supported",{effectivePlatforms:t.effectivePlatforms,platform:e})}function yr(e,t={}){return{status:"denied",reason:e,message:of,...t}}function I_(){return{status:"resolved",declaredPlatforms:[],effectivePlatforms:m_,platformsDeclared:!1,policy:"legacy_mobile_default"}}function sf(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(!p_(r))return{reason:"platform_unknown_value"};if(t.has(r))return{reason:"platform_duplicate_value"};t.add(r)}return{platforms:Object.freeze(Po.filter(r=>t.has(r)))}}function A_(e){if(typeof e!="string"||!e.trim())return!1;const t=ba(e.trim(),h_);return t!==void 0&&t>=0}function Ud(e){return typeof e=="string"&&e.trim()?e.trim():void 0}function __(e){return e==="explicit"||e==="legacy_mobile_default"}function D_(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function N_(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:M_(i.pathname),sanitizedPathnameHash:pa(i.pathname)}}catch{return{type:"security_violation",errorCode:e,timestamp:n,sdkVersion:r}}}function M_(e){return(e==="/"?e:e.replace(/\/+$/,"")).split("/").map(r=>r?":segment":"").join("/")}const b_=1e4,S_=1e4,is=2e3,T_=2,v_="open-with-native-credential-policy",af="安全提示",cf="即将打开未经验证的开发网页。该页面可能由本机或局域网服务提供,请确认来源可信后继续。";class O_{nonce=yc();runtimeId=yc();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=$u(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??b_,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:(B_(),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=tp(t.runtimePermissions),this.firstParty=t.firstParty===!0,this.networkPolicy=this.firstParty?void 0:Qu(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 Ug(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=Vp(t.sdkVersionPolicy);const n=WA(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=w_({operatingSystemName:t.environmentInfo?.operatingSystem?.name,...t.platformAccess===void 0?{}:{platformAccess:t.platformAccess}}),this.platformGateDecision.status==="denied")throw $_(this.platformGateDecision);if(this.miniProgramDetail=Q_(t),this.effectiveCapabilities=Gu(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),U_(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(z_(i)),this.launchUrl=i,this.options.onDevDocumentReload&&t.sdkVersionPolicy?.releaseChannel==="development"){const s=qu(new URL(i),this.locationBasePath);this.devDocumentDisposer=ep({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=Qg(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=ya(s);this.trace({runtimeId:this.runtimeId,timestamp:Date.now(),type:"error",method:rr,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[rr])&&this.bridgeServer?.postEvent(n,i)}};this.capabilityGraph=FA({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)=>xg(this.iframe,n,i),prepareScreenshot:(n,i,o)=>{const s=this.sdkVersionDecision?.sdkVersion;return!s||(ba(s,"0.9.1")??-1)<0?Promise.resolve(()=>{}):n_(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=UA({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 sp({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 x_(t)?t:df(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 $g(t,r,{allowPrivateNetwork:Cd(r)||jd(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??F_)({message:cf,title:af,url:t}):!0}async shouldConfirmDevMiniProgramLaunch(t){if(wc(t)==="production")return!1;const r=this.options.environment.getCurrentHref();return!Cd(r)&&!jd(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{zd(),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(()=>zd())}async isDevRuntime(){return this.devRuntimePromise??=Promise.resolve().then(()=>this.options.environment.isDevRuntime()).then(Boolean).catch(()=>!1),this.devRuntimePromise}applyIframeDefaults(){this.iframe.setAttribute("allow",Fg),this.iframe.setAttribute("referrerpolicy",Bg),this.iframe.setAttribute("sandbox",Yu)}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{Gp(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>=T_)){this.failRuntime(we("HEARTBEAT_TIMEOUT","小程序 SDK 心跳超时"));return}const t=`${Date.now().toString(36)}_${++this.probeSequence}`;this.pendingProbeId=t,this.bridgeServer?.postInternalRequest(Un,t,{probeId:t,timestamp:Date.now()}),this.heartbeatTimer=setTimeout(()=>{this.heartbeatTimer=void 0,this.sendLocationProbe()},is),this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"location_probe",method:Un})}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(Un,t,{probeId:t,timestamp:Date.now()}),this.trace({runtimeId:this.nonce,timestamp:Date.now(),type:"location_probe",method:Un})}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?S_:is))}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()},is)),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===Dh){this.handleCspViolation(t.payload);return}if(t.method!==_h)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"||!Wu(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=l_(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=N_(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:Hg,launchUrlType:wc(t),networkPolicy:v_})}failRuntime(t){const r=R_(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,k_(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 R_(e){const t=ya(e);return ao(e)&&"cause"in e&&df(t,e.cause),t}function df(e,t){return Object.defineProperty(e,"cause",{configurable:!0,enumerable:!1,value:t}),e}function k_(e){return{code:e.code,message:e.message,...e.data!==void 0?{data:e.data}:{},...e.cause!==void 0?{cause:C_(e.cause)}:{}}}const os=(()=>{const e=Object.getOwnPropertyDescriptor(new Error,"stack")?.get,t=Object.getOwnPropertyDescriptor(new Error,"stack")?.get;return typeof e=="function"&&e===t?e:void 0})(),P_=new Set([Error.prototype,TypeError.prototype,RangeError.prototype,ReferenceError.prototype,SyntaxError.prototype,URIError.prototype,EvalError.prototype]);function L_(e,t){const r=Object.getOwnPropertyDescriptor(e,t);if(!r)return;if("value"in r)return r.value;if(t!=="stack"||!os||r.get!==os)return;const n=Object.getPrototypeOf(e);if(P_.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 os.call(e)}}function C_(e){if(!(!e||typeof e!="object"))try{const t={};for(const r of["name","message","stack"]){const n=L_(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 x_(e){return ao(e)&&typeof e.code=="string"&&typeof e.message=="string"}function ao(e){return!!e&&typeof e=="object"}function ot(e,t){try{e?.(t)}catch{}}function U_(e,t,r){try{e?.(t,r)}catch{}}function jd(e){try{const t=new URL(e);return t.protocol==="http:"&&QA(t.hostname)}catch{return!1}}function j_(e){try{return new URL(e).origin}catch{return}}function z_(e){return Vg()?"*":j_(e)}function H_(e){return`${af}
|
|
6
|
-
|
|
7
|
-
${cf}
|
|
8
|
-
|
|
9
|
-
URL: ${e}`}function F_(e){return typeof window>"u"||typeof window.confirm!="function"?!1:window.confirm(H_(e.url))}function zd(){typeof window<"u"&&typeof window.close=="function"&&window.close()}function B_(){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:mu,knownMethodCount:xt.length,supportsFileCreate:xt.some(i=>i.method===gn),system:V_(e?.userAgent,e?.platform),userAgent:e?.userAgent??"",platform:e?.platform??"",language:e?.language??"",hardwareConcurrency:pr(e?.hardwareConcurrency),maxTouchPoints:pr(e?.maxTouchPoints),screen:{width:pr(t?.width),height:pr(t?.height)},viewport:{width:pr(r?.innerWidth),height:pr(r?.innerHeight),devicePixelRatio:G_(r?.devicePixelRatio)}});console.info("[hb-sdk-runtime] environment",n)}function V_(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 pr(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0?Math.floor(e):0}function G_(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:1}function $_(e){return we(g_,of,{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 Q_(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 q_(e){if(!ao(e?.ports)||Array.isArray(e.ports))throw new TypeError("createMiniProgramRuntime 必须显式提供 ports");if(!ao(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 O_(e)}function Y_(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",p),l=m=>{u||(u=!0,f(),c(m))},p=()=>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",p,{once:!0}),n.signal.aborted&&p()});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 p=()=>{try{d.abort()}catch{}m(),c(new DOMException("账号标识读取已取消","AbortError"))};n.signal.addEventListener("abort",p,{once:!0});const m=()=>n.signal.removeEventListener("abort",p);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 w=o.getRandomValues(new Uint8Array(32));l=`ak_${Array.from(w,I=>I.toString(16).padStart(2,"0")).join("")}`,u.put(l,f)}}catch{d.abort()}}})}finally{s.close()}}}const W_=/^(?: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,Z_=new Set(["origin","referer","user-agent"]);function K_(e,t){return hg({mode:"request-only",request:(r,n={signal:t.signal})=>t.run(n.signal,async i=>{const o={...n,signal:i},s=X_(r),a=await e.authenticatedRequest(s,o);return tD(a)})}).network}function X_(e){const t=J_(e.headers);return{...e,target:{...e.target},...e.params===void 0?{}:{params:{...e.params}},...t===void 0?{headers:void 0}:{headers:t}}}function J_(e){if(e!==void 0)return Object.fromEntries(Object.entries(e).filter(([t])=>!eD(t)))}function eD(e){const t=e.trim().toLowerCase();return Z_.has(t)}function tD(e){return{status:e.status,...e.statusText===void 0?{}:{statusText:e.statusText},data:e.data,headers:rD(e.headers)??{}}}function rD(e){if(e!==void 0)return Object.fromEntries(Object.entries(e).filter(([t])=>!nD(t)))}function nD(e){const t=e.trim().toLowerCase();return W_.test(t)||t.startsWith("x-heybox-")||t.startsWith("x-xhh-")}function iD(e,t,r){const n=dD(e.presentation,t);return{account:aD(e,t,r),network:K_(e,t),...e.storage===void 0?{}:{storage:cD(e,t)},...e.storage===void 0?{}:oD(e,t),...n===void 0?{}:{presentation:n},...e.protocol===void 0?{}:{protocol:e.protocol}}}function oD(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 sD(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 aD(e,t,r){const n=e.account.getAccountKey?.bind(e.account)??Y_();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 cD(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 dD(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)=>Mg(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 uD(){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 Yn(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 Yn(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(Yn(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 Yn(f.reason);return u}finally{for(const{listener:u,source:f}of c)f.removeEventListener("abort",u)}}}}function Yn(e){return new DOMException("Web Host operation aborted","AbortError")}async function lD(e){const t=uD(),r=new Set;let n=!1;const i=l=>{if(n||t.signal.aborted)return ss(l),()=>{};let p=!0;const m=()=>{p&&(p=!1,r.delete(m),ss(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 p of[...r])p();e.onDispose&&ss(e.onDispose)}};e.signal.addEventListener("abort",o,{once:!0}),e.signal.aborted&&s(e.signal.reason);const a=iD(e,t,i);a.storage?.getRaw&&a.storage.setRaw&&(a.scopedStorage=Ql({storage:a.storage,diagnostics:a.storageDiagnostics,coordinationKey:e.storage.storage,lock:ql,resolveScope:async()=>$l((await f()).configuration)}));const c=$u(a,{hostCapabilities:e.hostCapabilities,hasUserDataPresentation:e.userDataPresentation!==void 0,hasUserDataSettings:e.userDataPresentation?.openDataPermissions!==void 0}),d=sD(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:fD(e.authPresentation,t)},...e.userDataPresentation===void 0?{}:{userDataPresentation:hD(e.userDataPresentation,t)},hostCapabilities:c.effectiveCapabilities,dispose:s}}function ss(e){try{e()}catch{}}function fD(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 hD(e,t){return{...e.openDataPermissions?{openDataPermissions:r=>t.run(r.signal,n=>e.openDataPermissions({...r,signal:n}))}:{},confirmDataPermission:r=>t.run(r.signal,n=>e.confirmDataPermission({...r,signal:n}))}}function mD(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 Hd(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 Hd(c,t).catch(()=>{})}}).catch(i),o.catch(()=>{}),o}async function Hd(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 as=8*1024*1024,gD=new Set(["content-length","content-type","content-encoding","transfer-encoding","content-disposition","content-range"]),pD="/__hb_sdk__/game-save-download",Ge=(e,t)=>({code:e,message:t});function yD(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=mD({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 w=d(m);try{return await(await c()).getFileHandle(w)}catch(I){throw I instanceof DOMException&&I.name==="NotFoundError"?Ge("FILE_NOT_FOUND","存档缓存不存在"):I}}function f(m){const E={kind:"file",mode:"readwrite",name:m.split("/").at(-1),async create(w,I){a(I);const v=d(m),y=await c();if(w.exclusive)try{throw await y.getFileHandle(v),Ge("FILE_ALREADY_EXISTS","存档缓存已存在")}catch(O){if(!(O instanceof DOMException&&O.name==="NotFoundError"))throw O}a(I),await y.getFileHandle(v,{create:!0}),a(I)},async remove(w){a(w);const I=d(m);if(i)try{await(await i).removeEntry(I)}catch(v){if(!(v instanceof DOMException&&v.name==="NotFoundError"))throw v}},async read(w){const I=await(await u(m,w)).getFile();if(I.size>as)throw Ge("FILE_TOO_LARGE","存档文件超过 8 MiB");const v=new Uint8Array(await I.arrayBuffer());try{return a(w),v}catch(y){throw v.fill(0),y}},async write(){throw Ge("FILE_ACCESS_DENIED","存档缓存仅允许受控下载写入")},async stat(w){const I=await(await u(m,w)).getFile();return a(w),{kind:"file",size:I.size,modifiedAt:I.lastModified}}};return o.set(E,m),E}const l=async()=>{throw Ge("FILE_ACCESS_DENIED","浏览器仅开放存档私有缓存")},p={kind:"directory",mode:"readwrite",name:"",file:f,directory(m){return{...p,name:m,async create(E,w){if(a(w),m!==".hb-game-saves")return l();await c(),a(w)}}},create:l,stat:l,list:l};return{files:{sandbox:p},transfer:{network:{async open(m,E){if(a(E),!Hu(m))throw Ge("METHOD_FORBIDDEN","仅支持受控存档下载");const w=await(e.fetch??fetch)(pD,{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(!w.ok){const I=await w.json().catch(()=>({}));throw Ge(I.code==="FILE_TOO_LARGE"?"FILE_TOO_LARGE":"DOWNLOAD_NETWORK_FAILED","存档下载失败")}return s.add(w),{status:w.status,headers:Object.fromEntries(Array.from(w.headers).filter(([I])=>gD.has(I)).map(([I,v])=>[I,[v]])),body:w}},async release(m){s.delete(m),await m.body?.cancel()}},files:{async writeResource(m,E,w,I){let v,y;try{a(I);const O=o.get(m);if(!O||!s.delete(E))throw Ge("FILE_ACCESS_DENIED","下载资源不属于当前存档会话");if(w.mode!=="replace-existing")throw Ge("FILE_ACCESS_DENIED","存档下载目标必须先创建");if(v=await(await u(O,I)).createWritable(),!E.body)throw Ge("DOWNLOAD_NETWORK_FAILED","存档下载没有响应内容");y=E.body.getReader();let b=0;for(;;){a(I);const T=await y.read().catch(D=>{throw a(I),Ge(D instanceof DOMException&&D.name==="TimeoutError"?"DOWNLOAD_TIMEOUT":"DOWNLOAD_NETWORK_FAILED","存档下载流中断")});if(a(I),T.done)break;if(b+=T.value.byteLength,b>Math.min(w.maxBytes??as,as))throw Ge("FILE_TOO_LARGE","存档文件超过 8 MiB");await v.write(new Uint8Array(T.value)),I.onProgress(b)}if(w.expectedBytes!==void 0&&b!==w.expectedBytes)throw Ge("DOWNLOAD_NETWORK_FAILED","存档下载长度不匹配");return a(I),await v.close(),v=void 0,{committedBytes:b}}catch(O){throw O instanceof DOMException&&O.name==="QuotaExceededError"?Ge("FILE_QUOTA_EXCEEDED","浏览器存储空间不足"):O}finally{await y?.cancel().catch(()=>{}),y||await E.body?.cancel().catch(()=>{}),await v?.abort().catch(()=>{}),s.delete(E)}}}}}}function pt(e,t){throw{code:e,message:t}}function Xr(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 ED(e){return{declaredPermissions:e.declaredPermissions??{},platforms:[...e.platforms??[]].sort(),runtimePermissions:e.runtimePermissions,networkPolicy:e.networkPolicy}}function wD(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(),pt("UNAUTHORIZED","请先通过 hb-sdk login 登录小黑盒"));const{signed:c,browser:d}=a,u=jm(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(),pt("INVALID_STATE","开发启动授权尚未就绪,请检查 CLI 登录、项目绑定及开发票据状态"));let f;try{f=ju({...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||Xr(d.runtimePermissions)!==Xr(c.runtimePermissions)||Xr(d.networkPolicy)!==Xr(c.networkPolicy))&&(i(),pt("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:Xr([a.userId,a.accountRevision,l,d.contextRevision,ED(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 w=E&&typeof E=="object"&&"code"in E?String(E.code):"";if(["SESSION_UNAUTHENTICATED","SESSION_INVALIDATED","UNAUTHORIZED"].includes(w)&&pt("UNAUTHORIZED","小黑盒登录已失效,请重新登录"),["REQUEST_CANCELLED","REQUEST_TIMEOUT"].includes(w)||E instanceof DOMException&&["AbortError","TimeoutError"].includes(E.name))throw E;pt("REQUEST_FAILED","获取开发运行授权失败,请稍后重试")}d.throwIfAborted(),await e.refreshAccount(d),d.throwIfAborted(),o().key!==a.key&&pt("AUTHORIZATION_CONTEXT_CHANGED","账号或开发快照已变化,请重试");const f=u.data;(u.status===401||f?.status==="login"||f?.status==="relogin")&&pt("UNAUTHORIZED","小黑盒登录已失效,请重新登录"),(u.status!==200||f?.status!=="ok")&&pt("REQUEST_FAILED","获取开发运行授权失败,请检查开发资格后重试");const l=f.result,p=Number(l?.expires_at)*1e3;(typeof l?.token!="string"||!l.token.trim()||!Number.isSafeInteger(l?.expires_at)||!Number.isSafeInteger(p)||p<=t()||!["legacy","local","server"].includes(String(l.user_data_mode)))&&pt("INVALID_RESPONSE","开发运行授权响应无效");const m={token:l.token,expiresAt:Math.min(p,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,p=s(d,{...a,signal:AbortSignal.any([l.signal,e.signal])});u={promise:p,controller:l,users:0},n.set(d.key,u);const m=u;p.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((p,m)=>{f=()=>m(c.reason),c.addEventListener("abort",f,{once:!0}),c.aborted&&f()})]);return c.throwIfAborted(),o().key!==d.key&&pt("AUTHORIZATION_CONTEXT_CHANGED","账号或开发快照已变化,请重试"),l}finally{c.removeEventListener("abort",f),--u.users===0&&u.controller.abort()}}}}const ID="/__hb_sdk__/dev-context";function Fd(e,t){return Mn(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:Mn(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 sn(e,t=Date.now()){if(e.localDevGrant===void 0)return e;const r=Su(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:Yh({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 AD(e){if(!Mn(e)||!Bd(e,["networkRequest"]))return;const t=e.networkRequest;if(!(!Mn(t)||!Bd(t,["status","useOfficialDomain"]))&&!(t.status!=="enabled"&&t.status!=="disabled")&&typeof t.useOfficialDomain=="boolean")return{networkRequest:{status:t.status,useOfficialDomain:t.useOfficialDomain}}}const _D={networkRequest:{status:"disabled",useOfficialDomain:!1}};function Lo(e){const t=Qe(e.localDevGrant?ga({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}}:ND()}function uf(e,t,r){return r?.localDevGrant?ga({declaredPermissions:r.declaredPermissions??{},runtimePermissions:e,localDevGrant:r.localDevGrant}).runtimePermissions:lf(e,t,t.networkRequest.useOfficialDomain)}function DD(e){if(e.source!=="remote")return{schema_version:1,entries:[]};const t=Lo({...e,localDevGrant:void 0});return lf(e.runtimePermissions,t,!1)}function ND(){return{networkRequest:{..._D.networkRequest}}}function lf(e,t,r){const n=Qe(e);if(!n.valid)return{schema_version:1,entries:[]};const i=[];for(const s of or){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=Mn(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 Mn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&Object.getPrototypeOf(e)===Object.prototype}function Bd(e,t){return Object.keys(e).length===t.length&&t.every(n=>Object.hasOwn(e,n))}function MD(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 bD(e){return MD({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 SD(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 cs=new WeakMap;function La(e){return new Promise((t,r)=>{if(e.signal?.aborted){r(e.signal.reason);return}const{root:n,signal:i}=e;cs.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 w=cs.get(n)??null;for(;w instanceof HTMLElement&&!w.isConnected;){const I=w.closest("[data-host-dialog]");w=I?cs.get(I)??null:null}w instanceof HTMLElement&&(!E||E.contains(w))?w.focus():E?.querySelector("button")?.focus()}},d=Ff({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],w=o.at(-1);m.shiftKey&&document.activeElement===E?(m.preventDefault(),w.focus()):!m.shiftKey&&document.activeElement===w&&(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 p=s();p&&(p.inert=!0,p.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("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}const Vd="hb-sdk-action-dialog-style";async function Co(e){await ff(e)}async function TD(e){return await ff({title:"关注作者",detail:"是否关注当前小程序的作者?",signal:e.signal,method:"user.requestFollowAuthor",mode:"browser",confirmation:!0})?"confirmed":"cancelled"}async function ff(e){PD();const t=document.createElement("div");return t.className="hb-sdk-action-dialog",t.innerHTML=`
|
|
10
|
-
<div class="hb-sdk-action-dialog__panel">
|
|
11
|
-
<h2>${et(e.title)}</h2>
|
|
12
|
-
<pre class="hb-sdk-action-dialog__detail">${et(e.detail)}</pre>
|
|
13
|
-
<div class="hb-sdk-action-dialog__actions">
|
|
14
|
-
${e.confirmation?'<button type="button" data-action="cancel">取消</button>':""}
|
|
15
|
-
<button type="button" class="primary" data-action="confirm">${e.confirmation?"关注":"确定"}</button>
|
|
16
|
-
</div>
|
|
17
|
-
</div>`,await La({root:t,title:e.title,method:e.method??"host.action",signal:e.signal,callId:e.callId,mode:e.mode,...e.confirmation?{cancelAction:"cancel"}:{}})==="confirm"}async function vD(e,t){await Co({method:"navigation.openAppPage",title:"打开页面",detail:["protocolType: "+e.protocolType,"path: "+e.path,"params: "+Rr(e.params)].join(`
|
|
18
|
-
`),signal:t.signal,callId:t.requestId})}async function OD(e,t){await Co({method:"navigation.openAppPage",title:"打开小程序",detail:["miniProgramId: "+e.miniProgramId,"extra: "+Rr(e.extra)].join(`
|
|
19
|
-
`),signal:t.signal,callId:t.requestId})}async function RD(e,t){await Co({method:"share.showShareMenu",title:"分享",detail:["title: "+e.title,"description: "+e.description,"url: "+e.url,"channel: "+Rr(e.channel),"post: "+Rr(e.post)].join(`
|
|
20
|
-
`),signal:t.signal,callId:t.requestId})}async function kD(e,t){await Co({method:"share.screenshot",title:"截图分享",detail:["rect: "+Rr(e.rect),"post: "+Rr(e.post)].join(`
|
|
21
|
-
`),signal:t.signal,callId:t.requestId})}function Rr(e){return JSON.stringify(e,null,2)}function PD(){if(document.getElementById(Vd))return;const e=document.createElement("style");e.id=Vd,e.textContent=`
|
|
22
|
-
.hb-sdk-action-dialog {
|
|
23
|
-
position: absolute;
|
|
24
|
-
inset: 0;
|
|
25
|
-
display: grid;
|
|
26
|
-
place-items: center;
|
|
27
|
-
padding: 24px;
|
|
28
|
-
background: rgba(15, 23, 42, 0.45);
|
|
29
|
-
}
|
|
30
|
-
|
|
31
|
-
.hb-sdk-action-dialog__panel {
|
|
32
|
-
width: min(420px, 100%);
|
|
33
|
-
border-radius: 12px;
|
|
34
|
-
padding: 20px;
|
|
35
|
-
background: #fff;
|
|
36
|
-
box-shadow: 0 20px 45px rgba(15, 23, 42, 0.2);
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
.hb-sdk-action-dialog__panel h2 {
|
|
40
|
-
margin: 0 0 8px;
|
|
41
|
-
font-size: 18px;
|
|
42
|
-
}
|
|
43
|
-
|
|
44
|
-
.hb-sdk-action-dialog__detail {
|
|
45
|
-
margin: 0 0 16px;
|
|
46
|
-
max-height: 40vh;
|
|
47
|
-
overflow: auto;
|
|
48
|
-
color: #1f2933;
|
|
49
|
-
font-family: inherit;
|
|
50
|
-
font-size: 12px;
|
|
51
|
-
line-height: 1.6;
|
|
52
|
-
white-space: pre-wrap;
|
|
53
|
-
overflow-wrap: anywhere;
|
|
54
|
-
word-break: break-word;
|
|
55
|
-
}
|
|
56
|
-
|
|
57
|
-
.hb-sdk-action-dialog__actions {
|
|
58
|
-
display: flex;
|
|
59
|
-
justify-content: flex-end;
|
|
60
|
-
gap: 8px;
|
|
61
|
-
}
|
|
62
|
-
|
|
63
|
-
.hb-sdk-action-dialog__actions button {
|
|
64
|
-
min-height: 36px;
|
|
65
|
-
border: 1px solid #cad5e2;
|
|
66
|
-
border-radius: 6px;
|
|
67
|
-
padding: 0 12px;
|
|
68
|
-
background: #fff;
|
|
69
|
-
cursor: pointer;
|
|
70
|
-
}
|
|
71
|
-
|
|
72
|
-
.hb-sdk-action-dialog__actions .primary {
|
|
73
|
-
border-color: #2563eb;
|
|
74
|
-
color: #fff;
|
|
75
|
-
background: #2563eb;
|
|
76
|
-
}
|
|
77
|
-
`,document.head.appendChild(e)}const LD={identity:"小程序身份",profile:"昵称和头像",steam_account:"Steam 账号"};async function CD(e){const t=document.createElement("div");return t.className="hb-sdk-auth-dialog",t.innerHTML=`
|
|
78
|
-
<div class="hb-sdk-auth-dialog__panel">
|
|
79
|
-
<h2>授权请求</h2>
|
|
80
|
-
<p class="hb-sdk-auth-dialog__app">${et(e.miniProgram?.name||"当前小程序")} 申请访问:</p>
|
|
81
|
-
<ul class="hb-sdk-auth-dialog__scopes">${e.scopes.map(n=>`<li>${et(LD[n]||n)}</li>`).join("")}</ul>
|
|
82
|
-
${e.userProfile?.nickname?`<p class="hb-sdk-auth-dialog__profile">当前账号:${et(e.userProfile.nickname)}</p>`:""}
|
|
83
|
-
<div class="hb-sdk-auth-dialog__actions">
|
|
84
|
-
<button type="button" data-action="deny">拒绝</button>
|
|
85
|
-
<button type="button" class="primary" data-action="allow">允许</button>
|
|
86
|
-
</div>
|
|
87
|
-
</div>
|
|
88
|
-
`,await La({root:t,title:"授权请求",method:"auth.authorize",mode:"browser",signal:e.signal,cancelAction:"deny"})==="allow"?{status:"granted",grantedScopes:[...e.scopes]}:{status:"cancelled"}}function xD(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:Qa,releaseChannel:"development"},runtimePermissions:e.runtimePermissions,networkPolicy:e.networkPolicy,firstParty:e.firstParty===!0,...e.anonymousStorageScope?{anonymousStorageScope:e.anonymousStorageScope}:{},platformAccess:{source:"manifest",manifest:{platforms:Po},sdkVersion:Qa},environmentInfo:{appVersion:null,operatingSystem:{name:e.operatingSystem??"unknown",version:null}},...e.miniProgramId?{canonicalIdentity:{miniProgramId:e.miniProgramId}}:{}}}const Gd="hb-sdk-user-data-dialog-style",UD=new Map(er.map(e=>[e.key,e.name]));function jD(e){return(Rt(e)?UD.get(e):void 0)??"游戏资料"}function zD(e){return e==="upload"?"可上传":"无网络权限"}async function HD(e){BD();const t=e.miniProgramName?.trim()||"当前小程序",r=jD(e.resource),n=`“${t}”想读取你的${r}`,i=zD(e.egress),o=ig[e.egress],s=e.egress==="upload"?"↑":"⊘",a=document.createElement("div");a.className="hb-sdk-user-data-dialog",a.innerHTML=`
|
|
89
|
-
<div class="hb-sdk-user-data-dialog__panel">
|
|
90
|
-
<h2>${et(n)}</h2>
|
|
91
|
-
<dl class="hb-sdk-user-data-dialog__meta">
|
|
92
|
-
<dt>范围</dt><dd>${et(e.scopeText)}</dd>
|
|
93
|
-
<dt>用途</dt><dd>${et(e.purposeText)}</dd>
|
|
94
|
-
</dl>
|
|
95
|
-
<p class="hb-sdk-user-data-dialog__egress" data-egress="${et(e.egress)}">
|
|
96
|
-
<span class="hb-sdk-user-data-dialog__egress-label" aria-hidden="true">${et(s)}</span>
|
|
97
|
-
<span class="hb-sdk-user-data-dialog__egress-tag">${et(i)}</span>
|
|
98
|
-
<span>${et(o)}</span>
|
|
99
|
-
</p>
|
|
100
|
-
<p class="hb-sdk-user-data-dialog__browser-note">读取当前登录黑盒账号的真实资料。许可仅适用于本浏览器,不会同步到手机或其他客户端;来源登录需另行完成。</p>
|
|
101
|
-
<div class="hb-sdk-user-data-dialog__actions">
|
|
102
|
-
<button type="button" data-action="deny">拒绝</button>
|
|
103
|
-
<button type="button" data-action="session">本次使用允许</button>
|
|
104
|
-
${e.canPersist===!1?"":'<button type="button" class="primary" data-action="persistent">在此浏览器上始终允许</button>'}
|
|
105
|
-
</div>
|
|
106
|
-
</div>
|
|
107
|
-
`;const c=await La({root:a,title:n,method:"user.dataPermission.confirm",mode:"browser",signal:e.signal,cancelAction:"cancelled"});return{decision:FD(c)}}function FD(e){return e==="deny"||e==="session"||e==="persistent"?e:"cancelled"}function BD(){if(document.getElementById(Gd))return;const e=document.createElement("style");e.id=Gd,e.textContent=`
|
|
108
|
-
.hb-sdk-user-data-dialog {
|
|
109
|
-
position: absolute;
|
|
110
|
-
inset: 0;
|
|
111
|
-
display: grid;
|
|
112
|
-
place-items: center;
|
|
113
|
-
padding: 24px;
|
|
114
|
-
background: rgba(15, 23, 42, 0.45);
|
|
115
|
-
}
|
|
116
|
-
|
|
117
|
-
.hb-sdk-user-data-dialog__panel {
|
|
118
|
-
width: min(440px, 100%);
|
|
119
|
-
border-radius: 12px;
|
|
120
|
-
padding: 20px;
|
|
121
|
-
background: #fff;
|
|
122
|
-
box-shadow: 0 20px 45px rgba(15, 23, 42, 0.2);
|
|
123
|
-
}
|
|
124
|
-
|
|
125
|
-
.hb-sdk-user-data-dialog__panel h2 {
|
|
126
|
-
margin: 0 0 12px;
|
|
127
|
-
font-size: 17px;
|
|
128
|
-
line-height: 1.45;
|
|
129
|
-
color: #1f2933;
|
|
130
|
-
overflow-wrap: anywhere;
|
|
131
|
-
}
|
|
132
|
-
|
|
133
|
-
.hb-sdk-user-data-dialog__meta {
|
|
134
|
-
display: grid;
|
|
135
|
-
grid-template-columns: auto 1fr;
|
|
136
|
-
gap: 4px 10px;
|
|
137
|
-
margin: 0 0 12px;
|
|
138
|
-
font-size: 12px;
|
|
139
|
-
line-height: 1.6;
|
|
140
|
-
}
|
|
141
|
-
|
|
142
|
-
.hb-sdk-user-data-dialog__meta dt {
|
|
143
|
-
color: #7b8794;
|
|
144
|
-
white-space: nowrap;
|
|
145
|
-
}
|
|
146
|
-
|
|
147
|
-
.hb-sdk-user-data-dialog__meta dd {
|
|
148
|
-
white-space: pre-wrap;
|
|
149
|
-
margin: 0;
|
|
150
|
-
color: #1f2933;
|
|
151
|
-
overflow-wrap: anywhere;
|
|
152
|
-
}
|
|
153
|
-
|
|
154
|
-
.hb-sdk-user-data-dialog__egress {
|
|
155
|
-
display: flex;
|
|
156
|
-
flex-wrap: wrap;
|
|
157
|
-
align-items: baseline;
|
|
158
|
-
gap: 6px;
|
|
159
|
-
margin: 0 0 10px;
|
|
160
|
-
padding: 10px 12px;
|
|
161
|
-
border: 1px solid #cad5e2;
|
|
162
|
-
border-radius: 8px;
|
|
163
|
-
font-size: 12px;
|
|
164
|
-
line-height: 1.6;
|
|
165
|
-
color: #1f2933;
|
|
166
|
-
}
|
|
167
|
-
|
|
168
|
-
.hb-sdk-user-data-dialog__egress[data-egress="upload"] {
|
|
169
|
-
border-color: #e0b34d;
|
|
170
|
-
background: #fff8e6;
|
|
171
|
-
}
|
|
172
|
-
|
|
173
|
-
.hb-sdk-user-data-dialog__egress[data-egress="no_network"] {
|
|
174
|
-
border-color: #9fb3c8;
|
|
175
|
-
background: #f2f6fa;
|
|
176
|
-
}
|
|
177
|
-
|
|
178
|
-
.hb-sdk-user-data-dialog__egress-label {
|
|
179
|
-
font-weight: 700;
|
|
180
|
-
}
|
|
181
|
-
|
|
182
|
-
.hb-sdk-user-data-dialog__egress-tag {
|
|
183
|
-
font-weight: 700;
|
|
184
|
-
white-space: nowrap;
|
|
185
|
-
}
|
|
186
|
-
|
|
187
|
-
.hb-sdk-user-data-dialog__browser-note {
|
|
188
|
-
margin: 0 0 16px;
|
|
189
|
-
font-size: 11px;
|
|
190
|
-
line-height: 1.6;
|
|
191
|
-
color: #7b8794;
|
|
192
|
-
}
|
|
193
|
-
|
|
194
|
-
.hb-sdk-user-data-dialog__actions {
|
|
195
|
-
display: flex;
|
|
196
|
-
flex-wrap: wrap;
|
|
197
|
-
justify-content: flex-end;
|
|
198
|
-
gap: 8px;
|
|
199
|
-
}
|
|
200
|
-
|
|
201
|
-
.hb-sdk-user-data-dialog__actions button {
|
|
202
|
-
min-height: 36px;
|
|
203
|
-
border: 1px solid #cad5e2;
|
|
204
|
-
border-radius: 6px;
|
|
205
|
-
padding: 0 12px;
|
|
206
|
-
background: #fff;
|
|
207
|
-
color: #1f2933;
|
|
208
|
-
cursor: pointer;
|
|
209
|
-
}
|
|
210
|
-
|
|
211
|
-
.hb-sdk-user-data-dialog__actions .primary {
|
|
212
|
-
border-color: #2563eb;
|
|
213
|
-
color: #fff;
|
|
214
|
-
background: #2563eb;
|
|
215
|
-
}
|
|
216
|
-
`,document.head.appendChild(e)}function VD(e){let t,r,n,i,o,s=0,a=0,c=0,d=!1,u=Promise.resolve();const f=new Set,l=()=>{const I=e.resolveScope();return I?JSON.stringify(I):void 0},p=()=>{if(!d)for(const I of f)I()},m=async()=>{if(d||c)return;const I=t,v=l(),y=++s;if(!I||!v){r=void 0,i=void 0,p();return}try{const O=await I.getSnapshot();if(d||y!==s||t!==I||v!==l())return;r=O,n=v,i=void 0}catch(O){if(d||y!==s||t!==I||v!==l())return;r=void 0,o=v,i=O instanceof Error?O.message:"许可状态不可用"}p()},E=I=>{const v=t,y=l(),O=a;if(d||!v||!y)return Promise.resolve();const j=++s;c++;const b=u.then(async()=>{if(!(d||a!==O||y!==l()))try{const T=await I(v);if(d||j!==s||a!==O||y!==l())return;r=T,n=y,i=void 0}catch(T){if(d||j!==s||a!==O||y!==l())return;r=void 0,o=y,i=T instanceof Error?T.message:"许可设置失败"}}).finally(()=>{a===O&&c--,p()});return u=b,b},w=()=>{a++,s++,c=0,u=Promise.resolve(),t=void 0,r=void 0,i=void 0};return{snapshot(){const I=l(),v=I&&I===n?r:void 0,y=e.declared?.();return{scenario:"unknown",dataScenario:"unknown",egressTier:e.egressTier(),declaredSource:y?.source??"manifest",permissionStateReady:v!==void 0,stateError:I&&I===o?i:void 0,simulatedSession:[],resources:er.map(O=>{const j=v?.resources.find(T=>T.resource===O.key),b=j?.allowed===!0;return{resource:O.key,name:O.name,declared:y?.resources.includes(O.key)??!1,decision:j?.decision??"ask",revision:j?.revision??0,sessionAllowed:j?.sessionAllowed??!1,sessionSimulated:!1,licensed:b,...b?{sourceStatus:"unknown"}:{}}})}},subscribe(I){return d||f.add(I),()=>f.delete(I)},bind(I){d||(w(),t=I,m())},refresh:m,revokeSession:()=>E(I=>I.revokeSession()),resetAll:()=>E(I=>I.resetAll()),clearSession(){w(),p()},dispose(){d=!0,w(),f.clear()}}}function GD(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 $D(e){const t=Qe(e.runtimePermissions);let r={};return t.valid&&t.permissions.user_game_data?.status==="enabled"?r=_n(t.permissions.user_game_data.config.resources):e.runtimePermissions===void 0&&e.declaredPermissions?.user_game_data?.enabled&&(r=_n(e.declaredPermissions.user_game_data.resources)),{resources:$h(r),source:"manifest"}}const QD=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"]}),qD="host.userDataTelemetry",$d=80;function YD(e){return{method:qD,detail:{...e.payload,eventName:e.name,message:WD(e)}}}function WD(e){const t=QD[e.name]??[],r=[];for(const n of t){const i=e.payload[n];i!==void 0&&r.push(`${n}: ${hf(i)}`)}return[e.name,...r].join(" · ")}function hf(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=>hf(r)).join(",");else try{t=JSON.stringify(e)??""}catch{t="[无法序列化]"}return t.length>$d?`${t.slice(0,$d)}…`:t}const ZD=44;function KD(e){const t=()=>e.isCapsuleHidden?.()?0:ZD,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:Qf,showLoading:$f,hideLoading:Gf,vibrate:Vf,openAppPage:vD,openWindow:OD,showShareMenu:RD,captureAndShare:kD,setScreenshotChromeHidden:Bf}}const Qd=["launch-only","stdio","full","prepare-fail","prepare-cancel","launch-cancel","os-blocked","normal-exit","crash","output-limit"],Wn=[{phase:"downloading",loaded:4,total:12},{phase:"verifying",processed:8,total:12},{phase:"extracting",processed:12,total:12}],qd={"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 XD{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]:[...Qd];for(const n of r){const i=this.preparations.get(n);for(const o of i?.operation?.timers??[])this.clearSchedule(o);i?.operation?.reject(ze("COMPANION_PREPARATION_CANCELLED","固定 Fake 已重置")),this.preparations.delete(n),this.sessions.delete(n)}this.diagnostic("reset",t)}getInfo(t){const r=this.readAlias(t);return{alias:r,displayName:`Browser Fake: ${r}`,target:r==="os-blocked"?"macos-arm64":"windows-x64",capabilities:qd[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:Wn[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:Wn[0]},operation:c};this.preparations.set(n,d),this.diagnostic("prepare.started",n),Wn.forEach((u,f)=>{const l=this.schedule(()=>{if(c.timers.delete(l),!c.cancelled){d.status={state:"preparing",progress:u};try{c.listeners.forEach(p=>p(u))}catch(p){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:p instanceof Error?p.message:String(p)}),c.reject(p);return}if(this.diagnostic("prepare.progress",n,{phase:u.phase}),f===Wn.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(ze("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(ze("COMPANION_PREPARATION_CANCELLED","准备已取消")),n.operation=void 0,n.status={state:"not-prepared"},this.diagnostic("prepare.cancelled",r)}}getActiveSession(t){const r=this.readAlias(t),n=this.sessions.get(r);if(!n||n.exited)return;const i=n.snapshot.controllerGeneration;return n.snapshot={...n.snapshot,controllerGeneration:i+1},this.emit(bh,{sessionId:n.snapshot.id,controllerGeneration:i}),n.waitingOutput&&(n.queuedOutput.unshift(n.waitingOutput),n.waitingOutput=void 0,this.flushOutput(n)),this.diagnostic("session.controller-transferred",r,{controllerGeneration:n.snapshot.controllerGeneration}),{...n.snapshot,capabilities:[...n.snapshot.capabilities]}}launch(t){const r=this.readAlias(t);if(this.getPreparationStatus(r).state!=="ready")throw ze("COMPANION_NOT_PREPARED","固定 Fake 尚未准备完成");if(r==="os-blocked")throw ze("COMPANION_OS_BLOCKED","操作系统安全策略已阻止启动");const n=this.sessions.get(r);if(n&&!n.exited)throw ze("COMPANION_LAUNCH_FAILED","固定 Fake Session 已在运行");const i={id:`browser-fake-${++this.nextSessionId}`,alias:r,target:this.getInfo(r).target,capabilities:qd[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
|
|
217
|
-
`),this.queueOutput(o,"stderr",1,`fake:diagnostic
|
|
218
|
-
`)},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 ze("COMPANION_PIPE_CLOSED","stdio 未启用");if(r.stdinClosed)throw ze("COMPANION_PIPE_CLOSED","stdin 已关闭");const n=Math.max(1,...r.queuedOutput.map(i=>i.sequence),r.waitingOutput?.sequence??0)+1;this.queueOutput(r,"stdout",n,new Uint8Array(t.data)),this.diagnostic("stdio.write",r.snapshot.alias,{bytes:t.data.byteLength})}closeStdin(t){const r=this.readController(t);r.stdinClosed=!0,this.diagnostic("stdio.closed",r.snapshot.alias)}terminate(t){const r=this.readController(t);this.exit(r,{reason:"terminated"})}ackOutput(t){const r=this.readController(t),n=r.waitingOutput;!n||n.stream!==t.stream||n.sequence!==t.sequence||(r.waitingOutput=void 0,this.diagnostic("stdio.ack",r.snapshot.alias,{sequence:t.sequence,stream:t.stream}),this.flushOutput(r))}openAttachment(t){const r=this.readController(t);if(!r.snapshot.capabilities.includes("attachments"))throw ze("COMPANION_ATTACHMENT_NOT_FOUND","attachments 未启用");if(t.id!=="report")throw ze("COMPANION_ATTACHMENT_NOT_FOUND","固定 Fake Attachment 不存在");this.diagnostic("attachment.opened",r.snapshot.alias,{id:t.id});const n=new TextEncoder().encode(`Browser Fake Companion report
|
|
219
|
-
`);return{kind:"file",name:"browser-fake-report.txt",mode:"read",create:async()=>{throw ze("FILE_ACCESS_DENIED","Attachment 只读")},read:async()=>new Uint8Array(n),write:async()=>{throw ze("FILE_ACCESS_DENIED","Attachment 只读")},stat:async()=>({kind:"file",size:n.byteLength})}}showNotification(t){const r=this.readController(t);if(!r.snapshot.capabilities.includes("notifications"))throw ze("COMPANION_NOTIFICATION_UNAVAILABLE","notifications 未启用");this.diagnostic("notification.shown",r.snapshot.alias,{category:t.category})}queueOutput(t,r,n,i){t.queuedOutput.push({stream:r,sequence:n,data:typeof i=="string"?new TextEncoder().encode(i):i}),this.flushOutput(t)}flushOutput(t){if(t.exited||t.waitingOutput||!this.eventSink&&this.sessionEventListeners.size===0)return;const r=t.queuedOutput.shift();if(!r){t.pendingExit&&this.exit(t,t.pendingExit);return}t.waitingOutput=r,this.emit(Nh,{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(Mh,{sessionId:t.snapshot.id,exit:r}),this.diagnostic("session.exit",t.snapshot.alias,{...r}))}readController(t){const r=[...this.sessions.values()].find(n=>n.snapshot.id===t.sessionId);if(!r||r.exited)throw ze("COMPANION_SESSION_EXITED","固定 Fake Session 不存在");if(r.snapshot.controllerGeneration!==t.controllerGeneration)throw ze("COMPANION_SESSION_OWNERSHIP_LOST","固定 Fake Session 控制权已转移");return r}readAlias(t){if(!Qd.includes(t))throw ze("COMPANION_NOT_DECLARED","未知固定 Companion Fake 场景");return t}emit(t,r){this.eventSink?.(t,r),this.sessionEventListeners.forEach(n=>n({type:t,payload:r}))}diagnostic(t,r,n){this.onDiagnostic({action:t,...r?{alias:r}:{},...n?{detail:n}:{}})}}const JD=Object.freeze({[ho]:!0,[mo]:!0,[go]:!0,[po]:!0,[yo]:!0,[Eo]:!0,[wo]:!0,[Io]:!0,[Ao]:!0,[_o]:!0,[Do]:!0,[No]:!0,[En]:!0,[yn]:!0,[wn]:!0});function eN(e){return new XD(e)}function ze(e,t){return Object.assign(new Error(t),{code:e})}const tN=/^[A-Za-z0-9_-]{22}$/,rN="https://api.xiaoheihe.cn/open_inapp/";function nN(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(!tN.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 iN(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`${rN}#${r}`}function oN(e={}){const t=e.source??lN(e.document??document),r=e.readMetadata??fN,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(rn(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 sN(t,d);if(rn(u.signal),d.source==="camera"&&f.length!==1)throw ve("MEDIA_PREPARE_FAILED","相机模拟必须恰好返回 1 项");const l=[];try{for(const p of f)rn(u.signal),l.push(await cN(p,d,u.signal,r,n,o,s));rn(u.signal)}catch(p){for(const m of l)a(o.get(m.file));throw p}return l},release(d){for(const u of d)a(o.get(u.file))}}}async function sN(e,t){const r=await e.pickAlbum({accept:aN(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 aN(e){switch(e){case"image":return"image/*";case"video":return"video/*";default:return"image/*,video/*"}}async function cN(e,t,r,n,i,o,s){const a=dN(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);rn(r);const d=Yd(c.width),u=Yd(c.height);if(d===void 0||u===void 0)throw ve("MEDIA_PREPARE_FAILED",`无法读取 ${e.name} 的显示尺寸`);if(a==="video"){if(Wd(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=uN(e);o.set(l,f),s.add(f);const p={type:a,mimeType:e.type,size:e.size,width:d,height:u,previewUrl:f,file:l};return a==="video"?{...p,durationMs:Wd(c.durationMs)}:p}function dN(e){if(e.startsWith("image/"))return"image";if(e.startsWith("video/"))return"video"}function uN(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 lN(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"?yN():pN()}}}async function fN(e){return e.type.startsWith("video/")?mN(e):hN(e)}async function hN(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 mN(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 gN(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 gN(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 pN(){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 yN(){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:EN(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 wN(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 EN(e){for(const t of["video/webm;codecs=vp8","video/webm","video/mp4"])if(e.isTypeSupported?.(t))return t;return"video/webm"}async function wN(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 rn(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 Yd(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>0?e:void 0}function Wd(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0?e:void 0}function IN(e){const t=Qe(e.runtimePermissions),r=ga({declaredPermissions:e.declaredPermissions??{},runtimePermissions:e.runtimePermissions,localDevGrant:e.localDevGrant}),n=[],i=Qe(e.publishedRuntimePermissions),o=Qe(r.runtimePermissions);for(const s of ma){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 Zt(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 Zd="__hb_sdk_mini_dev_console_installed__",AN=["log","debug","info","warn","error"];function _N(e,t=console){if(t[Zd])return;let r=!1;for(const n of AN){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[Zd]=!0)}const Us=1,Kd=64*1024,DN=64,NN=/^[A-Za-z0-9_-]{22}$/;class Ke extends TypeError{code;constructor(t,r){super(r),this.name="BrowserDevHostChannelError",this.code=t}}function MN(e,t=!1){const r=SN(e,t);switch(js(r,"Server message"),TN(r),r.type){case"grant":return an(r,["version","type","connectionEpoch","nextClientSequence","nextServerSequence","snapshot"],"grant"),cn(r.connectionEpoch,"connectionEpoch"),Kt(r.nextClientSequence,"nextClientSequence"),Kt(r.nextServerSequence,"nextServerSequence"),Xd(r.snapshot),r;case"event":return an(r,["version","type","connectionEpoch","sequence","event","snapshot"],"event"),cn(r.connectionEpoch,"connectionEpoch"),Kt(r.sequence,"sequence"),r.event!=="account.changed"&&r.event!=="status.changed"&&zt("event must be account.changed or status.changed"),Xd(r.snapshot),r;case"heartbeat":return an(r,["version","type","connectionEpoch","sequence"],"heartbeat"),cn(r.connectionEpoch,"connectionEpoch"),Kt(r.sequence,"sequence"),r;default:return zt("Unknown server message type")}}function bN(e){const t=e.connectionEpoch;cn(t,"connectionEpoch"),Kt(e.nextSequence,"nextSequence");let r=e.nextSequence;return{get nextSequence(){return r},accept(n){if(cn(n.connectionEpoch,"connectionEpoch"),Kt(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 SN(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>Kd)throw new Ke("TEXT_FRAME_TOO_LARGE","Channel text frame exceeds 64 KiB");if(new TextEncoder().encode(e).byteLength>Kd)throw new Ke("TEXT_FRAME_TOO_LARGE","Channel text frame exceeds 64 KiB");try{return vN(e),JSON.parse(e)}catch(r){throw r instanceof Ke?r:new Ke("INVALID_JSON","Channel frame must contain strict JSON")}}function Xd(e){js(e,"snapshot"),an(e,["account","permissions"],"snapshot"),js(e.account,"snapshot.account"),an(e.account,["revision"],"snapshot.account"),Kt(e.account.revision,"snapshot.account.revision"),AD(e.permissions)||zt("snapshot.permissions is invalid")}function TN(e){e.version!==Us&&zt("version must be 1")}function js(e,t){(typeof e!="object"||e===null||Array.isArray(e)||Object.getPrototypeOf(e)!==Object.prototype)&&zt(`${t} must be a plain JSON object`)}function an(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)))&&zt(`${r} fields are invalid`)}function Kt(e,t){(typeof e!="number"||!Number.isSafeInteger(e)||e<0)&&zt(`${t} must be a non-negative safe integer`)}function cn(e,t){(typeof e!="string"||!NN.test(e))&&zt(`${t} must be a 22-character base64url value`)}function zt(e){throw new Ke("INVALID_MESSAGE",e)}function vN(e){new ON(e).scan()}class ON{constructor(t){this.source=t}position=0;scan(){if(this.skipWhitespace(),this.scanValue(),this.skipWhitespace(),this.position!==this.source.length)throw new SyntaxError("Unexpected trailing JSON data")}scanValue(t=0){const r=this.source[this.position];if(r==="{"||r==="["){if(t>=DN)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 Jd=[1e3,2e3,4e3,8e3,15e3];function RN(e){const t=new Set,r=e.webSocketFactory??(P=>new WebSocket(P)),n=e.randomValues??(P=>crypto.getRandomValues(P)),i=e.timers??{clearTimeout:P=>window.clearTimeout(P),setTimeout:(P,Q)=>window.setTimeout(P,Q)},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,p,m=!1,E=!1;const w=new Set,I=(P,Q)=>{if(!(!e.onDiagnostic||w.has(P))){w.add(P);try{e.onDiagnostic({phase:P,...Q?{code:Q}:{}})}catch{}}},v=(P,Q,R=!1)=>{if(u&&P.account.revision<u.account.revision)return;const L=u&&JSON.stringify(P)===JSON.stringify(u);if(u=P,!(L&&!R))for(const C of t)C(P,Q)},y=()=>{if(f||p!==void 0||c)return;const P=Jd[Math.min(l,Jd.length-1)];l+=1,p=i.setTimeout(()=>{p=void 0,x()},P)},O=()=>{f||!m||c||(p!==void 0&&(i.clearTimeout(p),p=void 0),x())},j=()=>{a()&&O()},b=()=>{s&&!s.hidden&&O()},T=()=>{E||(E=!0,o?.addEventListener("online",j),s?.addEventListener("visibilitychange",b))},D=()=>{E&&(E=!1,o?.removeEventListener("online",j),s?.removeEventListener("visibilitychange",b))},x=()=>{if(f||c)return;m=!0,T(),p!==void 0&&(i.clearTimeout(p),p=void 0);let P,Q;try{P=r(e.url)}catch{I("constructor","WEBSOCKET_CONSTRUCTION_FAILED"),y();return}try{Q=PN(n)}catch{I("entropy","NONCE_GENERATION_FAILED");try{P?.close(1011,"channel initialization failed")}catch{}y();return}c=P;let R,L,C;const z=()=>{P.removeEventListener("open",S),P.removeEventListener("message",M),P.removeEventListener("close",H),P.removeEventListener("error",F),d===z&&(d=void 0)},k=()=>{if(c===P){c=void 0,z();try{P.close(1008,"invalid channel state")}catch{}y()}},S=()=>{if(!(f||c!==P))try{P.send(JSON.stringify({version:Us,type:"hello",csrfToken:e.csrfToken,clientNonce:Q}))}catch{I("send","HELLO_SEND_FAILED"),k()}},M=$=>{if(f||c!==P)return;if(typeof $.data!="string"){I("parse","TEXT_FRAME_REQUIRED"),k();return}let K;try{K=MN($.data)}catch(h){I("parse",h instanceof Ke?h.code:"INVALID_MESSAGE"),k();return}if(K.type==="grant"){if(C){I("sequence","DUPLICATE_GRANT"),k();return}R=K.connectionEpoch,L=K.nextClientSequence,C=bN({connectionEpoch:R,nextSequence:K.nextServerSequence}),l=0,w.clear(),v(K.snapshot,{type:"grant"});return}if(!C||!R||L===void 0){I("sequence","MESSAGE_BEFORE_GRANT"),k();return}try{C.accept(K)}catch{I("sequence","INVALID_SEQUENCE"),k();return}if(K.type==="heartbeat"){try{P.send(JSON.stringify({version:Us,type:"heartbeat.ack",connectionEpoch:R,sequence:L}))}catch{I("send","HEARTBEAT_ACK_SEND_FAILED"),k()}L=L===Number.MAX_SAFE_INTEGER?void 0:L+1;return}v(K.snapshot,{type:"event",event:K.event},!0)},H=()=>{c===P&&(I("close","SOCKET_CLOSED"),c=void 0,z(),y())},F=()=>{I("open","SOCKET_ERROR"),k()};P.addEventListener("open",S),P.addEventListener("message",M),P.addEventListener("close",H),P.addEventListener("error",F),d=z};return{connect:x,subscribeUpdates(P){return t.add(P),()=>t.delete(P)},dispose(){if(f)return;f=!0,m=!1,D(),p!==void 0&&i.clearTimeout(p),p=void 0;const P=c;c=void 0,d?.(),P?.close(1e3,"client disposed"),t.clear()}}}function kN(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 PN(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=kN(t);if(!/^[A-Za-z0-9_-]{22}$/.test(r))throw new TypeError("Channel nonce source returned invalid bytes");return r}let Ae=!1,mf=!1,Fe;const gf=new AbortController;try{_N((e,t)=>{Xt(`console.${e}`,{source:"host",message:t.map(r=>ZN(r)).join(" ")},Date.now(),e==="log"||e==="debug"?"log":e)})}catch{}const LN="/__hb_sdk_bootstrap__",CN="/__hb_sdk__/mobile-launch-redirect",xN="/__hb_sdk__/network",UN="/session/status",jN="/session/request",zN="/session/events",eu=320,HN=1e3,FN=1e3,BN=15e3,tu="dark",VN=["windows","macos","linux","unknown"],pf=new URL(location.href).searchParams,yf=pf.get("mini_url"),Be=pf.get("ui_preview")==="1",be={get device(){return Kn("#device")},get mobileLanSelect(){return Kn("#mobile-lan-select")},get mobileQrImage(){return Kn("#mobile-qr-image")},get mobileQrStatus(){return Kn("#mobile-qr-status")}};if(!yf&&!Be)throw be.device.innerHTML='<div class="error">Missing mini_url query.</div>',new Error("Missing mini_url query.");const Ef=yf??"about:blank",De=await Fa(),Ca=Be?void 0:await ct.configure({csrfToken:De.csrfToken??"",diagnosticsToken:De.diagnosticsToken??"",signal:gf.signal,query:IM,onDropped:e=>{B.diagnosticsDropped=e},onOwnershipLost:Nf});B.diagnosticTargetId=Ca?.targetId??"";B.diagnosticOwnerId=Ca?.ownerId??"";B.diagnosticTargetName=Ca?.metadata.displayName??"";B.openPlatformBaseUrl=De.openPlatformBaseUrl;B.devReadiness=De.devReadiness;B.miniProgramSupportsDesktop=De.miniProgramSupportsDesktop;B.miniProgramPlatforms=De.devContext.platforms??[];B.desktopLaunch.workspaceCardsEnabled=De.workspaceCardsEnabled;su(De.hostPlatform);au(De.windowForm);let Ot=De.lanAddresses,si=De.defaultLanAddressId,Er=De.mobileLaunchRedirect,xa=De.nativeAppLaunchUnavailableReason,dn=De.devSessionId,zs=De.miniProgramManifestAccessToken,ai=De.workspaceCardsEnabled,ci=De,Ua=Uo(De),Xe=De.devContext,_r=De.browserDevContext,xe=sn(_r);fo();let kr=Lo(xe),xo=0;const Ht=new AbortController;let ja=0,It,Hs=0,Fs,bt=0,At=!1,co,di,Bs,ds=!1;const Pr=ah({apply:ch,waitForLayout:async e=>{await un(),await lu(e),await fu(e)}});let za=!1;function us(e){if(e.throwIfAborted(),Ae)throw new qt("SESSION_CLOSED","调试台已关闭");if(B.diagnosticOwnershipLost)throw new qt("TARGET_OWNERSHIP_LOST","此调试页已失效,请重新打开预览");if(!za)throw new qt("PREVIEW_NOT_READY","调试台正在初始化,请稍后重试");if(Ar)throw new qt("SESSION_DISCONNECTED","开发服务已断开,请重新启动 dev")}const Vs=oh({observe:()=>{const e=Sn()?{width:hi.value.width,height:hi.value.height}:{width:Es.value.screenWidth,height:Es.value.screenHeight};return{preset:B.deviceSelectionId,orientation:Sn()?e.width>=e.height?"landscape":"portrait":B.display.orientation,runtimeStatus:B.runtimeStatus,viewport:e,instanceId:Fe?.mounted?Fe.instanceId:null,browserPixelRatio:window.devicePixelRatio,presentation:uh()}},async selectPreset(e,t){us(t),B.deviceSelectOpen=!1;const r=B.previewMode,n=Fe;dh(e),await un(),t.throwIfAborted(),B.previewMode!==r&&await ru(n,t)},async applyOrientation(e,t){us(t),B.deviceSelectOpen=!1,await Pr.applyDisplay({mode:e,hideCapsule:B.display.capsuleHidden},t)},async reload(e){us(e),B.deviceSelectOpen=!1;const t=Fe;jt("runtime.restart",{boundary:ja+1}),sr("manual restart").catch(()=>{}),await ru(t,e)},async waitForLayout(e){await un(),e.throwIfAborted(),await lu(e),await fu(e)}}),ui=ph(),wf={...Vs.bridge,prepareCapture:ui.prepare,restoreCapture:ui.restore,cancel(e){Vs.bridge.cancel(e),ui.cancel(e)}};window.__HB_SDK_PREVIEW__=wf;async function ru(e,t){for(;;){if(t.throwIfAborted(),Ae)throw new qt("SESSION_CLOSED","调试台已关闭");if(Fe!==e&&It===void 0){const r=B.runtimeStatus;if(r==="ready"||Be&&r==="idle")return;if(r==="error")throw new qt("RUNTIME_START_FAILED","小程序 Runtime 启动失败,请查看调试日志");if(r==="closed")throw new qt("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 Gs,$s,Qs,qs,Ys,Ws,nu=Date.now(),Ar=!1,iu=Promise.resolve(),Dr=-1,bn=!1,Tt,Zs,Ks,li,Qt;const uo=new Set,ou="hb-sdk:browser-dev-host:user-data-device";function GN(){try{const e=localStorage.getItem(ou)?.trim();if(e)return e;const t=typeof crypto.randomUUID=="function"?crypto.randomUUID():`mock-${Date.now().toString(36)}`;return localStorage.setItem(ou,t),t}catch{return"browser-mock-device"}}const $N=GN();function QN(){return{miniProgramId:Xe.miniProgramId?.trim().toLowerCase()||"anonymous-mini-program",userId:Tt?.trim()||"anonymous-user",deviceId:$N,environment:"development"}}function If(){return uf(xe.runtimePermissions,kr,xe)}function qN(){const e=Qe(If());return e.valid&&e.permissions.network?.status==="enabled"?"upload":"no_network"}function YN(){return $D({declaredPermissions:xe.declaredPermissions,runtimePermissions:If()})}const _t=VD({resolveScope:QN,egressTier:qN,declared:YN});function Lr(){mf&&sh({..._t.snapshot(),targetId:B.diagnosticTargetId,instanceId:Fe?.instanceId})}_t.subscribe(Lr);mf=!0;Lr();function ls(){const e=_t.snapshot().stateError;if(e)throw new Error(e)}qf({async refresh(){await _t.refresh(),ls()},async revokeSession(){await _t.revokeSession(),ls()},async resetAll(){await _t.resetAll(),ls()}});const Xs=eN({onDiagnostic:({action:e,alias:t,detail:r})=>jt(`companion.fake.${e}`,{...t?{alias:t}:{},...r})}),Cr=bD({applyStatus:e=>vf(e,!0),fetchStatus:e=>Tf(Ga(Ht.signal,e)),getCanonicalRevision:()=>Dr,onError:_M,reconcile:()=>iM(xo)}),Js=SD({connectEvents:Of,invalidate:()=>Cr.invalidate(),isDisposed:()=>Ae,maxDelayMs:BN,minDelayMs:FN,timers:{clearTimeout:e=>window.clearTimeout(e),setTimeout:(e,t)=>window.setTimeout(()=>{e()},t)}});let fs=0,Zn="",hs=!1,ea,ta;function Af(){Be||Ae||B.diagnosticOwnershipLost||ct.poll().finally(()=>{!Ae&&!B.diagnosticOwnershipLost&&(ta=window.setTimeout(Af,1e3))})}Af();await lo(!1);Pf();Cf(Lf(De));Be&&KN();Tn();Be||await Df();WN();_f();dM();await sr("initial");Be||(Of(),rM());za=!0;function _f(){!Be&&!Ae&&(ea=window.setTimeout(()=>{Df().finally(_f)},1e3))}async function Df(){if(!(hs||Ae)){hs=!0;try{const e=await fetch(`${qa}?after=${fs}&limit=500`,{headers:{"x-hb-sdk-csrf":De.csrfToken??""},signal:AbortSignal.any([Ht.signal,AbortSignal.timeout(5e3)])});if(!e.ok){B.diagnosticsStale=!0;return}const t=await e.json();if(Ae)return;if(Zn&&t.epoch!==Zn){fs=0,Zn=t.epoch,Yf();return}Zn=t.epoch,B.uploadSessions=t.uploadSessions;const r=await fetch(`${qa}?mode=inspect`,{headers:{"x-hb-sdk-csrf":De.csrfToken??""},signal:AbortSignal.any([Ht.signal,AbortSignal.timeout(5e3)])});if(r.ok){const o=await r.json();B.diagnosticInstances=o.instances,B.diagnosticTargets=o.targets,B.diagnosticPrimaryTargetId=o.primaryTargetId;const s=o.targets.find(a=>a.targetId===B.diagnosticTargetId);s&&(B.diagnosticTargetName=s.metadata.displayName),s&&(s.state==="closed"||s.ownerId!==B.diagnosticOwnerId)&&Nf()}B.diagnosticsStale=!r.ok,B.diagnosticsGap=B.diagnosticsGap||t.gap===!0;const n=new Map(B.diagnosticTargets.map(o=>[o.targetId,o.metadata.displayName])),i=new Map(B.diagnosticInstances.map(o=>[o.instanceId,n.get(o.targetId)]));for(const o of t.items){const s=Wf(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,Zf(s,o.cursor))}fs=t.nextCursor}catch{B.diagnosticsStale=!0}finally{hs=!1}}}function WN(){window.addEventListener("beforeunload",DM),window.addEventListener("hb-sdk:refresh-storage",Tn),window.addEventListener("hb-sdk:qr-open-change",ra),window.addEventListener("hb-sdk:qr-refresh",Ha),un(()=>{B.qrOpen&&B.qrMode==="local"&&ra(new CustomEvent("hb-sdk:qr-open-change",{detail:{open:!0}}))}),Gs=Kf(()=>document.querySelector("#host-fullscreen-exit-mount")),$s=Br(()=>[ln.value,gs.value,Xn.value?.state,Xn.value?.stale,Xn.value?.capabilities.storage].join("|"),()=>{B.storage=[],B.storageError="",Tn()}),Qs=Br(()=>B.devicePresetId,()=>Pr.notifyViewportChange(),{flush:"post"}),qs=Br(()=>B.previewMode,()=>{vt("preview mode changed"),cu(!1),Xf(!1),xr("preview mode changed")},{flush:"sync"}),Ys=Br(()=>hi.value,()=>Pr.notifyViewportChange(),{flush:"post"}),Ws=Br(()=>B.desktopWindow.closed,(e,t)=>{if(Sn()){if(e){vt("desktop window closed"),B.runtimeStatus="closed";return}t&&B.runtimeStatus==="closed"&&xr("desktop window reopened")}},{flush:"sync"})}function ZN(e){if(typeof e=="string")return e;if(e instanceof Error)return(typeof e.stack=="string"?e.stack.split(`
|
|
220
|
-
`).slice(0,4).join(`
|
|
221
|
-
`):"")||`${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 ra(e){const t=e.detail?.open===!0;t!==At&&(At=t,bt+=1,jo(),co?.abort(),t&&(be.mobileLanSelect.addEventListener("change",Ha),Rf(),Cn()))}function Ha(){At&&Cn()}function xr(e){Ae||It!==void 0||(jt("runtime.restart",{boundary:ja+1}),It=window.setTimeout(()=>{It=void 0,Ae||sr(e)},0))}async function sr(e,t=Ef,r){if(Ae||Ar||B.diagnosticOwnershipLost)return;if(It!==void 0&&window.clearTimeout(It),It=void 0,vt(e),Sn()&&B.desktopWindow.closed){B.runtimeStatus="closed";return}const n=document.createElement("iframe");n.dataset.testid="device-iframe",n.title="小程序预览",n.allow="clipboard-read; clipboard-write",n.name="__hb_sdk_mini_dev__";const i=crypto.randomUUID(),o=Jf(i,c=>{Be||ct.event(i,c)}),s={instanceId:i,launchUrl:t,locationBasePath:r,interactions:o,sequence:++ja,state:"starting",iframe:n,terminal:new AbortController,permissions:zf(kr),mounted:!1,hadReady:!1,pendingNavigationReload:!1};if(s.iframe.dataset.hbSdkInstanceId=s.instanceId,Fe=s,B.runtimeStatus="loading",bf(),Be||ct.send({operation:"register",instanceId:s.instanceId}),await un(),!He(s))return;const a=Hf("#device");if(!a){ms(s,new Error("预览容器尚未挂载"));return}if(Be){a.innerHTML='<div class="browser-mock-preview"><span class="browser-mock-preview__icon">UI</span><strong>Browser Mock</strong><small>mp_preview</small></div>',B.runtimeStatus="idle";return}a.replaceChildren(s.iframe),s.mounted=!0,ct.send({operation:"activate",instanceId:s.instanceId});try{const c=await lD(XN(s));if(!He(s)){c.dispose();return}s.assembly=c,c.ports.companion=Xs.port,c.ports.media=oN({getMode:()=>B.mediaSimulation,signal:s.terminal.signal});const d=yD({signal:s.terminal.signal,csrfToken:()=>De.csrfToken??""}),u=q_({iframe:s.iframe,authorizationContext:wD({signal:s.terminal.signal,refreshAccount:f=>lo(!0,f),request:Sf,readState:()=>({signed:Xe,browser:xe,userId:Tt,accountRevision:Dr,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}:{},...JD},authPresentation:c.authPresentation,userDataPresentation:c.userDataPresentation,companionPresentation:Xs.presentation,resolveLaunchConfiguration:async()=>(await c.resolveLaunch()).configuration,dispose:()=>na(s),onDevDocumentReload:(f,l)=>{He(s)&&sr("development document reloaded",f,l)},onDevUploadSession:f=>{He(s)&&(s.uploadSessionId=f,Ur(s,{uploadSessionId:f}))},onReady:()=>{He(s)&&(s.state="ready",s.hadReady=!0,oa.value=d?u.diagnostics.gameSaves:void 0,B.runtimeStatus="ready",Ur(s),Xt("runtime.ready",{generation:s.sequence},Date.now(),void 0,s.instanceId))},onUserDataTelemetry:f=>{_t.refresh();const l=YD(f);Xt(l.method,l.detail,Date.now(),"info",s.instanceId)},onTrace:f=>tM(s,f),onError:f=>{He(s)&&ms(s,f)},onCapabilityTrace:f=>{Xt(f.method,{...f,source:"host"},f.timestamp,void 0,s.instanceId),He(s)&&f.method==="storage.setStorage"&&f.outcome==="success"&&Tn()}});s.runtime=u,await u.start(),He(s)&&_t.bind(u.getDataPermissionBridge())}catch(c){if(!He(s))return;ms(s,c),Xt("runtime.start.failed",xf(c,s),Date.now(),"error",s.instanceId),s.terminal.abort(c),s.runtime?.destroy(),s.iframe.remove(),na(s)}}function Nf(){Ae||B.diagnosticOwnershipLost||(B.diagnosticOwnershipLost=!0,vt("预览页面授权已失效"),B.runtimeStatus="closed",za=!1)}function He(e){return Fe===e&&!Ae&&!e.terminal.signal.aborted&&e.state!=="closed"&&e.state!=="failed"}function Ur(e,t={}){ct.send({operation:"update",instanceId:e.instanceId,state:e.state,...t})}function Mf(e,t){e.mounted&&(e.mounted=!1,ct.send({operation:"detach",instanceId:e.instanceId,reason:t}))}function na(e){Fe===e&&(oa.value=void 0),e.interactions.dispose();const t=e.assembly;e.assembly=void 0,t?.dispose()}function ms(e,t){e.state==="failed"||e.state==="closed"||(e.state="failed",e.interactions.dispose(),Ur(e,{error:xf(t,e),...e.uploadSessionId?{uploadSessionId:e.uploadSessionId}:{}}),Mf(e,"Runtime failed"),Fe===e&&(B.runtimeStatus="error"))}function vt(e){const t=Fe;t&&(Fe=void 0,oa.value=void 0,_t.clearSession(),t.state!=="failed"&&(t.state="closed",Ur(t,{reason:e})),Mf(t,e),(!ln.value||ln.value===B.diagnosticTargetId)&&(Hs+=1,Fs?.abort()),eh(),Xs.reset(),t.terminal.abort(new DOMException(e,"AbortError")),t.runtime?.destroy(),t.iframe.remove(),na(t),Pr.reset())}function KN(){const e=fh();B.diagnosticTargetId=e.targetId,B.diagnosticOwnerId=e.ownerId,B.diagnosticPrimaryTargetId=e.targetId,B.diagnosticTargetName=e.metadata.displayName,B.diagnosticTargets=[e],B.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"}};B.diagnosticTargets.push(t),B.diagnosticInstances.push({...B.diagnosticInstances[0],instanceId:t.currentInstanceId,targetId:t.targetId,ownerId:t.ownerId,kind:"mobile"}),ps({...ys("console.error",{source:"app",message:"真机示例:请求超时"},Date.now(),"error"),targetId:t.targetId,instanceId:t.currentInstanceId}),jt("runtime.ready",{generation:1}),ps(ys("console.info",{source:"app",message:"页面初始化完成"},Date.now(),"info")),jt("user.getInfo",{durationMs:34,outcome:"success"}),jt("network.request",{durationMs:86,network:{method:"GET",origin:"https://api.example.com",pathname:"/demo",responseStatus:200},outcome:"success"})}function XN(e){const t=e.terminal.signal,r=xe,n=dn,i=uf(r.runtimePermissions,e.permissions,r),o=Sn();return{signal:t,account:{async getCurrentUserId(){return(await lo(!1,t)).user_id},async ensureAuthenticated({signal:s}){await lo(!1,s)},onChange(s){return uo.add(s),()=>uo.delete(s)}},authenticatedRequest:Sf,storage:{area:"local",storage:GD(localStorage)},presentation:KD({close:async()=>{He(e)&&(vt("mini program closed"),bf(),B.runtimeStatus="closed",o&&cu(!0))},reload:()=>{He(e)&&(e.pendingNavigationReload=!0)},onNavigationBarStyleChange:s=>{He(e)&&du(s)},...o?{getViewportMetrics:()=>{const s=hi.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:()=>lh}:{getDeviceMetrics:()=>Es.value,applyDisplay:(s,a)=>Pr.applyDisplay(s,a),isCapsuleHidden:()=>B.display.capsuleHidden},onViewportChange:s=>Pr.onViewportChange(s)}),environment:{getCurrentHref:()=>location.href,isDevRuntime:()=>!0,setDocumentTitle:s=>{document.title=s}},resolveLaunch:async()=>({configuration:xD({launchUrl:e.launchUrl,locationBasePath:e.locationBasePath,runtimePermissions:i,networkPolicy:r.networkPolicy,firstParty:r.source==="remote"&&r.firstParty===!0,...B.miniProgram.bound&&B.miniProgram.name.trim()?{miniProgramName:B.miniProgram.name}:{},...r.miniProgramId?{miniProgramId:r.miniProgramId}:n?{anonymousStorageScope:n}:{},operatingSystem:o?B.hostPlatform:th.value.platform}),hostHints:{launchKind:r.source==="remote"?"dev-session":"anonymous-local-dev"}}),authPresentation:{confirmAuthorization:s=>CD(s),confirmFollowAuthor:s=>TD(s)},userDataPresentation:{confirmDataPermission:HD},protocol:JN(e)}}function Sn(){return B.previewMode==="desktop"}function JN(e){return{async invoke(t){Xt("device.executeProtocol",{outcome:"success",delivery:"mock",protocolType:eM(t)},Date.now(),void 0,e.instanceId)}}}function eM(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 bf(){document.documentElement.dataset.navigationBarStyle=tu,du(tu)}function tM(e,t){He(e)&&t.type==="document_validation"&&typeof t.documentVerifying=="boolean"&&Ur(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(rh({...t,generation:e.sequence})),...t.errorCode?{errorCode:t.errorCode}:{}}),e.runtimeId!==t.runtimeId&&(e.runtimeId=t.runtimeId,Ur(e,{runtimeId:t.runtimeId})),He(e)&&e.pendingNavigationReload&&t.type==="bridge_response"&&t.method==="navigation.reload"&&t.outcome==="success"&&(e.pendingNavigationReload=!1,xr("navigation.reload"))}async function Sf(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 Ba(n?xN:jN,{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&&Cr.invalidate();const o=await i.json();if(!i.ok)throw o;return o}async function lo(e,t){const r=xo,n=await Tf(Ga(Ht.signal,t));return Uf(r)?vf(n,e).status:ia()}async function Tf(e){return await(await fetch(UN,{cache:"no-store",credentials:"same-origin",redirect:"error",signal:e})).json()}function vf(e,t){if(!Number.isSafeInteger(e.revision)||e.revision<Dr)return{changed:!1,status:ia()};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!==Dr||e.authenticated!==bn||r!==Tt||n!==Zs||i!==Ks;return Dr=e.revision,bn=e.authenticated,Tt=r,Zs=n,Ks=i,Pf(),Lr(),t&&o&&uo.forEach(s=>s(Tt)),{changed:o,status:ia()}}function ia(){return{authenticated:bn,revision:Dr,...bn&&Tt?{user_id:Tt}:{}}}function rM(){if(!(!De.csrfToken||Ae))try{const e=new URL("/__hb_sdk__/channel",location.href);e.protocol=e.protocol==="https:"?"wss:":"ws:",Qt=RN({csrfToken:De.csrfToken,onDiagnostic:t=>jt("channel.diagnostic",t),url:e.toString()}),Qt.subscribeUpdates((t,r)=>nM(t,r)),Qt.connect()}catch{Qt?.dispose(),Qt=void 0}}function nM(e,t){Cr.invalidate(e.account.revision),bM(kr,e.permissions)?t.type==="event"&&t.event==="status.changed"&&sr("status changed"):(kr=zf(e.permissions),oM())}function Of(){if(li?.close(),li=void 0,!Tt||Ae)return;const e=new EventSource(zN);li=e,e.addEventListener("account-invalidated",()=>{Cr.invalidate()}),e.addEventListener("account-revision",()=>{Cr.invalidate()}),e.onopen=()=>{Js.reset()},e.onerror=()=>{e.close(),Js.schedule()}}async function iM(e){Uf(e)&&await sr("account revision changed")}async function oM(){Ae||(await sr("permission changed"),!Ae&&await Cn())}async function Fa(e){const t=await fetch(LN,{cache:"no-store",credentials:"same-origin",redirect:"error",signal:Ga(AbortSignal.timeout(5e3),e)});if(!t.ok)throw new Error("Browser Dev Host bootstrap request failed");const r=await t.json();if(!We(r))throw new Error("Browser Dev Host bootstrap is invalid");const n=jf(r.mobileLaunchRedirect);if(Object.hasOwn(r,"mobileLaunchRedirect")&&r.mobileLaunchRedirect!==void 0&&!n)throw new jr;return{openPlatformBaseUrl:typeof r.openPlatformBaseUrl=="string"?r.openPlatformBaseUrl:void 0,devReadiness:cM(r.devReadiness),csrfToken:typeof r.csrfToken=="string"?r.csrfToken:void 0,diagnosticsToken:typeof r.diagnosticsToken=="string"?r.diagnosticsToken:void 0,defaultLanAddressId:typeof r.defaultLanAddressId=="string"?r.defaultLanAddressId:void 0,devSessionId:typeof r.devSessionId=="string"&&/^[a-f0-9]{32}$/.test(r.devSessionId)?r.devSessionId:void 0,devContext:Fd(r.devContext,r.runtimePermissions),browserDevContext:Fd(r.browserDevContext??r.devContext,r.runtimePermissions),lanAddresses:Array.isArray(r.lanAddresses)?r.lanAddresses.filter(MM):[],loginAvailable:r.loginAvailable===!0,miniProgram:EM(r.miniProgram),miniProgramSupportsDesktop:r.miniProgramSupportsDesktop===!0,workspaceCardsEnabled:r.workspaceCardsEnabled===!0,mobileLaunchRedirect:n,nativeAppLaunchUnavailableReason:typeof r.nativeAppLaunchUnavailableReason=="string"?r.nativeAppLaunchUnavailableReason:void 0,miniProgramManifestAccessToken:typeof r.miniProgramManifestAccessToken=="string"?r.miniProgramManifestAccessToken:void 0,windowForm:aM(r.windowForm),hostPlatform:sM(r.hostPlatform)}}function sM(e){return VN.includes(e)?e:"unknown"}function aM(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 cM(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 Ba(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 dM(){Va(),Be||(Bs=window.setInterval(()=>{yM()},HN))}function Rf(e=be.mobileLanSelect.options.length>0?be.mobileLanSelect.value:void 0){be.mobileLanSelect.replaceChildren();for(const t of Ot){const r=document.createElement("option");r.value=t.id,r.textContent=`${t.name} · ${t.address}`,be.mobileLanSelect.appendChild(r)}e&&Ot.some(({id:t})=>t===e)?be.mobileLanSelect.value=e:si&&Ot.some(({id:t})=>t===si)?be.mobileLanSelect.value=si:Ot[0]&&(be.mobileLanSelect.value=Ot[0].id),be.mobileLanSelect.disabled=Ot.length===0}async function Cn(){if(Ae||!At)return;const e=++bt;if(co?.abort(),be.mobileQrImage.removeAttribute("src"),B.mobileQr={status:"loading",expiresAt:0},jo(),Be){const i=await Ya.toDataURL("hb-sdk-ui-preview",{width:eu,margin:1});if(e!==bt||Ae||!At)return;be.mobileQrImage.src=i,B.mobileQr={status:"ready",expiresAt:0},be.mobileQrStatus.textContent="UI 预览示例,不用于真机连接";return}if(Xe.source!=="remote"||!Xe.localDevLaunchToken||Xe.expiresAt!==void 0&&Xe.expiresAt<=Date.now()){be.mobileQrImage.removeAttribute("src"),B.mobileQr.status="error",be.mobileQrStatus.textContent=xa||"需要有效的本地调试启动票";return}const t=NM();if(!t?.mobileAppQrPayload){be.mobileQrImage.removeAttribute("src"),B.mobileQr.status="error",be.mobileQrStatus.textContent="未发现可用的局域网地址";return}const r=new AbortController;co=r;const n=AbortSignal.any([r.signal,Ht.signal,AbortSignal.timeout(1e4)]);be.mobileQrStatus.textContent="正在生成二维码...";try{const i=await mM(t,n);if(e!==bt||Ae)return;const o=await uM(i.address,i.expiresAt,n);if(e!==bt||Ae)return;const s=await Ya.toDataURL(o.payload,{width:eu,margin:1});if(e!==bt||Ae)return;if(n.throwIfAborted(),o.expiresAt<=Date.now())throw new Error("二维码已过期,请刷新重试");be.mobileQrImage.src=s,B.mobileQr={status:"ready",expiresAt:o.expiresAt},be.mobileQrStatus.textContent=`${i.address.name} · ${i.address.address}`,pM(o.expiresAt,e)}catch(i){if(e!==bt||Ae)return;if(i instanceof jr){fi();return}be.mobileQrImage.removeAttribute("src"),B.mobileQr.status="error",be.mobileQrStatus.textContent=n.aborted&&n.reason?.name==="TimeoutError"?"二维码生成超时,请检查连接后刷新重试":$a(i)}}async function uM(e,t,r){const n=e.mobileAppQrPayload;if(!n)throw new Error("Mobile 启动配置不可用");const i=await lM(e,n,r);if(!i)return{expiresAt:t,payload:n};try{return{expiresAt:Math.min(t,i.expiresAt),payload:iN(nN({host:e.address,port:location.port,token:i.token}))}}catch{throw new jr}}async function lM(e,t,r){if(Er?.addressId===e.id)return Er;if(!Er)return;const n=await Ba(CN,{signal:r,method:"POST",body:JSON.stringify({address_id:e.id,payload:t,previous_token:Er.token})});if(!n.ok)throw new jr;const i=await n.json(),o=We(i)?jf({addressId:i.address_id,expiresAt:i.expires_at,token:i.token}):void 0;if(!o||o.addressId!==e.id)throw new jr;return r.throwIfAborted(),Er=o,ci={...ci,mobileLaunchRedirect:o},Ua=Uo(ci),o}async function fM(e,t){const r=await Fa(t);t.throwIfAborted();const n=hM(r,e),i=n?.mobileAppQrPayload;if(!n||!i)throw new Error("Mobile 启动配置不可用");return kf(r),{...n,mobileAppQrPayload:i}}function hM(e,t){return e.lanAddresses.find(({id:r})=>r===t)??e.lanAddresses.find(({id:r})=>r===e.defaultLanAddressId)??e.lanAddresses[0]}function kf(e){const t=Zt(xe);B.devReadiness=e.devReadiness,B.miniProgramSupportsDesktop=e.miniProgramSupportsDesktop,B.miniProgramPlatforms=e.devContext.platforms??[],su(e.hostPlatform),au(e.windowForm),ai=e.workspaceCardsEnabled,ci=e,Ua=Uo(e),Xe=e.devContext,_r=e.browserDevContext,xe=sn(_r),kr=Lo(xe),fo(),Ot=e.lanAddresses,si=e.defaultLanAddressId,Er=e.mobileLaunchRedirect,xa=e.nativeAppLaunchUnavailableReason,dn=e.devSessionId,zs=e.miniProgramManifestAccessToken,Cf(Lf(e)),At&&Rf(),Va(),t!==Zt(xe)&&(vt("local permission context changed"),xr("local permission context changed"))}function fo(){if(Be){B.localPermissions=hh(),B.devContextWarning="";return}B.localPermissions=IN(xe),B.devContextWarning=xe.source==="anonymous"?"未连接线上上下文":xe.warning?"本地上下文受限,请检查 CLI 状态":"",Lr()}function Va(){let e;try{e=nh(Ef)}catch{}const t=Xe.miniProgramId?.trim().toLowerCase();let r=xa?.trim()??"";!r&&(Xe.source!=="remote"||!t)&&(r="请先绑定可管理的小程序"),!r&&!Xe.localDevLaunchToken?.trim()&&(r="正在等待有效的本地调试启动票"),!r&&ai&&!dn&&(r="本地调试会话尚未就绪"),!r&&Xe.expiresAt!==void 0&&Xe.expiresAt<=Date.now()&&(r="本地调试启动票已过期"),!r&&!e&&(r="未发现可用的本机调试地址"),uu({...e?{address:e}:{},...t?{miniProgramId:t}:{},...ai&&dn?{devSessionId:dn}:{},...zs?{miniProgramManifestToken:zs}:{},workspaceCardsEnabled:ai,ready:r==="",...r?{unavailableReason:r}:{}})}class jr extends Error{}async function mM(e,t){const r=iu.then(()=>(t.throwIfAborted(),gM(e,t)));return iu=r.then(()=>{},()=>{}),r}async function gM(e,t){const r=new URL(e.appUrl),n=new URL(ID,location.origin),i=await Ba(n.pathname,{signal:t,method:"POST",body:JSON.stringify({mini_url_origin:r.origin,runtime_permissions:DD(Xe)})}),o=await i.json();if(!i.ok||!We(o)||typeof o.token!="string"||typeof o.expires_at!="number")throw new Error("创建 Mobile Dev Session 失败");return{address:await fM(e.id,t),expiresAt:o.expires_at}}function pM(e,t){di=window.setTimeout(()=>{!Ae&&At&&t===bt&&Cn()},Math.max(1e3,e-Date.now()-3e4))}async function yM(){if(!(ds||Ae)){ds=!0;try{const e=await Fa();nu=Date.now();const t=Ar;Ar=!1;const r=Uo(e);if(!t&&r===Ua&&Zt(sn(e.browserDevContext))===Zt(xe)){_r=e.browserDevContext,xe=sn(_r),fo();return}kf(e),t&&xr("CLI dev session reconnected"),At&&Cn()}catch(e){e instanceof jr&&fi();const t=sn(_r);Zt(t)!==Zt(xe)&&(xe=t,kr=Lo(xe),fo(),vt("local permission context expired"),xr("local permission context expired"),Va(),At&&fi()),Date.now()-nu>=3e4&&!Ar&&(Ar=!0,vt("CLI dev session disconnected"),Hf("#device")?.replaceChildren(),B.runtimeStatus="closed",B.localPermissions=[],B.devContextWarning="调试会话已断开",uu({ready:!1,unavailableReason:"调试会话已断开"}),B.devReadiness={browser:{state:"blocked",reason:"调试会话已断开,等待 CLI 恢复"},mobile:{state:"blocked",reason:"调试会话已断开"},companion:{state:"blocked",reason:"调试会话已断开"}},At&&fi())}finally{ds=!1}}}function fi(){bt+=1,co?.abort(),jo(),be.mobileQrImage.removeAttribute("src"),B.mobileQr={status:"error",expiresAt:0},be.mobileQrStatus.textContent="Mobile 短链接配置无效"}function Uo(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:Zt(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 Pf(){if(!bn){B.account={authenticated:!1,avatar:"",nickname:"未登录"};return}B.account={authenticated:!0,avatar:Ks??"",nickname:Zs||Tt||"已登录"}}function Lf(e){if(e.miniProgram?.miniProgramId)return e.miniProgram;const t=e.devContext.miniProgramId?.trim();return t?{miniProgramId:t}:e.miniProgram??null}function Cf(e){if(!!!e?.miniProgramId||!e){B.miniProgram={bound:!1,id:"",iconUrl:"",name:"未绑定小程序",detail:"本地调试",description:"",version:""},Lr();return}B.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??""},Lr()}function EM(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 Tn(){const e=++Hs;Fs?.abort();const t=new AbortController;Fs=t;const r=ln.value,n=!r||r===B.diagnosticTargetId,i=Xn.value,o=gs.value||(n?Fe?.instanceId:void 0),s=()=>!Ae&&e===Hs&&r===ln.value&&o===(gs.value||(n?Fe?.instanceId:void 0));if(!n&&(!i||!o||i.stale||i.state!=="attached"||!i.capabilities.storage)){B.storage=[],B.storageError=!i||!i.capabilities.storage?"当前设备不支持存储诊断":"当前设备未连接或没有运行实例";return}if(Be){B.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}],B.storageError="";return}if(!o){B.storage=[],B.storageError="";return}try{const a=await ih({instanceId:o,resource:"storage"},{csrfToken:De.csrfToken,signal:AbortSignal.any([t.signal,Ht.signal])});if(!s())return;if(a.code)throw new Error(a.error??"Storage 诊断查询失败");B.storage=a.value,B.storageError=""}catch(a){if(!s())return;B.storage=[],B.storageError=$a(a)}}function xf(e,t=Fe){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){wM(ys(e,t,r,n==="debug"?"log":n),i)}function wM(e,t){if(Ae)return;if(Be){ps({...e,targetId:B.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 IM(e){const t=Fe;if(!t||e.instanceId!==t.instanceId||!He(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([Ht.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!He(t)||r!==t.runtime||e.instanceId!==t.instanceId?{code:"closed",error:"查询期间实例已结束"}:{value:s}}function AM(e,t){jt("host.message",{message:e,status:t})}function _M(e){Ae||AM($a(e),"error")}function jt(e,t){Xt(e,t)}function DM(){ct.close(),ea!==void 0&&window.clearTimeout(ea),ta!==void 0&&window.clearTimeout(ta),!Ae&&(Ae=!0,ui.dispose(),Vs.dispose(),window.__HB_SDK_PREVIEW__===wf&&delete window.__HB_SDK_PREVIEW__,window.removeEventListener("hb-sdk:refresh-storage",Tn),window.removeEventListener("hb-sdk:qr-open-change",ra),window.removeEventListener("hb-sdk:qr-refresh",Ha),xo+=1,Ht.abort(new DOMException("Browser Dev Host disposed","AbortError")),Cr.dispose(),vt("Browser Dev Host disposed"),_t.dispose(),ct.send({operation:"close-target",reason:"Browser Dev Host disposed"}),window.setTimeout(()=>gf.abort(),2e3),li?.close(),Qt?.dispose(),Qt=void 0,Js.dispose(),It!==void 0&&window.clearTimeout(It),It=void 0,jo(),Bs!==void 0&&window.clearInterval(Bs),uo.clear(),Gs?.(),Gs=void 0,$s?.(),$s=void 0,Qs?.(),Qs=void 0,qs?.(),qs=void 0,Ys?.(),Ys=void 0,Ws?.(),Ws=void 0)}function jo(){di!==void 0&&window.clearTimeout(di),di=void 0}function Ga(e,t){return t?AbortSignal.any([e,t]):e}function Uf(e){return!Ae&&e===xo}function NM(){return Ot.find(({id:e})=>e===be.mobileLanSelect.value)}function MM(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 jf(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 zf(e){return{networkRequest:{...e.networkRequest}}}function bM(e,t){return e.networkRequest.status===t.networkRequest.status&&e.networkRequest.useOfficialDomain===t.networkRequest.useOfficialDomain}function $a(e){return e instanceof Error&&e.message?e.message:"操作失败"}function We(e){return Object.prototype.toString.call(e)==="[object Object]"}function Kn(e){const t=document.querySelector(e);if(!t)throw new Error(`Missing Browser Dev Host element: ${e}`);return t}function Hf(e){return document.querySelector(e)??void 0}
|